opencrater 1.1.10 → 1.1.11

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'),L=require('os'),l=require('path'),child_process=require('child_process'),re=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 L__namespace=/*#__PURE__*/_interopNamespace(L);var l__namespace=/*#__PURE__*/_interopNamespace(l);var re__namespace=/*#__PURE__*/_interopNamespace(re);var x=(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 le(e=process.env){return l__namespace.join(L__namespace.homedir(),".config","opencrater")}function v(e=process.env){return l__namespace.join(le(e),"state.json")}function J(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function h(e){return typeof e=="number"&&Number.isFinite(e)}function ue(e){if(typeof e!="object"||e===null)return null;let t=e;return !h(t.minIntervalSeconds)||!h(t.serveTimeoutMs)||!h(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:h(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function pe(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n,r=o.ad;if(!h(o.renderBy)||typeof r!="object"||r===null||typeof r.impressionId!="string"||typeof r.clickUrl!="string"||typeof r.sponsorLabel!="string"||typeof r.creative!="object"||r.creative===null)continue;let s=r.creative;typeof s.title!="string"||typeof s.body!="string"||t.push({ad:{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 de(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 fe(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n;if(!(typeof o.topic!="string"||!h(o.at))&&(t.push({topic:o.topic.slice(0,32),at:o.at}),t.length>=24))break}return t}function ge(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 me(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 he(e){if(typeof e!="object"||e===null)return null;let t=e,n=o=>h(o)&&o>=0?o:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function ye(e){let t=J();if(typeof e!="object"||e===null)return t;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:t.installId,lastShownAt:h(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:ue(n.cachedConfig),allowedPlacements:de(n.allowedPlacements),sessionTopics:fe(n.sessionTopics),integrations:ge(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:me(n.computeRouting),computeCards:he(n.computeCards),configFetchedAt:h(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:pe(n.pool)}}function y(e=process.env){let t=v(e);try{let n=d__namespace.readFileSync(t,"utf8"),o=JSON.parse(n);return ye(o)}catch{let n=J();try{z(n,e);}catch{}return n}}function z(e,t=process.env){let n=v(t),o=l__namespace.dirname(n);d__namespace.mkdirSync(o,{recursive:true});let r=l__namespace.join(o,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);d__namespace.writeFileSync(r,JSON.stringify(e,null,2)+`
3
- `,"utf8");let s=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let i=0;;i++)try{d__namespace.renameSync(r,n);return}catch(u){let a=u.code??"";if(i>=4||!s.has(a)){try{d__namespace.rmSync(r,{force:!0});}catch{}if(i>=4)return;throw u}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(i+1));}catch{}}}function k(e,t=process.env){let n={...y(t),...e};return z(n,t),n}var G={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 S=["claude_code","codex","gemini_cli","copilot_cli"];function C(e){return e.includes("opencrater-hook")}function ke(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X(e,t){return C(e)&&new RegExp(`--package ['"]?${ke(t)}['"]?`).test(e)}function K(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var V='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',q="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function N(e,t,n,o){let r=`--placement ${t} --key ${K(n)} --package ${K(o)} --host ${e}`;return `{ if [ -f ${V} ]; then node ${V} ${r}; else npx -y -p opencrater opencrater-hook ${r}; fi; } 2>/dev/null || true`}function Se(e,t,n,o){let r=`--placement ${t} --key '${n}' --package '${o}' --host ${e}`;return `try { if (Test-Path "${q}") { node "${q}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function W(e,t,n,o){return N(e,t,n,o)}function Q(e,t){let n=L__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 R(e,t=process.env){let n=Q(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")}}function we(e,t=process.env){try{return d__namespace.existsSync(Q(e,t))}catch{return false}}function T(e=process.env){return S.filter(t=>we(t,e))}function P(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 j(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 be(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&X(n.command,t))}function ve(e,t,n,o){let r=R(e),s=P(r),i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let p=W(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(c=>Array.isArray(c.hooks)&&c.hooks.some(g=>g.command===p))}))return "nochange";for(let a of o){let c=(Array.isArray(i[a])?i[a]:[]).filter(g=>!be(g,n));c.push({matcher:"",hooks:[{type:"command",command:W(e,a,t,n)}]}),i[a]=c;}return s.hooks=i,j(r,s),"wrote"}function Ce(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&X(n,t))}function Oe(e,t,n,o){let r=R(e),s=P(r);typeof s.version!="number"&&(s.version=1);let i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let p=N(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(c=>c.bash===p)}))return "nochange";for(let a of o){let c=(Array.isArray(i[a])?i[a]:[]).filter(g=>!Ce(g,n));c.push({type:"command",bash:N(e,a,t,n),powershell:Se(e,a,t,n),timeoutSec:5}),i[a]=c;}return s.hooks=i,j(r,s),"wrote"}function E(e){return [...G[e]]}function H(e,t,n){let o=E(e);return o.length===0?"nochange":e==="copilot_cli"?Oe(e,t,n,o):ve(e,t,n,o)}function _(e,t,n=process.env){return T(n).map(o=>{try{let r=H(o,e,t);return {host:o,status:r,events:E(o)}}catch(r){return {host:o,status:"error",events:[],error:r.message}}})}function F(e=process.env){let t=[];for(let n of S){let o;try{o=P(R(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"&&C(f.command))?.command:void 0,c=[a.bash,a.command,a.powershell].find(f=>typeof f=="string"&&C(f)),g=p??c;g&&t.push({host:n,event:s,command:g});}}return t}function Z(e=process.env){let t=0;for(let n of S){let o=R(n,e),r;try{r=P(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(g=>{let f=g,B=Array.isArray(f.hooks)&&f.hooks.some(b=>typeof b.command=="string"&&C(b.command))||[f.bash,f.powershell,f.command].some(b=>typeof b=="string"&&C(b));return B&&t++,!B});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}):j(o,r);}catch{}}return t}var O="1.1.10";var Ae="https://api.opencrater.to";function I(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:Ae)).replace(/\/+$/,"")}function Pe(){return l__namespace.join(L__namespace.homedir(),".config","opencrater","runtime")}function Ee(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function te(e=Pe()){if(process.env.VITEST||process.env.OPENCRATER_DISABLE_RUNTIME_PIN)return false;try{return child_process.spawnSync("npm",Ee(e),{stdio:"ignore",windowsHide:!0,shell:process.platform==="win32"}).status===0}catch{return false}}function Ie(){let e=process.env.OPENCRATER_WEB_ORIGIN;return e&&e.trim()!==""?e.replace(/\/$/,""):I().replace("//api.","//").replace(/\/$/,"")}function $e(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 xe(e){let t=re__namespace.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>t.question(e,o=>(t.close(),n(o))))}function U(e){return `$${(e/1e6).toFixed(2)}`}async function D(e,t){try{let n=new URL(`${I()}/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 Ne(){let e=`${Ie()}/dev/link`;console.log("Sign in and generate a CLI token here (we tried to open it):"),console.log(` ${e}
5
- `),$e(e);let t=(await xe("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 D(t,y().installId);return n?(k({devToken:t}),console.log(`
6
- \u2713 Signed in as ${n.displayName}.`),console.log(` Compute balance: ${U(n.balanceMicroUsd)} \xB7 tier: ${n.trustTier}`),console.log(" See Blips in your sessions to earn your weekly compute."),0):(console.error("Couldn't verify that token \u2014 check it and try again."),1)}async function Te(){let e=y().devToken;if(!e)return console.error("Not signed in. Run: opencrater login"),1;let t=await D(e,y().installId);return t?(console.log(`Compute balance: ${U(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 je(){return k({devToken:null}),console.log("Signed out of the OpenCrater compute wallet on this machine."),0}async function He(e){let t=y().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await D(t,y().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=`${I().replace(/\/$/,"")}/gateway`,r=l__namespace.join(l__namespace.dirname(v()),"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 ${U(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 ie(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 ae(e,t){let n=y();n.integrations.some(o=>o.key===e&&o.package===t)||k({integrations:[...n.integrations,{key:e,package:t}].slice(-32)});}function M(e,t){if(e.length===0){console.log(`No supported AI CLIs detected yet \u2014 OpenCrater will wire ${t} automatically the moment you install one (it re-checks once a day).`);return}console.log(`OpenCrater wired ${t} into:`);for(let n of e)if(n.status==="error")console.log(` \u2717 ${n.host}: ${n.error}`);else {let o=n.status==="nochange"?" \u2014 already set up":"";console.log(` \u2022 ${n.host} (${n.events.join(", ")})${o}`);}}function _e(){return k({optOut:true}),console.log("OpenCrater Blips are now OFF for this machine."),console.log("Re-enable any time with: npx opencrater on"),0}function Fe(e){let{flags:t}=ie(e),n=t.get("key"),o=t.get("package");return k({optOut:false}),n&&o?(ae(n,o),M(_(n,o),o),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(te()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):console.log("OpenCrater Blips are now ON for this machine."),console.log("Opt out any time with: npx opencrater off"),0}function Me(){let e=y(),t=e.lastShownAt>0?new Date(e.lastShownAt).toISOString():"never";console.log(`opencrater v${O}`),console.log(` state file: ${v()}`),console.log(` install id: ${e.installId}`),console.log(` opted out: ${e.optOut?"yes":"no"}`),console.log(` last shown: ${t}`),console.log(` pooled ads: ${e.pool.length}`),console.log(` hosts found: ${T().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 Ue(e){let{flags:t}=ie(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;ae(n,o);let r=t.get("host");if(r&&r!=="true"){if(!S.includes(r))return console.error(`Unknown host "${r}". Supported: ${S.join(", ")}`),1;let s=r;try{let i=H(s,n,o);M([{host:s,status:i,events:E(s)}],o);}catch(i){return console.error(`Could not wire ${s}: ${i.message}`),1}}else M(_(n,o),o);return console.log("Remove with: npx opencrater hooks uninstall"),0}function De(){let e=Z();return k({integrations:[]}),console.log(e>0?`Removed ${e} OpenCrater hook${e===1?"":"s"} across all hosts.`:"No OpenCrater hooks installed."),0}function Be(){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 oe(){return console.log(`opencrater v${O} \u2014 OpenCrater Blips
2
+ 'use strict';var crypto=require('crypto'),d=require('fs'),L=require('os'),l=require('path'),child_process=require('child_process'),re=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 L__namespace=/*#__PURE__*/_interopNamespace(L);var l__namespace=/*#__PURE__*/_interopNamespace(l);var re__namespace=/*#__PURE__*/_interopNamespace(re);var x=(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 le(e=process.env){return l__namespace.join(L__namespace.homedir(),".config","opencrater")}function v(e=process.env){return l__namespace.join(le(e),"state.json")}function J(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function h(e){return typeof e=="number"&&Number.isFinite(e)}function ue(e){if(typeof e!="object"||e===null)return null;let t=e;return !h(t.minIntervalSeconds)||!h(t.serveTimeoutMs)||!h(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:h(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function pe(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n,r=o.blip;if(!h(o.renderBy)||typeof r!="object"||r===null||typeof r.impressionId!="string"||typeof r.clickUrl!="string"||typeof r.sponsorLabel!="string"||typeof r.creative!="object"||r.creative===null)continue;let 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 de(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 fe(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n;if(!(typeof o.topic!="string"||!h(o.at))&&(t.push({topic:o.topic.slice(0,32),at:o.at}),t.length>=24))break}return t}function ge(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 me(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 he(e){if(typeof e!="object"||e===null)return null;let t=e,n=o=>h(o)&&o>=0?o:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function ye(e){let t=J();if(typeof e!="object"||e===null)return t;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:t.installId,lastShownAt:h(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:ue(n.cachedConfig),allowedPlacements:de(n.allowedPlacements),sessionTopics:fe(n.sessionTopics),integrations:ge(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:me(n.computeRouting),computeCards:he(n.computeCards),configFetchedAt:h(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:pe(n.pool)}}function y(e=process.env){let t=v(e);try{let n=d__namespace.readFileSync(t,"utf8"),o=JSON.parse(n);return ye(o)}catch{let n=J();try{z(n,e);}catch{}return n}}function z(e,t=process.env){let n=v(t),o=l__namespace.dirname(n);d__namespace.mkdirSync(o,{recursive:true});let r=l__namespace.join(o,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);d__namespace.writeFileSync(r,JSON.stringify(e,null,2)+`
3
+ `,"utf8");let s=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let i=0;;i++)try{d__namespace.renameSync(r,n);return}catch(u){let a=u.code??"";if(i>=4||!s.has(a)){try{d__namespace.rmSync(r,{force:!0});}catch{}if(i>=4)return;throw u}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(i+1));}catch{}}}function k(e,t=process.env){let n={...y(t),...e};return z(n,t),n}var G={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 S=["claude_code","codex","gemini_cli","copilot_cli"];function C(e){return e.includes("opencrater-hook")}function ke(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X(e,t){return C(e)&&new RegExp(`--package ['"]?${ke(t)}['"]?`).test(e)}function K(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var V='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',q="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function N(e,t,n,o){let r=`--placement ${t} --key ${K(n)} --package ${K(o)} --host ${e}`;return `{ if [ -f ${V} ]; then node ${V} ${r}; else npx -y -p opencrater opencrater-hook ${r}; fi; } 2>/dev/null || true`}function Se(e,t,n,o){let r=`--placement ${t} --key '${n}' --package '${o}' --host ${e}`;return `try { if (Test-Path "${q}") { node "${q}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function W(e,t,n,o){return N(e,t,n,o)}function Q(e,t){let n=L__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 P(e,t=process.env){let n=Q(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")}}function be(e,t=process.env){try{return d__namespace.existsSync(Q(e,t))}catch{return false}}function T(e=process.env){return S.filter(t=>be(t,e))}function A(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 j(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 we(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&X(n.command,t))}function ve(e,t,n,o){let r=P(e),s=A(r),i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let p=W(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(c=>Array.isArray(c.hooks)&&c.hooks.some(g=>g.command===p))}))return "nochange";for(let a of o){let c=(Array.isArray(i[a])?i[a]:[]).filter(g=>!we(g,n));c.push({matcher:"",hooks:[{type:"command",command:W(e,a,t,n)}]}),i[a]=c;}return s.hooks=i,j(r,s),"wrote"}function Ce(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&X(n,t))}function Oe(e,t,n,o){let r=P(e),s=A(r);typeof s.version!="number"&&(s.version=1);let i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let p=N(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(c=>c.bash===p)}))return "nochange";for(let a of o){let c=(Array.isArray(i[a])?i[a]:[]).filter(g=>!Ce(g,n));c.push({type:"command",bash:N(e,a,t,n),powershell:Se(e,a,t,n),timeoutSec:5}),i[a]=c;}return s.hooks=i,j(r,s),"wrote"}function E(e){return [...G[e]]}function H(e,t,n){let o=E(e);return o.length===0?"nochange":e==="copilot_cli"?Oe(e,t,n,o):ve(e,t,n,o)}function _(e,t,n=process.env){return T(n).map(o=>{try{let r=H(o,e,t);return {host:o,status:r,events:E(o)}}catch(r){return {host:o,status:"error",events:[],error:r.message}}})}function F(e=process.env){let t=[];for(let n of S){let o;try{o=A(P(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"&&C(f.command))?.command:void 0,c=[a.bash,a.command,a.powershell].find(f=>typeof f=="string"&&C(f)),g=p??c;g&&t.push({host:n,event:s,command:g});}}return t}function Z(e=process.env){let t=0;for(let n of S){let o=P(n,e),r;try{r=A(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(g=>{let f=g,D=Array.isArray(f.hooks)&&f.hooks.some(w=>typeof w.command=="string"&&C(w.command))||[f.bash,f.powershell,f.command].some(w=>typeof w=="string"&&C(w));return D&&t++,!D});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}):j(o,r);}catch{}}return t}var O="1.1.11";var Re="https://api.opencrater.to";function I(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:Re)).replace(/\/+$/,"")}function Ae(){return l__namespace.join(L__namespace.homedir(),".config","opencrater","runtime")}function Ee(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function te(e=Ae()){if(process.env.VITEST||process.env.OPENCRATER_DISABLE_RUNTIME_PIN)return false;try{return child_process.spawnSync("npm",Ee(e),{stdio:"ignore",windowsHide:!0,shell:process.platform==="win32"}).status===0}catch{return false}}function Ie(){let e=process.env.OPENCRATER_WEB_ORIGIN;return e&&e.trim()!==""?e.replace(/\/$/,""):I().replace("//api.","//").replace(/\/$/,"")}function $e(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 xe(e){let t=re__namespace.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>t.question(e,o=>(t.close(),n(o))))}function U(e){return `$${(e/1e6).toFixed(2)}`}async function B(e,t){try{let n=new URL(`${I()}/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 Ne(){let e=`${Ie()}/dev/link`;console.log("Sign in and generate a CLI token here (we tried to open it):"),console.log(` ${e}
5
+ `),$e(e);let t=(await xe("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 B(t,y().installId);return n?(k({devToken:t}),console.log(`
6
+ \u2713 Signed in as ${n.displayName}.`),console.log(` Compute balance: ${U(n.balanceMicroUsd)} \xB7 tier: ${n.trustTier}`),console.log(" See Blips in your sessions to earn your weekly compute."),0):(console.error("Couldn't verify that token \u2014 check it and try again."),1)}async function Te(){let e=y().devToken;if(!e)return console.error("Not signed in. Run: opencrater login"),1;let t=await B(e,y().installId);return t?(console.log(`Compute balance: ${U(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 je(){return k({devToken:null}),console.log("Signed out of the OpenCrater compute wallet on this machine."),0}async function He(e){let t=y().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await B(t,y().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=`${I().replace(/\/$/,"")}/gateway`,r=l__namespace.join(l__namespace.dirname(v()),"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 ${U(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 ie(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 ae(e,t){let n=y();n.integrations.some(o=>o.key===e&&o.package===t)||k({integrations:[...n.integrations,{key:e,package:t}].slice(-32)});}function M(e,t){if(e.length===0){console.log(`No supported AI CLIs detected yet \u2014 OpenCrater will wire ${t} automatically the moment you install one (it re-checks once a day).`);return}console.log(`OpenCrater wired ${t} into:`);for(let n of e)if(n.status==="error")console.log(` \u2717 ${n.host}: ${n.error}`);else {let o=n.status==="nochange"?" \u2014 already set up":"";console.log(` \u2022 ${n.host} (${n.events.join(", ")})${o}`);}}function _e(){return k({optOut:true}),console.log("OpenCrater Blips are now OFF for this machine."),console.log("Re-enable any time with: npx opencrater on"),0}function Fe(e){let{flags:t}=ie(e),n=t.get("key"),o=t.get("package");return k({optOut:false}),n&&o?(ae(n,o),M(_(n,o),o),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(te()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):console.log("OpenCrater Blips are now ON for this machine."),console.log("Opt out any time with: npx opencrater off"),0}function Me(){let e=y(),t=e.lastShownAt>0?new Date(e.lastShownAt).toISOString():"never";console.log(`opencrater v${O}`),console.log(` state file: ${v()}`),console.log(` install id: ${e.installId}`),console.log(` opted out: ${e.optOut?"yes":"no"}`),console.log(` last shown: ${t}`),console.log(` pooled ads: ${e.pool.length}`),console.log(` hosts found: ${T().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 Ue(e){let{flags:t}=ie(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;ae(n,o);let r=t.get("host");if(r&&r!=="true"){if(!S.includes(r))return console.error(`Unknown host "${r}". Supported: ${S.join(", ")}`),1;let s=r;try{let i=H(s,n,o);M([{host:s,status:i,events:E(s)}],o);}catch(i){return console.error(`Could not wire ${s}: ${i.message}`),1}}else M(_(n,o),o);return console.log("Remove with: npx opencrater hooks uninstall"),0}function Be(){let e=Z();return k({integrations:[]}),console.log(e>0?`Removed ${e} OpenCrater hook${e===1?"":"s"} across all hosts.`:"No OpenCrater hooks installed."),0}function De(){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 oe(){return console.log(`opencrater v${O} \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: ${S.join(", ")}
27
- Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function Le(e){let[t,...n]=e;switch(t){case "off":return _e();case "on":return Fe(n);case "login":return Ne();case "balance":return Te();case "logout":return je();case "code":return He(n);case "status":return Me();case "hooks":{let[o,...r]=n;switch(o){case "install":return Ue(r);case "uninstall":return De();case "list":return Be();default:return console.error("Usage: opencrater hooks <install|uninstall|list>"),1}}case "version":case "--version":case "-v":return console.log(O),0;case void 0:case "help":case "--help":case "-h":return oe();default:return console.error(`Unknown command: ${t}`),oe(),1}}typeof x<"u"&&typeof module<"u"&&x.main===module&&Promise.resolve().then(()=>Le(process.argv.slice(2))).then(e=>{process.exitCode=e;}).catch(e=>{console.error(`opencrater: ${e.message}`),process.exitCode=1;});exports.runCli=Le;
27
+ Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function Le(e){let[t,...n]=e;switch(t){case "off":return _e();case "on":return Fe(n);case "login":return Ne();case "balance":return Te();case "logout":return je();case "code":return He(n);case "status":return Me();case "hooks":{let[o,...r]=n;switch(o){case "install":return Ue(r);case "uninstall":return Be();case "list":return De();default:return console.error("Usage: opencrater hooks <install|uninstall|list>"),1}}case "version":case "--version":case "-v":return console.log(O),0;case void 0:case "help":case "--help":case "-h":return oe();default:return console.error(`Unknown command: ${t}`),oe(),1}}typeof x<"u"&&typeof module<"u"&&x.main===module&&Promise.resolve().then(()=>Le(process.argv.slice(2))).then(e=>{process.exitCode=e;}).catch(e=>{console.error(`opencrater: ${e.message}`),process.exitCode=1;});exports.runCli=Le;
package/dist/hook.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var child_process=require('child_process'),l=require('fs'),R=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 l__namespace=/*#__PURE__*/_interopNamespace(l);var R__namespace=/*#__PURE__*/_interopNamespace(R);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:""},se={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],generic:["SessionStart","Stop"]},ae={claude_code:["SessionStart","Stop","SessionEnd","Notification","UserPromptSubmit","SubagentStart","SubagentStop","StopFailure","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionRequest","PermissionDenied","UserPromptExpansion","PreCompact","PostCompact","TaskCreated","TaskCompleted","Setup","TeammateIdle","Elicitation","ElicitationResult","ConfigChange","InstructionsLoaded","WorktreeCreate","WorktreeRemove","CwdChanged","FileChanged","MessageDisplay"],codex:["Stop","SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","PreCompact","PostCompact"],openclaw:[],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 E="1.1.10";var Qe="https://api.opencrater.to";function V(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return ((n&&n.trim()!==""?n:Qe)).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 j(e){return typeof e=="number"&&Number.isFinite(e)}function et(e){let t=M;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:j(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:j(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:j(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:j(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function L(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 ce(e,t){let n=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:n,sdkVersion:E,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 ue(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:et(t.config),...Array.isArray(t.allowedPlacements)?{allowedPlacements:t.allowedPlacements.filter(r=>typeof r=="string")}:{}};return t.ad!==void 0&&t.ad!==null&&(n.ad=t.ad),typeof t.computeBalanceMicroUsd=="number"&&(n.computeBalanceMicroUsd=t.computeBalanceMicroUsd),typeof t.weeklyGrantMicroUsd=="number"&&(n.weeklyGrantMicroUsd=t.weeklyGrantMicroUsd),n}async function le(e,t){let n=await L(t.origin,"/v1/serve",ce(e,t),t.timeoutMs);return ue(n)}async function pe(e,t,n){let r={...ce(t,n),publisherKey:t.publisherKey??"",packageName:t.packageName??""},o=await L(n.origin,"/v1/dev/serve",r,n.timeoutMs,{authorization:`Bearer ${e}`});return ue(o)}function de(e,t,n){return L(n.origin,"/v1/dev/impression",{impressionId:t},n.timeoutMs,{authorization:`Bearer ${e}`}).then(()=>{}).catch(()=>{})}function W(e,t){return L(t.origin,"/v1/events/impression",{impressionId:e},t.timeoutMs).then(()=>{}).catch(()=>{})}function fe(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 me(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function U(e){let t=fe(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 D(e=process.env){return g__namespace.join(R__namespace.homedir(),".config","opencrater")}function he(e=process.env){return g__namespace.join(D(e),"state.json")}function ye(){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 nt(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 ot(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.ad;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({ad:{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 rt(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 it(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 st(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 at(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 ct(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 ut(e){let t=ye();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:nt(n.cachedConfig),allowedPlacements:rt(n.allowedPlacements),sessionTopics:it(n.sessionTopics),integrations:st(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:at(n.computeRouting),computeCards:ct(n.computeCards),configFetchedAt:k(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:ot(n.pool)}}function q(e=process.env){let t=he(e);try{let n=l__namespace.readFileSync(t,"utf8"),r=JSON.parse(n);return ut(r)}catch{let n=ye();try{y(n,e);}catch{}return n}}function y(e,t=process.env){let n=he(t),r=g__namespace.dirname(n);l__namespace.mkdirSync(r,{recursive:true});let o=g__namespace.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);l__namespace.writeFileSync(o,JSON.stringify(e,null,2)+`
4
- `,"utf8");let i=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let s=0;;s++)try{l__namespace.renameSync(o,n);return}catch(p){let a=p.code??"";if(s>=4||!i.has(a)){try{l__namespace.rmSync(o,{force:!0});}catch{}if(s>=4)return;throw p}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(s+1));}catch{}}}var lt=300*1e3;function pt(){return g__namespace.join(D(),"blocked-ads.json")}function X(){return g__namespace.join(D(),"recent-renders.json")}function dt(){return g__namespace.join(D(),"reported-ads.json")}function Se(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 ft(e){try{let t=JSON.parse(l__namespace.readFileSync(pt(),"utf8"));return Se(t&&typeof t=="object"?t:{},e)}catch{return {}}}function mt(){try{let e=JSON.parse(l__namespace.readFileSync(dt(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}function gt(e){return e?mt()[e]!==void 0:false}function H(e,t=Date.now()){return e?ft(t)[e]!==void 0||gt(e):false}function be(e){try{let t=JSON.parse(l__namespace.readFileSync(X(),"utf8"));return Se(t&&typeof t=="object"?t:{},e)}catch{return {}}}function F(e,t=Date.now()){if(e)try{let n=be(t);n[e]=t+lt,l__namespace.mkdirSync(g__namespace.dirname(X()),{recursive:!0}),l__namespace.writeFileSync(X(),JSON.stringify(n));}catch{}}function B(e,t=Date.now()){return e?be(t)[e]!==void 0:false}function ht(e,t){return e.filter(n=>n.renderBy>t)}function Z(e,t){let n=ht(e.pool,t),r=n.shift();return {ad:r?r.ad:null,pool:n}}var yt=["claude_code","codex","gemini_cli","copilot_cli"];function St(e){return e.includes("opencrater-hook")}function bt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ee(e,t){return St(e)&&new RegExp(`--package ['"]?${bt(t)}['"]?`).test(e)}function ke(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var we='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',ve="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function Q(e,t,n,r){let o=`--placement ${t} --key ${ke(n)} --package ${ke(r)} --host ${e}`;return `{ if [ -f ${we} ]; then node ${we} ${o}; else npx -y -p opencrater opencrater-hook ${o}; fi; } 2>/dev/null || true`}function kt(e,t,n,r){let o=`--placement ${t} --key '${n}' --package '${r}' --host ${e}`;return `try { if (Test-Path "${ve}") { node "${ve}" ${o} } else { npx -y -p opencrater opencrater-hook ${o} } } catch {}`}function Ce(e,t,n,r){return Q(e,t,n,r)}function Te(e,t){let n=R__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 G(e,t=process.env){let n=Te(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")}}function wt(e,t=process.env){try{return l__namespace.existsSync(Te(e,t))}catch{return false}}function vt(e=process.env){return yt.filter(t=>wt(t,e))}function Ae(e){let t;try{t=l__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 Oe(e,t){let n=g__namespace.dirname(e);l__namespace.mkdirSync(n,{recursive:true});let r=g__namespace.join(n,`.${g__namespace.basename(e)}.${process.pid}.tmp`);l__namespace.writeFileSync(r,JSON.stringify(t,null,2)+`
5
- `,"utf8"),l__namespace.renameSync(r,e);}function Ct(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&Ee(n.command,t))}function Rt(e,t,n,r){let o=G(e),i=Ae(o),s=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(r.every(a=>{let d=Ce(e,a,t,n);return (Array.isArray(s[a])?s[a]:[]).some(f=>Array.isArray(f.hooks)&&f.hooks.some(c=>c.command===d))}))return "nochange";for(let a of r){let f=(Array.isArray(s[a])?s[a]:[]).filter(c=>!Ct(c,n));f.push({matcher:"",hooks:[{type:"command",command:Ce(e,a,t,n)}]}),s[a]=f;}return i.hooks=s,Oe(o,i),"wrote"}function Et(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&Ee(n,t))}function Tt(e,t,n,r){let o=G(e),i=Ae(o);typeof i.version!="number"&&(i.version=1);let s=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(r.every(a=>{let d=Q(e,a,t,n);return (Array.isArray(s[a])?s[a]:[]).some(f=>f.bash===d)}))return "nochange";for(let a of r){let f=(Array.isArray(s[a])?s[a]:[]).filter(c=>!Et(c,n));f.push({type:"command",bash:Q(e,a,t,n),powershell:kt(e,a,t,n),timeoutSec:5}),s[a]=f;}return i.hooks=s,Oe(o,i),"wrote"}function _e(e){return [...ae[e]]}function At(e,t,n){let r=_e(e);return r.length===0?"nochange":e==="copilot_cli"?Tt(e,t,n,r):Rt(e,t,n,r)}function Ie(e,t,n=process.env){return vt(n).map(r=>{try{let o=At(r,e,t);return {host:r,status:o,events:_e(r)}}catch(o){return {host:r,status:"error",events:[],error:o.message}}})}function _t(){return g__namespace.join(R__namespace.homedir(),".config","opencrater","runtime")}function It(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function ee(e=_t()){child_process.spawn("npm",It(e),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var Me={atLimit:false,resetAt:null};function De(e,t=R__namespace.homedir()){try{if(e==="claude_code")return Pt(t);if(e==="codex")return xt(t)}catch{}return Me}function Pt(e){let t=l__namespace.readFileSync(g__namespace.join(e,".claude.json"),"utf8"),n=JSON.parse(t),r=n.hasAvailableSubscription===false||n.cachedExtraUsageDisabledReason==="out_of_credits",o=null,p=n.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof p=="string"){let a=Date.parse(p);Number.isFinite(a)&&(o=a);}return {atLimit:r,resetAt:o}}function xt(e){return l__namespace.accessSync(g__namespace.join(e,".codex","auth.json")),Me}function $e(e,t){switch(e){case "gemini_cli":return t==="AfterAgent";case "copilot_cli":return t==="agentStop";default:return t==="Stop"}}var je=36e5,Nt=30*6e4,Mt=30*6e4,Dt=4*je,$t=3,J="https://opencrater.to/dashboard";function K(e){return `$${(e/1e6).toFixed(2)}`}function jt(e,t){return t<=0?0:Math.max(0,Math.min(100,Math.round(e/t*100)))}function Lt(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/je))}h`,o=new Date(e).toISOString().slice(0,10);return ` Your host limit resets in ${r} (${o}).`}function Le(e){let{balanceMicroUsd:t,weeklyGrantMicroUsd:n,onGateway:r,turnEnd:o,host:i,cc:s,now:p}=e;if(t===null)return null;if(t<=0)return p-(s.lastDepletedAt??0)<Mt?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."+Lt(i.resetAt,p),url:J,cta:"Earn more"}};if(r){if(!o||(s.turns??0)%$t!==0)return null;let a=n&&n>0?jt(t,n):null;return {kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:a!==null?`${a}% of your weekly compute left \u2014 ${K(t)} remaining.`:`${K(t)} of compute remaining this week.`,url:J,cta:"Wallet"}}}return i.atLimit?p-(s.lastLimitAt??0)<Nt?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:`${K(t)} of OpenCrater compute is ready. Continue this session now: opencrater code -c`,url:J,cta:"opencrater code -c"}}:p-(s.lastBackupAt??0)>=Dt?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:`${K(t)} of OpenCrater compute waiting. When you hit your limit: opencrater code -c`,url:J,cta:"opencrater code -c"}}:null}var Bt=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function ne(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Gt(e){return ne(e.OPENCRATER_DISABLE)||ne(e.TSN_DISABLE)}function Jt(e){return Bt.some(t=>ne(e[t]))}function z(e){return e?{...M,...e}:M}function Ke(e,t={}){if(Gt(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(Jt(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 Kt=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 Yt(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||Yt(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)||Kt.has(i))&&!n.includes(i)&&(n.push(i),n.length>=t))return n}return n}function oe(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 re(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 Ye(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 qt=false,Xt=process.platform==="win32"?8e3:3200,Zt=150,ze=250,Qt=2800;function en(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 tn(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 nn="\\\\.\\CONOUT$";function on(e){return !e||e==="?"||e==="??"||e==="-"?null:e.startsWith("/")?e:`/dev/${e}`}function rn(e){let t=e.match(/^\s*(\d+)\s+(\S+)/);return t?{ppid:Number(t[1]),tty:t[2]}:null}function sn(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 an(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 cn(e){try{let t=an(l__namespace.readFileSync(`/proc/${e}/stat`,"utf8"));if(t)return {ppid:t.ppid,ttyPath:sn(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=rn(t);return n?{ppid:n.ppid,ttyPath:on(n.tty)}:null}catch{return null}}function un(){if(process.platform==="win32")return {path:nn,ownerPid:null};let e=process.pid;for(let t=0;t<12&&e>1;t++){let n=cn(e);if(!n)return null;if(n.ttyPath)return {path:n.ttyPath,ownerPid:e};e=n.ppid;}return null}function ln(e){return e==="win32"?{detached:false,stdio:"ignore",windowsHide:false}:{detached:true,stdio:"ignore",windowsHide:false}}async function $(e,t,n,r,o){try{let i=g__namespace.join(__dirname,"paint.js"),s=z(t.cachedConfig),p=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:V(),durationMs:p*1e3,disclosure:!t.disclosureShown},d={...process.env,OPENCRATER_PAINT:JSON.stringify(a)};if(!d.OPENCRATER_TTY){let c=un();c&&(d.OPENCRATER_TTY=c.path,c.ownerPid!==null&&(d.OPENCRATER_HOST_PID=String(c.ownerPid)));}let f=child_process.spawn(process.execPath,[i],{...ln(process.platform),env:d});process.platform==="win32"?await new Promise(c=>{let u=!1,A=()=>{u||(u=!0,c());};f.on("exit",A),f.on("error",A),setTimeout(A,7500);}):f.unref();}catch{}return {...t,lastShownAt:Date.now(),disclosureShown:true}}function Ve(e){if(process.platform!=="win32")return false;try{let t=g__namespace.join(R__namespace.homedir(),".config","opencrater","painter.lock"),n=JSON.parse(l__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 pn=8e3;function We(){let e=g__namespace.join(R__namespace.homedir(),".config","opencrater","render.lock");try{let t=l__namespace.statSync(e);if(Date.now()-t.mtimeMs<pn)return !1;l__namespace.unlinkSync(e);}catch{}try{return l__namespace.mkdirSync(g__namespace.join(R__namespace.homedir(),".config","opencrater"),{recursive:!0}),l__namespace.writeFileSync(e,String(process.pid),{flag:"wx"}),!0}catch{return false}}function dn(e,t,n,r){if(!t)return true;let o=e.allowedPlacements[`${t}:${n}`];return o?o.includes(r):t==="opencrater"?se[n].includes(r):true}var fn=1440*60*1e3;function mn(){try{let e=g__namespace.join(R__namespace.homedir(),".config","opencrater","runtime"),t=g__namespace.join(e,"node_modules","opencrater","dist","hook.js"),n=g__namespace.join(e,".last-update");if(l__namespace.existsSync(t)){try{if(Date.now()-l__namespace.statSync(n).mtimeMs<fn)return}catch{}try{l__namespace.writeFileSync(n,String(Date.now()));}catch{return}}else {let r=g__namespace.join(e,".installing");try{l__namespace.mkdirSync(e,{recursive:!0});let o=l__namespace.statSync(r);if(Date.now()-o.mtimeMs<600*1e3)return}catch{}l__namespace.writeFileSync(r,String(Date.now()));}ee(e);}catch{}}function qe(e,t){if(!t)return false;let n=s=>s.split(/[-+]/)[0].split(".").map(p=>parseInt(p,10)||0),r=n(e),o=n(t),i=Math.max(r.length,o.length);for(let s=0;s<i;s++){let p=r[s]??0,a=o[s]??0;if(p!==a)return p<a}return false}function Xe(){try{let e=g__namespace.join(R__namespace.homedir(),".config","opencrater","runtime"),t=g__namespace.join(e,".last-update"),n=g__namespace.join(e,".force-update");try{if(Date.now()-l__namespace.statSync(n).mtimeMs<600*1e3)return}catch{}l__namespace.mkdirSync(e,{recursive:!0}),l__namespace.writeFileSync(n,String(Date.now()));try{l__namespace.rmSync(t,{force:!0});}catch{}ee(e);}catch{}}function gn(){try{let e=g__namespace.join(R__namespace.homedir(),".config","opencrater");l__namespace.mkdirSync(e,{recursive:!0}),l__namespace.writeFileSync(g__namespace.join(e,"activity.signal"),String(Date.now()));}catch{}}var hn=1440*60*1e3;function yn(){try{let e=g__namespace.join(R__namespace.homedir(),".config","opencrater"),t=g__namespace.join(e,".last-host-check");try{if(Date.now()-l__namespace.statSync(t).mtimeMs<hn)return}catch{}l__namespace.mkdirSync(e,{recursive:!0});try{l__namespace.writeFileSync(t,String(Date.now()));}catch{return}let n=q();if(n.optOut||n.integrations.length===0)return;for(let r of n.integrations)try{Ie(r.key,r.package);}catch{}}catch{}}async function Sn(){let e=en(process.argv.slice(2));gn(),mn(),yn();let t=await tn(Zt),n={};if(t)try{n=JSON.parse(t);let u=n.hook_event_name;!e.placement&&typeof u=="string"&&(e.placement=u);}catch{}let r=e.placement??"SessionStart",o=q(),i=Ke({env:process.env,state:o,now:Date.now()},{skipTTY:true});if(i!==null){if(i==="frequency"){let u=oe(n);u.length>0&&y({...o,sessionTopics:re(o.sessionTopics,u,Date.now())});}h("hook suppressed:",i);return}if(o={...o,sessionTopics:re(o.sessionTopics,oe(n),Date.now())},!dn(o,e.package,e.host,r)){y(o),h("hook gated: placement",r,"not selected for",e.package);return}let s=z(o.cachedConfig),p=V(),a={origin:p,timeoutMs:Math.min(s.serveTimeoutMs,Qt),installId:o.installId,topics:Ye(o.sessionTopics,Date.now())};if(o.devToken){let u=await pe(o.devToken,{publisherKey:e.key??"",packageName:e.package??"",placement:r,host:e.host},a);if(u){if(o={...o,cachedConfig:u.config,configFetchedAt:Date.now()},qe(E,u.config.minSdkVersion)&&Xe(),qt);let A=e.host??"claude_code",ie=$e(A,r),O=o.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};ie&&(O.turns+=1);let _=Le({balanceMicroUsd:typeof u.computeBalanceMicroUsd=="number"?u.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof u.weeklyGrantMicroUsd=="number"?u.weeklyGrantMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway"),turnEnd:ie,host:De(A),cc:O,now:Date.now()}),Ze=(u.config.displayDurationSeconds??25)*1e3,v=u.fill&&u.ad&&!H(u.ad.campaignId)&&!B(u.ad.campaignId)?u.ad:null;if((_||v)&&!Ve(Ze)&&We())if(_){let I=Date.now();_.kind==="limit"?O.lastLimitAt=I:_.kind==="depleted"?O.lastDepletedAt=I:_.kind==="backup"&&(O.lastBackupAt=I),o=await $({..._.card,label:"OpenCrater"},o);}else v&&(F(v.campaignId),o=await $(U(v),o,v.creative,v.impressionId,v.campaignId),o.devToken&&de(o.devToken,v.impressionId,a));o={...o,computeCards:O};}y(o);return}let{ad:d,pool:f}=Z(o,Date.now());for(;d&&(H(d.campaignId)||B(d.campaignId));)h("hook: pooled ad skipped \u2014 campaign inside a local cooldown"),{ad:d,pool:f}=Z({pool:f},Date.now());if((d||e.key)&&Ve((s.displayDurationSeconds??25)*1e3)){y(o),h("hook: a card is already on screen \u2014 not rendering another");return}if((d||e.key)&&!We()){y(o),h("hook: render slot already claimed by a concurrent fire");return}if(d){F(d.campaignId),o=await $(U(d),{...o,pool:f},d.creative,d.impressionId,d.campaignId),y(o),await Promise.race([W(d.impressionId,a),new Promise(u=>setTimeout(u,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 c=await le({publisherKey:e.key,packageName:e.package,placement:r,host:e.host},a);if(!c){y(o);return}if(o={...o,cachedConfig:c.config,configFetchedAt:Date.now()},qe(E,c.config.minSdkVersion)&&(h(`SDK ${E} below floor ${c.config.minSdkVersion} \u2014 forcing runtime update`),Xe()),e.package&&c.allowedPlacements&&(o={...o,allowedPlacements:{...o.allowedPlacements,[`${e.package}:${e.host}`]:c.allowedPlacements}}),c.fill&&c.ad){if(H(c.ad.campaignId)||B(c.ad.campaignId)){h("hook: served ad suppressed \u2014 campaign inside a local cooldown"),y(o);return}F(c.ad.campaignId),o=await $(U(c.ad),o,c.ad.creative,c.ad.impressionId,c.ad.campaignId),y(o),await Promise.race([W(c.ad.impressionId,a),new Promise(u=>setTimeout(u,ze).unref?.())]);return}c.fallback&&(o=await $(me(c.fallback),o)),y(o);}if(typeof P<"u"&&typeof module<"u"&&P.main===module){let e=setTimeout(()=>process.exit(0),Xt);Sn().catch(t=>h(`opencrater-hook v${E} error:`,t)).finally(()=>{clearTimeout(e),process.exit(0);});}
6
- exports.decodeTtyNr=sn;exports.painterSpawnOptions=ln;exports.parseProcStat=an;exports.parsePsLine=rn;exports.resolveTtyPath=un;exports.ttyNameToDevPath=on;
2
+ 'use strict';var child_process=require('child_process'),u=require('fs'),R=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 R__namespace=/*#__PURE__*/_interopNamespace(R);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:""},se={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],generic:["SessionStart","Stop"]},ae={claude_code:["SessionStart","Stop","SessionEnd","Notification","UserPromptSubmit","SubagentStart","SubagentStop","StopFailure","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionRequest","PermissionDenied","UserPromptExpansion","PreCompact","PostCompact","TaskCreated","TaskCompleted","Setup","TeammateIdle","Elicitation","ElicitationResult","ConfigChange","InstructionsLoaded","WorktreeCreate","WorktreeRemove","CwdChanged","FileChanged","MessageDisplay"],codex:["Stop","SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","PreCompact","PostCompact"],openclaw:[],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 E="1.1.11";var Qe="https://api.opencrater.to";function V(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return ((n&&n.trim()!==""?n:Qe)).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 et(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 ce(e,t){let n=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:n,sdkVersion:E,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:et(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 ue(e,t){let n=await j(t.origin,"/v1/serve",ce(e,t),t.timeoutMs);return le(n)}async function pe(e,t,n){let r={...ce(t,n),publisherKey:t.publisherKey??"",packageName:t.packageName??""},o=await j(n.origin,"/v1/dev/serve",r,n.timeoutMs,{authorization:`Bearer ${e}`});return le(o)}function de(e,t,n){return j(n.origin,"/v1/dev/impression",{impressionId:t},n.timeoutMs,{authorization:`Bearer ${e}`}).then(()=>{}).catch(()=>{})}function W(e,t){return j(t.origin,"/v1/events/impression",{impressionId:e},t.timeoutMs).then(()=>{}).catch(()=>{})}function fe(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 me(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function L(e){let t=fe(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(R__namespace.homedir(),".config","opencrater")}function he(e=process.env){return g__namespace.join($(e),"state.json")}function ye(){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 nt(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 ot(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 rt(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 it(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 st(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 at(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 ct(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 lt(e){let t=ye();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:nt(n.cachedConfig),allowedPlacements:rt(n.allowedPlacements),sessionTopics:it(n.sessionTopics),integrations:st(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:at(n.computeRouting),computeCards:ct(n.computeCards),configFetchedAt:k(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:ot(n.pool)}}function q(e=process.env){let t=he(e);try{let n=u__namespace.readFileSync(t,"utf8"),r=JSON.parse(n);return lt(r)}catch{let n=ye();try{y(n,e);}catch{}return n}}function y(e,t=process.env){let n=he(t),r=g__namespace.dirname(n);u__namespace.mkdirSync(r,{recursive:true});let o=g__namespace.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);u__namespace.writeFileSync(o,JSON.stringify(e,null,2)+`
4
+ `,"utf8");let i=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let s=0;;s++)try{u__namespace.renameSync(o,n);return}catch(p){let a=p.code??"";if(s>=4||!i.has(a)){try{u__namespace.rmSync(o,{force:!0});}catch{}if(s>=4)return;throw p}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(s+1));}catch{}}}var ut=300*1e3;function pt(){return g__namespace.join($(),"blocked-ads.json")}function X(){return g__namespace.join($(),"recent-renders.json")}function dt(){return g__namespace.join($(),"reported-ads.json")}function Se(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 ft(e){try{let t=JSON.parse(u__namespace.readFileSync(pt(),"utf8"));return Se(t&&typeof t=="object"?t:{},e)}catch{return {}}}function mt(){try{let e=JSON.parse(u__namespace.readFileSync(dt(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}function gt(e){return e?mt()[e]!==void 0:false}function U(e,t=Date.now()){return e?ft(t)[e]!==void 0||gt(e):false}function be(e){try{let t=JSON.parse(u__namespace.readFileSync(X(),"utf8"));return Se(t&&typeof t=="object"?t:{},e)}catch{return {}}}function H(e,t=Date.now()){if(e)try{let n=be(t);n[e]=t+ut,u__namespace.mkdirSync(g__namespace.dirname(X()),{recursive:!0}),u__namespace.writeFileSync(X(),JSON.stringify(n));}catch{}}function F(e,t=Date.now()){return e?be(t)[e]!==void 0:false}function ht(e,t){return e.filter(n=>n.renderBy>t)}function Z(e,t){let n=ht(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}var yt=["claude_code","codex","gemini_cli","copilot_cli"];function St(e){return e.includes("opencrater-hook")}function bt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ee(e,t){return St(e)&&new RegExp(`--package ['"]?${bt(t)}['"]?`).test(e)}function ke(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var we='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',ve="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function Q(e,t,n,r){let o=`--placement ${t} --key ${ke(n)} --package ${ke(r)} --host ${e}`;return `{ if [ -f ${we} ]; then node ${we} ${o}; else npx -y -p opencrater opencrater-hook ${o}; fi; } 2>/dev/null || true`}function kt(e,t,n,r){let o=`--placement ${t} --key '${n}' --package '${r}' --host ${e}`;return `try { if (Test-Path "${ve}") { node "${ve}" ${o} } else { npx -y -p opencrater opencrater-hook ${o} } } catch {}`}function Ce(e,t,n,r){return Q(e,t,n,r)}function Te(e,t){let n=R__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 G(e,t=process.env){let n=Te(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")}}function wt(e,t=process.env){try{return u__namespace.existsSync(Te(e,t))}catch{return false}}function vt(e=process.env){return yt.filter(t=>wt(t,e))}function Oe(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 _e(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 Ct(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&Ee(n.command,t))}function Rt(e,t,n,r){let o=G(e),i=Oe(o),s=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(r.every(a=>{let d=Ce(e,a,t,n);return (Array.isArray(s[a])?s[a]:[]).some(f=>Array.isArray(f.hooks)&&f.hooks.some(c=>c.command===d))}))return "nochange";for(let a of r){let f=(Array.isArray(s[a])?s[a]:[]).filter(c=>!Ct(c,n));f.push({matcher:"",hooks:[{type:"command",command:Ce(e,a,t,n)}]}),s[a]=f;}return i.hooks=s,_e(o,i),"wrote"}function Et(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&Ee(n,t))}function Tt(e,t,n,r){let o=G(e),i=Oe(o);typeof i.version!="number"&&(i.version=1);let s=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(r.every(a=>{let d=Q(e,a,t,n);return (Array.isArray(s[a])?s[a]:[]).some(f=>f.bash===d)}))return "nochange";for(let a of r){let f=(Array.isArray(s[a])?s[a]:[]).filter(c=>!Et(c,n));f.push({type:"command",bash:Q(e,a,t,n),powershell:kt(e,a,t,n),timeoutSec:5}),s[a]=f;}return i.hooks=s,_e(o,i),"wrote"}function Ie(e){return [...ae[e]]}function Ot(e,t,n){let r=Ie(e);return r.length===0?"nochange":e==="copilot_cli"?Tt(e,t,n,r):Rt(e,t,n,r)}function Ae(e,t,n=process.env){return vt(n).map(r=>{try{let o=Ot(r,e,t);return {host:r,status:o,events:Ie(r)}}catch(o){return {host:r,status:"error",events:[],error:o.message}}})}function It(){return g__namespace.join(R__namespace.homedir(),".config","opencrater","runtime")}function At(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function ee(e=It()){child_process.spawn("npm",At(e),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var Me={atLimit:false,resetAt:null};function $e(e,t=R__namespace.homedir()){try{if(e==="claude_code")return Pt(t);if(e==="codex")return xt(t)}catch{}return Me}function Pt(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,p=n.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof p=="string"){let a=Date.parse(p);Number.isFinite(a)&&(o=a);}return {atLimit:r,resetAt:o}}function xt(e){return u__namespace.accessSync(g__namespace.join(e,".codex","auth.json")),Me}function De(e,t){switch(e){case "gemini_cli":return t==="AfterAgent";case "copilot_cli":return t==="agentStop";default:return t==="Stop"}}var Be=36e5,Nt=30*6e4,Mt=30*6e4,$t=4*Be,Dt=3,J="https://opencrater.to/dashboard";function K(e){return `$${(e/1e6).toFixed(2)}`}function Bt(e,t){return t<=0?0:Math.max(0,Math.min(100,Math.round(e/t*100)))}function jt(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/Be))}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:p}=e;if(t===null)return null;if(t<=0)return p-(s.lastDepletedAt??0)<Mt?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."+jt(i.resetAt,p),url:J,cta:"Earn more"}};if(r){if(!o||(s.turns??0)%Dt!==0)return null;let a=n&&n>0?Bt(t,n):null;return {kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:a!==null?`${a}% of your weekly compute left \u2014 ${K(t)} remaining.`:`${K(t)} of compute remaining this week.`,url:J,cta:"Wallet"}}}return i.atLimit?p-(s.lastLimitAt??0)<Nt?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:`${K(t)} of OpenCrater compute is ready. Continue this session now: opencrater code -c`,url:J,cta:"opencrater code -c"}}:p-(s.lastBackupAt??0)>=$t?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:`${K(t)} of OpenCrater compute waiting. When you hit your limit: opencrater code -c`,url:J,cta:"opencrater code -c"}}:null}var Ft=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function ne(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Gt(e){return ne(e.OPENCRATER_DISABLE)||ne(e.TSN_DISABLE)}function Jt(e){return Ft.some(t=>ne(e[t]))}function z(e){return e?{...M,...e}:M}function Ke(e,t={}){if(Gt(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(Jt(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 Kt=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 Yt(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||Yt(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)||Kt.has(i))&&!n.includes(i)&&(n.push(i),n.length>=t))return n}return n}function oe(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 re(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 Ye(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 qt=false,Xt=process.platform==="win32"?8e3:3200,Zt=150,ze=250,Qt=2800;function en(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 tn(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 nn="\\\\.\\CONOUT$";function on(e){return !e||e==="?"||e==="??"||e==="-"?null:e.startsWith("/")?e:`/dev/${e}`}function rn(e){let t=e.match(/^\s*(\d+)\s+(\S+)/);return t?{ppid:Number(t[1]),tty:t[2]}:null}function sn(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 an(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 cn(e){try{let t=an(u__namespace.readFileSync(`/proc/${e}/stat`,"utf8"));if(t)return {ppid:t.ppid,ttyPath:sn(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=rn(t);return n?{ppid:n.ppid,ttyPath:on(n.tty)}:null}catch{return null}}function ln(){if(process.platform==="win32")return {path:nn,ownerPid:null};let e=process.pid;for(let t=0;t<12&&e>1;t++){let n=cn(e);if(!n)return null;if(n.ttyPath)return {path:n.ttyPath,ownerPid:e};e=n.ppid;}return null}function un(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=z(t.cachedConfig),p=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:V(),durationMs:p*1e3,disclosure:!t.disclosureShown},d={...process.env,OPENCRATER_PAINT:JSON.stringify(a)};if(!d.OPENCRATER_TTY){let c=ln();c&&(d.OPENCRATER_TTY=c.path,c.ownerPid!==null&&(d.OPENCRATER_HOST_PID=String(c.ownerPid)));}let f=child_process.spawn(process.execPath,[i],{...un(process.platform),env:d});process.platform==="win32"?await new Promise(c=>{let l=!1,O=()=>{l||(l=!0,c());};f.on("exit",O),f.on("error",O),setTimeout(O,7500);}):f.unref();}catch{}return {...t,lastShownAt:Date.now(),disclosureShown:true}}function Ve(e){if(process.platform!=="win32")return false;try{let t=g__namespace.join(R__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 pn=8e3;function We(){let e=g__namespace.join(R__namespace.homedir(),".config","opencrater","render.lock");try{let t=u__namespace.statSync(e);if(Date.now()-t.mtimeMs<pn)return !1;u__namespace.unlinkSync(e);}catch{}try{return u__namespace.mkdirSync(g__namespace.join(R__namespace.homedir(),".config","opencrater"),{recursive:!0}),u__namespace.writeFileSync(e,String(process.pid),{flag:"wx"}),!0}catch{return false}}function dn(e,t,n,r){if(!t)return true;let o=e.allowedPlacements[`${t}:${n}`];return o?o.includes(r):t==="opencrater"?se[n].includes(r):true}var fn=1440*60*1e3;function mn(){try{let e=g__namespace.join(R__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<fn)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()));}ee(e);}catch{}}function qe(e,t){if(!t)return false;let n=s=>s.split(/[-+]/)[0].split(".").map(p=>parseInt(p,10)||0),r=n(e),o=n(t),i=Math.max(r.length,o.length);for(let s=0;s<i;s++){let p=r[s]??0,a=o[s]??0;if(p!==a)return p<a}return false}function Xe(){try{let e=g__namespace.join(R__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{}ee(e);}catch{}}function gn(){try{let e=g__namespace.join(R__namespace.homedir(),".config","opencrater");u__namespace.mkdirSync(e,{recursive:!0}),u__namespace.writeFileSync(g__namespace.join(e,"activity.signal"),String(Date.now()));}catch{}}var hn=1440*60*1e3;function yn(){try{let e=g__namespace.join(R__namespace.homedir(),".config","opencrater"),t=g__namespace.join(e,".last-host-check");try{if(Date.now()-u__namespace.statSync(t).mtimeMs<hn)return}catch{}u__namespace.mkdirSync(e,{recursive:!0});try{u__namespace.writeFileSync(t,String(Date.now()));}catch{return}let n=q();if(n.optOut||n.integrations.length===0)return;for(let r of n.integrations)try{Ae(r.key,r.package);}catch{}}catch{}}async function Sn(){let e=en(process.argv.slice(2));gn(),mn(),yn();let t=await tn(Zt),n={};if(t)try{n=JSON.parse(t);let l=n.hook_event_name;!e.placement&&typeof l=="string"&&(e.placement=l);}catch{}let r=e.placement??"SessionStart",o=q(),i=Ke({env:process.env,state:o,now:Date.now()},{skipTTY:true});if(i!==null){if(i==="frequency"){let l=oe(n);l.length>0&&y({...o,sessionTopics:re(o.sessionTopics,l,Date.now())});}h("hook suppressed:",i);return}if(o={...o,sessionTopics:re(o.sessionTopics,oe(n),Date.now())},!dn(o,e.package,e.host,r)){y(o),h("hook gated: placement",r,"not selected for",e.package);return}let s=z(o.cachedConfig),p=V(),a={origin:p,timeoutMs:Math.min(s.serveTimeoutMs,Qt),installId:o.installId,topics:Ye(o.sessionTopics,Date.now())};if(o.devToken){let l=await pe(o.devToken,{publisherKey:e.key??"",packageName:e.package??"",placement:r,host:e.host},a);if(l){if(o={...o,cachedConfig:l.config,configFetchedAt:Date.now()},qe(E,l.config.minSdkVersion)&&Xe(),qt);let O=e.host??"claude_code",ie=De(O,r),_=o.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};ie&&(_.turns+=1);let I=je({balanceMicroUsd:typeof l.computeBalanceMicroUsd=="number"?l.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof l.weeklyGrantMicroUsd=="number"?l.weeklyGrantMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway"),turnEnd:ie,host:$e(O),cc:_,now:Date.now()}),Ze=(l.config.displayDurationSeconds??25)*1e3,v=l.fill&&l.blip&&!U(l.blip.campaignId)&&!F(l.blip.campaignId)?l.blip:null;if((I||v)&&!Ve(Ze)&&We())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&&(H(v.campaignId),o=await D(L(v),o,v.creative,v.impressionId,v.campaignId),o.devToken&&de(o.devToken,v.impressionId,a));o={...o,computeCards:_};}y(o);return}let{blip:d,pool:f}=Z(o,Date.now());for(;d&&(U(d.campaignId)||F(d.campaignId));)h("hook: pooled blip skipped \u2014 campaign inside a local cooldown"),{blip:d,pool:f}=Z({pool:f},Date.now());if((d||e.key)&&Ve((s.displayDurationSeconds??25)*1e3)){y(o),h("hook: a card is already on screen \u2014 not rendering another");return}if((d||e.key)&&!We()){y(o),h("hook: render slot already claimed by a concurrent fire");return}if(d){H(d.campaignId),o=await D(L(d),{...o,pool:f},d.creative,d.impressionId,d.campaignId),y(o),await Promise.race([W(d.impressionId,a),new Promise(l=>setTimeout(l,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 c=await ue({publisherKey:e.key,packageName:e.package,placement:r,host:e.host},a);if(!c){y(o);return}if(o={...o,cachedConfig:c.config,configFetchedAt:Date.now()},qe(E,c.config.minSdkVersion)&&(h(`SDK ${E} below floor ${c.config.minSdkVersion} \u2014 forcing runtime update`),Xe()),e.package&&c.allowedPlacements&&(o={...o,allowedPlacements:{...o.allowedPlacements,[`${e.package}:${e.host}`]:c.allowedPlacements}}),c.fill&&c.blip){if(U(c.blip.campaignId)||F(c.blip.campaignId)){h("hook: served blip suppressed \u2014 campaign inside a local cooldown"),y(o);return}H(c.blip.campaignId),o=await D(L(c.blip),o,c.blip.creative,c.blip.impressionId,c.blip.campaignId),y(o),await Promise.race([W(c.blip.impressionId,a),new Promise(l=>setTimeout(l,ze).unref?.())]);return}c.fallback&&(o=await D(me(c.fallback),o)),y(o);}if(typeof P<"u"&&typeof module<"u"&&P.main===module){let e=setTimeout(()=>process.exit(0),Xt);Sn().catch(t=>h(`opencrater-hook v${E} error:`,t)).finally(()=>{clearTimeout(e),process.exit(0);});}
6
+ exports.decodeTtyNr=sn;exports.painterSpawnOptions=un;exports.parseProcStat=an;exports.parsePsLine=rn;exports.resolveTtyPath=ln;exports.ttyNameToDevPath=on;
package/dist/index.d.mts CHANGED
@@ -18,8 +18,8 @@ interface Creative {
18
18
  /** Upload-time text fallback rendered when rich media can't display. */
19
19
  textFallback?: string;
20
20
  }
21
- /** A served sponsor ad. `clickUrl` is the per-impression tracked redirect. */
22
- interface Ad {
21
+ /** A served sponsor blip. `clickUrl` is the per-impression tracked redirect. */
22
+ interface Blip {
23
23
  impressionId: string;
24
24
  /** Campaign identity — used for LOCAL politeness (dismiss cooldown). */
25
25
  campaignId?: string;
@@ -49,7 +49,7 @@ interface RemoteConfig {
49
49
  /** Response of POST /v1/serve. */
50
50
  interface ServeResponse {
51
51
  fill: boolean;
52
- ad?: Ad;
52
+ blip?: Blip;
53
53
  fallback?: Fallback | null;
54
54
  config: RemoteConfig;
55
55
  /**
@@ -65,7 +65,7 @@ interface ServeResponse {
65
65
  }
66
66
  /** Response of POST /v1/serve/batch. */
67
67
  interface BatchResponse {
68
- ads: Ad[];
68
+ blips: Blip[];
69
69
  fallback?: Fallback | null;
70
70
  config: RemoteConfig;
71
71
  allowedPlacements?: string[];
@@ -79,10 +79,10 @@ interface SponsorOptions {
79
79
  /** Override the API origin (default https://api.opencrater.to, or OPENCRATER_API_ORIGIN). */
80
80
  apiOrigin?: string;
81
81
  }
82
- /** A preloaded ad waiting in the local pool. */
83
- interface PooledAd {
84
- ad: Ad;
85
- /** Epoch ms after which this pooled ad must not be rendered. */
82
+ /** A preloaded blip waiting in the local pool. */
83
+ interface PooledBlip {
84
+ blip: Blip;
85
+ /** Epoch ms after which this pooled blip must not be rendered. */
86
86
  renderBy: number;
87
87
  }
88
88
  /** Persistent on-disk state (~/.config/opencrater/state.json). */
@@ -96,7 +96,7 @@ interface OpenCraterState {
96
96
  cachedConfig: RemoteConfig | null;
97
97
  /** Epoch ms when cachedConfig was fetched. 0 = never. */
98
98
  configFetchedAt: number;
99
- pool: PooledAd[];
99
+ pool: PooledBlip[];
100
100
  /**
101
101
  * Per-package render gate, cached from serve responses: package name →
102
102
  * hooks its owner selected. A package with no entry is unrestricted.
@@ -196,7 +196,7 @@ type ImageProtocol = "iterm2" | "kitty" | "none";
196
196
  declare function detectImageProtocol(env?: Env, isTTY?: boolean): ImageProtocol;
197
197
 
198
198
  /**
199
- * The text card for an ad of ANY creative format (pure, sync — safe for the
199
+ * The text card for a blip of ANY creative format (pure, sync — safe for the
200
200
  * non-TTY hook path, which must never fetch media):
201
201
  * - text → the standard card
202
202
  * - image/gif → standard card with body swapped for the text fallback
@@ -204,7 +204,7 @@ declare function detectImageProtocol(env?: Env, isTTY?: boolean): ImageProtocol;
204
204
  * - audio → text fallback card, CTA defaults to "🔊 Listen"
205
205
  * The click URL is always carried, so the link stays reachable everywhere.
206
206
  */
207
- declare function textCardForAd(ad: Ad): RenderCardInput;
207
+ declare function textCardForBlip(blip: Blip): RenderCardInput;
208
208
  interface MediaRenderOptions extends RenderOptions {
209
209
  /** Override protocol detection (tests). Defaults to detectImageProtocol(). */
210
210
  protocol?: ImageProtocol;
@@ -214,28 +214,28 @@ interface MediaRenderOptions extends RenderOptions {
214
214
  maxBytes?: number;
215
215
  }
216
216
  /**
217
- * Render an ad of any creative format to a string. Image/GIF creatives in a
217
+ * Render a blip of any creative format to a string. Image/GIF creatives in a
218
218
  * capable terminal get the inline image ABOVE the standard text card (the
219
219
  * sponsor label, body and click URL always remain as text). Everything else,
220
220
  * and every failure, degrades to the text card. Never throws, never plays
221
221
  * media: video/audio are click-through only.
222
222
  */
223
- declare function renderAd(ad: Ad, opts?: MediaRenderOptions): Promise<string>;
223
+ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<string>;
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.10";
227
+ declare const SDK_VERSION = "1.1.11";
228
228
 
229
229
  /** Public API. Every method is fail-silent: it never throws. */
230
230
  declare const sponsor: {
231
231
  /** Fetch + render + report an impression. Resolves true if rendered. */
232
232
  show(opts: SponsorOptions): Promise<boolean>;
233
- /** Fetch an ad without rendering. Resolves to the Ad or null. */
234
- fetch(opts: SponsorOptions): Promise<Ad | null>;
235
- /** Fill the local preload pool. Resolves to the number of ads pooled. */
233
+ /** Fetch a blip without rendering. Resolves to the Blip or null. */
234
+ fetch(opts: SponsorOptions): Promise<Blip | null>;
235
+ /** Fill the local preload pool. Resolves to the number of blips pooled. */
236
236
  preload(opts: SponsorOptions): Promise<number>;
237
- /** Render a pooled ad without network on the hot path. */
237
+ /** Render a pooled blip without network on the hot path. */
238
238
  renderFromPool(opts: SponsorOptions): Promise<boolean>;
239
239
  };
240
240
 
241
- export { type Ad, type BatchResponse, type Creative, type CreativeFormat, DEFAULT_CONFIG, type Fallback, HOOK_CATALOG, type HookEvent, type Host, type ImageProtocol, type MediaRenderOptions, type OpenCraterState, type PooledAd, type RemoteConfig, type RenderCardInput, type RenderOptions, SDK_VERSION, type ServeResponse, type SponsorOptions, detectImageProtocol, renderAd, renderCard, sponsor, textCardForAd };
241
+ export { type BatchResponse, type Blip, type Creative, type CreativeFormat, DEFAULT_CONFIG, type Fallback, HOOK_CATALOG, type HookEvent, type Host, type ImageProtocol, type MediaRenderOptions, type OpenCraterState, type PooledBlip, type RemoteConfig, type RenderCardInput, type RenderOptions, SDK_VERSION, type ServeResponse, type SponsorOptions, detectImageProtocol, renderBlip, renderCard, sponsor, textCardForBlip };
package/dist/index.d.ts CHANGED
@@ -18,8 +18,8 @@ interface Creative {
18
18
  /** Upload-time text fallback rendered when rich media can't display. */
19
19
  textFallback?: string;
20
20
  }
21
- /** A served sponsor ad. `clickUrl` is the per-impression tracked redirect. */
22
- interface Ad {
21
+ /** A served sponsor blip. `clickUrl` is the per-impression tracked redirect. */
22
+ interface Blip {
23
23
  impressionId: string;
24
24
  /** Campaign identity — used for LOCAL politeness (dismiss cooldown). */
25
25
  campaignId?: string;
@@ -49,7 +49,7 @@ interface RemoteConfig {
49
49
  /** Response of POST /v1/serve. */
50
50
  interface ServeResponse {
51
51
  fill: boolean;
52
- ad?: Ad;
52
+ blip?: Blip;
53
53
  fallback?: Fallback | null;
54
54
  config: RemoteConfig;
55
55
  /**
@@ -65,7 +65,7 @@ interface ServeResponse {
65
65
  }
66
66
  /** Response of POST /v1/serve/batch. */
67
67
  interface BatchResponse {
68
- ads: Ad[];
68
+ blips: Blip[];
69
69
  fallback?: Fallback | null;
70
70
  config: RemoteConfig;
71
71
  allowedPlacements?: string[];
@@ -79,10 +79,10 @@ interface SponsorOptions {
79
79
  /** Override the API origin (default https://api.opencrater.to, or OPENCRATER_API_ORIGIN). */
80
80
  apiOrigin?: string;
81
81
  }
82
- /** A preloaded ad waiting in the local pool. */
83
- interface PooledAd {
84
- ad: Ad;
85
- /** Epoch ms after which this pooled ad must not be rendered. */
82
+ /** A preloaded blip waiting in the local pool. */
83
+ interface PooledBlip {
84
+ blip: Blip;
85
+ /** Epoch ms after which this pooled blip must not be rendered. */
86
86
  renderBy: number;
87
87
  }
88
88
  /** Persistent on-disk state (~/.config/opencrater/state.json). */
@@ -96,7 +96,7 @@ interface OpenCraterState {
96
96
  cachedConfig: RemoteConfig | null;
97
97
  /** Epoch ms when cachedConfig was fetched. 0 = never. */
98
98
  configFetchedAt: number;
99
- pool: PooledAd[];
99
+ pool: PooledBlip[];
100
100
  /**
101
101
  * Per-package render gate, cached from serve responses: package name →
102
102
  * hooks its owner selected. A package with no entry is unrestricted.
@@ -196,7 +196,7 @@ type ImageProtocol = "iterm2" | "kitty" | "none";
196
196
  declare function detectImageProtocol(env?: Env, isTTY?: boolean): ImageProtocol;
197
197
 
198
198
  /**
199
- * The text card for an ad of ANY creative format (pure, sync — safe for the
199
+ * The text card for a blip of ANY creative format (pure, sync — safe for the
200
200
  * non-TTY hook path, which must never fetch media):
201
201
  * - text → the standard card
202
202
  * - image/gif → standard card with body swapped for the text fallback
@@ -204,7 +204,7 @@ declare function detectImageProtocol(env?: Env, isTTY?: boolean): ImageProtocol;
204
204
  * - audio → text fallback card, CTA defaults to "🔊 Listen"
205
205
  * The click URL is always carried, so the link stays reachable everywhere.
206
206
  */
207
- declare function textCardForAd(ad: Ad): RenderCardInput;
207
+ declare function textCardForBlip(blip: Blip): RenderCardInput;
208
208
  interface MediaRenderOptions extends RenderOptions {
209
209
  /** Override protocol detection (tests). Defaults to detectImageProtocol(). */
210
210
  protocol?: ImageProtocol;
@@ -214,28 +214,28 @@ interface MediaRenderOptions extends RenderOptions {
214
214
  maxBytes?: number;
215
215
  }
216
216
  /**
217
- * Render an ad of any creative format to a string. Image/GIF creatives in a
217
+ * Render a blip of any creative format to a string. Image/GIF creatives in a
218
218
  * capable terminal get the inline image ABOVE the standard text card (the
219
219
  * sponsor label, body and click URL always remain as text). Everything else,
220
220
  * and every failure, degrades to the text card. Never throws, never plays
221
221
  * media: video/audio are click-through only.
222
222
  */
223
- declare function renderAd(ad: Ad, opts?: MediaRenderOptions): Promise<string>;
223
+ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<string>;
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.10";
227
+ declare const SDK_VERSION = "1.1.11";
228
228
 
229
229
  /** Public API. Every method is fail-silent: it never throws. */
230
230
  declare const sponsor: {
231
231
  /** Fetch + render + report an impression. Resolves true if rendered. */
232
232
  show(opts: SponsorOptions): Promise<boolean>;
233
- /** Fetch an ad without rendering. Resolves to the Ad or null. */
234
- fetch(opts: SponsorOptions): Promise<Ad | null>;
235
- /** Fill the local preload pool. Resolves to the number of ads pooled. */
233
+ /** Fetch a blip without rendering. Resolves to the Blip or null. */
234
+ fetch(opts: SponsorOptions): Promise<Blip | null>;
235
+ /** Fill the local preload pool. Resolves to the number of blips pooled. */
236
236
  preload(opts: SponsorOptions): Promise<number>;
237
- /** Render a pooled ad without network on the hot path. */
237
+ /** Render a pooled blip without network on the hot path. */
238
238
  renderFromPool(opts: SponsorOptions): Promise<boolean>;
239
239
  };
240
240
 
241
- export { type Ad, type BatchResponse, type Creative, type CreativeFormat, DEFAULT_CONFIG, type Fallback, HOOK_CATALOG, type HookEvent, type Host, type ImageProtocol, type MediaRenderOptions, type OpenCraterState, type PooledAd, type RemoteConfig, type RenderCardInput, type RenderOptions, SDK_VERSION, type ServeResponse, type SponsorOptions, detectImageProtocol, renderAd, renderCard, sponsor, textCardForAd };
241
+ export { type BatchResponse, type Blip, type Creative, type CreativeFormat, DEFAULT_CONFIG, type Fallback, HOOK_CATALOG, type HookEvent, type Host, type ImageProtocol, type MediaRenderOptions, type OpenCraterState, type PooledBlip, type RemoteConfig, type RenderCardInput, type RenderOptions, SDK_VERSION, type ServeResponse, type SponsorOptions, detectImageProtocol, renderBlip, renderCard, sponsor, textCardForBlip };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- 'use strict';var crypto=require('crypto'),d=require('fs'),ee=require('os'),k=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 d__namespace=/*#__PURE__*/_interopNamespace(d);var ee__namespace=/*#__PURE__*/_interopNamespace(ee);var k__namespace=/*#__PURE__*/_interopNamespace(k);var D=(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 F="1.1.10";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 l(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let t=D("os"),n=D("fs"),r=D("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():(l(`POST ${t} -> HTTP ${i.status}`),null)}catch(i){return l(`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:F,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.ad!==void 0&&t.ad!==null&&(n.ad=t.ad),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.ads)?{ads:o.ads,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"),C={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},ce=60,le=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(c=>c.length>0),o=[],i="";for(let c of r){let p=i===""?c:`${i} ${c}`;if(p.length<=t)i=p;else if(i!==""&&o.push(i),i=c.length>t?y(c,t):c,o.length>=n)break}i!==""&&o.length<n&&o.push(i),o.length>n&&(o.length=n);let a=o.join(" "),s=o.length-1,u=o[s];return u!==void 0&&a.length<r.join(" ").length&&(o[s]=y(`${u}\u2026`,t)),o}function v(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 O(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 P(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(le,Math.min(n,ce))-4,i=t.color??O(),a=t.hyperlinks??v(),s=(f,B)=>i?`${B}${f}${C.reset}`:f,u=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored Blip \xB7 ${e.sponsorLabel}`,o):"Sponsored Blip",c=[];c.push(s(u,C.dim)),e.title!==e.sponsorLabel&&c.push(s(y(e.title,o),C.bold));for(let f of de(e.body,o,2))c.push(f);let p="\u2192 ";if(a){let f=y(e.cta??e.url,o-p.length);c.push(p+s(fe(e.url,f),C.dim));}else e.cta&&c.push(y(e.cta,o)),c.push(p+s(y(e.url,o-p.length),C.dim));let A=`\u256D${"\u2500".repeat(o+2)}\u256E`,I=`\u2570${"\u2500".repeat(o+2)}\u256F`,$=c.map(f=>{let B=" ".repeat(Math.max(0,o-pe(f)));return `\u2502 ${f}${B} \u2502`}),h=[];return t.disclosure&&h.push(s(ue,C.dim)),h.push(A,...$,I),h.join(`
1
+ 'use strict';var crypto=require('crypto'),d=require('fs'),ee=require('os'),k=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 d__namespace=/*#__PURE__*/_interopNamespace(d);var ee__namespace=/*#__PURE__*/_interopNamespace(ee);var k__namespace=/*#__PURE__*/_interopNamespace(k);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 h={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var re=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var D="1.1.11";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 l(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let t=F("os"),n=F("fs"),r=F("path");n.appendFileSync(r.join(t.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(o=>String(o)).join(" ")}
2
+ `);}catch{}}catch{}}function v(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let t=h;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:v(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:v(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:v(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:v(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function 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():(l(`POST ${t} -> HTTP ${i.status}`),null)}catch(i){return l(`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"),C={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},ce=60,le=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(c=>c.length>0),o=[],i="";for(let c of r){let p=i===""?c:`${i} ${c}`;if(p.length<=t)i=p;else if(i!==""&&o.push(i),i=c.length>t?y(c,t):c,o.length>=n)break}i!==""&&o.length<n&&o.push(i),o.length>n&&(o.length=n);let a=o.join(" "),s=o.length-1,u=o[s];return u!==void 0&&a.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 B(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(le,Math.min(n,ce))-4,i=t.color??P(),a=t.hyperlinks??O(),s=(f,$)=>i?`${$}${f}${C.reset}`:f,u=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored Blip \xB7 ${e.sponsorLabel}`,o):"Sponsored Blip",c=[];c.push(s(u,C.dim)),e.title!==e.sponsorLabel&&c.push(s(y(e.title,o),C.bold));for(let f of de(e.body,o,2))c.push(f);let p="\u2192 ";if(a){let f=y(e.cta??e.url,o-p.length);c.push(p+s(fe(e.url,f),C.dim));}else e.cta&&c.push(y(e.cta,o)),c.push(p+s(y(e.url,o-p.length),C.dim));let I=`\u256D${"\u2500".repeat(o+2)}\u256E`,E=`\u2570${"\u2500".repeat(o+2)}\u256F`,L=c.map(f=>{let $=" ".repeat(Math.max(0,o-pe(f)));return `\u2502 ${f}${$} \u2502`}),b=[];return t.disclosure&&b.push(s(ue,C.dim)),b.push(I,...L,E),b.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"]),x=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 l(`media: HTTP ${i.status} for ${e}`),null;let a=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!ye.has(a))return l(`media: disallowed content-type "${a}" for ${e}`),null;let s=Number(i.headers.get("content-length")??"0");if(Number.isFinite(s)&&s>o)return l(`media: content-length ${s} exceeds ${o} for ${e}`),null;let u=i.body;if(u&&typeof u.getReader=="function"){let p=u.getReader(),A=[],I=0;for(;;){let{done:$,value:h}=await p.read();if($)break;if(h!==void 0){if(I+=h.byteLength,I>o)return await p.cancel().catch(()=>{}),l(`media: stream exceeded ${o} bytes for ${e}`),null;A.push(h);}}return Buffer.concat(A)}let c=Buffer.from(await i.arrayBuffer());return c.byteLength>o?(l(`media: body ${c.byteLength} bytes exceeds ${o} for ${e}`),null):c}catch(i){return l(`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 Ce(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),a=`m=${r+x>=t.length?0:1}`,s=r===0?`f=100,a=T,${a}`:a;n.push(`${w}_G${s};${o}${w}\\`);}return n.join("")}function _(e){let t=P(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(_(e),t);let r=t.protocol??Y();if(r==="none"||n.mediaUrl===void 0||n.mediaUrl==="")return m(_(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(_(e),t):(r==="kitty"?Ce(i):be(i))+`
5
- `+m(P(e),t)}catch(n){return l("media: render failed, falling back to text:",n),m(P(e),t)}}function ke(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=>({ad:r,renderBy:t+n}))}function Q(e,t){let n=ke(e.pool,t),r=n.shift();return {ad:r?r.ad:null,pool:n}}function Te(e=process.env){return k__namespace.join(ee__namespace.homedir(),".config","opencrater")}function te(e=process.env){return k__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 Ae(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.ad;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({ad:{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 Ie(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 ve(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 Oe(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 Pe(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 xe(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:Ie(n.allowedPlacements),sessionTopics:Ee(n.sessionTopics),integrations:ve(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:Oe(n.computeRouting),computeCards:Pe(n.computeCards),configFetchedAt:g(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:Ae(n.pool)}}function T(e=process.env){let t=te(e);try{let n=d__namespace.readFileSync(t,"utf8"),r=JSON.parse(n);return xe(r)}catch{let n=ne();try{S(n,e);}catch{}return n}}function S(e,t=process.env){let n=te(t),r=k__namespace.dirname(n);d__namespace.mkdirSync(r,{recursive:true});let o=k__namespace.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);d__namespace.writeFileSync(o,JSON.stringify(e,null,2)+`
6
- `,"utf8");let i=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let a=0;;a++)try{d__namespace.renameSync(o,n);return}catch(s){let u=s.code??"";if(a>=4||!i.has(u)){try{d__namespace.rmSync(o,{force:!0});}catch{}if(a>=4)return;throw s}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(a+1));}catch{}}}var _e=["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 Me(e){return H(e.OPENCRATER_DISABLE)||H(e.TSN_DISABLE)}function Le(e){return _e.some(t=>H(e[t]))}function z(e){return e?{...b,...e}:b}function R(e,t={}){if(Me(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(Le(e.env))return "ci";if(!t.skipTTY&&!e.isTTY)return "not_tty";if(!t.skipFrequency){let r=n.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<r)return "frequency"}return null}async function M(e){try{return await e()}catch(t){return l("suppressed error:",t),null}}function L(e,t){let n=z(t.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:n.serveTimeoutMs,installId:t.installId,config:n}}function $e(e,t){let n=!t.disclosureShown,r=m(e,{width:process.stdout.columns??80,color:O(),hyperlinks:v(),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:O(),hyperlinks:v(),disclosure:!t.disclosureShown});return process.stdout.write(n),{...t,lastShownAt:Date.now(),disclosureShown:true}}async function Be(e){let t=T(),n=R({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()},{skipFrequency:true});if(n!==null)return l("fetch suppressed:",n),null;let r=L(e,t),o=await U(e,r);return o?(S({...t,cachedConfig:o.config,configFetchedAt:Date.now()}),o.fill&&o.ad?o.ad:null):null}async function De(e){let t=T(),n=R({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()});if(n!==null)return l("suppressed:",n),false;let r=L(e,t),o=await U(e,r);return o?(t={...t,cachedConfig:o.config,configFetchedAt:Date.now()},o.fill&&o.ad?(t=await oe(o.ad,t),S(t),j(o.ad.impressionId,r),true):o.fallback?(t=$e(J(o.fallback),t),S(t),true):(S(t),false)):false}async function Fe(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 l("preload suppressed:",n),0;let r=L(e,t),o=Math.max(1,r.config.preloadPoolSize),i=await q(e,o,r);if(!i)return 0;let a=Date.now(),s=Z(i.ads,a);return S({...t,pool:s,cachedConfig:i.config,configFetchedAt:a}),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 l("renderFromPool suppressed:",r),false;let{ad:o,pool:i}=Q(t,n);if(!o)return S({...t,pool:i}),false;let a=await oe(o,{...t,pool:i});S(a);let s=L(e,t);return j(o.impressionId,s),true}var lt={show(e){return M(()=>De(e)).then(t=>t??false)},fetch(e){return M(()=>Be(e))},preload(e){return M(()=>Fe(e)).then(t=>t??0)},renderFromPool(e){return M(()=>Ne(e)).then(t=>t??false)}};exports.DEFAULT_CONFIG=b;exports.HOOK_CATALOG=re;exports.SDK_VERSION=F;exports.detectImageProtocol=Y;exports.renderAd=G;exports.renderCard=m;exports.sponsor=lt;exports.textCardForAd=_;
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"]),A=4096;async function be(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 l(`media: HTTP ${i.status} for ${e}`),null;let a=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!ye.has(a))return l(`media: disallowed content-type "${a}" for ${e}`),null;let s=Number(i.headers.get("content-length")??"0");if(Number.isFinite(s)&&s>o)return l(`media: content-length ${s} exceeds ${o} for ${e}`),null;let u=i.body;if(u&&typeof u.getReader=="function"){let p=u.getReader(),I=[],E=0;for(;;){let{done:L,value:b}=await p.read();if(L)break;if(b!==void 0){if(E+=b.byteLength,E>o)return await p.cancel().catch(()=>{}),l(`media: stream exceeded ${o} bytes for ${e}`),null;I.push(b);}}return Buffer.concat(I)}let c=Buffer.from(await i.arrayBuffer());return c.byteLength>o?(l(`media: body ${c.byteLength} bytes exceeds ${o} for ${e}`),null):c}catch(i){return l(`media: fetch failed for ${e}:`,i),null}}function he(e){let t=e.toString("base64");return `${w}]1337;File=inline=1;size=${e.byteLength};width=auto:${t}${me}`}function Ce(e){let t=e.toString("base64");if(t.length<=A)return `${w}_Gf=100,a=T;${t}${w}\\`;let n=[];for(let r=0;r<t.length;r+=A){let o=t.slice(r,r+A),a=`m=${r+A>=t.length?0:1}`,s=r===0?`f=100,a=T,${a}`:a;n.push(`${w}_G${s};${o}${w}\\`);}return n.join("")}function x(e){let t=B(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 be(n.mediaUrl,t.fetchImpl??fetch,o);return i===null||i.byteLength===0?m(x(e),t):(r==="kitty"?Ce(i):he(i))+`
5
+ `+m(B(e),t)}catch(n){return l("media: render failed, falling back to text:",n),m(B(e),t)}}function ke(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=ke(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}function Te(e=process.env){return k__namespace.join(ee__namespace.homedir(),".config","opencrater")}function te(e=process.env){return k__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 Ee(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 ve(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 Be(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 Ae(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:Ee(n.allowedPlacements),sessionTopics:ve(n.sessionTopics),integrations:Oe(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:Pe(n.computeRouting),computeCards:Be(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=d__namespace.readFileSync(t,"utf8"),r=JSON.parse(n);return Ae(r)}catch{let n=ne();try{S(n,e);}catch{}return n}}function S(e,t=process.env){let n=te(t),r=k__namespace.dirname(n);d__namespace.mkdirSync(r,{recursive:true});let o=k__namespace.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);d__namespace.writeFileSync(o,JSON.stringify(e,null,2)+`
6
+ `,"utf8");let i=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let a=0;;a++)try{d__namespace.renameSync(o,n);return}catch(s){let u=s.code??"";if(a>=4||!i.has(u)){try{d__namespace.rmSync(o,{force:!0});}catch{}if(a>=4)return;throw s}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(a+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?{...h,...e}:h}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 l("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 l("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 l("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 l("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 a=Date.now(),s=Z(i.blips,a);return S({...t,pool:s,cachedConfig:i.config,configFetchedAt:a}),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 l("renderFromPool suppressed:",r),false;let{blip:o,pool:i}=Q(t,n);if(!o)return S({...t,pool:i}),false;let a=await oe(o,{...t,pool:i});S(a);let s=M(e,t);return j(o.impressionId,s),true}var lt={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=h;exports.HOOK_CATALOG=re;exports.SDK_VERSION=D;exports.detectImageProtocol=Y;exports.renderBlip=G;exports.renderCard=m;exports.sponsor=lt;exports.textCardForBlip=x;
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import {randomUUID}from'crypto';import*as d from'fs';import*as ee from'os';import*as k from'path';var D=(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 F="1.1.10";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 l(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let t=D("os"),n=D("fs"),r=D("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():(l(`POST ${t} -> HTTP ${i.status}`),null)}catch(i){return l(`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:F,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.ad!==void 0&&t.ad!==null&&(n.ad=t.ad),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.ads)?{ads:o.ads,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"),C={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},ce=60,le=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(c=>c.length>0),o=[],i="";for(let c of r){let p=i===""?c:`${i} ${c}`;if(p.length<=t)i=p;else if(i!==""&&o.push(i),i=c.length>t?y(c,t):c,o.length>=n)break}i!==""&&o.length<n&&o.push(i),o.length>n&&(o.length=n);let a=o.join(" "),s=o.length-1,u=o[s];return u!==void 0&&a.length<r.join(" ").length&&(o[s]=y(`${u}\u2026`,t)),o}function v(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 O(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 P(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(le,Math.min(n,ce))-4,i=t.color??O(),a=t.hyperlinks??v(),s=(f,B)=>i?`${B}${f}${C.reset}`:f,u=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored Blip \xB7 ${e.sponsorLabel}`,o):"Sponsored Blip",c=[];c.push(s(u,C.dim)),e.title!==e.sponsorLabel&&c.push(s(y(e.title,o),C.bold));for(let f of de(e.body,o,2))c.push(f);let p="\u2192 ";if(a){let f=y(e.cta??e.url,o-p.length);c.push(p+s(fe(e.url,f),C.dim));}else e.cta&&c.push(y(e.cta,o)),c.push(p+s(y(e.url,o-p.length),C.dim));let A=`\u256D${"\u2500".repeat(o+2)}\u256E`,I=`\u2570${"\u2500".repeat(o+2)}\u256F`,$=c.map(f=>{let B=" ".repeat(Math.max(0,o-pe(f)));return `\u2502 ${f}${B} \u2502`}),h=[];return t.disclosure&&h.push(s(ue,C.dim)),h.push(A,...$,I),h.join(`
1
+ import {randomUUID}from'crypto';import*as d from'fs';import*as ee from'os';import*as k 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 h={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var re=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var D="1.1.11";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 l(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let t=F("os"),n=F("fs"),r=F("path");n.appendFileSync(r.join(t.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(o=>String(o)).join(" ")}
2
+ `);}catch{}}catch{}}function v(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let t=h;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:v(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:v(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:v(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:v(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function 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():(l(`POST ${t} -> HTTP ${i.status}`),null)}catch(i){return l(`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"),C={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},ce=60,le=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(c=>c.length>0),o=[],i="";for(let c of r){let p=i===""?c:`${i} ${c}`;if(p.length<=t)i=p;else if(i!==""&&o.push(i),i=c.length>t?y(c,t):c,o.length>=n)break}i!==""&&o.length<n&&o.push(i),o.length>n&&(o.length=n);let a=o.join(" "),s=o.length-1,u=o[s];return u!==void 0&&a.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 B(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(le,Math.min(n,ce))-4,i=t.color??P(),a=t.hyperlinks??O(),s=(f,$)=>i?`${$}${f}${C.reset}`:f,u=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored Blip \xB7 ${e.sponsorLabel}`,o):"Sponsored Blip",c=[];c.push(s(u,C.dim)),e.title!==e.sponsorLabel&&c.push(s(y(e.title,o),C.bold));for(let f of de(e.body,o,2))c.push(f);let p="\u2192 ";if(a){let f=y(e.cta??e.url,o-p.length);c.push(p+s(fe(e.url,f),C.dim));}else e.cta&&c.push(y(e.cta,o)),c.push(p+s(y(e.url,o-p.length),C.dim));let I=`\u256D${"\u2500".repeat(o+2)}\u256E`,E=`\u2570${"\u2500".repeat(o+2)}\u256F`,L=c.map(f=>{let $=" ".repeat(Math.max(0,o-pe(f)));return `\u2502 ${f}${$} \u2502`}),b=[];return t.disclosure&&b.push(s(ue,C.dim)),b.push(I,...L,E),b.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"]),x=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 l(`media: HTTP ${i.status} for ${e}`),null;let a=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!ye.has(a))return l(`media: disallowed content-type "${a}" for ${e}`),null;let s=Number(i.headers.get("content-length")??"0");if(Number.isFinite(s)&&s>o)return l(`media: content-length ${s} exceeds ${o} for ${e}`),null;let u=i.body;if(u&&typeof u.getReader=="function"){let p=u.getReader(),A=[],I=0;for(;;){let{done:$,value:h}=await p.read();if($)break;if(h!==void 0){if(I+=h.byteLength,I>o)return await p.cancel().catch(()=>{}),l(`media: stream exceeded ${o} bytes for ${e}`),null;A.push(h);}}return Buffer.concat(A)}let c=Buffer.from(await i.arrayBuffer());return c.byteLength>o?(l(`media: body ${c.byteLength} bytes exceeds ${o} for ${e}`),null):c}catch(i){return l(`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 Ce(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),a=`m=${r+x>=t.length?0:1}`,s=r===0?`f=100,a=T,${a}`:a;n.push(`${w}_G${s};${o}${w}\\`);}return n.join("")}function _(e){let t=P(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(_(e),t);let r=t.protocol??Y();if(r==="none"||n.mediaUrl===void 0||n.mediaUrl==="")return m(_(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(_(e),t):(r==="kitty"?Ce(i):be(i))+`
5
- `+m(P(e),t)}catch(n){return l("media: render failed, falling back to text:",n),m(P(e),t)}}function ke(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=>({ad:r,renderBy:t+n}))}function Q(e,t){let n=ke(e.pool,t),r=n.shift();return {ad:r?r.ad:null,pool:n}}function Te(e=process.env){return k.join(ee.homedir(),".config","opencrater")}function te(e=process.env){return k.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 Ae(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.ad;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({ad:{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 Ie(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 ve(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 Oe(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 Pe(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 xe(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:Ie(n.allowedPlacements),sessionTopics:Ee(n.sessionTopics),integrations:ve(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:Oe(n.computeRouting),computeCards:Pe(n.computeCards),configFetchedAt:g(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:Ae(n.pool)}}function T(e=process.env){let t=te(e);try{let n=d.readFileSync(t,"utf8"),r=JSON.parse(n);return xe(r)}catch{let n=ne();try{S(n,e);}catch{}return n}}function S(e,t=process.env){let n=te(t),r=k.dirname(n);d.mkdirSync(r,{recursive:true});let o=k.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);d.writeFileSync(o,JSON.stringify(e,null,2)+`
6
- `,"utf8");let i=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let a=0;;a++)try{d.renameSync(o,n);return}catch(s){let u=s.code??"";if(a>=4||!i.has(u)){try{d.rmSync(o,{force:!0});}catch{}if(a>=4)return;throw s}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(a+1));}catch{}}}var _e=["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 Me(e){return H(e.OPENCRATER_DISABLE)||H(e.TSN_DISABLE)}function Le(e){return _e.some(t=>H(e[t]))}function z(e){return e?{...b,...e}:b}function R(e,t={}){if(Me(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(Le(e.env))return "ci";if(!t.skipTTY&&!e.isTTY)return "not_tty";if(!t.skipFrequency){let r=n.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<r)return "frequency"}return null}async function M(e){try{return await e()}catch(t){return l("suppressed error:",t),null}}function L(e,t){let n=z(t.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:n.serveTimeoutMs,installId:t.installId,config:n}}function $e(e,t){let n=!t.disclosureShown,r=m(e,{width:process.stdout.columns??80,color:O(),hyperlinks:v(),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:O(),hyperlinks:v(),disclosure:!t.disclosureShown});return process.stdout.write(n),{...t,lastShownAt:Date.now(),disclosureShown:true}}async function Be(e){let t=T(),n=R({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()},{skipFrequency:true});if(n!==null)return l("fetch suppressed:",n),null;let r=L(e,t),o=await U(e,r);return o?(S({...t,cachedConfig:o.config,configFetchedAt:Date.now()}),o.fill&&o.ad?o.ad:null):null}async function De(e){let t=T(),n=R({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()});if(n!==null)return l("suppressed:",n),false;let r=L(e,t),o=await U(e,r);return o?(t={...t,cachedConfig:o.config,configFetchedAt:Date.now()},o.fill&&o.ad?(t=await oe(o.ad,t),S(t),j(o.ad.impressionId,r),true):o.fallback?(t=$e(J(o.fallback),t),S(t),true):(S(t),false)):false}async function Fe(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 l("preload suppressed:",n),0;let r=L(e,t),o=Math.max(1,r.config.preloadPoolSize),i=await q(e,o,r);if(!i)return 0;let a=Date.now(),s=Z(i.ads,a);return S({...t,pool:s,cachedConfig:i.config,configFetchedAt:a}),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 l("renderFromPool suppressed:",r),false;let{ad:o,pool:i}=Q(t,n);if(!o)return S({...t,pool:i}),false;let a=await oe(o,{...t,pool:i});S(a);let s=L(e,t);return j(o.impressionId,s),true}var lt={show(e){return M(()=>De(e)).then(t=>t??false)},fetch(e){return M(()=>Be(e))},preload(e){return M(()=>Fe(e)).then(t=>t??0)},renderFromPool(e){return M(()=>Ne(e)).then(t=>t??false)}};export{b as DEFAULT_CONFIG,re as HOOK_CATALOG,F as SDK_VERSION,Y as detectImageProtocol,G as renderAd,m as renderCard,lt as sponsor,_ as textCardForAd};
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"]),A=4096;async function be(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 l(`media: HTTP ${i.status} for ${e}`),null;let a=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!ye.has(a))return l(`media: disallowed content-type "${a}" for ${e}`),null;let s=Number(i.headers.get("content-length")??"0");if(Number.isFinite(s)&&s>o)return l(`media: content-length ${s} exceeds ${o} for ${e}`),null;let u=i.body;if(u&&typeof u.getReader=="function"){let p=u.getReader(),I=[],E=0;for(;;){let{done:L,value:b}=await p.read();if(L)break;if(b!==void 0){if(E+=b.byteLength,E>o)return await p.cancel().catch(()=>{}),l(`media: stream exceeded ${o} bytes for ${e}`),null;I.push(b);}}return Buffer.concat(I)}let c=Buffer.from(await i.arrayBuffer());return c.byteLength>o?(l(`media: body ${c.byteLength} bytes exceeds ${o} for ${e}`),null):c}catch(i){return l(`media: fetch failed for ${e}:`,i),null}}function he(e){let t=e.toString("base64");return `${w}]1337;File=inline=1;size=${e.byteLength};width=auto:${t}${me}`}function Ce(e){let t=e.toString("base64");if(t.length<=A)return `${w}_Gf=100,a=T;${t}${w}\\`;let n=[];for(let r=0;r<t.length;r+=A){let o=t.slice(r,r+A),a=`m=${r+A>=t.length?0:1}`,s=r===0?`f=100,a=T,${a}`:a;n.push(`${w}_G${s};${o}${w}\\`);}return n.join("")}function x(e){let t=B(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 be(n.mediaUrl,t.fetchImpl??fetch,o);return i===null||i.byteLength===0?m(x(e),t):(r==="kitty"?Ce(i):he(i))+`
5
+ `+m(B(e),t)}catch(n){return l("media: render failed, falling back to text:",n),m(B(e),t)}}function ke(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=ke(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}function Te(e=process.env){return k.join(ee.homedir(),".config","opencrater")}function te(e=process.env){return k.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 Ee(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 ve(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 Be(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 Ae(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:Ee(n.allowedPlacements),sessionTopics:ve(n.sessionTopics),integrations:Oe(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:Pe(n.computeRouting),computeCards:Be(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=d.readFileSync(t,"utf8"),r=JSON.parse(n);return Ae(r)}catch{let n=ne();try{S(n,e);}catch{}return n}}function S(e,t=process.env){let n=te(t),r=k.dirname(n);d.mkdirSync(r,{recursive:true});let o=k.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);d.writeFileSync(o,JSON.stringify(e,null,2)+`
6
+ `,"utf8");let i=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let a=0;;a++)try{d.renameSync(o,n);return}catch(s){let u=s.code??"";if(a>=4||!i.has(u)){try{d.rmSync(o,{force:!0});}catch{}if(a>=4)return;throw s}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(a+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?{...h,...e}:h}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 l("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 l("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 l("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 l("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 a=Date.now(),s=Z(i.blips,a);return S({...t,pool:s,cachedConfig:i.config,configFetchedAt:a}),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 l("renderFromPool suppressed:",r),false;let{blip:o,pool:i}=Q(t,n);if(!o)return S({...t,pool:i}),false;let a=await oe(o,{...t,pool:i});S(a);let s=M(e,t);return j(o.impressionId,s),true}var lt={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{h as DEFAULT_CONFIG,re as HOOK_CATALOG,D as SDK_VERSION,Y as detectImageProtocol,G as renderBlip,m as renderCard,lt as sponsor,x as textCardForBlip};
package/dist/paint.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var child_process=require('child_process'),crypto=require('crypto'),Fe=require('http'),ot=require('fs'),Me=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 Me__namespace=/*#__PURE__*/_interopNamespace(Me);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 ke(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(Me__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 Re(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 k=0;k<h;k++){let C=l[D+1+k],b=k>=$?O[k-$]:0,S=I[k],B=k>=$?I[k-$]:0,y;switch(F){case 0:y=C;break;case 1:y=C+b;break;case 2:y=C+S;break;case 3:y=C+(b+S>>1);break;case 4:{let _=b+S-B,X=Math.abs(_-b),Ot=Math.abs(_-S),G=Math.abs(_-B);y=C+(X<=Ot&&X<=G?b:Ot<=G?S:B);break}default:return null}O[k]=y&255;}for(let k=0;k<i;k++){let C=k*$,b=(x*i+k)*4;N[b]=O[C],N[b+1]=O[C+1],N[b+2]=O[C+2],N[b+3]=$===4?O[C+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,Cn=12*1024*1024,An=6e3,_e=25e3,Ge=64,w="\x1B",kn="\x07",Te=`${w}7`,De=`${w}8`;function Ut(t,e){return `${w}]8;;${t}${w}\\${e}${w}]8;;${w}\\`}function jt(t){return t.replace(/\x1b\[[0-9;]*m/g,"").replace(/\x1b\]8;;[^\x1b\x07]*(?:\x1b\\|\x07)/g,"").replace(/[︎️]/g,"").length}function mt(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-1))}\u2026`}function xn(t,e){let 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 Mn(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(U__namespace.join(Me.homedir(),".config","opencrater","pump-err.log"),"a");}catch{}T("spawning pump:",e);let i=child_process.spawn(e,["-NoProfile","-NonInteractive","-EncodedCommand",t],{stdio:["pipe","pipe",n],windowsHide:!0});i.on("error",m=>T("pump spawn error:",e,"-",m.message)),i.on("exit",m=>T("pump process exited code",m,"pid",i.pid));let a=i.stdin;if(!a)return T("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&&(T("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 T("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]):(T("wmi spawn failed:",(a.stdout??"").trim(),"|",(a.stderr??"").trim()),0)}catch(e){return T("wmi spawn threw",e.message),0}}function Nn(t,e){try{let n=U__namespace.join(Me.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)];Wt&&p.push("--debug");let r=En(p.join(" "));return T("escape: wmi persistent painter pid",r),r>0}catch(n){return T("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 `${w}]1337;File=inline=1;size=${t.length};width=${e.w};height=${e.h};preserveAspectRatio=1:${n}${kn}`}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 _=y+1;_<4;_++){let X=r(l[y],l[_]);X>O&&(O=X,N=y,I=_);}let x=0,D=[0,0,0],F=[0,0,0],k=0,C=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],k++):(F[0]+=l[y][0],F[1]+=l[y][1],F[2]+=l[y][2],C++);if(O<1e3){let y=Ot=>Ot&-8,_=[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;${_[0]};${_[1]};${_[2]}m`:`${w}[48;5;${ae(_[0],_[1],_[2])}m`;X!==$&&(d+=X,$=X),d+=" ";continue}let b=k?[Math.round(D[0]/k),Math.round(D[1]/k),Math.round(D[2]/k)]:[0,0,0],S=C?[Math.round(F[0]/C),Math.round(F[1]/C),Math.round(F[2]/C)]: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 jn(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 Wn(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(C=>C.length>0);if(x.length===0)break;let D=" ".repeat(n),F=Math.floor((i-x.length)/2),k=[];for(let C=0;C<i;C++){let b=x[C-F];if(b===void 0)k.push(D);else {let S=" ".repeat(Math.max(0,n-jt(b)));k.push(b+S);}}h.push(k);}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(Me.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 p=0;p<e.rows;p++)i+=`\x1B[${e.row+p};${e.col}H${a}`;i+="\x1B8",t.write(i);}}}catch{}}var We="";function Gn(t){let e=JSON.stringify(t);if(e!==We){We=e;try{ot.mkdirSync(U__namespace.dirname(It),{recursive:!0}),ot.writeFileSync(It,JSON.stringify(t));}catch{}}}function Hn(){try{JSON.parse(ot.readFileSync(It,"utf8")).pid===process.pid&&ot.unlinkSync(It);}catch{}}var Wt=process.env.OPENCRATER_DEBUG==="1";function T(...t){try{if(!Wt)return;let e=`[opencrater-paint] ${t.map(n=>String(n)).join(" ")}`;console.error(e);try{ot.appendFileSync(U__namespace.join(Me.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"),p=process.env.OPENCRATER_PAINT;if(a)try{p=ot.readFileSync(a,"utf8");}catch(o){T("payload-file unreadable:",o.message);}if(!p){T("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"&&(Wt=!0),delete o._env;}r=o;}catch(o){T("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){T("Windows: could not start the console pump (powershell.exe)");return}d=o;}else {try{$=ot.openSync(m,"w");}catch(o){T("could not open output device",m,"-",o.message);return}d=Mn($);}T("painting via",Y?"Windows console pump":m,"format",r.format??"text"),process.env.OPENCRATER_FLOW!=="1"&&!Y&&je(d);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",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 k=x?Math.max(8,Math.min(16,Math.floor((F-14)/2)*2)):vn,C=O?5:k,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,_=Date.now(),X=l?`${w}[2m`:"",G=l?`${w}[38;5;214m`:"",L=l?`${w}[0m`:"",P=I,Ct=Tn(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,Mt=0,pt=0,q=null,J="none",Ft=null,Bt=null,at=null,Gt=0,me=0,Z=null,E=0,M=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*C))),M=Math.max(2,Math.min(C,Math.round(c/(2*u))||C)),O&&(M=Math.min(M,C));let f=Math.min(1,o/(E*2),s/(M*2));f<1&&(E=Math.max(8,Math.floor(E*f)),M=Math.max(2,Math.floor(M*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 Blip \xB7 ${s}`:"Sponsored Blip"),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,j=z>0?`Auto dismiss in: ${z}s `:"",R=l?z<=5?`${w}[1;38;5;196m`:z<=12?`${w}[1;38;5;178m`:`${w}[1;38;5;35m`:"",A=mt(c,Math.max(8,S-2-j.length)),W=" ".repeat(Math.max(1,S-A.length-j.length-1));f.push(`${X}${A}${L}${W}${R}${j}${L}${G}${v}${L}`);let Q=l?Ct!=="none"||(process.env.COLORTERM??"").includes("truecolor")?`${w}[1;38;2;255;184;48m`:`${w}[1;38;5;214m`:"",tt=O&&M>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",_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;f.push(`${it("\u266A")} ${G}${_t}${L} ${G}${sn}${L}`);}let Xt=process.env.TERM_PROGRAM??"",en=process.env.TERM??"",qt=Ct!=="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),_t=l?`${w}[38;2;${$t[0]};${$t[1]};${$t[2]}m`:"";yt.push(`${_t}${dt}${L}`);}let Ce=Bt??(r.impressionId?`${st}/r/${r.impressionId}`:null),Ae=Ce&&qt?` \xB7 ${Ut(Ce,`${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-jt(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-jt(v)));return `${G}\u2502${L} ${v}${z} ${G}\u2502${L}`},g;if(O&&M>0&&(H||rt)){let v=S-E-2,z=o[0]??"",j=o.slice(1),R=H?H[Mt%H.length]:null;g=[u,f(z)];let A=Math.max(j.length,M);for(let W=0;W<A;W++){let Q=j[W]??"",tt=" ".repeat(Math.max(0,v-jt(Q))),Xt=W<M&&R?R[W]??" ".repeat(E):" ".repeat(E);g.push(`${G}\u2502${L} ${Q}${tt} ${Xt} ${G}\u2502${L}`);}}else {g=[u,...o.map(f)];let v=Math.max(0,Math.floor((S-E)/2)),z=Math.max(0,S-E-v);if(H&&M>0){let j=H[Mt%H.length];for(let R=0;R<M;R++){let A=j[R]??" ".repeat(E);g.push(`${G}\u2502${L} ${" ".repeat(v)}${A}${" ".repeat(z)} ${G}\u2502${L}`);}}else if(rt&&M>0)for(let j=0;j<M;j++)g.push(`${G}\u2502${L} ${" ".repeat(S)} ${G}\u2502${L}`);}return g.push(...s.map(f)),g.push(c),he=s.length+1,g},Ht=0,be=`${w}[?2026h`,$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:_,...r.impressionId?{impressionId:r.impressionId}:{},...gt?{dismissUrl:gt}:{}});let s=be+Te,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&&M>0){let f=O?y+2:y+o.length-he-M,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&&Mt++,s},ct=()=>{d.write(zt());},Se=()=>{let o=be+Te+`${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,Rt=null,Pt=null,Et=null,gt=null,K=o=>{if(T("cleanup wipe="+o+" elapsed="+(Date.now()-_)+"ms"),fe||(fe=true,de([{type:"dwell",ms:Date.now()-_}])),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,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*M>1100?200:Ee;lt=setInterval(ct,H&&H.length>1?s:Lt);},Nt=()=>(Z||(Z=ot.mkdtempSync(U__namespace.join(Me.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 W=Buffer.alloc(A.width*A.height*3);for(let Q=0,tt=0;Q<A.rgba.length;Q+=4,tt+=3)W[tt]=A.rgba[Q],W[tt+1]=A.rgba[Q+1],W[tt+2]=A.rgba[Q+2];E=Math.floor(A.width/2),M=Math.floor(A.height/2),H=[ze(W,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,j=v?Number(v[2]):f?.h??9;if(O&&et("ffmpeg")&&z>0&&j>0){let R=Math.min(z,j),A=Math.floor((z-R)/2),W=Math.floor((j-R)/2);g=`crop=${R}:${R}:${A}:${W}`,z=R,j=R,v=null;}if(Xe(z,j),!o&&Ct==="iterm2"){rt=Le(s.data,{w:E,h:M}),pt=0;return}if(!o&&Ct==="kitty"&&s.type==="image/png"){rt=Dn(s.data,{w:E,h:M}),pt=0;return}if(o&&Ct==="iterm2"&&et("ffmpeg"))try{let R=U__namespace.join(Nt(),"out.gif");if(child_process.spawnSync("ffmpeg",["-y","-i",c,"-t","6","-vf","fps=8,scale=280:-1:flags=lanczos","-loop","0",R],{timeout:12e3}).status===0){let W=ot.readFileSync(R);if(W.length<=Ne){rt=Le(W,{w:E,h:M}),pt=0;return}}}catch{}if(et("ffmpeg"))try{let R=o||s.type==="image/gif",A=Wn(c,Nt(),E,M,R,g)??jn(c,E,M,R,N,g);A&&A.length>0&&(H=A,Mt=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(Me.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,Cn);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=ke(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");},_e).unref?.();}catch{}},ve=()=>{if(!r.impressionId||r.replay)return;let o=U__namespace.join(Me.homedir(),".config","opencrater","dismiss.signal"),s=Date.now();Rt=setInterval(()=>{try{let u=ot.readFileSync(o,"utf8"),c=JSON.parse(u),f=typeof c.at=="number"&&c.at>=s-5e3,g=!c.impressionId||c.impressionId===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(Me.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),T("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{}je(d);let g=H,v=!!(g&&g.length>1);ct(),lt=setInterval(ct,v?Ee:Lt),Ie(),Oe(),ve(),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),f);return}let s=o?.pid??0;s>0&&Nn(r,s)&&(d.close(),process.exit(0)),T("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
2
+ 'use strict';var child_process=require('child_process'),crypto=require('crypto'),Fe=require('http'),ot=require('fs'),Me=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 Me__namespace=/*#__PURE__*/_interopNamespace(Me);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 Ae(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(Me__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 Re(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 A=0;A<h;A++){let C=l[D+1+A],b=A>=$?O[A-$]:0,S=I[A],B=A>=$?I[A-$]:0,y;switch(F){case 0:y=C;break;case 1:y=C+b;break;case 2:y=C+S;break;case 3:y=C+(b+S>>1);break;case 4:{let _=b+S-B,X=Math.abs(_-b),Ot=Math.abs(_-S),G=Math.abs(_-B);y=C+(X<=Ot&&X<=G?b:Ot<=G?S:B);break}default:return null}O[A]=y&255;}for(let A=0;A<i;A++){let C=A*$,b=(x*i+A)*4;N[b]=O[C],N[b+1]=O[C+1],N[b+2]=O[C+2],N[b+3]=$===4?O[C+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,Cn=12*1024*1024,kn=6e3,_e=25e3,Ge=64,w="\x1B",An="\x07",Te=`${w}7`,De=`${w}8`;function Ut(t,e){return `${w}]8;;${t}${w}\\${e}${w}]8;;${w}\\`}function jt(t){return t.replace(/\x1b\[[0-9;]*m/g,"").replace(/\x1b\]8;;[^\x1b\x07]*(?:\x1b\\|\x07)/g,"").replace(/[︎️]/g,"").length}function mt(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-1))}\u2026`}function xn(t,e){let 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 Mn(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(U__namespace.join(Me.homedir(),".config","opencrater","pump-err.log"),"a");}catch{}T("spawning pump:",e);let i=child_process.spawn(e,["-NoProfile","-NonInteractive","-EncodedCommand",t],{stdio:["pipe","pipe",n],windowsHide:!0});i.on("error",m=>T("pump spawn error:",e,"-",m.message)),i.on("exit",m=>T("pump process exited code",m,"pid",i.pid));let a=i.stdin;if(!a)return T("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&&(T("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 T("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]):(T("wmi spawn failed:",(a.stdout??"").trim(),"|",(a.stderr??"").trim()),0)}catch(e){return T("wmi spawn threw",e.message),0}}function Nn(t,e){try{let n=U__namespace.join(Me.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)];Wt&&p.push("--debug");let r=En(p.join(" "));return T("escape: wmi persistent painter pid",r),r>0}catch(n){return T("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 `${w}]1337;File=inline=1;size=${t.length};width=${e.w};height=${e.h};preserveAspectRatio=1:${n}${An}`}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 _=y+1;_<4;_++){let X=r(l[y],l[_]);X>O&&(O=X,N=y,I=_);}let x=0,D=[0,0,0],F=[0,0,0],A=0,C=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],A++):(F[0]+=l[y][0],F[1]+=l[y][1],F[2]+=l[y][2],C++);if(O<1e3){let y=Ot=>Ot&-8,_=[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;${_[0]};${_[1]};${_[2]}m`:`${w}[48;5;${ae(_[0],_[1],_[2])}m`;X!==$&&(d+=X,$=X),d+=" ";continue}let b=A?[Math.round(D[0]/A),Math.round(D[1]/A),Math.round(D[2]/A)]:[0,0,0],S=C?[Math.round(F[0]/C),Math.round(F[1]/C),Math.round(F[2]/C)]: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 jn(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 Wn(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(C=>C.length>0);if(x.length===0)break;let D=" ".repeat(n),F=Math.floor((i-x.length)/2),A=[];for(let C=0;C<i;C++){let b=x[C-F];if(b===void 0)A.push(D);else {let S=" ".repeat(Math.max(0,n-jt(b)));A.push(b+S);}}h.push(A);}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(kn)});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(Me.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 p=0;p<e.rows;p++)i+=`\x1B[${e.row+p};${e.col}H${a}`;i+="\x1B8",t.write(i);}}}catch{}}var We="";function Gn(t){let e=JSON.stringify(t);if(e!==We){We=e;try{ot.mkdirSync(U__namespace.dirname(It),{recursive:!0}),ot.writeFileSync(It,JSON.stringify(t));}catch{}}}function Hn(){try{JSON.parse(ot.readFileSync(It,"utf8")).pid===process.pid&&ot.unlinkSync(It);}catch{}}var Wt=process.env.OPENCRATER_DEBUG==="1";function T(...t){try{if(!Wt)return;let e=`[opencrater-paint] ${t.map(n=>String(n)).join(" ")}`;console.error(e);try{ot.appendFileSync(U__namespace.join(Me.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"),p=process.env.OPENCRATER_PAINT;if(a)try{p=ot.readFileSync(a,"utf8");}catch(o){T("payload-file unreadable:",o.message);}if(!p){T("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"&&(Wt=!0),delete o._env;}r=o;}catch(o){T("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){T("Windows: could not start the console pump (powershell.exe)");return}d=o;}else {try{$=ot.openSync(m,"w");}catch(o){T("could not open output device",m,"-",o.message);return}d=Mn($);}T("painting via",Y?"Windows console pump":m,"format",r.format??"text"),process.env.OPENCRATER_FLOW!=="1"&&!Y&&je(d);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",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 A=x?Math.max(8,Math.min(16,Math.floor((F-14)/2)*2)):vn,C=O?5:A,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,_=Date.now(),X=l?`${w}[2m`:"",G=l?`${w}[38;5;214m`:"",L=l?`${w}[0m`:"",P=I,Ct=Tn(process.env),xt=process.env.OPENCRATER_FLOW==="1",Ye=process.env.OPENCRATER_MUTE==="1",st=r.apiOrigin??"https://api.opencrater.to",kt=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,Mt=0,pt=0,q=null,J="none",Ft=null,Bt=null,at=null,Gt=0,me=0,Z=null,E=0,M=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*C))),M=Math.max(2,Math.min(C,Math.round(c/(2*u))||C)),O&&(M=Math.min(M,C));let f=Math.min(1,o/(E*2),s/(M*2));f<1&&(E=Math.max(8,Math.floor(E*f)),M=Math.max(2,Math.floor(M*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 Blip \xB7 ${s}`:"Sponsored Blip"),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,j=z>0?`Auto dismiss in: ${z}s `:"",R=l?z<=5?`${w}[1;38;5;196m`:z<=12?`${w}[1;38;5;178m`:`${w}[1;38;5;35m`:"",k=mt(c,Math.max(8,S-2-j.length)),W=" ".repeat(Math.max(1,S-k.length-j.length-1));f.push(`${X}${k}${L}${W}${R}${j}${L}${G}${v}${L}`);let Q=l?Ct!=="none"||(process.env.COLORTERM??"").includes("truecolor")?`${w}[1;38;2;255;184;48m`:`${w}[1;38;5;214m`:"",tt=O&&M>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",_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;f.push(`${it("\u266A")} ${G}${_t}${L} ${G}${sn}${L}`);}let Xt=process.env.TERM_PROGRAM??"",en=process.env.TERM??"",qt=Ct!=="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-kt.length);yt.push(Ut(r.url,Kt(`${kt}${V} \u2192`,$t,Zt)));}else {let V=(r.cta&&r.cta.trim()!==""?r.cta.trim():"VISIT").toUpperCase();kt.length+V.length+1+Qt.length<=S?yt.push(Kt(`${V} ${kt}${Qt}`,$t,Zt)):yt.push(Kt(`${kt}${Qt}`,$t,Zt));let ft=process.platform==="darwin"?"\u2318-click":"Ctrl-click",dt=mt(`${it("\u2191")} ${ft} the link to open`,S),_t=l?`${w}[38;2;${$t[0]};${$t[1]};${$t[2]}m`:"";yt.push(`${_t}${dt}${L}`);}let Ce=Bt??(r.impressionId?`${st}/r/${r.impressionId}`:null),ke=Ce&&qt?` \xB7 ${Ut(Ce,`${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-jt(ke)))}${ke}${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-jt(v)));return `${G}\u2502${L} ${v}${z} ${G}\u2502${L}`},g;if(O&&M>0&&(H||rt)){let v=S-E-2,z=o[0]??"",j=o.slice(1),R=H?H[Mt%H.length]:null;g=[u,f(z)];let k=Math.max(j.length,M);for(let W=0;W<k;W++){let Q=j[W]??"",tt=" ".repeat(Math.max(0,v-jt(Q))),Xt=W<M&&R?R[W]??" ".repeat(E):" ".repeat(E);g.push(`${G}\u2502${L} ${Q}${tt} ${Xt} ${G}\u2502${L}`);}}else {g=[u,...o.map(f)];let v=Math.max(0,Math.floor((S-E)/2)),z=Math.max(0,S-E-v);if(H&&M>0){let j=H[Mt%H.length];for(let R=0;R<M;R++){let k=j[R]??" ".repeat(E);g.push(`${G}\u2502${L} ${" ".repeat(v)}${k}${" ".repeat(z)} ${G}\u2502${L}`);}}else if(rt&&M>0)for(let j=0;j<M;j++)g.push(`${G}\u2502${L} ${" ".repeat(S)} ${G}\u2502${L}`);}return g.push(...s.map(f)),g.push(c),he=s.length+1,g},Ht=0,be=`${w}[?2026h`,$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:_,...r.impressionId?{impressionId:r.impressionId}:{},...gt?{dismissUrl:gt}:{}});let s=be+Te,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&&M>0){let f=O?y+2:y+o.length-he-M,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&&Mt++,s},ct=()=>{d.write(zt());},Se=()=>{let o=be+Te+`${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,Rt=null,Pt=null,Et=null,gt=null,K=o=>{if(T("cleanup wipe="+o+" elapsed="+(Date.now()-_)+"ms"),fe||(fe=true,de([{type:"dwell",ms:Date.now()-_}])),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,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*M>1100?200:Ee;lt=setInterval(ct,H&&H.length>1?s:Lt);},Nt=()=>(Z||(Z=ot.mkdtempSync(U__namespace.join(Me.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 k=Pe(new Uint8Array(await R.arrayBuffer()));if(k&&k.width>=4&&k.height>=2){let W=Buffer.alloc(k.width*k.height*3);for(let Q=0,tt=0;Q<k.rgba.length;Q+=4,tt+=3)W[tt]=k.rgba[Q],W[tt+1]=k.rgba[Q+1],W[tt+2]=k.rgba[Q+2];E=Math.floor(k.width/2),M=Math.floor(k.height/2),H=[ze(W,k.width,k.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,j=v?Number(v[2]):f?.h??9;if(O&&et("ffmpeg")&&z>0&&j>0){let R=Math.min(z,j),k=Math.floor((z-R)/2),W=Math.floor((j-R)/2);g=`crop=${R}:${R}:${k}:${W}`,z=R,j=R,v=null;}if(Xe(z,j),!o&&Ct==="iterm2"){rt=Le(s.data,{w:E,h:M}),pt=0;return}if(!o&&Ct==="kitty"&&s.type==="image/png"){rt=Dn(s.data,{w:E,h:M}),pt=0;return}if(o&&Ct==="iterm2"&&et("ffmpeg"))try{let R=U__namespace.join(Nt(),"out.gif");if(child_process.spawnSync("ffmpeg",["-y","-i",c,"-t","6","-vf","fps=8,scale=280:-1:flags=lanczos","-loop","0",R],{timeout:12e3}).status===0){let W=ot.readFileSync(R);if(W.length<=Ne){rt=Le(W,{w:E,h:M}),pt=0;return}}}catch{}if(et("ffmpeg"))try{let R=o||s.type==="image/gif",k=Wn(c,Nt(),E,M,R,g)??jn(c,E,M,R,N,g);k&&k.length>0&&(H=k,Mt=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(Me.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,Cn);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=Ae(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");},_e).unref?.();}catch{}},ve=()=>{if(!r.impressionId||r.replay)return;let o=U__namespace.join(Me.homedir(),".config","opencrater","dismiss.signal"),s=Date.now();Rt=setInterval(()=>{try{let u=ot.readFileSync(o,"utf8"),c=JSON.parse(u),f=typeof c.at=="number"&&c.at>=s-5e3,g=!c.impressionId||c.impressionId===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(Me.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),T("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{}je(d);let g=H,v=!!(g&&g.length>1);ct(),lt=setInterval(ct,v?Ee:Lt),Ie(),Oe(),ve(),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),f);return}let s=o?.pid??0;s>0&&Nn(r,s)&&(d.close(),process.exit(0)),T("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
6
  `;for(let g of s)c+=`${u}${g}\r
7
7
  `;rt&&M>0&&(c+=`${u}${rt}\r
8
8
  `),d.write(c);let f=q?_e+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/")){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 ad 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(Me.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();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencrater",
3
- "version": "1.1.10",
3
+ "version": "1.1.11",
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",