opencrater 1.1.41 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/cli.js +8 -8
- package/dist/hook.js +8 -7
- package/dist/index.d.mts +6 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +5 -5
- package/dist/index.mjs +5 -5
- package/dist/paint.js +8 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
# opencrater
|
|
6
6
|
|
|
7
|
-
**
|
|
7
|
+
**Blips for the terminal.** Tasteful, opt-in sponsor cards for CLI tools, MCP servers, and AI agents — the rendering engine that powers [OpenCrater](https://opencrater.to).
|
|
8
8
|
|
|
9
9
|
[](https://www.npmjs.com/package/opencrater)
|
|
10
10
|
[](https://nodejs.org)
|
package/dist/cli.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var crypto=require('crypto'),
|
|
3
|
-
`,"utf8");for(let
|
|
4
|
-
`,"utf8"),
|
|
2
|
+
'use strict';var crypto=require('crypto'),u=require('fs'),I=require('os'),f=require('path'),child_process=require('child_process'),pe=require('readline');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var u__namespace=/*#__PURE__*/_interopNamespace(u);var I__namespace=/*#__PURE__*/_interopNamespace(I);var f__namespace=/*#__PURE__*/_interopNamespace(f);var pe__namespace=/*#__PURE__*/_interopNamespace(pe);var F=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(o,n)=>(typeof require<"u"?require:o)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var X=360*60*1e3;function ke(e=process.env){return f__namespace.join(I__namespace.homedir(),".config","opencrater")}function A(e=process.env){return f__namespace.join(ke(e),"state.json")}function W(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function h(e){return typeof e=="number"&&Number.isFinite(e)}var Z=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function ee(e){for(let o=0;;o++)try{return {text:u__namespace.readFileSync(e,"utf8")}}catch(n){let t=n.code??"";if(!(t==="ENOENT"||Z.has(t)))return {locked:true};if(o>=4)return t==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(o+1));}catch{}}}function we(e){if(typeof e!="object"||e===null)return null;let o=e;return !h(o.minIntervalSeconds)||!h(o.serveTimeoutMs)||!h(o.preloadPoolSize)||typeof o.killSwitch!="boolean"?null:{minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:o.preloadPoolSize,killSwitch:o.killSwitch,displayDurationSeconds:h(o.displayDurationSeconds)?o.displayDurationSeconds:25,minSdkVersion:typeof o.minSdkVersion=="string"?o.minSdkVersion:""}}function be(e){if(!Array.isArray(e))return [];let o=[];for(let n of e){if(typeof n!="object"||n===null)continue;let t=n,i=t.blip;if(!h(t.renderBy)||typeof i!="object"||i===null||typeof i.impressionId!="string"||typeof i.clickUrl!="string"||typeof i.sponsorLabel!="string"||typeof i.creative!="object"||i.creative===null)continue;let s=i.creative;typeof s.title!="string"||typeof s.body!="string"||o.push({blip:{impressionId:i.impressionId,...typeof i.campaignId=="string"?{campaignId:i.campaignId}:{},clickUrl:i.clickUrl,sponsorLabel:i.sponsorLabel,creative:{format:"text",title:s.title,body:s.body,...typeof s.cta=="string"?{cta:s.cta}:{}}},renderBy:t.renderBy});}return o}function ve(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let o={};for(let[n,t]of Object.entries(e)){if(!Array.isArray(t))continue;let i=t.filter(s=>typeof s=="string"&&s.length<=64);o[n]=i.slice(0,64);}return o}function Se(e){if(!Array.isArray(e))return [];let o=[];for(let n of e){if(typeof n!="object"||n===null)continue;let t=n;if(!(typeof t.topic!="string"||!h(t.at))&&(o.push({topic:t.topic.slice(0,32),at:t.at}),o.length>=24))break}return o}function je(e){if(!Array.isArray(e))return [];let o=[],n=new Set;for(let t of e){if(typeof t!="object"||t===null)continue;let i=t;if(typeof i.key!="string"||typeof i.package!="string"||i.key===""||i.package==="")continue;let s=`${i.package}\0${i.key}`;if(!n.has(s)&&(n.add(s),o.push({key:i.key,package:i.package}),o.length>=32))break}return o}function xe(e){if(typeof e!="object"||e===null)return null;let o=e,n={};if(typeof o.savedEnv=="object"&&o.savedEnv!==null)for(let[t,i]of Object.entries(o.savedEnv))(typeof i=="string"||i===null)&&(n[t]=i);return {active:o.active===true,savedEnv:n}}function Ce(e){if(typeof e!="object"||e===null)return null;let o=e,n=t=>h(t)&&t>=0?t:0;return {turns:n(o.turns),lastLimitAt:n(o.lastLimitAt),lastDepletedAt:n(o.lastDepletedAt),lastBackupAt:n(o.lastBackupAt)}}function Oe(e){let o=e.attrTagsAt,n=e.attrTagsCwd;return !h(o)||Date.now()-o>X||typeof n!="string"||n.length===0||n.length>64?{}:{attrTags:Array.isArray(e.attrTags)?e.attrTags.filter(i=>typeof i=="string"&&i.length<=40).slice(0,48):[],attrTagsCwd:n,attrTagsAt:o}}function Ae(e){let o=W();if(typeof e!="object"||e===null)return o;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:o.installId,lastShownAt:h(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:we(n.cachedConfig),allowedPlacements:ve(n.allowedPlacements),sessionTopics:Se(n.sessionTopics),integrations:je(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:xe(n.computeRouting),computeCards:Ce(n.computeCards),configFetchedAt:h(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:be(n.pool),...Oe(n)}}function p(e=process.env){let o=A(e),n=ee(o);if(n.text!==void 0)try{return Ae(JSON.parse(n.text))}catch{let t=W();try{O(t,e);}catch{}return t}if(n.missing){let t=W();try{O(t,e);}catch{}return t}return W()}function O(e,o=process.env,n={}){let t=A(o),i=f__namespace.dirname(t);u__namespace.mkdirSync(i,{recursive:true});let s=ee(t),a=null;if(s.text!==void 0)try{a=JSON.parse(s.text);}catch{a=null;}if(a)typeof a.lastShownAt=="number"&&a.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:a.lastShownAt}),!n.allowClearToken&&typeof a.devToken=="string"&&e.devToken==null&&(e={...e,devToken:a.devToken}),typeof a.installId=="string"&&a.installId.length>0&&a.installId!==e.installId&&(e={...e,installId:a.installId});else if(!n.allowClearToken&&e.devToken==null&&s.text===void 0&&!s.missing)return;let d=f__namespace.join(i,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);u__namespace.writeFileSync(d,JSON.stringify(e,null,2)+`
|
|
3
|
+
`,"utf8");for(let r=0;;r++)try{u__namespace.renameSync(d,t);return}catch(c){let l=c.code??"";if(r>=4||!Z.has(l)){try{u__namespace.rmSync(d,{force:!0});}catch{}if(r>=4)return;throw c}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(r+1));}catch{}}}function S(e,o=process.env){let n={...p(o),...e};return O(n,o),n}var ne={claude_code:["SessionStart","Stop","SessionEnd","Notification","UserPromptSubmit","SubagentStart","SubagentStop","StopFailure","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionRequest","PermissionDenied","UserPromptExpansion","PreCompact","PostCompact","TaskCreated","TaskCompleted","Setup","TeammateIdle","Elicitation","ElicitationResult","ConfigChange","InstructionsLoaded","WorktreeCreate","WorktreeRemove","CwdChanged","FileChanged","MessageDisplay"],codex:["Stop","SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","PreCompact","PostCompact"],openclaw:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd","Notification","BeforeAgent","BeforeModel","AfterModel","BeforeToolSelection","BeforeTool","AfterTool","PreCompress"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var b=["claude_code","codex","gemini_cli","copilot_cli","grok_cli"];function j(e){return e.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(e)}function Re(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pe(e,o){return j(e)&&new RegExp(`--package ['"]?${Re(o)}['"]?`).test(e)}function se(e,o){return o?Pe(e,o):j(e)&&!/--package\b/.test(e)}function oe(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var te='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',ie="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function R(e,o,n,t){let i=`--placement ${o}`;return n&&(i+=` --key ${oe(n)}`),t&&(i+=` --package ${oe(t)}`),i+=` --host ${e}`,`{ if [ -f ${te} ]; then node ${te} ${i}; else npx -y -p opencrater opencrater-hook ${i}; fi; } 2>/dev/null || true`}function Ee(e,o,n){if(process.platform!=="win32")return R("grok_cli",e,o,n);let t=`--placement ${e}`;o&&(t+=` --key ${o}`),n&&(t+=` --package ${n}`),t+=" --host grok_cli";let i=`${I__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${i}") { node "${i}" ${t} } else { npx -y -p opencrater opencrater-hook ${t} } } catch {}`}function ae(e,o,n,t){let i=`--placement ${o}`;return n&&(i+=` --key '${n}'`),t&&(i+=` --package '${t}'`),i+=` --host ${e}`,`try { if (Test-Path "${ie}") { node "${ie}" ${i} } else { npx -y -p opencrater opencrater-hook ${i} } } catch {}`}function Te(e,o,n){if(process.platform!=="win32")return R("claude_code",e,o,n);let t=`--placement ${e}`;return o&&(t+=` --key ${o}`),n&&(t+=` --package ${n}`),t+=" --host claude_code",`node "${`${I__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${t}; exit 0`}function z(e,o,n,t){if(e==="grok_cli")return {type:"command",command:Ee(o,n,t),timeout:15};let s={type:"command",command:e==="claude_code"?Te(o,n,t):R(e,o,n,t)};return e==="codex"&&(s.commandWindows=ae(e,o,n,t)),s}function G(e,o){let n=I__namespace.homedir();switch(e){case "claude_code":{let t=o.CLAUDE_CONFIG_DIR;return t&&t.trim()!==""?t:f__namespace.join(n,".claude")}case "codex":{let t=o.CODEX_HOME;return t&&t.trim()!==""?t:f__namespace.join(n,".codex")}case "gemini_cli":return f__namespace.join(n,".gemini");case "copilot_cli":{let t=o.COPILOT_HOME;return t&&t.trim()!==""?t:f__namespace.join(n,".copilot")}case "grok_cli":{let t=o.GROK_HOME;return t&&t.trim()!==""?t:f__namespace.join(n,".grok")}default:return f__namespace.join(n,".opencrater-unknown")}}function N(e,o=process.env){let n=G(e,o);switch(e){case "claude_code":return f__namespace.join(n,"settings.json");case "codex":return f__namespace.join(n,"hooks.json");case "gemini_cli":return f__namespace.join(n,"settings.json");case "copilot_cli":return f__namespace.join(n,"hooks","hooks.json");case "grok_cli":return f__namespace.join(n,"hooks","opencrater.json");default:return f__namespace.join(n,"hooks.json")}}var $e={claude_code:["claude"],codex:["codex"],gemini_cli:["gemini"],copilot_cli:["copilot"],grok_cli:["grok"]};function _e(e,o){if(e.length===0)return false;let n=(o.PATH??o.Path??"").split(f__namespace.delimiter).filter(Boolean),t=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let i of n)for(let s of e)for(let a of t)try{if(u__namespace.existsSync(f__namespace.join(i,s+a)))return !0}catch{}return false}function We(e,o=process.env){try{if(u__namespace.existsSync(G(e,o)))return !0}catch{}return _e($e[e]??[],o)}function J(e=process.env){return b.filter(o=>We(o,e))}function M(e){let o;try{o=u__namespace.readFileSync(e,"utf8");}catch{return {}}let n=JSON.parse(o);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n}function K(e,o){let n=f__namespace.dirname(e);u__namespace.mkdirSync(n,{recursive:true});let t=f__namespace.join(n,`.${f__namespace.basename(e)}.${process.pid}.tmp`);u__namespace.writeFileSync(t,JSON.stringify(o,null,2)+`
|
|
4
|
+
`,"utf8"),u__namespace.renameSync(t,e);}function Ie(e,o){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&se(n.command,o))}function Ne(e,o,n,t){let i=N(e),s=M(i),a=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(t.every(r=>{let c=z(e,r,o,n);return (Array.isArray(a[r])?a[r]:[]).some(l=>Array.isArray(l.hooks)&&l.hooks.some(g=>g.command===c.command&&g.commandWindows===c.commandWindows))}))return "nochange";for(let r of t){let l=(Array.isArray(a[r])?a[r]:[]).filter(m=>!Ie(m,n)),g=e==="grok_cli"?{hooks:[z(e,r,o,n)]}:{matcher:"",hooks:[z(e,r,o,n)]};l.push(g),a[r]=l;}return s.hooks=a,K(i,s),"wrote"}var re=12;function Me(e,o){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&se(n,o))}function He(e,o,n,t){let i=N(e),s=M(i);typeof s.version!="number"&&(s.version=1);let a=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(t.every(r=>{let c=R(e,r,o,n);return (Array.isArray(a[r])?a[r]:[]).some(l=>l.bash===c&&l.timeoutSec===re)}))return "nochange";for(let r of t){let l=(Array.isArray(a[r])?a[r]:[]).filter(g=>!Me(g,n));l.push({type:"command",bash:R(e,r,o,n),powershell:ae(e,r,o,n),timeoutSec:re}),a[r]=l;}return s.hooks=a,K(i,s),"wrote"}function H(e){return [...ne[e]]}function qe(e){let o=e;for(let n of ["claude","cursor"]){if(new RegExp(`^\\s*\\[compat\\.${n}\\]`,"m").test(o))continue;let t=o.length===0?"":o.endsWith(`
|
|
5
5
|
`)?`
|
|
6
6
|
`:`
|
|
7
7
|
|
|
8
8
|
`;o+=`${t}[compat.${n}]
|
|
9
9
|
hooks = false
|
|
10
|
-
`;}return o}function
|
|
11
|
-
`),
|
|
12
|
-
\u2713 Signed in as ${n.displayName}.`),console.log(` Compute balance: ${
|
|
10
|
+
`;}return o}function Le(e){try{let o=f__namespace.join(G("grok_cli",e),"config.toml"),n="";try{n=u__namespace.readFileSync(o,"utf8");}catch{}let t=qe(n);if(t===n)return;u__namespace.mkdirSync(f__namespace.dirname(o),{recursive:!0}),u__namespace.writeFileSync(o,t,"utf8");}catch{}}function q(e,o,n){let t=H(e);return t.length===0?"nochange":(e==="grok_cli"&&Le(process.env),e==="copilot_cli"?He(e,o,n,t):Ne(e,o,n,t))}function P(e,o,n=process.env){return J(n).map(t=>{try{let i=q(t,e,o);return {host:t,status:i,events:H(t)}}catch(i){return {host:t,status:"error",events:[],error:i.message}}})}function V(e=process.env){let o=[];for(let n of b){let t;try{t=M(N(n,e));}catch{continue}let i=t.hooks;if(!(!i||typeof i!="object"))for(let[s,a]of Object.entries(i))for(let d of Array.isArray(a)?a:[]){let r=d,c=Array.isArray(r.hooks)?r.hooks.find(m=>typeof m.command=="string"&&j(m.command))?.command:void 0,l=[r.bash,r.command,r.powershell].find(m=>typeof m=="string"&&j(m)),g=c??l;g&&o.push({host:n,event:s,command:g});}}return o}function ce(e=process.env){let o=0;for(let n of b){let t=N(n,e),i;try{i=M(t);}catch{continue}let s=i.hooks;if(!s||typeof s!="object")continue;let a=s,d=false;for(let r of Object.keys(a)){let c=Array.isArray(a[r])?a[r]:[],l=c.filter(g=>{let m=g,Y=Array.isArray(m.hooks)&&m.hooks.some(C=>typeof C.command=="string"&&j(C.command))||[m.bash,m.powershell,m.command].some(C=>typeof C=="string"&&j(C));return Y&&o++,!Y});l.length!==c.length&&(d=true,l.length>0?a[r]=l:delete a[r]);}if(d)try{let r=Object.keys(i).filter(l=>l!=="version"&&l!=="hooks"),c=n==="copilot_cli"||n==="codex";Object.keys(a).length===0&&r.length===0&&c?u__namespace.rmSync(t,{force:!0}):K(t,i);}catch{}}return o}var E="1.2.0";var Be="https://api.opencrater.to";function x(e,o=process.env){let n=o.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:Be)).replace(/\/+$/,"")}function Fe(){return f__namespace.join(I__namespace.homedir(),".config","opencrater","runtime")}function De(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function L(e=Fe()){if(process.env.VITEST||process.env.OPENCRATER_DISABLE_RUNTIME_PIN)return false;try{return child_process.spawnSync("npm",De(e),{stdio:"ignore",windowsHide:!0,shell:process.platform==="win32"}).status===0}catch{return false}}function ze(){let e=process.env.OPENCRATER_WEB_ORIGIN;return e&&e.trim()!==""?e.replace(/\/$/,""):x().replace("//api.","//").replace(/\/$/,"")}function Ge(e){try{let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";child_process.spawn(o,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref();}catch{}}function Je(e){let o=pe__namespace.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>o.question(e,t=>(o.close(),n(t))))}function T(e){return `${Math.round(e/1e3).toLocaleString()} tokens`}function Ke(e){let o=e/1e3;return o>0&&o<10?`${(Math.round(o*10)/10).toFixed(1)} tokens`:`${Math.round(o).toLocaleString()} tokens`}function $(e){let o=e?.pendingMicroUsd??0;return o>0?` \xB7 +${Ke(o)} pending`:""}async function _(e,o){try{let n=new URL(`${x()}/v1/dev/me`);o&&n.searchParams.set("installId",o);let t=await fetch(n,{headers:{authorization:`Bearer ${e}`}});return t.ok?await t.json():null}catch{return null}}async function Ve(){let e=`${ze()}/dev/link`;console.log("Sign in and generate a CLI token here (we tried to open it):"),console.log(` ${e}
|
|
11
|
+
`),Ge(e);let o=(await Je("Paste your token (ocd_\u2026): ")).trim();if(!o.startsWith("ocd_"))return console.error("That doesn't look like a token (should start with ocd_)."),1;let n=await _(o,p().installId);if(!n)return console.error("Couldn't verify that token \u2014 check it and try again."),1;S({devToken:o}),console.log(`
|
|
12
|
+
\u2713 Signed in as ${n.displayName}.`),console.log(` Compute balance: ${T(n.balanceMicroUsd)}${$(n)} \xB7 tier: ${n.trustTier}`);let t=P().filter(i=>i.status!=="error").map(i=>i.host);return t.length?(console.log(` Wired into: ${t.join(", ")}`),process.stdout.write(" Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(L()?"\u2713":"skipped (hooks use npx fallback)")):console.log(" No supported AI CLIs detected yet \u2014 they'll wire automatically once you install one."),console.log(" See Blips in your sessions to earn your weekly compute."),0}async function Ye(){let e=p().devToken;if(!e)return console.error("Not signed in. Run: opencrater login"),1;let o=await _(e,p().installId);return o?(console.log(`Compute balance: ${T(o.balanceMicroUsd)}${$(o)}`),console.log(` signed in as: ${o.displayName} \xB7 tier: ${o.trustTier}`),0):(console.error("Couldn't reach OpenCrater (or your session expired \u2014 try: opencrater login)."),1)}function Xe(){return O({...p(),devToken:null},process.env,{allowClearToken:true}),console.log("Signed out of the OpenCrater compute wallet on this machine."),0}async function Qe(e){let o=p().devToken;if(!o)return console.error("Not signed in. Run: opencrater login"),1;let n=await _(o,p().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let t=`${x().replace(/\/$/,"")}/gateway`,i=f__namespace.join(f__namespace.dirname(A()),"claude-gateway.settings.json");try{u__namespace.mkdirSync(f__namespace.dirname(i),{recursive:!0}),u__namespace.writeFileSync(i,JSON.stringify({apiKeyHelper:`echo ${o}`}),{mode:384});}catch(d){return console.error(`Couldn't write gateway settings: ${d.message}`),1}n&&console.log(`Launching Claude Code on OpenCrater compute \xB7 balance ${T(n.balanceMicroUsd)}${$(n)}`);let s={...process.env,ANTHROPIC_BASE_URL:t,OPENCRATER_ON_GATEWAY:"1"};delete s.ANTHROPIC_API_KEY;let a=child_process.spawn("claude",[...e,"--settings",i],{stdio:"inherit",env:s,shell:process.platform==="win32"});return await new Promise(d=>{a.on("exit",r=>d(r??0)),a.on("error",r=>{console.error(`Couldn't launch claude: ${r.message}`),console.error("Is Claude Code installed? https://claude.com/claude-code"),d(127);});})}async function Ze(e){let o=p().devToken;if(!o)return console.error("Not signed in. Run: opencrater login"),1;let n=await _(o,p().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let t=`${x().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Codex on OpenCrater compute \xB7 balance ${T(n.balanceMicroUsd)}${$(n)}`);let i={...process.env,OPENCRATER_TOKEN:o,OPENCRATER_ON_GATEWAY:"1"},s=["-c",'model_provider="opencrater"',"-c",'model_providers.opencrater.name="OpenCrater"',"-c",`model_providers.opencrater.base_url="${t}"`,"-c",'model_providers.opencrater.wire_api="responses"',"-c",'model_providers.opencrater.env_key="OPENCRATER_TOKEN"'],a=[];for(let r=0;r<e.length;r++){let c=e[r],l=e[r+1];c==="-c"&&(l===void 0||!l.includes("="))?a.push("resume","--last"):a.push(c);}let d=child_process.spawn("codex",[...s,...a],{stdio:"inherit",env:i,shell:process.platform==="win32"});return await new Promise(r=>{d.on("exit",c=>r(c??0)),d.on("error",c=>{console.error(`Couldn't launch codex: ${c.message}`),console.error("Is Codex installed? npm i -g @openai/codex"),r(127);});})}function en(){let e=process.env.GROK_HOME;return e&&e.trim()!==""?e:f__namespace.join(I__namespace.homedir(),".grok")}function nn(e){let o=f__namespace.join(en(),"config.toml"),n="";try{n=u__namespace.readFileSync(o,"utf8");}catch{}if(/^\s*\[model\.opencrater\]/m.test(n))return;let t=n.length===0?"":n.endsWith(`
|
|
13
13
|
`)?`
|
|
14
14
|
`:`
|
|
15
15
|
|
|
@@ -18,7 +18,7 @@ model = "x-ai/grok-build-0.1"
|
|
|
18
18
|
base_url = "${e}"
|
|
19
19
|
name = "OpenCrater Compute"
|
|
20
20
|
env_key = "OPENCRATER_TOKEN"
|
|
21
|
-
`,
|
|
21
|
+
`,u__namespace.mkdirSync(f__namespace.dirname(o),{recursive:true}),u__namespace.writeFileSync(o,n,"utf8");}async function on(e){let o=p().devToken;if(!o)return console.error("Not signed in. Run: opencrater login"),1;let n=await _(o,p().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let t=`${x().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Grok on OpenCrater compute \xB7 balance ${T(n.balanceMicroUsd)}${$(n)}`);try{q("grok_cli");}catch{}try{nn(t);}catch(r){return console.error(`Couldn't configure the Grok compute model: ${r.message}`),1}let i={...process.env,OPENCRATER_TOKEN:o,OPENCRATER_ON_GATEWAY:"1"};delete i.GROK_MODELS_BASE_URL,delete i.GROK_HOME;let a=e.some(r=>r==="-m"||r==="--model"||r.startsWith("--model="))?[]:["-m","opencrater"],d=child_process.spawn("grok",[...a,...e],{stdio:"inherit",env:i,shell:process.platform==="win32"});return await new Promise(r=>{d.on("exit",c=>r(c??0)),d.on("error",c=>{console.error(`Couldn't launch grok: ${c.message}`),console.error("Is Grok installed? npm i -g @xai-official/grok"),r(127);});})}function me(e){let o=new Map,n=[];for(let t=0;t<e.length;t++){let i=e[t];if(i!==void 0)if(i.startsWith("--")){let s=i.indexOf("=");if(s!==-1)o.set(i.slice(2,s),i.slice(s+1));else {let a=e[t+1];a!==void 0&&!a.startsWith("--")?(o.set(i.slice(2),a),t++):o.set(i.slice(2),"true");}}else n.push(i);}return {flags:o,rest:n}}function ge(e,o){let n=p();n.integrations.some(t=>t.key===e&&t.package===o)||S({integrations:[...n.integrations,{key:e,package:o}].slice(-32)});}function B(e,o){let n=o||"compute hooks";if(e.length===0){console.log(`No supported AI CLIs detected yet \u2014 OpenCrater will wire ${n} automatically the moment you install one (it re-checks on the next session).`);return}console.log(`OpenCrater wired ${n} into:`);for(let t of e)if(t.status==="error")console.log(` \u2717 ${t.host}: ${t.error}`);else {let i=t.status==="nochange"?" \u2014 already set up":"";console.log(` \u2022 ${t.host} (${t.events.join(", ")})${i}`);}}function tn(){return S({optOut:true}),console.log("OpenCrater Blips are now OFF for this machine."),console.log("Re-enable any time with: npx opencrater on"),0}function rn(e){let{flags:o}=me(e),n=o.get("key"),t=o.get("package");return S({optOut:false}),n&&t?(ge(n,t),B(P(n,t),t),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(L()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):p().devToken?(B(P()),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(L()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):(console.log("OpenCrater Blips are now ON for this machine."),console.log("Earn compute: run `opencrater login` (no package needed)."),console.log("Earn cash as a publisher: `opencrater on --key <key> --package <name>`.")),console.log("Opt out any time with: npx opencrater off"),0}function sn(){let e=p(),o=e.lastShownAt>0?new Date(e.lastShownAt).toISOString():"never";console.log(`opencrater v${E}`),console.log(` state file: ${A()}`),console.log(` install id: ${e.installId}`),console.log(` opted out: ${e.optOut?"yes":"no"}`),console.log(` last shown: ${o}`),console.log(` pooled Blips: ${e.pool.length}`),console.log(` hosts found: ${J().join(", ")||"(none)"}`),console.log(` integrations: ${e.integrations.map(t=>t.package).join(", ")||"(none)"}`);let n=V();return console.log(` wired hooks: ${n.length}`),0}function an(e){let{flags:o}=me(e),n=o.get("key"),t=o.get("package");if(!n||!t)return console.error("Usage: opencrater hooks install --key <publisherKey> --package <name> [--host <host>]"),1;ge(n,t);let i=o.get("host");if(i&&i!=="true"){if(!b.includes(i))return console.error(`Unknown host "${i}". Supported: ${b.join(", ")}`),1;let s=i;try{let a=q(s,n,t);B([{host:s,status:a,events:H(s)}],t);}catch(a){return console.error(`Could not wire ${s}: ${a.message}`),1}}else B(P(n,t),t);return console.log("Remove with: npx opencrater hooks uninstall"),0}function cn(){let e=ce();return S({integrations:[]}),console.log(e>0?`Removed ${e} OpenCrater hook${e===1?"":"s"} across all hosts.`:"No OpenCrater hooks installed."),0}function ln(){let e=V();if(e.length===0)return console.log("No OpenCrater hooks installed."),0;for(let o of e)console.log(`${o.host} ${o.event}: ${o.command}`);return 0}function de(){return console.log(`opencrater v${E} \u2014 OpenCrater Blips
|
|
22
22
|
|
|
23
23
|
Usage:
|
|
24
24
|
opencrater on [--key <ock_\u2026> --package <name>]
|
|
@@ -43,4 +43,4 @@ Usage:
|
|
|
43
43
|
opencrater hooks list List installed OpenCrater hooks
|
|
44
44
|
|
|
45
45
|
Hosts: ${b.join(", ")}
|
|
46
|
-
Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function
|
|
46
|
+
Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function fn(e){let[o,...n]=e;switch(o){case "off":return tn();case "on":return rn(n);case "login":return Ve();case "balance":return Ye();case "logout":return Xe();case "claude":case "code":return Qe(n);case "codex":return Ze(n);case "grok":return on(n);case "status":return sn();case "hooks":{let[t,...i]=n;switch(t){case "install":return an(i);case "uninstall":return cn();case "list":return ln();default:return console.error("Usage: opencrater hooks <install|uninstall|list>"),1}}case "version":case "--version":case "-v":return console.log(E),0;case void 0:case "help":case "--help":case "-h":return de();default:return console.error(`Unknown command: ${o}`),de(),1}}typeof F<"u"&&typeof module<"u"&&F.main===module&&Promise.resolve().then(()=>fn(process.argv.slice(2))).then(e=>{process.exitCode=e;}).catch(e=>{console.error(`opencrater: ${e.message}`),process.exitCode=1;});exports.runCli=fn;
|
package/dist/hook.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var child_process=require('child_process'),
|
|
3
|
-
`);}catch{}}catch{}}function U(e){return typeof e=="number"&&Number.isFinite(e)}function ct(e){let t=$;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:U(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:U(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:U(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:U(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function B(e,t,n,r,o){try{let i=await fetch(`${e}${t}`,{method:"POST",headers:{"content-type":"application/json",...o??{}},body:JSON.stringify(n),signal:AbortSignal.timeout(r)});return i.ok?await i.json():(y(`POST ${t} -> HTTP ${i.status}`),null)}catch(i){return y(`POST ${t} failed:`,i),null}}function Se(e,t){let n=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:n,sdkVersion:_,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 be(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:ct(t.config),...Array.isArray(t.allowedPlacements)?{allowedPlacements:t.allowedPlacements.filter(r=>typeof r=="string")}:{}};return t.blip!==void 0&&t.blip!==null&&(n.blip=t.blip),typeof t.computeBalanceMicroUsd=="number"&&(n.computeBalanceMicroUsd=t.computeBalanceMicroUsd),typeof t.weeklyGrantMicroUsd=="number"&&(n.weeklyGrantMicroUsd=t.weeklyGrantMicroUsd),typeof t.pendingMicroUsd=="number"&&(n.pendingMicroUsd=t.pendingMicroUsd),n}async function ke(e,t){let n=await B(t.origin,"/v1/serve",Se(e,t),t.timeoutMs);return be(n)}async function we(e,t,n){let r={...Se(t,n),publisherKey:t.publisherKey??"",packageName:t.packageName??""},o=await B(n.origin,"/v1/dev/serve",r,n.timeoutMs,{authorization:`Bearer ${e}`});return be(o)}function ve(e,t,n){return B(n.origin,"/v1/dev/impression",{impressionId:t},n.timeoutMs,{authorization:`Bearer ${e}`}).then(()=>{}).catch(()=>{})}function ee(e,t){return B(t.origin,"/v1/events/impression",{impressionId:e},t.timeoutMs).then(()=>{}).catch(()=>{})}function Ce(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 Ee(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function L(e){let t=Ce(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 M(e=process.env){return m__namespace.join(T__namespace.homedir(),".config","opencrater")}function G(e=process.env){return m__namespace.join(M(e),"state.json")}function F(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function k(e){return typeof e=="number"&&Number.isFinite(e)}var Re=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function _e(e){for(let t=0;;t++)try{return {text:d__namespace.readFileSync(e,"utf8")}}catch(n){let r=n.code??"";if(!(r==="ENOENT"||Re.has(r)))return {locked:true};if(t>=4)return r==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(t+1));}catch{}}}function ut(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 pt(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 dt(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 ft(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 mt(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 gt(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 ht(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 yt(e){let t=F();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:ut(n.cachedConfig),allowedPlacements:dt(n.allowedPlacements),sessionTopics:ft(n.sessionTopics),integrations:mt(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:gt(n.computeRouting),computeCards:ht(n.computeCards),configFetchedAt:k(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:pt(n.pool)}}function te(e=process.env){let t=G(e),n=_e(t);if(n.text!==void 0)try{return yt(JSON.parse(n.text))}catch{let r=F();try{S(r,e);}catch{}return r}if(n.missing){let r=F();try{S(r,e);}catch{}return r}return F()}function S(e,t=process.env,n={}){let r=G(t),o=m__namespace.dirname(r);d__namespace.mkdirSync(o,{recursive:true});let i=_e(r),s=null;if(i.text!==void 0)try{s=JSON.parse(i.text);}catch{s=null;}if(s)typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt}),!n.allowClearToken&&typeof s.devToken=="string"&&e.devToken==null&&(e={...e,devToken:s.devToken}),typeof s.installId=="string"&&s.installId.length>0&&s.installId!==e.installId&&(e={...e,installId:s.installId});else if(!n.allowClearToken&&e.devToken==null&&i.text===void 0&&!i.missing)return;let l=m__namespace.join(o,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);d__namespace.writeFileSync(l,JSON.stringify(e,null,2)+`
|
|
4
|
-
`,"utf8");for(let a=0;;a++)try{d__namespace.renameSync(l,r);return}catch(c){let f=c.code??"";if(a>=4||!Re.has(f)){try{d__namespace.rmSync(l,{force:!0});}catch{}if(a>=4)return;throw c}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(a+1));}catch{}}}var St=300*1e3;function bt(){return m__namespace.join(M(),"blocked-ads.json")}function ne(){return m__namespace.join(M(),"recent-renders.json")}function kt(){return m__namespace.join(M(),"reported-ads.json")}function Oe(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 wt(e){try{let t=JSON.parse(d__namespace.readFileSync(bt(),"utf8"));return Oe(t&&typeof t=="object"?t:{},e)}catch{return {}}}function vt(){try{let e=JSON.parse(d__namespace.readFileSync(kt(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}function Ct(e){return e?vt()[e]!==void 0:false}function J(e,t=Date.now()){return e?wt(t)[e]!==void 0||Ct(e):false}function Ie(e){try{let t=JSON.parse(d__namespace.readFileSync(ne(),"utf8"));return Oe(t&&typeof t=="object"?t:{},e)}catch{return {}}}function K(e,t=Date.now()){if(e)try{let n=Ie(t);n[e]=t+St,d__namespace.mkdirSync(m__namespace.dirname(ne()),{recursive:!0}),d__namespace.writeFileSync(ne(),JSON.stringify(n));}catch{}}function Y(e,t=Date.now()){return e?Ie(t)[e]!==void 0:false}function Et(e,t){return e.filter(n=>n.renderBy>t)}function oe(e,t){let n=Et(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}var Tt=["claude_code","codex","gemini_cli","copilot_cli","grok_cli"];function $e(e){return e.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(e)}function Rt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _t(e,t){return $e(e)&&new RegExp(`--package ['"]?${Rt(t)}['"]?`).test(e)}function Me(e,t){return t?_t(e,t):$e(e)&&!/--package\b/.test(e)}function Ae(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var xe='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',Pe="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function D(e,t,n,r){let o=`--placement ${t}`;return n&&(o+=` --key ${Ae(n)}`),r&&(o+=` --package ${Ae(r)}`),o+=` --host ${e}`,`{ if [ -f ${xe} ]; then node ${xe} ${o}; else npx -y -p opencrater opencrater-hook ${o}; fi; } 2>/dev/null || true`}function Ot(e,t,n){if(process.platform!=="win32")return D("grok_cli",e,t,n);let r=`--placement ${e}`;t&&(r+=` --key ${t}`),n&&(r+=` --package ${n}`),r+=" --host grok_cli";let o=`${T__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${o}") { node "${o}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function De(e,t,n,r){let o=`--placement ${t}`;return n&&(o+=` --key '${n}'`),r&&(o+=` --package '${r}'`),o+=` --host ${e}`,`try { if (Test-Path "${Pe}") { node "${Pe}" ${o} } else { npx -y -p opencrater opencrater-hook ${o} } } catch {}`}function It(e,t,n){if(process.platform!=="win32")return D("claude_code",e,t,n);let r=`--placement ${e}`;return t&&(r+=` --key ${t}`),n&&(r+=` --package ${n}`),r+=" --host claude_code",`node "${`${T__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${r}; exit 0`}function re(e,t,n,r){if(e==="grok_cli")return {type:"command",command:Ot(t,n,r),timeout:15};let i={type:"command",command:e==="claude_code"?It(t,n,r):D(e,t,n,r)};return e==="codex"&&(i.commandWindows=De(e,t,n,r)),i}function ie(e,t){let n=T__namespace.homedir();switch(e){case "claude_code":{let r=t.CLAUDE_CONFIG_DIR;return r&&r.trim()!==""?r:m__namespace.join(n,".claude")}case "codex":{let r=t.CODEX_HOME;return r&&r.trim()!==""?r:m__namespace.join(n,".codex")}case "gemini_cli":return m__namespace.join(n,".gemini");case "copilot_cli":{let r=t.COPILOT_HOME;return r&&r.trim()!==""?r:m__namespace.join(n,".copilot")}case "grok_cli":{let r=t.GROK_HOME;return r&&r.trim()!==""?r:m__namespace.join(n,".grok")}default:return m__namespace.join(n,".opencrater-unknown")}}function V(e,t=process.env){let n=ie(e,t);switch(e){case "claude_code":return m__namespace.join(n,"settings.json");case "codex":return m__namespace.join(n,"hooks.json");case "gemini_cli":return m__namespace.join(n,"settings.json");case "copilot_cli":return m__namespace.join(n,"hooks","hooks.json");case "grok_cli":return m__namespace.join(n,"hooks","opencrater.json");default:return m__namespace.join(n,"hooks.json")}}var At={claude_code:["claude"],codex:["codex"],gemini_cli:["gemini"],copilot_cli:["copilot"],grok_cli:["grok"]};function xt(e,t){if(e.length===0)return false;let n=(t.PATH??t.Path??"").split(m__namespace.delimiter).filter(Boolean),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let o of n)for(let i of e)for(let s of r)try{if(d__namespace.existsSync(m__namespace.join(o,i+s)))return !0}catch{}return false}function Pt(e,t=process.env){try{if(d__namespace.existsSync(ie(e,t)))return !0}catch{}return xt(At[e]??[],t)}function se(e=process.env){return Tt.filter(t=>Pt(t,e))}function He(e){let t;try{t=d__namespace.readFileSync(e,"utf8");}catch{return {}}let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n}function je(e,t){let n=m__namespace.dirname(e);d__namespace.mkdirSync(n,{recursive:true});let r=m__namespace.join(n,`.${m__namespace.basename(e)}.${process.pid}.tmp`);d__namespace.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
5
|
-
`,"utf8")
|
|
2
|
+
'use strict';var child_process=require('child_process'),h=require('fs'),I=require('os'),y=require('path'),crypto=require('crypto');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var h__namespace=/*#__PURE__*/_interopNamespace(h);var I__namespace=/*#__PURE__*/_interopNamespace(I);var y__namespace=/*#__PURE__*/_interopNamespace(y);var M=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(o,e)=>(typeof require<"u"?require:o)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var B={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""},Te={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]},Re={claude_code:["SessionStart","Stop","SessionEnd","Notification","UserPromptSubmit","SubagentStart","SubagentStop","StopFailure","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionRequest","PermissionDenied","UserPromptExpansion","PreCompact","PostCompact","TaskCreated","TaskCompleted","Setup","TeammateIdle","Elicitation","ElicitationResult","ConfigChange","InstructionsLoaded","WorktreeCreate","WorktreeRemove","CwdChanged","FileChanged","MessageDisplay"],codex:["Stop","SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","PreCompact","PostCompact"],openclaw:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd","Notification","BeforeAgent","BeforeModel","AfterModel","BeforeToolSelection","BeforeTool","AfterTool","PreCompress"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var N="1.2.0";var yt="https://api.opencrater.to";function G(t,o=process.env){let e=o.OPENCRATER_API_ORIGIN;return ((e&&e.trim()!==""?e:yt)).replace(/\/+$/,"")}function x(...t){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...t);try{let o=M("os"),e=M("fs"),r=M("path");e.appendFileSync(r.join(o.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${t.map(n=>String(n)).join(" ")}
|
|
3
|
+
`);}catch{}}catch{}}function z(t){return typeof t=="number"&&Number.isFinite(t)}function bt(t){let o=B;if(typeof t!="object"||t===null)return {...o};let e=t;return {minIntervalSeconds:z(e.minIntervalSeconds)?e.minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:z(e.serveTimeoutMs)?e.serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:z(e.preloadPoolSize)?e.preloadPoolSize:o.preloadPoolSize,killSwitch:e.killSwitch===true,displayDurationSeconds:z(e.displayDurationSeconds)?e.displayDurationSeconds:o.displayDurationSeconds,minSdkVersion:typeof e.minSdkVersion=="string"?e.minSdkVersion:o.minSdkVersion}}async function je(t,o,e,r,n){try{let c=await fetch(`${t}${o}`,{method:"POST",headers:{"content-type":"application/json",...n??{}},body:JSON.stringify(e),signal:AbortSignal.timeout(r)});return c.ok?await c.json():(x(`POST ${o} -> HTTP ${c.status}`),null)}catch(c){return x(`POST ${o} failed:`,c),null}}function Ee(t,o){let e=t.host??"generic";return {publisherKey:t.publisherKey,packageName:t.packageName,placement:t.placement,host:e,sdkVersion:N,installId:o.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:o.topics&&o.topics.length>0?o.topics:void 0,tags:o.tags&&o.tags.length>0?o.tags:void 0}}function _e(t){if(typeof t!="object"||t===null)return null;let o=t;if(typeof o.fill!="boolean")return null;let e={fill:o.fill,fallback:o.fallback??null,config:bt(o.config),...Array.isArray(o.allowedPlacements)?{allowedPlacements:o.allowedPlacements.filter(r=>typeof r=="string")}:{}};return o.blip!==void 0&&o.blip!==null&&(e.blip=o.blip),typeof o.computeBalanceMicroUsd=="number"&&(e.computeBalanceMicroUsd=o.computeBalanceMicroUsd),typeof o.weeklyGrantMicroUsd=="number"&&(e.weeklyGrantMicroUsd=o.weeklyGrantMicroUsd),typeof o.pendingMicroUsd=="number"&&(e.pendingMicroUsd=o.pendingMicroUsd),e}async function Oe(t,o){let e=await je(o.origin,"/v1/serve",Ee(t,o),o.timeoutMs);return _e(e)}async function Ae(t,o,e){let r={...Ee(o,e),publisherKey:o.publisherKey??"",packageName:o.packageName??""},n=await je(e.origin,"/v1/dev/serve",r,e.timeoutMs,{authorization:`Bearer ${t}`});return _e(n)}var wt=48,J=360*60*1e3;function Pe(t){return crypto.createHash("sha256").update(t).digest("hex").slice(0,16)}function Ie(t){let o=new Set,e=s=>{o.size<wt&&o.add(s);},r=[];try{r=h__namespace.readdirSync(t);}catch{return []}let n=s=>r.includes(s),c=s=>{try{return h__namespace.readFileSync(y__namespace.join(t,s),"utf8")}catch{return ""}},f=s=>{try{return JSON.parse(c(s))}catch{return null}},u=f("package.json")??{},d={...u.dependencies??{},...u.devDependencies??{},...u.peerDependencies??{}},a=s=>Object.prototype.hasOwnProperty.call(d,s),p=s=>Object.keys(d).some(i=>i===s||i.startsWith(s));n("package.json")&&(e("lang:javascript"),(a("typescript")||n("tsconfig.json"))&&e("lang:typescript")),(n("deno.json")||n("deno.jsonc"))&&e("lang:typescript"),(n("tsconfig.json")||n("tsconfig.base.json"))&&e("lang:typescript"),n("jsconfig.json")&&e("lang:javascript"),(n("bun.lockb")||n("bun.lock"))&&e("lang:javascript"),r.some(s=>s.endsWith(".ts")||s.endsWith(".tsx")||s.endsWith(".mts")||s.endsWith(".cts"))&&e("lang:typescript"),r.some(s=>s.endsWith(".js")||s.endsWith(".jsx")||s.endsWith(".mjs")||s.endsWith(".cjs"))&&e("lang:javascript"),(n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile"))&&e("lang:python"),(n("setup.cfg")||n("Pipfile.lock")||n("poetry.lock")||n("uv.lock")||n("environment.yml"))&&e("lang:python"),r.some(s=>s.endsWith(".py")||s.endsWith(".pyi")||s.endsWith(".ipynb"))&&e("lang:python"),(n("go.mod")||n("go.sum")||n("go.work"))&&e("lang:go"),r.some(s=>s.endsWith(".go"))&&e("lang:go"),(n("Cargo.toml")||n("Cargo.lock"))&&e("lang:rust"),r.some(s=>s.endsWith(".rs"))&&e("lang:rust"),(n("pom.xml")||n("build.gradle"))&&e("lang:java"),r.some(s=>s.endsWith(".java"))&&e("lang:java"),(n("build.gradle.kts")||n("settings.gradle.kts"))&&e("lang:kotlin"),r.some(s=>s.endsWith(".kt")||s.endsWith(".kts"))&&e("lang:kotlin"),(n("build.sbt")||n(".scalafmt.conf"))&&e("lang:scala"),r.some(s=>s.endsWith(".scala")||s.endsWith(".sc"))&&e("lang:scala"),r.some(s=>s.endsWith(".groovy")||s.endsWith(".gradle"))&&e("lang:groovy"),(n("deps.edn")||n("project.clj")||n("shadow-cljs.edn"))&&e("lang:clojure"),r.some(s=>s.endsWith(".clj")||s.endsWith(".cljs")||s.endsWith(".cljc"))&&e("lang:clojure"),r.some(s=>s.endsWith(".csproj")||s.endsWith(".sln"))&&e("lang:csharp"),r.some(s=>s.endsWith(".fsproj"))&&e("lang:fsharp"),r.some(s=>s.endsWith(".cs"))&&e("lang:csharp"),r.some(s=>s.endsWith(".fs")||s.endsWith(".fsx")||s.endsWith(".fsi"))&&e("lang:fsharp"),r.some(s=>s.endsWith(".cpp")||s.endsWith(".cc")||s.endsWith(".cxx")||s.endsWith(".hpp")||s.endsWith(".hxx"))&&e("lang:cpp"),r.some(s=>s.endsWith(".c"))&&e("lang:c"),(n("composer.json")||n("composer.lock"))&&e("lang:php"),r.some(s=>s.endsWith(".php"))&&e("lang:php"),(n("Gemfile")||n("Gemfile.lock")||n(".ruby-version")||r.some(s=>s.endsWith(".gemspec")))&&e("lang:ruby"),r.some(s=>s.endsWith(".rb")||s==="Rakefile")&&e("lang:ruby"),(n("Package.swift")||n("Podfile")||r.some(s=>s.endsWith(".xcodeproj")||s.endsWith(".xcworkspace")))&&e("lang:swift"),r.some(s=>s.endsWith(".swift"))&&e("lang:swift"),r.some(s=>s.endsWith(".m")||s.endsWith(".mm"))&&e("lang:objective-c"),(n("pubspec.yaml")||n("pubspec.yml")||n("pubspec.lock"))&&e("lang:dart"),r.some(s=>s.endsWith(".dart"))&&e("lang:dart"),(n("mix.exs")||n("mix.lock"))&&e("lang:elixir"),r.some(s=>s.endsWith(".ex")||s.endsWith(".exs"))&&e("lang:elixir"),(n("rebar.config")||n("rebar.lock"))&&e("lang:erlang"),r.some(s=>s.endsWith(".erl")||s.endsWith(".hrl"))&&e("lang:erlang"),(n("gleam.toml")||r.some(s=>s.endsWith(".gleam")))&&e("lang:gleam"),(n("stack.yaml")||n("cabal.project")||r.some(s=>s.endsWith(".cabal")||s.endsWith(".hs")))&&e("lang:haskell"),(n("dune-project")||n("dune")||r.some(s=>s.endsWith(".ml")||s.endsWith(".mli")))&&e("lang:ocaml"),(r.some(s=>s.endsWith(".rockspec")||s.endsWith(".lua"))||n(".luarc.json"))&&e("lang:lua"),(n("cpanfile")||n("Makefile.PL")||r.some(s=>s.endsWith(".pl")||s.endsWith(".pm")))&&e("lang:perl"),(n("DESCRIPTION")||n("renv.lock")||r.some(s=>s.endsWith(".Rproj")||s.endsWith(".Rmd")||s.endsWith(".R")))&&e("lang:r"),(n("Project.toml")||n("Manifest.toml")||r.some(s=>s.endsWith(".jl")))&&e("lang:julia"),(n("build.zig")||n("build.zig.zon")||r.some(s=>s.endsWith(".zig")))&&e("lang:zig"),r.some(s=>s.endsWith(".nimble")||s.endsWith(".nim"))&&e("lang:nim"),(n("shard.yml")||n("shard.lock")||r.some(s=>s.endsWith(".cr")))&&e("lang:crystal"),(n("v.mod")||r.some(s=>s.endsWith(".vsh")))&&e("lang:vlang"),r.some(s=>s.endsWith(".hx")||s.endsWith(".hxml"))&&e("lang:haxe"),(n("foundry.toml")||n("hardhat.config.js")||n("hardhat.config.ts")||r.some(s=>s.endsWith(".sol")))&&e("lang:solidity"),r.some(s=>s.endsWith(".f")||s.endsWith(".f90")||s.endsWith(".f95"))&&e("lang:fortran"),r.some(s=>s.endsWith(".cob")||s.endsWith(".cbl"))&&e("lang:cobol"),r.some(s=>s.endsWith(".asm"))&&e("lang:assembly"),r.some(s=>s.endsWith(".sh")||s.endsWith(".bash")||s.endsWith(".zsh"))&&e("lang:shell"),r.some(s=>s.endsWith(".ps1")||s.endsWith(".psm1"))&&e("lang:powershell"),r.some(s=>s.endsWith(".sql"))&&e("lang:sql"),r.some(s=>s.endsWith(".html")||s.endsWith(".htm"))&&e("lang:html"),r.some(s=>s.endsWith(".css"))&&e("lang:css"),r.some(s=>s.endsWith(".scss")||s.endsWith(".sass"))&&e("lang:scss"),r.some(s=>s.endsWith(".graphql")||s.endsWith(".gql"))&&e("lang:graphql"),r.some(s=>s.endsWith(".proto"))&&e("lang:protobuf");{if(a("react")&&e("fw:react"),a("next")&&e("fw:nextjs"),a("vue")&&e("fw:vue"),(a("nuxt")||a("nuxt3"))&&e("fw:nuxt"),a("@angular/core")&&e("fw:angular"),a("svelte")&&e("fw:svelte"),a("@sveltejs/kit")&&e("fw:sveltekit"),(a("@remix-run/react")||a("@remix-run/node"))&&e("fw:remix"),a("astro")&&e("fw:astro"),a("gatsby")&&e("fw:gatsby"),a("solid-js")&&e("fw:solid"),(a("@solidjs/start")||a("solid-start"))&&e("fw:solidstart"),(a("@builder.io/qwik")||a("@qwik.dev/core"))&&e("fw:qwik"),a("preact")&&e("fw:preact"),(a("lit")||a("lit-element"))&&e("fw:lit"),(a("ember-source")||a("ember-cli"))&&e("fw:ember"),a("htmx.org")&&e("fw:htmx"),a("vite")&&e("fw:vite"),a("webpack")&&e("fw:webpack"),a("express")&&e("fw:express"),a("fastify")&&e("fw:fastify"),a("@nestjs/core")&&e("fw:nestjs"),a("koa")&&e("fw:koa"),a("hono")&&e("fw:hono"),(a("@hapi/hapi")||a("hapi"))&&e("fw:hapi"),a("@adonisjs/core")&&e("fw:adonis"),(a("@trpc/server")||a("@trpc/client"))&&e("fw:trpc"),a("sails")&&e("fw:sails"),a("electron")&&e("fw:electron"),a("react-native")&&e("fw:react-native"),a("expo")&&e("fw:expo"),p("@ionic/")&&e("fw:ionic"),a("@capacitor/core")&&e("fw:capacitor"),n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile")){let i=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")).toLowerCase();i.includes("fastapi")&&e("fw:fastapi"),i.includes("django")&&e("fw:django"),i.includes("flask")&&e("fw:flask"),i.includes("litestar")&&e("fw:litestar"),i.includes("starlette")&&e("fw:starlette"),i.includes("tornado")&&e("fw:tornado"),i.includes("sanic")&&e("fw:sanic"),i.includes("aiohttp")&&e("fw:aiohttp"),i.includes("pyramid")&&e("fw:pyramid"),i.includes("fasthtml")&&e("fw:fasthtml"),(i.includes("torch")||i.includes("pytorch"))&&e("fw:pytorch"),i.includes("tensorflow")&&e("fw:tensorflow"),(i.includes("jax")||i.includes("jaxlib"))&&e("fw:jax"),i.includes("keras")&&e("fw:keras"),(i.includes("scikit-learn")||i.includes("sklearn"))&&e("fw:scikit-learn"),i.includes("transformers")&&e("fw:transformers"),i.includes("langchain")&&e("fw:langchain"),(i.includes("llama-index")||i.includes("llama_index")||i.includes("llamaindex"))&&e("fw:llamaindex"),i.includes("pandas")&&e("fw:pandas"),i.includes("numpy")&&e("fw:numpy"),i.includes("streamlit")&&e("fw:streamlit"),i.includes("gradio")&&e("fw:gradio"),i.includes("fastai")&&e("fw:fastai");}if(n("go.mod")){let i=c("go.mod").toLowerCase();i.includes("gin-gonic/gin")&&e("fw:gin"),i.includes("labstack/echo")&&e("fw:echo"),i.includes("gofiber/fiber")&&e("fw:fiber"),i.includes("go-chi/chi")&&e("fw:chi"),(i.includes("gorilla/mux")||i.includes("gorilla/websocket"))&&e("fw:gorilla"),(i.includes("beego/beego")||i.includes("astaxie/beego"))&&e("fw:beego"),i.includes("gobuffalo/buffalo")&&e("fw:buffalo");}if(n("Cargo.toml")){let i=c("Cargo.toml").toLowerCase();i.includes("actix-web")&&e("fw:actix"),i.includes("axum")&&e("fw:axum"),i.includes("rocket")&&e("fw:rocket"),i.includes("warp")&&e("fw:warp"),i.includes("tonic")&&e("fw:tonic"),i.includes("leptos")&&e("fw:leptos"),i.includes("yew")&&e("fw:yew"),i.includes("tauri")&&e("fw:tauri"),i.includes("dioxus")&&e("fw:dioxus"),i.includes("bevy")&&e("fw:bevy");}if(n("pom.xml")||n("build.gradle")||n("build.gradle.kts")){let i=(c("pom.xml")+c("build.gradle")+c("build.gradle.kts")).toLowerCase();(i.includes("spring-boot")||i.includes("springframework"))&&e("fw:spring"),i.includes("quarkus")&&e("fw:quarkus"),i.includes("micronaut")&&e("fw:micronaut"),(i.includes("io.ktor")||i.includes("ktor-"))&&e("fw:ktor"),(i.includes("vertx")||i.includes("vert.x"))&&e("fw:vertx"),(i.includes("com.android")||i.includes("androidx"))&&e("fw:android"),(i.includes("androidx.compose")||i.includes("jetpack"))&&e("fw:jetpack-compose"),(i.includes("kotlin-multiplatform")||i.includes('kotlin("multiplatform")'))&&e("fw:kotlin-multiplatform");}if(n("Gemfile")){let i=c("Gemfile").toLowerCase();i.includes("rails")&&e("fw:rails"),i.includes("sinatra")&&e("fw:sinatra"),i.includes("hanami")&&e("fw:hanami");}if(n("composer.json")){let i=c("composer.json").toLowerCase();(i.includes("laravel/framework")||i.includes("laravel/laravel"))&&e("fw:laravel"),i.includes("symfony/")&&e("fw:symfony"),i.includes("drupal/")&&e("fw:drupal"),i.includes("codeigniter")&&e("fw:codeigniter"),i.includes("slim/slim")&&e("fw:slim");}(n("wp-config.php")||n("wp-load.php")||n("wp-content"))&&e("fw:wordpress"),n("pubspec.yaml")&&c("pubspec.yaml").toLowerCase().includes("flutter")&&e("fw:flutter");{let i=r.filter(b=>b.endsWith(".csproj"));if(i.length>0){let b=i.map(g=>c(g)).join(`
|
|
4
|
+
`).toLowerCase();(b.includes("microsoft.net.sdk.web")||b.includes("microsoft.aspnetcore"))&&e("fw:aspnet"),b.includes("blazor")&&e("fw:blazor"),(b.includes("microsoft.net.sdk.maui")||b.includes("usemaui"))&&e("fw:maui");}}(n("ProjectSettings")||r.includes("Assembly-CSharp.csproj"))&&e("fw:unity"),n("project.godot")&&e("fw:godot");{let i=c("Package.swift").toLowerCase();i.includes("swiftui")&&e("fw:swiftui"),i.includes("uikit")&&e("fw:uikit");}let s=i=>r.some(b=>b===i||b.startsWith(i+"."));s("next.config")&&e("fw:nextjs"),s("nuxt.config")&&e("fw:nuxt"),s("astro.config")&&e("fw:astro"),s("svelte.config")&&e("fw:svelte"),s("remix.config")&&e("fw:remix"),s("gatsby-config")&&e("fw:gatsby"),s("vite.config")&&e("fw:vite"),s("vue.config")&&e("fw:vue"),s("qwik.config")&&e("fw:qwik"),n("angular.json")&&e("fw:angular"),s("capacitor.config")&&e("fw:capacitor"),s("ionic.config")&&e("fw:ionic"),n("app.json")&&c("app.json").toLowerCase().includes('"expo"')&&e("fw:expo");}{if((a("pg")||a("postgres")||a("pg-promise")||a("@vercel/postgres"))&&e("infra:postgres"),(a("mysql")||a("mysql2"))&&e("infra:mysql"),a("mariadb")&&e("infra:mariadb"),(a("redis")||a("ioredis"))&&e("infra:redis"),(a("mongodb")||a("mongoose"))&&e("infra:mongodb"),a("mongoose")&&e("infra:mongoose"),(a("better-sqlite3")||a("sqlite3")||a("sqlite"))&&e("infra:sqlite"),a("@libsql/client")&&e("infra:libsql"),a("cassandra-driver")&&e("infra:cassandra"),(a("@elastic/elasticsearch")||a("elasticsearch"))&&e("infra:elasticsearch"),a("@opensearch-project/opensearch")&&e("infra:opensearch"),(a("@clickhouse/client")||a("clickhouse"))&&e("infra:clickhouse"),(a("duckdb")||a("@duckdb/node-api"))&&e("infra:duckdb"),a("neo4j-driver")&&e("infra:neo4j"),a("@influxdata/influxdb-client")&&e("infra:influxdb"),a("snowflake-sdk")&&e("infra:snowflake"),a("@google-cloud/bigquery")&&e("infra:bigquery"),(a("firebase-admin")||a("@google-cloud/firestore"))&&e("infra:firestore"),(a("faunadb")||a("fauna"))&&e("infra:fauna"),(a("surrealdb")||a("surrealdb.js"))&&e("infra:surrealdb"),a("@qdrant/js-client-rest")&&e("infra:qdrant"),a("@pinecone-database/pinecone")&&e("infra:pinecone"),(a("weaviate-ts-client")||a("weaviate-client"))&&e("infra:weaviate"),a("chromadb")&&e("infra:chromadb"),a("@zilliz/milvus2-sdk-node")&&e("infra:milvus"),(a("@prisma/client")||a("prisma"))&&e("infra:prisma"),a("drizzle-orm")&&e("infra:drizzle"),a("typeorm")&&e("infra:typeorm"),(a("aws-sdk")||p("@aws-sdk/"))&&e("infra:aws"),(p("@google-cloud/")||a("googleapis"))&&e("infra:gcp"),p("@azure/")&&e("infra:azure"),(p("@cloudflare/")||a("wrangler"))&&e("infra:cloudflare"),(a("@vercel/node")||a("@vercel/kv")||a("@vercel/blob"))&&e("infra:vercel"),(a("firebase")||a("firebase-admin"))&&e("infra:firebase"),a("@supabase/supabase-js")&&e("infra:supabase"),a("@neondatabase/serverless")&&e("infra:neon"),a("@planetscale/database")&&e("infra:planetscale"),p("@upstash/")&&e("infra:upstash"),a("@tursodatabase/api")&&e("infra:turso"),a("modal")&&e("infra:modal"),a("replicate")&&e("infra:replicate"),(a("kafkajs")||a("node-rdkafka"))&&e("infra:kafka"),(a("amqplib")||a("rabbitmq-client"))&&e("infra:rabbitmq"),a("nats")&&e("infra:nats"),(p("@aws-sdk/client-sqs")||a("sqs-consumer"))&&e("infra:sqs"),a("@google-cloud/pubsub")&&e("infra:pubsub"),p("@temporalio/")&&e("infra:temporal"),(a("bullmq")||a("bull"))&&e("infra:bullmq"),p("@sentry/")&&e("infra:sentry"),(p("@datadog/")||a("dd-trace"))&&e("infra:datadog"),p("@opentelemetry/")&&e("infra:opentelemetry"),a("newrelic")&&e("infra:newrelic"),(a("posthog-node")||a("posthog-js"))&&e("infra:posthog"),p("@honeycombio/")&&e("infra:honeycomb"),a("prom-client")&&e("infra:prometheus"),(a("stripe")||a("@stripe/stripe-js"))&&e("infra:stripe"),p("@paddle/")&&e("infra:paddle"),p("@clerk/")&&e("infra:clerk"),(a("auth0")||p("@auth0/"))&&e("infra:auth0"),(a("next-auth")||p("@auth/"))&&e("infra:nextauth"),a("twilio")&&e("infra:twilio"),a("@sendgrid/mail")&&e("infra:sendgrid"),a("resend")&&e("infra:resend"),a("postmark")&&e("infra:postmark"),p("@pulumi/")&&e("infra:pulumi"),n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile")){let i=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")).toLowerCase();(i.includes("psycopg")||i.includes("asyncpg"))&&e("infra:postgres"),(i.includes("pymysql")||i.includes("aiomysql")||i.includes("mysqlclient"))&&e("infra:mysql"),(i.includes("redis")||i.includes("aioredis"))&&e("infra:redis"),(i.includes("pymongo")||i.includes("motor")||i.includes("mongoengine"))&&e("infra:mongodb"),i.includes("elasticsearch")&&e("infra:elasticsearch"),i.includes("clickhouse")&&e("infra:clickhouse"),i.includes("duckdb")&&e("infra:duckdb"),i.includes("neo4j")&&e("infra:neo4j"),i.includes("snowflake")&&e("infra:snowflake"),i.includes("qdrant-client")&&e("infra:qdrant"),i.includes("pinecone")&&e("infra:pinecone"),i.includes("chromadb")&&e("infra:chromadb"),i.includes("pymilvus")&&e("infra:milvus"),i.includes("sqlalchemy")&&e("infra:sqlalchemy"),(i.includes("boto3")||i.includes("botocore"))&&e("infra:aws"),i.includes("google-cloud")&&e("infra:gcp"),i.includes("azure-")&&e("infra:azure"),i.includes("supabase")&&e("infra:supabase"),(i.includes("confluent-kafka")||i.includes("aiokafka")||i.includes("kafka-python"))&&e("infra:kafka"),(i.includes("pika")||i.includes("aio-pika"))&&e("infra:rabbitmq"),i.includes("temporalio")&&e("infra:temporal"),i.includes("sentry-sdk")&&e("infra:sentry"),(i.includes("ddtrace")||i.includes("datadog"))&&e("infra:datadog"),i.includes("opentelemetry")&&e("infra:opentelemetry"),i.includes("stripe")&&e("infra:stripe"),i.includes("twilio")&&e("infra:twilio"),i.includes("pulumi")&&e("infra:pulumi"),i.includes("ansible")&&e("infra:ansible");}if(n("go.mod")){let i=c("go.mod").toLowerCase();(i.includes("lib/pq")||i.includes("jackc/pgx"))&&e("infra:postgres"),i.includes("go-sql-driver/mysql")&&e("infra:mysql"),(i.includes("go-redis")||i.includes("redis/go-redis"))&&e("infra:redis"),i.includes("go.mongodb.org/mongo-driver")&&e("infra:mongodb"),i.includes("aws/aws-sdk-go")&&e("infra:aws"),i.includes("cloud.google.com/go")&&e("infra:gcp"),(i.includes("segmentio/kafka-go")||i.includes("sarama"))&&e("infra:kafka"),i.includes("getsentry/sentry-go")&&e("infra:sentry"),i.includes("go.opentelemetry.io")&&e("infra:opentelemetry"),i.includes("stripe/stripe-go")&&e("infra:stripe"),i.includes("hashicorp/terraform")&&e("infra:terraform"),i.includes("k8s.io/client-go")&&e("infra:kubernetes");}(n("Dockerfile")||n("docker-compose.yml")||n("docker-compose.yaml")||n("compose.yaml")||n("compose.yml")||n(".dockerignore"))&&e("infra:docker"),(n("Containerfile")||n("podman-compose.yml"))&&e("infra:podman"),r.some(i=>i.endsWith(".tf")||i===".terraform.lock.hcl")&&e("infra:terraform"),(n("Pulumi.yaml")||n("Pulumi.yml"))&&e("infra:pulumi"),(n("ansible.cfg")||n("playbook.yml")||n("playbook.yaml"))&&e("infra:ansible"),(n("kustomization.yaml")||n("kustomization.yml")||n("k8s")||n("kubernetes")||n("skaffold.yaml"))&&e("infra:kubernetes"),(n("Chart.yaml")||n("helmfile.yaml"))&&(e("infra:helm"),e("infra:kubernetes")),r.some(i=>i.endsWith(".nomad")||i.endsWith(".nomad.hcl"))&&e("infra:nomad"),(n("vercel.json")||n(".vercel"))&&e("infra:vercel"),(n("netlify.toml")||n(".netlify"))&&e("infra:netlify"),n("fly.toml")&&e("infra:fly"),(n("railway.json")||n("railway.toml"))&&e("infra:railway"),n("render.yaml")&&e("infra:render"),n("Procfile")&&e("infra:heroku"),(n("wrangler.toml")||n("wrangler.jsonc")||n("wrangler.json"))&&e("infra:cloudflare"),n("supabase")&&e("infra:supabase"),(n("firebase.json")||n(".firebaserc"))&&e("infra:firebase"),(n("serverless.yml")||n("serverless.yaml")||n("template.yaml")||n("samconfig.toml"))&&e("infra:aws"),(n("prisma")||n("schema.prisma"))&&e("infra:prisma"),(n("drizzle.config.ts")||n("drizzle.config.js"))&&e("infra:drizzle");let s=false;try{s=n(".github")&&h__namespace.existsSync(y__namespace.join(t,".github","workflows"));}catch{s=false;}s&&e("infra:github-actions"),(n(".gitlab-ci.yml")||n(".gitlab-ci.yaml"))&&e("infra:gitlab-ci"),n(".circleci")&&e("infra:circleci"),n("Jenkinsfile")&&e("infra:jenkins");{let i=(c("Dockerfile")+c("docker-compose.yml")+c("docker-compose.yaml")+c("compose.yaml")+c("compose.yml")).toLowerCase();i&&((i.includes("postgres")||i.includes("pgvector"))&&e("infra:postgres"),i.includes("timescale")&&e("infra:timescaledb"),i.includes("mysql")&&e("infra:mysql"),i.includes("mariadb")&&e("infra:mariadb"),i.includes("redis")&&e("infra:redis"),i.includes("mongo")&&e("infra:mongodb"),i.includes("cassandra")&&e("infra:cassandra"),i.includes("cockroach")&&e("infra:cockroachdb"),i.includes("clickhouse")&&e("infra:clickhouse"),i.includes("elasticsearch")&&e("infra:elasticsearch"),i.includes("neo4j")&&e("infra:neo4j"),i.includes("qdrant")&&e("infra:qdrant"),i.includes("rabbitmq")&&e("infra:rabbitmq"),(i.includes("kafka")||i.includes("redpanda"))&&e("infra:kafka"),i.includes("nats")&&e("infra:nats"),i.includes("grafana")&&e("infra:grafana"),(i.includes("prometheus")||i.includes("prom/"))&&e("infra:prometheus"));}}{let i=(...w)=>w.some(a),b=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")+c("environment.yml")).toLowerCase(),g=c("go.mod").toLowerCase(),m=c("Cargo.toml").toLowerCase(),l=w=>b.includes(w),A=w=>r.some(ae=>ae.toLowerCase().endsWith(w)),k=(...w)=>w.some(ae=>n(ae)),R=()=>Array.from(o).some(w=>w.startsWith("type:")),se=()=>Array.from(o).some(w=>w.startsWith("fw:"));(a("@modelcontextprotocol/sdk")||l("modelcontextprotocol")||l("fastmcp")||g.includes("modelcontextprotocol")||k("mcp.json",".mcp.json"))&&e("type:mcp-server"),(i("langgraph","@langchain/langgraph","crewai","autogen","@mastra/core","@openai/agents","@langchain/core")||l("langgraph")||l("crewai")||l("autogen")||l("pyautogen")||l("smolagents")||l("haystack"))&&e("type:agent-framework"),(i("ai","openai","@anthropic-ai/sdk","@google/generative-ai","@ai-sdk/openai","@ai-sdk/anthropic","langchain","@huggingface/inference","cohere-ai","ollama","groq-sdk","@mistralai/mistralai")||l("openai")||l("anthropic")||l("langchain")||l("litellm")||l("google-generativeai")||l("cohere")||l("ollama"))&&e("type:ai-app"),(A(".sol")||k("hardhat.config.js","hardhat.config.ts","foundry.toml","truffle-config.js","Anchor.toml","Move.toml")||i("hardhat","ethers","web3","@solana/web3.js","wagmi","viem","@openzeppelin/contracts"))&&e("type:smart-contract"),(k("project.godot","ProjectSettings")||A(".unity")||A(".uproject")||i("phaser","kaplay","kaboom","excalibur","playcanvas")||m.includes("bevy")||m.includes("macroquad")||m.includes("ggez")||l("pygame")||l("arcade"))&&e("type:game");{let w=f("manifest.json");(w&&Object.prototype.hasOwnProperty.call(w,"manifest_version")||i("webextension-polyfill","@types/chrome","wxt","plasmo"))&&e("type:browser-extension");}(i("react-native","expo","nativescript")||n("pubspec.yaml")||A(".xcodeproj")||k("AndroidManifest.xml"))&&e("type:mobile-app"),(i("electron","@tauri-apps/api","@tauri-apps/cli","nw")||k("tauri.conf.json","src-tauri")||m.includes("tauri")||m.includes("egui")||l("pyqt5")||l("pyqt6")||l("pyside6")||l("kivy"))&&e("type:desktop-app"),(i("discord.js","telegraf","node-telegram-bot-api","@slack/bolt","probot","grammy")||l("discord.py")||l("python-telegram-bot")||l("slack-bolt")||l("slack_bolt")||l("aiogram")||l("pyrogram"))&&e("type:bot"),(k("dbt_project.yml","dagster.yaml")||i("@dagster-io/dagster","apache-airflow")||l("airflow")||l("dagster")||l("prefect")||l("dbt-core")||l("luigi")||l("kedro")||l("pyspark")||l("apache-beam"))&&e("type:data-pipeline"),(l("torch")||l("tensorflow")||l("keras")||l("jax")||l("scikit-learn")||l("sklearn")||l("xgboost")||l("lightgbm")||l("pytorch-lightning")||l("diffusers")||l("mlflow"))&&e("type:ml-model"),(A(".ipynb")||l("jupyter")||l("jupyterlab")||l("marimo")||n("notebooks"))&&e("type:notebook"),(k("mkdocs.yml","mkdocs.yaml","mint.json","docusaurus.config.js","docusaurus.config.ts","book.toml")||i("@docusaurus/core","vitepress","vuepress","nextra","@astrojs/starlight")||l("mkdocs")||l("sphinx"))&&e("type:documentation"),(k("hugo.toml","_config.yml",".eleventy.js","eleventy.config.js","astro.config.mjs","astro.config.ts","astro.config.js")||i("astro","gatsby","@11ty/eleventy","hexo","gridsome")||l("pelican"))&&e("type:static-site"),i("@medusajs/medusa","@saleor/sdk","@shopify/hydrogen","vendure","@vendure/core","snipcart","use-shopping-cart","swell-js")&&e("type:ecommerce"),(u.bin||i("commander","yargs","oclif","@oclif/core","cac","meow","inquirer","@clack/prompts","ink")||l("click")||l("typer")||l("docopt")||g.includes("spf13/cobra")||g.includes("urfave/cli")||m.includes("clap")||m.includes("structopt"))&&e("type:cli"),(k("pnpm-workspace.yaml","turbo.json","nx.json","lerna.json","rush.json")||Array.isArray(u.workspaces)||m.includes("[workspace]")||n("go.work"))&&e("type:monorepo");let T=i("next","react","vue","@angular/core","svelte","@sveltejs/kit","solid-js","nuxt","remix","@remix-run/react","preact","qwik"),j=i("express","fastify","@nestjs/core","koa","hapi","@hapi/hapi","hono")||l("fastapi")||l("django")||l("flask")||l("starlette")||l("sanic")||g.includes("gin-gonic/gin")||g.includes("labstack/echo")||g.includes("gofiber/fiber")||m.includes("axum")||m.includes("actix-web")||(c("pom.xml")+c("build.gradle")).toLowerCase().includes("spring-boot"),ve=Array.from(o).some(w=>["infra:postgres","infra:mysql","infra:mongodb","infra:supabase","infra:neon"].includes(w)),xe=i("next-auth","@clerk/nextjs","@auth0/auth0-react","passport","lucia","@workos-inc/node")||l("django-allauth")||l("flask-login"),Ce=i("stripe","@stripe/stripe-js","@paddle/paddle-js","@lemonsqueezy/lemonsqueezy.js")||l("stripe");(!T&&!j&&(u.main||u.exports||u.module||u.types||u.publishConfig)||n("Cargo.toml")&&!m.includes("[[bin]]")&&m.includes("[lib]")||k("LICENSE","LICENSE.md","LICENSE.txt")&&!T&&!j&&!R())&&!R()&&e("type:library"),T?(ve&&(xe||Ce)&&e("type:saas"),e("type:web-app")):j&&(ve&&(xe||Ce)&&e("type:saas"),e("type:api-service")),R()||(se()?e("type:web-app"):k("Dockerfile","docker-compose.yml","compose.yaml")||r.some(w=>w.endsWith(".tf"))||k("Chart.yaml","kustomization.yaml","wrangler.toml","serverless.yml",".github")||i("@pulumi/pulumi","aws-cdk-lib","cdktf")?e("type:devops-tool"):n("package.json")&&(u.main||u.exports)&&e("type:library"));}return Array.from(o)}function Ne(t){let o={sponsorLabel:t.sponsorLabel,title:t.creative.title,body:t.creative.body,url:t.clickUrl};return t.creative.cta!==void 0&&(o.cta=t.creative.cta),o}function $e(t){return {sponsorLabel:"",title:t.title,body:t.body,url:t.url}}function K(t){let o=Ne(t),e=t.creative;switch(e.format){case "image":case "gif":return {...o,body:e.textFallback??o.body};case "video":return {...o,body:e.textFallback??o.body,cta:o.cta??"\u25B6 Watch"};case "audio":return {...o,body:e.textFallback??o.body,cta:o.cta??"\u{1F50A} Listen"};default:return o}}function H(t=process.env){return y__namespace.join(I__namespace.homedir(),".config","opencrater")}function V(t=process.env){return y__namespace.join(H(t),"state.json")}function Y(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function E(t){return typeof t=="number"&&Number.isFinite(t)}var Le=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function De(t){for(let o=0;;o++)try{return {text:h__namespace.readFileSync(t,"utf8")}}catch(e){let r=e.code??"";if(!(r==="ENOENT"||Le.has(r)))return {locked:true};if(o>=4)return r==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(o+1));}catch{}}}function vt(t){if(typeof t!="object"||t===null)return null;let o=t;return !E(o.minIntervalSeconds)||!E(o.serveTimeoutMs)||!E(o.preloadPoolSize)||typeof o.killSwitch!="boolean"?null:{minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:o.preloadPoolSize,killSwitch:o.killSwitch,displayDurationSeconds:E(o.displayDurationSeconds)?o.displayDurationSeconds:25,minSdkVersion:typeof o.minSdkVersion=="string"?o.minSdkVersion:""}}function xt(t){if(!Array.isArray(t))return [];let o=[];for(let e of t){if(typeof e!="object"||e===null)continue;let r=e,n=r.blip;if(!E(r.renderBy)||typeof n!="object"||n===null||typeof n.impressionId!="string"||typeof n.clickUrl!="string"||typeof n.sponsorLabel!="string"||typeof n.creative!="object"||n.creative===null)continue;let c=n.creative;typeof c.title!="string"||typeof c.body!="string"||o.push({blip:{impressionId:n.impressionId,...typeof n.campaignId=="string"?{campaignId:n.campaignId}:{},clickUrl:n.clickUrl,sponsorLabel:n.sponsorLabel,creative:{format:"text",title:c.title,body:c.body,...typeof c.cta=="string"?{cta:c.cta}:{}}},renderBy:r.renderBy});}return o}function Ct(t){if(typeof t!="object"||t===null||Array.isArray(t))return {};let o={};for(let[e,r]of Object.entries(t)){if(!Array.isArray(r))continue;let n=r.filter(c=>typeof c=="string"&&c.length<=64);o[e]=n.slice(0,64);}return o}function Tt(t){if(!Array.isArray(t))return [];let o=[];for(let e of t){if(typeof e!="object"||e===null)continue;let r=e;if(!(typeof r.topic!="string"||!E(r.at))&&(o.push({topic:r.topic.slice(0,32),at:r.at}),o.length>=24))break}return o}function Rt(t){if(!Array.isArray(t))return [];let o=[],e=new Set;for(let r of t){if(typeof r!="object"||r===null)continue;let n=r;if(typeof n.key!="string"||typeof n.package!="string"||n.key===""||n.package==="")continue;let c=`${n.package}\0${n.key}`;if(!e.has(c)&&(e.add(c),o.push({key:n.key,package:n.package}),o.length>=32))break}return o}function jt(t){if(typeof t!="object"||t===null)return null;let o=t,e={};if(typeof o.savedEnv=="object"&&o.savedEnv!==null)for(let[r,n]of Object.entries(o.savedEnv))(typeof n=="string"||n===null)&&(e[r]=n);return {active:o.active===true,savedEnv:e}}function Et(t){if(typeof t!="object"||t===null)return null;let o=t,e=r=>E(r)&&r>=0?r:0;return {turns:e(o.turns),lastLimitAt:e(o.lastLimitAt),lastDepletedAt:e(o.lastDepletedAt),lastBackupAt:e(o.lastBackupAt)}}function _t(t){let o=t.attrTagsAt,e=t.attrTagsCwd;return !E(o)||Date.now()-o>J||typeof e!="string"||e.length===0||e.length>64?{}:{attrTags:Array.isArray(t.attrTags)?t.attrTags.filter(n=>typeof n=="string"&&n.length<=40).slice(0,48):[],attrTagsCwd:e,attrTagsAt:o}}function Ot(t){let o=Y();if(typeof t!="object"||t===null)return o;let e=t;return {installId:typeof e.installId=="string"&&e.installId.length>0?e.installId:o.installId,lastShownAt:E(e.lastShownAt)&&e.lastShownAt>=0?e.lastShownAt:0,optOut:e.optOut===true,disclosureShown:e.disclosureShown===true,cachedConfig:vt(e.cachedConfig),allowedPlacements:Ct(e.allowedPlacements),sessionTopics:Tt(e.sessionTopics),integrations:Rt(e.integrations),devToken:typeof e.devToken=="string"?e.devToken:null,computeRouting:jt(e.computeRouting),computeCards:Et(e.computeCards),configFetchedAt:E(e.configFetchedAt)&&e.configFetchedAt>=0?e.configFetchedAt:0,pool:xt(e.pool),..._t(e)}}function le(t=process.env){let o=V(t),e=De(o);if(e.text!==void 0)try{return Ot(JSON.parse(e.text))}catch{let r=Y();try{C(r,t);}catch{}return r}if(e.missing){let r=Y();try{C(r,t);}catch{}return r}return Y()}function C(t,o=process.env,e={}){let r=V(o),n=y__namespace.dirname(r);h__namespace.mkdirSync(n,{recursive:true});let c=De(r),f=null;if(c.text!==void 0)try{f=JSON.parse(c.text);}catch{f=null;}if(f)typeof f.lastShownAt=="number"&&f.lastShownAt>t.lastShownAt&&(t={...t,lastShownAt:f.lastShownAt}),!e.allowClearToken&&typeof f.devToken=="string"&&t.devToken==null&&(t={...t,devToken:f.devToken}),typeof f.installId=="string"&&f.installId.length>0&&f.installId!==t.installId&&(t={...t,installId:f.installId});else if(!e.allowClearToken&&t.devToken==null&&c.text===void 0&&!c.missing)return;let u=y__namespace.join(n,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);h__namespace.writeFileSync(u,JSON.stringify(t,null,2)+`
|
|
5
|
+
`,"utf8");for(let d=0;;d++)try{h__namespace.renameSync(u,r);return}catch(a){let p=a.code??"";if(d>=4||!Le.has(p)){try{h__namespace.rmSync(u,{force:!0});}catch{}if(d>=4)return;throw a}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(d+1));}catch{}}}var At=300*1e3;function Pt(){return y__namespace.join(H(),"blocked-ads.json")}function fe(){return y__namespace.join(H(),"recent-renders.json")}function It(){return y__namespace.join(H(),"reported-ads.json")}function We(t,o){let e={};for(let[r,n]of Object.entries(t))typeof n=="number"&&Number.isFinite(n)&&n>o&&(e[r]=n);return e}function Nt(t){try{let o=JSON.parse(h__namespace.readFileSync(Pt(),"utf8"));return We(o&&typeof o=="object"?o:{},t)}catch{return {}}}function $t(){try{let t=JSON.parse(h__namespace.readFileSync(It(),"utf8"));return t&&typeof t=="object"?t:{}}catch{return {}}}function Mt(t){return t?$t()[t]!==void 0:false}function X(t,o=Date.now()){return t?Nt(o)[t]!==void 0||Mt(t):false}function Be(t){try{let o=JSON.parse(h__namespace.readFileSync(fe(),"utf8"));return We(o&&typeof o=="object"?o:{},t)}catch{return {}}}function Z(t,o=Date.now()){if(t)try{let e=Be(o);e[t]=o+At,h__namespace.mkdirSync(y__namespace.dirname(fe()),{recursive:!0}),h__namespace.writeFileSync(fe(),JSON.stringify(e));}catch{}}function Q(t,o=Date.now()){return t?Be(o)[t]!==void 0:false}function Lt(t,o){return t.filter(e=>e.renderBy>o)}function ue(t,o){let e=Lt(t.pool,o),r=e.shift();return {blip:r?r.blip:null,pool:e}}var Dt=["claude_code","codex","gemini_cli","copilot_cli","grok_cli"];function ze(t){return t.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(t)}function Wt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Bt(t,o){return ze(t)&&new RegExp(`--package ['"]?${Wt(o)}['"]?`).test(t)}function Ge(t,o){return o?Bt(t,o):ze(t)&&!/--package\b/.test(t)}function He(t){return /^[A-Za-z0-9@_./:-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var Ue='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',Fe="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function U(t,o,e,r){let n=`--placement ${o}`;return e&&(n+=` --key ${He(e)}`),r&&(n+=` --package ${He(r)}`),n+=` --host ${t}`,`{ if [ -f ${Ue} ]; then node ${Ue} ${n}; else npx -y -p opencrater opencrater-hook ${n}; fi; } 2>/dev/null || true`}function Ht(t,o,e){if(process.platform!=="win32")return U("grok_cli",t,o,e);let r=`--placement ${t}`;o&&(r+=` --key ${o}`),e&&(r+=` --package ${e}`),r+=" --host grok_cli";let n=`${I__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${n}") { node "${n}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function Je(t,o,e,r){let n=`--placement ${o}`;return e&&(n+=` --key '${e}'`),r&&(n+=` --package '${r}'`),n+=` --host ${t}`,`try { if (Test-Path "${Fe}") { node "${Fe}" ${n} } else { npx -y -p opencrater opencrater-hook ${n} } } catch {}`}function Ut(t,o,e){if(process.platform!=="win32")return U("claude_code",t,o,e);let r=`--placement ${t}`;return o&&(r+=` --key ${o}`),e&&(r+=` --package ${e}`),r+=" --host claude_code",`node "${`${I__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${r}; exit 0`}function de(t,o,e,r){if(t==="grok_cli")return {type:"command",command:Ht(o,e,r),timeout:15};let c={type:"command",command:t==="claude_code"?Ut(o,e,r):U(t,o,e,r)};return t==="codex"&&(c.commandWindows=Je(t,o,e,r)),c}function pe(t,o){let e=I__namespace.homedir();switch(t){case "claude_code":{let r=o.CLAUDE_CONFIG_DIR;return r&&r.trim()!==""?r:y__namespace.join(e,".claude")}case "codex":{let r=o.CODEX_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".codex")}case "gemini_cli":return y__namespace.join(e,".gemini");case "copilot_cli":{let r=o.COPILOT_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".copilot")}case "grok_cli":{let r=o.GROK_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".grok")}default:return y__namespace.join(e,".opencrater-unknown")}}function te(t,o=process.env){let e=pe(t,o);switch(t){case "claude_code":return y__namespace.join(e,"settings.json");case "codex":return y__namespace.join(e,"hooks.json");case "gemini_cli":return y__namespace.join(e,"settings.json");case "copilot_cli":return y__namespace.join(e,"hooks","hooks.json");case "grok_cli":return y__namespace.join(e,"hooks","opencrater.json");default:return y__namespace.join(e,"hooks.json")}}var Ft={claude_code:["claude"],codex:["codex"],gemini_cli:["gemini"],copilot_cli:["copilot"],grok_cli:["grok"]};function qt(t,o){if(t.length===0)return false;let e=(o.PATH??o.Path??"").split(y__namespace.delimiter).filter(Boolean),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let n of e)for(let c of t)for(let f of r)try{if(h__namespace.existsSync(y__namespace.join(n,c+f)))return !0}catch{}return false}function zt(t,o=process.env){try{if(h__namespace.existsSync(pe(t,o)))return !0}catch{}return qt(Ft[t]??[],o)}function me(t=process.env){return Dt.filter(o=>zt(o,t))}function Ke(t){let o;try{o=h__namespace.readFileSync(t,"utf8");}catch{return {}}let e=JSON.parse(o);if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t} is not a JSON object`);return e}function Ye(t,o){let e=y__namespace.dirname(t);h__namespace.mkdirSync(e,{recursive:true});let r=y__namespace.join(e,`.${y__namespace.basename(t)}.${process.pid}.tmp`);h__namespace.writeFileSync(r,JSON.stringify(o,null,2)+`
|
|
6
|
+
`,"utf8"),h__namespace.renameSync(r,t);}function Gt(t,o){return Array.isArray(t.hooks)&&t.hooks.some(e=>typeof e.command=="string"&&Ge(e.command,o))}function Jt(t,o,e,r){let n=te(t),c=Ke(n),f=c.hooks&&typeof c.hooks=="object"?c.hooks:{};if(r.every(d=>{let a=de(t,d,o,e);return (Array.isArray(f[d])?f[d]:[]).some(p=>Array.isArray(p.hooks)&&p.hooks.some(s=>s.command===a.command&&s.commandWindows===a.commandWindows))}))return "nochange";for(let d of r){let p=(Array.isArray(f[d])?f[d]:[]).filter(i=>!Gt(i,e)),s=t==="grok_cli"?{hooks:[de(t,d,o,e)]}:{matcher:"",hooks:[de(t,d,o,e)]};p.push(s),f[d]=p;}return c.hooks=f,Ye(n,c),"wrote"}var qe=12;function Kt(t,o){return [t.bash,t.powershell,t.command].some(e=>typeof e=="string"&&Ge(e,o))}function Yt(t,o,e,r){let n=te(t),c=Ke(n);typeof c.version!="number"&&(c.version=1);let f=c.hooks&&typeof c.hooks=="object"?c.hooks:{};if(r.every(d=>{let a=U(t,d,o,e);return (Array.isArray(f[d])?f[d]:[]).some(p=>p.bash===a&&p.timeoutSec===qe)}))return "nochange";for(let d of r){let p=(Array.isArray(f[d])?f[d]:[]).filter(s=>!Kt(s,e));p.push({type:"command",bash:U(t,d,o,e),powershell:Je(t,d,o,e),timeoutSec:qe}),f[d]=p;}return c.hooks=f,Ye(n,c),"wrote"}function Ve(t){return [...Re[t]]}function Vt(t){let o=t;for(let e of ["claude","cursor"]){if(new RegExp(`^\\s*\\[compat\\.${e}\\]`,"m").test(o))continue;let r=o.length===0?"":o.endsWith(`
|
|
6
7
|
`)?`
|
|
7
8
|
`:`
|
|
8
9
|
|
|
9
|
-
`;
|
|
10
|
+
`;o+=`${r}[compat.${e}]
|
|
10
11
|
hooks = false
|
|
11
|
-
`;}return t}function jt(e){try{let t=m__namespace.join(ie("grok_cli",e),"config.toml"),n="";try{n=d__namespace.readFileSync(t,"utf8");}catch{}let r=Ht(n);if(r===n)return;d__namespace.mkdirSync(m__namespace.dirname(t),{recursive:!0}),d__namespace.writeFileSync(t,r,"utf8");}catch{}}function Ut(e,t,n){let r=Ue(e);return r.length===0?"nochange":(e==="grok_cli"&&jt(process.env),e==="copilot_cli"?Dt(e,t,n,r):$t(e,t,n,r))}function ae(e,t,n=process.env){return se(n).map(r=>{try{let o=Ut(r,e,t);return {host:r,status:o,events:Ue(r)}}catch(o){return {host:r,status:"error",events:[],error:o.message}}})}function Lt(){return m__namespace.join(T__namespace.homedir(),".config","opencrater","runtime")}function Ft(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function ce(e=Lt()){child_process.spawn("npm",Ft(e),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var Ge={atLimit:false,resetAt:null};function Je(e,t=T__namespace.homedir()){try{if(e==="claude_code")return Gt(t);if(e==="codex")return Jt(t)}catch{}return Ge}function Gt(e){let t=d__namespace.readFileSync(m__namespace.join(e,".claude.json"),"utf8"),n=JSON.parse(t),r=n.hasAvailableSubscription===false||n.cachedExtraUsageDisabledReason==="out_of_credits",o=null,l=n.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof l=="string"){let a=Date.parse(l);Number.isFinite(a)&&(o=a);}return {atLimit:r,resetAt:o}}function Jt(e){return d__namespace.accessSync(m__namespace.join(e,".codex","auth.json")),Ge}function Ke(e,t){switch(e){case "gemini_cli":return t==="AfterAgent";case "copilot_cli":return t==="agentStop";default:return t==="Stop"}}var Ye=36e5,Kt=30*6e4,Yt=30*6e4,Wt=4*Ye,Vt=3,z="https://opencrater.to/dashboard";function H(e){return `${Math.round(e/1e3).toLocaleString()} tokens`}function zt(e){let t=e/1e3;return t>0&&t<10?`${(Math.round(t*10)/10).toFixed(1)} tokens`:`${Math.round(t).toLocaleString()} tokens`}function qt(e){switch(e){case "claude_code":return {name:"Claude Code",launch:"opencrater claude",resume:"opencrater claude -c"};case "codex":return {name:"Codex",launch:"opencrater codex",resume:"opencrater codex -c"};case "grok_cli":return {name:"Grok",launch:"opencrater grok",resume:"opencrater grok -c"};default:return null}}var q="opencrater claude";function Xt(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/Ye))}h`,o=new Date(e).toISOString().slice(0,10);return ` Your host limit resets in ${r} (${o}).`}function We(e){let{balanceMicroUsd:t,pendingMicroUsd:n,onGateway:r,turnEnd:o,hostName:i,host:s,cc:l,now:a}=e;if(t===null)return null;let c=qt(i),f=n&&n>0?` (+${zt(n)} pending)`:"";return t<=0?a-(l.lastDepletedAt??0)<Yt?null:{kind:"depleted",card:{sponsorLabel:"OpenCrater",title:"Compute used up",body:`Keep coding in any CLI to earn more compute, then switch back to ${c?.name??"your plan"}.`+Xt(s.resetAt,a),url:z,cta:"Earn more"}}:r?!o||(l.turns??0)%Vt!==0?null:{kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:`${H(t)} compute available${f}.`,url:z,cta:"Wallet"}}:s.atLimit?a-(l.lastLimitAt??0)<Kt?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:c?`${H(t)} of OpenCrater compute is ready. Continue this ${c.name} session now: ${c.resume}`:`${H(t)} of OpenCrater compute is ready. Run your coding agent on it: ${q}`,url:z,cta:c?c.resume:q}}:a-(l.lastBackupAt??0)>=Wt?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:c?`${H(t)} of OpenCrater compute waiting${f}. When you hit your limit: ${c.resume}`:`${H(t)} of OpenCrater compute waiting${f}. Spend it any time: ${q}`,url:z,cta:c?c.resume:q}}:null}var tn=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function ue(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function nn(e){return ue(e.OPENCRATER_DISABLE)||ue(e.TSN_DISABLE)}function on(e){return tn.some(t=>ue(e[t]))}function Z(e){return e?{...$,...e}:$}function et(e,t={}){if(nn(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(on(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 rn=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 sn(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 an(e,t=12){let n=[];for(let r of e.slice(0,2e3).split(/\s+/))if(!(!r||sn(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)||rn.has(i))&&!n.includes(i)&&(n.push(i),n.length>=t))return n}return n}function pe(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 an(t.join(" "))}function de(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 tt(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 un=false,pn=process.platform==="win32"?8e3:3200,dn=150,fe=250,fn=2800,me="claude_code";function mn(e){let t={host:"claude_code"};for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1];switch(r){case "--placement":o!==void 0&&(t.placement=o,n++);break;case "--key":o!==void 0&&(t.key=o,n++);break;case "--package":o!==void 0&&(t.package=o,n++);break;case "--host":(o==="claude_code"||o==="codex"||o==="openclaw"||o==="gemini_cli"||o==="copilot_cli"||o==="grok_cli"||o==="generic")&&(t.host=o,n++);break;}}return t}function gn(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 hn="\\\\.\\CONOUT$";function yn(e){return !e||e==="?"||e==="??"||e==="-"?null:e.startsWith("/")?e:`/dev/${e}`}function Sn(e){let t=e.match(/^\s*(\d+)\s+(\S+)/);return t?{ppid:Number(t[1]),tty:t[2]}:null}function bn(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 kn(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 wn(e){try{let t=kn(d__namespace.readFileSync(`/proc/${e}/stat`,"utf8"));if(t)return {ppid:t.ppid,ttyPath:bn(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=Sn(t);return n?{ppid:n.ppid,ttyPath:yn(n.tty)}:null}catch{return null}}function vn(){if(process.platform==="win32")return {path:hn,ownerPid:null};let e=process.pid;for(let t=0;t<12&&e>1;t++){let n=wn(e);if(!n)return null;if(n.ttyPath)return {path:n.ttyPath,ownerPid:e};e=n.ppid;}return null}function Cn(e){return e==="win32"?{detached:false,stdio:"ignore",windowsHide:false}:{detached:true,stdio:"ignore",windowsHide:false}}async function j(e,t,n,r,o){try{let i=m__namespace.join(__dirname,"paint.js"),s=Z(t.cachedConfig),l=Math.min(Math.max(s.displayDurationSeconds??25,3),120),a={...e,format:n?.format,mediaUrl:n?.mediaUrl,mediaPixelUrl:n?.mediaPixelUrl,audioUrl:n?.audioUrl,impressionId:r,campaignId:o,apiOrigin:Q(),durationMs:l*1e3,disclosure:!t.disclosureShown,host:me},c={...process.env,OPENCRATER_PAINT:JSON.stringify(a)};if(!c.OPENCRATER_TTY){let u=vn();u&&(c.OPENCRATER_TTY=u.path,u.ownerPid!==null&&(c.OPENCRATER_HOST_PID=String(u.ownerPid)));}let f=child_process.spawn(process.execPath,[i],{...Cn(process.platform),env:c});process.platform==="win32"?await new Promise(u=>{let p=!1,R=()=>{p||(p=!0,u());};f.on("exit",R),f.on("error",R),setTimeout(R,7500);}):f.unref();}catch{}return {...t,lastShownAt:Date.now(),disclosureShown:true}}function nt(e){if(process.platform!=="win32")return false;try{let t=m__namespace.join(T__namespace.homedir(),".config","opencrater","painter.lock"),n=JSON.parse(d__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 En=8e3;function ot(){let e=m__namespace.join(T__namespace.homedir(),".config","opencrater","render.lock");try{let t=d__namespace.statSync(e);if(Date.now()-t.mtimeMs<En)return !1;d__namespace.unlinkSync(e);}catch{}try{return d__namespace.mkdirSync(m__namespace.join(T__namespace.homedir(),".config","opencrater"),{recursive:!0}),d__namespace.writeFileSync(e,String(process.pid),{flag:"wx"}),!0}catch{return false}}function Tn(e,t,n,r){if(!t)return true;let o=e.allowedPlacements[`${t}:${n}`];return o?o.includes(r):t==="opencrater"?he[n].includes(r):true}var Rn=1440*60*1e3;function _n(){try{let e=m__namespace.join(T__namespace.homedir(),".config","opencrater","runtime"),t=m__namespace.join(e,"node_modules","opencrater","dist","hook.js"),n=m__namespace.join(e,".last-update");if(d__namespace.existsSync(t)){try{if(Date.now()-d__namespace.statSync(n).mtimeMs<Rn)return}catch{}try{d__namespace.writeFileSync(n,String(Date.now()));}catch{return}}else {let r=m__namespace.join(e,".installing");try{d__namespace.mkdirSync(e,{recursive:!0});let o=d__namespace.statSync(r);if(Date.now()-o.mtimeMs<600*1e3)return}catch{}d__namespace.writeFileSync(r,String(Date.now()));}ce(e);}catch{}}function rt(e,t){if(!t)return false;let n=s=>s.split(/[-+]/)[0].split(".").map(l=>parseInt(l,10)||0),r=n(e),o=n(t),i=Math.max(r.length,o.length);for(let s=0;s<i;s++){let l=r[s]??0,a=o[s]??0;if(l!==a)return l<a}return false}function it(){try{let e=m__namespace.join(T__namespace.homedir(),".config","opencrater","runtime"),t=m__namespace.join(e,".last-update"),n=m__namespace.join(e,".force-update");try{if(Date.now()-d__namespace.statSync(n).mtimeMs<600*1e3)return}catch{}d__namespace.mkdirSync(e,{recursive:!0}),d__namespace.writeFileSync(n,String(Date.now()));try{d__namespace.rmSync(t,{force:!0});}catch{}ce(e);}catch{}}function On(){try{let e=m__namespace.join(T__namespace.homedir(),".config","opencrater");d__namespace.mkdirSync(e,{recursive:!0}),d__namespace.writeFileSync(m__namespace.join(e,"activity.signal"),String(Date.now()));}catch{}}var In=1440*60*1e3;function An(){try{let e=m__namespace.join(T__namespace.homedir(),".config","opencrater"),t=m__namespace.join(e,".last-host-check"),n=m__namespace.join(e,".known-hosts"),r=se().sort(),o=[];try{let l=JSON.parse(d__namespace.readFileSync(n,"utf8"));Array.isArray(l)&&(o=l.filter(a=>typeof a=="string"));}catch{}if(!r.some(l=>!o.includes(l)))try{if(Date.now()-d__namespace.statSync(t).mtimeMs<In)return}catch{}d__namespace.mkdirSync(e,{recursive:!0});try{d__namespace.writeFileSync(t,String(Date.now()));}catch{return}let s=te();try{d__namespace.writeFileSync(n,JSON.stringify(r));}catch{}if(s.optOut)return;if(s.devToken)try{ae();}catch{}for(let l of s.integrations)try{ae(l.key,l.package);}catch{}}catch{}}async function xn(){let e=mn(process.argv.slice(2));if(me=e.host,process.env.GROK_HOOK_EVENT&&me!=="grok_cli")return;On(),_n(),An();let t=await gn(dn),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=te();y(`state=${G()} devToken=${o.devToken?"present":"MISSING"}`,`host=${e.host} placement=${r}`);let i=et({env:process.env,state:o,now:Date.now()},{skipTTY:true});if(i!==null){if(i==="frequency"){let p=pe(n);p.length>0&&S({...o,sessionTopics:de(o.sessionTopics,p,Date.now())});}y("hook suppressed:",i);return}if(o={...o,sessionTopics:de(o.sessionTopics,pe(n),Date.now())},!Tn(o,e.package,e.host,r)){S(o),y("hook gated: placement",r,"not selected for",e.package);return}let s=Z(o.cachedConfig),l=Q(),a={origin:l,timeoutMs:Math.min(s.serveTimeoutMs,fn),installId:o.installId,topics:tt(o.sessionTopics,Date.now())};if(o.devToken){let p=await we(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()},rt(_,p.config.minSdkVersion)&&it(),un);let R=e.host??"claude_code",ge=Ke(R,r),I=o.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};ge&&(I.turns+=1);let A=We({balanceMicroUsd:typeof p.computeBalanceMicroUsd=="number"?p.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof p.weeklyGrantMicroUsd=="number"?p.weeklyGrantMicroUsd:null,pendingMicroUsd:typeof p.pendingMicroUsd=="number"?p.pendingMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway")||process.env.OPENCRATER_ON_GATEWAY==="1",turnEnd:ge,hostName:R,host:Je(R),cc:I,now:Date.now()}),st=(p.config.displayDurationSeconds??25)*1e3,v=p.fill&&p.blip&&!J(p.blip.campaignId)&&!Y(p.blip.campaignId)?p.blip:null;if((A||v)&&!nt(st)&&ot())if(A){let C=Date.now();A.kind==="limit"?I.lastLimitAt=C:A.kind==="depleted"?I.lastDepletedAt=C:A.kind==="backup"&&(I.lastBackupAt=C),o=await j({...A.card,label:"OpenCrater"},o);}else v&&(K(v.campaignId),o=await j(L(v),o,v.creative,v.impressionId,v.campaignId),o.devToken&&await Promise.race([ve(o.devToken,v.impressionId,a),new Promise(C=>setTimeout(C,fe).unref?.())]));o={...o,computeCards:I};}S(o);return}let{blip:c,pool:f}=oe(o,Date.now());for(;c&&(J(c.campaignId)||Y(c.campaignId));)y("hook: pooled blip skipped \u2014 campaign inside a local cooldown"),{blip:c,pool:f}=oe({pool:f},Date.now());if((c||e.key)&&nt((s.displayDurationSeconds??25)*1e3)){S(o),y("hook: a card is already on screen \u2014 not rendering another");return}if((c||e.key)&&!ot()){S(o),y("hook: render slot already claimed by a concurrent fire");return}if(c){K(c.campaignId),o=await j(L(c),{...o,pool:f},c.creative,c.impressionId,c.campaignId),S(o),await Promise.race([ee(c.impressionId,a),new Promise(p=>setTimeout(p,fe).unref?.())]);return}if(f.length!==o.pool.length&&(o={...o,pool:f}),!e.key||!e.package){S(o),y("hook: pool empty and no --key/--package; nothing to render");return}let u=await ke({publisherKey:e.key,packageName:e.package,placement:r,host:e.host},a);if(!u){S(o);return}if(o={...o,cachedConfig:u.config,configFetchedAt:Date.now()},rt(_,u.config.minSdkVersion)&&(y(`SDK ${_} below floor ${u.config.minSdkVersion} \u2014 forcing runtime update`),it()),e.package&&u.allowedPlacements&&(o={...o,allowedPlacements:{...o.allowedPlacements,[`${e.package}:${e.host}`]:u.allowedPlacements}}),u.fill&&u.blip){if(J(u.blip.campaignId)||Y(u.blip.campaignId)){y("hook: served blip suppressed \u2014 campaign inside a local cooldown"),S(o);return}K(u.blip.campaignId),o=await j(L(u.blip),o,u.blip.creative,u.blip.impressionId,u.blip.campaignId),S(o),await Promise.race([ee(u.blip.impressionId,a),new Promise(p=>setTimeout(p,fe).unref?.())]);return}u.fallback&&(o=await j(Ee(u.fallback),o)),S(o);}if(typeof x<"u"&&typeof module<"u"&&x.main===module){let e=setTimeout(()=>process.exit(0),pn);xn().catch(t=>y(`opencrater-hook v${_} error:`,t)).finally(()=>{clearTimeout(e),process.exit(0);});}
|
|
12
|
-
exports.decodeTtyNr=
|
|
12
|
+
`;}return o}function Xt(t){try{let o=y__namespace.join(pe("grok_cli",t),"config.toml"),e="";try{e=h__namespace.readFileSync(o,"utf8");}catch{}let r=Vt(e);if(r===e)return;h__namespace.mkdirSync(y__namespace.dirname(o),{recursive:!0}),h__namespace.writeFileSync(o,r,"utf8");}catch{}}function Zt(t,o,e){let r=Ve(t);return r.length===0?"nochange":(t==="grok_cli"&&Xt(process.env),t==="copilot_cli"?Yt(t,o,e,r):Jt(t,o,e,r))}function ge(t,o,e=process.env){return me(e).map(r=>{try{let n=Zt(r,t,o);return {host:r,status:n,events:Ve(r)}}catch(n){return {host:r,status:"error",events:[],error:n.message}}})}function en(){return y__namespace.join(I__namespace.homedir(),".config","opencrater","runtime")}function tn(t){return ["install","--prefix",t,"opencrater@latest","--silent","--no-audit","--no-fund"]}function he(t=en()){child_process.spawn("npm",tn(t),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var et={atLimit:false,resetAt:null};function tt(t,o=I__namespace.homedir()){try{if(t==="claude_code")return nn(o);if(t==="codex")return on(o)}catch{}return et}function nn(t){let o=h__namespace.readFileSync(y__namespace.join(t,".claude.json"),"utf8"),e=JSON.parse(o),r=e.hasAvailableSubscription===false||e.cachedExtraUsageDisabledReason==="out_of_credits",n=null,u=e.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof u=="string"){let d=Date.parse(u);Number.isFinite(d)&&(n=d);}return {atLimit:r,resetAt:n}}function on(t){return h__namespace.accessSync(y__namespace.join(t,".codex","auth.json")),et}function nt(t,o){switch(t){case "gemini_cli":return o==="AfterAgent";case "copilot_cli":return o==="agentStop";default:return o==="Stop"}}var ot=36e5,rn=30*6e4,sn=30*6e4,an=4*ot,cn=3,ne="https://opencrater.to/dashboard";function F(t){return `${Math.round(t/1e3).toLocaleString()} tokens`}function ln(t){let o=t/1e3;return o>0&&o<10?`${(Math.round(o*10)/10).toFixed(1)} tokens`:`${Math.round(o).toLocaleString()} tokens`}function fn(t){switch(t){case "claude_code":return {name:"Claude Code",launch:"opencrater claude",resume:"opencrater claude -c"};case "codex":return {name:"Codex",launch:"opencrater codex",resume:"opencrater codex -c"};case "grok_cli":return {name:"Grok",launch:"opencrater grok",resume:"opencrater grok -c"};default:return null}}var oe="opencrater claude";function un(t,o){if(!t||t<=o)return "";let e=t-o,r=e>=864e5?`${Math.floor(e/864e5)}d`:`${Math.max(1,Math.floor(e/ot))}h`,n=new Date(t).toISOString().slice(0,10);return ` Your host limit resets in ${r} (${n}).`}function rt(t){let{balanceMicroUsd:o,pendingMicroUsd:e,onGateway:r,turnEnd:n,hostName:c,host:f,cc:u,now:d}=t;if(o===null)return null;let a=fn(c),p=e&&e>0?` (+${ln(e)} pending)`:"";return o<=0?d-(u.lastDepletedAt??0)<sn?null:{kind:"depleted",card:{sponsorLabel:"OpenCrater",title:"Compute used up",body:`Keep coding in any CLI to earn more compute, then switch back to ${a?.name??"your plan"}.`+un(f.resetAt,d),url:ne,cta:"Earn more"}}:r?!n||(u.turns??0)%cn!==0?null:{kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:`${F(o)} compute available${p}.`,url:ne,cta:"Wallet"}}:f.atLimit?d-(u.lastLimitAt??0)<rn?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:a?`${F(o)} of OpenCrater compute is ready. Continue this ${a.name} session now: ${a.resume}`:`${F(o)} of OpenCrater compute is ready. Run your coding agent on it: ${oe}`,url:ne,cta:a?a.resume:oe}}:d-(u.lastBackupAt??0)>=an?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:a?`${F(o)} of OpenCrater compute waiting${p}. When you hit your limit: ${a.resume}`:`${F(o)} of OpenCrater compute waiting${p}. Spend it any time: ${oe}`,url:ne,cta:a?a.resume:oe}}:null}var gn=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function be(t){return t!==void 0&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"}function hn(t){return be(t.OPENCRATER_DISABLE)||be(t.TSN_DISABLE)}function yn(t){return gn.some(o=>be(t[o]))}function ie(t){return t?{...B,...t}:B}function ut(t,o={}){if(hn(t.env))return "env_disabled";if(t.state.optOut)return "opt_out";let e=ie(t.state.cachedConfig);if(e.killSwitch)return "kill_switch";if(yn(t.env))return "ci";if(!o.skipTTY&&false);if(!o.skipFrequency){let r=e.minIntervalSeconds*1e3;if(t.state.lastShownAt>0&&t.now-t.state.lastShownAt<r)return "frequency"}return null}var bn=new Set(["the","and","for","but","not","you","all","any","can","this","that","with","have","will","your","from","they","what","when","where","how","why","make","fix","add","update","remove","create","delete","change","error","errors","bug","bugs","file","files","code","test","tests","run","running","build","please","help","want","need","should","would","could","into","about","then","here","there","now","new","use","using","used","work","working","works","check","show","see","look","get","set","let","lets","dont","cant","issue"]);function kn(t){if(t.includes("/")||t.includes("\\")||t.includes("@")||t.includes("://"))return true;let o=t.toLowerCase();return !!(/^(sk|pk|rk|ock|ghp|gho|ghs|xox|akia|eyj|npm|glpat)[-_]/.test(o)||t.length>=16&&/^[0-9a-f]+$/i.test(t)||t.length>=20&&/^[A-Za-z0-9+/=_-]+$/.test(t)&&/[A-Z]/.test(t)&&/[0-9]/.test(t))}function wn(t,o=12){let e=[];for(let r of t.slice(0,2e3).split(/\s+/))if(!(!r||kn(r)))for(let n of r.split(/[^A-Za-z0-9+#.]+|(?<=[a-z0-9])(?=[A-Z])/)){let c=n.replace(/^[.]+|[.]+$/g,"").toLowerCase();if(!(c.length<3||c.length>24)&&!(/^\d+$/.test(c)||bn.has(c))&&!e.includes(c)&&(e.push(c),e.length>=o))return e}return e}function ke(t){let o=[];typeof t.prompt=="string"&&o.push(t.prompt);let e=t.cwd;if(typeof e=="string"&&e.length>0){let r=e.replace(/[\\/]+$/,""),n=r.split(/[\\/]/).pop()??"",c=(process.env.HOME??process.env.USERPROFILE??"").replace(/[\\/]+$/,""),f=process.env.USER??process.env.USERNAME??"";r!==c&&n!==f&&n.length>0&&o.push(n.replace(/[-_]/g," "));}return wn(o.join(" "))}function we(t,o,e){let r=new Map;for(let{topic:n,at:c}of t)e-c<216e5&&r.set(n,c);for(let n of o)r.set(n,e);return [...r.entries()].map(([n,c])=>({topic:n,at:c})).sort((n,c)=>c.at-n.at).slice(0,24)}function dt(t,o){return t.filter(({at:e})=>o-e<216e5).sort((e,r)=>r.at-e.at).slice(0,12).map(({topic:e})=>e)}var xn=false,Cn=process.platform==="win32"?8e3:3200,Tn=150,Rn=2800,Se="claude_code";function jn(t){let o={host:"claude_code"};for(let e=0;e<t.length;e++){let r=t[e],n=t[e+1];switch(r){case "--placement":n!==void 0&&(o.placement=n,e++);break;case "--key":n!==void 0&&(o.key=n,e++);break;case "--package":n!==void 0&&(o.package=n,e++);break;case "--host":(n==="claude_code"||n==="codex"||n==="openclaw"||n==="gemini_cli"||n==="copilot_cli"||n==="grok_cli"||n==="generic")&&(o.host=n,e++);break;}}return o}function En(t){return new Promise(o=>{if(process.stdin.isTTY){o("");return}let e="",r=false,n=()=>{r||(r=true,o(e));},c=setTimeout(n,t);c.unref?.(),process.stdin.setEncoding("utf8"),process.stdin.on("data",f=>{e+=f;}),process.stdin.on("end",()=>{clearTimeout(c),n();}),process.stdin.on("error",()=>{clearTimeout(c),n();});})}var _n="\\\\.\\CONOUT$";function On(t){return !t||t==="?"||t==="??"||t==="-"?null:t.startsWith("/")?t:`/dev/${t}`}function An(t){let o=t.match(/^\s*(\d+)\s+(\S+)/);return o?{ppid:Number(o[1]),tty:o[2]}:null}function Pn(t){if(!Number.isInteger(t)||t<=0)return null;let o=t>>8&4095,e=t&255|t>>12&1048320;return o>=136&&o<=143?`/dev/pts/${(o-136)*256+e}`:o===4?e<64?`/dev/tty${e}`:`/dev/ttyS${e-64}`:null}function In(t){let o=t.lastIndexOf(")");if(o<0)return null;let e=t.slice(o+1).trim().split(/\s+/),r=Number(e[1]),n=Number(e[4]);return !Number.isInteger(r)||!Number.isInteger(n)?null:{ppid:r,ttyNr:n}}function Nn(t){try{let o=In(h__namespace.readFileSync(`/proc/${t}/stat`,"utf8"));if(o)return {ppid:o.ppid,ttyPath:Pn(o.ttyNr)}}catch{}try{let o=child_process.spawnSync("ps",["-o","ppid=,tty=","-p",String(t)],{encoding:"utf8",timeout:1500}).stdout?.trim();if(!o)return null;let e=An(o);return e?{ppid:e.ppid,ttyPath:On(e.tty)}:null}catch{return null}}function $n(){if(process.platform==="win32")return {path:_n,ownerPid:null};let t=process.pid;for(let o=0;o<12&&t>1;o++){let e=Nn(t);if(!e)return null;if(e.ttyPath)return {path:e.ttyPath,ownerPid:t};t=e.ppid;}return null}function Mn(t){return t==="win32"?{detached:false,stdio:"ignore",windowsHide:false}:{detached:true,stdio:"ignore",windowsHide:false}}async function q(t,o,e,r,n,c){try{let f=y__namespace.join(__dirname,"paint.js"),u,d;if(c&&r){let g=G();c.kind==="dev"?(u=`${g}/v1/dev/impression`,d=c.token):u=`${g}/v1/events/impression`;}let a=ie(o.cachedConfig),p=Math.min(Math.max(a.displayDurationSeconds??25,3),120),s={...t,format:e?.format,mediaUrl:e?.mediaUrl,mediaPixelUrl:e?.mediaPixelUrl,audioUrl:e?.audioUrl,impressionId:r,campaignId:n,apiOrigin:G(),reportImpressionUrl:u,reportImpressionAuth:d,durationMs:p*1e3,disclosure:!o.disclosureShown,host:Se},i={...process.env,OPENCRATER_PAINT:JSON.stringify(s)};if(!i.OPENCRATER_TTY){let g=$n();g&&(i.OPENCRATER_TTY=g.path,g.ownerPid!==null&&(i.OPENCRATER_HOST_PID=String(g.ownerPid)));}let b=child_process.spawn(process.execPath,[f],{...Mn(process.platform),env:i});process.platform==="win32"?await new Promise(g=>{let m=!1,l=()=>{m||(m=!0,g());};b.on("exit",l),b.on("error",l),setTimeout(l,7500);}):b.unref();}catch{}return {...o,lastShownAt:Date.now(),disclosureShown:true}}function pt(t){if(process.platform!=="win32")return false;try{let o=y__namespace.join(I__namespace.homedir(),".config","opencrater","painter.lock"),e=JSON.parse(h__namespace.readFileSync(o,"utf8"));if(typeof e.startedAt!="number"||Date.now()-e.startedAt>t+1500)return !1;if(typeof e.pid=="number")try{process.kill(e.pid,0);}catch(r){if(r.code==="ESRCH")return !1}return !0}catch{return false}}var Ln=8e3;function mt(){let t=y__namespace.join(I__namespace.homedir(),".config","opencrater","render.lock");try{let o=h__namespace.statSync(t);if(Date.now()-o.mtimeMs<Ln)return !1;h__namespace.unlinkSync(t);}catch{}try{return h__namespace.mkdirSync(y__namespace.join(I__namespace.homedir(),".config","opencrater"),{recursive:!0}),h__namespace.writeFileSync(t,String(process.pid),{flag:"wx"}),!0}catch{return false}}function Dn(t,o,e,r){if(!o)return true;let n=t.allowedPlacements[`${o}:${e}`];return n?n.includes(r):o==="opencrater"?Te[e].includes(r):true}var Wn=1440*60*1e3;function Bn(){try{let t=y__namespace.join(I__namespace.homedir(),".config","opencrater","runtime"),o=y__namespace.join(t,"node_modules","opencrater","dist","hook.js"),e=y__namespace.join(t,".last-update");if(h__namespace.existsSync(o)){try{if(Date.now()-h__namespace.statSync(e).mtimeMs<Wn)return}catch{}try{h__namespace.writeFileSync(e,String(Date.now()));}catch{return}}else {let r=y__namespace.join(t,".installing");try{h__namespace.mkdirSync(t,{recursive:!0});let n=h__namespace.statSync(r);if(Date.now()-n.mtimeMs<600*1e3)return}catch{}h__namespace.writeFileSync(r,String(Date.now()));}he(t);}catch{}}function gt(t,o){if(!o)return false;let e=f=>f.split(/[-+]/)[0].split(".").map(u=>parseInt(u,10)||0),r=e(t),n=e(o),c=Math.max(r.length,n.length);for(let f=0;f<c;f++){let u=r[f]??0,d=n[f]??0;if(u!==d)return u<d}return false}function ht(){try{let t=y__namespace.join(I__namespace.homedir(),".config","opencrater","runtime"),o=y__namespace.join(t,".last-update"),e=y__namespace.join(t,".force-update");try{if(Date.now()-h__namespace.statSync(e).mtimeMs<600*1e3)return}catch{}h__namespace.mkdirSync(t,{recursive:!0}),h__namespace.writeFileSync(e,String(Date.now()));try{h__namespace.rmSync(o,{force:!0});}catch{}he(t);}catch{}}function Hn(){try{let t=y__namespace.join(I__namespace.homedir(),".config","opencrater");h__namespace.mkdirSync(t,{recursive:!0}),h__namespace.writeFileSync(y__namespace.join(t,"activity.signal"),String(Date.now()));}catch{}}var Un=1440*60*1e3;function Fn(){try{let t=y__namespace.join(I__namespace.homedir(),".config","opencrater"),o=y__namespace.join(t,".last-host-check"),e=y__namespace.join(t,".known-hosts"),r=me().sort(),n=[];try{let u=JSON.parse(h__namespace.readFileSync(e,"utf8"));Array.isArray(u)&&(n=u.filter(d=>typeof d=="string"));}catch{}if(!r.some(u=>!n.includes(u)))try{if(Date.now()-h__namespace.statSync(o).mtimeMs<Un)return}catch{}h__namespace.mkdirSync(t,{recursive:!0});try{h__namespace.writeFileSync(o,String(Date.now()));}catch{return}let f=le();try{h__namespace.writeFileSync(e,JSON.stringify(r));}catch{}if(f.optOut)return;if(f.devToken)try{ge();}catch{}for(let u of f.integrations)try{ge(u.key,u.package);}catch{}}catch{}}async function qn(){let t=jn(process.argv.slice(2));if(Se=t.host,process.env.GROK_HOOK_EVENT&&Se!=="grok_cli")return;Hn(),Bn(),Fn();let o=await En(Tn),e={};if(o)try{e=JSON.parse(o);let m=e.hook_event_name;!t.placement&&typeof m=="string"&&(t.placement=m);}catch{}let r=t.placement??"SessionStart",n=le();x(`state=${V()} devToken=${n.devToken?"present":"MISSING"}`,`host=${t.host} placement=${r}`);let c=ut({env:process.env,state:n,now:Date.now()},{skipTTY:true});if(c!==null){if(c==="frequency"){let m=ke(e);m.length>0&&C({...n,sessionTopics:we(n.sessionTopics,m,Date.now())});}x("hook suppressed:",c);return}if(n={...n,sessionTopics:we(n.sessionTopics,ke(e),Date.now())},!Dn(n,t.package,t.host,r)){C(n),x("hook gated: placement",r,"not selected for",t.package);return}let f=ie(n.cachedConfig),u=G(),d=typeof e?.cwd=="string"&&e.cwd||process.cwd(),a=Pe(d),p=n.attrTags??[];if(n.attrTagsCwd!==a||!n.attrTagsAt||Date.now()-n.attrTagsAt>J){try{p=Ie(d);}catch{p=[];}n={...n,attrTags:p,attrTagsCwd:a,attrTagsAt:Date.now()};}let s={origin:u,timeoutMs:Math.min(f.serveTimeoutMs,Rn),installId:n.installId,topics:dt(n.sessionTopics,Date.now()),tags:p};if(n.devToken){let m=await Ae(n.devToken,{publisherKey:t.key??"",packageName:t.package??"",placement:r,host:t.host},s);if(m){if(n={...n,cachedConfig:m.config,configFetchedAt:Date.now()},gt(N,m.config.minSdkVersion)&&ht(),xn);let l=t.host??"claude_code",A=nt(l,r),k=n.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};A&&(k.turns+=1);let R=rt({balanceMicroUsd:typeof m.computeBalanceMicroUsd=="number"?m.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof m.weeklyGrantMicroUsd=="number"?m.weeklyGrantMicroUsd:null,pendingMicroUsd:typeof m.pendingMicroUsd=="number"?m.pendingMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway")||process.env.OPENCRATER_ON_GATEWAY==="1",turnEnd:A,hostName:l,host:tt(l),cc:k,now:Date.now()}),se=(m.config.displayDurationSeconds??25)*1e3,T=m.fill&&m.blip&&!X(m.blip.campaignId)&&!Q(m.blip.campaignId)?m.blip:null;if((R||T)&&!pt(se)&&mt())if(R){let j=Date.now();R.kind==="limit"?k.lastLimitAt=j:R.kind==="depleted"?k.lastDepletedAt=j:R.kind==="backup"&&(k.lastBackupAt=j),n=await q({...R.card,label:"OpenCrater"},n);}else T&&(Z(T.campaignId),n=await q(K(T),n,T.creative,T.impressionId,T.campaignId,n.devToken?{kind:"dev",token:n.devToken}:void 0));n={...n,computeCards:k};}C(n);return}let{blip:i,pool:b}=ue(n,Date.now());for(;i&&(X(i.campaignId)||Q(i.campaignId));)x("hook: pooled blip skipped \u2014 campaign inside a local cooldown"),{blip:i,pool:b}=ue({pool:b},Date.now());if((i||t.key)&&pt((f.displayDurationSeconds??25)*1e3)){C(n),x("hook: a card is already on screen \u2014 not rendering another");return}if((i||t.key)&&!mt()){C(n),x("hook: render slot already claimed by a concurrent fire");return}if(i){Z(i.campaignId),n=await q(K(i),{...n,pool:b},i.creative,i.impressionId,i.campaignId,{kind:"publisher"}),C(n);return}if(b.length!==n.pool.length&&(n={...n,pool:b}),!t.key||!t.package){C(n),x("hook: pool empty and no --key/--package; nothing to render");return}let g=await Oe({publisherKey:t.key,packageName:t.package,placement:r,host:t.host},s);if(!g){C(n);return}if(n={...n,cachedConfig:g.config,configFetchedAt:Date.now()},gt(N,g.config.minSdkVersion)&&(x(`SDK ${N} below floor ${g.config.minSdkVersion} \u2014 forcing runtime update`),ht()),t.package&&g.allowedPlacements&&(n={...n,allowedPlacements:{...n.allowedPlacements,[`${t.package}:${t.host}`]:g.allowedPlacements}}),g.fill&&g.blip){if(X(g.blip.campaignId)||Q(g.blip.campaignId)){x("hook: served blip suppressed \u2014 campaign inside a local cooldown"),C(n);return}Z(g.blip.campaignId),n=await q(K(g.blip),n,g.blip.creative,g.blip.impressionId,g.blip.campaignId,{kind:"publisher"}),C(n);return}g.fallback&&(n=await q($e(g.fallback),n)),C(n);}if(typeof M<"u"&&typeof module<"u"&&M.main===module){let t=setTimeout(()=>process.exit(0),Cn);qn().catch(o=>x(`opencrater-hook v${N} error:`,o)).finally(()=>{clearTimeout(t),process.exit(0);});}
|
|
13
|
+
exports.decodeTtyNr=Pn;exports.painterSpawnOptions=Mn;exports.parseArgs=jn;exports.parseProcStat=In;exports.parsePsLine=An;exports.resolveTtyPath=$n;exports.ttyNameToDevPath=On;
|
package/dist/index.d.mts
CHANGED
|
@@ -110,6 +110,11 @@ interface OpenCraterState {
|
|
|
110
110
|
topic: string;
|
|
111
111
|
at: number;
|
|
112
112
|
}[];
|
|
113
|
+
/** Cached developer-attribute tags (ns:value) detected from the project,
|
|
114
|
+
* keyed by the cwd they were scanned from, with a timestamp for TTL. */
|
|
115
|
+
attrTags?: string[];
|
|
116
|
+
attrTagsCwd?: string;
|
|
117
|
+
attrTagsAt?: number;
|
|
113
118
|
/**
|
|
114
119
|
* Publisher integrations wired on this machine: each is the (key, package)
|
|
115
120
|
* a `opencrater on --key … --package …` ran with. The auto-integrator
|
|
@@ -227,7 +232,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
|
|
|
227
232
|
|
|
228
233
|
/** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
|
|
229
234
|
* AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
|
|
230
|
-
declare const SDK_VERSION = "1.
|
|
235
|
+
declare const SDK_VERSION = "1.2.0";
|
|
231
236
|
|
|
232
237
|
/** Public API. Every method is fail-silent: it never throws. */
|
|
233
238
|
declare const sponsor: {
|
package/dist/index.d.ts
CHANGED
|
@@ -110,6 +110,11 @@ interface OpenCraterState {
|
|
|
110
110
|
topic: string;
|
|
111
111
|
at: number;
|
|
112
112
|
}[];
|
|
113
|
+
/** Cached developer-attribute tags (ns:value) detected from the project,
|
|
114
|
+
* keyed by the cwd they were scanned from, with a timestamp for TTL. */
|
|
115
|
+
attrTags?: string[];
|
|
116
|
+
attrTagsCwd?: string;
|
|
117
|
+
attrTagsAt?: number;
|
|
113
118
|
/**
|
|
114
119
|
* Publisher integrations wired on this machine: each is the (key, package)
|
|
115
120
|
* a `opencrater on --key … --package …` ran with. The auto-integrator
|
|
@@ -227,7 +232,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
|
|
|
227
232
|
|
|
228
233
|
/** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
|
|
229
234
|
* AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
|
|
230
|
-
declare const SDK_VERSION = "1.
|
|
235
|
+
declare const SDK_VERSION = "1.2.0";
|
|
231
236
|
|
|
232
237
|
/** Public API. Every method is fail-silent: it never throws. */
|
|
233
238
|
declare const sponsor: {
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
'use strict';var crypto=require('crypto'),
|
|
2
|
-
`);}catch{}}catch{}}function
|
|
1
|
+
'use strict';var crypto=require('crypto'),m=require('fs'),ie=require('os'),S=require('path');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var m__namespace=/*#__PURE__*/_interopNamespace(m);var ie__namespace=/*#__PURE__*/_interopNamespace(ie);var S__namespace=/*#__PURE__*/_interopNamespace(S);var q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var le=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var N="1.2.0";var ce="https://api.opencrater.to";function K(e,n=process.env){let t=n.OPENCRATER_API_ORIGIN;return (e??(t&&t.trim()!==""?t:ce)).replace(/\/+$/,"")}function c(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let n=q("os"),t=q("fs"),o=q("path");t.appendFileSync(o.join(n.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(i=>String(i)).join(" ")}
|
|
2
|
+
`);}catch{}}catch{}}function R(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let n=w;if(typeof e!="object"||e===null)return {...n};let t=e;return {minIntervalSeconds:R(t.minIntervalSeconds)?t.minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:R(t.serveTimeoutMs)?t.serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:R(t.preloadPoolSize)?t.preloadPoolSize:n.preloadPoolSize,killSwitch:t.killSwitch===true,displayDurationSeconds:R(t.displayDurationSeconds)?t.displayDurationSeconds:n.displayDurationSeconds,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:n.minSdkVersion}}async function D(e,n,t,o,i){try{let r=await fetch(`${e}${n}`,{method:"POST",headers:{"content-type":"application/json",...i??{}},body:JSON.stringify(t),signal:AbortSignal.timeout(o)});return r.ok?await r.json():(c(`POST ${n} -> HTTP ${r.status}`),null)}catch(r){return c(`POST ${n} failed:`,r),null}}function J(e,n){let t=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:t,sdkVersion:N,installId:n.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:n.topics&&n.topics.length>0?n.topics:void 0,tags:n.tags&&n.tags.length>0?n.tags:void 0}}function fe(e){if(typeof e!="object"||e===null)return null;let n=e;if(typeof n.fill!="boolean")return null;let t={fill:n.fill,fallback:n.fallback??null,config:V(n.config),...Array.isArray(n.allowedPlacements)?{allowedPlacements:n.allowedPlacements.filter(o=>typeof o=="string")}:{}};return n.blip!==void 0&&n.blip!==null&&(t.blip=n.blip),typeof n.computeBalanceMicroUsd=="number"&&(t.computeBalanceMicroUsd=n.computeBalanceMicroUsd),typeof n.weeklyGrantMicroUsd=="number"&&(t.weeklyGrantMicroUsd=n.weeklyGrantMicroUsd),typeof n.pendingMicroUsd=="number"&&(t.pendingMicroUsd=n.pendingMicroUsd),t}async function F(e,n){let t=await D(n.origin,"/v1/serve",J(e,n),n.timeoutMs);return fe(t)}async function X(e,n,t){let o=await D(t.origin,"/v1/serve/batch",{...J(e,t),count:n},t.timeoutMs);if(typeof o!="object"||o===null)return null;let i=o;return Array.isArray(i.blips)?{blips:i.blips,fallback:i.fallback??null,config:V(i.config),...Array.isArray(i.allowedPlacements)?{allowedPlacements:i.allowedPlacements.filter(r=>typeof r=="string")}:{}}:null}function $(e,n){return D(n.origin,"/v1/events/impression",{impressionId:e},n.timeoutMs).then(()=>{}).catch(()=>{})}var ue=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},de=60,pe=24,me="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function ge(e){return e.replace(ue,"").length}function y(e,n){return n<=0?"":e.length<=n?e:n===1?"\u2026":e.slice(0,n-1).trimEnd()+"\u2026"}function he(e,n,t){let o=e.split(/\s+/).filter(l=>l.length>0),i=[],r="";for(let l of o){let u=r===""?l:`${r} ${l}`;if(u.length<=n)r=u;else if(r!==""&&i.push(r),r=l.length>n?y(l,n):l,i.length>=t)break}r!==""&&i.length<t&&i.push(r),i.length>t&&(i.length=t);let s=i.join(" "),a=i.length-1,f=i[a];return f!==void 0&&s.length<o.join(" ").length&&(i[a]=y(`${f}\u2026`,n)),i}function I(e=process.env,n=!!process.stdout.isTTY){if(!n)return false;if(e.FORCE_HYPERLINK!==void 0&&e.FORCE_HYPERLINK!=="0")return true;let t=e.TERM_PROGRAM??"";return !!(["iTerm.app","WezTerm","ghostty","Hyper","vscode","Tabby"].includes(t)||e.KITTY_WINDOW_ID||e.WT_SESSION||Number(e.VTE_VERSION??"0")>=5e3)}function P(e=process.env,n=!!process.stdout.isTTY){return !(e.NO_COLOR!==void 0&&e.NO_COLOR!==""||!n||(e.TERM??"")==="dumb")}function ye(e,n){return `\x1B]8;;${e}\x07${n}\x1B]8;;\x07`}function E(e){let n={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(n.cta=e.creative.cta),n}function Z(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function h(e,n={}){let t=n.width??process.stdout.columns??80,i=Math.max(pe,Math.min(t,de))-4,r=n.color??P(),s=n.hyperlinks??I(),a=(g,M)=>r?`${M}${g}${k.reset}`:g,f=e.label?y(e.label,i):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,i):"Sponsored Blips",l=[];l.push(a(f,k.dim)),e.title!==e.sponsorLabel&&l.push(a(y(e.title,i),k.bold));for(let g of he(e.body,i,2))l.push(g);let u="\u2192 ";if(s){let g=y(e.cta??e.url,i-u.length);l.push(u+a(ye(e.url,g),k.dim));}else e.cta&&l.push(y(e.cta,i)),l.push(u+a(y(e.url,i-u.length),k.dim));let T=`\u256D${"\u2500".repeat(i+2)}\u256E`,j=`\u2570${"\u2500".repeat(i+2)}\u256F`,L=l.map(g=>{let M=" ".repeat(Math.max(0,i-ge(g)));return `\u2502 ${g}${M} \u2502`}),b=[];return n.disclosure&&b.push(a(me,k.dim)),b.push(T,...L,j),b.join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`}function
|
|
5
|
-
`+
|
|
6
|
-
`,"utf8");for(let
|
|
4
|
+
`}function Q(e){return e!==void 0&&e!==""}function z(e=process.env,n=!!process.stdout.isTTY){if(!n)return "none";let t=e.TERM??"";if(Q(e.TMUX)||t.startsWith("tmux")||t.startsWith("screen"))return "none";let o=e.TERM_PROGRAM??"";return o==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||o==="WezTerm"?"iterm2":t==="xterm-kitty"||Q(e.KITTY_WINDOW_ID)?"kitty":"none"}var v="\x1B",be="\x07",we=2e3,ke=2*1024*1024,Se=new Set(["image/png","image/jpeg","image/gif","image/webp"]),O=4096;async function ve(e,n=fetch,t={}){let o=t.timeoutMs??we,i=t.maxBytes??ke;try{let r=await n(e,{signal:AbortSignal.timeout(o)});if(!r.ok)return c(`media: HTTP ${r.status} for ${e}`),null;let s=(r.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!Se.has(s))return c(`media: disallowed content-type "${s}" for ${e}`),null;let a=Number(r.headers.get("content-length")??"0");if(Number.isFinite(a)&&a>i)return c(`media: content-length ${a} exceeds ${i} for ${e}`),null;let f=r.body;if(f&&typeof f.getReader=="function"){let u=f.getReader(),T=[],j=0;for(;;){let{done:L,value:b}=await u.read();if(L)break;if(b!==void 0){if(j+=b.byteLength,j>i)return await u.cancel().catch(()=>{}),c(`media: stream exceeded ${i} bytes for ${e}`),null;T.push(b);}}return Buffer.concat(T)}let l=Buffer.from(await r.arrayBuffer());return l.byteLength>i?(c(`media: body ${l.byteLength} bytes exceeds ${i} for ${e}`),null):l}catch(r){return c(`media: fetch failed for ${e}:`,r),null}}function xe(e){let n=e.toString("base64");return `${v}]1337;File=inline=1;size=${e.byteLength};width=auto:${n}${be}`}function Ce(e){let n=e.toString("base64");if(n.length<=O)return `${v}_Gf=100,a=T;${n}${v}\\`;let t=[];for(let o=0;o<n.length;o+=O){let i=n.slice(o,o+O),s=`m=${o+O>=n.length?0:1}`,a=o===0?`f=100,a=T,${s}`:s;t.push(`${v}_G${a};${i}${v}\\`);}return t.join("")}function A(e){let n=E(e),t=e.creative;switch(t.format){case "image":case "gif":return {...n,body:t.textFallback??n.body};case "video":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u25B6 Watch"};case "audio":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u{1F50A} Listen"};default:return n}}async function U(e,n={}){try{let t=e.creative;if(t.format!=="image"&&t.format!=="gif")return h(A(e),n);let o=n.protocol??z();if(o==="none"||t.mediaUrl===void 0||t.mediaUrl==="")return h(A(e),n);let i={};n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs),n.maxBytes!==void 0&&(i.maxBytes=n.maxBytes);let r=await ve(t.mediaUrl,n.fetchImpl??fetch,i);return r===null||r.byteLength===0?h(A(e),n):(o==="kitty"?Ce(r):xe(r))+`
|
|
5
|
+
`+h(E(e),n)}catch(t){return c("media: render failed, falling back to text:",t),h(E(e),n)}}function Te(e,n){return e.filter(t=>t.renderBy>n)}function ee(e,n,t=18e5){return e.filter(o=>o&&typeof o.impressionId=="string"&&typeof o.clickUrl=="string"&&o.creative&&typeof o.creative.title=="string").map(o=>({blip:o,renderBy:n+t}))}function ne(e,n){let t=Te(e.pool,n),o=t.shift();return {blip:o?o.blip:null,pool:t}}var te=360*60*1e3;function Ie(e=process.env){return S__namespace.join(ie__namespace.homedir(),".config","opencrater")}function oe(e=process.env){return S__namespace.join(Ie(e),"state.json")}function W(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function d(e){return typeof e=="number"&&Number.isFinite(e)}var re=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function se(e){for(let n=0;;n++)try{return {text:m__namespace.readFileSync(e,"utf8")}}catch(t){let o=t.code??"";if(!(o==="ENOENT"||re.has(o)))return {locked:true};if(n>=4)return o==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(n+1));}catch{}}}function Pe(e){if(typeof e!="object"||e===null)return null;let n=e;return !d(n.minIntervalSeconds)||!d(n.serveTimeoutMs)||!d(n.preloadPoolSize)||typeof n.killSwitch!="boolean"?null:{minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:n.preloadPoolSize,killSwitch:n.killSwitch,displayDurationSeconds:d(n.displayDurationSeconds)?n.displayDurationSeconds:25,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:""}}function Ee(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t,i=o.blip;if(!d(o.renderBy)||typeof i!="object"||i===null||typeof i.impressionId!="string"||typeof i.clickUrl!="string"||typeof i.sponsorLabel!="string"||typeof i.creative!="object"||i.creative===null)continue;let r=i.creative;typeof r.title!="string"||typeof r.body!="string"||n.push({blip:{impressionId:i.impressionId,...typeof i.campaignId=="string"?{campaignId:i.campaignId}:{},clickUrl:i.clickUrl,sponsorLabel:i.sponsorLabel,creative:{format:"text",title:r.title,body:r.body,...typeof r.cta=="string"?{cta:r.cta}:{}}},renderBy:o.renderBy});}return n}function Oe(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let n={};for(let[t,o]of Object.entries(e)){if(!Array.isArray(o))continue;let i=o.filter(r=>typeof r=="string"&&r.length<=64);n[t]=i.slice(0,64);}return n}function Ae(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t;if(!(typeof o.topic!="string"||!d(o.at))&&(n.push({topic:o.topic.slice(0,32),at:o.at}),n.length>=24))break}return n}function We(e){if(!Array.isArray(e))return [];let n=[],t=new Set;for(let o of e){if(typeof o!="object"||o===null)continue;let i=o;if(typeof i.key!="string"||typeof i.package!="string"||i.key===""||i.package==="")continue;let r=`${i.package}\0${i.key}`;if(!t.has(r)&&(t.add(r),n.push({key:i.key,package:i.package}),n.length>=32))break}return n}function Be(e){if(typeof e!="object"||e===null)return null;let n=e,t={};if(typeof n.savedEnv=="object"&&n.savedEnv!==null)for(let[o,i]of Object.entries(n.savedEnv))(typeof i=="string"||i===null)&&(t[o]=i);return {active:n.active===true,savedEnv:t}}function _e(e){if(typeof e!="object"||e===null)return null;let n=e,t=o=>d(o)&&o>=0?o:0;return {turns:t(n.turns),lastLimitAt:t(n.lastLimitAt),lastDepletedAt:t(n.lastDepletedAt),lastBackupAt:t(n.lastBackupAt)}}function Le(e){let n=e.attrTagsAt,t=e.attrTagsCwd;return !d(n)||Date.now()-n>te||typeof t!="string"||t.length===0||t.length>64?{}:{attrTags:Array.isArray(e.attrTags)?e.attrTags.filter(i=>typeof i=="string"&&i.length<=40).slice(0,48):[],attrTagsCwd:t,attrTagsAt:n}}function Me(e){let n=W();if(typeof e!="object"||e===null)return n;let t=e;return {installId:typeof t.installId=="string"&&t.installId.length>0?t.installId:n.installId,lastShownAt:d(t.lastShownAt)&&t.lastShownAt>=0?t.lastShownAt:0,optOut:t.optOut===true,disclosureShown:t.disclosureShown===true,cachedConfig:Pe(t.cachedConfig),allowedPlacements:Oe(t.allowedPlacements),sessionTopics:Ae(t.sessionTopics),integrations:We(t.integrations),devToken:typeof t.devToken=="string"?t.devToken:null,computeRouting:Be(t.computeRouting),computeCards:_e(t.computeCards),configFetchedAt:d(t.configFetchedAt)&&t.configFetchedAt>=0?t.configFetchedAt:0,pool:Ee(t.pool),...Le(t)}}function x(e=process.env){let n=oe(e),t=se(n);if(t.text!==void 0)try{return Me(JSON.parse(t.text))}catch{let o=W();try{p(o,e);}catch{}return o}if(t.missing){let o=W();try{p(o,e);}catch{}return o}return W()}function p(e,n=process.env,t={}){let o=oe(n),i=S__namespace.dirname(o);m__namespace.mkdirSync(i,{recursive:true});let r=se(o),s=null;if(r.text!==void 0)try{s=JSON.parse(r.text);}catch{s=null;}if(s)typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt}),!t.allowClearToken&&typeof s.devToken=="string"&&e.devToken==null&&(e={...e,devToken:s.devToken}),typeof s.installId=="string"&&s.installId.length>0&&s.installId!==e.installId&&(e={...e,installId:s.installId});else if(!t.allowClearToken&&e.devToken==null&&r.text===void 0&&!r.missing)return;let a=S__namespace.join(i,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);m__namespace.writeFileSync(a,JSON.stringify(e,null,2)+`
|
|
6
|
+
`,"utf8");for(let f=0;;f++)try{m__namespace.renameSync(a,o);return}catch(l){let u=l.code??"";if(f>=4||!re.has(u)){try{m__namespace.rmSync(a,{force:!0});}catch{}if(f>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(f+1));}catch{}}}var qe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Y(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return Y(e.OPENCRATER_DISABLE)||Y(e.TSN_DISABLE)}function De(e){return qe.some(n=>Y(e[n]))}function H(e){return e?{...w,...e}:w}function C(e,n={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let t=H(e.state.cachedConfig);if(t.killSwitch)return "kill_switch";if(De(e.env))return "ci";if(!n.skipTTY&&!e.isTTY)return "not_tty";if(!n.skipFrequency){let o=t.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<o)return "frequency"}return null}async function B(e){try{return await e()}catch(n){return c("suppressed error:",n),null}}function _(e,n){let t=H(n.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:t.serveTimeoutMs,installId:n.installId,config:t}}function Fe(e,n){let t=!n.disclosureShown,o=h(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:t});return process.stdout.write(o),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function ae(e,n){let t=await U(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:!n.disclosureShown});return process.stdout.write(t),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function $e(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipFrequency:true});if(t!==null)return c("fetch suppressed:",t),null;let o=_(e,n),i=await F(e,o);return i?(p({...n,cachedConfig:i.config,configFetchedAt:Date.now()}),i.fill&&i.blip?i.blip:null):null}async function ze(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()});if(t!==null)return c("suppressed:",t),false;let o=_(e,n),i=await F(e,o);return i?(n={...n,cachedConfig:i.config,configFetchedAt:Date.now()},i.fill&&i.blip?(n=await ae(i.blip,n),p(n),$(i.blip.impressionId,o),true):i.fallback?(n=Fe(Z(i.fallback),n),p(n),true):(p(n),false)):false}async function Ue(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipTTY:true,skipFrequency:true});if(t!==null)return c("preload suppressed:",t),0;let o=_(e,n),i=Math.max(1,o.config.preloadPoolSize),r=await X(e,i,o);if(!r)return 0;let s=Date.now(),a=ee(r.blips,s);return p({...n,pool:a,cachedConfig:r.config,configFetchedAt:s}),a.length}async function Ge(e){let n=x(),t=Date.now(),o=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:t});if(o!==null)return c("renderFromPool suppressed:",o),false;let{blip:i,pool:r}=ne(n,t);if(!i)return p({...n,pool:r}),false;let s=await ae(i,{...n,pool:r});p(s);let a=_(e,n);return $(i.impressionId,a),true}var kn={show(e){return B(()=>ze(e)).then(n=>n??false)},fetch(e){return B(()=>$e(e))},preload(e){return B(()=>Ue(e)).then(n=>n??0)},renderFromPool(e){return B(()=>Ge(e)).then(n=>n??false)}};exports.DEFAULT_CONFIG=w;exports.HOOK_CATALOG=le;exports.SDK_VERSION=N;exports.detectImageProtocol=z;exports.renderBlip=U;exports.renderCard=h;exports.sponsor=kn;exports.textCardForBlip=A;
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {randomUUID}from'crypto';import*as
|
|
2
|
-
`);}catch{}}catch{}}function
|
|
1
|
+
import {randomUUID}from'crypto';import*as m from'fs';import*as ie from'os';import*as S from'path';var q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var le=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var N="1.2.0";var ce="https://api.opencrater.to";function K(e,n=process.env){let t=n.OPENCRATER_API_ORIGIN;return (e??(t&&t.trim()!==""?t:ce)).replace(/\/+$/,"")}function c(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let n=q("os"),t=q("fs"),o=q("path");t.appendFileSync(o.join(n.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(i=>String(i)).join(" ")}
|
|
2
|
+
`);}catch{}}catch{}}function R(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let n=w;if(typeof e!="object"||e===null)return {...n};let t=e;return {minIntervalSeconds:R(t.minIntervalSeconds)?t.minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:R(t.serveTimeoutMs)?t.serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:R(t.preloadPoolSize)?t.preloadPoolSize:n.preloadPoolSize,killSwitch:t.killSwitch===true,displayDurationSeconds:R(t.displayDurationSeconds)?t.displayDurationSeconds:n.displayDurationSeconds,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:n.minSdkVersion}}async function D(e,n,t,o,i){try{let r=await fetch(`${e}${n}`,{method:"POST",headers:{"content-type":"application/json",...i??{}},body:JSON.stringify(t),signal:AbortSignal.timeout(o)});return r.ok?await r.json():(c(`POST ${n} -> HTTP ${r.status}`),null)}catch(r){return c(`POST ${n} failed:`,r),null}}function J(e,n){let t=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:t,sdkVersion:N,installId:n.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:n.topics&&n.topics.length>0?n.topics:void 0,tags:n.tags&&n.tags.length>0?n.tags:void 0}}function fe(e){if(typeof e!="object"||e===null)return null;let n=e;if(typeof n.fill!="boolean")return null;let t={fill:n.fill,fallback:n.fallback??null,config:V(n.config),...Array.isArray(n.allowedPlacements)?{allowedPlacements:n.allowedPlacements.filter(o=>typeof o=="string")}:{}};return n.blip!==void 0&&n.blip!==null&&(t.blip=n.blip),typeof n.computeBalanceMicroUsd=="number"&&(t.computeBalanceMicroUsd=n.computeBalanceMicroUsd),typeof n.weeklyGrantMicroUsd=="number"&&(t.weeklyGrantMicroUsd=n.weeklyGrantMicroUsd),typeof n.pendingMicroUsd=="number"&&(t.pendingMicroUsd=n.pendingMicroUsd),t}async function F(e,n){let t=await D(n.origin,"/v1/serve",J(e,n),n.timeoutMs);return fe(t)}async function X(e,n,t){let o=await D(t.origin,"/v1/serve/batch",{...J(e,t),count:n},t.timeoutMs);if(typeof o!="object"||o===null)return null;let i=o;return Array.isArray(i.blips)?{blips:i.blips,fallback:i.fallback??null,config:V(i.config),...Array.isArray(i.allowedPlacements)?{allowedPlacements:i.allowedPlacements.filter(r=>typeof r=="string")}:{}}:null}function $(e,n){return D(n.origin,"/v1/events/impression",{impressionId:e},n.timeoutMs).then(()=>{}).catch(()=>{})}var ue=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},de=60,pe=24,me="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function ge(e){return e.replace(ue,"").length}function y(e,n){return n<=0?"":e.length<=n?e:n===1?"\u2026":e.slice(0,n-1).trimEnd()+"\u2026"}function he(e,n,t){let o=e.split(/\s+/).filter(l=>l.length>0),i=[],r="";for(let l of o){let u=r===""?l:`${r} ${l}`;if(u.length<=n)r=u;else if(r!==""&&i.push(r),r=l.length>n?y(l,n):l,i.length>=t)break}r!==""&&i.length<t&&i.push(r),i.length>t&&(i.length=t);let s=i.join(" "),a=i.length-1,f=i[a];return f!==void 0&&s.length<o.join(" ").length&&(i[a]=y(`${f}\u2026`,n)),i}function I(e=process.env,n=!!process.stdout.isTTY){if(!n)return false;if(e.FORCE_HYPERLINK!==void 0&&e.FORCE_HYPERLINK!=="0")return true;let t=e.TERM_PROGRAM??"";return !!(["iTerm.app","WezTerm","ghostty","Hyper","vscode","Tabby"].includes(t)||e.KITTY_WINDOW_ID||e.WT_SESSION||Number(e.VTE_VERSION??"0")>=5e3)}function P(e=process.env,n=!!process.stdout.isTTY){return !(e.NO_COLOR!==void 0&&e.NO_COLOR!==""||!n||(e.TERM??"")==="dumb")}function ye(e,n){return `\x1B]8;;${e}\x07${n}\x1B]8;;\x07`}function E(e){let n={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(n.cta=e.creative.cta),n}function Z(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function h(e,n={}){let t=n.width??process.stdout.columns??80,i=Math.max(pe,Math.min(t,de))-4,r=n.color??P(),s=n.hyperlinks??I(),a=(g,M)=>r?`${M}${g}${k.reset}`:g,f=e.label?y(e.label,i):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,i):"Sponsored Blips",l=[];l.push(a(f,k.dim)),e.title!==e.sponsorLabel&&l.push(a(y(e.title,i),k.bold));for(let g of he(e.body,i,2))l.push(g);let u="\u2192 ";if(s){let g=y(e.cta??e.url,i-u.length);l.push(u+a(ye(e.url,g),k.dim));}else e.cta&&l.push(y(e.cta,i)),l.push(u+a(y(e.url,i-u.length),k.dim));let T=`\u256D${"\u2500".repeat(i+2)}\u256E`,j=`\u2570${"\u2500".repeat(i+2)}\u256F`,L=l.map(g=>{let M=" ".repeat(Math.max(0,i-ge(g)));return `\u2502 ${g}${M} \u2502`}),b=[];return n.disclosure&&b.push(a(me,k.dim)),b.push(T,...L,j),b.join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`}function
|
|
5
|
-
`+
|
|
6
|
-
`,"utf8");for(let
|
|
4
|
+
`}function Q(e){return e!==void 0&&e!==""}function z(e=process.env,n=!!process.stdout.isTTY){if(!n)return "none";let t=e.TERM??"";if(Q(e.TMUX)||t.startsWith("tmux")||t.startsWith("screen"))return "none";let o=e.TERM_PROGRAM??"";return o==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||o==="WezTerm"?"iterm2":t==="xterm-kitty"||Q(e.KITTY_WINDOW_ID)?"kitty":"none"}var v="\x1B",be="\x07",we=2e3,ke=2*1024*1024,Se=new Set(["image/png","image/jpeg","image/gif","image/webp"]),O=4096;async function ve(e,n=fetch,t={}){let o=t.timeoutMs??we,i=t.maxBytes??ke;try{let r=await n(e,{signal:AbortSignal.timeout(o)});if(!r.ok)return c(`media: HTTP ${r.status} for ${e}`),null;let s=(r.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!Se.has(s))return c(`media: disallowed content-type "${s}" for ${e}`),null;let a=Number(r.headers.get("content-length")??"0");if(Number.isFinite(a)&&a>i)return c(`media: content-length ${a} exceeds ${i} for ${e}`),null;let f=r.body;if(f&&typeof f.getReader=="function"){let u=f.getReader(),T=[],j=0;for(;;){let{done:L,value:b}=await u.read();if(L)break;if(b!==void 0){if(j+=b.byteLength,j>i)return await u.cancel().catch(()=>{}),c(`media: stream exceeded ${i} bytes for ${e}`),null;T.push(b);}}return Buffer.concat(T)}let l=Buffer.from(await r.arrayBuffer());return l.byteLength>i?(c(`media: body ${l.byteLength} bytes exceeds ${i} for ${e}`),null):l}catch(r){return c(`media: fetch failed for ${e}:`,r),null}}function xe(e){let n=e.toString("base64");return `${v}]1337;File=inline=1;size=${e.byteLength};width=auto:${n}${be}`}function Ce(e){let n=e.toString("base64");if(n.length<=O)return `${v}_Gf=100,a=T;${n}${v}\\`;let t=[];for(let o=0;o<n.length;o+=O){let i=n.slice(o,o+O),s=`m=${o+O>=n.length?0:1}`,a=o===0?`f=100,a=T,${s}`:s;t.push(`${v}_G${a};${i}${v}\\`);}return t.join("")}function A(e){let n=E(e),t=e.creative;switch(t.format){case "image":case "gif":return {...n,body:t.textFallback??n.body};case "video":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u25B6 Watch"};case "audio":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u{1F50A} Listen"};default:return n}}async function U(e,n={}){try{let t=e.creative;if(t.format!=="image"&&t.format!=="gif")return h(A(e),n);let o=n.protocol??z();if(o==="none"||t.mediaUrl===void 0||t.mediaUrl==="")return h(A(e),n);let i={};n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs),n.maxBytes!==void 0&&(i.maxBytes=n.maxBytes);let r=await ve(t.mediaUrl,n.fetchImpl??fetch,i);return r===null||r.byteLength===0?h(A(e),n):(o==="kitty"?Ce(r):xe(r))+`
|
|
5
|
+
`+h(E(e),n)}catch(t){return c("media: render failed, falling back to text:",t),h(E(e),n)}}function Te(e,n){return e.filter(t=>t.renderBy>n)}function ee(e,n,t=18e5){return e.filter(o=>o&&typeof o.impressionId=="string"&&typeof o.clickUrl=="string"&&o.creative&&typeof o.creative.title=="string").map(o=>({blip:o,renderBy:n+t}))}function ne(e,n){let t=Te(e.pool,n),o=t.shift();return {blip:o?o.blip:null,pool:t}}var te=360*60*1e3;function Ie(e=process.env){return S.join(ie.homedir(),".config","opencrater")}function oe(e=process.env){return S.join(Ie(e),"state.json")}function W(){return {installId:randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function d(e){return typeof e=="number"&&Number.isFinite(e)}var re=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function se(e){for(let n=0;;n++)try{return {text:m.readFileSync(e,"utf8")}}catch(t){let o=t.code??"";if(!(o==="ENOENT"||re.has(o)))return {locked:true};if(n>=4)return o==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(n+1));}catch{}}}function Pe(e){if(typeof e!="object"||e===null)return null;let n=e;return !d(n.minIntervalSeconds)||!d(n.serveTimeoutMs)||!d(n.preloadPoolSize)||typeof n.killSwitch!="boolean"?null:{minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:n.preloadPoolSize,killSwitch:n.killSwitch,displayDurationSeconds:d(n.displayDurationSeconds)?n.displayDurationSeconds:25,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:""}}function Ee(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t,i=o.blip;if(!d(o.renderBy)||typeof i!="object"||i===null||typeof i.impressionId!="string"||typeof i.clickUrl!="string"||typeof i.sponsorLabel!="string"||typeof i.creative!="object"||i.creative===null)continue;let r=i.creative;typeof r.title!="string"||typeof r.body!="string"||n.push({blip:{impressionId:i.impressionId,...typeof i.campaignId=="string"?{campaignId:i.campaignId}:{},clickUrl:i.clickUrl,sponsorLabel:i.sponsorLabel,creative:{format:"text",title:r.title,body:r.body,...typeof r.cta=="string"?{cta:r.cta}:{}}},renderBy:o.renderBy});}return n}function Oe(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let n={};for(let[t,o]of Object.entries(e)){if(!Array.isArray(o))continue;let i=o.filter(r=>typeof r=="string"&&r.length<=64);n[t]=i.slice(0,64);}return n}function Ae(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t;if(!(typeof o.topic!="string"||!d(o.at))&&(n.push({topic:o.topic.slice(0,32),at:o.at}),n.length>=24))break}return n}function We(e){if(!Array.isArray(e))return [];let n=[],t=new Set;for(let o of e){if(typeof o!="object"||o===null)continue;let i=o;if(typeof i.key!="string"||typeof i.package!="string"||i.key===""||i.package==="")continue;let r=`${i.package}\0${i.key}`;if(!t.has(r)&&(t.add(r),n.push({key:i.key,package:i.package}),n.length>=32))break}return n}function Be(e){if(typeof e!="object"||e===null)return null;let n=e,t={};if(typeof n.savedEnv=="object"&&n.savedEnv!==null)for(let[o,i]of Object.entries(n.savedEnv))(typeof i=="string"||i===null)&&(t[o]=i);return {active:n.active===true,savedEnv:t}}function _e(e){if(typeof e!="object"||e===null)return null;let n=e,t=o=>d(o)&&o>=0?o:0;return {turns:t(n.turns),lastLimitAt:t(n.lastLimitAt),lastDepletedAt:t(n.lastDepletedAt),lastBackupAt:t(n.lastBackupAt)}}function Le(e){let n=e.attrTagsAt,t=e.attrTagsCwd;return !d(n)||Date.now()-n>te||typeof t!="string"||t.length===0||t.length>64?{}:{attrTags:Array.isArray(e.attrTags)?e.attrTags.filter(i=>typeof i=="string"&&i.length<=40).slice(0,48):[],attrTagsCwd:t,attrTagsAt:n}}function Me(e){let n=W();if(typeof e!="object"||e===null)return n;let t=e;return {installId:typeof t.installId=="string"&&t.installId.length>0?t.installId:n.installId,lastShownAt:d(t.lastShownAt)&&t.lastShownAt>=0?t.lastShownAt:0,optOut:t.optOut===true,disclosureShown:t.disclosureShown===true,cachedConfig:Pe(t.cachedConfig),allowedPlacements:Oe(t.allowedPlacements),sessionTopics:Ae(t.sessionTopics),integrations:We(t.integrations),devToken:typeof t.devToken=="string"?t.devToken:null,computeRouting:Be(t.computeRouting),computeCards:_e(t.computeCards),configFetchedAt:d(t.configFetchedAt)&&t.configFetchedAt>=0?t.configFetchedAt:0,pool:Ee(t.pool),...Le(t)}}function x(e=process.env){let n=oe(e),t=se(n);if(t.text!==void 0)try{return Me(JSON.parse(t.text))}catch{let o=W();try{p(o,e);}catch{}return o}if(t.missing){let o=W();try{p(o,e);}catch{}return o}return W()}function p(e,n=process.env,t={}){let o=oe(n),i=S.dirname(o);m.mkdirSync(i,{recursive:true});let r=se(o),s=null;if(r.text!==void 0)try{s=JSON.parse(r.text);}catch{s=null;}if(s)typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt}),!t.allowClearToken&&typeof s.devToken=="string"&&e.devToken==null&&(e={...e,devToken:s.devToken}),typeof s.installId=="string"&&s.installId.length>0&&s.installId!==e.installId&&(e={...e,installId:s.installId});else if(!t.allowClearToken&&e.devToken==null&&r.text===void 0&&!r.missing)return;let a=S.join(i,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);m.writeFileSync(a,JSON.stringify(e,null,2)+`
|
|
6
|
+
`,"utf8");for(let f=0;;f++)try{m.renameSync(a,o);return}catch(l){let u=l.code??"";if(f>=4||!re.has(u)){try{m.rmSync(a,{force:!0});}catch{}if(f>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(f+1));}catch{}}}var qe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Y(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return Y(e.OPENCRATER_DISABLE)||Y(e.TSN_DISABLE)}function De(e){return qe.some(n=>Y(e[n]))}function H(e){return e?{...w,...e}:w}function C(e,n={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let t=H(e.state.cachedConfig);if(t.killSwitch)return "kill_switch";if(De(e.env))return "ci";if(!n.skipTTY&&!e.isTTY)return "not_tty";if(!n.skipFrequency){let o=t.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<o)return "frequency"}return null}async function B(e){try{return await e()}catch(n){return c("suppressed error:",n),null}}function _(e,n){let t=H(n.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:t.serveTimeoutMs,installId:n.installId,config:t}}function Fe(e,n){let t=!n.disclosureShown,o=h(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:t});return process.stdout.write(o),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function ae(e,n){let t=await U(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:!n.disclosureShown});return process.stdout.write(t),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function $e(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipFrequency:true});if(t!==null)return c("fetch suppressed:",t),null;let o=_(e,n),i=await F(e,o);return i?(p({...n,cachedConfig:i.config,configFetchedAt:Date.now()}),i.fill&&i.blip?i.blip:null):null}async function ze(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()});if(t!==null)return c("suppressed:",t),false;let o=_(e,n),i=await F(e,o);return i?(n={...n,cachedConfig:i.config,configFetchedAt:Date.now()},i.fill&&i.blip?(n=await ae(i.blip,n),p(n),$(i.blip.impressionId,o),true):i.fallback?(n=Fe(Z(i.fallback),n),p(n),true):(p(n),false)):false}async function Ue(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipTTY:true,skipFrequency:true});if(t!==null)return c("preload suppressed:",t),0;let o=_(e,n),i=Math.max(1,o.config.preloadPoolSize),r=await X(e,i,o);if(!r)return 0;let s=Date.now(),a=ee(r.blips,s);return p({...n,pool:a,cachedConfig:r.config,configFetchedAt:s}),a.length}async function Ge(e){let n=x(),t=Date.now(),o=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:t});if(o!==null)return c("renderFromPool suppressed:",o),false;let{blip:i,pool:r}=ne(n,t);if(!i)return p({...n,pool:r}),false;let s=await ae(i,{...n,pool:r});p(s);let a=_(e,n);return $(i.impressionId,a),true}var kn={show(e){return B(()=>ze(e)).then(n=>n??false)},fetch(e){return B(()=>$e(e))},preload(e){return B(()=>Ue(e)).then(n=>n??0)},renderFromPool(e){return B(()=>Ge(e)).then(n=>n??false)}};export{w as DEFAULT_CONFIG,le as HOOK_CATALOG,N as SDK_VERSION,z as detectImageProtocol,U as renderBlip,h as renderCard,kn as sponsor,A as textCardForBlip};
|
package/dist/paint.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var child_process=require('child_process'),crypto=require('crypto'),
|
|
3
|
-
`);function
|
|
4
|
-
`).filter(
|
|
5
|
-
`);}catch{}}catch{}}function zn(){let t=process.argv.slice(2),e=o=>{let s=t.indexOf(o);return s>=0?t[s+1]:void 0};t.includes("--debug")&&(jt=true,process.env.OPENCRATER_DEBUG="1");let n=t.includes("--persist")||process.env.OPENCRATER_WIN_PERSIST==="1",i=Number(e("--console-pid")??"0");i>0&&(process.env.OPENCRATER_WIN_CONSOLE_PID=String(i));let a=e("--payload-file"),p=process.env.OPENCRATER_PAINT;if(a)try{p=ot.readFileSync(a,"utf8");}catch(o){_("payload-file unreadable:",o.message);}if(!p){_("no paint payload (env or --payload-file) \u2014 nothing to draw");return}let r;try{let o=JSON.parse(p);if(o._env&&typeof o._env=="object"){let s=process.env.OPENCRATER_WIN_CONSOLE_PID;Object.assign(process.env,o._env),s&&(process.env.OPENCRATER_WIN_CONSOLE_PID=s),process.env.OPENCRATER_DEBUG==="1"&&(jt=!0),delete o._env;}r=o;}catch(o){_("paint payload is not valid JSON:",o.message);return}let m=process.env.OPENCRATER_TTY??"/dev/tty",d,$=-1;if(Y){let o=Pn();if(!o){_("Windows: could not start the console pump (powershell.exe)");return}d=o;}else {try{$=ot.openSync(m,"w");}catch(o){_("could not open output device",m,"-",o.message);return}d=Rn($);}_("painting via",Y?"Windows console pump":m,"format",r.format??"text"),process.env.OPENCRATER_FLOW!=="1"&&!Y&&We(d);let h=0;if(Y)h=Tn()??0;else try{let o=new pe__namespace.WriteStream($);o.columns&&(h=o.columns);}catch{}h||(h=80);let l=process.env.NO_COLOR===void 0,N=l&&Ln(process.env),I=(r.format??"text").toLowerCase(),O=I==="image"||I==="logo",x=I==="gif"||I==="video",D=x?72:56,F=Y?24:40;if(Y)process.stdout.rows&&(F=process.stdout.rows);else try{let o=new pe__namespace.WriteStream(ot.openSync(m,"w"));o.rows&&(F=o.rows);}catch{}let C=x?Math.max(8,Math.min(16,Math.floor((F-14)/2)*2)):vn,k=O?5:C,b=Math.min(D,h-4);if(b<24){d.close();return}let S=b-4,B=Math.max(1,h-b-1),y=2,T=Date.now(),X=l?`${w}[2m`:"",G=l?`${w}[38;5;214m`:"",L=l?`${w}[0m`:"",P=I,kt=_n(process.env),xt=process.env.OPENCRATER_FLOW==="1",Ye=process.env.OPENCRATER_MUTE==="1",st=r.apiOrigin??"https://api.opencrater.to",At=P==="video"?`${it("\u25B6")} `:P==="audio"?`${it("\u266A")} `:"",fe=false,de=o=>{if(r.impressionId)try{fetch(`${st}/v1/events/engagement`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({impressionId:r.impressionId,events:o}),signal:AbortSignal.timeout(1500)}).catch(()=>{});}catch{}},rt=null,H=null,Rt=0,pt=0,q=null,J="none",Ft=null,Bt=null,at=null,Gt=0,me=0,Z=null,E=0,R=0,Xe=(o,s)=>{let u=o/s,c=O?Math.min(10,Math.floor(S*.35)):S;E=Math.max(4,Math.min(c,Math.round(2*u*k))),R=Math.max(2,Math.min(k,Math.round(c/(2*u))||k)),O&&(R=Math.min(R,k));let f=Math.min(1,o/(E*2),s/(R*2));f<1&&(E=Math.max(8,Math.floor(E*f)),R=Math.max(2,Math.floor(R*f)));},ht=0,qe=()=>{let o=(r.label??"").trim(),s=(r.sponsorLabel??"").trim(),u=s.toLowerCase()===r.title.trim().toLowerCase(),c=o||(s&&!u?`Sponsored Blips \xB7 ${s}`:"Sponsored Blips"),f=[],g=gt??`${st}/x/${r.impressionId}`,v=r.impressionId||r.replay&>?Ut(g,it("\u2715")):"",z=ht>0&&!xt?Math.max(0,Math.ceil((ht-Date.now())/1e3)):0,W=z>0?`Auto dismiss in: ${z}s `:"",M=l?z<=5?`${w}[1;38;5;196m`:z<=12?`${w}[1;38;5;178m`:`${w}[1;38;5;35m`:"",A=mt(c,Math.max(8,S-2-W.length)),j=" ".repeat(Math.max(1,S-A.length-W.length-1));f.push(`${X}${A}${L}${j}${M}${W}${L}${G}${v}${L}`);let Q=l?kt!=="none"||(process.env.COLORTERM??"").includes("truecolor")?`${w}[1;38;2;255;184;48m`:`${w}[1;38;5;214m`:"",tt=O&&R>0?S-E-2:S;O||f.push(""),f.push(`${Q}${mt(r.title.toUpperCase(),tt)}${L}`);for(let V of xn(r.body,tt))f.push(V);if(J!=="none"){let V=J==="playing"?`${it("\u23F8")} pause`:J==="paused"?`${it("\u25B6")} play`:`${it("\u25B6")} replay`,ft=Math.max(6,Math.min(14,tt-V.length-5)),dt="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",Tt="";for(let _t=0;_t<ft;_t++){let an=J==="playing"?Math.abs(Math.sin(pt*.9+_t*1.7)*.55+Math.sin(pt*.37+_t*.53)*.45):.05;Tt+=dt[Math.max(0,Math.min(7,Math.floor(an*8)))];}let sn=Ft?Ut(Ft,V):V;f.push(`${it("\u266A")} ${G}${Tt}${L} ${G}${sn}${L}`);}let Xt=process.env.TERM_PROGRAM??"",en=process.env.TERM??"",qt=kt!=="none"||["vscode","ghostty","iTerm.app","WezTerm","Hyper","WarpTerminal","rio","Tabby"].includes(Xt)||/kitty|wezterm|alacritty|foot|rio|ghostty/i.test(en)||process.env.WT_SESSION!==void 0||process.env.ConEmuANSI==="ON"||process.env.VTE_VERSION!==void 0,Kt=(V,ft,dt)=>l?`${w}[48;2;${ft[0]};${ft[1]};${ft[2]};38;2;${dt[0]};${dt[1]};${dt[2]};1m ${V} ${w}[0m`:`[ ${V} ]`,$t=[240,178,50],Zt=[12,12,10],Qt=r.impressionId?`${st}/k/${r.impressionId}`:r.url,yt=[];if(qt){let V=mt(r.cta&&r.cta.trim()!==""?r.cta:"visit sponsor",S-6-At.length);yt.push(Ut(r.url,Kt(`${At}${V} \u2192`,$t,Zt)));}else {let V=(r.cta&&r.cta.trim()!==""?r.cta.trim():"VISIT").toUpperCase();At.length+V.length+1+Qt.length<=S?yt.push(Kt(`${V} ${At}${Qt}`,$t,Zt)):yt.push(Kt(`${At}${Qt}`,$t,Zt));let ft=process.platform==="darwin"?"\u2318-click":"Ctrl-click",dt=mt(`${it("\u2191")} ${ft} the link to open`,S),Tt=l?`${w}[38;2;${$t[0]};${$t[1]};${$t[2]}m`:"";yt.push(`${Tt}${dt}${L}`);}let ke=Bt??(r.impressionId?`${st}/r/${r.impressionId}`:null),Ae=ke&&qt?` \xB7 ${Ut(ke,`${it("\u2691")} report`)}`:"",on=qt?"dismiss: click \u2715 or npx opencrater x \xB7 opt out: npx opencrater off":"dismiss: npx opencrater x \xB7 opt out: npx opencrater off";return yt.push(`${X}${mt(on,Math.max(0,S-Wt(Ae)))}${Ae}${L}`),{head:f,tail:yt}},he=0,ge=()=>{let{head:o,tail:s}=qe(),u=`${G}\u256D${"\u2500".repeat(b-2)}\u256E${L}`,c=`${G}\u2570${"\u2500".repeat(b-2)}\u256F${L}`,f=v=>{let z=" ".repeat(Math.max(0,S-Wt(v)));return `${G}\u2502${L} ${v}${z} ${G}\u2502${L}`},g;if(O&&R>0&&(H||rt)){let v=S-E-2,z=o[0]??"",W=o.slice(1),M=H?H[Rt%H.length]:null;g=[u,f(z)];let A=Math.max(W.length,R);for(let j=0;j<A;j++){let Q=W[j]??"",tt=" ".repeat(Math.max(0,v-Wt(Q))),Xt=j<R&&M?M[j]??" ".repeat(E):" ".repeat(E);g.push(`${G}\u2502${L} ${Q}${tt} ${Xt} ${G}\u2502${L}`);}}else {g=[u,...o.map(f)];let v=Math.max(0,Math.floor((S-E)/2)),z=Math.max(0,S-E-v);if(H&&R>0){let W=H[Rt%H.length];for(let M=0;M<R;M++){let A=W[M]??" ".repeat(E);g.push(`${G}\u2502${L} ${" ".repeat(v)}${A}${" ".repeat(z)} ${G}\u2502${L}`);}}else if(rt&&R>0)for(let W=0;W<R;W++)g.push(`${G}\u2502${L} ${" ".repeat(S)} ${G}\u2502${L}`);}return g.push(...s.map(f)),g.push(c),he=s.length+1,g},Ht=0,be=`${w}[?2026h`,$e=`${w}[?2026l`,ye=0,we=2e3,Ze=8,zt=()=>{let o=ge();Ht=Math.max(Ht,o.length),Gn({pid:process.pid,row:y,col:B,width:b,rows:o.length,startedAt:T,...r.impressionId?{impressionId:r.impressionId}:{},...gt?{dismissUrl:gt}:{}});let s=be+_e,u=Date.now()<ye,c=Math.max(1,y-(u?Ze:2));for(let f=c;f<y;f++)s+=`${w}[${f};${B}H${w}[0m${" ".repeat(b)}`;for(let f=0;f<o.length;f++)s+=`${w}[${y+f};${B}H${o[f]}`;if(rt&&pt%(u?1:3)===0&&R>0){let f=O?y+2:y+o.length-he-R,g=O?B+2+(S-E):B+2+Math.max(0,Math.floor((S-E)/2));s+=`${w}[${f};${g}H${rt}`;}return s+=De+$e,pt++,H&&H.length>1&&Rt++,s},ct=()=>{d.write(zt());},Se=()=>{let o=be+_e+`${w}[0m`,s=" ".repeat(b);for(let u=0;u<Ht;u++)o+=`${w}[${y+u};${B}H${s}`;o+=De+$e,d.write(o);},lt=null,Mt=null,Pt=null,Et=null,gt=null,K=o=>{if(_("cleanup wipe="+o+" elapsed="+(Date.now()-T)+"ms"),fe||(fe=true,de([{type:"dwell",ms:Date.now()-T}])),lt&&clearInterval(lt),Mt&&clearInterval(Mt),Pt&&clearInterval(Pt),o){let s=Number(process.env.OPENCRATER_HOST_PID??0);s>1&&!Y&&setTimeout(()=>{try{process.kill(s,"SIGWINCH");}catch{}},80);}if(Et){try{Et.close();}catch{}Et=null;}if(lt=null,Mt=null,Pt=null,q){try{q.kill("SIGKILL");}catch{}q=null;}if(Z){try{ot.rmSync(Z,{recursive:!0,force:!0});}catch{}Z=null;}if(Se(),Hn(),Y){let s=false,u=()=>{s||(s=true,process.exit(0));};d.closeAndWait().then(u),setTimeout(u,1500).unref?.();return}d.close(),process.exit(0);},Qe=()=>{lt&&clearInterval(lt);let s=E*R>1100?200:Ee;lt=setInterval(ct,H&&H.length>1?s:Lt);},Nt=()=>(Z||(Z=ot.mkdtempSync(U__namespace.join(Re.tmpdir(),"ocpaint-"))),Z),Jt=async()=>{if(r.mediaPixelUrl&&(I==="image"||I==="logo"))try{let M=await fetch(r.mediaPixelUrl,{signal:AbortSignal.timeout(2500)});if(M.ok){let A=Pe(new Uint8Array(await M.arrayBuffer()));if(A&&A.width>=4&&A.height>=2){let j=Buffer.alloc(A.width*A.height*3);for(let Q=0,tt=0;Q<A.rgba.length;Q+=4,tt+=3)j[tt]=A.rgba[Q],j[tt+1]=A.rgba[Q+1],j[tt+2]=A.rgba[Q+2];E=Math.floor(A.width/2),R=Math.floor(A.height/2),H=[ze(j,A.width,A.height,N)];return}}}catch{}if(!r.mediaUrl)return;let o=P==="video",s=await Ue(r.mediaUrl,o?On:Ne);if(!s||!(o?s.type.startsWith("video/"):s.type.startsWith("image/")))return;let c=U__namespace.join(Nt(),"in");try{ot.writeFileSync(c,s.data);}catch{return}let f=Je(c),g=et("ffmpeg")?Fn(c):null,v=g?.match(/crop=(\d+):(\d+)/),z=v?Number(v[1]):f?.w??16,W=v?Number(v[2]):f?.h??9;if(O&&et("ffmpeg")&&z>0&&W>0){let M=Math.min(z,W),A=Math.floor((z-M)/2),j=Math.floor((W-M)/2);g=`crop=${M}:${M}:${A}:${j}`,z=M,W=M,v=null;}if(Xe(z,W),!o&&kt==="iterm2"){rt=Le(s.data,{w:E,h:R}),pt=0;return}if(!o&&kt==="kitty"&&s.type==="image/png"){rt=Dn(s.data,{w:E,h:R}),pt=0;return}if(o&&kt==="iterm2"&&et("ffmpeg"))try{let M=U__namespace.join(Nt(),"out.gif");if(child_process.spawnSync("ffmpeg",["-y","-i",c,"-t","6","-vf","fps=8,scale=280:-1:flags=lanczos","-loop","0",M],{timeout:12e3}).status===0){let j=ot.readFileSync(M);if(j.length<=Ne){rt=Le(j,{w:E,h:R}),pt=0;return}}}catch{}if(et("ffmpeg"))try{let M=o||s.type==="image/gif",A=jn(c,Nt(),E,R,M,g)??Wn(c,E,R,M,N,g);A&&A.length>0&&(H=A,Rt=0,Qe());}catch{}},Yt=(o=0)=>{if(!at)return;let{kind:s,file:u,vol:c}=at,f=Math.max(0,o/1e3),g,v;s==="afplay"?(g="afplay",v=["-v",c.toFixed(2),u]):s==="ffplay"?(g="ffplay",v=["-nodisp","-autoexit","-volume",String(Math.round(c*100))],f>.2&&v.push("-ss",f.toFixed(2)),v.push(u)):s==="mpv"?(g="mpv",v=["--no-video","--really-quiet",`--volume=${Math.round(c*100)}`],f>.2&&v.push(`--start=${f.toFixed(2)}`),v.push(u)):s==="paplay"?(g="paplay",v=[`--volume=${Math.round(c*65536)}`,u]):(g="mpg123",v=["-q","-f",String(Math.round(32768*c))],f>.2&&v.push("-k",String(Math.round(o/26.12))),v.push(u));try{q=Y?child_process.spawn(g,v,{stdio:"ignore",detached:!0,windowsHide:!0}):child_process.spawn(g,v,{stdio:"ignore"}),J="playing",me=Date.now(),q.on("exit",()=>{J!=="paused"&&(J="ended",Gt=0);});}catch{J="none";}},tn=()=>{try{J==="playing"&&q?(J="paused",Gt+=Date.now()-me,q.kill("SIGKILL"),q=null,de([{type:"sound_muted"}])):J==="paused"?at?.canSeek&&Yt(Gt):J==="ended"&&Yt(0);}catch{}ct();},bt=async(o=r.mediaUrl)=>{if(!o||Ye)return;let s=U__namespace.join(Re.homedir(),".config","opencrater","audio-plays.json");try{let c=[];try{c=JSON.parse(ot.readFileSync(s,"utf8")),Array.isArray(c)||(c=[]);}catch{}let f=xe(Date.now(),c);if(ot.writeFileSync(s,JSON.stringify(f.next)),!f.play)return}catch{}let u=await Ue(o,kn);if(!(!u||!u.type.startsWith("audio/")))try{let c=u.type.includes("wav")?"wav":u.type.includes("ogg")?"ogg":"mp3",f=U__namespace.join(Nt(),`ad.${c}`);ot.writeFileSync(f,u.data);let g=Ce(new Date().getHours());if(et("ffplay"))at={kind:"ffplay",file:f,vol:g,canSeek:!0};else if(!Y&&et("mpv"))at={kind:"mpv",file:f,vol:g,canSeek:!0};else if(process.platform==="darwin"&&et("afplay"))at={kind:"afplay",file:f,vol:g,canSeek:!1};else if(!Y&&et("mpg123")&&c==="mp3")at={kind:"mpg123",file:f,vol:g,canSeek:!0};else if(!Y&&c!=="mp3"&&et("paplay"))at={kind:"paplay",file:f,vol:g,canSeek:!1};else return;Yt(),setTimeout(()=>{try{q?.kill("SIGKILL");}catch{}(J==="playing"||J==="paused")&&(J="ended");},Te).unref?.();}catch{}},ve=()=>{if(!r.impressionId||r.replay)return;let o=U__namespace.join(Re.homedir(),".config","opencrater","dismiss.signal"),s=Date.now();Mt=setInterval(()=>{try{let u=ot.readFileSync(o,"utf8"),c=JSON.parse(u),f=typeof c.at=="number"&&c.at>=s-5e3,g=!c.impressionId||c.impressionId===r.impressionId;if(f&&g){try{ot.unlinkSync(o);}catch{}Dt(r.campaignId),fetch(`${st}/x/${r.impressionId}`,{signal:AbortSignal.timeout(1500)}).catch(()=>{}),K(!0);return}}catch{}(async()=>{try{let u=await fetch(`${st}/v1/events/dismissed/${r.impressionId}`,{signal:AbortSignal.timeout(1200)});if(!u.ok)return;(await u.json()).dismissed&&(Dt(r.campaignId),K(!0));}catch{}})();},In);},Ie=()=>{if(xt)return;let o=U__namespace.join(Re.homedir(),".config","opencrater","activity.signal"),s=Date.now(),u=1500;Pt=setInterval(()=>{try{let c=ot.statSync(o).mtimeMs;c>s+u&&c>Date.now()-we&&(ye=c+we,ct());}catch{}},150);};if(Y){(async()=>{let o=d.size?await d.size:null;if(o&&o.cols>=24&&(h=o.cols,b=Math.min(D,h-4),S=b-4,B=Math.max(1,h-b-1),_("windows geometry from pump:","cols",h,"width",b,"col",B,"ownerPid",o.pid)),P==="image"||P==="logo"||P==="gif"||P==="video"?await Jt():P==="audio"&&await bt(),r.audioUrl&&P!=="audio"&&bt(r.audioUrl),n){let f=Math.min(Math.max(r.durationMs??se,3e3),12e4);if(ht=Date.now()+f,a)try{ot.unlinkSync(a);}catch{}We(d);let g=H,v=!!(g&&g.length>1);ct(),lt=setInterval(ct,v?Ee:Lt),Ie(),Oe(),ve(),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),f);return}let s=o?.pid??0;s>0&&Nn(r,s)&&(d.close(),process.exit(0)),_("no job-escape (ownerPid",s,") \u2014 bounded toast fallback");let u=Number(process.env.OPENCRATER_WIN_HOLD_MS),c=u>0?u:Math.min(r.durationMs??se,5e3);if(ht=Date.now()+c,d.write(zt()),await new Promise(f=>{let g=setInterval(()=>{if(Date.now()>=ht){clearInterval(g),f();return}d.write(zt());},Lt);}),Se(),Z)try{ot.rmSync(Z,{recursive:!0,force:!0});}catch{}await d.closeAndWait(),process.exit(0);})();return}if(xt){(async()=>{P==="image"||P==="logo"||P==="gif"||P==="video"?await Jt():P==="audio"&&await bt(),r.audioUrl&&P!=="audio"&&bt(r.audioUrl);let o=H;o&&o.length>1&&(H=[o[0]]);let s=ge(),u=" ".repeat(Math.max(0,h-b-2)),c=`\r
|
|
6
|
-
`;for(let
|
|
7
|
-
`;
|
|
8
|
-
`),
|
|
9
|
-
exports.windowsVtOk=
|
|
2
|
+
'use strict';var child_process=require('child_process'),crypto=require('crypto'),Ft=require('http'),re=require('fs'),Pt=require('os'),L=require('path'),zlib=require('zlib'),dt=require('tty');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ft__namespace=/*#__PURE__*/_interopNamespace(Ft);var re__namespace=/*#__PURE__*/_interopNamespace(re);var Pt__namespace=/*#__PURE__*/_interopNamespace(Pt);var L__namespace=/*#__PURE__*/_interopNamespace(L);var dt__namespace=/*#__PURE__*/_interopNamespace(dt);var et=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function At(e){return e>=21||e<8?.2:.4}function Ot(e,t){let i=t.filter(o=>Number.isFinite(o)&&e-o<6e5&&o<=e);return i.length>=2?{play:false,next:i}:{play:true,next:[...i,e]}}function it(e=process.env){return L__namespace.join(Pt__namespace.homedir(),".config","opencrater")}var un=600*1e3;function rt(){return L__namespace.join(it(),"blocked-ads.json")}function ot(){return L__namespace.join(it(),"reported-ads.json")}function dn(e,t){let i={};for(let[o,a]of Object.entries(e))typeof a=="number"&&Number.isFinite(a)&&a>t&&(i[o]=a);return i}function pn(e){try{let t=JSON.parse(re__namespace.readFileSync(rt(),"utf8"));return dn(t&&typeof t=="object"?t:{},e)}catch{return {}}}function Ne(e,t=Date.now()){if(e)try{let i=pn(t);i[e]=t+un,re__namespace.mkdirSync(L__namespace.dirname(rt()),{recursive:!0}),re__namespace.writeFileSync(rt(),JSON.stringify(i));}catch{}}function mn(){try{let e=JSON.parse(re__namespace.readFileSync(ot(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}function Rt(e,t=Date.now()){if(e)try{let i=mn();i[e]=t,re__namespace.mkdirSync(L__namespace.dirname(ot()),{recursive:!0}),re__namespace.writeFileSync(ot(),JSON.stringify(i));}catch{}}var hn=[137,80,78,71,13,10,26,10];function Tt(e){try{if(e.length<45)return null;for(let A=0;A<8;A++)if(e[A]!==hn[A])return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=8,o=0,a=0,u=0,n=-1,m=0,p=[];for(;i+8<=e.length;){let A=t.getUint32(i),N=String.fromCharCode(e[i+4],e[i+5],e[i+6],e[i+7]),U=e.subarray(i+8,i+8+A);if(N==="IHDR")o=t.getUint32(i+8),a=t.getUint32(i+12),u=e[i+16],n=e[i+17],m=e[i+20];else if(N==="IDAT")p.push(U);else if(N==="IEND")break;i+=12+A;}if(u!==8||n!==2&&n!==6||m!==0||o===0||a===0||o>1024||a>1024)return null;let y=n===6?4:3,g=o*y,c=zlib.inflateSync(Buffer.concat(p.map(A=>Buffer.from(A))));if(c.length<(g+1)*a)return null;let M=new Uint8Array(o*a*4),S=new Uint8Array(g),x=new Uint8Array(g);for(let A=0;A<a;A++){let N=A*(g+1),U=c[N];for(let j=0;j<g;j++){let I=c[N+1+j],b=j>=y?x[j-y]:0,$=S[j],F=j>=y?S[j-y]:0,w;switch(U){case 0:w=I;break;case 1:w=I+b;break;case 2:w=I+$;break;case 3:w=I+(b+$>>1);break;case 4:{let W=b+$-F,V=Math.abs(W-b),xe=Math.abs(W-$),B=Math.abs(W-F);w=I+(V<=xe&&V<=B?b:xe<=B?$:F);break}default:return null}x[j]=w&255;}for(let j=0;j<o;j++){let I=j*y,b=(A*o+j)*4;M[b]=x[I],M[b+1]=x[I+1],M[b+2]=x[I+2],M[b+3]=y===4?x[I+3]:255;}S.set(x);}return {width:o,height:a,rgba:M}}catch{return null}}var _e=300,Mt=140,at=12e3,In=9;var Cn=1500,Wt=3*1024*1024,jn=12*1024*1024,An=12*1024*1024,On=6e3,Et=25e3,zt=64,k="\x1B",Pn="\x07",Nt=`${k}7`,_t=`${k}8`;function Le(e,t){return `${k}]8;;${e}${k}\\${t}${k}]8;;${k}\\`}function De(e){return e.replace(/\x1b\[[0-9;]*m/g,"").replace(/\x1b\]8;;[^\x1b\x07]*(?:\x1b\\|\x07)/g,"").replace(/[︎️]/g,"").length}function me(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}\u2026`}function Rn(e,t){let i=e.split(/\s+/).filter(Boolean),o=[],a="";for(let u of i)if(a===""?a=me(u,t):a.length+1+u.length<=t?a+=` ${u}`:(o.push(a),a=me(u,t)),o.length>=3)break;return a&&o.length<4&&o.push(a),o}var J=process.platform==="win32";function oe(e){return J?`${e}\uFE0E`:e}function Tn(e){let t=()=>{try{re.closeSync(e);}catch{}};return {write:i=>{try{re.writeSync(e,i);}catch{}},close:t,closeAndWait:async()=>t()}}var Mn=["$ErrorActionPreference='SilentlyContinue'","$dbg=$env:OPENCRATER_DEBUG -eq '1'","$log=Join-Path $env:USERPROFILE '.config\\opencrater\\pump.log'","function L($m){ if($dbg){ try{ Add-Content -LiteralPath $log -Value ((Get-Date).ToString('o')+' '+$m) }catch{} } }","L 'pump: process started (loading types)'","Add-Type -TypeDefinition @'","using System;using System.Runtime.InteropServices;","namespace OCP{","public struct COORD{public short X;public short Y;}","public struct SR{public short L;public short T;public short R;public short B;}","public struct CSBI{public COORD sz;public COORD cur;public ushort attr;public SR win;public COORD max;}","public static class N{",'[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)]public static extern IntPtr CreateFileW(string n,uint a,uint s,IntPtr sec,uint d,uint f,IntPtr t);','[DllImport("kernel32.dll")]public static extern bool GetConsoleMode(IntPtr h,out uint m);','[DllImport("kernel32.dll")]public static extern bool SetConsoleMode(IntPtr h,uint m);','[DllImport("kernel32.dll")]public static extern bool SetConsoleOutputCP(uint cp);','[DllImport("kernel32.dll")]public static extern bool WriteFile(IntPtr h,byte[] b,uint n,out uint w,IntPtr o);','[DllImport("kernel32.dll")]public static extern bool FreeConsole();','[DllImport("kernel32.dll")]public static extern bool AttachConsole(uint p);','[DllImport("kernel32.dll")]public static extern IntPtr GetStdHandle(int n);','[DllImport("kernel32.dll")]public static extern bool GetConsoleScreenBufferInfo(IntPtr h,out CSBI i);',"}}","'@","L 'pump: types loaded'","$o=[uint32]'0xC0000000'","function OpenConout(){ return [OCP.N]::CreateFileW('CONOUT$',$o,3,[IntPtr]::Zero,3,0,[IntPtr]::Zero) }","function Csbi($hh){ $z=New-Object OCP.CSBI; if($hh -ne [IntPtr]-1 -and [OCP.N]::GetConsoleScreenBufferInfo($hh,[ref]$z)){ return $z } else { return $null } }","$self=Csbi (OpenConout); if($self){ L ('pump: SELF bufH='+$self.sz.Y+' winRows='+($self.win.B-$self.win.T+1)+' curY='+$self.cur.Y) }","$how='self'; $winId=0","$given=[int]($env:OPENCRATER_WIN_CONSOLE_PID)","if($given -gt 0){ [void][OCP.N]::FreeConsole(); if([OCP.N]::AttachConsole([uint32]$given)){ $winId=$given; $how='given' } L ('pump: given console pid '+$given+' attached='+($winId -eq $given)) }","if($winId -eq 0){"," $par=@{}; try{ Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { $par[[int]$_.ProcessId]=[int]$_.ParentProcessId } }catch{ L 'pump: WMI walk failed' }"," $chain=New-Object System.Collections.ArrayList; $p=$PID; for($i=0;$i -lt 12;$i++){ if(-not $par.ContainsKey($p)){break}; $pp=$par[$p]; if($pp -le 4){break}; $nm='?'; try{ $nm=(Get-Process -Id $pp -ErrorAction Stop).ProcessName }catch{}; [void]$chain.Add(@{id=$pp;name=$nm}); $p=$pp }"," L ('pump: ancestors = ' + (($chain | ForEach-Object { $_.name+'('+$_.id+')' }) -join ' -> '))"," foreach($c in $chain){ [void][OCP.N]::FreeConsole(); if([OCP.N]::AttachConsole([uint32]$c.id)){ $b=Csbi (OpenConout); if($b){ L ('pump: '+$c.name+'('+$c.id+') bufH='+$b.sz.Y+' winRows='+($b.win.B-$b.win.T+1)+' curY='+$b.cur.Y); if($b.sz.Y -lt 1000 -and $c.name -notmatch '^(WindowsTerminal|OpenConsole|conhost|explorer|Code|devenv|wininit|services|svchost|WmiPrvSE)$'){ $winId=$c.id; $how=('attach:'+$c.name) } } } }","}","[void][OCP.N]::FreeConsole()","if($winId -ne 0){ [void][OCP.N]::AttachConsole([uint32]$winId) } else { [void][OCP.N]::AttachConsole(0xFFFFFFFF); $how='attach-parent' }","$h=OpenConout","if($h -eq [IntPtr]-1){ L 'pump: NO CONSOLE after attach walk'; exit 1 }","$fb=Csbi $h; if($fb){ L ('pump: FINAL via '+$how+' bufH='+$fb.sz.Y+' winRows='+($fb.win.B-$fb.win.T+1)+' curY='+$fb.cur.Y) } else { L ('pump: FINAL via '+$how) }","if($fb){ $cols=$fb.win.R-$fb.win.L+1; $rows=$fb.win.B-$fb.win.T+1; [Console]::Out.WriteLine('OCWIN '+$winId+' '+$cols+' '+$rows); [Console]::Out.Flush() }","$m=[uint32]0;[void][OCP.N]::GetConsoleMode($h,[ref]$m);[void][OCP.N]::SetConsoleMode($h,($m -bor 4));[void][OCP.N]::SetConsoleOutputCP(65001)","$in=[Console]::OpenStandardInput();$buf=New-Object byte[] 65536;$tot=0;$frames=0","while(($n=$in.Read($buf,0,$buf.Length)) -gt 0){$w=[uint32]0;[void][OCP.N]::WriteFile($h,$buf,$n,[ref]$w,[IntPtr]::Zero);$tot+=$w;$frames++}","L ('pump: stdin closed, streamed '+$tot+' bytes in '+$frames+' chunks')"].join(`
|
|
3
|
+
`);function Gt(){return `${process.env.SystemRoot||process.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`}function Wn(){try{let e=Buffer.from(Mn,"utf16le").toString("base64"),t=Gt(),i="ignore";if(process.env.OPENCRATER_DEBUG==="1")try{i=re.openSync(L__namespace.join(Pt.homedir(),".config","opencrater","pump-err.log"),"a");}catch{}E("spawning pump:",t);let o=child_process.spawn(t,["-NoProfile","-NonInteractive","-EncodedCommand",e],{stdio:["pipe","pipe",i],windowsHide:!0});o.on("error",m=>E("pump spawn error:",t,"-",m.message)),o.on("exit",m=>E("pump process exited code",m,"pid",o.pid));let a=o.stdin;if(!a)return E("pump: no stdin pipe"),null;a.on("error",()=>{});let u=!1;return o.on("exit",()=>{u=!0;}),{size:new Promise(m=>{let p="",y=!1,g=M=>{y||(y=!0,m(M));},c=o.stdout;if(!c)return g(null);c.setEncoding("utf8"),c.on("data",M=>{p+=M;let S=p.match(/OCWIN\s+(\d+)\s+(\d+)\s+(\d+)/);S&&(E("pump reported console pid",S[1],"size",S[2]+"x"+S[3]),g({pid:Number(S[1]),cols:Number(S[2]),rows:Number(S[3])}));}),c.on("error",()=>g(null)),c.on("end",()=>g(null)),setTimeout(()=>g(null),2500);}),write:m=>{try{a.write(m);}catch{}},close:()=>{try{a.end();}catch{}},closeAndWait:()=>new Promise(m=>{if(u)return m();let p=!1,y=()=>{p||(p=!0,m());};o.on("exit",y),setTimeout(y,5e3);try{a.end();}catch{y();}})}}catch(e){return E("pump: spawn threw",e.message),null}}function En(e){try{let t=e.replace(/'/g,"''"),i=`$ErrorActionPreference='Stop';try{$r=$null;try{$su=([wmiclass]'Win32_ProcessStartup').CreateInstance();$su.CreateFlags=[uint32]8;$r=([wmiclass]'Win32_Process').Create('${t}',$null,$su)}catch{};if($r -eq $null -or $r.ReturnValue -ne 0){$r=([wmiclass]'Win32_Process').Create('${t}')};if($r.ReturnValue -eq 0){[Console]::Out.Write('OCPID '+$r.ProcessId)}else{[Console]::Out.Write('OCERR rv='+$r.ReturnValue)}}catch{[Console]::Out.Write('OCERR '+$_.Exception.Message)}`,o=Buffer.from(i,"utf16le").toString("base64"),a=child_process.spawnSync(Gt(),["-NoProfile","-NonInteractive","-EncodedCommand",o],{timeout:5e3,encoding:"utf8"}),u=(a.stdout??"").match(/OCPID\s+(\d+)/);return u?Number(u[1]):(E("wmi spawn failed:",(a.stdout??"").trim(),"|",(a.stderr??"").trim()),0)}catch(t){return E("wmi spawn threw",t.message),0}}function Nn(e,t){try{let i=L__namespace.join(Pt.homedir(),".config","opencrater");re.mkdirSync(i,{recursive:!0});let o=L__namespace.join(i,`paint-${process.pid}-${Date.now()}.json`);re.writeFileSync(o,JSON.stringify({...e,_env:process.env}),"utf8");let a=m=>`"${m}"`,u=[a(process.execPath),a(__filename),"--persist","--payload-file",a(o),"--console-pid",String(t)];qe&&u.push("--debug");let n=En(u.join(" "));return E("escape: wmi persistent painter pid",n),n>0}catch(i){return E("escape failed",i.message),false}}function hi(e){return !!(e.WT_SESSION||e.TERM_PROGRAM||e.ConEmuANSI==="ON"||e.ANSICON)}function _n(){try{let e=child_process.spawnSync("mode",["con"],{timeout:1500,encoding:"utf8"}).stdout;if(!e)return null;let i=[...e.matchAll(/:\s*(\d+)/g)].map(o=>Number(o[1]))[1];return i&&i>0?i:null}catch{return null}}function Ln(e){let t=e.TERM_PROGRAM??"",i=e.TERM??"";return e.TMUX?"none":t==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||t==="WezTerm"?"iterm2":i==="xterm-kitty"||e.KITTY_WINDOW_ID?"kitty":"none"}function Lt(e,t){let i=e.toString("base64");return `${k}]1337;File=inline=1;size=${e.length};width=${t.w};height=${t.h};preserveAspectRatio=1:${i}${Pn}`}function Dn(e,t){let i=e.toString("base64"),o=[];for(let u=0;u<i.length;u+=4096)o.push(i.slice(u,u+4096));let a="";for(let u=0;u<o.length;u++){let n=u===0,m=u===o.length-1,p=n?`a=T,f=100,c=${t.w},r=${t.h},m=${m?0:1}`:`m=${m?0:1}`;a+=`${k}_G${p};${o[u]}${k}\\`;}return a}function qn(e){let t=(e.COLORTERM??"").toLowerCase();if(t.includes("truecolor")||t.includes("24bit"))return true;let i=e.TERM_PROGRAM??"";return ["iTerm.app","WezTerm","vscode","ghostty","Apple_Terminal"].includes(i)}function lt(e,t,i){if(Math.abs(e-t)<12&&Math.abs(t-i)<12&&Math.abs(e-i)<12)return e<8?16:e>248?231:232+Math.round((e-8)/247*23);let o=a=>Math.round(a/255*5);return 16+36*o(e)+6*o(t)+o(i)}var Un=[" ","\u2598","\u259D","\u2580","\u2596","\u258C","\u259E","\u259B","\u2597","\u259A","\u2590","\u259C","\u2584","\u2599","\u259F","\u2588"];function Ht(e,t,i,o){let a=[],u=(m,p)=>{let y=(p*t+m)*3;return [e[y],e[y+1],e[y+2]]},n=(m,p)=>{let y=m[0]-p[0],g=m[1]-p[1],c=m[2]-p[2];return y*y+g*g+c*c};for(let m=0;m+1<i;m+=2){let p="",y="";for(let g=0;g+1<t;g+=2){let c=[u(g,m),u(g+1,m),u(g,m+1),u(g+1,m+1)],M=0,S=1,x=-1;for(let w=0;w<4;w++)for(let W=w+1;W<4;W++){let V=n(c[w],c[W]);V>x&&(x=V,M=w,S=W);}let A=0,N=[0,0,0],U=[0,0,0],j=0,I=0;for(let w=0;w<4;w++)n(c[w],c[M])<=n(c[w],c[S])?(A|=1<<w,N[0]+=c[w][0],N[1]+=c[w][1],N[2]+=c[w][2],j++):(U[0]+=c[w][0],U[1]+=c[w][1],U[2]+=c[w][2],I++);if(x<1e3){let w=xe=>xe&-8,W=[w(Math.round((c[0][0]+c[1][0]+c[2][0]+c[3][0])/4)),w(Math.round((c[0][1]+c[1][1]+c[2][1]+c[3][1])/4)),w(Math.round((c[0][2]+c[1][2]+c[2][2]+c[3][2])/4))],V=o?`${k}[48;2;${W[0]};${W[1]};${W[2]}m`:`${k}[48;5;${lt(W[0],W[1],W[2])}m`;V!==y&&(p+=V,y=V),p+=" ";continue}let b=j?[Math.round(N[0]/j),Math.round(N[1]/j),Math.round(N[2]/j)]:[0,0,0],$=I?[Math.round(U[0]/I),Math.round(U[1]/I),Math.round(U[2]/I)]:b,F=o?`${k}[38;2;${b[0]};${b[1]};${b[2]};48;2;${$[0]};${$[1]};${$[2]}m`:`${k}[38;5;${lt(b[0],b[1],b[2])};48;5;${lt($[0],$[1],$[2])}m`;F!==y&&(p+=F,y=F),p+=Un[A];}p+=`${k}[0m`,a.push(p);}return a}function Fn(e,t,i,o,a,u){let n=t*2,m=i*2,p=`${u?`${u},`:""}scale=${n}:${m}:flags=lanczos+accurate_rnd`,y=["-y","-i",e];o?y.push("-t","6","-vf",`fps=7,${p}`):y.push("-frames:v","1","-vf",p),y.push("-f","rawvideo","-pix_fmt","rgb24","-");let g=child_process.spawnSync("ffmpeg",y,{timeout:12e3,maxBuffer:64*1024*1024});if(g.status!==0||!g.stdout||g.stdout.length===0)return null;let c=n*m*3,M=Math.min(Math.floor(g.stdout.length/c),zt);if(M===0)return null;let S=[];for(let x=0;x<M;x++)S.push(Ht(g.stdout.subarray(x*c,(x+1)*c),n,m,a));return S}function Bn(e,t,i,o,a,u){if(!te("chafa"))return null;let n=L__namespace.join(t,"fr_%03d.png"),m=["-y","-i",e],p=[];if(a?(m.push("-t","6"),p.push("fps=5")):m.push("-frames:v","1"),u&&p.push(u),p.length>0&&m.push("-vf",p.join(",")),m.push(n),child_process.spawnSync("ffmpeg",m,{timeout:12e3}).status!==0)return null;let g=[];for(let c=1;c<=zt;c++){let M=L__namespace.join(t,`fr_${String(c).padStart(3,"0")}.png`),S;try{S=child_process.spawnSync("chafa",a?["-f","symbols","-s",`${i}x${o}`,"--stretch","--symbols","vhalf","--colors","full",M]:["-f","symbols","-s",`${i}x${o}`,"--stretch","--colors","full",M],{timeout:5e3,maxBuffer:8*1024*1024,encoding:"utf8"});}catch{break}if(S.status!==0||!S.stdout)break;let A=S.stdout.replace(/\x1b\[\?25[lh]/g,"").split(`
|
|
4
|
+
`).filter(I=>I.length>0);if(A.length===0)break;let N=" ".repeat(i),U=Math.floor((o-A.length)/2),j=[];for(let I=0;I<o;I++){let b=A[I-U];if(b===void 0)j.push(N);else {let $=" ".repeat(Math.max(0,i-De(b)));j.push(b+$);}}g.push(j);}return g.length>0?g:null}function Jt(e){try{let t=child_process.spawnSync("ffprobe",["-v","quiet","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0",e],{timeout:5e3,encoding:"utf8"});if(t.status!==0||!t.stdout)return null;let i=t.stdout.trim().match(/^(\d+),(\d+)/);if(!i)return null;let o=Number(i[1]),a=Number(i[2]);return o>0&&a>0?{w:o,h:a}:null}catch{return null}}function zn(e){try{let i=(child_process.spawnSync("ffmpeg",["-t","2","-i",e,"-vf","cropdetect=24:2:1","-f","null","-"],{timeout:8e3,encoding:"utf8"}).stderr??"").match(/crop=(\d+):(\d+):(\d+):(\d+)/g);if(!i||i.length===0)return null;let o=i[i.length-1],a=o.match(/crop=(\d+):(\d+):(\d+):(\d+)/),u=Number(a[1]),n=Number(a[2]);if(u<8||n<8)return null;let m=Jt(e);if(m){let p=u*n/(m.w*m.h);if(p<.55||p>.92)return null}return o}catch{return null}}function te(e){try{return J?child_process.spawnSync("where",[e],{timeout:2e3}).status===0:child_process.spawnSync("sh",["-c",'command -v -- "$1" >/dev/null 2>&1',"sh",e],{timeout:2e3}).status===0}catch{return false}}async function Dt(e,t){try{let i=await fetch(e,{signal:AbortSignal.timeout(On)});if(!i.ok)return null;let o=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(Number(i.headers.get("content-length")??"0")>t)return null;let u=Buffer.from(await i.arrayBuffer());return u.length===0||u.length>t?null:{data:u,type:o}}catch{return null}}var Se=L__namespace.join(Pt.homedir(),".config","opencrater","painter.lock"),Gn=6e3;function qt(e){try{if(!re.existsSync(Se))return;let t=JSON.parse(re.readFileSync(Se,"utf8"));if(t.pid&&t.pid!==process.pid){if(t.startedAt&&Date.now()-t.startedAt<Gn){let o=!0;try{process.kill(t.pid,0);}catch{o=!1;}o&&(e.close(),process.exit(0));}let i=!0;try{process.kill(t.pid,"SIGTERM");}catch{i=!1;}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,250);}catch{}if(t.rows>0&&t.width>0){let o="\x1B7\x1B[0m",a=" ".repeat(t.width);for(let u=0;u<t.rows;u++)o+=`\x1B[${t.row+u};${t.col}H${a}`;o+="\x1B8",e.write(o);}}}catch{}}var Ut="";function Hn(e){let t=JSON.stringify(e);if(t!==Ut){Ut=t;try{re.mkdirSync(L__namespace.dirname(Se),{recursive:!0}),re.writeFileSync(Se,JSON.stringify(e));}catch{}}}function Jn(){try{JSON.parse(re.readFileSync(Se,"utf8")).pid===process.pid&&re.unlinkSync(Se);}catch{}}var qe=process.env.OPENCRATER_DEBUG==="1";function E(...e){try{if(!qe)return;let t=`[opencrater-paint] ${e.map(i=>String(i)).join(" ")}`;console.error(t);try{re.appendFileSync(L__namespace.join(Pt.homedir(),".config","opencrater","paint.log"),`${new Date().toISOString()} ${t}
|
|
5
|
+
`);}catch{}}catch{}}function Yn(){let e=process.argv.slice(2),t=r=>{let s=e.indexOf(r);return s>=0?e[s+1]:void 0};e.includes("--debug")&&(qe=true,process.env.OPENCRATER_DEBUG="1");let i=e.includes("--persist")||process.env.OPENCRATER_WIN_PERSIST==="1",o=Number(t("--console-pid")??"0");o>0&&(process.env.OPENCRATER_WIN_CONSOLE_PID=String(o));let a=t("--payload-file"),u=process.env.OPENCRATER_PAINT;if(a)try{u=re.readFileSync(a,"utf8");}catch(r){E("payload-file unreadable:",r.message);}if(!u){E("no paint payload (env or --payload-file) \u2014 nothing to draw");return}let n;try{let r=JSON.parse(u);if(r._env&&typeof r._env=="object"){let s=process.env.OPENCRATER_WIN_CONSOLE_PID;Object.assign(process.env,r._env),s&&(process.env.OPENCRATER_WIN_CONSOLE_PID=s),process.env.OPENCRATER_DEBUG==="1"&&(qe=!0),delete r._env;}n=r;}catch(r){E("paint payload is not valid JSON:",r.message);return}let m=process.env.OPENCRATER_TTY??"/dev/tty",p,y=-1;if(J){let r=Wn();if(!r){E("Windows: could not start the console pump (powershell.exe)");return}p=r;}else {try{y=re.openSync(m,"w");}catch(r){E("could not open output device",m,"-",r.message);return}p=Tn(y);}E("painting via",J?"Windows console pump":m,"format",n.format??"text"),process.env.OPENCRATER_FLOW!=="1"&&!J&&qt(p);let g=0;if(J)g=_n()??0;else try{let r=new dt__namespace.WriteStream(y);r.columns&&(g=r.columns);}catch{}g||(g=80);let c=process.env.NO_COLOR===void 0,M=c&&qn(process.env),S=(n.format??"text").toLowerCase(),x=S==="image"||S==="logo",A=S==="gif"||S==="video",N=A?72:56,U=J?24:40;if(J)process.stdout.rows&&(U=process.stdout.rows);else try{let r=new dt__namespace.WriteStream(re.openSync(m,"w"));r.rows&&(U=r.rows);}catch{}let j=A?Math.max(8,Math.min(16,Math.floor((U-14)/2)*2)):In,I=x?5:j,b=Math.min(N,g-4);if(b<24){p.close();return}let $=b-4,F=Math.max(1,g-b-1),w=2,W=Date.now(),V=c?`${k}[2m`:"",B=c?`${k}[38;5;214m`:"",_=c?`${k}[0m`:"",R=S,Ie=Ln(process.env),Ae=process.env.OPENCRATER_FLOW==="1",Yt=process.env.OPENCRATER_MUTE==="1",se=n.apiOrigin??"https://api.opencrater.to",Ce=R==="video"?`${oe("\u25B6")} `:R==="audio"?`${oe("\u266A")} `:"",pt=false,mt=r=>{if(n.impressionId)try{fetch(`${se}/v1/events/engagement`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({impressionId:n.impressionId,events:r}),signal:AbortSignal.timeout(1500)}).catch(()=>{});}catch{}};if(n.reportImpressionUrl&&n.impressionId&&!n.replay)try{fetch(n.reportImpressionUrl,{method:"POST",headers:{"content-type":"application/json",...n.reportImpressionAuth?{authorization:`Bearer ${n.reportImpressionAuth}`}:{}},body:JSON.stringify({impressionId:n.impressionId}),signal:AbortSignal.timeout(8e3)}).catch(()=>{});}catch{}let ie=null,z=null,Oe=0,ue=0,X=null,H="none",Ue=null,Fe=null,ae=null,Be=0,gt=0,Z=null,T=0,O=0,Xt=(r,s)=>{let f=r/s,l=x?Math.min(10,Math.floor($*.35)):$;T=Math.max(4,Math.min(l,Math.round(2*f*I))),O=Math.max(2,Math.min(I,Math.round(l/(2*f))||I)),x&&(O=Math.min(O,I));let d=Math.min(1,r/(T*2),s/(O*2));d<1&&(T=Math.max(8,Math.floor(T*d)),O=Math.max(2,Math.floor(O*d)));},ge=0,Kt=()=>{let r=(n.label??"").trim(),s=(n.sponsorLabel??"").trim(),f=s.toLowerCase()===n.title.trim().toLowerCase(),l=r||(s&&!f?`Sponsored Blips \xB7 ${s}`:"Sponsored Blips"),d=[],h=he??`${se}/x/${n.impressionId}`,v=n.impressionId||n.replay&&he?Le(h,oe("\u2715")):"",G=ge>0&&!Ae?Math.max(0,Math.ceil((ge-Date.now())/1e3)):0,D=G>0?`Auto dismiss in: ${G}s `:"",P=c?G<=5?`${k}[1;38;5;196m`:G<=12?`${k}[1;38;5;178m`:`${k}[1;38;5;35m`:"",C=me(l,Math.max(8,$-2-D.length)),q=" ".repeat(Math.max(1,$-C.length-D.length-1));d.push(`${V}${C}${_}${q}${P}${D}${_}${B}${v}${_}`);let Q=c?Ie!=="none"||(process.env.COLORTERM??"").includes("truecolor")?`${k}[1;38;2;255;184;48m`:`${k}[1;38;5;214m`:"",ee=x&&O>0?$-T-2:$;x||d.push(""),d.push(`${Q}${me(n.title.toUpperCase(),ee)}${_}`);for(let Y of Rn(n.body,ee))d.push(Y);if(H!=="none"){let Y=H==="playing"?`${oe("\u23F8")} pause`:H==="paused"?`${oe("\u25B6")} play`:`${oe("\u25B6")} replay`,de=Math.max(6,Math.min(14,ee-Y.length-5)),pe="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",We="";for(let Ee=0;Ee<de;Ee++){let ln=H==="playing"?Math.abs(Math.sin(ue*.9+Ee*1.7)*.55+Math.sin(ue*.37+Ee*.53)*.45):.05;We+=pe[Math.max(0,Math.min(7,Math.floor(ln*8)))];}let an=Ue?Le(Ue,Y):Y;d.push(`${oe("\u266A")} ${B}${We}${_} ${B}${an}${_}`);}let Ve=process.env.TERM_PROGRAM??"",nn=process.env.TERM??"",Xe=Ie!=="none"||["vscode","ghostty","iTerm.app","WezTerm","Hyper","WarpTerminal","rio","Tabby"].includes(Ve)||/kitty|wezterm|alacritty|foot|rio|ghostty/i.test(nn)||process.env.WT_SESSION!==void 0||process.env.ConEmuANSI==="ON"||process.env.VTE_VERSION!==void 0,Ke=(Y,de,pe)=>c?`${k}[48;2;${de[0]};${de[1]};${de[2]};38;2;${pe[0]};${pe[1]};${pe[2]};1m ${Y} ${k}[0m`:`[ ${Y} ]`,ye=[240,178,50],Ze=[12,12,10],Qe=n.impressionId?`${se}/k/${n.impressionId}`:n.url,we=[];if(Xe){let Y=me(n.cta&&n.cta.trim()!==""?n.cta:"visit sponsor",$-6-Ce.length);we.push(Le(n.url,Ke(`${Ce}${Y} \u2192`,ye,Ze)));}else {let Y=(n.cta&&n.cta.trim()!==""?n.cta.trim():"VISIT").toUpperCase();Ce.length+Y.length+1+Qe.length<=$?we.push(Ke(`${Y} ${Ce}${Qe}`,ye,Ze)):we.push(Ke(`${Ce}${Qe}`,ye,Ze));let de=process.platform==="darwin"?"\u2318-click":"Ctrl-click",pe=me(`${oe("\u2191")} ${de} the link to open`,$),We=c?`${k}[38;2;${ye[0]};${ye[1]};${ye[2]}m`:"";we.push(`${We}${pe}${_}`);}let Ct=Fe??(n.impressionId?`${se}/r/${n.impressionId}`:null),jt=Ct&&Xe?` \xB7 ${Le(Ct,`${oe("\u2691")} report`)}`:"",sn=Xe?"dismiss: click \u2715 or npx opencrater x \xB7 opt out: npx opencrater off":"dismiss: npx opencrater x \xB7 opt out: npx opencrater off";return we.push(`${V}${me(sn,Math.max(0,$-De(jt)))}${jt}${_}`),{head:d,tail:we}},ht=0,bt=()=>{let{head:r,tail:s}=Kt(),f=`${B}\u256D${"\u2500".repeat(b-2)}\u256E${_}`,l=`${B}\u2570${"\u2500".repeat(b-2)}\u256F${_}`,d=v=>{let G=" ".repeat(Math.max(0,$-De(v)));return `${B}\u2502${_} ${v}${G} ${B}\u2502${_}`},h;if(x&&O>0&&(z||ie)){let v=$-T-2,G=r[0]??"",D=r.slice(1),P=z?z[Oe%z.length]:null;h=[f,d(G)];let C=Math.max(D.length,O);for(let q=0;q<C;q++){let Q=D[q]??"",ee=" ".repeat(Math.max(0,v-De(Q))),Ve=q<O&&P?P[q]??" ".repeat(T):" ".repeat(T);h.push(`${B}\u2502${_} ${Q}${ee} ${Ve} ${B}\u2502${_}`);}}else {h=[f,...r.map(d)];let v=Math.max(0,Math.floor(($-T)/2)),G=Math.max(0,$-T-v);if(z&&O>0){let D=z[Oe%z.length];for(let P=0;P<O;P++){let C=D[P]??" ".repeat(T);h.push(`${B}\u2502${_} ${" ".repeat(v)}${C}${" ".repeat(G)} ${B}\u2502${_}`);}}else if(ie&&O>0)for(let D=0;D<O;D++)h.push(`${B}\u2502${_} ${" ".repeat($)} ${B}\u2502${_}`);}return h.push(...s.map(d)),h.push(l),ht=s.length+1,h},ze=0,yt=`${k}[?2026h`,wt=`${k}[?2026l`,kt=0,$t=2e3,Qt=8,Ge=()=>{let r=bt();ze=Math.max(ze,r.length),Hn({pid:process.pid,row:w,col:F,width:b,rows:r.length,startedAt:W,...n.impressionId?{impressionId:n.impressionId}:{},...he?{dismissUrl:he}:{}});let s=yt+Nt,f=Date.now()<kt,l=Math.max(1,w-(f?Qt:2));for(let d=l;d<w;d++)s+=`${k}[${d};${F}H${k}[0m${" ".repeat(b)}`;for(let d=0;d<r.length;d++)s+=`${k}[${w+d};${F}H${r[d]}`;if(ie&&ue%(f?1:3)===0&&O>0){let d=x?w+2:w+r.length-ht-O,h=x?F+2+($-T):F+2+Math.max(0,Math.floor(($-T)/2));s+=`${k}[${d};${h}H${ie}`;}return s+=_t+wt,ue++,z&&z.length>1&&Oe++,s},le=()=>{p.write(Ge());},vt=()=>{let r=yt+Nt+`${k}[0m`,s=" ".repeat(b);for(let f=0;f<ze;f++)r+=`${k}[${w+f};${F}H${s}`;r+=_t+wt,p.write(r);},ce=null,Pe=null,Re=null,Te=null,he=null,K=r=>{if(E("cleanup wipe="+r+" elapsed="+(Date.now()-W)+"ms"),pt||(pt=true,mt([{type:"dwell",ms:Date.now()-W}])),ce&&clearInterval(ce),Pe&&clearInterval(Pe),Re&&clearInterval(Re),r){let s=Number(process.env.OPENCRATER_HOST_PID??0);s>1&&!J&&setTimeout(()=>{try{process.kill(s,"SIGWINCH");}catch{}},80);}if(Te){try{Te.close();}catch{}Te=null;}if(ce=null,Pe=null,Re=null,X){try{X.kill("SIGKILL");}catch{}X=null;}if(Z){try{re.rmSync(Z,{recursive:!0,force:!0});}catch{}Z=null;}if(vt(),Jn(),J){let s=false,f=()=>{s||(s=true,process.exit(0));};p.closeAndWait().then(f),setTimeout(f,1500).unref?.();return}p.close(),process.exit(0);},en=()=>{ce&&clearInterval(ce);let s=T*O>1100?200:Mt;ce=setInterval(le,z&&z.length>1?s:_e);},Me=()=>(Z||(Z=re.mkdtempSync(L__namespace.join(Pt.tmpdir(),"ocpaint-"))),Z),He=async()=>{if(n.mediaPixelUrl&&(S==="image"||S==="logo"))try{let P=await fetch(n.mediaPixelUrl,{signal:AbortSignal.timeout(2500)});if(P.ok){let C=Tt(new Uint8Array(await P.arrayBuffer()));if(C&&C.width>=4&&C.height>=2){let q=Buffer.alloc(C.width*C.height*3);for(let Q=0,ee=0;Q<C.rgba.length;Q+=4,ee+=3)q[ee]=C.rgba[Q],q[ee+1]=C.rgba[Q+1],q[ee+2]=C.rgba[Q+2];T=Math.floor(C.width/2),O=Math.floor(C.height/2),z=[Ht(q,C.width,C.height,M)];return}}}catch{}if(!n.mediaUrl)return;let r=R==="video",s=await Dt(n.mediaUrl,r?jn:Wt);if(!s||!(r?s.type.startsWith("video/"):s.type.startsWith("image/")))return;let l=L__namespace.join(Me(),"in");try{re.writeFileSync(l,s.data);}catch{return}let d=Jt(l),h=te("ffmpeg")?zn(l):null,v=h?.match(/crop=(\d+):(\d+)/),G=v?Number(v[1]):d?.w??16,D=v?Number(v[2]):d?.h??9;if(x&&te("ffmpeg")&&G>0&&D>0){let P=Math.min(G,D),C=Math.floor((G-P)/2),q=Math.floor((D-P)/2);h=`crop=${P}:${P}:${C}:${q}`,G=P,D=P,v=null;}if(Xt(G,D),!r&&Ie==="iterm2"){ie=Lt(s.data,{w:T,h:O}),ue=0;return}if(!r&&Ie==="kitty"&&s.type==="image/png"){ie=Dn(s.data,{w:T,h:O}),ue=0;return}if(r&&Ie==="iterm2"&&te("ffmpeg"))try{let P=L__namespace.join(Me(),"out.gif");if(child_process.spawnSync("ffmpeg",["-y","-i",l,"-t","6","-vf","fps=8,scale=280:-1:flags=lanczos","-loop","0",P],{timeout:12e3}).status===0){let q=re.readFileSync(P);if(q.length<=Wt){ie=Lt(q,{w:T,h:O}),ue=0;return}}}catch{}if(te("ffmpeg"))try{let P=r||s.type==="image/gif",C=Bn(l,Me(),T,O,P,h)??Fn(l,T,O,P,M,h);C&&C.length>0&&(z=C,Oe=0,en());}catch{}},Je=(r=0)=>{if(!ae)return;let{kind:s,file:f,vol:l}=ae,d=Math.max(0,r/1e3),h,v;s==="afplay"?(h="afplay",v=["-v",l.toFixed(2),f]):s==="ffplay"?(h="ffplay",v=["-nodisp","-autoexit","-volume",String(Math.round(l*100))],d>.2&&v.push("-ss",d.toFixed(2)),v.push(f)):s==="mpv"?(h="mpv",v=["--no-video","--really-quiet",`--volume=${Math.round(l*100)}`],d>.2&&v.push(`--start=${d.toFixed(2)}`),v.push(f)):s==="paplay"?(h="paplay",v=[`--volume=${Math.round(l*65536)}`,f]):(h="mpg123",v=["-q","-f",String(Math.round(32768*l))],d>.2&&v.push("-k",String(Math.round(r/26.12))),v.push(f));try{X=J?child_process.spawn(h,v,{stdio:"ignore",detached:!0,windowsHide:!0}):child_process.spawn(h,v,{stdio:"ignore"}),H="playing",gt=Date.now(),X.on("exit",()=>{H!=="paused"&&(H="ended",Be=0);});}catch{H="none";}},tn=()=>{try{H==="playing"&&X?(H="paused",Be+=Date.now()-gt,X.kill("SIGKILL"),X=null,mt([{type:"sound_muted"}])):H==="paused"?ae?.canSeek&&Je(Be):H==="ended"&&Je(0);}catch{}le();},be=async(r=n.mediaUrl)=>{if(!r||Yt)return;let s=L__namespace.join(Pt.homedir(),".config","opencrater","audio-plays.json");try{let l=[];try{l=JSON.parse(re.readFileSync(s,"utf8")),Array.isArray(l)||(l=[]);}catch{}let d=Ot(Date.now(),l);if(re.writeFileSync(s,JSON.stringify(d.next)),!d.play)return}catch{}let f=await Dt(r,An);if(!(!f||!f.type.startsWith("audio/")))try{let l=f.type.includes("wav")?"wav":f.type.includes("ogg")?"ogg":"mp3",d=L__namespace.join(Me(),`ad.${l}`);re.writeFileSync(d,f.data);let h=At(new Date().getHours());if(te("ffplay"))ae={kind:"ffplay",file:d,vol:h,canSeek:!0};else if(!J&&te("mpv"))ae={kind:"mpv",file:d,vol:h,canSeek:!0};else if(process.platform==="darwin"&&te("afplay"))ae={kind:"afplay",file:d,vol:h,canSeek:!1};else if(!J&&te("mpg123")&&l==="mp3")ae={kind:"mpg123",file:d,vol:h,canSeek:!0};else if(!J&&l!=="mp3"&&te("paplay"))ae={kind:"paplay",file:d,vol:h,canSeek:!1};else return;Je(),setTimeout(()=>{try{X?.kill("SIGKILL");}catch{}(H==="playing"||H==="paused")&&(H="ended");},Et).unref?.();}catch{}},St=()=>{if(!n.impressionId||n.replay)return;let r=L__namespace.join(Pt.homedir(),".config","opencrater","dismiss.signal"),s=Date.now();Pe=setInterval(()=>{try{let f=re.readFileSync(r,"utf8"),l=JSON.parse(f),d=typeof l.at=="number"&&l.at>=s-5e3,h=!l.impressionId||l.impressionId===n.impressionId;if(d&&h){try{re.unlinkSync(r);}catch{}Ne(n.campaignId),fetch(`${se}/x/${n.impressionId}`,{signal:AbortSignal.timeout(1500)}).catch(()=>{}),K(!0);return}}catch{}(async()=>{try{let f=await fetch(`${se}/v1/events/dismissed/${n.impressionId}`,{signal:AbortSignal.timeout(1200)});if(!f.ok)return;(await f.json()).dismissed&&(Ne(n.campaignId),K(!0));}catch{}})();},Cn);},xt=()=>{if(Ae)return;let r=L__namespace.join(Pt.homedir(),".config","opencrater","activity.signal"),s=Date.now(),f=1500;Re=setInterval(()=>{try{let l=re.statSync(r).mtimeMs;l>s+f&&l>Date.now()-$t&&(kt=l+$t,le());}catch{}},150);};if(J){(async()=>{let r=p.size?await p.size:null;if(r&&r.cols>=24&&(g=r.cols,b=Math.min(N,g-4),$=b-4,F=Math.max(1,g-b-1),E("windows geometry from pump:","cols",g,"width",b,"col",F,"ownerPid",r.pid)),R==="image"||R==="logo"||R==="gif"||R==="video"?await He():R==="audio"&&await be(),n.audioUrl&&R!=="audio"&&be(n.audioUrl),i){let d=Math.min(Math.max(n.durationMs??at,3e3),12e4);if(ge=Date.now()+d,a)try{re.unlinkSync(a);}catch{}qt(p);let h=z,v=!!(h&&h.length>1);le(),ce=setInterval(le,v?Mt:_e),xt(),It(),St(),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),d);return}let s=r?.pid??0;s>0&&Nn(n,s)&&(p.close(),process.exit(0)),E("no job-escape (ownerPid",s,") \u2014 bounded toast fallback");let f=Number(process.env.OPENCRATER_WIN_HOLD_MS),l=f>0?f:Math.min(n.durationMs??at,5e3);if(ge=Date.now()+l,p.write(Ge()),await new Promise(d=>{let h=setInterval(()=>{if(Date.now()>=ge){clearInterval(h),d();return}p.write(Ge());},_e);}),vt(),Z)try{re.rmSync(Z,{recursive:!0,force:!0});}catch{}await p.closeAndWait(),process.exit(0);})();return}if(Ae){(async()=>{R==="image"||R==="logo"||R==="gif"||R==="video"?await He():R==="audio"&&await be(),n.audioUrl&&R!=="audio"&&be(n.audioUrl);let r=z;r&&r.length>1&&(z=[r[0]]);let s=bt(),f=" ".repeat(Math.max(0,g-b-2)),l=`\r
|
|
6
|
+
`;for(let h of s)l+=`${f}${h}\r
|
|
7
|
+
`;ie&&O>0&&(l+=`${f}${ie}\r
|
|
8
|
+
`),p.write(l);let d=X?Et+1e3:250;setTimeout(()=>{if(X)try{X.kill("SIGKILL");}catch{}if(Z)try{re.rmSync(Z,{recursive:!0,force:!0});}catch{}p.close(),process.exit(0);},d);})();return}le(),ce=setInterval(le,_e);function It(){if(!(!n.impressionId&&!n.replay||Ae))try{let r=crypto.randomBytes(8).toString("hex"),s=Ft__namespace.createServer((f,l)=>{if(!f.url||!f.url.includes(r)){l.writeHead(404).end();return}if(f.url.startsWith("/p/")){Rt(n.campaignId),n.impressionId?(l.writeHead(302,{location:`${se}/r/${n.impressionId}`}),l.end()):(l.writeHead(200,{"content-type":"text/html; charset=utf-8"}),l.end(`<!doctype html><meta charset=utf-8><title>Ad reported</title><body style="font-family:ui-monospace,monospace;background:#0c0c0a;color:#e9e6da;display:grid;place-items:center;height:100vh;margin:0"><p>\u2691 Reported \u2014 you won't see this Blip again. This tab closes itself.</p><script>setTimeout(function(){window.close()},600);</script>`)),setTimeout(()=>K(!0),150);return}if(f.url.startsWith("/a/")){tn(),l.writeHead(200,{"content-type":"text/html; charset=utf-8"}),l.end('<!doctype html><meta charset=utf-8><title>Audio</title><body style="font-family:ui-monospace,monospace;background:#0c0c0a;color:#e9e6da;display:grid;place-items:center;height:100vh;margin:0"><p>\u266A toggled \u2014 this tab closes itself.</p><script>setTimeout(function(){window.close()},300);</script>');return}l.writeHead(200,{"content-type":"text/html; charset=utf-8"}),l.end('<!doctype html><meta charset=utf-8><title>Ad dismissed</title><body style="font-family:ui-monospace,monospace;background:#0c0c0a;color:#e9e6da;display:grid;place-items:center;height:100vh;margin:0"><p>\u2715 Ad dismissed \u2014 this tab closes itself.</p><script>setTimeout(function(){window.close()},400);</script>'),Ne(n.campaignId),!n.replay&&n.impressionId&&fetch(`${se}/x/${n.impressionId}`,{signal:AbortSignal.timeout(2e3)}).catch(()=>{}),setTimeout(()=>K(!0),150);});s.unref(),s.listen(0,"127.0.0.1",()=>{let f=s.address();f&&typeof f=="object"&&(he=`http://127.0.0.1:${f.port}/x/${r}`,Ue=`http://127.0.0.1:${f.port}/a/${r}`,Fe=`http://127.0.0.1:${f.port}/p/${r}`,Te=s,le());}),s.on("error",()=>{he=null,Fe=null;});}catch{}}try{re.writeFileSync(L__namespace.join(Pt.homedir(),".config","opencrater","last-ad.json"),JSON.stringify({payload:n,at:Date.now()}));}catch{}It(),St(),xt(),R==="image"||R==="logo"||R==="gif"||R==="video"?He():R==="audio"&&be(),n.audioUrl&&R!=="audio"&&be(n.audioUrl);let Ye=n.durationMs??(R==="video"?18e3:R==="audio"?16e3:at);ge=Date.now()+Ye,setTimeout(()=>K(true),Ye),process.on("SIGTERM",()=>K(true)),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),Ye+5e3).unref?.();}typeof et<"u"&&typeof module<"u"&&et.main===module&&Yn();
|
|
9
|
+
exports.windowsVtOk=hi;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencrater",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "OpenCrater — sponsor cards for AI coding terminals (Claude Code, Codex, Gemini CLI, Copilot CLI). One command, auto-wires every host, opt out anytime.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"opencrater",
|