opencrater 1.1.17 → 1.1.18
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 +1 -1
- package/dist/hook.js +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/paint.js +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
'use strict';var crypto=require('crypto'),p=require('fs'),J=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 p__namespace=/*#__PURE__*/_interopNamespace(p);var J__namespace=/*#__PURE__*/_interopNamespace(J);var l__namespace=/*#__PURE__*/_interopNamespace(l);var re__namespace=/*#__PURE__*/_interopNamespace(re);var j=(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(J__namespace.homedir(),".config","opencrater")}function C(e=process.env){return l__namespace.join(le(e),"state.json")}function z(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function y(e){return typeof e=="number"&&Number.isFinite(e)}function ue(e){if(typeof e!="object"||e===null)return null;let t=e;return !y(t.minIntervalSeconds)||!y(t.serveTimeoutMs)||!y(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:y(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function 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(!y(o.renderBy)||typeof r!="object"||r===null||typeof r.impressionId!="string"||typeof r.clickUrl!="string"||typeof r.sponsorLabel!="string"||typeof r.creative!="object"||r.creative===null)continue;let s=r.creative;typeof s.title!="string"||typeof s.body!="string"||t.push({blip:{impressionId:r.impressionId,...typeof r.campaignId=="string"?{campaignId:r.campaignId}:{},clickUrl:r.clickUrl,sponsorLabel:r.sponsorLabel,creative:{format:"text",title:s.title,body:s.body,...typeof s.cta=="string"?{cta:s.cta}:{}}},renderBy:o.renderBy});}return t}function 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"||!y(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=>y(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=z();if(typeof e!="object"||e===null)return t;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:t.installId,lastShownAt:y(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig: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:y(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:pe(n.pool)}}function h(e=process.env){let t=C(e);try{let n=p__namespace.readFileSync(t,"utf8"),o=JSON.parse(n);return ye(o)}catch{let n=z();try{G(n,e);}catch{}return n}}function G(e,t=process.env){let n=C(t),o=l__namespace.dirname(n);p__namespace.mkdirSync(o,{recursive:true});try{let i=JSON.parse(p__namespace.readFileSync(n,"utf8"));typeof i.lastShownAt=="number"&&i.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:i.lastShownAt});}catch{}let r=l__namespace.join(o,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);p__namespace.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
3
3
|
`,"utf8");let s=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let i=0;;i++)try{p__namespace.renameSync(r,n);return}catch(u){let a=u.code??"";if(i>=4||!s.has(a)){try{p__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={...h(t),...e};return G(n,t),n}var K={claude_code:["SessionStart","Stop","SessionEnd","Notification","UserPromptSubmit","SubagentStart","SubagentStop","StopFailure","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionRequest","PermissionDenied","UserPromptExpansion","PreCompact","PostCompact","TaskCreated","TaskCompleted","Setup","TeammateIdle","Elicitation","ElicitationResult","ConfigChange","InstructionsLoaded","WorktreeCreate","WorktreeRemove","CwdChanged","FileChanged","MessageDisplay"],codex:["Stop","SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","PreCompact","PostCompact"],openclaw:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd","Notification","BeforeAgent","BeforeModel","AfterModel","BeforeToolSelection","BeforeTool","AfterTool","PreCompress"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],generic:["SessionStart","Stop"]};var S=["claude_code","codex","gemini_cli","copilot_cli"];function w(e){return e.includes("opencrater-hook")}function ke(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Se(e,t){return w(e)&&new RegExp(`--package ['"]?${ke(t)}['"]?`).test(e)}function Q(e,t){return t?Se(e,t):w(e)&&!/--package\b/.test(e)}function V(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var q='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',W="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function H(e,t,n,o){let r=`--placement ${t}`;return n&&(r+=` --key ${V(n)}`),o&&(r+=` --package ${V(o)}`),r+=` --host ${e}`,`{ if [ -f ${q} ]; then node ${q} ${r}; else npx -y -p opencrater opencrater-hook ${r}; fi; } 2>/dev/null || true`}function be(e,t,n,o){let r=`--placement ${t}`;return n&&(r+=` --key '${n}'`),o&&(r+=` --package '${o}'`),r+=` --host ${e}`,`try { if (Test-Path "${W}") { node "${W}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function Y(e,t,n,o){return H(e,t,n,o)}function Z(e,t){let n=J__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=Z(e,t);switch(e){case "claude_code":return l__namespace.join(n,"settings.json");case "codex":return l__namespace.join(n,"hooks.json");case "gemini_cli":return l__namespace.join(n,"settings.json");case "copilot_cli":return l__namespace.join(n,"hooks","hooks.json");default:return l__namespace.join(n,"hooks.json")}}var we={claude_code:["claude"],codex:["codex"],gemini_cli:["gemini"],copilot_cli:["copilot"]};function ve(e,t){if(e.length===0)return false;let n=(t.PATH??t.Path??"").split(l__namespace.delimiter).filter(Boolean),o=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let r of n)for(let s of e)for(let i of o)try{if(p__namespace.existsSync(l__namespace.join(r,s+i)))return !0}catch{}return false}function Ce(e,t=process.env){try{if(p__namespace.existsSync(Z(e,t)))return !0}catch{}return ve(we[e]??[],t)}function _(e=process.env){return S.filter(t=>Ce(t,e))}function E(e){let t;try{t=p__namespace.readFileSync(e,"utf8");}catch{return {}}let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n}function M(e,t){let n=l__namespace.dirname(e);p__namespace.mkdirSync(n,{recursive:true});let o=l__namespace.join(n,`.${l__namespace.basename(e)}.${process.pid}.tmp`);p__namespace.writeFileSync(o,JSON.stringify(t,null,2)+`
|
|
4
|
-
`,"utf8"),p__namespace.renameSync(o,e);}function Oe(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&Q(n.command,t))}function Ae(e,t,n,o){let r=R(e),s=E(r),i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let d=Y(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(c=>Array.isArray(c.hooks)&&c.hooks.some(m=>m.command===d))}))return "nochange";for(let a of o){let c=(Array.isArray(i[a])?i[a]:[]).filter(m=>!Oe(m,n));c.push({matcher:"",hooks:[{type:"command",command:Y(e,a,t,n)}]}),i[a]=c;}return s.hooks=i,M(r,s),"wrote"}function Pe(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&Q(n,t))}function Re(e,t,n,o){let r=R(e),s=E(r);typeof s.version!="number"&&(s.version=1);let i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let d=H(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(c=>c.bash===d)}))return "nochange";for(let a of o){let c=(Array.isArray(i[a])?i[a]:[]).filter(m=>!Pe(m,n));c.push({type:"command",bash:H(e,a,t,n),powershell:be(e,a,t,n),timeoutSec:5}),i[a]=c;}return s.hooks=i,M(r,s),"wrote"}function I(e){return [...K[e]]}function U(e,t,n){let o=I(e);return o.length===0?"nochange":e==="copilot_cli"?Re(e,t,n,o):Ae(e,t,n,o)}function O(e,t,n=process.env){return _(n).map(o=>{try{let r=U(o,e,t);return {host:o,status:r,events:I(o)}}catch(r){return {host:o,status:"error",events:[],error:r.message}}})}function B(e=process.env){let t=[];for(let n of S){let o;try{o=E(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,d=Array.isArray(a.hooks)?a.hooks.find(f=>typeof f.command=="string"&&w(f.command))?.command:void 0,c=[a.bash,a.command,a.powershell].find(f=>typeof f=="string"&&w(f)),m=d??c;m&&t.push({host:n,event:s,command:m});}}return t}function ee(e=process.env){let t=0;for(let n of S){let o=R(n,e),r;try{r=E(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 d=Array.isArray(i[a])?i[a]:[],c=d.filter(m=>{let f=m,L=Array.isArray(f.hooks)&&f.hooks.some(v=>typeof v.command=="string"&&w(v.command))||[f.bash,f.powershell,f.command].some(v=>typeof v=="string"&&w(v));return L&&t++,!L});c.length!==d.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"),d=n==="copilot_cli"||n==="codex";Object.keys(i).length===0&&a.length===0&&d?p__namespace.rmSync(o,{force:!0}):M(o,r);}catch{}}return t}var A="1.1.
|
|
4
|
+
`,"utf8"),p__namespace.renameSync(o,e);}function Oe(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&Q(n.command,t))}function Ae(e,t,n,o){let r=R(e),s=E(r),i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let d=Y(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(c=>Array.isArray(c.hooks)&&c.hooks.some(m=>m.command===d))}))return "nochange";for(let a of o){let c=(Array.isArray(i[a])?i[a]:[]).filter(m=>!Oe(m,n));c.push({matcher:"",hooks:[{type:"command",command:Y(e,a,t,n)}]}),i[a]=c;}return s.hooks=i,M(r,s),"wrote"}function Pe(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&Q(n,t))}function Re(e,t,n,o){let r=R(e),s=E(r);typeof s.version!="number"&&(s.version=1);let i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let d=H(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(c=>c.bash===d)}))return "nochange";for(let a of o){let c=(Array.isArray(i[a])?i[a]:[]).filter(m=>!Pe(m,n));c.push({type:"command",bash:H(e,a,t,n),powershell:be(e,a,t,n),timeoutSec:5}),i[a]=c;}return s.hooks=i,M(r,s),"wrote"}function I(e){return [...K[e]]}function U(e,t,n){let o=I(e);return o.length===0?"nochange":e==="copilot_cli"?Re(e,t,n,o):Ae(e,t,n,o)}function O(e,t,n=process.env){return _(n).map(o=>{try{let r=U(o,e,t);return {host:o,status:r,events:I(o)}}catch(r){return {host:o,status:"error",events:[],error:r.message}}})}function B(e=process.env){let t=[];for(let n of S){let o;try{o=E(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,d=Array.isArray(a.hooks)?a.hooks.find(f=>typeof f.command=="string"&&w(f.command))?.command:void 0,c=[a.bash,a.command,a.powershell].find(f=>typeof f=="string"&&w(f)),m=d??c;m&&t.push({host:n,event:s,command:m});}}return t}function ee(e=process.env){let t=0;for(let n of S){let o=R(n,e),r;try{r=E(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 d=Array.isArray(i[a])?i[a]:[],c=d.filter(m=>{let f=m,L=Array.isArray(f.hooks)&&f.hooks.some(v=>typeof v.command=="string"&&w(v.command))||[f.bash,f.powershell,f.command].some(v=>typeof v=="string"&&w(v));return L&&t++,!L});c.length!==d.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"),d=n==="copilot_cli"||n==="codex";Object.keys(i).length===0&&a.length===0&&d?p__namespace.rmSync(o,{force:!0}):M(o,r);}catch{}}return t}var A="1.1.18";var Ee="https://api.opencrater.to";function $(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:Ee)).replace(/\/+$/,"")}function $e(){return l__namespace.join(J__namespace.homedir(),".config","opencrater","runtime")}function xe(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function x(e=$e()){if(process.env.VITEST||process.env.OPENCRATER_DISABLE_RUNTIME_PIN)return false;try{return child_process.spawnSync("npm",xe(e),{stdio:"ignore",windowsHide:!0,shell:process.platform==="win32"}).status===0}catch{return false}}function Ne(){let e=process.env.OPENCRATER_WEB_ORIGIN;return e&&e.trim()!==""?e.replace(/\/$/,""):$().replace("//api.","//").replace(/\/$/,"")}function Te(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 je(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 F(e){return `$${(e/1e6).toFixed(2)}`}async function D(e,t){try{let n=new URL(`${$()}/v1/dev/me`);t&&n.searchParams.set("installId",t);let o=await fetch(n,{headers:{authorization:`Bearer ${e}`}});return o.ok?await o.json():null}catch{return null}}async function He(){let e=`${Ne()}/dev/link`;console.log("Sign in and generate a CLI token here (we tried to open it):"),console.log(` ${e}
|
|
5
5
|
`),Te(e);let t=(await je("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,h().installId);if(!n)return console.error("Couldn't verify that token \u2014 check it and try again."),1;k({devToken:t}),console.log(`
|
|
6
6
|
\u2713 Signed in as ${n.displayName}.`),console.log(` Compute balance: ${F(n.balanceMicroUsd)} \xB7 tier: ${n.trustTier}`);let o=O().filter(r=>r.status!=="error").map(r=>r.host);return o.length?(console.log(` Wired into: ${o.join(", ")}`),process.stdout.write(" Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(x()?"\u2713":"skipped (hooks use npx fallback)")):console.log(" No supported AI CLIs detected yet \u2014 they'll wire automatically once you install one."),console.log(" See Blips in your sessions to earn your weekly compute."),0}async function _e(){let e=h().devToken;if(!e)return console.error("Not signed in. Run: opencrater login"),1;let t=await D(e,h().installId);return t?(console.log(`Compute balance: ${F(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 Me(){return k({devToken:null}),console.log("Signed out of the OpenCrater compute wallet on this machine."),0}async function Ue(e){let t=h().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await D(t,h().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let o=`${$().replace(/\/$/,"")}/gateway`,r=l__namespace.join(l__namespace.dirname(C()),"claude-gateway.settings.json");try{p__namespace.mkdirSync(l__namespace.dirname(r),{recursive:!0}),p__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 ${F(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=h();n.integrations.some(o=>o.key===e&&o.package===t)||k({integrations:[...n.integrations,{key:e,package:t}].slice(-32)});}function N(e,t){let n=t||"compute hooks";if(e.length===0){console.log(`No supported AI CLIs detected yet \u2014 OpenCrater will wire ${n} automatically the moment you install one (it re-checks on the next session).`);return}console.log(`OpenCrater wired ${n} into:`);for(let o of e)if(o.status==="error")console.log(` \u2717 ${o.host}: ${o.error}`);else {let r=o.status==="nochange"?" \u2014 already set up":"";console.log(` \u2022 ${o.host} (${o.events.join(", ")})${r}`);}}function Be(){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),N(O(n,o),o),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(x()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):h().devToken?(N(O()),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(x()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):(console.log("OpenCrater Blips are now ON for this machine."),console.log("Earn compute: run `opencrater login` (no package needed)."),console.log("Earn cash as a publisher: `opencrater on --key <key> --package <name>`.")),console.log("Opt out any time with: npx opencrater off"),0}function De(){let e=h(),t=e.lastShownAt>0?new Date(e.lastShownAt).toISOString():"never";console.log(`opencrater v${A}`),console.log(` state file: ${C()}`),console.log(` install id: ${e.installId}`),console.log(` opted out: ${e.optOut?"yes":"no"}`),console.log(` last shown: ${t}`),console.log(` pooled Blips: ${e.pool.length}`),console.log(` hosts found: ${_().join(", ")||"(none)"}`),console.log(` integrations: ${e.integrations.map(o=>o.package).join(", ")||"(none)"}`);let n=B();return console.log(` wired hooks: ${n.length}`),0}function Le(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=U(s,n,o);N([{host:s,status:i,events:I(s)}],o);}catch(i){return console.error(`Could not wire ${s}: ${i.message}`),1}}else N(O(n,o),o);return console.log("Remove with: npx opencrater hooks uninstall"),0}function Je(){let e=ee();return k({integrations:[]}),console.log(e>0?`Removed ${e} OpenCrater hook${e===1?"":"s"} across all hosts.`:"No OpenCrater hooks installed."),0}function ze(){let e=B();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${A} \u2014 OpenCrater Blips
|
|
7
7
|
|
package/dist/hook.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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:""},ce={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],generic:["SessionStart","Stop"]},le={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.
|
|
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:""},ce={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],generic:["SessionStart","Stop"]},le={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.18";var tt="https://api.opencrater.to";function V(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return ((n&&n.trim()!==""?n:tt)).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
3
|
`);}catch{}}catch{}}function B(e){return typeof e=="number"&&Number.isFinite(e)}function nt(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 ue(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 pe(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:nt(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 de(e,t){let n=await j(t.origin,"/v1/serve",ue(e,t),t.timeoutMs);return pe(n)}async function fe(e,t,n){let r={...ue(t,n),publisherKey:t.publisherKey??"",packageName:t.packageName??""},o=await j(n.origin,"/v1/dev/serve",r,n.timeoutMs,{authorization:`Bearer ${e}`});return pe(o)}function me(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 ge(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 he(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function L(e){let t=ge(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 Se(e=process.env){return g__namespace.join($(e),"state.json")}function be(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function k(e){return typeof e=="number"&&Number.isFinite(e)}function rt(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 it(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 st(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 at(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 ct(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 lt(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 ut(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 pt(e){let t=be();if(typeof e!="object"||e===null)return t;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:t.installId,lastShownAt:k(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:rt(n.cachedConfig),allowedPlacements:st(n.allowedPlacements),sessionTopics:at(n.sessionTopics),integrations:ct(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:lt(n.computeRouting),computeCards:ut(n.computeCards),configFetchedAt:k(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:it(n.pool)}}function q(e=process.env){let t=Se(e);try{let n=u__namespace.readFileSync(t,"utf8"),r=JSON.parse(n);return pt(r)}catch{let n=be();try{y(n,e);}catch{}return n}}function y(e,t=process.env){let n=Se(t),r=g__namespace.dirname(n);u__namespace.mkdirSync(r,{recursive:true});try{let s=JSON.parse(u__namespace.readFileSync(n,"utf8"));typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt});}catch{}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
4
|
`,"utf8");let i=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let s=0;;s++)try{u__namespace.renameSync(o,n);return}catch(c){let a=c.code??"";if(s>=4||!i.has(a)){try{u__namespace.rmSync(o,{force:!0});}catch{}if(s>=4)return;throw c}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(s+1));}catch{}}}var dt=300*1e3;function ft(){return g__namespace.join($(),"blocked-ads.json")}function X(){return g__namespace.join($(),"recent-renders.json")}function mt(){return g__namespace.join($(),"reported-ads.json")}function ke(e,t){let n={};for(let[r,o]of Object.entries(e))typeof o=="number"&&Number.isFinite(o)&&o>t&&(n[r]=o);return n}function gt(e){try{let t=JSON.parse(u__namespace.readFileSync(ft(),"utf8"));return ke(t&&typeof t=="object"?t:{},e)}catch{return {}}}function ht(){try{let e=JSON.parse(u__namespace.readFileSync(mt(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}function yt(e){return e?ht()[e]!==void 0:false}function H(e,t=Date.now()){return e?gt(t)[e]!==void 0||yt(e):false}function we(e){try{let t=JSON.parse(u__namespace.readFileSync(X(),"utf8"));return ke(t&&typeof t=="object"?t:{},e)}catch{return {}}}function U(e,t=Date.now()){if(e)try{let n=we(t);n[e]=t+dt,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?we(t)[e]!==void 0:false}function St(e,t){return e.filter(n=>n.renderBy>t)}function Z(e,t){let n=St(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}var bt=["claude_code","codex","gemini_cli","copilot_cli"];function Oe(e){return e.includes("opencrater-hook")}function kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wt(e,t){return Oe(e)&&new RegExp(`--package ['"]?${kt(t)}['"]?`).test(e)}function _e(e,t){return t?wt(e,t):Oe(e)&&!/--package\b/.test(e)}function ve(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Ce='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',Re="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function Q(e,t,n,r){let o=`--placement ${t}`;return n&&(o+=` --key ${ve(n)}`),r&&(o+=` --package ${ve(r)}`),o+=` --host ${e}`,`{ if [ -f ${Ce} ]; then node ${Ce} ${o}; else npx -y -p opencrater opencrater-hook ${o}; fi; } 2>/dev/null || true`}function vt(e,t,n,r){let o=`--placement ${t}`;return n&&(o+=` --key '${n}'`),r&&(o+=` --package '${r}'`),o+=` --host ${e}`,`try { if (Test-Path "${Re}") { node "${Re}" ${o} } else { npx -y -p opencrater opencrater-hook ${o} } } catch {}`}function Ee(e,t,n,r){return Q(e,t,n,r)}function Ie(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 J(e,t=process.env){let n=Ie(e,t);switch(e){case "claude_code":return g__namespace.join(n,"settings.json");case "codex":return g__namespace.join(n,"hooks.json");case "gemini_cli":return g__namespace.join(n,"settings.json");case "copilot_cli":return g__namespace.join(n,"hooks","hooks.json");default:return g__namespace.join(n,"hooks.json")}}var Ct={claude_code:["claude"],codex:["codex"],gemini_cli:["gemini"],copilot_cli:["copilot"]};function Rt(e,t){if(e.length===0)return false;let n=(t.PATH??t.Path??"").split(g__namespace.delimiter).filter(Boolean),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let o of n)for(let i of e)for(let s of r)try{if(u__namespace.existsSync(g__namespace.join(o,i+s)))return !0}catch{}return false}function Et(e,t=process.env){try{if(u__namespace.existsSync(Ie(e,t)))return !0}catch{}return Rt(Ct[e]??[],t)}function ee(e=process.env){return bt.filter(t=>Et(t,e))}function Ae(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 Pe(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
5
|
`,"utf8"),u__namespace.renameSync(r,e);}function Tt(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&_e(n.command,t))}function Ot(e,t,n,r){let o=J(e),i=Ae(o),s=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(r.every(a=>{let d=Ee(e,a,t,n);return (Array.isArray(s[a])?s[a]:[]).some(f=>Array.isArray(f.hooks)&&f.hooks.some(l=>l.command===d))}))return "nochange";for(let a of r){let f=(Array.isArray(s[a])?s[a]:[]).filter(l=>!Tt(l,n));f.push({matcher:"",hooks:[{type:"command",command:Ee(e,a,t,n)}]}),s[a]=f;}return i.hooks=s,Pe(o,i),"wrote"}function _t(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&_e(n,t))}function It(e,t,n,r){let o=J(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(l=>!_t(l,n));f.push({type:"command",bash:Q(e,a,t,n),powershell:vt(e,a,t,n),timeoutSec:5}),s[a]=f;}return i.hooks=s,Pe(o,i),"wrote"}function xe(e){return [...le[e]]}function At(e,t,n){let r=xe(e);return r.length===0?"nochange":e==="copilot_cli"?It(e,t,n,r):Ot(e,t,n,r)}function te(e,t,n=process.env){return ee(n).map(r=>{try{let o=At(r,e,t);return {host:r,status:o,events:xe(r)}}catch(o){return {host:r,status:"error",events:[],error:o.message}}})}function xt(){return g__namespace.join(R__namespace.homedir(),".config","opencrater","runtime")}function Nt(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function ne(e=xt()){child_process.spawn("npm",Nt(e),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var De={atLimit:false,resetAt:null};function Be(e,t=R__namespace.homedir()){try{if(e==="claude_code")return Mt(t);if(e==="codex")return $t(t)}catch{}return De}function Mt(e){let t=u__namespace.readFileSync(g__namespace.join(e,".claude.json"),"utf8"),n=JSON.parse(t),r=n.hasAvailableSubscription===false||n.cachedExtraUsageDisabledReason==="out_of_credits",o=null,c=n.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof c=="string"){let a=Date.parse(c);Number.isFinite(a)&&(o=a);}return {atLimit:r,resetAt:o}}function $t(e){return u__namespace.accessSync(g__namespace.join(e,".codex","auth.json")),De}function je(e,t){switch(e){case "gemini_cli":return t==="AfterAgent";case "copilot_cli":return t==="agentStop";default:return t==="Stop"}}var Le=36e5,Dt=30*6e4,Bt=30*6e4,jt=4*Le,Lt=3,G="https://opencrater.to/dashboard";function K(e){return `$${(e/1e6).toFixed(2)}`}function Ht(e,t){return t<=0?0:Math.max(0,Math.min(100,Math.round(e/t*100)))}function Ut(e,t){if(!e||e<=t)return "";let n=e-t,r=n>=864e5?`${Math.floor(n/864e5)}d`:`${Math.max(1,Math.floor(n/Le))}h`,o=new Date(e).toISOString().slice(0,10);return ` Your host limit resets in ${r} (${o}).`}function He(e){let{balanceMicroUsd:t,weeklyGrantMicroUsd:n,onGateway:r,turnEnd:o,host:i,cc:s,now:c}=e;if(t===null)return null;if(t<=0)return c-(s.lastDepletedAt??0)<Bt?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."+Ut(i.resetAt,c),url:G,cta:"Earn more"}};if(r){if(!o||(s.turns??0)%Lt!==0)return null;let a=n&&n>0?Ht(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:G,cta:"Wallet"}}}return i.atLimit?c-(s.lastLimitAt??0)<Dt?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:G,cta:"opencrater code -c"}}:c-(s.lastBackupAt??0)>=jt?{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:G,cta:"opencrater code -c"}}:null}var Kt=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function re(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Yt(e){return re(e.OPENCRATER_DISABLE)||re(e.TSN_DISABLE)}function zt(e){return Kt.some(t=>re(e[t]))}function z(e){return e?{...M,...e}:M}function ze(e,t={}){if(Yt(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(zt(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 Vt=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 Wt(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 qt(e,t=12){let n=[];for(let r of e.slice(0,2e3).split(/\s+/))if(!(!r||Wt(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)||Vt.has(i))&&!n.includes(i)&&(n.push(i),n.length>=t))return n}return n}function ie(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 qt(t.join(" "))}function se(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 Ve(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,en=process.platform==="win32"?8e3:3200,tn=150,We=250,nn=2800;function on(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 rn(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 sn="\\\\.\\CONOUT$";function an(e){return !e||e==="?"||e==="??"||e==="-"?null:e.startsWith("/")?e:`/dev/${e}`}function cn(e){let t=e.match(/^\s*(\d+)\s+(\S+)/);return t?{ppid:Number(t[1]),tty:t[2]}:null}function ln(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 un(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 pn(e){try{let t=un(u__namespace.readFileSync(`/proc/${e}/stat`,"utf8"));if(t)return {ppid:t.ppid,ttyPath:ln(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=cn(t);return n?{ppid:n.ppid,ttyPath:an(n.tty)}:null}catch{return null}}function dn(){if(process.platform==="win32")return {path:sn,ownerPid:null};let e=process.pid;for(let t=0;t<12&&e>1;t++){let n=pn(e);if(!n)return null;if(n.ttyPath)return {path:n.ttyPath,ownerPid:e};e=n.ppid;}return null}function fn(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),c=Math.min(Math.max(s.displayDurationSeconds??25,3),120),a={...e,format:n?.format,mediaUrl:n?.mediaUrl,mediaPixelUrl:n?.mediaPixelUrl,audioUrl:n?.audioUrl,impressionId:r,campaignId:o,apiOrigin:V(),durationMs:c*1e3,disclosure:!t.disclosureShown},d={...process.env,OPENCRATER_PAINT:JSON.stringify(a)};if(!d.OPENCRATER_TTY){let l=dn();l&&(d.OPENCRATER_TTY=l.path,l.ownerPid!==null&&(d.OPENCRATER_HOST_PID=String(l.ownerPid)));}let f=child_process.spawn(process.execPath,[i],{...fn(process.platform),env:d});process.platform==="win32"?await new Promise(l=>{let p=!1,O=()=>{p||(p=!0,l());};f.on("exit",O),f.on("error",O),setTimeout(O,7500);}):f.unref();}catch{}return {...t,lastShownAt:Date.now(),disclosureShown:true}}function qe(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 mn=8e3;function Xe(){let e=g__namespace.join(R__namespace.homedir(),".config","opencrater","render.lock");try{let t=u__namespace.statSync(e);if(Date.now()-t.mtimeMs<mn)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 gn(e,t,n,r){if(!t)return true;let o=e.allowedPlacements[`${t}:${n}`];return o?o.includes(r):t==="opencrater"?ce[n].includes(r):true}var hn=1440*60*1e3;function yn(){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<hn)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()));}ne(e);}catch{}}function Ze(e,t){if(!t)return false;let n=s=>s.split(/[-+]/)[0].split(".").map(c=>parseInt(c,10)||0),r=n(e),o=n(t),i=Math.max(r.length,o.length);for(let s=0;s<i;s++){let c=r[s]??0,a=o[s]??0;if(c!==a)return c<a}return false}function Qe(){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{}ne(e);}catch{}}function Sn(){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 bn=1440*60*1e3;function kn(){try{let e=g__namespace.join(R__namespace.homedir(),".config","opencrater"),t=g__namespace.join(e,".last-host-check"),n=g__namespace.join(e,".known-hosts"),r=ee().sort(),o=[];try{let c=JSON.parse(u__namespace.readFileSync(n,"utf8"));Array.isArray(c)&&(o=c.filter(a=>typeof a=="string"));}catch{}if(!r.some(c=>!o.includes(c)))try{if(Date.now()-u__namespace.statSync(t).mtimeMs<bn)return}catch{}u__namespace.mkdirSync(e,{recursive:!0});try{u__namespace.writeFileSync(t,String(Date.now()));}catch{return}let s=q();try{u__namespace.writeFileSync(n,JSON.stringify(r));}catch{}if(s.optOut)return;if(s.devToken)try{te();}catch{}for(let c of s.integrations)try{te(c.key,c.package);}catch{}}catch{}}async function wn(){let e=on(process.argv.slice(2));Sn(),yn(),kn();let t=await rn(tn),n={};if(t)try{n=JSON.parse(t);let p=n.hook_event_name;!e.placement&&typeof p=="string"&&(e.placement=p);}catch{}let r=e.placement??"SessionStart",o=q(),i=ze({env:process.env,state:o,now:Date.now()},{skipTTY:true});if(i!==null){if(i==="frequency"){let p=ie(n);p.length>0&&y({...o,sessionTopics:se(o.sessionTopics,p,Date.now())});}h("hook suppressed:",i);return}if(o={...o,sessionTopics:se(o.sessionTopics,ie(n),Date.now())},!gn(o,e.package,e.host,r)){y(o),h("hook gated: placement",r,"not selected for",e.package);return}let s=z(o.cachedConfig),c=V(),a={origin:c,timeoutMs:Math.min(s.serveTimeoutMs,nn),installId:o.installId,topics:Ve(o.sessionTopics,Date.now())};if(o.devToken){let p=await fe(o.devToken,{publisherKey:e.key??"",packageName:e.package??"",placement:r,host:e.host},a);if(p){if(o={...o,cachedConfig:p.config,configFetchedAt:Date.now()},Ze(E,p.config.minSdkVersion)&&Qe(),Qt);let O=e.host??"claude_code",ae=je(O,r),_=o.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};ae&&(_.turns+=1);let I=He({balanceMicroUsd:typeof p.computeBalanceMicroUsd=="number"?p.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof p.weeklyGrantMicroUsd=="number"?p.weeklyGrantMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway"),turnEnd:ae,host:Be(O),cc:_,now:Date.now()}),et=(p.config.displayDurationSeconds??25)*1e3,v=p.fill&&p.blip&&!H(p.blip.campaignId)&&!F(p.blip.campaignId)?p.blip:null;if((I||v)&&!qe(et)&&Xe())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&&(U(v.campaignId),o=await D(L(v),o,v.creative,v.impressionId,v.campaignId),o.devToken&&me(o.devToken,v.impressionId,a));o={...o,computeCards:_};}y(o);return}let{blip:d,pool:f}=Z(o,Date.now());for(;d&&(H(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)&&qe((s.displayDurationSeconds??25)*1e3)){y(o),h("hook: a card is already on screen \u2014 not rendering another");return}if((d||e.key)&&!Xe()){y(o),h("hook: render slot already claimed by a concurrent fire");return}if(d){U(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(p=>setTimeout(p,We).unref?.())]);return}if(f.length!==o.pool.length&&(o={...o,pool:f}),!e.key||!e.package){y(o),h("hook: pool empty and no --key/--package; nothing to render");return}let l=await de({publisherKey:e.key,packageName:e.package,placement:r,host:e.host},a);if(!l){y(o);return}if(o={...o,cachedConfig:l.config,configFetchedAt:Date.now()},Ze(E,l.config.minSdkVersion)&&(h(`SDK ${E} below floor ${l.config.minSdkVersion} \u2014 forcing runtime update`),Qe()),e.package&&l.allowedPlacements&&(o={...o,allowedPlacements:{...o.allowedPlacements,[`${e.package}:${e.host}`]:l.allowedPlacements}}),l.fill&&l.blip){if(H(l.blip.campaignId)||F(l.blip.campaignId)){h("hook: served blip suppressed \u2014 campaign inside a local cooldown"),y(o);return}U(l.blip.campaignId),o=await D(L(l.blip),o,l.blip.creative,l.blip.impressionId,l.blip.campaignId),y(o),await Promise.race([W(l.blip.impressionId,a),new Promise(p=>setTimeout(p,We).unref?.())]);return}l.fallback&&(o=await D(he(l.fallback),o)),y(o);}if(typeof P<"u"&&typeof module<"u"&&P.main===module){let e=setTimeout(()=>process.exit(0),en);wn().catch(t=>h(`opencrater-hook v${E} error:`,t)).finally(()=>{clearTimeout(e),process.exit(0);});}
|
package/dist/index.d.mts
CHANGED
|
@@ -224,7 +224,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
|
|
|
224
224
|
|
|
225
225
|
/** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
|
|
226
226
|
* AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
|
|
227
|
-
declare const SDK_VERSION = "1.1.
|
|
227
|
+
declare const SDK_VERSION = "1.1.18";
|
|
228
228
|
|
|
229
229
|
/** Public API. Every method is fail-silent: it never throws. */
|
|
230
230
|
declare const sponsor: {
|
package/dist/index.d.ts
CHANGED
|
@@ -224,7 +224,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
|
|
|
224
224
|
|
|
225
225
|
/** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
|
|
226
226
|
* AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
|
|
227
|
-
declare const SDK_VERSION = "1.1.
|
|
227
|
+
declare const SDK_VERSION = "1.1.18";
|
|
228
228
|
|
|
229
229
|
/** Public API. Every method is fail-silent: it never throws. */
|
|
230
230
|
declare const sponsor: {
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
'use strict';var crypto=require('crypto'),u=require('fs'),ee=require('os'),C=require('path');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var u__namespace=/*#__PURE__*/_interopNamespace(u);var ee__namespace=/*#__PURE__*/_interopNamespace(ee);var C__namespace=/*#__PURE__*/_interopNamespace(C);var F=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var b={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var re=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var D="1.1.
|
|
2
|
-
`);}catch{}}catch{}}function v(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: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"),k={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 fe(e,t,n){let r=e.split(/\s+/).filter(c=>c.length>0),o=[],i="";for(let c of r){let f=i===""?c:`${i} ${c}`;if(f.length<=t)i=f;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 s=o.join(" "),a=o.length-1,p=o[a];return p!==void 0&&s.length<r.join(" ").length&&(o[a]=y(`${p}\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 de(e,t){return `\x1B]8;;${e}\x07${t}\x1B]8;;\x07`}function A(e){let t={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(t.cta=e.creative.cta),t}function J(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function m(e,t={}){let n=t.width??process.stdout.columns??80,o=Math.max(le,Math.min(n,ce))-4,i=t.color??P(),s=t.hyperlinks??O(),a=(d,$)=>i?`${$}${d}${k.reset}`:d,p=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored
|
|
1
|
+
'use strict';var crypto=require('crypto'),u=require('fs'),ee=require('os'),C=require('path');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var u__namespace=/*#__PURE__*/_interopNamespace(u);var ee__namespace=/*#__PURE__*/_interopNamespace(ee);var C__namespace=/*#__PURE__*/_interopNamespace(C);var F=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var b={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var re=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var D="1.1.18";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=b;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:v(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:v(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:v(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:v(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function 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"),k={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 fe(e,t,n){let r=e.split(/\s+/).filter(c=>c.length>0),o=[],i="";for(let c of r){let f=i===""?c:`${i} ${c}`;if(f.length<=t)i=f;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 s=o.join(" "),a=o.length-1,p=o[a];return p!==void 0&&s.length<r.join(" ").length&&(o[a]=y(`${p}\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 de(e,t){return `\x1B]8;;${e}\x07${t}\x1B]8;;\x07`}function A(e){let t={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(t.cta=e.creative.cta),t}function J(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function m(e,t={}){let n=t.width??process.stdout.columns??80,o=Math.max(le,Math.min(n,ce))-4,i=t.color??P(),s=t.hyperlinks??O(),a=(d,$)=>i?`${$}${d}${k.reset}`:d,p=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,o):"Sponsored Blips",c=[];c.push(a(p,k.dim)),e.title!==e.sponsorLabel&&c.push(a(y(e.title,o),k.bold));for(let d of fe(e.body,o,2))c.push(d);let f="\u2192 ";if(s){let d=y(e.cta??e.url,o-f.length);c.push(f+a(de(e.url,d),k.dim));}else e.cta&&c.push(y(e.cta,o)),c.push(f+a(y(e.url,o-f.length),k.dim));let I=`\u256D${"\u2500".repeat(o+2)}\u256E`,E=`\u2570${"\u2500".repeat(o+2)}\u256F`,L=c.map(d=>{let $=" ".repeat(Math.max(0,o-pe(d)));return `\u2502 ${d}${$} \u2502`}),h=[];return t.disclosure&&h.push(a(ue,k.dim)),h.push(I,...L,E),h.join(`
|
|
3
3
|
`)+`
|
|
4
4
|
`}function X(e){return e!==void 0&&e!==""}function Y(e=process.env,t=!!process.stdout.isTTY){if(!t)return "none";let n=e.TERM??"";if(X(e.TMUX)||n.startsWith("tmux")||n.startsWith("screen"))return "none";let r=e.TERM_PROGRAM??"";return r==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||r==="WezTerm"?"iterm2":n==="xterm-kitty"||X(e.KITTY_WINDOW_ID)?"kitty":"none"}var w="\x1B",me="\x07",ge=2e3,Se=2*1024*1024,ye=new Set(["image/png","image/jpeg","image/gif","image/webp"]),B=4096;async function he(e,t=fetch,n={}){let r=n.timeoutMs??ge,o=n.maxBytes??Se;try{let i=await t(e,{signal:AbortSignal.timeout(r)});if(!i.ok)return l(`media: HTTP ${i.status} for ${e}`),null;let s=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!ye.has(s))return l(`media: disallowed content-type "${s}" for ${e}`),null;let a=Number(i.headers.get("content-length")??"0");if(Number.isFinite(a)&&a>o)return l(`media: content-length ${a} exceeds ${o} for ${e}`),null;let p=i.body;if(p&&typeof p.getReader=="function"){let f=p.getReader(),I=[],E=0;for(;;){let{done:L,value:h}=await f.read();if(L)break;if(h!==void 0){if(E+=h.byteLength,E>o)return await f.cancel().catch(()=>{}),l(`media: stream exceeded ${o} bytes for ${e}`),null;I.push(h);}}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 be(e){let t=e.toString("base64");return `${w}]1337;File=inline=1;size=${e.byteLength};width=auto:${t}${me}`}function ke(e){let t=e.toString("base64");if(t.length<=B)return `${w}_Gf=100,a=T;${t}${w}\\`;let n=[];for(let r=0;r<t.length;r+=B){let o=t.slice(r,r+B),s=`m=${r+B>=t.length?0:1}`,a=r===0?`f=100,a=T,${s}`:s;n.push(`${w}_G${a};${o}${w}\\`);}return n.join("")}function x(e){let t=A(e),n=e.creative;switch(n.format){case "image":case "gif":return {...t,body:n.textFallback??t.body};case "video":return {...t,body:n.textFallback??t.body,cta:t.cta??"\u25B6 Watch"};case "audio":return {...t,body:n.textFallback??t.body,cta:t.cta??"\u{1F50A} Listen"};default:return t}}async function G(e,t={}){try{let n=e.creative;if(n.format!=="image"&&n.format!=="gif")return m(x(e),t);let r=t.protocol??Y();if(r==="none"||n.mediaUrl===void 0||n.mediaUrl==="")return m(x(e),t);let o={};t.timeoutMs!==void 0&&(o.timeoutMs=t.timeoutMs),t.maxBytes!==void 0&&(o.maxBytes=t.maxBytes);let i=await he(n.mediaUrl,t.fetchImpl??fetch,o);return i===null||i.byteLength===0?m(x(e),t):(r==="kitty"?ke(i):be(i))+`
|
|
5
5
|
`+m(A(e),t)}catch(n){return l("media: render failed, falling back to text:",n),m(A(e),t)}}function Ce(e,t){return e.filter(n=>n.renderBy>t)}function Z(e,t,n=18e5){return e.filter(r=>r&&typeof r.impressionId=="string"&&typeof r.clickUrl=="string"&&r.creative&&typeof r.creative.title=="string").map(r=>({blip:r,renderBy:t+n}))}function Q(e,t){let n=Ce(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}function Te(e=process.env){return C__namespace.join(ee__namespace.homedir(),".config","opencrater")}function te(e=process.env){return C__namespace.join(Te(e),"state.json")}function ne(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function g(e){return typeof e=="number"&&Number.isFinite(e)}function Re(e){if(typeof e!="object"||e===null)return null;let t=e;return !g(t.minIntervalSeconds)||!g(t.serveTimeoutMs)||!g(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:g(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function Ie(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n,o=r.blip;if(!g(r.renderBy)||typeof o!="object"||o===null||typeof o.impressionId!="string"||typeof o.clickUrl!="string"||typeof o.sponsorLabel!="string"||typeof o.creative!="object"||o.creative===null)continue;let i=o.creative;typeof i.title!="string"||typeof i.body!="string"||t.push({blip:{impressionId:o.impressionId,...typeof o.campaignId=="string"?{campaignId:o.campaignId}:{},clickUrl:o.clickUrl,sponsorLabel:o.sponsorLabel,creative:{format:"text",title:i.title,body:i.body,...typeof i.cta=="string"?{cta:i.cta}:{}}},renderBy:r.renderBy});}return t}function 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 Ae(e){if(typeof e!="object"||e===null)return null;let t=e,n=r=>g(r)&&r>=0?r:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function Be(e){let t=ne();if(typeof e!="object"||e===null)return t;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:t.installId,lastShownAt:g(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:Re(n.cachedConfig),allowedPlacements:Ee(n.allowedPlacements),sessionTopics:ve(n.sessionTopics),integrations:Oe(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:Pe(n.computeRouting),computeCards:Ae(n.computeCards),configFetchedAt:g(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:Ie(n.pool)}}function T(e=process.env){let t=te(e);try{let n=u__namespace.readFileSync(t,"utf8"),r=JSON.parse(n);return Be(r)}catch{let n=ne();try{S(n,e);}catch{}return n}}function S(e,t=process.env){let n=te(t),r=C__namespace.dirname(n);u__namespace.mkdirSync(r,{recursive:true});try{let s=JSON.parse(u__namespace.readFileSync(n,"utf8"));typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt});}catch{}let o=C__namespace.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);u__namespace.writeFileSync(o,JSON.stringify(e,null,2)+`
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {randomUUID}from'crypto';import*as u from'fs';import*as ee from'os';import*as C from'path';var F=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var b={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var re=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var D="1.1.
|
|
2
|
-
`);}catch{}}catch{}}function v(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: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"),k={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 fe(e,t,n){let r=e.split(/\s+/).filter(c=>c.length>0),o=[],i="";for(let c of r){let f=i===""?c:`${i} ${c}`;if(f.length<=t)i=f;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 s=o.join(" "),a=o.length-1,p=o[a];return p!==void 0&&s.length<r.join(" ").length&&(o[a]=y(`${p}\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 de(e,t){return `\x1B]8;;${e}\x07${t}\x1B]8;;\x07`}function A(e){let t={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(t.cta=e.creative.cta),t}function J(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function m(e,t={}){let n=t.width??process.stdout.columns??80,o=Math.max(le,Math.min(n,ce))-4,i=t.color??P(),s=t.hyperlinks??O(),a=(d,$)=>i?`${$}${d}${k.reset}`:d,p=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored
|
|
1
|
+
import {randomUUID}from'crypto';import*as u from'fs';import*as ee from'os';import*as C from'path';var F=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var b={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var re=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var D="1.1.18";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=b;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:v(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:v(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:v(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:v(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function 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"),k={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 fe(e,t,n){let r=e.split(/\s+/).filter(c=>c.length>0),o=[],i="";for(let c of r){let f=i===""?c:`${i} ${c}`;if(f.length<=t)i=f;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 s=o.join(" "),a=o.length-1,p=o[a];return p!==void 0&&s.length<r.join(" ").length&&(o[a]=y(`${p}\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 de(e,t){return `\x1B]8;;${e}\x07${t}\x1B]8;;\x07`}function A(e){let t={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(t.cta=e.creative.cta),t}function J(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function m(e,t={}){let n=t.width??process.stdout.columns??80,o=Math.max(le,Math.min(n,ce))-4,i=t.color??P(),s=t.hyperlinks??O(),a=(d,$)=>i?`${$}${d}${k.reset}`:d,p=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,o):"Sponsored Blips",c=[];c.push(a(p,k.dim)),e.title!==e.sponsorLabel&&c.push(a(y(e.title,o),k.bold));for(let d of fe(e.body,o,2))c.push(d);let f="\u2192 ";if(s){let d=y(e.cta??e.url,o-f.length);c.push(f+a(de(e.url,d),k.dim));}else e.cta&&c.push(y(e.cta,o)),c.push(f+a(y(e.url,o-f.length),k.dim));let I=`\u256D${"\u2500".repeat(o+2)}\u256E`,E=`\u2570${"\u2500".repeat(o+2)}\u256F`,L=c.map(d=>{let $=" ".repeat(Math.max(0,o-pe(d)));return `\u2502 ${d}${$} \u2502`}),h=[];return t.disclosure&&h.push(a(ue,k.dim)),h.push(I,...L,E),h.join(`
|
|
3
3
|
`)+`
|
|
4
4
|
`}function X(e){return e!==void 0&&e!==""}function Y(e=process.env,t=!!process.stdout.isTTY){if(!t)return "none";let n=e.TERM??"";if(X(e.TMUX)||n.startsWith("tmux")||n.startsWith("screen"))return "none";let r=e.TERM_PROGRAM??"";return r==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||r==="WezTerm"?"iterm2":n==="xterm-kitty"||X(e.KITTY_WINDOW_ID)?"kitty":"none"}var w="\x1B",me="\x07",ge=2e3,Se=2*1024*1024,ye=new Set(["image/png","image/jpeg","image/gif","image/webp"]),B=4096;async function he(e,t=fetch,n={}){let r=n.timeoutMs??ge,o=n.maxBytes??Se;try{let i=await t(e,{signal:AbortSignal.timeout(r)});if(!i.ok)return l(`media: HTTP ${i.status} for ${e}`),null;let s=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!ye.has(s))return l(`media: disallowed content-type "${s}" for ${e}`),null;let a=Number(i.headers.get("content-length")??"0");if(Number.isFinite(a)&&a>o)return l(`media: content-length ${a} exceeds ${o} for ${e}`),null;let p=i.body;if(p&&typeof p.getReader=="function"){let f=p.getReader(),I=[],E=0;for(;;){let{done:L,value:h}=await f.read();if(L)break;if(h!==void 0){if(E+=h.byteLength,E>o)return await f.cancel().catch(()=>{}),l(`media: stream exceeded ${o} bytes for ${e}`),null;I.push(h);}}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 be(e){let t=e.toString("base64");return `${w}]1337;File=inline=1;size=${e.byteLength};width=auto:${t}${me}`}function ke(e){let t=e.toString("base64");if(t.length<=B)return `${w}_Gf=100,a=T;${t}${w}\\`;let n=[];for(let r=0;r<t.length;r+=B){let o=t.slice(r,r+B),s=`m=${r+B>=t.length?0:1}`,a=r===0?`f=100,a=T,${s}`:s;n.push(`${w}_G${a};${o}${w}\\`);}return n.join("")}function x(e){let t=A(e),n=e.creative;switch(n.format){case "image":case "gif":return {...t,body:n.textFallback??t.body};case "video":return {...t,body:n.textFallback??t.body,cta:t.cta??"\u25B6 Watch"};case "audio":return {...t,body:n.textFallback??t.body,cta:t.cta??"\u{1F50A} Listen"};default:return t}}async function G(e,t={}){try{let n=e.creative;if(n.format!=="image"&&n.format!=="gif")return m(x(e),t);let r=t.protocol??Y();if(r==="none"||n.mediaUrl===void 0||n.mediaUrl==="")return m(x(e),t);let o={};t.timeoutMs!==void 0&&(o.timeoutMs=t.timeoutMs),t.maxBytes!==void 0&&(o.maxBytes=t.maxBytes);let i=await he(n.mediaUrl,t.fetchImpl??fetch,o);return i===null||i.byteLength===0?m(x(e),t):(r==="kitty"?ke(i):be(i))+`
|
|
5
5
|
`+m(A(e),t)}catch(n){return l("media: render failed, falling back to text:",n),m(A(e),t)}}function Ce(e,t){return e.filter(n=>n.renderBy>t)}function Z(e,t,n=18e5){return e.filter(r=>r&&typeof r.impressionId=="string"&&typeof r.clickUrl=="string"&&r.creative&&typeof r.creative.title=="string").map(r=>({blip:r,renderBy:t+n}))}function Q(e,t){let n=Ce(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}function Te(e=process.env){return C.join(ee.homedir(),".config","opencrater")}function te(e=process.env){return C.join(Te(e),"state.json")}function ne(){return {installId:randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function g(e){return typeof e=="number"&&Number.isFinite(e)}function Re(e){if(typeof e!="object"||e===null)return null;let t=e;return !g(t.minIntervalSeconds)||!g(t.serveTimeoutMs)||!g(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:g(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function Ie(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n,o=r.blip;if(!g(r.renderBy)||typeof o!="object"||o===null||typeof o.impressionId!="string"||typeof o.clickUrl!="string"||typeof o.sponsorLabel!="string"||typeof o.creative!="object"||o.creative===null)continue;let i=o.creative;typeof i.title!="string"||typeof i.body!="string"||t.push({blip:{impressionId:o.impressionId,...typeof o.campaignId=="string"?{campaignId:o.campaignId}:{},clickUrl:o.clickUrl,sponsorLabel:o.sponsorLabel,creative:{format:"text",title:i.title,body:i.body,...typeof i.cta=="string"?{cta:i.cta}:{}}},renderBy:r.renderBy});}return t}function 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 Ae(e){if(typeof e!="object"||e===null)return null;let t=e,n=r=>g(r)&&r>=0?r:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function Be(e){let t=ne();if(typeof e!="object"||e===null)return t;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:t.installId,lastShownAt:g(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:Re(n.cachedConfig),allowedPlacements:Ee(n.allowedPlacements),sessionTopics:ve(n.sessionTopics),integrations:Oe(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:Pe(n.computeRouting),computeCards:Ae(n.computeCards),configFetchedAt:g(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:Ie(n.pool)}}function T(e=process.env){let t=te(e);try{let n=u.readFileSync(t,"utf8"),r=JSON.parse(n);return Be(r)}catch{let n=ne();try{S(n,e);}catch{}return n}}function S(e,t=process.env){let n=te(t),r=C.dirname(n);u.mkdirSync(r,{recursive:true});try{let s=JSON.parse(u.readFileSync(n,"utf8"));typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt});}catch{}let o=C.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);u.writeFileSync(o,JSON.stringify(e,null,2)+`
|
package/dist/paint.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
'use strict';var child_process=require('child_process'),crypto=require('crypto'),We=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 We__namespace=/*#__PURE__*/_interopNamespace(We);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]),W=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(W);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),W=l[D];for(let k=0;k<h;k++){let A=l[D+1+k],b=k>=$?O[k-$]:0,S=I[k],B=k>=$?I[k-$]:0,y;switch(W){case 0:y=A;break;case 1:y=A+b;break;case 2:y=A+S;break;case 3:y=A+(b+S>>1);break;case 4:{let _=b+S-B,X=Math.abs(_-b),Ot=Math.abs(_-S),G=Math.abs(_-B);y=A+(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 A=k*$,b=(x*i+k)*4;N[b]=O[A],N[b+1]=O[A+1],N[b+2]=O[A+2],N[b+3]=$===4?O[A+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,An=12*1024*1024,Cn=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
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)];Ft&&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],W=[0,0,0],k=0,A=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++):(W[0]+=l[y][0],W[1]+=l[y][1],W[2]+=l[y][2],A++);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=A?[Math.round(W[0]/A),Math.round(W[1]/A),Math.round(W[2]/A)]: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 Fn(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
4
|
`).filter(A=>A.length>0);if(x.length===0)break;let D=" ".repeat(n),W=Math.floor((i-x.length)/2),k=[];for(let A=0;A<i;A++){let b=x[A-W];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 Wn(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(Cn)});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 Fe="";function Gn(t){let e=JSON.stringify(t);if(e!==Fe){Fe=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 Ft=process.env.OPENCRATER_DEBUG==="1";function T(...t){try{if(!Ft)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")&&(Ft=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"&&(Ft=!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,W=Y?24:40;if(Y)process.stdout.rows&&(W=process.stdout.rows);else try{let o=new pe__namespace.WriteStream(ot.openSync(m,"w"));o.rows&&(W=o.rows);}catch{}let k=x?Math.max(8,Math.min(16,Math.floor((W-14)/2)*2)):vn,A=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,At=Tn(process.env),xt=process.env.OPENCRATER_FLOW==="1",Ye=process.env.OPENCRATER_MUTE==="1",st=r.apiOrigin??"https://api.opencrater.to",Ct=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",Wt=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*A))),M=Math.max(2,Math.min(A,Math.round(c/(2*u))||A)),O&&(M=Math.min(M,A));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&>?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`:"",C=mt(c,Math.max(8,S-2-j.length)),F=" ".repeat(Math.max(1,S-C.length-j.length-1));f.push(`${X}${C}${L}${F}${R}${j}${L}${G}${v}${L}`);let Q=l?At!=="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=Wt?Ut(Wt,V):V;f.push(`${it("\u266A")} ${G}${_t}${L} ${G}${sn}${L}`);}let Xt=process.env.TERM_PROGRAM??"",en=process.env.TERM??"",qt=At!=="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-Ct.length);yt.push(Ut(r.url,Kt(`${Ct}${V} \u2192`,$t,Zt)));}else {let V=(r.cta&&r.cta.trim()!==""?r.cta.trim():"VISIT").toUpperCase();Ct.length+V.length+1+Qt.length<=S?yt.push(Kt(`${V} ${Ct}${Qt}`,$t,Zt)):yt.push(Kt(`${Ct}${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 Ae=Bt??(r.impressionId?`${st}/r/${r.impressionId}`:null),Ce=Ae&&qt?` \xB7 ${Ut(Ae,`${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(Ce)))}${Ce}${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 C=Math.max(j.length,M);for(let F=0;F<C;F++){let Q=j[F]??"",tt=" ".repeat(Math.max(0,v-jt(Q))),Xt=F<M&&R?R[F]??" ".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 C=j[R]??" ".repeat(E);g.push(`${G}\u2502${L} ${" ".repeat(v)}${C}${" ".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 C=Pe(new Uint8Array(await R.arrayBuffer()));if(C&&C.width>=4&&C.height>=2){let F=Buffer.alloc(C.width*C.height*3);for(let Q=0,tt=0;Q<C.rgba.length;Q+=4,tt+=3)F[tt]=C.rgba[Q],F[tt+1]=C.rgba[Q+1],F[tt+2]=C.rgba[Q+2];E=Math.floor(C.width/2),M=Math.floor(C.height/2),H=[ze(F,C.width,C.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")?Wn(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),C=Math.floor((z-R)/2),F=Math.floor((j-R)/2);g=`crop=${R}:${R}:${C}:${F}`,z=R,j=R,v=null;}if(Xe(z,j),!o&&At==="iterm2"){rt=Le(s.data,{w:E,h:M}),pt=0;return}if(!o&&At==="kitty"&&s.type==="image/png"){rt=Dn(s.data,{w:E,h:M}),pt=0;return}if(o&&At==="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 F=ot.readFileSync(R);if(F.length<=Ne){rt=Le(F,{w:E,h:M}),pt=0;return}}}catch{}if(et("ffmpeg"))try{let R=o||s.type==="image/gif",C=Fn(c,Nt(),E,M,R,g)??jn(c,E,M,R,N,g);C&&C.length>0&&(H=C,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,An);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
|
|
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")&&(Ft=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"&&(Ft=!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,W=Y?24:40;if(Y)process.stdout.rows&&(W=process.stdout.rows);else try{let o=new pe__namespace.WriteStream(ot.openSync(m,"w"));o.rows&&(W=o.rows);}catch{}let k=x?Math.max(8,Math.min(16,Math.floor((W-14)/2)*2)):vn,A=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,At=Tn(process.env),xt=process.env.OPENCRATER_FLOW==="1",Ye=process.env.OPENCRATER_MUTE==="1",st=r.apiOrigin??"https://api.opencrater.to",Ct=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",Wt=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*A))),M=Math.max(2,Math.min(A,Math.round(c/(2*u))||A)),O&&(M=Math.min(M,A));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 Blips \xB7 ${s}`:"Sponsored Blips"),f=[],g=gt??`${st}/x/${r.impressionId}`,v=r.impressionId||r.replay&>?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`:"",C=mt(c,Math.max(8,S-2-j.length)),F=" ".repeat(Math.max(1,S-C.length-j.length-1));f.push(`${X}${C}${L}${F}${R}${j}${L}${G}${v}${L}`);let Q=l?At!=="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=Wt?Ut(Wt,V):V;f.push(`${it("\u266A")} ${G}${_t}${L} ${G}${sn}${L}`);}let Xt=process.env.TERM_PROGRAM??"",en=process.env.TERM??"",qt=At!=="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-Ct.length);yt.push(Ut(r.url,Kt(`${Ct}${V} \u2192`,$t,Zt)));}else {let V=(r.cta&&r.cta.trim()!==""?r.cta.trim():"VISIT").toUpperCase();Ct.length+V.length+1+Qt.length<=S?yt.push(Kt(`${V} ${Ct}${Qt}`,$t,Zt)):yt.push(Kt(`${Ct}${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 Ae=Bt??(r.impressionId?`${st}/r/${r.impressionId}`:null),Ce=Ae&&qt?` \xB7 ${Ut(Ae,`${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(Ce)))}${Ce}${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 C=Math.max(j.length,M);for(let F=0;F<C;F++){let Q=j[F]??"",tt=" ".repeat(Math.max(0,v-jt(Q))),Xt=F<M&&R?R[F]??" ".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 C=j[R]??" ".repeat(E);g.push(`${G}\u2502${L} ${" ".repeat(v)}${C}${" ".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 C=Pe(new Uint8Array(await R.arrayBuffer()));if(C&&C.width>=4&&C.height>=2){let F=Buffer.alloc(C.width*C.height*3);for(let Q=0,tt=0;Q<C.rgba.length;Q+=4,tt+=3)F[tt]=C.rgba[Q],F[tt+1]=C.rgba[Q+1],F[tt+2]=C.rgba[Q+2];E=Math.floor(C.width/2),M=Math.floor(C.height/2),H=[ze(F,C.width,C.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")?Wn(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),C=Math.floor((z-R)/2),F=Math.floor((j-R)/2);g=`crop=${R}:${R}:${C}:${F}`,z=R,j=R,v=null;}if(Xe(z,j),!o&&At==="iterm2"){rt=Le(s.data,{w:E,h:M}),pt=0;return}if(!o&&At==="kitty"&&s.type==="image/png"){rt=Dn(s.data,{w:E,h:M}),pt=0;return}if(o&&At==="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 F=ot.readFileSync(R);if(F.length<=Ne){rt=Le(F,{w:E,h:M}),pt=0;return}}}catch{}if(et("ffmpeg"))try{let R=o||s.type==="image/gif",C=Fn(c,Nt(),E,M,R,g)??jn(c,E,M,R,N,g);C&&C.length>0&&(H=C,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,An);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
|
|
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=We__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 Blip again. This tab closes itself.</p><script>setTimeout(function(){window.close()},600);</script>`)),setTimeout(()=>K(!0),150);return}if(u.url.startsWith("/a/")){tn(),c.writeHead(200,{"content-type":"text/html; charset=utf-8"}),c.end('<!doctype html><meta charset=utf-8><title>Audio</title><body style="font-family:ui-monospace,monospace;background:#0c0c0a;color:#e9e6da;display:grid;place-items:center;height:100vh;margin:0"><p>\u266A toggled \u2014 this tab closes itself.</p><script>setTimeout(function(){window.close()},300);</script>');return}c.writeHead(200,{"content-type":"text/html; charset=utf-8"}),c.end('<!doctype html><meta charset=utf-8><title>Ad dismissed</title><body style="font-family:ui-monospace,monospace;background:#0c0c0a;color:#e9e6da;display:grid;place-items:center;height:100vh;margin:0"><p>\u2715 Ad dismissed \u2014 this tab closes itself.</p><script>setTimeout(function(){window.close()},400);</script>'),Dt(r.campaignId),!r.replay&&r.impressionId&&fetch(`${st}/x/${r.impressionId}`,{signal:AbortSignal.timeout(2e3)}).catch(()=>{}),setTimeout(()=>K(!0),150);});s.unref(),s.listen(0,"127.0.0.1",()=>{let u=s.address();u&&typeof u=="object"&&(gt=`http://127.0.0.1:${u.port}/x/${o}`,Wt=`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.
|
|
3
|
+
"version": "1.1.18",
|
|
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",
|