publishport-opencli 1.0.26 → 1.0.28

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.
Files changed (40) hide show
  1. package/cli-manifest.json +308 -18
  2. package/clis/_shared/video-publish.js +2 -1
  3. package/clis/baijiahao/article.js +17 -1
  4. package/clis/bilibili/coin.js +1 -1
  5. package/clis/bilibili/danmaku.js +5 -0
  6. package/clis/bilibili/favorite-add.js +1 -1
  7. package/clis/bilibili/upload.js +1 -1
  8. package/clis/bilibili/video-edit.js +3 -0
  9. package/clis/bilibili/video.js +1 -1
  10. package/clis/jike/api.js +2 -2
  11. package/clis/jike/comments.js +1 -0
  12. package/clis/jike/delete.js +1 -0
  13. package/clis/jike/topic.js +1 -20
  14. package/clis/kuaishou/auth.js +8 -1
  15. package/clis/kuaishou/publish.js +6 -6
  16. package/clis/nowcoder/comment.js +1 -1
  17. package/clis/nowcoder/comments.js +1 -1
  18. package/clis/nowcoder/detail.js +4 -2
  19. package/clis/nowcoder/dm-list.js +1 -1
  20. package/clis/nowcoder/dm-read.js +1 -1
  21. package/clis/nowcoder/dm-send.js +1 -1
  22. package/clis/nowcoder/drafts.js +1 -1
  23. package/clis/nowcoder/experience.js +4 -2
  24. package/clis/nowcoder/inbox.js +1 -1
  25. package/clis/nowcoder/like.js +1 -1
  26. package/clis/nowcoder/my.js +1 -1
  27. package/clis/nowcoder/recommend.js +1 -1
  28. package/clis/nowcoder/search.js +3 -2
  29. package/clis/nowcoder/utils.js +14 -17
  30. package/clis/nowcoder/watch.js +1 -1
  31. package/clis/quora/create-answer.js +12 -8
  32. package/clis/reddit/comment.js +28 -7
  33. package/clis/reddit/upvote.js +21 -5
  34. package/clis/xiaohongshu/publish.js +1 -1
  35. package/clis/zhihu/comment.js +2 -2
  36. package/dist/src/cli.js +23 -23
  37. package/dist/src/commands/auth.js +3 -3
  38. package/dist/src/doctor.js +1 -1
  39. package/dist/src/pipeline/template.js +3 -1
  40. package/package.json +1 -1
package/dist/src/cli.js CHANGED
@@ -1,7 +1,7 @@
1
- import*as O from"node:fs";import*as me from"node:os";import*as k from"node:path";import{fileURLToPath as no}from"node:url";import{Command as Re,InvalidArgumentError as gt,Option as so}from"commander";import io from"js-yaml";import{findPackageRoot,getBuiltEntryCandidates as ao}from"./package-paths.js";import{fullName as Je,getRegistry as Se,strategyLabel as ht}from"./registry.js";import{serializeCommand as co,formatArgSummary as lo}from"./serialization.js";import{render as xe}from"./output.js";import{PKG_VERSION as Ee}from"./version.js";import{printCompletionScript as uo}from"./completion.js";import{loadExternalClis as Me,executeExternalCli as mo,installExternalCli as po,registerExternalCli as fo,isBinaryInstalled as je,formatExternalCliLabel as wt}from"./external.js";import{listOpenCliSkills as go,readOpenCliSkill as ho}from"./skills.js";import{registerAllCommands as wo}from"./commanderAdapter.js";import{classifyAdapter as yt,formatRootAdapterHelpText as yo,installCommanderNamespaceStructuredHelp as pe,installStructuredHelp as bo,leadingPositionalFromUsage as So,rootHelpData as xo}from"./help.js";import{EXIT_CODES as f,getErrorMessage as M,BrowserConnectError as vo,CliError as Ue,CommandExecutionError as Ro,toEnvelope as Eo}from"./errors.js";import{TargetError as bt}from"./browser/target-errors.js";import{resolveTargetJs as Co,getTextResolvedJs as _o,getValueResolvedJs as Oo,getAttributesResolvedJs as $o,selectResolvedJs as ko,isAutocompleteResolvedJs as No}from"./browser/target-resolver.js";import{buildFindJs as Ao,buildSemanticFindJs as St,isFindError as xt}from"./browser/find.js";import{inferShape as vt}from"./browser/shape.js";import{assignKeys as Rt}from"./browser/network-key.js";import{DEFAULT_TTL_MS as Et,findEntry as To,loadNetworkCache as Io,saveNetworkCache as Po}from"./browser/network-cache.js";import{NETWORK_INTERCEPTOR_JS as Ce}from"./browser/network-interceptor.js";import{parseFilter as Jo,shapeMatchesFilter as Mo}from"./browser/shape-filter.js";import{buildHtmlTreeJs as jo}from"./browser/html-tree.js";import{buildExtractHtmlJs as Uo,runExtractFromHtml as Do}from"./browser/extract.js";import{analyzeSite as Go}from"./browser/analyze.js";import{registerAuthCommands as Bo}from"./commands/auth.js";import{daemonRestart as Fo,daemonStatus as Lo,daemonStop as zo,daemonWarm as Wo}from"./commands/daemon.js";import{log as Z}from"./logger.js";import{bindTab as Ho,BrowserCommandError as Ct,sendCommand as Vo}from"./browser/daemon-client.js";import{fetchDaemonStatus as qo}from"./browser/daemon-transport.js";import{aliasForContextId as _t,listManagedProfiles as De,loadProfileConfig as Xo,renameProfile as Ko,resolveProfile as Ot,resolveProfileContextId as Zo,setDefaultProfile as Yo}from"./browser/profile.js";import{createManagedProfile as Qo,ensureManagedChrome as Ge,isManagedChromeRunning as er,removeManagedProfile as tr,stopManagedChrome as or,resolveManagedOpts as $t,updateManagedProfileConfig as rr}from"./browser/managed-chrome.js";import{testProxy as nr,parseProxyUrl as Be}from"./browser/proxy-test.js";import{formatDaemonVersion as sr,isDaemonStale as ir}from"./browser/daemon-version.js";import{DEFAULT_BROWSER_CONNECT_TIMEOUT as Fe}from"./browser/config.js";const Le=no(import.meta.url),ar='Target tab/page identity returned by "browser open", "browser tab new", or "browser tab list"',kt=1000;function _e(a,c){if(a===void 0||a===null||a==="")return null;const i=String(a).trim(),p=/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(i);if(!p)return{error:`--${c} must be a duration like 500ms, 30s, 2m, got "${i}"`};const b=Number.parseFloat(p[1]),g=p[2]??"ms";return Math.round(b*(g==="h"?3600000:g==="m"?60000:g==="s"?1000:1))}function ze(a){return typeof a==="number"&&Number.isFinite(a)&&a>0?a:Date.now()}function fe(a){if(typeof a!=="number"||!Number.isFinite(a)||a<=0)return;return new Date(a).toISOString()}function We(a,c,i=Date.now()){const p=c.sinceMs!=null?i-c.sinceMs:void 0,b=c.untilMs!=null?i-c.untilMs:void 0;return a.filter((g)=>{const N=g.timestamp??i;if(p!==void 0&&N<p)return!1;if(b!==void 0&&N>b)return!1;return!0})}export function selectFreshByTimestamp(a,c){const i=a.filter((b)=>Number(b.timestamp??0)>c),p=i.length>0?Math.max(c,...i.map((b)=>Number(b.timestamp??0)).filter(Number.isFinite)):c;return{fresh:i,lastSeenTs:p}}async function ge(a){if(a.readNetworkCapture){const i=await a.readNetworkCapture();if(Array.isArray(i)&&i.length>0)return i.map((p)=>{const b=p.responsePreview??null;let g=null;if(b)try{g=JSON.parse(b)}catch{g=b}const N=typeof p.responseBodyFullSize==="number"?p.responseBodyFullSize:b?b.length:0,v=p.responseBodyTruncated===!0;return{url:p.url||"",method:p.method||"GET",status:p.responseStatus||0,size:N,ct:p.responseContentType||"",body:g,bodyFullSize:N,bodyTruncated:v,timestamp:ze(p.timestamp),...p.channel?{channel:p.channel}:{},...p.direction?{direction:p.direction}:{},...p.eventName?{eventName:String(p.eventName)}:{},...p.eventId?{eventId:String(p.eventId)}:{}}})}const c=await a.evaluate("(function(){ var out = window.__opencli_net || []; window.__opencli_net = []; return JSON.stringify(out); })()");try{return JSON.parse(c).map((p)=>({...p,timestamp:ze(p.timestamp)}))}catch{if(process.env.OPENCLI_VERBOSE)Z.warn(`[network] Failed to parse interceptor buffer: ${typeof c==="string"?c.slice(0,200):String(c)}`);return[]}}const Nt=4000;function cr(a){if(typeof a!=="string")return a??null;return a.length>Nt?`${a.slice(0,Nt)}…[truncated ${a.length} chars]`:a}function At(a){return a.filter((c)=>{if(c.channel==="websocket"||c.channel==="eventsource")return!0;const i=c.ct?.toLowerCase()??"";return(i.includes("json")||i.includes("xml")||i.includes("text/plain")||i.includes("javascript"))&&!/\.(js|css|png|jpg|gif|svg|woff|ico|map)(\?|$)/i.test(c.url)&&!/analytics|tracking|telemetry|beacon|pixel|gtag|fbevents/i.test(c.url)})}const lr={invalid_args:f.USAGE_ERROR,invalid_filter:f.USAGE_ERROR,invalid_max_body:f.USAGE_ERROR};function q(a,c,i={}){console.log(JSON.stringify({error:{code:a,message:c,...i}},null,2));process.exitCode=lr[a]??f.GENERIC_ERROR}const dr="Site sitemap available. For navigation context, use the opencli-browser-sitemap skill; treat browser state as truth if it disagrees.";function ur(a,c=Se()){let i;try{i=new URL(a).hostname.toLowerCase().replace(/^www\./,"")}catch{return[]}const p=new Map;for(const v of c.values()){if(!v.domain)continue;let E=v.domain.toLowerCase().trim();try{E=new URL(E.includes("://")?E:`https://${E}`).hostname.toLowerCase()}catch{E=E.split("/")[0]??E}E=E.replace(/^www\./,"");if(!E)continue;if(i===E||i.endsWith(`.${E}`))p.set(v.site,Math.max(p.get(v.site)??0,E.length))}const b=[...p.entries()].sort((v,E)=>E[1]-v[1]||v[0].localeCompare(E[0])).map(([v])=>v),g=i.split(".").filter(Boolean),N=g.length>=2?g[g.length-2]:g[0];return[...new Set([...b,...N?[N]:[]])]}function Tt(a,c){return a.find((i)=>c(i))}function mr(a,c){const i=a.replace(/[^a-zA-Z0-9_-]+/g,"-");if(!i)return{};const p=k.join(c.homeDir,".ppcli","sites",i);return{local:Tt([k.join(p,"sitemap"),k.join(p,"sitemap.md")],c.fileExists),global:Tt([k.join(c.packageRoot,"sitemaps",i),k.join(c.packageRoot,"sitemaps",`${i}.md`)],c.fileExists)}}export function resolveSitemapAvailabilityForUrl(a,c={}){const i=c.homeDir??me.homedir(),p=c.packageRoot??findPackageRoot(Le),b=c.registry??Se(),g=c.fileExists??O.existsSync;for(const N of ur(a,b)){const v=mr(N,{homeDir:i,packageRoot:p,fileExists:g});if(!v.local&&!v.global)continue;const E=v.local&&v.global?"local+global":v.local?"local":"global";return{site:N,available:!0,source:E,hint:dr,paths:v}}return null}function It(a){const c=a.replace(/[^a-zA-Z0-9_-]+/g,"_");return k.join(Jt(),"browser-sitemap-hints",`${c}.json`)}function Pt(a){try{const c=JSON.parse(O.readFileSync(It(a),"utf-8"));if(c&&typeof c==="object"&&Array.isArray(c.seenSites))return{seenSites:c.seenSites.filter((i)=>typeof i==="string"),updatedAt:typeof c.updatedAt==="string"?c.updatedAt:new Date(0).toISOString()}}catch{}return{seenSites:[],updatedAt:new Date(0).toISOString()}}function pr(a,c){const i=Pt(a);if(!i.seenSites.includes(c))i.seenSites.push(c);const p=It(a);O.mkdirSync(k.dirname(p),{recursive:!0});O.writeFileSync(p,JSON.stringify({seenSites:i.seenSites,updatedAt:new Date().toISOString()}),"utf-8")}function fr(a,c,i){const p=resolveSitemapAvailabilityForUrl(a);if(!p)return null;if(!i.oncePerSession)return p;if(Pt(c).seenSites.includes(p.site))return null;pr(c,p.site);return p}export function checkSiteMemory(a){const c=k.join(me.homedir(),".ppcli","sites",a),i=k.join(c,"endpoints.json"),p=k.join(c,"notes.md");let b=0,g=O.existsSync(i);if(g)try{const v=JSON.parse(O.readFileSync(i,"utf-8"));if(v&&typeof v==="object"&&!Array.isArray(v))b=Object.keys(v).length;else if(Array.isArray(v))b=v.length}catch{g=!1}const N=O.existsSync(p);return{ok:g&&b>0&&N,siteDir:c,endpoints:{present:g,count:b,path:i},notes:{present:N,path:p}}}export function printSiteMemoryReport(a,c){if(a.ok){console.log(` ✓ Memory: endpoints.json (${a.endpoints.count}), notes.md present at ${a.siteDir}`);return}const i=c?"✗":"⚠",p=[];if(!a.endpoints.present)p.push("endpoints.json");else if(a.endpoints.count===0)p.push("endpoints.json (empty)");if(!a.notes.present)p.push("notes.md");console.log(` ${i} Memory: missing ${p.join(", ")} under ${a.siteDir}`);console.log(" Write the endpoint you just verified + a 1-line session note so the next agent starts from minute 0, not minute 95.");if(!c)console.log(" (Re-run with --strict-memory to fail instead of warn.)")}export function normalizeVerifyRows(a){if(Array.isArray(a))return a.map((c)=>c&&typeof c==="object"?c:{value:c});if(a&&typeof a==="object"){const c=a;for(const i of["rows","items","data","results"])if(Array.isArray(c[i]))return c[i].map((p)=>p&&typeof p==="object"?p:{value:p});return[c]}return[]}export function renderVerifyPreview(a,c={}){const i=c.maxRows??10,p=c.maxCols??6,b=c.cellMax??40;if(a.length===0)return" (no rows)";const g=Array.from(new Set(a.flatMap((T)=>Object.keys(T)))),N=g.slice(0,p),v=a.slice(0,i),E=(T)=>{if(T===null||T===void 0)return"";return(typeof T==="object"?JSON.stringify(T):String(T)).replace(/\s+/g," ").slice(0,b)},Y=N.map((T)=>Math.max(T.length,...v.map((X)=>E(X[T]).length))),oe=(T)=>T.map((X,S)=>X.padEnd(Y[S])).join(" "),V=[];V.push(` ${oe(N)}`);V.push(` ${Y.map((T)=>"-".repeat(T)).join(" ")}`);for(const T of v)V.push(` ${oe(N.map((X)=>E(T[X])))}`);if(a.length>i)V.push(` ... and ${a.length-i} more row(s)`);if(g.length>p)V.push(` (${g.length-p} more column(s) hidden)`);return V.join(`
2
- `)}function Jt(){return process.env.OPENCLI_CACHE_DIR||k.join(me.homedir(),".ppcli","cache")}function Mt(a){const c=a.replace(/[^a-zA-Z0-9_-]+/g,"_");return k.join(Jt(),"browser-state",`${c}.json`)}function jt(a){try{const c=O.readFileSync(Mt(a),"utf-8"),i=JSON.parse(c);return i&&typeof i==="object"?i:null}catch{return null}}function he(a,c){const i=Mt(c);if(!a){O.rmSync(i,{force:!0});return}O.mkdirSync(k.dirname(i),{recursive:!0});O.writeFileSync(i,JSON.stringify({defaultPage:a,updatedAt:new Date().toISOString()}),"utf-8")}function gr(a,c){return a.some((i)=>{return typeof i==="object"&&i!==null&&"page"in i&&typeof i.page==="string"&&i.page===c})}async function He(a,c,i){const p=c.trim();if(!p)return;let b;try{b=await a.tabs()}catch(g){if(i.source==="saved"){he(void 0,i.scope);return}throw Error(`Target tab ${p} could not be validated in the current browser session. The Browser Bridge session may have restarted; re-run "ppcli browser tab list" and choose a current target.`,{cause:g})}if(Array.isArray(b)&&gr(b,p))return p;if(i.source==="saved"){he(void 0,i.scope);return}throw Error(`Target tab ${p} is not part of the current browser session. The Browser Bridge session may have restarted; re-run "ppcli browser tab list" and choose a current target.`)}function Oe(a,c){return c?`${c}:${a}`:a}async function hr(a,c){const i=jt(c)?.defaultPage?.trim();if(!i)return;return He(a,i,{scope:c,source:"saved"})}async function wr(a,c,i,p={}){const b=Ot(p.profile);if(b.kind==="managed"){if(c)throw Error(`托管环境「${b.name}」是单窗口复用标签模型,不支持 --tab 定位。直接省略 --tab 即可。`);const T=p.windowMode??Ve(void 0,"background"),{ensureManagedChrome:X}=await import("./browser/managed-chrome.js"),{CDPBridge:S}=await import("./browser/cdp.js"),{generateFingerprintJs:ve}=await import("./browser/fingerprint.js"),ie=await X(b.name,b.entry,{windowMode:T}),re=b.entry.fingerprint,ae=b.entry.proxy;return new S().connect({timeout:Fe,session:a,surface:"browser",cdpEndpoint:ie,contextId:b.name,windowMode:T,...re?.enabled?{initScript:ve(re)}:{},...ae?.username?{proxyAuth:{username:ae.username,password:ae.password??""}}:{}})}const{BrowserBridge:g}=await import("./browser/index.js"),N=new g,v=process.env.OPENCLI_BROWSER_IDLE_TIMEOUT,E=v?parseInt(v,10):void 0,Y=await N.connect({timeout:Fe,session:a,surface:"browser",...i&&{contextId:i},...E&&E>0&&{idleTimeout:E},windowMode:p.windowMode??Ve(void 0,"background")}),oe=Oe(a,i),V=c?await He(Y,c,{scope:oe,source:"explicit"}):await hr(Y,oe);if(V){if(!Y.setActivePage)throw Error("This browser session does not support explicit tab targeting");Y.setActivePage(V)}return Y}function Ve(a,c){const i=qe(a,"window");if(i!==void 0&&i!==""){if(i==="foreground"||i==="background")return i;throw Error(`--window must be one of: foreground, background. Received: "${String(i)}"`)}const p=process.env.OPENCLI_WINDOW;if(p!==void 0&&p!==""){if(p==="foreground"||p==="background")return p;throw Error(`OPENCLI_WINDOW must be one of: foreground, background. Received: "${p}"`)}return c}function R(a){return a.option("--tab <targetId>",ar)}function yr(a){if(!a)return;const c=a.optsWithGlobals?a.optsWithGlobals():a.opts();return typeof c.tab==="string"&&c.tab.trim()?c.tab.trim():void 0}function qe(a,c){let i=a;while(i){const p=i.opts();if(Object.prototype.hasOwnProperty.call(p,c)&&p[c]!==void 0)return p[c];i=i.parent}return}function Ut(a){const c=qe(a,"session");if(typeof c==="string"&&c.trim())return c.trim();throw Error("<session> is a required positional argument: ppcli browser <session> <command>")}function Dt(a){return Zo(Xe(a))}function Xe(a){const c=qe(a,"profile");return typeof c==="string"&&c.trim()?c.trim():void 0}function Ke(a){const c=a.session;if(typeof c==="string"&&c.trim())return c.trim();throw Error("Browser page is missing a session")}function $e(a){const c=a.contextId;return Oe(Ke(a),typeof c==="string"&&c.trim()?c.trim():void 0)}function br(a){return typeof a==="string"?a:JSON.stringify(a,null,2)}function Sr(a,c){const i=br(a),p=i.match(/^interactive:\s*(\d+)\s*$/m);return{ok:!0,chars:i.length,bytes:Buffer.byteLength(i,"utf8"),lines:i?i.split(/\r?\n/).length:0,approx_tokens:Math.ceil(i.length/4),refs:(i.match(/(^|\n)\s*\[\d+\]/g)??[]).length,frame_sections:(i.match(/(^|\n)frame /g)??[]).length,...p?{interactive:Number(p[1])}:{},elapsed_ms:c}}async function Gt(a,c){const i=Date.now();try{const p=await a.snapshot({viewportExpand:2000,source:c});return Sr(p,Date.now()-i)}catch(p){return{ok:!1,elapsed_ms:Date.now()-i,error:{...p instanceof Error&&"code"in p?{code:String(p.code)}:{},message:p instanceof Error?p.message:String(p)}}}}function Bt(a,c){if(typeof a==="string"&&a.trim())return a.trim();const i=c instanceof Re?c.opts().tab:c?.tab;if(typeof i==="string"&&i.trim())return i.trim();return}function Ft(a,c,i){if(a===void 0)return i;const p=parseInt(a,10);if(Number.isNaN(p)||p<=0){console.error(`[cli] Invalid ${c}="${a}", using default ${i}`);return i}return p}function Lt(a,c){if(!/^\d+$/.test(a))throw new gt(`--${c} must be a positive integer (got "${a}")`);const i=parseInt(a,10);if(i<=0)throw new gt(`--${c} must be a positive integer (got "${a}")`);return i}function xr(a){if(a.verbose)process.env.OPENCLI_VERBOSE="1"}function vr(a){return[...new Set(a.commands.map((c)=>c.name()))].sort((c,i)=>c.localeCompare(i)).join(", ")}function Rr(a){for(const c of a.commands){if(c.commands.length===0)continue;const i=vr(c);if(i)c.description(i)}}export function createProgram(a,c){const i=new Re;i.name("ppcli").description("Make any website your CLI. Zero setup. AI-powered.").version(Ee).option("--profile <name>","Chrome profile/context alias for Browser Bridge commands").enablePositionalOptions();i.command("list").description("List all available CLI commands").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((e)=>{const t=Se(),o=[...new Set(t.values())].sort((m,y)=>Je(m).localeCompare(Je(y))),r=e.format,n=r==="json"||r==="yaml";if(r!=="table"){const m=n?o.map(co):o.map((y)=>({command:Je(y),site:y.site,name:y.name,aliases:y.aliases?.join(", ")??"",description:y.description,access:y.access,strategy:ht(y),browser:!!y.browser,args:lo(y.args)}));xe(m,{fmt:r,columns:["command","site","name","aliases","description","access","strategy","browser","args",...n?["columns","domain"]:[]],title:"ppcli/list",source:"ppcli list"});return}const s=new Map,l=new Map;for(const m of o){const y=yt(m.domain)==="app"?s:l,x=y.get(m.site)??[];x.push(m);y.set(m.site,x)}const d=(m,y)=>{console.log(` ${m}`);for(const x of y){const _=ht(x),D=_==="public"?"[public]":`[${_}]`,j=x.aliases?.length?` (aliases: ${x.aliases.join(", ")})`:"";console.log(` ${x.name} ${D}${j}${x.description?` — ${x.description}`:""}`)}console.log()};console.log();console.log(" ppcli"+" — available commands");console.log();if(s.size>0){console.log(" App adapters");console.log();for(const[m,y]of s)d(m,y)}if(l.size>0){console.log(" Site adapters");console.log();for(const[m,y]of l)d(m,y)}const u=Me();if(u.length>0){console.log(" external CLIs");for(const m of u){const x=je(m.binary)?"[installed]":"[auto-install]";console.log(` ${wt(m)} ${x}${m.description?` — ${m.description}`:""}`)}console.log()}console.log(` ${o.length} built-in commands across ${s.size} apps + ${l.size} sites, ${u.length} external CLIs`);console.log()});i.command("validate").description("Validate CLI definitions").argument("[target]","site or site/name").action(async(e)=>{const{validateClisWithTarget:t,renderValidationReport:o}=await import("./validate.js");console.log(o(t([a,c],e)))});i.command("verify").description("Validate + smoke test").argument("[target]").option("--smoke","Run smoke tests",!1).action(async(e,t)=>{const{verifyClis:o,renderVerifyReport:r}=await import("./verify.js"),n=await o({builtinClis:a,userClis:c,target:e,smoke:t.smoke});console.log(r(n));process.exitCode=n.ok?f.SUCCESS:f.GENERIC_ERROR});const p=i.command("skills").description("Read bundled ppcli skills");p.command("list").description("List bundled ppcli-* skills").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((e)=>{const t=go();xe(t,{fmt:e.format,fmtExplicit:!!e.format,columns:["name","description","version","path"],title:"ppcli/skills/list",source:"ppcli skills list"})});p.command("read").description("Print an ppcli-* skill's SKILL.md or reference file").argument("<skill>","Skill name, or skill/path like opencli-browser/references/foo.md").argument("[path]","Path under the skill directory").option("--json","Output a JSON envelope instead of raw markdown",!1).action((e,t,o)=>{let r;try{r=ho(e,t??"")}catch(n){console.error(`Error: ${M(n)}`);if(n instanceof Ue&&n.hint)console.error(`Hint: ${n.hint}`);process.exitCode=n instanceof Ue?n.exitCode:f.GENERIC_ERROR;return}if(o.json){console.log(JSON.stringify(r,null,2));return}process.stdout.write(r.content);if(!r.content.endsWith(`
1
+ import*as k from"node:fs";import*as pe from"node:os";import*as O from"node:path";import{fileURLToPath as no}from"node:url";import{Command as Ce,InvalidArgumentError as wt,Option as so}from"commander";import io from"js-yaml";import{findPackageRoot,getBuiltEntryCandidates as ao}from"./package-paths.js";import{fullName as je,getRegistry as ve,strategyLabel as yt}from"./registry.js";import{serializeCommand as co,formatArgSummary as lo}from"./serialization.js";import{render as Re}from"./output.js";import{PKG_VERSION as _e}from"./version.js";import{printCompletionScript as uo}from"./completion.js";import{loadExternalClis as Ue,executeExternalCli as mo,installExternalCli as po,registerExternalCli as fo,isBinaryInstalled as De,formatExternalCliLabel as bt}from"./external.js";import{listOpenCliSkills as go,readOpenCliSkill as ho}from"./skills.js";import{registerAllCommands as wo}from"./commanderAdapter.js";import{classifyAdapter as St,formatRootAdapterHelpText as yo,installCommanderNamespaceStructuredHelp as fe,installStructuredHelp as bo,leadingPositionalFromUsage as So,rootHelpData as xo}from"./help.js";import{EXIT_CODES as f,getErrorMessage as j,BrowserConnectError as vo,CliError as Ge,CommandExecutionError as Ro,toEnvelope as Eo}from"./errors.js";import{TargetError as xt}from"./browser/target-errors.js";import{resolveTargetJs as Co,getTextResolvedJs as _o,getValueResolvedJs as Oo,getAttributesResolvedJs as $o,selectResolvedJs as ko,isAutocompleteResolvedJs as No}from"./browser/target-resolver.js";import{buildFindJs as Ao,buildSemanticFindJs as vt,isFindError as Rt}from"./browser/find.js";import{inferShape as Et}from"./browser/shape.js";import{assignKeys as Ct}from"./browser/network-key.js";import{DEFAULT_TTL_MS as _t,findEntry as To,loadNetworkCache as Io,saveNetworkCache as Po}from"./browser/network-cache.js";import{NETWORK_INTERCEPTOR_JS as Oe}from"./browser/network-interceptor.js";import{parseFilter as Jo,shapeMatchesFilter as Mo}from"./browser/shape-filter.js";import{buildHtmlTreeJs as jo}from"./browser/html-tree.js";import{buildExtractHtmlJs as Uo,runExtractFromHtml as Do}from"./browser/extract.js";import{analyzeSite as Go}from"./browser/analyze.js";import{registerAuthCommands as Bo}from"./commands/auth.js";import{daemonRestart as Fo,daemonStatus as Lo,daemonStop as zo,daemonWarm as Wo}from"./commands/daemon.js";import{log as Y}from"./logger.js";import{bindTab as Ho,BrowserCommandError as Ot,sendCommand as Vo}from"./browser/daemon-client.js";import{fetchDaemonStatus as qo}from"./browser/daemon-transport.js";import{aliasForContextId as $t,listManagedProfiles as Be,loadProfileConfig as Xo,renameProfile as Ko,resolveProfile as kt,resolveProfileContextId as Zo,setDefaultProfile as Yo}from"./browser/profile.js";import{createManagedProfile as Qo,ensureManagedChrome as Fe,isManagedChromeRunning as er,removeManagedProfile as tr,stopManagedChrome as or,resolveManagedOpts as Nt,updateManagedProfileConfig as rr}from"./browser/managed-chrome.js";import{testProxy as nr,parseProxyUrl as Le}from"./browser/proxy-test.js";import{formatDaemonVersion as sr,isDaemonStale as ir}from"./browser/daemon-version.js";import{DEFAULT_BROWSER_CONNECT_TIMEOUT as ze}from"./browser/config.js";const We=no(import.meta.url),ar='Target tab/page identity returned by "browser open", "browser tab new", or "browser tab list"',At=1000;function $e(a,c){if(a===void 0||a===null||a==="")return null;const i=String(a).trim(),p=/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(i);if(!p)return{error:`--${c} must be a duration like 500ms, 30s, 2m, got "${i}"`};const b=Number.parseFloat(p[1]),g=p[2]??"ms";return Math.round(b*(g==="h"?3600000:g==="m"?60000:g==="s"?1000:1))}function He(a){return typeof a==="number"&&Number.isFinite(a)&&a>0?a:Date.now()}function ge(a){if(typeof a!=="number"||!Number.isFinite(a)||a<=0)return;return new Date(a).toISOString()}function Ve(a,c,i=Date.now()){const p=c.sinceMs!=null?i-c.sinceMs:void 0,b=c.untilMs!=null?i-c.untilMs:void 0;return a.filter((g)=>{const N=g.timestamp??i;if(p!==void 0&&N<p)return!1;if(b!==void 0&&N>b)return!1;return!0})}export function selectFreshByTimestamp(a,c){const i=a.filter((b)=>Number(b.timestamp??0)>c),p=i.length>0?Math.max(c,...i.map((b)=>Number(b.timestamp??0)).filter(Number.isFinite)):c;return{fresh:i,lastSeenTs:p}}async function he(a){if(a.readNetworkCapture){const i=await a.readNetworkCapture();if(Array.isArray(i)&&i.length>0)return i.map((p)=>{const b=p.responsePreview??null;let g=null;if(b)try{g=JSON.parse(b)}catch{g=b}const N=typeof p.responseBodyFullSize==="number"?p.responseBodyFullSize:b?b.length:0,v=p.responseBodyTruncated===!0;return{url:p.url||"",method:p.method||"GET",status:p.responseStatus||0,size:N,ct:p.responseContentType||"",body:g,bodyFullSize:N,bodyTruncated:v,timestamp:He(p.timestamp),...p.channel?{channel:p.channel}:{},...p.direction?{direction:p.direction}:{},...p.eventName?{eventName:String(p.eventName)}:{},...p.eventId?{eventId:String(p.eventId)}:{}}})}const c=await a.evaluate("(function(){ var out = window.__opencli_net || []; window.__opencli_net = []; return JSON.stringify(out); })()");try{return JSON.parse(c).map((p)=>({...p,timestamp:He(p.timestamp)}))}catch{if(process.env.OPENCLI_VERBOSE)Y.warn(`[network] Failed to parse interceptor buffer: ${typeof c==="string"?c.slice(0,200):String(c)}`);return[]}}const Tt=4000;function cr(a){if(typeof a!=="string")return a??null;return a.length>Tt?`${a.slice(0,Tt)}…[truncated ${a.length} chars]`:a}function It(a){return a.filter((c)=>{if(c.channel==="websocket"||c.channel==="eventsource")return!0;const i=c.ct?.toLowerCase()??"";return(i.includes("json")||i.includes("xml")||i.includes("text/plain")||i.includes("javascript"))&&!/\.(js|css|png|jpg|gif|svg|woff|ico|map)(\?|$)/i.test(c.url)&&!/analytics|tracking|telemetry|beacon|pixel|gtag|fbevents/i.test(c.url)})}const lr={invalid_args:f.USAGE_ERROR,invalid_filter:f.USAGE_ERROR,invalid_max_body:f.USAGE_ERROR};function X(a,c,i={}){console.log(JSON.stringify({error:{code:a,message:c,...i}},null,2));process.exitCode=lr[a]??f.GENERIC_ERROR}const dr="Site sitemap available. For navigation context, use the opencli-browser-sitemap skill; treat browser state as truth if it disagrees.";function ur(a,c=ve()){let i;try{i=new URL(a).hostname.toLowerCase().replace(/^www\./,"")}catch{return[]}const p=new Map;for(const v of c.values()){if(!v.domain)continue;let E=v.domain.toLowerCase().trim();try{E=new URL(E.includes("://")?E:`https://${E}`).hostname.toLowerCase()}catch{E=E.split("/")[0]??E}E=E.replace(/^www\./,"");if(!E)continue;if(i===E||i.endsWith(`.${E}`))p.set(v.site,Math.max(p.get(v.site)??0,E.length))}const b=[...p.entries()].sort((v,E)=>E[1]-v[1]||v[0].localeCompare(E[0])).map(([v])=>v),g=i.split(".").filter(Boolean),N=g.length>=2?g[g.length-2]:g[0];return[...new Set([...b,...N?[N]:[]])]}function Pt(a,c){return a.find((i)=>c(i))}function mr(a,c){const i=a.replace(/[^a-zA-Z0-9_-]+/g,"-");if(!i)return{};const p=O.join(c.homeDir,".ppcli","sites",i);return{local:Pt([O.join(p,"sitemap"),O.join(p,"sitemap.md")],c.fileExists),global:Pt([O.join(c.packageRoot,"sitemaps",i),O.join(c.packageRoot,"sitemaps",`${i}.md`)],c.fileExists)}}export function resolveSitemapAvailabilityForUrl(a,c={}){const i=c.homeDir??pe.homedir(),p=c.packageRoot??findPackageRoot(We),b=c.registry??ve(),g=c.fileExists??k.existsSync;for(const N of ur(a,b)){const v=mr(N,{homeDir:i,packageRoot:p,fileExists:g});if(!v.local&&!v.global)continue;const E=v.local&&v.global?"local+global":v.local?"local":"global";return{site:N,available:!0,source:E,hint:dr,paths:v}}return null}function Jt(a){const c=a.replace(/[^a-zA-Z0-9_-]+/g,"_");return O.join(jt(),"browser-sitemap-hints",`${c}.json`)}function Mt(a){try{const c=JSON.parse(k.readFileSync(Jt(a),"utf-8"));if(c&&typeof c==="object"&&Array.isArray(c.seenSites))return{seenSites:c.seenSites.filter((i)=>typeof i==="string"),updatedAt:typeof c.updatedAt==="string"?c.updatedAt:new Date(0).toISOString()}}catch{}return{seenSites:[],updatedAt:new Date(0).toISOString()}}function pr(a,c){const i=Mt(a);if(!i.seenSites.includes(c))i.seenSites.push(c);const p=Jt(a);k.mkdirSync(O.dirname(p),{recursive:!0});k.writeFileSync(p,JSON.stringify({seenSites:i.seenSites,updatedAt:new Date().toISOString()}),"utf-8")}function fr(a,c,i){const p=resolveSitemapAvailabilityForUrl(a);if(!p)return null;if(!i.oncePerSession)return p;if(Mt(c).seenSites.includes(p.site))return null;pr(c,p.site);return p}export function checkSiteMemory(a){const c=O.join(pe.homedir(),".ppcli","sites",a),i=O.join(c,"endpoints.json"),p=O.join(c,"notes.md");let b=0,g=k.existsSync(i);if(g)try{const v=JSON.parse(k.readFileSync(i,"utf-8"));if(v&&typeof v==="object"&&!Array.isArray(v))b=Object.keys(v).length;else if(Array.isArray(v))b=v.length}catch{g=!1}const N=k.existsSync(p);return{ok:g&&b>0&&N,siteDir:c,endpoints:{present:g,count:b,path:i},notes:{present:N,path:p}}}export function printSiteMemoryReport(a,c){if(a.ok){console.log(` ✓ Memory: endpoints.json (${a.endpoints.count}), notes.md present at ${a.siteDir}`);return}const i=c?"✗":"⚠",p=[];if(!a.endpoints.present)p.push("endpoints.json");else if(a.endpoints.count===0)p.push("endpoints.json (empty)");if(!a.notes.present)p.push("notes.md");console.log(` ${i} Memory: missing ${p.join(", ")} under ${a.siteDir}`);console.log(" Write the endpoint you just verified + a 1-line session note so the next agent starts from minute 0, not minute 95.");if(!c)console.log(" (Re-run with --strict-memory to fail instead of warn.)")}export function normalizeVerifyRows(a){if(Array.isArray(a))return a.map((c)=>c&&typeof c==="object"?c:{value:c});if(a&&typeof a==="object"){const c=a;for(const i of["rows","items","data","results"])if(Array.isArray(c[i]))return c[i].map((p)=>p&&typeof p==="object"?p:{value:p});return[c]}return[]}export function renderVerifyPreview(a,c={}){const i=c.maxRows??10,p=c.maxCols??6,b=c.cellMax??40;if(a.length===0)return" (no rows)";const g=Array.from(new Set(a.flatMap((T)=>Object.keys(T)))),N=g.slice(0,p),v=a.slice(0,i),E=(T)=>{if(T===null||T===void 0)return"";return(typeof T==="object"?JSON.stringify(T):String(T)).replace(/\s+/g," ").slice(0,b)},Q=N.map((T)=>Math.max(T.length,...v.map((K)=>E(K[T]).length))),re=(T)=>T.map((K,S)=>K.padEnd(Q[S])).join(" "),V=[];V.push(` ${re(N)}`);V.push(` ${Q.map((T)=>"-".repeat(T)).join(" ")}`);for(const T of v)V.push(` ${re(N.map((K)=>E(T[K])))}`);if(a.length>i)V.push(` ... and ${a.length-i} more row(s)`);if(g.length>p)V.push(` (${g.length-p} more column(s) hidden)`);return V.join(`
2
+ `)}function jt(){return process.env.OPENCLI_CACHE_DIR||O.join(pe.homedir(),".ppcli","cache")}function Ut(a){const c=a.replace(/[^a-zA-Z0-9_-]+/g,"_");return O.join(jt(),"browser-state",`${c}.json`)}function Dt(a){try{const c=k.readFileSync(Ut(a),"utf-8"),i=JSON.parse(c);return i&&typeof i==="object"?i:null}catch{return null}}function we(a,c){const i=Ut(c);if(!a){k.rmSync(i,{force:!0});return}k.mkdirSync(O.dirname(i),{recursive:!0});k.writeFileSync(i,JSON.stringify({defaultPage:a,updatedAt:new Date().toISOString()}),"utf-8")}function gr(a,c){return a.some((i)=>{return typeof i==="object"&&i!==null&&"page"in i&&typeof i.page==="string"&&i.page===c})}async function qe(a,c,i){const p=c.trim();if(!p)return;let b;try{b=await a.tabs()}catch(g){if(i.source==="saved"){we(void 0,i.scope);return}throw Error(`Target tab ${p} could not be validated in the current browser session. The Browser Bridge session may have restarted; re-run "ppcli browser tab list" and choose a current target.`,{cause:g})}if(Array.isArray(b)&&gr(b,p))return p;if(i.source==="saved"){we(void 0,i.scope);return}throw Error(`Target tab ${p} is not part of the current browser session. The Browser Bridge session may have restarted; re-run "ppcli browser tab list" and choose a current target.`)}function ke(a,c){return c?`${c}:${a}`:a}async function hr(a,c){const i=Dt(c)?.defaultPage?.trim();if(!i)return;return qe(a,i,{scope:c,source:"saved"})}async function wr(a,c,i,p={}){const b=kt(p.profile);if(b.kind==="managed"){if(c)throw Error(`托管环境「${b.name}」是单窗口复用标签模型,不支持 --tab 定位。直接省略 --tab 即可。`);const T=p.windowMode??Xe(void 0,"background"),{ensureManagedChrome:K}=await import("./browser/managed-chrome.js"),{CDPBridge:S}=await import("./browser/cdp.js"),{generateFingerprintJs:Ee}=await import("./browser/fingerprint.js"),ae=await K(b.name,b.entry,{windowMode:T}),ne=b.entry.fingerprint,ce=b.entry.proxy,ye=new S;return{page:await ye.connect({timeout:ze,session:a,surface:"browser",cdpEndpoint:ae,contextId:b.name,windowMode:T,...ne?.enabled?{initScript:Ee(ne)}:{},...ce?.username?{proxyAuth:{username:ce.username,password:ce.password??""}}:{}}),close:()=>ye.close()}}const{BrowserBridge:g}=await import("./browser/index.js"),N=new g,v=process.env.OPENCLI_BROWSER_IDLE_TIMEOUT,E=v?parseInt(v,10):void 0,Q=await N.connect({timeout:ze,session:a,surface:"browser",...i&&{contextId:i},...E&&E>0&&{idleTimeout:E},windowMode:p.windowMode??Xe(void 0,"background")}),re=ke(a,i),V=c?await qe(Q,c,{scope:re,source:"explicit"}):await hr(Q,re);if(V){if(!Q.setActivePage)throw Error("This browser session does not support explicit tab targeting");Q.setActivePage(V)}return{page:Q,close:()=>N.close()}}function Xe(a,c){const i=Ke(a,"window");if(i!==void 0&&i!==""){if(i==="foreground"||i==="background")return i;throw Error(`--window must be one of: foreground, background. Received: "${String(i)}"`)}const p=process.env.OPENCLI_WINDOW;if(p!==void 0&&p!==""){if(p==="foreground"||p==="background")return p;throw Error(`OPENCLI_WINDOW must be one of: foreground, background. Received: "${p}"`)}return c}function R(a){return a.option("--tab <targetId>",ar)}function yr(a){if(!a)return;const c=a.optsWithGlobals?a.optsWithGlobals():a.opts();return typeof c.tab==="string"&&c.tab.trim()?c.tab.trim():void 0}function Ke(a,c){let i=a;while(i){const p=i.opts();if(Object.prototype.hasOwnProperty.call(p,c)&&p[c]!==void 0)return p[c];i=i.parent}return}function Gt(a){const c=Ke(a,"session");if(typeof c==="string"&&c.trim())return c.trim();throw Error("<session> is a required positional argument: ppcli browser <session> <command>")}function Bt(a){return Zo(Ze(a))}function Ze(a){const c=Ke(a,"profile");return typeof c==="string"&&c.trim()?c.trim():void 0}function Ye(a){const c=a.session;if(typeof c==="string"&&c.trim())return c.trim();throw Error("Browser page is missing a session")}function Ne(a){const c=a.contextId;return ke(Ye(a),typeof c==="string"&&c.trim()?c.trim():void 0)}function br(a){return typeof a==="string"?a:JSON.stringify(a,null,2)}function Sr(a,c){const i=br(a),p=i.match(/^interactive:\s*(\d+)\s*$/m);return{ok:!0,chars:i.length,bytes:Buffer.byteLength(i,"utf8"),lines:i?i.split(/\r?\n/).length:0,approx_tokens:Math.ceil(i.length/4),refs:(i.match(/(^|\n)\s*\[\d+\]/g)??[]).length,frame_sections:(i.match(/(^|\n)frame /g)??[]).length,...p?{interactive:Number(p[1])}:{},elapsed_ms:c}}async function Ft(a,c){const i=Date.now();try{const p=await a.snapshot({viewportExpand:2000,source:c});return Sr(p,Date.now()-i)}catch(p){return{ok:!1,elapsed_ms:Date.now()-i,error:{...p instanceof Error&&"code"in p?{code:String(p.code)}:{},message:p instanceof Error?p.message:String(p)}}}}function Lt(a,c){if(typeof a==="string"&&a.trim())return a.trim();const i=c instanceof Ce?c.opts().tab:c?.tab;if(typeof i==="string"&&i.trim())return i.trim();return}function zt(a,c,i){if(a===void 0)return i;const p=parseInt(a,10);if(Number.isNaN(p)||p<=0){console.error(`[cli] Invalid ${c}="${a}", using default ${i}`);return i}return p}function Wt(a,c){if(!/^\d+$/.test(a))throw new wt(`--${c} must be a positive integer (got "${a}")`);const i=parseInt(a,10);if(i<=0)throw new wt(`--${c} must be a positive integer (got "${a}")`);return i}function xr(a){if(a.verbose)process.env.OPENCLI_VERBOSE="1"}function vr(a){return[...new Set(a.commands.map((c)=>c.name()))].sort((c,i)=>c.localeCompare(i)).join(", ")}function Rr(a){for(const c of a.commands){if(c.commands.length===0)continue;const i=vr(c);if(i)c.description(i)}}export function createProgram(a,c){const i=new Ce;i.name("ppcli").description("Make any website your CLI. Zero setup. AI-powered.").version(_e).option("--profile <name>","Chrome profile/context alias for Browser Bridge commands").enablePositionalOptions();i.command("list").description("List all available CLI commands").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((e)=>{const t=ve(),o=[...new Set(t.values())].sort((m,w)=>je(m).localeCompare(je(w))),r=e.format,n=r==="json"||r==="yaml";if(r!=="table"){const m=n?o.map(co):o.map((w)=>({command:je(w),site:w.site,name:w.name,aliases:w.aliases?.join(", ")??"",description:w.description,access:w.access,strategy:yt(w),browser:!!w.browser,args:lo(w.args)}));Re(m,{fmt:r,columns:["command","site","name","aliases","description","access","strategy","browser","args",...n?["columns","domain"]:[]],title:"ppcli/list",source:"ppcli list"});return}const s=new Map,l=new Map;for(const m of o){const w=St(m.domain)==="app"?s:l,x=w.get(m.site)??[];x.push(m);w.set(m.site,x)}const d=(m,w)=>{console.log(` ${m}`);for(const x of w){const _=yt(x),D=_==="public"?"[public]":`[${_}]`,B=x.aliases?.length?` (aliases: ${x.aliases.join(", ")})`:"";console.log(` ${x.name} ${D}${B}${x.description?` — ${x.description}`:""}`)}console.log()};console.log();console.log(" ppcli"+" — available commands");console.log();if(s.size>0){console.log(" App adapters");console.log();for(const[m,w]of s)d(m,w)}if(l.size>0){console.log(" Site adapters");console.log();for(const[m,w]of l)d(m,w)}const u=Ue();if(u.length>0){console.log(" external CLIs");for(const m of u){const x=De(m.binary)?"[installed]":"[auto-install]";console.log(` ${bt(m)} ${x}${m.description?` — ${m.description}`:""}`)}console.log()}console.log(` ${o.length} built-in commands across ${s.size} apps + ${l.size} sites, ${u.length} external CLIs`);console.log()});i.command("validate").description("Validate CLI definitions").argument("[target]","site or site/name").action(async(e)=>{const{validateClisWithTarget:t,renderValidationReport:o}=await import("./validate.js");console.log(o(t([a,c],e)))});i.command("verify").description("Validate + smoke test").argument("[target]").option("--smoke","Run smoke tests",!1).action(async(e,t)=>{const{verifyClis:o,renderVerifyReport:r}=await import("./verify.js"),n=await o({builtinClis:a,userClis:c,target:e,smoke:t.smoke});console.log(r(n));process.exitCode=n.ok?f.SUCCESS:f.GENERIC_ERROR});const p=i.command("skills").description("Read bundled ppcli skills");p.command("list").description("List bundled ppcli-* skills").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((e)=>{const t=go();Re(t,{fmt:e.format,fmtExplicit:!!e.format,columns:["name","description","version","path"],title:"ppcli/skills/list",source:"ppcli skills list"})});p.command("read").description("Print an ppcli-* skill's SKILL.md or reference file").argument("<skill>","Skill name, or skill/path like opencli-browser/references/foo.md").argument("[path]","Path under the skill directory").option("--json","Output a JSON envelope instead of raw markdown",!1).action((e,t,o)=>{let r;try{r=ho(e,t??"")}catch(n){console.error(`Error: ${j(n)}`);if(n instanceof Ge&&n.hint)console.error(`Hint: ${n.hint}`);process.exitCode=n instanceof Ge?n.exitCode:f.GENERIC_ERROR;return}if(o.json){console.log(JSON.stringify(r,null,2));return}process.stdout.write(r.content);if(!r.content.endsWith(`
3
3
  `))process.stdout.write(`
4
- `)});const b=Bo(i);i.command("convention-audit").description("Scan adapters for agent-native convention violations").argument("[target]","site or site/name").option("--site <site>","Limit audit to one site").option("-f, --format <fmt>","Output format: table, json, yaml","table").option("--strict","Exit non-zero when violations are found",!1).action(async(e,t)=>{const{runConventionAudit:o,renderConventionAuditText:r}=await import("./convention-audit.js"),n=o({projectRoot:findPackageRoot(Le),target:e,site:t.site}),s=String(t.format??"table").toLowerCase();if(s==="json"||s==="yaml"||s==="yml")xe(n,{fmt:s});else console.log(r(n));if(t.strict&&!n.ok)process.exitCode=f.GENERIC_ERROR});const g=i.command("browser").addOption(new so("--session <name>","Internal — set automatically from the <session> positional").hideHelp()).option("--window <mode>","Browser window mode: foreground or background").description("Browser control — navigate, click, type, extract, wait (no LLM needed)").usage("<session> <command> [options]").addHelpText("after",`
4
+ `)});const b=Bo(i);i.command("convention-audit").description("Scan adapters for agent-native convention violations").argument("[target]","site or site/name").option("--site <site>","Limit audit to one site").option("-f, --format <fmt>","Output format: table, json, yaml","table").option("--strict","Exit non-zero when violations are found",!1).action(async(e,t)=>{const{runConventionAudit:o,renderConventionAuditText:r}=await import("./convention-audit.js"),n=o({projectRoot:findPackageRoot(We),target:e,site:t.site}),s=String(t.format??"table").toLowerCase();if(s==="json"||s==="yaml"||s==="yml")Re(n,{fmt:s});else console.log(r(n));if(t.strict&&!n.ok)process.exitCode=f.GENERIC_ERROR});const g=i.command("browser").addOption(new so("--session <name>","Internal — set automatically from the <session> positional").hideHelp()).option("--window <mode>","Browser window mode: foreground or background").description("Browser control — navigate, click, type, extract, wait (no LLM needed)").usage("<session> <command> [options]").addHelpText("after",`
5
5
  <session> is a required positional: pass the name of the browser session every subcommand should operate on. Reuse the same name across calls to keep the tab/state alive; pick a different name to isolate parallel browser work.
6
6
 
7
7
  Examples:
@@ -11,8 +11,8 @@ Examples:
11
11
  $ ppcli browser work state
12
12
  $ ppcli browser work bind
13
13
  $ ppcli browser work unbind
14
- `),N=g.description();async function v(e,t,o={}){const r=await e.evaluate(Co(t,o));if(!r.ok)throw new bt({code:r.code,message:r.message,hint:r.hint,candidates:r.candidates,matches_n:r.matches_n});return{matches_n:r.matches_n,match_level:r.match_level}}function E(e){if(e===void 0||e===null||e==="")return null;const t=String(e);if(!/^\d+$/.test(t))return{error:`--nth must be a non-negative integer, got "${t}"`};return Number.parseInt(t,10)}function Y(e){console.log(JSON.stringify({error:{code:e.code,message:e.message,hint:e.hint,...e.candidates&&{candidates:e.candidates},...e.matches_n!==void 0&&{matches_n:e.matches_n}}},null,2))}function oe(e){return e.toLowerCase().includes("javascript dialog")}function V(e){console.log(JSON.stringify({error:{code:"javascript_dialog_open",message:e,hint:"Handle the modal first: ppcli browser dialog accept (or dismiss). Use --text for prompt dialogs."}},null,2))}function T(e){if(!e.code)return;console.log(JSON.stringify({error:{code:e.code,message:e.message,...e.hint?{hint:e.hint}:{}}},null,2))}function X(e){Z.error(e.message);if(e.hint)Z.error(`Hint: ${e.hint}`)}function S(e){return async(...t)=>{let o=null;try{const r=t.at(-1)instanceof Re?t.at(-1):void 0,n=yr(r),s=Ut(r),l=Dt(r),d=Ve(r,"background");o=await wr(s,n,l,{windowMode:d,profile:Xe(r)});await e(o,...t)}catch(r){if(r instanceof vo){Z.error(r.message);if(r.hint)Z.error(`Hint: ${r.hint}`)}else if(r instanceof Ct){if(oe(r.message))V(r.message);else T(r);X(r)}else if(r instanceof bt){Y(r);Z.error(`[${r.code}] ${r.message}`);if(r.hint)Z.error(`Hint: ${r.hint}`)}else{const n=M(r);if(oe(n)){V(n);Z.error(n)}else if(n.includes("attach failed")||n.includes("chrome-extension://"))Z.error("Browser attach failed — another extension may be interfering. Try disabling 1Password.");else Z.error(n)}process.exitCode=f.GENERIC_ERROR}}}function ve(e,t){return async(o,r)=>{const n=o instanceof Re?o:r,s=Ut(n),l=Dt(n);try{if(t?.managedGuardMessage&&Ot(Xe(n)).kind==="managed")throw Error(t.managedGuardMessage);const{BrowserBridge:d}=await import("./browser/index.js");await new d().connect({timeout:Fe,session:s,surface:"browser",...l&&{contextId:l}});await e({session:s,contextId:l})}catch(d){if(d instanceof Ct){T(d);X(d)}else Z.error(d instanceof Error?d.message:String(d));process.exitCode=f.GENERIC_ERROR}}}g.command("bind").description("Bind the current Chrome tab/window to the browser session named by <session>").action(ve(async({session:e,contextId:t})=>{const o=await Ho(e,{...t&&{contextId:t}});he(void 0,Oe(e,t));console.log(JSON.stringify({session:e,...o&&typeof o==="object"?o:{data:o}},null,2))},{managedGuardMessage:"托管环境不支持 bind:它是独立自动化窗口,直接用 browser open/eval 等命令即可。"}));g.command("unbind").description("Detach the bound browser session named by <session> without closing the user tab/window").action(ve(async({session:e,contextId:t})=>{await Vo("close-window",{session:e,surface:"browser",...t&&{contextId:t}});he(void 0,Oe(e,t));console.log(JSON.stringify({unbound:!0,session:e},null,2))},{managedGuardMessage:"托管环境不支持 unbind:它没有绑定到扩展的会话。"}));const ie=g.command("tab").description("Tab management — list, create, and close tabs in the browser session");ie.command("list").description("List tabs in the browser session with target IDs").action(S(async(e)=>{const t=await e.tabs();console.log(JSON.stringify(t,null,2))}));ie.command("new").argument("[url]","Optional URL to open in the new tab").description("Create a new tab and print its target ID").action(S(async(e,t)=>{if(!e.newTab)throw Error("This browser session does not support creating tabs");const o=await e.newTab(t);console.log(JSON.stringify({page:o,url:t??null},null,2))}));R(ie.command("select").argument("[targetId]",'Target tab/page identity returned by "browser open", "browser tab new", or "browser tab list"').description("Select a tab by target ID and make it the default browser tab")).action(S(async(e,t,o)=>{const r=Bt(t,o);if(!r)throw Error("Target tab required. Pass it as an argument or --tab <targetId>.");await e.selectTab(r);he(r,$e(e));console.log(JSON.stringify({selected:r},null,2))}));R(ie.command("close").argument("[targetId]",'Target tab/page identity returned by "browser open", "browser tab new", or "browser tab list"').description("Close a tab by target ID")).action(S(async(e,t,o)=>{const r=Bt(t,o);if(!e.closeTab)throw Error("This browser session does not support closing tabs");if(!r)throw Error("Target tab required. Pass it as an argument or --tab <targetId>.");const n=await He(e,r,{scope:$e(e),source:"explicit"});if(!n)throw Error(`Target tab ${r} is not part of the current browser session.`);await e.closeTab(n);const s=$e(e);if(jt(s)?.defaultPage===n)he(void 0,s);console.log(JSON.stringify({closed:n},null,2))}));R(g.command("open").argument("<url>").description("Open URL in the browser session")).action(S(async(e,t,o)=>{const r=await e.startNetworkCapture?.()??!1;await e.goto(t);await e.wait(2);if(!r)try{await e.evaluate(Ce)}catch{}const n=await e.getCurrentUrl?.()??t,s=fr(n,$e(e),{oncePerSession:!0});console.log(JSON.stringify({url:n,...e.getActivePage?.()?{page:e.getActivePage?.()}:{},...s?{sitemap:s}:{}},null,2))}));R(g.command("back").description("Go back in browser history")).action(S(async(e,t)=>{await e.evaluate("history.back()");await e.wait(2);console.log("Navigated back")}));R(g.command("scroll").argument("<direction>","up or down").option("--amount <pixels>","Pixels to scroll","500")).description("Scroll page").action(S(async(e,t,o)=>{if(t!=="up"&&t!=="down"){console.error(`Invalid direction "${t}". Use "up" or "down".`);process.exitCode=f.USAGE_ERROR;return}await e.scroll(t,parseInt(o.amount,10));console.log(`Scrolled ${t}`)}));R(g.command("state").description("Page state: URL, title, interactive elements with [N] indices").option("--source <source>","Snapshot backend: dom (default) or ax prototype","dom").option("--compare-sources","Print DOM vs AX snapshot metrics for observation promotion decisions",!1)).action(S(async(e,t)=>{if(t.compareSources===!0){const[s,l]=await Promise.all([Gt(e,"dom"),Gt(e,"ax")]);console.log(JSON.stringify({url:await e.getCurrentUrl?.()??"",sources:{dom:s,ax:l}},null,2));return}const o=String(t.source??"dom").toLowerCase();if(o!=="dom"&&o!=="ax"){console.log(JSON.stringify({error:{code:"invalid_source",message:`--source must be "dom" or "ax", got "${t.source}"`}},null,2));process.exitCode=f.USAGE_ERROR;return}const r=await e.snapshot({viewportExpand:2000,source:o}),n=await e.getCurrentUrl?.()??"";console.log(`URL: ${n}
15
- `);console.log(typeof r==="string"?r:JSON.stringify(r,null,2))}));R(g.command("frames").description("List cross-origin iframe targets in snapshot order")).action(S(async(e)=>{const t=await e.frames?.()??[];console.log(JSON.stringify(t,null,2))}));R(g.command("screenshot").argument("[path]","Save to file (base64 if omitted)")).option("--full-page","Capture the full scrollable page, not just the viewport",!1).option("--annotate","Overlay visible browser state ref labels on the screenshot",!1).option("--width <n>","Override viewport width in CSS pixels for this screenshot only",(e)=>Lt(e,"width")).option("--height <n>","Override viewport height in CSS pixels for this screenshot only (ignored with --full-page)",(e)=>Lt(e,"height")).option("--scroll-to <selector>","Scroll this element into view (centered) before capturing").description("Take screenshot").action(S(async(e,t,o)=>{if(o.scrollTo){const s=JSON.stringify(String(o.scrollTo));if(!await e.evaluate(`(() => { const el = document.querySelector(${s}); if (!el) return false; el.scrollIntoView({ block: 'center', inline: 'center' }); return true; })()`))throw new Ro(`--scroll-to 没匹配到元素: ${o.scrollTo}`);await e.wait(150)}const r={fullPage:o.fullPage===!0,annotate:o.annotate===!0,width:o.width,height:o.height},n=o.annotate===!0?(e.annotatedScreenshot??e.screenshot).bind(e):e.screenshot.bind(e);if(t){await n({...r,path:t});console.log(`Screenshot saved to: ${t}`)}else console.log(await n({...r,format:"png"}))}));const re=[".js-mocaptcha-img",".moclickcaptcha-img",".moclickcaptcha-draw",".geetest_item_img",".geetest_widget canvas",".captcha-image img",".captcha img",".captcha canvas",'img[src*="captcha" i]','img[class*="captcha" i]','canvas[class*="captcha" i]'],ae=6;function Ze(e){const t=e&&e.trim()?[e.trim(),...re]:re;return`(() => {
14
+ `),N=g.description();async function v(e,t,o={}){const r=await e.evaluate(Co(t,o));if(!r.ok)throw new xt({code:r.code,message:r.message,hint:r.hint,candidates:r.candidates,matches_n:r.matches_n});return{matches_n:r.matches_n,match_level:r.match_level}}function E(e){if(e===void 0||e===null||e==="")return null;const t=String(e);if(!/^\d+$/.test(t))return{error:`--nth must be a non-negative integer, got "${t}"`};return Number.parseInt(t,10)}function Q(e){console.log(JSON.stringify({error:{code:e.code,message:e.message,hint:e.hint,...e.candidates&&{candidates:e.candidates},...e.matches_n!==void 0&&{matches_n:e.matches_n}}},null,2))}function re(e){return e.toLowerCase().includes("javascript dialog")}function V(e){console.log(JSON.stringify({error:{code:"javascript_dialog_open",message:e,hint:"Handle the modal first: ppcli browser dialog accept (or dismiss). Use --text for prompt dialogs."}},null,2))}function T(e){if(!e.code)return;console.log(JSON.stringify({error:{code:e.code,message:e.message,...e.hint?{hint:e.hint}:{}}},null,2))}function K(e){Y.error(e.message);if(e.hint)Y.error(`Hint: ${e.hint}`)}function S(e){return async(...t)=>{let o=null;try{const r=t.at(-1)instanceof Ce?t.at(-1):void 0,n=yr(r),s=Gt(r),l=Bt(r),d=Xe(r,"background");o=await wr(s,n,l,{windowMode:d,profile:Ze(r)});await e(o.page,...t)}catch(r){if(r instanceof vo){Y.error(r.message);if(r.hint)Y.error(`Hint: ${r.hint}`)}else if(r instanceof Ot){if(re(r.message))V(r.message);else T(r);K(r)}else if(r instanceof xt){Q(r);Y.error(`[${r.code}] ${r.message}`);if(r.hint)Y.error(`Hint: ${r.hint}`)}else{const n=j(r);if(re(n)){V(n);Y.error(n)}else if(n.includes("attach failed")||n.includes("chrome-extension://"))Y.error("Browser attach failed — another extension may be interfering. Try disabling 1Password.");else Y.error(n)}process.exitCode=f.GENERIC_ERROR}finally{await o?.close()}}}function Ee(e,t){return async(o,r)=>{const n=o instanceof Ce?o:r,s=Gt(n),l=Bt(n);try{if(t?.managedGuardMessage&&kt(Ze(n)).kind==="managed")throw Error(t.managedGuardMessage);const{BrowserBridge:d}=await import("./browser/index.js");await new d().connect({timeout:ze,session:s,surface:"browser",...l&&{contextId:l}});await e({session:s,contextId:l})}catch(d){if(d instanceof Ot){T(d);K(d)}else Y.error(d instanceof Error?d.message:String(d));process.exitCode=f.GENERIC_ERROR}}}g.command("bind").description("Bind the current Chrome tab/window to the browser session named by <session>").action(Ee(async({session:e,contextId:t})=>{const o=await Ho(e,{...t&&{contextId:t}});we(void 0,ke(e,t));console.log(JSON.stringify({session:e,...o&&typeof o==="object"?o:{data:o}},null,2))},{managedGuardMessage:"托管环境不支持 bind:它是独立自动化窗口,直接用 browser open/eval 等命令即可。"}));g.command("unbind").description("Detach the bound browser session named by <session> without closing the user tab/window").action(Ee(async({session:e,contextId:t})=>{await Vo("close-window",{session:e,surface:"browser",...t&&{contextId:t}});we(void 0,ke(e,t));console.log(JSON.stringify({unbound:!0,session:e},null,2))},{managedGuardMessage:"托管环境不支持 unbind:它没有绑定到扩展的会话。"}));const ae=g.command("tab").description("Tab management — list, create, and close tabs in the browser session");ae.command("list").description("List tabs in the browser session with target IDs").action(S(async(e)=>{const t=await e.tabs();console.log(JSON.stringify(t,null,2))}));ae.command("new").argument("[url]","Optional URL to open in the new tab").description("Create a new tab and print its target ID").action(S(async(e,t)=>{if(!e.newTab)throw Error("This browser session does not support creating tabs");const o=await e.newTab(t);console.log(JSON.stringify({page:o,url:t??null},null,2))}));R(ae.command("select").argument("[targetId]",'Target tab/page identity returned by "browser open", "browser tab new", or "browser tab list"').description("Select a tab by target ID and make it the default browser tab")).action(S(async(e,t,o)=>{const r=Lt(t,o);if(!r)throw Error("Target tab required. Pass it as an argument or --tab <targetId>.");await e.selectTab(r);we(r,Ne(e));console.log(JSON.stringify({selected:r},null,2))}));R(ae.command("close").argument("[targetId]",'Target tab/page identity returned by "browser open", "browser tab new", or "browser tab list"').description("Close a tab by target ID")).action(S(async(e,t,o)=>{const r=Lt(t,o);if(!e.closeTab)throw Error("This browser session does not support closing tabs");if(!r)throw Error("Target tab required. Pass it as an argument or --tab <targetId>.");const n=await qe(e,r,{scope:Ne(e),source:"explicit"});if(!n)throw Error(`Target tab ${r} is not part of the current browser session.`);await e.closeTab(n);const s=Ne(e);if(Dt(s)?.defaultPage===n)we(void 0,s);console.log(JSON.stringify({closed:n},null,2))}));R(g.command("open").argument("<url>").description("Open URL in the browser session")).action(S(async(e,t,o)=>{const r=await e.startNetworkCapture?.()??!1;await e.goto(t);await e.wait(2);if(!r)try{await e.evaluate(Oe)}catch{}const n=await e.getCurrentUrl?.()??t,s=fr(n,Ne(e),{oncePerSession:!0});console.log(JSON.stringify({url:n,...e.getActivePage?.()?{page:e.getActivePage?.()}:{},...s?{sitemap:s}:{}},null,2))}));R(g.command("back").description("Go back in browser history")).action(S(async(e,t)=>{await e.evaluate("history.back()");await e.wait(2);console.log("Navigated back")}));R(g.command("scroll").argument("<direction>","up or down").option("--amount <pixels>","Pixels to scroll","500")).description("Scroll page").action(S(async(e,t,o)=>{if(t!=="up"&&t!=="down"){console.error(`Invalid direction "${t}". Use "up" or "down".`);process.exitCode=f.USAGE_ERROR;return}await e.scroll(t,parseInt(o.amount,10));console.log(`Scrolled ${t}`)}));R(g.command("state").description("Page state: URL, title, interactive elements with [N] indices").option("--source <source>","Snapshot backend: dom (default) or ax prototype","dom").option("--compare-sources","Print DOM vs AX snapshot metrics for observation promotion decisions",!1)).action(S(async(e,t)=>{if(t.compareSources===!0){const[s,l]=await Promise.all([Ft(e,"dom"),Ft(e,"ax")]);console.log(JSON.stringify({url:await e.getCurrentUrl?.()??"",sources:{dom:s,ax:l}},null,2));return}const o=String(t.source??"dom").toLowerCase();if(o!=="dom"&&o!=="ax"){console.log(JSON.stringify({error:{code:"invalid_source",message:`--source must be "dom" or "ax", got "${t.source}"`}},null,2));process.exitCode=f.USAGE_ERROR;return}const r=await e.snapshot({viewportExpand:2000,source:o}),n=await e.getCurrentUrl?.()??"";console.log(`URL: ${n}
15
+ `);console.log(typeof r==="string"?r:JSON.stringify(r,null,2))}));R(g.command("frames").description("List cross-origin iframe targets in snapshot order")).action(S(async(e)=>{const t=await e.frames?.()??[];console.log(JSON.stringify(t,null,2))}));R(g.command("screenshot").argument("[path]","Save to file (base64 if omitted)")).option("--full-page","Capture the full scrollable page, not just the viewport",!1).option("--annotate","Overlay visible browser state ref labels on the screenshot",!1).option("--width <n>","Override viewport width in CSS pixels for this screenshot only",(e)=>Wt(e,"width")).option("--height <n>","Override viewport height in CSS pixels for this screenshot only (ignored with --full-page)",(e)=>Wt(e,"height")).option("--scroll-to <selector>","Scroll this element into view (centered) before capturing").description("Take screenshot").action(S(async(e,t,o)=>{if(o.scrollTo){const s=JSON.stringify(String(o.scrollTo));if(!await e.evaluate(`(() => { const el = document.querySelector(${s}); if (!el) return false; el.scrollIntoView({ block: 'center', inline: 'center' }); return true; })()`))throw new Ro(`--scroll-to 没匹配到元素: ${o.scrollTo}`);await e.wait(150)}const r={fullPage:o.fullPage===!0,annotate:o.annotate===!0,width:o.width,height:o.height},n=o.annotate===!0?(e.annotatedScreenshot??e.screenshot).bind(e):e.screenshot.bind(e);if(t){await n({...r,path:t});console.log(`Screenshot saved to: ${t}`)}else console.log(await n({...r,format:"png"}))}));const ne=[".js-mocaptcha-img",".moclickcaptcha-img",".moclickcaptcha-draw",".geetest_item_img",".geetest_widget canvas",".captcha-image img",".captcha img",".captcha canvas",'img[src*="captcha" i]','img[class*="captcha" i]','canvas[class*="captcha" i]'],ce=6;function ye(e){const t=e&&e.trim()?[e.trim(),...ne]:ne;return`(() => {
16
16
  var sels = ${JSON.stringify(t)};
17
17
  var el = null, used = '';
18
18
  for (var i = 0; i < sels.length; i++) {
@@ -46,7 +46,7 @@ Examples:
46
46
  viewport: { w: window.innerWidth, h: window.innerHeight },
47
47
  prompt: prompt,
48
48
  };
49
- })()`}function zt(e){const t=e&&e.trim()?[e.trim(),...re]:re;return`(() => {
49
+ })()`}function Qe(e){const t=e&&e.trim()?[e.trim(),...ne]:ne;return`(() => {
50
50
  var sels = ${JSON.stringify(t)};
51
51
  var present = false;
52
52
  for (var i = 0; i < sels.length; i++) {
@@ -69,7 +69,7 @@ Examples:
69
69
  }
70
70
  } catch (e) {}
71
71
  return { captcha_present: present, status_text: status, url: (location.href || '').slice(0, 100) };
72
- })()`}R(g.command("captcha").argument("[selector]","验证码图片元素 CSS 选择器(缺省自动探测常见点选验证码)")).option("--save <path>","把全视口截图存到该路径(缺省存到临时 PNG 文件)").option("--scale <n>","验证码区域裁剪图的放大倍数(1..6,缺省 3;放大后认扭曲字更准)","3").description("抓取点选验证码:存整图 + 只含验证码的放大裁剪图 + 返回坐标与提示文字,供 AI 视觉识别后配合 captcha-click 点击").action(S(async(e,t,o)=>{const r=await e.evaluate(Ze(typeof t==="string"?t:void 0));if(!r||!r.found){console.log(JSON.stringify({error:{code:"captcha_not_found",message:'未探测到点选验证码图片。可显式传选择器,如 ppcli browser <s> captcha ".js-mocaptcha-img"',tried:re}},null,2));process.exitCode=f.USAGE_ERROR;return}const n=o?.save&&String(o.save)||k.join(me.tmpdir(),`opencli-captcha-${Date.now()}.png`);await e.screenshot({format:"png",path:n});const s=r.rect,l=r.dpr||1,d=Math.max(1,Math.min(6,Number(o?.scale??3)||3)),u=ae;let m=null;const y=e.cdp;if(typeof y==="function"){const x={x:Math.max(0,s.x-u),y:Math.max(0,s.y-u),width:s.w+u*2,height:s.h+u*2,scale:d},_=await y.call(e,"Page.captureScreenshot",{format:"jpeg",quality:82,clip:x,captureBeyondViewport:!1});if(_&&_.data){m=n.replace(/\.png$/i,"")+".crop.jpg";O.writeFileSync(m,Buffer.from(_.data,"base64"))}}console.log(JSON.stringify({ok:!0,selector:r.selector,prompt:r.prompt||"",crop:m,crop_scale:m?d:null,crop_pad:m?u:null,saved:n,rect_css:s,rect_screenshot_px:{x:Math.round(s.x*l),y:Math.round(s.y*l),w:Math.round(s.w*l),h:Math.round(s.h*l)},dpr:l,natural:r.natural,viewport:r.viewport,guide:"① read_local_file 打开 crop(只含验证码、已放大)认清每个待点字与顺序(注意会混入不在 prompt 里的干扰字,只点 prompt 要求的)。"+"② 坐标直接读成「在 crop 这张图里的比例」(0..1,左上角为 0,0)——不用管 pad/rect,看到字在 crop 的哪就填哪。"+'③ 执行:ppcli browser <session> captcha-click --crop --in "'+r.selector+'" "x1,y1 x2,y2 ..."(--crop 表示坐标是 crop 图比例;空格分隔,顺序即点击顺序)。'+"命令会回读点了几个、验证码是否还在、URL 是否跳转,据此判断成功/补点/重来。"},null,2))}));R(g.command("captcha-click").argument("<points>",'待点击坐标,空格分隔且顺序即点击顺序,如 "0.30,0.46 0.68,0.66"')).option("--in <selector>","坐标映射基准元素(缺省自动探测验证码图片)").option("--crop","坐标按「captcha 裁剪图(crop)里的比例」解释(0..1,左上角为0,0)——AI 看哪张就按那张填,内部自动扣掉 pad。推荐").option("--px","坐标按「截图设备像素」解释(自动按 devicePixelRatio 换算成 CSS 像素)").option("--css","坐标按「CSS 视口像素」解释(直接点击,不做映射)").option("--delay <ms>","每次点击之间的间隔毫秒","250").description("按坐标依次点击(点选验证码用):把 AI 从图上读到的位置一次性点上,点完回读验证码是否还在/是否跳转。默认坐标为相对基准元素的比例(0..1),--crop 则为裁剪图比例").action(S(async(e,t,o)=>{const n=String(t??"").trim().split(/\s+/).filter(Boolean).map((w)=>{const[A,G]=w.split(",");return{x:Number(A),y:Number(G)}});if(n.length===0||n.some((w)=>!Number.isFinite(w.x)||!Number.isFinite(w.y))){console.log(JSON.stringify({error:{code:"usage_error",message:'坐标格式应为 "x,y x,y ...",如 "0.30,0.46 0.68,0.66"'}},null,2));process.exitCode=f.USAGE_ERROR;return}const s=o?.css?"css":o?.px?"px":o?.crop?"crop":"frac",l=Math.max(0,Number(o?.delay??250)||0);let d={x:0,y:0,w:0,h:0},u=1;if(s!=="css"){const w=await e.evaluate(Ze(typeof o?.in==="string"?o.in:void 0));if(!w||!w.found||!w.rect){console.log(JSON.stringify({error:{code:"captcha_not_found",message:"captcha-click 找不到基准元素,请用 --in <selector> 指定,或用 --css 传绝对坐标"}},null,2));process.exitCode=f.USAGE_ERROR;return}d=w.rect;u=w.dpr||1}const m=ae,y=d.w+m*2,x=d.h+m*2,_=Math.max(0,d.x-m),D=Math.max(0,d.y-m),j=(w)=>{if(s==="css")return w;if(s==="px")return{x:w.x/u,y:w.y/u};if(s==="crop")return{x:_+w.x*y,y:D+w.y*x};return{x:d.x+w.x*d.w,y:d.y+w.y*d.h}},{cdp:J,nativeClick:P}=e,z=(w)=>new Promise((A)=>setTimeout(A,w));async function W(w,A,G,B){if(typeof J==="function"){const F=12+B%4;for(let K=1;K<=F;K++){const te=K/F,I=te*te*(3-2*te),H=Math.sin(te*Math.PI)*10*(B%2===0?1:-1),Pe=G.x+(w-G.x)*I,ro=G.y+(A-G.y)*I+H;await J.call(e,"Input.dispatchMouseEvent",{type:"mouseMoved",x:Math.round(Pe),y:Math.round(ro)});await z(8+K%3*6)}await J.call(e,"Input.dispatchMouseEvent",{type:"mouseMoved",x:w,y:A});await z(40+B%3*25);await J.call(e,"Input.dispatchMouseEvent",{type:"mousePressed",x:w,y:A,button:"left",clickCount:1});await z(45+B%4*20);await J.call(e,"Input.dispatchMouseEvent",{type:"mouseReleased",x:w,y:A,button:"left",clickCount:1});return"cdp"}if(typeof P==="function"){await P.call(e,w,A);return"native"}await e.evaluate(`(() => { var el = document.elementFromPoint(${w}, ${A}); if (!el) return false; ['mousemove','mousedown','mouseup','click'].forEach(function(t){ el.dispatchEvent(new MouseEvent(t, { bubbles: true, cancelable: true, view: window, clientX: ${w}, clientY: ${A} })); }); return true; })()`);return"synthetic"}const ne=[];let h="synthetic",C={x:Math.round(d.x+d.w/2)||400,y:Math.round(d.y-40)||200};for(let w=0;w<n.length;w++){const A=j(n[w]),G=Math.round(A.x),B=Math.round(A.y);h=await W(G,B,C,w);C={x:G,y:B};ne.push({x:G,y:B});if(w<n.length-1&&l>0)await z(l)}await z(700);let Q={};try{Q=await e.evaluate(zt(typeof o?.in==="string"?o.in:void 0))}catch{}console.log(JSON.stringify({ok:!0,mode:s,method:h,clicked_n:ne.length,points_css:ne,after:Q},null,2))}));R(g.command("console")).option("--level <level>","Console level: all, error, warning, log, info, debug","all").option("--since <duration>","Only include messages from the last duration (for example: 30s, 2m)").option("--until <duration>","Only include messages older than the duration from now").option("--follow","Continuously print new console messages as JSON lines",!1).description("Read recent browser console messages").action(S(async(e,t)=>{const o=_e(t.since,"since"),r=_e(t.until,"until");if(o&&typeof o==="object"){console.log(JSON.stringify({error:{code:"invalid_since",message:o.error}},null,2));process.exitCode=f.USAGE_ERROR;return}if(r&&typeof r==="object"){console.log(JSON.stringify({error:{code:"invalid_until",message:r.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const n=(d)=>d.map((u)=>{if(u&&typeof u==="object"){const m=u;return{...m,timestamp:ze(m.timestamp)}}return{type:"log",text:String(u),timestamp:Date.now()}}),s=(d)=>We(d,{sinceMs:o,untilMs:r}).filter((u)=>{if(t.level==="all")return!0;const m=String(u.type??u.level??"").toLowerCase();return t.level==="error"?m==="error"||m==="warning":m===String(t.level).toLowerCase()});if(t.follow){let d=0;while(!0){const u=s(n(await e.consoleMessages("all"))),m=selectFreshByTimestamp(u,d);for(const y of m.fresh)console.log(JSON.stringify({...y,timestamp:fe(y.timestamp)}));d=m.lastSeenTs;await new Promise((y)=>setTimeout(y,kt))}}const l=s(n(await e.consoleMessages(t.level)));console.log(JSON.stringify({session:Ke(e),captured_at:new Date().toISOString(),count:l.length,messages:l.map((d)=>({...d,timestamp:fe(d.timestamp)}))},null,2))}));R(g.command("analyze").argument("<url>")).description("Classify site: anti-bot vendor, real-data API candidates, pattern (A/B/C/D), nearest adapter, next step").action(S(async(e,t)=>{const o=await e.startNetworkCapture?.()??!1;await e.goto(t);await e.wait(2);if(!o)try{await e.evaluate(Ce)}catch{}await ge(e);await e.wait(1);const n=(await ge(e)).map((_)=>({url:_.url,status:_.status,contentType:_.ct,bodyPreview:typeof _.body==="string"?_.body.slice(0,2000):_.body?JSON.stringify(_.body).slice(0,2000):null})),s=`(function(){
72
+ })()`}R(g.command("captcha").argument("[selector]","验证码图片元素 CSS 选择器(缺省自动探测常见点选验证码)")).option("--save <path>","把全视口截图存到该路径(缺省存到临时 PNG 文件)").option("--scale <n>","验证码区域裁剪图的放大倍数(1..6,缺省 3;放大后认扭曲字更准)","3").description("抓取点选验证码:存整图 + 只含验证码的放大裁剪图 + 返回坐标与提示文字,供 AI 视觉识别后配合 captcha-click 点击").action(S(async(e,t,o)=>{const r=await e.evaluate(ye(typeof t==="string"?t:void 0));if(!r||!r.found){console.log(JSON.stringify({error:{code:"captcha_not_found",message:'未探测到点选验证码图片。可显式传选择器,如 ppcli browser <s> captcha ".js-mocaptcha-img"',tried:ne}},null,2));process.exitCode=f.USAGE_ERROR;return}const n=o?.save&&String(o.save)||O.join(pe.tmpdir(),`opencli-captcha-${Date.now()}.png`);await e.screenshot({format:"png",path:n});const s=r.rect,l=r.dpr||1,d=Math.max(1,Math.min(6,Number(o?.scale??3)||3)),u=ce;let m=null;const w=e.cdp;if(typeof w==="function"){const x={x:Math.max(0,s.x-u),y:Math.max(0,s.y-u),width:s.w+u*2,height:s.h+u*2,scale:d},_=await w.call(e,"Page.captureScreenshot",{format:"jpeg",quality:82,clip:x,captureBeyondViewport:!1});if(_&&_.data){m=n.replace(/\.png$/i,"")+".crop.jpg";k.writeFileSync(m,Buffer.from(_.data,"base64"))}}console.log(JSON.stringify({ok:!0,selector:r.selector,prompt:r.prompt||"",crop:m,crop_scale:m?d:null,crop_pad:m?u:null,saved:n,rect_css:s,rect_screenshot_px:{x:Math.round(s.x*l),y:Math.round(s.y*l),w:Math.round(s.w*l),h:Math.round(s.h*l)},dpr:l,natural:r.natural,viewport:r.viewport,guide:"① read_local_file 打开 crop(只含验证码、已放大)认清每个待点字与顺序(注意会混入不在 prompt 里的干扰字,只点 prompt 要求的)。"+"② 坐标直接读成「在 crop 这张图里的比例」(0..1,左上角为 0,0)——不用管 pad/rect,看到字在 crop 的哪就填哪。"+'③ 执行:ppcli browser <session> captcha-click --crop --in "'+r.selector+'" "x1,y1 x2,y2 ..."(--crop 表示坐标是 crop 图比例;空格分隔,顺序即点击顺序)。'+"命令会回读点了几个、验证码是否还在、URL 是否跳转,据此判断成功/补点/重来。"},null,2))}));R(g.command("captcha-click").argument("<points>",'待点击坐标,空格分隔且顺序即点击顺序,如 "0.30,0.46 0.68,0.66"')).option("--in <selector>","坐标映射基准元素(缺省自动探测验证码图片)").option("--crop","坐标按「captcha 裁剪图(crop)里的比例」解释(0..1,左上角为0,0)——AI 看哪张就按那张填,内部自动扣掉 pad。推荐").option("--px","坐标按「截图设备像素」解释(自动按 devicePixelRatio 换算成 CSS 像素)").option("--css","坐标按「CSS 视口像素」解释(直接点击,不做映射)").option("--delay <ms>","每次点击之间的间隔毫秒","250").description("按坐标依次点击(点选验证码用):把 AI 从图上读到的位置一次性点上,点完回读验证码是否还在/是否跳转。默认坐标为相对基准元素的比例(0..1),--crop 则为裁剪图比例").action(S(async(e,t,o)=>{const n=String(t??"").trim().split(/\s+/).filter(Boolean).map((h)=>{const[A,M]=h.split(",");return{x:Number(A),y:Number(M)}});if(n.length===0||n.some((h)=>!Number.isFinite(h.x)||!Number.isFinite(h.y))){console.log(JSON.stringify({error:{code:"usage_error",message:'坐标格式应为 "x,y x,y ...",如 "0.30,0.46 0.68,0.66"'}},null,2));process.exitCode=f.USAGE_ERROR;return}const s=o?.css?"css":o?.px?"px":o?.crop?"crop":"frac",l=Math.max(0,Number(o?.delay??250)||0);let d={x:0,y:0,w:0,h:0},u=1;if(s!=="css"){const h=await e.evaluate(ye(typeof o?.in==="string"?o.in:void 0));if(!h||!h.found||!h.rect){console.log(JSON.stringify({error:{code:"captcha_not_found",message:"captcha-click 找不到基准元素,请用 --in <selector> 指定,或用 --css 传绝对坐标"}},null,2));process.exitCode=f.USAGE_ERROR;return}d=h.rect;u=h.dpr||1}const m=ce,w=d.w+m*2,x=d.h+m*2,_=Math.max(0,d.x-m),D=Math.max(0,d.y-m),B=(h)=>{if(s==="css")return h;if(s==="px")return{x:h.x/u,y:h.y/u};if(s==="crop")return{x:_+h.x*w,y:D+h.y*x};return{x:d.x+h.x*d.w,y:d.y+h.y*d.h}},{cdp:I,nativeClick:L}=e,J=(h)=>new Promise((A)=>setTimeout(A,h));async function z(h,A,M,W){if(typeof I==="function"){const Z=12+W%4;for(let F=1;F<=Z;F++){const oe=F/Z,ie=oe*oe*(3-2*oe),P=Math.sin(oe*Math.PI)*10*(W%2===0?1:-1),H=M.x+(h-M.x)*ie,Me=M.y+(A-M.y)*ie+P;await I.call(e,"Input.dispatchMouseEvent",{type:"mouseMoved",x:Math.round(H),y:Math.round(Me)});await J(8+F%3*6)}await I.call(e,"Input.dispatchMouseEvent",{type:"mouseMoved",x:h,y:A});await J(40+W%3*25);await I.call(e,"Input.dispatchMouseEvent",{type:"mousePressed",x:h,y:A,button:"left",clickCount:1});await J(45+W%4*20);await I.call(e,"Input.dispatchMouseEvent",{type:"mouseReleased",x:h,y:A,button:"left",clickCount:1});return"cdp"}if(typeof L==="function"){await L.call(e,h,A);return"native"}await e.evaluate(`(() => { var el = document.elementFromPoint(${h}, ${A}); if (!el) return false; ['mousemove','mousedown','mouseup','click'].forEach(function(t){ el.dispatchEvent(new MouseEvent(t, { bubbles: true, cancelable: true, view: window, clientX: ${h}, clientY: ${A} })); }); return true; })()`);return"synthetic"}const te=[];let y="synthetic",C={x:Math.round(d.x+d.w/2)||400,y:Math.round(d.y-40)||200};for(let h=0;h<n.length;h++){const A=B(n[h]),M=Math.round(A.x),W=Math.round(A.y);y=await z(M,W,C,h);C={x:M,y:W};te.push({x:M,y:W});if(h<n.length-1&&l>0)await J(l)}await J(700);let q={};try{q=await e.evaluate(Qe(typeof o?.in==="string"?o.in:void 0))}catch{}console.log(JSON.stringify({ok:!0,mode:s,method:y,clicked_n:te.length,points_css:te,after:q},null,2))}));R(g.command("console")).option("--level <level>","Console level: all, error, warning, log, info, debug","all").option("--since <duration>","Only include messages from the last duration (for example: 30s, 2m)").option("--until <duration>","Only include messages older than the duration from now").option("--follow","Continuously print new console messages as JSON lines",!1).description("Read recent browser console messages").action(S(async(e,t)=>{const o=$e(t.since,"since"),r=$e(t.until,"until");if(o&&typeof o==="object"){console.log(JSON.stringify({error:{code:"invalid_since",message:o.error}},null,2));process.exitCode=f.USAGE_ERROR;return}if(r&&typeof r==="object"){console.log(JSON.stringify({error:{code:"invalid_until",message:r.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const n=(d)=>d.map((u)=>{if(u&&typeof u==="object"){const m=u;return{...m,timestamp:He(m.timestamp)}}return{type:"log",text:String(u),timestamp:Date.now()}}),s=(d)=>Ve(d,{sinceMs:o,untilMs:r}).filter((u)=>{if(t.level==="all")return!0;const m=String(u.type??u.level??"").toLowerCase();return t.level==="error"?m==="error"||m==="warning":m===String(t.level).toLowerCase()});if(t.follow){let d=0;while(!0){const u=s(n(await e.consoleMessages("all"))),m=selectFreshByTimestamp(u,d);for(const w of m.fresh)console.log(JSON.stringify({...w,timestamp:ge(w.timestamp)}));d=m.lastSeenTs;await new Promise((w)=>setTimeout(w,At))}}const l=s(n(await e.consoleMessages(t.level)));console.log(JSON.stringify({session:Ye(e),captured_at:new Date().toISOString(),count:l.length,messages:l.map((d)=>({...d,timestamp:ge(d.timestamp)}))},null,2))}));R(g.command("analyze").argument("<url>")).description("Classify site: anti-bot vendor, real-data API candidates, pattern (A/B/C/D), nearest adapter, next step").action(S(async(e,t)=>{const o=await e.startNetworkCapture?.()??!1;await e.goto(t);await e.wait(2);if(!o)try{await e.evaluate(Oe)}catch{}await he(e);await e.wait(1);const n=(await he(e)).map((_)=>({url:_.url,status:_.status,contentType:_.ct,bodyPreview:typeof _.body==="string"?_.body.slice(0,2000):_.body?JSON.stringify(_.body).slice(0,2000):null})),s=`(function(){
73
73
  return {
74
74
  cookieNames: (document.cookie || '').split(';').map(function(c){ return c.trim().split('=')[0]; }).filter(Boolean),
75
75
  initialState: {
@@ -81,7 +81,7 @@ Examples:
81
81
  title: document.title || '',
82
82
  finalUrl: location.href,
83
83
  };
84
- })()`,l=await e.evaluate(s),d=(await e.getCookies({url:l.finalUrl||t}).catch(()=>[])).map((_)=>_.name).filter(Boolean),u=[...new Set([...l.cookieNames,...d])],m={requestedUrl:t,finalUrl:l.finalUrl,cookieNames:u,networkEntries:n,initialState:l.initialState,title:l.title},y=Go(m,Se()),x=resolveSitemapAvailabilityForUrl(l.finalUrl||t);console.log(JSON.stringify({...y,...x?{sitemap:x}:{}},null,2))}));const L=(e)=>e.option("--role <role>","Semantic role (button, link, textbox, option, etc.)").option("--name <text>","Accessible name contains text (aria-label, label, title, placeholder, or visible text)").option("--label <text>","Associated label contains text").option("--text <text>","Visible text contains text").option("--testid <id>","data-testid / data-test / test-id contains id"),Ye=(e,t)=>e.option(`--${t}-role <role>`,`${t} semantic role`).option(`--${t}-name <text>`,`${t} accessible name contains text`).option(`--${t}-label <text>`,`${t} associated label contains text`).option(`--${t}-text <text>`,`${t} visible text contains text`).option(`--${t}-testid <id>`,`${t} data-testid / data-test / test-id contains id`),we=(e)=>{const t={};for(const o of["role","name","label","text","testid"]){const r=e[o];if(typeof r==="string"&&r.trim())t[o]=r.trim()}return Object.keys(t).length>0?t:null},Wt=(e,t)=>{const o={},r={role:`${t}Role`,name:`${t}Name`,label:`${t}Label`,text:`${t}Text`,testid:`${t}Testid`};for(const n of["role","name","label","text","testid"]){const s=e[r[n]];if(typeof s==="string"&&s.trim())o[n]=s.trim()}return Object.keys(o).length>0?o:null},Qe=async(e,t,o)=>{const r=await e.evaluate(St({...t,limit:6}));if(xt(r))return r;if(o==="write"&&r.matches_n!==1)return{error:{code:"semantic_ambiguous",message:`Semantic locator matched ${r.matches_n} elements; write actions require a unique target.`,hint:"Add --name/--label/--text/--testid or use browser find with a narrower locator.",matches_n:r.matches_n,entries:r.entries}};const n=r.entries[0];if(!n)return{error:{code:"semantic_not_found",message:"Semantic locator matched 0 elements",hint:"Try browser state, --source ax, or relax the semantic locator."}};const s=String(n.ref);if(o==="read")return{target:s,...r.matches_n>1?{total_matches:r.matches_n}:{}};return s},Ht=async(e,t,o)=>{const r=we(t);if(!r)return null;return Qe(e,r,o)},ke=async(e,t,o,r)=>{const n=typeof t==="string"&&t.trim()?t.trim():"",s=!!we(o);if(n&&s)return{error:{code:"usage_error",message:"Pass either <target> or semantic locator flags, not both."}};if(n)return n;const l=await Ht(e,o,r);if(l)return l;return{error:{code:"usage_error",message:"Missing target. Pass a numeric ref/CSS selector, or semantic flags like --role button --name Submit."}}},ce=(e)=>{console.log(JSON.stringify(e,null,2));process.exitCode=f.USAGE_ERROR},le=async(e,t,o)=>{const r=await ke(e,t,o,"write");if(typeof r==="string")return r;if("error"in r)ce(r);return null},Ne=async(e,t,o,r,n)=>{const s=!!we(r);if(s&&o!==void 0){ce({error:{code:"usage_error",message:`When using semantic locator flags, pass only <${n}> as the positional argument.`}});return null}const l=s?t:o;if(l===void 0){ce({error:{code:"usage_error",message:`Missing ${n}.`,hint:s?`With semantic locator flags, pass the ${n} as the only positional argument.`:`Pass both a target and ${n}.`}});return null}const d=await le(e,s?void 0:t,r);if(!d)return null;return{target:d,value:String(l)}},et=async(e,t,o,r,n)=>{const s=typeof t==="string"&&t.trim()?t.trim():"",l=Wt(o,r);if(s&&l){ce({error:{code:"usage_error",message:`Pass either <${n}> or --${r}-* semantic locator flags, not both.`}});return null}if(s)return s;if(l){const d=await Qe(e,l,"write");if(typeof d==="string")return d;if("error"in d)ce(d);return null}ce({error:{code:"usage_error",message:`Missing ${n}. Pass a numeric ref/CSS selector, or --${r}-role/--${r}-name semantic flags.`}});return null};R(L(g.command("find")).option("--css <selector>","CSS selector (required)").option("--limit <n>","Max entries returned","50").option("--text-max <n>","Max chars of trimmed text per entry","120").description("Find DOM elements by CSS or semantic locator — returns JSON {matches_n, entries[]}")).action(S(async(e,t)=>{const o=we(t);if((!t.css||typeof t.css!=="string")&&!o){console.log(JSON.stringify({error:{code:"usage_error",message:"--css <selector> or a semantic locator flag is required",hint:'Examples: ppcli browser find --css ".btn.primary"; ppcli browser find --role button --name Save'}},null,2));process.exitCode=f.USAGE_ERROR;return}if(t.css&&o){console.log(JSON.stringify({error:{code:"usage_error",message:"Pass either --css or semantic locator flags, not both."}},null,2));process.exitCode=f.USAGE_ERROR;return}const r=E(t.limit);if(r&&typeof r==="object"&&"error"in r){console.log(JSON.stringify({error:{code:"usage_error",message:r.error.replace("--nth","--limit")}},null,2));process.exitCode=f.USAGE_ERROR;return}const n=E(t.textMax);if(n&&typeof n==="object"&&"error"in n){console.log(JSON.stringify({error:{code:"usage_error",message:n.error.replace("--nth","--text-max")}},null,2));process.exitCode=f.USAGE_ERROR;return}const s=await e.evaluate(o?St({...o,limit:r??void 0,textMax:n??void 0}):Ao(t.css,{limit:r??void 0,textMax:n??void 0}));if(xt(s)){console.log(JSON.stringify(s,null,2));process.exitCode=f.GENERIC_ERROR;return}console.log(JSON.stringify(s,null,2))}));const de=g.command("get").description("Get page properties");R(de.command("title").description("Page title")).action(S(async(e)=>{console.log(await e.evaluate("document.title"))}));R(de.command("url").description("Current page URL")).action(S(async(e)=>{console.log(await e.getCurrentUrl?.()??await e.evaluate("location.href"))}));const Ae=async(e,t,o,r,n)=>{const s=await ke(e,t,o,"read");if(typeof s!=="string"&&"error"in s){console.log(JSON.stringify(s,null,2));process.exitCode=f.USAGE_ERROR;return}const l=typeof s==="string"?s:s.target,d=typeof s==="string"?void 0:s.total_matches,u=E(o.nth);if(u&&typeof u==="object"&&"error"in u){console.log(JSON.stringify({error:{code:"usage_error",message:u.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{matches_n:m,match_level:y}=await v(e,l,{firstOnMulti:u===null,...typeof u==="number"?{nth:u}:{}}),x=await e.evaluate(r);let _;if(n==="attributes")try{_=x==null?{}:JSON.parse(String(x))}catch{_=x}else _=x??null;console.log(JSON.stringify({value:_,matches_n:m,match_level:y,...d&&d>1?{total_matches:d}:{}},null,2))};R(L(de.command("text")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","Pick the nth match (0-based) when <target> is a multi-match CSS selector").description("Element text content — JSON envelope {value, matches_n}")).action(S(async(e,t,o)=>Ae(e,t,o??{},_o(),"text")));R(L(de.command("value")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","Pick the nth match (0-based) when <target> is a multi-match CSS selector").description("Input/textarea value — JSON envelope {value, matches_n}")).action(S(async(e,t,o)=>Ae(e,t,o??{},Oo(),"value")));R(de.command("html").option("--selector <css>","CSS selector scope (first match)").option("--as <format>",'Output format: "html" (default) or "json" for structured tree',"html").option("--max <n>","Max characters of raw HTML to return (0 = unlimited)","0").option("--depth <n>","(--as json) Max tree depth below root (0 = root only, 0 disables = unlimited via empty)","").option("--children-max <n>","(--as json) Max element children kept per node (empty = unlimited)","").option("--text-max <n>","(--as json) Max chars of direct text kept per node (empty = unlimited)","").description("Page HTML (or scoped); use --as json for a {tag, attrs, text, children} tree")).action(S(async(e,t)=>{const o=String(t.as||"html").toLowerCase();if(o!=="html"&&o!=="json"){console.log(JSON.stringify({error:{code:"invalid_format",message:`--as must be "html" or "json", got "${t.as}"`}},null,2));process.exitCode=f.USAGE_ERROR;return}const r=String(t.max??"0");if(!/^\d+$/.test(r)){console.log(JSON.stringify({error:{code:"invalid_max",message:`--max must be a non-negative integer, got "${t.max}"`}},null,2));process.exitCode=f.USAGE_ERROR;return}const n=Number.parseInt(r,10);if(o==="json"){const u=(J,P)=>{const z=P===void 0||P===null?"":String(P);if(z==="")return null;if(!/^\d+$/.test(z))return{error:`${J} must be a non-negative integer, got "${z}"`};return Number.parseInt(z,10)},m=u("--depth",t.depth),y=u("--children-max",t.childrenMax),x=u("--text-max",t.textMax);for(const J of[m,y,x])if(J&&typeof J==="object"&&"error"in J){console.log(JSON.stringify({error:{code:"invalid_budget",message:J.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const _=jo({selector:t.selector??null,depth:m,childrenMax:y,textMax:x}),D=await e.evaluate(_);if(D&&typeof D==="object"&&"invalidSelector"in D&&D.invalidSelector){console.log(JSON.stringify({error:{code:"invalid_selector",message:`Selector "${t.selector}" is not a valid CSS selector: ${D.reason}`}},null,2));process.exitCode=f.USAGE_ERROR;return}const j=D;if(!j||j.matched===0){console.log(JSON.stringify({error:{code:"selector_not_found",message:t.selector?`Selector "${t.selector}" matched 0 elements.`:"Page has no documentElement."}},null,2));process.exitCode=f.USAGE_ERROR;return}console.log(JSON.stringify(j,null,2));return}const s=t.selector?JSON.stringify(t.selector):"null",l=await e.evaluate(`(() => {
84
+ })()`,l=await e.evaluate(s),d=(await e.getCookies({url:l.finalUrl||t}).catch(()=>[])).map((_)=>_.name).filter(Boolean),u=[...new Set([...l.cookieNames,...d])],m={requestedUrl:t,finalUrl:l.finalUrl,cookieNames:u,networkEntries:n,initialState:l.initialState,title:l.title},w=Go(m,ve()),x=resolveSitemapAvailabilityForUrl(l.finalUrl||t);console.log(JSON.stringify({...w,...x?{sitemap:x}:{}},null,2))}));const G=(e)=>e.option("--role <role>","Semantic role (button, link, textbox, option, etc.)").option("--name <text>","Accessible name contains text (aria-label, label, title, placeholder, or visible text)").option("--label <text>","Associated label contains text").option("--text <text>","Visible text contains text").option("--testid <id>","data-testid / data-test / test-id contains id"),et=(e,t)=>e.option(`--${t}-role <role>`,`${t} semantic role`).option(`--${t}-name <text>`,`${t} accessible name contains text`).option(`--${t}-label <text>`,`${t} associated label contains text`).option(`--${t}-text <text>`,`${t} visible text contains text`).option(`--${t}-testid <id>`,`${t} data-testid / data-test / test-id contains id`),be=(e)=>{const t={};for(const o of["role","name","label","text","testid"]){const r=e[o];if(typeof r==="string"&&r.trim())t[o]=r.trim()}return Object.keys(t).length>0?t:null},Ht=(e,t)=>{const o={},r={role:`${t}Role`,name:`${t}Name`,label:`${t}Label`,text:`${t}Text`,testid:`${t}Testid`};for(const n of["role","name","label","text","testid"]){const s=e[r[n]];if(typeof s==="string"&&s.trim())o[n]=s.trim()}return Object.keys(o).length>0?o:null},tt=async(e,t,o)=>{const r=await e.evaluate(vt({...t,limit:6}));if(Rt(r))return r;if(o==="write"&&r.matches_n!==1)return{error:{code:"semantic_ambiguous",message:`Semantic locator matched ${r.matches_n} elements; write actions require a unique target.`,hint:"Add --name/--label/--text/--testid or use browser find with a narrower locator.",matches_n:r.matches_n,entries:r.entries}};const n=r.entries[0];if(!n)return{error:{code:"semantic_not_found",message:"Semantic locator matched 0 elements",hint:"Try browser state, --source ax, or relax the semantic locator."}};const s=String(n.ref);if(o==="read")return{target:s,...r.matches_n>1?{total_matches:r.matches_n}:{}};return s},Vt=async(e,t,o)=>{const r=be(t);if(!r)return null;return tt(e,r,o)},Ae=async(e,t,o,r)=>{const n=typeof t==="string"&&t.trim()?t.trim():"",s=!!be(o);if(n&&s)return{error:{code:"usage_error",message:"Pass either <target> or semantic locator flags, not both."}};if(n)return n;const l=await Vt(e,o,r);if(l)return l;return{error:{code:"usage_error",message:"Missing target. Pass a numeric ref/CSS selector, or semantic flags like --role button --name Submit."}}},le=(e)=>{console.log(JSON.stringify(e,null,2));process.exitCode=f.USAGE_ERROR},de=async(e,t,o)=>{const r=await Ae(e,t,o,"write");if(typeof r==="string")return r;if("error"in r)le(r);return null},Te=async(e,t,o,r,n)=>{const s=!!be(r);if(s&&o!==void 0){le({error:{code:"usage_error",message:`When using semantic locator flags, pass only <${n}> as the positional argument.`}});return null}const l=s?t:o;if(l===void 0){le({error:{code:"usage_error",message:`Missing ${n}.`,hint:s?`With semantic locator flags, pass the ${n} as the only positional argument.`:`Pass both a target and ${n}.`}});return null}const d=await de(e,s?void 0:t,r);if(!d)return null;return{target:d,value:String(l)}},ot=async(e,t,o,r,n)=>{const s=typeof t==="string"&&t.trim()?t.trim():"",l=Ht(o,r);if(s&&l){le({error:{code:"usage_error",message:`Pass either <${n}> or --${r}-* semantic locator flags, not both.`}});return null}if(s)return s;if(l){const d=await tt(e,l,"write");if(typeof d==="string")return d;if("error"in d)le(d);return null}le({error:{code:"usage_error",message:`Missing ${n}. Pass a numeric ref/CSS selector, or --${r}-role/--${r}-name semantic flags.`}});return null};R(G(g.command("find")).option("--css <selector>","CSS selector (required)").option("--limit <n>","Max entries returned","50").option("--text-max <n>","Max chars of trimmed text per entry","120").description("Find DOM elements by CSS or semantic locator — returns JSON {matches_n, entries[]}")).action(S(async(e,t)=>{const o=be(t);if((!t.css||typeof t.css!=="string")&&!o){console.log(JSON.stringify({error:{code:"usage_error",message:"--css <selector> or a semantic locator flag is required",hint:'Examples: ppcli browser find --css ".btn.primary"; ppcli browser find --role button --name Save'}},null,2));process.exitCode=f.USAGE_ERROR;return}if(t.css&&o){console.log(JSON.stringify({error:{code:"usage_error",message:"Pass either --css or semantic locator flags, not both."}},null,2));process.exitCode=f.USAGE_ERROR;return}const r=E(t.limit);if(r&&typeof r==="object"&&"error"in r){console.log(JSON.stringify({error:{code:"usage_error",message:r.error.replace("--nth","--limit")}},null,2));process.exitCode=f.USAGE_ERROR;return}const n=E(t.textMax);if(n&&typeof n==="object"&&"error"in n){console.log(JSON.stringify({error:{code:"usage_error",message:n.error.replace("--nth","--text-max")}},null,2));process.exitCode=f.USAGE_ERROR;return}const s=await e.evaluate(o?vt({...o,limit:r??void 0,textMax:n??void 0}):Ao(t.css,{limit:r??void 0,textMax:n??void 0}));if(Rt(s)){console.log(JSON.stringify(s,null,2));process.exitCode=f.GENERIC_ERROR;return}console.log(JSON.stringify(s,null,2))}));const ue=g.command("get").description("Get page properties");R(ue.command("title").description("Page title")).action(S(async(e)=>{console.log(await e.evaluate("document.title"))}));R(ue.command("url").description("Current page URL")).action(S(async(e)=>{console.log(await e.getCurrentUrl?.()??await e.evaluate("location.href"))}));const Ie=async(e,t,o,r,n)=>{const s=await Ae(e,t,o,"read");if(typeof s!=="string"&&"error"in s){console.log(JSON.stringify(s,null,2));process.exitCode=f.USAGE_ERROR;return}const l=typeof s==="string"?s:s.target,d=typeof s==="string"?void 0:s.total_matches,u=E(o.nth);if(u&&typeof u==="object"&&"error"in u){console.log(JSON.stringify({error:{code:"usage_error",message:u.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{matches_n:m,match_level:w}=await v(e,l,{firstOnMulti:u===null,...typeof u==="number"?{nth:u}:{}}),x=await e.evaluate(r);let _;if(n==="attributes")try{_=x==null?{}:JSON.parse(String(x))}catch{_=x}else _=x??null;console.log(JSON.stringify({value:_,matches_n:m,match_level:w,...d&&d>1?{total_matches:d}:{}},null,2))};R(G(ue.command("text")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","Pick the nth match (0-based) when <target> is a multi-match CSS selector").description("Element text content — JSON envelope {value, matches_n}")).action(S(async(e,t,o)=>Ie(e,t,o??{},_o(),"text")));R(G(ue.command("value")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","Pick the nth match (0-based) when <target> is a multi-match CSS selector").description("Input/textarea value — JSON envelope {value, matches_n}")).action(S(async(e,t,o)=>Ie(e,t,o??{},Oo(),"value")));R(ue.command("html").option("--selector <css>","CSS selector scope (first match)").option("--as <format>",'Output format: "html" (default) or "json" for structured tree',"html").option("--max <n>","Max characters of raw HTML to return (0 = unlimited)","0").option("--depth <n>","(--as json) Max tree depth below root (0 = root only, 0 disables = unlimited via empty)","").option("--children-max <n>","(--as json) Max element children kept per node (empty = unlimited)","").option("--text-max <n>","(--as json) Max chars of direct text kept per node (empty = unlimited)","").description("Page HTML (or scoped); use --as json for a {tag, attrs, text, children} tree")).action(S(async(e,t)=>{const o=String(t.as||"html").toLowerCase();if(o!=="html"&&o!=="json"){console.log(JSON.stringify({error:{code:"invalid_format",message:`--as must be "html" or "json", got "${t.as}"`}},null,2));process.exitCode=f.USAGE_ERROR;return}const r=String(t.max??"0");if(!/^\d+$/.test(r)){console.log(JSON.stringify({error:{code:"invalid_max",message:`--max must be a non-negative integer, got "${t.max}"`}},null,2));process.exitCode=f.USAGE_ERROR;return}const n=Number.parseInt(r,10);if(o==="json"){const u=(I,L)=>{const J=L===void 0||L===null?"":String(L);if(J==="")return null;if(!/^\d+$/.test(J))return{error:`${I} must be a non-negative integer, got "${J}"`};return Number.parseInt(J,10)},m=u("--depth",t.depth),w=u("--children-max",t.childrenMax),x=u("--text-max",t.textMax);for(const I of[m,w,x])if(I&&typeof I==="object"&&"error"in I){console.log(JSON.stringify({error:{code:"invalid_budget",message:I.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const _=jo({selector:t.selector??null,depth:m,childrenMax:w,textMax:x}),D=await e.evaluate(_);if(D&&typeof D==="object"&&"invalidSelector"in D&&D.invalidSelector){console.log(JSON.stringify({error:{code:"invalid_selector",message:`Selector "${t.selector}" is not a valid CSS selector: ${D.reason}`}},null,2));process.exitCode=f.USAGE_ERROR;return}const B=D;if(!B||B.matched===0){console.log(JSON.stringify({error:{code:"selector_not_found",message:t.selector?`Selector "${t.selector}" matched 0 elements.`:"Page has no documentElement."}},null,2));process.exitCode=f.USAGE_ERROR;return}console.log(JSON.stringify(B,null,2));return}const s=t.selector?JSON.stringify(t.selector):"null",l=await e.evaluate(`(() => {
85
85
  const s = ${s};
86
86
  if (s) {
87
87
  try {
@@ -93,7 +93,7 @@ Examples:
93
93
  }
94
94
  return { kind: 'ok', html: document.documentElement ? document.documentElement.outerHTML : null };
95
95
  })()`);if(l.kind==="invalid_selector"){console.log(JSON.stringify({error:{code:"invalid_selector",message:`Selector "${t.selector}" is not a valid CSS selector: ${l.reason}`}},null,2));process.exitCode=f.USAGE_ERROR;return}const d=l.html;if(d===null){if(t.selector){console.log(JSON.stringify({error:{code:"selector_not_found",message:`Selector "${t.selector}" matched 0 elements.`}},null,2));process.exitCode=f.USAGE_ERROR;return}console.log("(empty)");return}if(n>0&&d.length>n){console.log(`<!-- ppcli: truncated ${n} of ${d.length} chars; re-run without --max (or --max 0) for full -->
96
- ${d.slice(0,n)}`);return}console.log(d)}));R(L(de.command("attributes")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","Pick the nth match (0-based) when <target> is a multi-match CSS selector").description("Element attributes — JSON envelope {value, matches_n}")).action(S(async(e,t,o)=>Ae(e,t,o??{},$o(),"attributes")));function ee(e){const t=E(e);if(t&&typeof t==="object"&&"error"in t)return t;if(typeof t==="number")return{opts:{nth:t}};return{opts:{}}}function Vt(e){const t=Array.isArray(e)?e:[];if(t.length===0)return{error:{code:"usage_error",message:"At least one file path is required.",hint:'Example: ppcli browser upload "input[type=file]" ./receipt.pdf'}};const o=[];for(const r of t){const n=String(r),s=n==="~"||n.startsWith(`~${k.sep}`)?k.join(me.homedir(),n.slice(2)):n,l=k.resolve(s);if(!O.existsSync(l))return{error:{code:"file_not_found",message:`File not found: ${l}`}};if(!O.statSync(l).isFile())return{error:{code:"not_a_file",message:`Not a regular file: ${l}`}};o.push(l)}return{files:o}}function tt(e,t){const o=E(e);if(o&&typeof o==="object"&&"error"in o)return{error:o.error.replace("--nth",t)};if(typeof o==="number")return{opts:{nth:o}};return{opts:{}}}R(L(g.command("click")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Click element — JSON envelope {clicked, target, matches_n}")).action(S(async(e,t,o)=>{const r=await ke(e,t,o??{},"write");if(typeof r!=="string"){console.log(JSON.stringify(r,null,2));process.exitCode=f.USAGE_ERROR;return}const n=ee(o?.nth);if("error"in n){console.log(JSON.stringify({error:{code:"usage_error",message:n.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{matches_n:s,match_level:l,click_method:d,hit:u,retargeted:m}=await e.click(r,n.opts);console.log(JSON.stringify({clicked:!0,target:r,matches_n:s,match_level:l,...d&&{click_method:d},...u&&{hit:u},...m&&{retargeted:m}},null,2))}));R(L(g.command("type")).argument("[targetOrText]","Numeric ref/CSS target, or text when using --role/--name/etc.").argument("[text]","Text to type").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Click element, then type text — JSON envelope {typed, text, target, matches_n, autocomplete}")).action(S(async(e,t,o,r)=>{const n=await Ne(e,t,o,r??{},"text");if(!n)return;const s=ee(r?.nth);if("error"in s){console.log(JSON.stringify({error:{code:"usage_error",message:s.error}},null,2));process.exitCode=f.USAGE_ERROR;return}await e.click(n.target,s.opts);await e.wait(0.3);const{matches_n:l,match_level:d}=await e.typeText(n.target,n.value,s.opts),u=await e.evaluate(No());if(u)await e.wait(0.4);console.log(JSON.stringify({typed:!0,text:n.value,target:n.target,matches_n:l,match_level:d,autocomplete:!!u},null,2))}));R(L(g.command("hover")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Move the mouse over an element — JSON envelope {hovered, target, matches_n}")).action(S(async(e,t,o)=>{if(typeof e.hover!=="function")throw Error("browser hover is not supported by this browser backend");const r=await le(e,t,o??{});if(!r)return;const n=ee(o?.nth);if("error"in n){console.log(JSON.stringify({error:{code:"usage_error",message:n.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{matches_n:s,match_level:l}=await e.hover(r,n.opts);console.log(JSON.stringify({hovered:!0,target:r,matches_n:s,match_level:l},null,2))}));R(L(g.command("focus")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Focus an element — JSON envelope {focused, target, matches_n}")).action(S(async(e,t,o)=>{if(typeof e.focus!=="function")throw Error("browser focus is not supported by this browser backend");const r=await le(e,t,o??{});if(!r)return;const n=ee(o?.nth);if("error"in n){console.log(JSON.stringify({error:{code:"usage_error",message:n.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{focused:s,matches_n:l,match_level:d}=await e.focus(r,n.opts);console.log(JSON.stringify({focused:s,target:r,matches_n:l,match_level:d},null,2))}));R(L(g.command("dblclick")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Double-click element — JSON envelope {dblclicked, target, matches_n}")).action(S(async(e,t,o)=>{if(typeof e.dblClick!=="function")throw Error("browser dblclick is not supported by this browser backend");const r=await le(e,t,o??{});if(!r)return;const n=ee(o?.nth);if("error"in n){console.log(JSON.stringify({error:{code:"usage_error",message:n.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{matches_n:s,match_level:l}=await e.dblClick(r,n.opts);console.log(JSON.stringify({dblclicked:!0,target:r,matches_n:s,match_level:l},null,2))}));const ot=async(e,t,o,r)=>{if(typeof e.setChecked!=="function")throw Error(`browser ${r?"check":"uncheck"} is not supported by this browser backend`);const n=await le(e,t,o);if(!n)return;const s=ee(o?.nth);if("error"in s){console.log(JSON.stringify({error:{code:"usage_error",message:s.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const l=await e.setChecked(n,r,s.opts);console.log(JSON.stringify({checked:l.checked,changed:l.changed,target:n,matches_n:l.matches_n,match_level:l.match_level,...l.kind?{kind:l.kind}:{}},null,2))};R(L(g.command("check")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Ensure a checkbox/radio/aria-checked control is checked — JSON envelope {checked, changed, target, matches_n}")).action(S(async(e,t,o)=>{await ot(e,t,o??{},!0)}));R(L(g.command("uncheck")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Ensure a checkbox/aria-checked control is unchecked — JSON envelope {checked, changed, target, matches_n}")).action(S(async(e,t,o)=>{await ot(e,t,o??{},!1)}));R(L(g.command("upload")).argument("[targetOrFile]","Numeric ref/CSS target, or first file when using --role/--name/etc.").argument("[files...]","Local file path(s) to attach").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Attach local files to a file input — JSON envelope {uploaded, files, file_names, target, matches_n}")).action(S(async(e,t,o,r)=>{if(typeof e.uploadFiles!=="function")throw Error("browser upload is not supported by this browser backend");const n=!!we(r??{}),l=await le(e,n?void 0:t,r??{});if(!l)return;const d=ee(r?.nth);if("error"in d){console.log(JSON.stringify({error:{code:"usage_error",message:d.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const u=n?[t,...Array.isArray(o)?o:[]].filter((x)=>x!==void 0):o,m=Vt(u);if("error"in m){console.log(JSON.stringify({error:m.error},null,2));process.exitCode=f.USAGE_ERROR;return}const y=await e.uploadFiles(l,m.files,d.opts);console.log(JSON.stringify(y,null,2))}));R(Ye(Ye(g.command("drag"),"from"),"to").argument("[source]","Numeric ref/CSS selector to drag from, or omit with --from-role/--from-name/etc.").argument("[target]","Numeric ref/CSS selector to drop onto, or omit with --to-role/--to-name/etc.").option("--from-nth <n>","When <source> is a multi-match CSS selector, pick the nth match (0-based)").option("--to-nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Drag one element to another — JSON envelope {dragged, source, target, source_matches_n, target_matches_n}")).action(S(async(e,t,o,r)=>{if(typeof e.drag!=="function")throw Error("browser drag is not supported by this browser backend");const n=await et(e,t,r??{},"from","source");if(!n)return;const s=await et(e,o,r??{},"to","target");if(!s)return;const l=tt(r?.fromNth,"--from-nth");if("error"in l){console.log(JSON.stringify({error:{code:"usage_error",message:l.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const d=tt(r?.toNth,"--to-nth");if("error"in d){console.log(JSON.stringify({error:{code:"usage_error",message:d.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const u=await e.drag(n,s,{from:l.opts,to:d.opts});console.log(JSON.stringify(u,null,2))}));R(L(g.command("fill")).argument("[targetOrText]","Numeric ref/CSS target, or text when using --role/--name/etc.").argument("[text]","Text to set exactly").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Set input/textarea/contenteditable text exactly and verify the value — JSON envelope {filled, verified, text, actual}")).action(S(async(e,t,o,r)=>{const n=await Ne(e,t,o,r??{},"text");if(!n)return;const s=ee(r?.nth);if("error"in s){console.log(JSON.stringify({error:{code:"usage_error",message:s.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const l=await e.fillText(n.target,n.value,s.opts);if(!l.verified)process.exitCode=f.GENERIC_ERROR;console.log(JSON.stringify({filled:l.filled,verified:l.verified,target:n.target,text:n.value,actual:l.actual,length:l.length,matches_n:l.matches_n,match_level:l.match_level,...l.mode?{mode:l.mode}:{}},null,2))}));R(L(g.command("select")).argument("[targetOrOption]","Numeric ref/CSS target, or option text when using --role/--name/etc.").argument("[option]","Option text (or value) to select").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Select dropdown option — JSON envelope {selected, target, matches_n}")).action(S(async(e,t,o,r)=>{const n=await Ne(e,t,o,r??{},"option");if(!n)return;const s=ee(r?.nth);if("error"in s){console.log(JSON.stringify({error:{code:"usage_error",message:s.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{matches_n:l,match_level:d}=await v(e,n.target,s.opts),u=await e.evaluate(ko(n.value));if(u?.error){console.log(JSON.stringify({error:{code:u.error==="Not a <select>"?"not_a_select":"option_not_found",message:u.error,...u.available&&{available:u.available},matches_n:l}},null,2));process.exitCode=f.GENERIC_ERROR;return}console.log(JSON.stringify({selected:u?.selected??n.value,target:n.target,matches_n:l,match_level:d},null,2))}));R(g.command("keys").argument("<key>","Key to press (Enter, Escape, Tab, Control+a)")).description("Press keyboard key").action(S(async(e,t)=>{await e.pressKey(t);console.log(`Pressed: ${t}`)}));const rt=g.command("dialog").description("Handle a blocking JavaScript alert/confirm/prompt dialog");R(rt.command("accept").option("--text <text>","Prompt text to submit for prompt() dialogs").description("Accept the currently open JavaScript dialog")).action(S(async(e,t)=>{if(!e.handleJavaScriptDialog)throw Error("This browser session does not support JavaScript dialog handling");try{await e.handleJavaScriptDialog(!0,t?.text)}catch(o){if(M(o).toLowerCase().includes("no dialog")){console.log(JSON.stringify({error:{code:"no_javascript_dialog",message:"No JavaScript dialog is currently open."}},null,2));process.exitCode=f.USAGE_ERROR;return}throw o}console.log(JSON.stringify({handled:!0,action:"accept",...t?.text!==void 0&&{text:t.text}},null,2))}));R(rt.command("dismiss").description("Dismiss the currently open JavaScript dialog")).action(S(async(e)=>{if(!e.handleJavaScriptDialog)throw Error("This browser session does not support JavaScript dialog handling");try{await e.handleJavaScriptDialog(!1)}catch(t){if(M(t).toLowerCase().includes("no dialog")){console.log(JSON.stringify({error:{code:"no_javascript_dialog",message:"No JavaScript dialog is currently open."}},null,2));process.exitCode=f.USAGE_ERROR;return}throw t}console.log(JSON.stringify({handled:!0,action:"dismiss"},null,2))}));R(g.command("wait")).argument("<type>","selector, text, time, xhr, or download").argument("[value]","CSS selector, text string, seconds, XHR URL regex, or download filename/URL pattern").option("--timeout <ms>","Timeout in milliseconds","10000").description('Wait for selector, text, time, matching XHR, or browser download (e.g. wait selector ".loaded", wait text "Success", wait time 3, wait xhr "/api/search", wait download receipt.pdf)').action(S(async(e,t,o,r)=>{const n=parseInt(r.timeout,10);if(t==="time"){const s=parseFloat(o??"2");await e.wait(s);console.log(`Waited ${s}s`)}else if(t==="selector"){if(!o){console.error("Missing CSS selector");process.exitCode=f.USAGE_ERROR;return}await e.wait({selector:o,timeout:n/1000});console.log(`Element "${o}" appeared`)}else if(t==="text"){if(!o){console.error("Missing text");process.exitCode=f.USAGE_ERROR;return}await e.wait({text:o,timeout:n/1000});console.log(`Text "${o}" appeared`)}else if(t==="xhr"){if(!o){console.error("Missing XHR URL regex");process.exitCode=f.USAGE_ERROR;return}let s;try{s=new RegExp(o)}catch(y){console.error(`Invalid regex "${o}": ${y instanceof Error?y.message:String(y)}`);process.exitCode=f.USAGE_ERROR;return}if(!(await e.startNetworkCapture?.()??!1))try{await e.evaluate(Ce)}catch{}await ge(e);const d=Date.now()+n,u=400;let m=null;while(Date.now()<d&&!m){m=(await ge(e)).find((x)=>s.test(x.url))??null;if(!m)await new Promise((x)=>setTimeout(x,u))}if(!m){console.log(JSON.stringify({error:{code:"xhr_not_seen",message:`No captured XHR matched /${o}/ within ${n}ms`,hint:"Check the pattern against `browser network` output; the endpoint may not have fired yet, or capture is disabled."}},null,2));process.exitCode=f.GENERIC_ERROR;return}console.log(JSON.stringify({matched:{url:m.url,status:m.status,contentType:m.ct}},null,2))}else if(t==="download"){if(typeof e.waitForDownload!=="function"){console.log(JSON.stringify({error:{code:"download_wait_unavailable",message:"The active browser backend does not support download lifecycle waits.",hint:"Use the Browser Bridge extension version 1.0.8 or newer, then retry the command."}},null,2));process.exitCode=f.GENERIC_ERROR;return}const s=await e.waitForDownload(String(o??""),n);if(!s.downloaded){const l=s.state==="interrupted"&&s.id!==void 0?"download_failed":"download_not_seen";console.log(JSON.stringify({error:{code:l,message:s.error??`No download matched "${o??"*"}" within ${n}ms`,hint:"Check the pattern against the expected filename or URL; use a longer --timeout if the download starts slowly."},download:s},null,2));process.exitCode=f.GENERIC_ERROR;return}console.log(JSON.stringify(s,null,2))}else{console.error(`Unknown wait type "${t}". Use: selector, text, time, xhr, or download`);process.exitCode=f.USAGE_ERROR}}));R(g.command("eval").argument("<js>","JavaScript code").option("--frame <index>",'Cross-origin iframe index from "browser frames"').description("Execute JS in page context, return result")).action(S(async(e,t,o)=>{let r;if(o.frame!==void 0){const n=Number.parseInt(o.frame,10);if(!Number.isInteger(n)||n<0){console.error(`Invalid frame index "${o.frame}". Use a 0-based index from "browser frames".`);process.exitCode=f.USAGE_ERROR;return}if(!e.evaluateInFrame)throw Error("This browser session does not support frame-targeted evaluation");r=await e.evaluateInFrame(t,n)}else r=await e.evaluate(t);if(typeof r==="string")console.log(r);else console.log(JSON.stringify(r,null,2))}));R(g.command("extract").option("--selector <css>","CSS selector scope; defaults to <main>/<article>/<body>").option("--chunk-size <chars>","Target chunk size in chars","20000").option("--start <char>","Start offset (use next_start_char from a previous extract)","0").description("Extract page content as markdown, paragraph-aware chunks for long pages")).action(S(async(e,t)=>{const o=String(t.chunkSize??"20000");if(!/^\d+$/.test(o)||Number.parseInt(o,10)<=0){console.log(JSON.stringify({error:{code:"invalid_chunk_size",message:`--chunk-size must be a positive integer, got "${t.chunkSize}"`}},null,2));process.exitCode=f.USAGE_ERROR;return}const r=String(t.start??"0");if(!/^\d+$/.test(r)){console.log(JSON.stringify({error:{code:"invalid_start",message:`--start must be a non-negative integer, got "${t.start}"`}},null,2));process.exitCode=f.USAGE_ERROR;return}const n=Number.parseInt(o,10),s=Number.parseInt(r,10),l=typeof t.selector==="string"&&t.selector.length>0?t.selector:null,d=Uo(l),u=await e.evaluate(d);if(!u){console.log(JSON.stringify({error:{code:"extract_failed",message:"Page returned no root element."}},null,2));process.exitCode=f.USAGE_ERROR;return}if("invalidSelector"in u){console.log(JSON.stringify({error:{code:"invalid_selector",message:`Selector "${l}" is not a valid CSS selector: ${u.reason}`}},null,2));process.exitCode=f.USAGE_ERROR;return}if("notFound"in u){console.log(JSON.stringify({error:{code:"selector_not_found",message:l?`Selector "${l}" matched 0 elements.`:"Page has no body/main/article element."}},null,2));process.exitCode=f.USAGE_ERROR;return}const m=Do({html:u.html,url:u.url,title:u.title,selector:l,start:s,chunkSize:n});console.log(JSON.stringify(m,null,2))}));R(g.command("network")).option("--detail <key>","Emit full body for the entry with this key").option("--all","Include static resources (js/css/images/telemetry)").option("--raw","Emit full bodies for every entry (skip shape preview)").option("--filter <fields>","Comma-separated field names; keep only entries whose body shape has ALL names as path segments").option("--since <duration>","Only include entries from the last duration (for example: 30s, 2m)").option("--until <duration>","Only include entries older than the duration from now").option("--follow","Continuously print new matching entries as JSON lines",!1).option("--failed","Only include failed HTTP requests (status 0 or >= 400)",!1).option("--max-body <chars>","With --detail: cap the emitted body at N chars (0 = unlimited, default)","0").option("--ttl <ms>","Cache TTL in ms for --detail lookups",String(Et)).description("Capture network requests as shape previews; retrieve full bodies by key").action(S(async(e,t)=>{const o=Ft(t.ttl,"ttl",Et),r=Ke(e),n=typeof t.detail==="string"&&t.detail.length>0,s=typeof t.filter==="string",l=_e(t.since,"since"),d=_e(t.until,"until");if(l&&typeof l==="object"){q("invalid_since",l.error);return}if(d&&typeof d==="object"){q("invalid_until",d.error);return}if(n&&s){q("invalid_args","--filter and --detail cannot be used together (one narrows a list, the other fetches a specific entry).");return}let u=null;if(s){const h=Jo(t.filter);if("reason"in h){q("invalid_filter",h.reason);return}u=h.fields}if(n&&t.follow){q("invalid_args","--follow cannot be used with --detail.");return}if(n){const h=Io(r,{ttlMs:o});if(h.status==="missing"){q("cache_missing",`No cached capture. Run "browser network" first (in session "${r}").`);return}if(h.status==="expired"){q("cache_expired",`Cache is stale (age ${h.ageMs}ms > ttl ${o}ms). Re-run "browser network" to refresh.`);return}if(h.status==="corrupt"||!h.file){q("cache_corrupt",'Cache file is malformed; re-run "browser network" to regenerate.');return}const C=To(h.file,t.detail);if(!C){q("key_not_found",`Key "${t.detail}" not in cache.`,{available_keys:h.file.entries.map((K)=>K.key)});return}const Q=String(t.maxBody??"0");if(!/^\d+$/.test(Q)){q("invalid_max_body",`--max-body must be a non-negative integer, got "${t.maxBody}"`);return}const w=Number.parseInt(Q,10);let A=C.body,G=!1;if(w>0&&typeof C.body==="string"&&C.body.length>w){A=C.body.slice(0,w);G=!0}const B=C.body_truncated===!0,F={key:C.key,url:C.url,method:C.method,status:C.status,ct:C.ct,size:C.size,...typeof C.timestamp==="number"?{timestamp:fe(C.timestamp)}:{},shape:vt(C.body),body:A};if(B||G){F.body_truncated=!0;F.body_full_size=C.body_full_size??C.size;F.body_truncation_reason=B?"capture-limit":"max-body"}console.log(JSON.stringify(F,null,2));return}if(t.follow){if(!await e.startNetworkCapture?.())try{await e.evaluate(Ce)}catch{}while(!0){const h=await ge(e).catch((w)=>{q("capture_failed",`Could not read network capture: ${w.message}`);return[]});let C=t.all?h:At(h);C=We(C,{sinceMs:l,untilMs:d});if(t.failed)C=C.filter((w)=>w.status===0||w.status>=400);const Q=Rt(C);for(const w of Q){const A=w.channel==="websocket"||w.channel==="eventsource";console.log(JSON.stringify({key:w.key,timestamp:fe(w.timestamp),method:w.method,status:w.status,url:w.url,ct:w.ct,size:w.size,...A?{channel:w.channel,direction:w.direction}:{},...w.eventName?{event_name:w.eventName}:{},...A?{body:cr(w.body)}:{},...w.bodyTruncated?{body_truncated:!0}:{}}))}await new Promise((w)=>setTimeout(w,kt))}}let m;try{m=await ge(e)}catch(h){q("capture_failed",`Could not read network capture: ${h.message}`);return}let y=t.all?m:At(m);y=We(y,{sinceMs:l,untilMs:d});if(t.failed)y=y.filter((h)=>h.status===0||h.status>=400);const x=m.length-y.length,D=Rt(y).map((h)=>({key:h.key,url:h.url,method:h.method,status:h.status,size:h.size,ct:h.ct,body:h.body,...typeof h.timestamp==="number"?{timestamp:h.timestamp}:{},...h.bodyTruncated?{body_truncated:!0}:{},...h.bodyTruncated&&typeof h.bodyFullSize==="number"?{body_full_size:h.bodyFullSize}:{}}));let j=null;try{Po(r,D)}catch(h){j=`Could not persist capture cache: ${h.message}. --detail lookups may miss this capture.`}const J=D.map((h)=>({entry:h,shape:vt(h.body)})),P=u?J.filter((h)=>Mo(h.shape,u)):J,z=u?J.length-P.length:0,W={session:r,captured_at:new Date().toISOString(),count:P.length,filtered_out:x};if(u){W.filter=u;W.filter_dropped=z}if(j)W.cache_warning=j;const ne=P.filter((h)=>h.entry.body_truncated).length;if(ne>0){W.body_truncated_count=ne;W.body_truncated_hint="Some bodies exceeded the capture limit; their `shape` reflects only the captured prefix."}if(t.raw)W.entries=P.map((h)=>({...h.entry,...typeof h.entry.timestamp==="number"?{timestamp:fe(h.entry.timestamp)}:{}}));else{W.entries=P.map((h)=>({key:h.entry.key,method:h.entry.method,...typeof h.entry.timestamp==="number"?{timestamp:fe(h.entry.timestamp)}:{},status:h.entry.status,url:h.entry.url,ct:h.entry.ct,size:h.entry.size,shape:h.shape,...h.entry.body_truncated?{body_truncated:!0}:{}}));W.detail_hint='Run "browser network --detail <key>" for full body.'}console.log(JSON.stringify(W,null,2))}));g.command("init").argument("<name>","Adapter name in site/command format (e.g. hn/top)").description("Generate adapter scaffold in ~/.ppcli/clis/").action(async(e)=>{try{const t=e.split("/");if(t.length!==2||!t[0]||!t[1]){console.error("Name must be site/command format (e.g. hn/top)");process.exitCode=f.USAGE_ERROR;return}const[o,r]=t;if(!/^[a-zA-Z0-9_-]+$/.test(o)||!/^[a-zA-Z0-9_-]+$/.test(r)){console.error("Name parts must be alphanumeric/dash/underscore only");process.exitCode=f.USAGE_ERROR;return}const n=await import("node:os"),s=await import("node:fs"),l=await import("node:path"),d=l.join(n.homedir(),".ppcli","clis",o),u=l.join(d,`${r}.js`);if(s.existsSync(u)){console.log(`Adapter already exists: ${u}`);return}const y=`import { cli, Strategy } from '@jackwener/opencli/registry';
96
+ ${d.slice(0,n)}`);return}console.log(d)}));R(G(ue.command("attributes")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","Pick the nth match (0-based) when <target> is a multi-match CSS selector").description("Element attributes — JSON envelope {value, matches_n}")).action(S(async(e,t,o)=>Ie(e,t,o??{},$o(),"attributes")));function ee(e){const t=E(e);if(t&&typeof t==="object"&&"error"in t)return t;if(typeof t==="number")return{opts:{nth:t}};return{opts:{}}}function qt(e){const t=Array.isArray(e)?e:[];if(t.length===0)return{error:{code:"usage_error",message:"At least one file path is required.",hint:'Example: ppcli browser upload "input[type=file]" ./receipt.pdf'}};const o=[];for(const r of t){const n=String(r),s=n==="~"||n.startsWith(`~${O.sep}`)?O.join(pe.homedir(),n.slice(2)):n,l=O.resolve(s);if(!k.existsSync(l))return{error:{code:"file_not_found",message:`File not found: ${l}`}};if(!k.statSync(l).isFile())return{error:{code:"not_a_file",message:`Not a regular file: ${l}`}};o.push(l)}return{files:o}}function rt(e,t){const o=E(e);if(o&&typeof o==="object"&&"error"in o)return{error:o.error.replace("--nth",t)};if(typeof o==="number")return{opts:{nth:o}};return{opts:{}}}R(G(g.command("click")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Click element — JSON envelope {clicked, target, matches_n}")).action(S(async(e,t,o)=>{const r=await Ae(e,t,o??{},"write");if(typeof r!=="string"){console.log(JSON.stringify(r,null,2));process.exitCode=f.USAGE_ERROR;return}const n=ee(o?.nth);if("error"in n){console.log(JSON.stringify({error:{code:"usage_error",message:n.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{matches_n:s,match_level:l,click_method:d,hit:u,retargeted:m}=await e.click(r,n.opts);console.log(JSON.stringify({clicked:!0,target:r,matches_n:s,match_level:l,...d&&{click_method:d},...u&&{hit:u},...m&&{retargeted:m}},null,2))}));R(G(g.command("type")).argument("[targetOrText]","Numeric ref/CSS target, or text when using --role/--name/etc.").argument("[text]","Text to type").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Click element, then type text — JSON envelope {typed, text, target, matches_n, autocomplete}")).action(S(async(e,t,o,r)=>{const n=await Te(e,t,o,r??{},"text");if(!n)return;const s=ee(r?.nth);if("error"in s){console.log(JSON.stringify({error:{code:"usage_error",message:s.error}},null,2));process.exitCode=f.USAGE_ERROR;return}await e.click(n.target,s.opts);await e.wait(0.3);const{matches_n:l,match_level:d}=await e.typeText(n.target,n.value,s.opts),u=await e.evaluate(No());if(u)await e.wait(0.4);console.log(JSON.stringify({typed:!0,text:n.value,target:n.target,matches_n:l,match_level:d,autocomplete:!!u},null,2))}));R(G(g.command("hover")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Move the mouse over an element — JSON envelope {hovered, target, matches_n}")).action(S(async(e,t,o)=>{if(typeof e.hover!=="function")throw Error("browser hover is not supported by this browser backend");const r=await de(e,t,o??{});if(!r)return;const n=ee(o?.nth);if("error"in n){console.log(JSON.stringify({error:{code:"usage_error",message:n.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{matches_n:s,match_level:l}=await e.hover(r,n.opts);console.log(JSON.stringify({hovered:!0,target:r,matches_n:s,match_level:l},null,2))}));R(G(g.command("focus")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Focus an element — JSON envelope {focused, target, matches_n}")).action(S(async(e,t,o)=>{if(typeof e.focus!=="function")throw Error("browser focus is not supported by this browser backend");const r=await de(e,t,o??{});if(!r)return;const n=ee(o?.nth);if("error"in n){console.log(JSON.stringify({error:{code:"usage_error",message:n.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{focused:s,matches_n:l,match_level:d}=await e.focus(r,n.opts);console.log(JSON.stringify({focused:s,target:r,matches_n:l,match_level:d},null,2))}));R(G(g.command("dblclick")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Double-click element — JSON envelope {dblclicked, target, matches_n}")).action(S(async(e,t,o)=>{if(typeof e.dblClick!=="function")throw Error("browser dblclick is not supported by this browser backend");const r=await de(e,t,o??{});if(!r)return;const n=ee(o?.nth);if("error"in n){console.log(JSON.stringify({error:{code:"usage_error",message:n.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{matches_n:s,match_level:l}=await e.dblClick(r,n.opts);console.log(JSON.stringify({dblclicked:!0,target:r,matches_n:s,match_level:l},null,2))}));const nt=async(e,t,o,r)=>{if(typeof e.setChecked!=="function")throw Error(`browser ${r?"check":"uncheck"} is not supported by this browser backend`);const n=await de(e,t,o);if(!n)return;const s=ee(o?.nth);if("error"in s){console.log(JSON.stringify({error:{code:"usage_error",message:s.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const l=await e.setChecked(n,r,s.opts);console.log(JSON.stringify({checked:l.checked,changed:l.changed,target:n,matches_n:l.matches_n,match_level:l.match_level,...l.kind?{kind:l.kind}:{}},null,2))};R(G(g.command("check")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Ensure a checkbox/radio/aria-checked control is checked — JSON envelope {checked, changed, target, matches_n}")).action(S(async(e,t,o)=>{await nt(e,t,o??{},!0)}));R(G(g.command("uncheck")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Ensure a checkbox/aria-checked control is unchecked — JSON envelope {checked, changed, target, matches_n}")).action(S(async(e,t,o)=>{await nt(e,t,o??{},!1)}));R(G(g.command("upload")).argument("[targetOrFile]","Numeric ref/CSS target, or first file when using --role/--name/etc.").argument("[files...]","Local file path(s) to attach").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Attach local files to a file input — JSON envelope {uploaded, files, file_names, target, matches_n}")).action(S(async(e,t,o,r)=>{if(typeof e.uploadFiles!=="function")throw Error("browser upload is not supported by this browser backend");const n=!!be(r??{}),l=await de(e,n?void 0:t,r??{});if(!l)return;const d=ee(r?.nth);if("error"in d){console.log(JSON.stringify({error:{code:"usage_error",message:d.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const u=n?[t,...Array.isArray(o)?o:[]].filter((x)=>x!==void 0):o,m=qt(u);if("error"in m){console.log(JSON.stringify({error:m.error},null,2));process.exitCode=f.USAGE_ERROR;return}const w=await e.uploadFiles(l,m.files,d.opts);console.log(JSON.stringify(w,null,2))}));R(et(et(g.command("drag"),"from"),"to").argument("[source]","Numeric ref/CSS selector to drag from, or omit with --from-role/--from-name/etc.").argument("[target]","Numeric ref/CSS selector to drop onto, or omit with --to-role/--to-name/etc.").option("--from-nth <n>","When <source> is a multi-match CSS selector, pick the nth match (0-based)").option("--to-nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Drag one element to another — JSON envelope {dragged, source, target, source_matches_n, target_matches_n}")).action(S(async(e,t,o,r)=>{if(typeof e.drag!=="function")throw Error("browser drag is not supported by this browser backend");const n=await ot(e,t,r??{},"from","source");if(!n)return;const s=await ot(e,o,r??{},"to","target");if(!s)return;const l=rt(r?.fromNth,"--from-nth");if("error"in l){console.log(JSON.stringify({error:{code:"usage_error",message:l.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const d=rt(r?.toNth,"--to-nth");if("error"in d){console.log(JSON.stringify({error:{code:"usage_error",message:d.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const u=await e.drag(n,s,{from:l.opts,to:d.opts});console.log(JSON.stringify(u,null,2))}));R(G(g.command("fill")).argument("[targetOrText]","Numeric ref/CSS target, or text when using --role/--name/etc.").argument("[text]","Text to set exactly").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Set input/textarea/contenteditable text exactly and verify the value — JSON envelope {filled, verified, text, actual}")).action(S(async(e,t,o,r)=>{const n=await Te(e,t,o,r??{},"text");if(!n)return;const s=ee(r?.nth);if("error"in s){console.log(JSON.stringify({error:{code:"usage_error",message:s.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const l=await e.fillText(n.target,n.value,s.opts);if(!l.verified)process.exitCode=f.GENERIC_ERROR;console.log(JSON.stringify({filled:l.filled,verified:l.verified,target:n.target,text:n.value,actual:l.actual,length:l.length,matches_n:l.matches_n,match_level:l.match_level,...l.mode?{mode:l.mode}:{}},null,2))}));R(G(g.command("select")).argument("[targetOrOption]","Numeric ref/CSS target, or option text when using --role/--name/etc.").argument("[option]","Option text (or value) to select").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Select dropdown option — JSON envelope {selected, target, matches_n}")).action(S(async(e,t,o,r)=>{const n=await Te(e,t,o,r??{},"option");if(!n)return;const s=ee(r?.nth);if("error"in s){console.log(JSON.stringify({error:{code:"usage_error",message:s.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const{matches_n:l,match_level:d}=await v(e,n.target,s.opts),u=await e.evaluate(ko(n.value));if(u?.error){console.log(JSON.stringify({error:{code:u.error==="Not a <select>"?"not_a_select":"option_not_found",message:u.error,...u.available&&{available:u.available},matches_n:l}},null,2));process.exitCode=f.GENERIC_ERROR;return}console.log(JSON.stringify({selected:u?.selected??n.value,target:n.target,matches_n:l,match_level:d},null,2))}));R(g.command("keys").argument("<key>","Key to press (Enter, Escape, Tab, Control+a)")).description("Press keyboard key").action(S(async(e,t)=>{await e.pressKey(t);console.log(`Pressed: ${t}`)}));const st=g.command("dialog").description("Handle a blocking JavaScript alert/confirm/prompt dialog");R(st.command("accept").option("--text <text>","Prompt text to submit for prompt() dialogs").description("Accept the currently open JavaScript dialog")).action(S(async(e,t)=>{if(!e.handleJavaScriptDialog)throw Error("This browser session does not support JavaScript dialog handling");try{await e.handleJavaScriptDialog(!0,t?.text)}catch(o){if(j(o).toLowerCase().includes("no dialog")){console.log(JSON.stringify({error:{code:"no_javascript_dialog",message:"No JavaScript dialog is currently open."}},null,2));process.exitCode=f.USAGE_ERROR;return}throw o}console.log(JSON.stringify({handled:!0,action:"accept",...t?.text!==void 0&&{text:t.text}},null,2))}));R(st.command("dismiss").description("Dismiss the currently open JavaScript dialog")).action(S(async(e)=>{if(!e.handleJavaScriptDialog)throw Error("This browser session does not support JavaScript dialog handling");try{await e.handleJavaScriptDialog(!1)}catch(t){if(j(t).toLowerCase().includes("no dialog")){console.log(JSON.stringify({error:{code:"no_javascript_dialog",message:"No JavaScript dialog is currently open."}},null,2));process.exitCode=f.USAGE_ERROR;return}throw t}console.log(JSON.stringify({handled:!0,action:"dismiss"},null,2))}));R(g.command("wait")).argument("<type>","selector, text, time, xhr, or download").argument("[value]","CSS selector, text string, seconds, XHR URL regex, or download filename/URL pattern").option("--timeout <ms>","Timeout in milliseconds","10000").description('Wait for selector, text, time, matching XHR, or browser download (e.g. wait selector ".loaded", wait text "Success", wait time 3, wait xhr "/api/search", wait download receipt.pdf)').action(S(async(e,t,o,r)=>{const n=parseInt(r.timeout,10);if(t==="time"){const s=parseFloat(o??"2");await e.wait(s);console.log(`Waited ${s}s`)}else if(t==="selector"){if(!o){console.error("Missing CSS selector");process.exitCode=f.USAGE_ERROR;return}await e.wait({selector:o,timeout:n/1000});console.log(`Element "${o}" appeared`)}else if(t==="text"){if(!o){console.error("Missing text");process.exitCode=f.USAGE_ERROR;return}await e.wait({text:o,timeout:n/1000});console.log(`Text "${o}" appeared`)}else if(t==="xhr"){if(!o){console.error("Missing XHR URL regex");process.exitCode=f.USAGE_ERROR;return}let s;try{s=new RegExp(o)}catch(w){console.error(`Invalid regex "${o}": ${w instanceof Error?w.message:String(w)}`);process.exitCode=f.USAGE_ERROR;return}if(!(await e.startNetworkCapture?.()??!1))try{await e.evaluate(Oe)}catch{}await he(e);const d=Date.now()+n,u=400;let m=null;while(Date.now()<d&&!m){m=(await he(e)).find((x)=>s.test(x.url))??null;if(!m)await new Promise((x)=>setTimeout(x,u))}if(!m){console.log(JSON.stringify({error:{code:"xhr_not_seen",message:`No captured XHR matched /${o}/ within ${n}ms`,hint:"Check the pattern against `browser network` output; the endpoint may not have fired yet, or capture is disabled."}},null,2));process.exitCode=f.GENERIC_ERROR;return}console.log(JSON.stringify({matched:{url:m.url,status:m.status,contentType:m.ct}},null,2))}else if(t==="download"){if(typeof e.waitForDownload!=="function"){console.log(JSON.stringify({error:{code:"download_wait_unavailable",message:"The active browser backend does not support download lifecycle waits.",hint:"Use the Browser Bridge extension version 1.0.8 or newer, then retry the command."}},null,2));process.exitCode=f.GENERIC_ERROR;return}const s=await e.waitForDownload(String(o??""),n);if(!s.downloaded){const l=s.state==="interrupted"&&s.id!==void 0?"download_failed":"download_not_seen";console.log(JSON.stringify({error:{code:l,message:s.error??`No download matched "${o??"*"}" within ${n}ms`,hint:"Check the pattern against the expected filename or URL; use a longer --timeout if the download starts slowly."},download:s},null,2));process.exitCode=f.GENERIC_ERROR;return}console.log(JSON.stringify(s,null,2))}else{console.error(`Unknown wait type "${t}". Use: selector, text, time, xhr, or download`);process.exitCode=f.USAGE_ERROR}}));R(g.command("eval").argument("<js>","JavaScript code").option("--frame <index>",'Cross-origin iframe index from "browser frames"').description("Execute JS in page context, return result")).action(S(async(e,t,o)=>{let r;if(o.frame!==void 0){const n=Number.parseInt(o.frame,10);if(!Number.isInteger(n)||n<0){console.error(`Invalid frame index "${o.frame}". Use a 0-based index from "browser frames".`);process.exitCode=f.USAGE_ERROR;return}if(!e.evaluateInFrame)throw Error("This browser session does not support frame-targeted evaluation");r=await e.evaluateInFrame(t,n)}else r=await e.evaluate(t);if(typeof r==="string")console.log(r);else console.log(JSON.stringify(r,null,2))}));R(g.command("extract").option("--selector <css>","CSS selector scope; defaults to <main>/<article>/<body>").option("--chunk-size <chars>","Target chunk size in chars","20000").option("--start <char>","Start offset (use next_start_char from a previous extract)","0").description("Extract page content as markdown, paragraph-aware chunks for long pages")).action(S(async(e,t)=>{const o=String(t.chunkSize??"20000");if(!/^\d+$/.test(o)||Number.parseInt(o,10)<=0){console.log(JSON.stringify({error:{code:"invalid_chunk_size",message:`--chunk-size must be a positive integer, got "${t.chunkSize}"`}},null,2));process.exitCode=f.USAGE_ERROR;return}const r=String(t.start??"0");if(!/^\d+$/.test(r)){console.log(JSON.stringify({error:{code:"invalid_start",message:`--start must be a non-negative integer, got "${t.start}"`}},null,2));process.exitCode=f.USAGE_ERROR;return}const n=Number.parseInt(o,10),s=Number.parseInt(r,10),l=typeof t.selector==="string"&&t.selector.length>0?t.selector:null,d=Uo(l),u=await e.evaluate(d);if(!u){console.log(JSON.stringify({error:{code:"extract_failed",message:"Page returned no root element."}},null,2));process.exitCode=f.USAGE_ERROR;return}if("invalidSelector"in u){console.log(JSON.stringify({error:{code:"invalid_selector",message:`Selector "${l}" is not a valid CSS selector: ${u.reason}`}},null,2));process.exitCode=f.USAGE_ERROR;return}if("notFound"in u){console.log(JSON.stringify({error:{code:"selector_not_found",message:l?`Selector "${l}" matched 0 elements.`:"Page has no body/main/article element."}},null,2));process.exitCode=f.USAGE_ERROR;return}const m=Do({html:u.html,url:u.url,title:u.title,selector:l,start:s,chunkSize:n});console.log(JSON.stringify(m,null,2))}));R(g.command("network")).option("--detail <key>","Emit full body for the entry with this key").option("--all","Include static resources (js/css/images/telemetry)").option("--raw","Emit full bodies for every entry (skip shape preview)").option("--filter <fields>","Comma-separated field names; keep only entries whose body shape has ALL names as path segments").option("--since <duration>","Only include entries from the last duration (for example: 30s, 2m)").option("--until <duration>","Only include entries older than the duration from now").option("--follow","Continuously print new matching entries as JSON lines",!1).option("--failed","Only include failed HTTP requests (status 0 or >= 400)",!1).option("--max-body <chars>","With --detail: cap the emitted body at N chars (0 = unlimited, default)","0").option("--ttl <ms>","Cache TTL in ms for --detail lookups",String(_t)).description("Capture network requests as shape previews; retrieve full bodies by key").action(S(async(e,t)=>{const o=zt(t.ttl,"ttl",_t),r=Ye(e),n=typeof t.detail==="string"&&t.detail.length>0,s=typeof t.filter==="string",l=$e(t.since,"since"),d=$e(t.until,"until");if(l&&typeof l==="object"){X("invalid_since",l.error);return}if(d&&typeof d==="object"){X("invalid_until",d.error);return}if(n&&s){X("invalid_args","--filter and --detail cannot be used together (one narrows a list, the other fetches a specific entry).");return}let u=null;if(s){const y=Jo(t.filter);if("reason"in y){X("invalid_filter",y.reason);return}u=y.fields}if(n&&t.follow){X("invalid_args","--follow cannot be used with --detail.");return}if(n){const y=Io(r,{ttlMs:o});if(y.status==="missing"){X("cache_missing",`No cached capture. Run "browser network" first (in session "${r}").`);return}if(y.status==="expired"){X("cache_expired",`Cache is stale (age ${y.ageMs}ms > ttl ${o}ms). Re-run "browser network" to refresh.`);return}if(y.status==="corrupt"||!y.file){X("cache_corrupt",'Cache file is malformed; re-run "browser network" to regenerate.');return}const C=To(y.file,t.detail);if(!C){X("key_not_found",`Key "${t.detail}" not in cache.`,{available_keys:y.file.entries.map((F)=>F.key)});return}const q=String(t.maxBody??"0");if(!/^\d+$/.test(q)){X("invalid_max_body",`--max-body must be a non-negative integer, got "${t.maxBody}"`);return}const h=Number.parseInt(q,10);let A=C.body,M=!1;if(h>0&&typeof C.body==="string"&&C.body.length>h){A=C.body.slice(0,h);M=!0}const W=C.body_truncated===!0,Z={key:C.key,url:C.url,method:C.method,status:C.status,ct:C.ct,size:C.size,...typeof C.timestamp==="number"?{timestamp:ge(C.timestamp)}:{},shape:Et(C.body),body:A};if(W||M){Z.body_truncated=!0;Z.body_full_size=C.body_full_size??C.size;Z.body_truncation_reason=W?"capture-limit":"max-body"}console.log(JSON.stringify(Z,null,2));return}if(t.follow){if(!await e.startNetworkCapture?.())try{await e.evaluate(Oe)}catch{}while(!0){const y=await he(e).catch((h)=>{X("capture_failed",`Could not read network capture: ${h.message}`);return[]});let C=t.all?y:It(y);C=Ve(C,{sinceMs:l,untilMs:d});if(t.failed)C=C.filter((h)=>h.status===0||h.status>=400);const q=Ct(C);for(const h of q){const A=h.channel==="websocket"||h.channel==="eventsource";console.log(JSON.stringify({key:h.key,timestamp:ge(h.timestamp),method:h.method,status:h.status,url:h.url,ct:h.ct,size:h.size,...A?{channel:h.channel,direction:h.direction}:{},...h.eventName?{event_name:h.eventName}:{},...A?{body:cr(h.body)}:{},...h.bodyTruncated?{body_truncated:!0}:{}}))}await new Promise((h)=>setTimeout(h,At))}}let m;try{m=await he(e)}catch(y){X("capture_failed",`Could not read network capture: ${y.message}`);return}let w=t.all?m:It(m);w=Ve(w,{sinceMs:l,untilMs:d});if(t.failed)w=w.filter((y)=>y.status===0||y.status>=400);const x=m.length-w.length,D=Ct(w).map((y)=>({key:y.key,url:y.url,method:y.method,status:y.status,size:y.size,ct:y.ct,body:y.body,...typeof y.timestamp==="number"?{timestamp:y.timestamp}:{},...y.bodyTruncated?{body_truncated:!0}:{},...y.bodyTruncated&&typeof y.bodyFullSize==="number"?{body_full_size:y.bodyFullSize}:{}}));let B=null;try{Po(r,D)}catch(y){B=`Could not persist capture cache: ${y.message}. --detail lookups may miss this capture.`}const I=D.map((y)=>({entry:y,shape:Et(y.body)})),L=u?I.filter((y)=>Mo(y.shape,u)):I,J=u?I.length-L.length:0,z={session:r,captured_at:new Date().toISOString(),count:L.length,filtered_out:x};if(u){z.filter=u;z.filter_dropped=J}if(B)z.cache_warning=B;const te=L.filter((y)=>y.entry.body_truncated).length;if(te>0){z.body_truncated_count=te;z.body_truncated_hint="Some bodies exceeded the capture limit; their `shape` reflects only the captured prefix."}if(t.raw)z.entries=L.map((y)=>({...y.entry,...typeof y.entry.timestamp==="number"?{timestamp:ge(y.entry.timestamp)}:{}}));else{z.entries=L.map((y)=>({key:y.entry.key,method:y.entry.method,...typeof y.entry.timestamp==="number"?{timestamp:ge(y.entry.timestamp)}:{},status:y.entry.status,url:y.entry.url,ct:y.entry.ct,size:y.entry.size,shape:y.shape,...y.entry.body_truncated?{body_truncated:!0}:{}}));z.detail_hint='Run "browser network --detail <key>" for full body.'}console.log(JSON.stringify(z,null,2))}));g.command("init").argument("<name>","Adapter name in site/command format (e.g. hn/top)").description("Generate adapter scaffold in ~/.ppcli/clis/").action(async(e)=>{try{const t=e.split("/");if(t.length!==2||!t[0]||!t[1]){console.error("Name must be site/command format (e.g. hn/top)");process.exitCode=f.USAGE_ERROR;return}const[o,r]=t;if(!/^[a-zA-Z0-9_-]+$/.test(o)||!/^[a-zA-Z0-9_-]+$/.test(r)){console.error("Name parts must be alphanumeric/dash/underscore only");process.exitCode=f.USAGE_ERROR;return}const n=await import("node:os"),s=await import("node:fs"),l=await import("node:path"),d=l.join(n.homedir(),".ppcli","clis",o),u=l.join(d,`${r}.js`);if(s.existsSync(u)){console.log(`Adapter already exists: ${u}`);return}const w=`import { cli, Strategy } from '@jackwener/opencli/registry';
97
97
 
98
98
  cli({
99
99
  site: '${o}',
@@ -115,18 +115,18 @@ cli({
115
115
  return [];
116
116
  },
117
117
  });
118
- `;s.mkdirSync(d,{recursive:!0});s.writeFileSync(u,y,"utf-8");console.log(`Created: ${u}`);console.log("First time on this site? Run: ppcli browser analyze <url>");console.log(`Edit the file to implement your adapter, then run: ppcli browser verify ${e}`)}catch(t){console.error(`Error: ${t instanceof Error?t.message:String(t)}`);process.exitCode=f.GENERIC_ERROR}});g.command("verify").argument("<name>","Adapter name in site/command format (e.g. hn/top)").option("--write-fixture","Write a starter fixture to ~/.ppcli/sites/<site>/verify/<command>.json if none exists").option("--update-fixture","Overwrite an existing fixture with one derived from current output").option("--no-fixture","Ignore any fixture file for this run (no value-level validation)").option("--strict-memory","Fail (not just warn) when ~/.ppcli/sites/<site>/endpoints.json or notes.md is missing").option("--seed-args <value>","Seed args when no fixture exists; use JSON array/object for multiple args or flags").option("--trace <mode>","Trace capture for the adapter subprocess: off, on, retain-on-failure","off").description("Execute an adapter and validate output; uses fixture at ~/.ppcli/sites/<site>/verify/<cmd>.json when present").action(async(e,t={})=>{try{const o=e.split("/");if(o.length!==2){console.error("Name must be site/command format");process.exitCode=f.USAGE_ERROR;return}const[r,n]=o;if(!/^[a-zA-Z0-9_-]+$/.test(r)||!/^[a-zA-Z0-9_-]+$/.test(n)){console.error("Name parts must be alphanumeric/dash/underscore only");process.exitCode=f.USAGE_ERROR;return}const{execFileSync:s}=await import("node:child_process"),{loadFixture:l,writeFixture:d,deriveFixture:u,validateRows:m,validateRowShape:y,fixturePath:x,expandFixtureArgs:_,parseSeedArgs:D}=await import("./browser/verify-fixture.js"),j=k.join(me.homedir(),".ppcli","clis",r,`${n}.js`);if(!O.existsSync(j)){console.error(`Adapter not found: ${j}`);console.error(`Run "ppcli browser init ${e}" to create it.`);process.exitCode=f.GENERIC_ERROR;return}console.log(`\uD83D\uDD0D Verifying ${e}...
119
- `);console.log(` Loading: ${j}`);let P=t.fixture!==!1?l(r,n):null;const z=O.readFileSync(j,"utf-8"),W=/['"]limit['"]/.test(z),ne=D(t.seedArgs),h=P?.args??ne,C=_(h);if(h===void 0&&C.length===0&&W)C.push("--limit","3");const Q=t.trace&&t.trace!=="off"?["--trace",t.trace]:[],w=[...C,...Q].join(" "),A=resolveBrowserVerifyInvocation(),G=[...A.args,r,n,...C,...Q,"--format","json"];let B;try{B=s(A.binary,G,{cwd:A.cwd,timeout:30000,encoding:"utf-8",env:process.env,stdio:["pipe","pipe","pipe"],...A.shell?{shell:!0}:{}})}catch(I){console.log(` Executing: ppcli ${r} ${n} ${w}
120
- `);const H=I;if(H.stdout)console.log(String(H.stdout));if(H.stderr)console.error(String(H.stderr).slice(0,500));console.log(`
121
- ✗ Adapter failed. Fix the code and try again.`);process.exitCode=f.GENERIC_ERROR;return}console.log(` Executing: ppcli ${r} ${n} ${w}
122
- `);let F;try{F=normalizeVerifyRows(JSON.parse(B))}catch{console.log(B);console.log("\n ✗ Could not parse adapter output as JSON. Is `--format json` broken?");process.exitCode=f.GENERIC_ERROR;return}console.log(renderVerifyPreview(F));console.log(`
123
- → ${F.length} row${F.length===1?"":"s"}`);const K=y(F);if(K.length>0){console.log(`
124
- ✗ Adapter output violates row shape conventions:`);for(const I of K.slice(0,20)){const H=I.rowIndex!==void 0?`row[${I.rowIndex}] `:"";console.log(` - [${I.rule}] ${H}${I.detail}`)}if(K.length>20)console.log(` ... and ${K.length-20} more failure(s)`);console.log(`
125
- Keep rows agent-native: <=12 top-level keys, nesting depth <=1, and id-shaped fields at top level.`);process.exitCode=f.GENERIC_ERROR;return}if(t.writeFixture||t.updateFixture)if(P&&!t.updateFixture){console.log(`
126
- Fixture already exists at ${x(r,n)}.`);console.log(" Use --update-fixture to overwrite.")}else{const H=u(F,h!==void 0?h:W?{limit:3}:void 0),Pe=d(r,n,H);console.log(`
127
- ${P?"↻ Updated":"✎ Wrote"} fixture: ${Pe}`);console.log(" Review and hand-tune the derived expectations (add patterns / notEmpty, tighten rowCount).");P=H}if(!P){console.log(`
128
- ✓ Adapter runs. (No fixture at ${x(r,n)} — consider --write-fixture to seed one.)`);const I=checkSiteMemory(r);printSiteMemoryReport(I,t.strictMemory);if(!I.ok&&t.strictMemory)process.exitCode=f.GENERIC_ERROR;return}const te=m(F,P);if(te.length===0){console.log(`
129
- ✓ Adapter matches fixture (${x(r,n)}).`);const I=checkSiteMemory(r);printSiteMemoryReport(I,t.strictMemory);if(!I.ok&&t.strictMemory)process.exitCode=f.GENERIC_ERROR;return}console.log(`
130
- ✗ Adapter output does not match fixture:`);for(const I of te.slice(0,20)){const H=I.rowIndex!==void 0?`row[${I.rowIndex}] `:"";console.log(` - [${I.rule}] ${H}${I.detail}`)}if(te.length>20)console.log(` ... and ${te.length-20} more failure(s)`);process.exitCode=f.GENERIC_ERROR}catch(o){console.error(`Error: ${o instanceof Error?o.message:String(o)}`);process.exitCode=f.GENERIC_ERROR}});g.command("close").description("Release the current browser session tab lease").action(S(async(e)=>{await e.closeWindow?.();console.log("Browser session tab lease released")}));i.command("doctor").description("Diagnose ppcli browser bridge connectivity").option("-v, --verbose","Debug output").action(async(e)=>{xr(e);const{runBrowserDoctor:t,renderBrowserDoctorReport:o}=await import("./doctor.js"),r=await t({cliVersion:Ee});console.log(o(r))});i.command("completion").description("Output shell completion script").argument("<shell>","Shell type: bash, zsh, or fish").action((e)=>{uo(e)});const se=i.command("plugin").description("Manage ppcli plugins"),qt=se.description();se.command("install").description("Install a plugin from a git repository").argument("<source>","Plugin source (e.g. github:user/repo)").action(async(e)=>{const{installPlugin:t}=await import("./plugin.js"),{discoverPlugins:o}=await import("./discovery.js");try{const r=t(e);await o();if(Array.isArray(r))if(r.length===0)console.log("No plugins were installed (all skipped or incompatible).");else console.log(`✅ Installed ${r.length} plugin(s) from monorepo: ${r.join(", ")}`);else console.log(`✅ Plugin "${r}" installed successfully. Commands are ready to use.`)}catch(r){console.error(`Error: ${M(r)}`);process.exitCode=f.GENERIC_ERROR}});se.command("uninstall").description("Uninstall a plugin").argument("<name>","Plugin name").action(async(e)=>{const{uninstallPlugin:t}=await import("./plugin.js");try{t(e);console.log(`✅ Plugin "${e}" uninstalled.`)}catch(o){console.error(`Error: ${M(o)}`);process.exitCode=f.GENERIC_ERROR}});se.command("update").description("Update a plugin (or all plugins) to the latest version").argument("[name]","Plugin name (required unless --all is passed)").option("--all","Update all installed plugins").action(async(e,t)=>{if(!e&&!t.all){console.error("Error: Please specify a plugin name or use the --all flag.");process.exitCode=f.USAGE_ERROR;return}if(e&&t.all){console.error("Error: Cannot specify both a plugin name and --all.");process.exitCode=f.USAGE_ERROR;return}const{updatePlugin:o,updateAllPlugins:r}=await import("./plugin.js"),{discoverPlugins:n}=await import("./discovery.js");if(t.all){const s=r();if(s.length>0)await n();let l=!1;console.log(" Update Results:");for(const d of s){if(d.success){console.log(` ✓ ${d.name}`);continue}l=!0;console.log(` ✗ ${d.name} — ${String(d.error)}`)}if(s.length===0){console.log(" No plugins installed.");return}console.log();if(l){console.error("Completed with some errors.");process.exitCode=f.GENERIC_ERROR}else console.log("✅ All plugins updated successfully.");return}try{o(e);await n();console.log(`✅ Plugin "${e}" updated successfully.`)}catch(s){console.error(`Error: ${M(s)}`);process.exitCode=f.GENERIC_ERROR}});se.command("list").description("List installed plugins").option("-f, --format <fmt>","Output format: table, json","table").action(async(e)=>{const{listPlugins:t}=await import("./plugin.js"),o=t();if(o.length===0){console.log(" No plugins installed.");console.log(" Install one with: ppcli plugin install github:user/repo");return}if(e.format==="json"){xe(o,{fmt:"json",columns:["name","commands","source"],title:"ppcli/plugins",source:"ppcli plugin list"});return}console.log();console.log(" Installed plugins");console.log();const r=o.filter((s)=>!s.monorepoName),n=new Map;for(const s of o){if(!s.monorepoName)continue;const l=n.get(s.monorepoName)??[];l.push(s);n.set(s.monorepoName,l)}for(const s of r){const l=s.version?` @${s.version}`:"",d=s.description?` — ${s.description}`:"",u=s.commands.length>0?` (${s.commands.join(", ")})`:"",m=s.source?` ← ${s.source}`:"";console.log(` ${s.name}${l}${d}${u}${m}`)}for(const[s,l]of n){console.log();console.log(` \uD83D\uDCE6 ${s} (monorepo)`);for(const d of l){const u=d.version?` @${d.version}`:"",m=d.description?` — ${d.description}`:"",y=d.commands.length>0?` (${d.commands.join(", ")})`:"";console.log(` ${d.name}${u}${m}${y}`)}}console.log();console.log(` ${o.length} plugin(s) installed`);console.log()});se.command("create").description("Create a new plugin scaffold").argument("<name>","Plugin name (lowercase, hyphens allowed)").option("-d, --dir <path>","Output directory (default: ./<name>)").option("--description <text>","Plugin description").action(async(e,t)=>{const{createPluginScaffold:o}=await import("./plugin-scaffold.js");try{const r=o(e,{dir:t.dir,description:t.description});console.log(`✅ Plugin scaffold created at ${r.dir}`);console.log();console.log(" Files created:");for(const n of r.files)console.log(` ${n}`);console.log();console.log(" Next steps:");console.log(` cd ${r.dir}`);console.log(` ppcli plugin install file://${r.dir}`);console.log(` ppcli ${e} hello`)}catch(r){console.error(`Error: ${M(r)}`);process.exitCode=f.GENERIC_ERROR}});const ye=i.command("adapter").description("Manage CLI adapters"),Xt=ye.description();ye.command("status").description("Show which sites have local overrides vs using official baseline").action(async()=>{const e=await import("node:os"),t=k.join(e.homedir(),".ppcli","clis"),o=a;try{const n=(await O.promises.readdir(t,{withFileTypes:!0})).filter((l)=>l.isDirectory()).map((l)=>l.name).sort();let s=[];try{s=(await O.promises.readdir(o,{withFileTypes:!0})).filter((d)=>d.isDirectory()).map((d)=>d.name).sort()}catch{}if(n.length===0){console.log("No local adapter overrides. All sites use the official baseline.");return}console.log(`Local overrides in ~/.ppcli/clis/ (${n.length} sites):
118
+ `;s.mkdirSync(d,{recursive:!0});s.writeFileSync(u,w,"utf-8");console.log(`Created: ${u}`);console.log("First time on this site? Run: ppcli browser analyze <url>");console.log(`Edit the file to implement your adapter, then run: ppcli browser verify ${e}`)}catch(t){console.error(`Error: ${t instanceof Error?t.message:String(t)}`);process.exitCode=f.GENERIC_ERROR}});g.command("verify").argument("<name>","Adapter name in site/command format (e.g. hn/top)").option("--write-fixture","Write a starter fixture to ~/.ppcli/sites/<site>/verify/<command>.json if none exists").option("--update-fixture","Overwrite an existing fixture with one derived from current output").option("--no-fixture","Ignore any fixture file for this run (no value-level validation)").option("--strict-memory","Fail (not just warn) when ~/.ppcli/sites/<site>/endpoints.json or notes.md is missing").option("--seed-args <value>","Seed args when no fixture exists; use JSON array/object for multiple args or flags").option("--trace <mode>","Trace capture for the adapter subprocess: off, on, retain-on-failure","off").description("Execute an adapter and validate output; uses fixture at ~/.ppcli/sites/<site>/verify/<cmd>.json when present").action(async(e,t={})=>{try{const o=e.split("/");if(o.length!==2){console.error("Name must be site/command format");process.exitCode=f.USAGE_ERROR;return}const[r,n]=o;if(!/^[a-zA-Z0-9_-]+$/.test(r)||!/^[a-zA-Z0-9_-]+$/.test(n)){console.error("Name parts must be alphanumeric/dash/underscore only");process.exitCode=f.USAGE_ERROR;return}const{execFileSync:s}=await import("node:child_process"),{loadFixture:l,writeFixture:d,deriveFixture:u,validateRows:m,validateRowShape:w,fixturePath:x,expandFixtureArgs:_,parseSeedArgs:D}=await import("./browser/verify-fixture.js"),B=O.join(c||O.join(pe.homedir(),".ppcli","clis"),r,`${n}.js`),I=k.existsSync(B)||!a?B:O.join(a,r,`${n}.js`);if(!k.existsSync(I)){console.error(`Adapter not found: ${I}`);console.error(`Run "ppcli browser init ${e}" to create it.`);process.exitCode=f.GENERIC_ERROR;return}console.log(`\uD83D\uDD0D Verifying ${e}...
119
+ `);console.log(` Loading: ${I}`);let J=t.fixture!==!1?l(r,n):null;const z=k.readFileSync(I,"utf-8"),te=/['"]limit['"]/.test(z),y=D(t.seedArgs),C=J?.args??y,q=_(C);if(C===void 0&&q.length===0&&te)q.push("--limit","3");const h=t.trace&&t.trace!=="off"?["--trace",t.trace]:[],A=[...q,...h].join(" "),M=resolveBrowserVerifyInvocation(),W=[...M.args,r,n,...q,...h,"--format","json"];let Z;try{Z=s(M.binary,W,{cwd:M.cwd,timeout:30000,encoding:"utf-8",env:process.env,stdio:["pipe","pipe","pipe"],...M.shell?{shell:!0}:{}})}catch(P){console.log(` Executing: ppcli ${r} ${n} ${A}
120
+ `);const H=P;if(H.stdout)console.log(String(H.stdout));if(H.stderr)console.error(String(H.stderr).slice(0,500));console.log(`
121
+ ✗ Adapter failed. Fix the code and try again.`);process.exitCode=f.GENERIC_ERROR;return}console.log(` Executing: ppcli ${r} ${n} ${A}
122
+ `);let F;try{F=normalizeVerifyRows(JSON.parse(Z))}catch{console.log(Z);console.log("\n ✗ Could not parse adapter output as JSON. Is `--format json` broken?");process.exitCode=f.GENERIC_ERROR;return}console.log(renderVerifyPreview(F));console.log(`
123
+ → ${F.length} row${F.length===1?"":"s"}`);const oe=w(F);if(oe.length>0){console.log(`
124
+ ✗ Adapter output violates row shape conventions:`);for(const P of oe.slice(0,20)){const H=P.rowIndex!==void 0?`row[${P.rowIndex}] `:"";console.log(` - [${P.rule}] ${H}${P.detail}`)}if(oe.length>20)console.log(` ... and ${oe.length-20} more failure(s)`);console.log(`
125
+ Keep rows agent-native: <=12 top-level keys, nesting depth <=1, and id-shaped fields at top level.`);process.exitCode=f.GENERIC_ERROR;return}if(t.writeFixture||t.updateFixture)if(J&&!t.updateFixture){console.log(`
126
+ Fixture already exists at ${x(r,n)}.`);console.log(" Use --update-fixture to overwrite.")}else{const H=u(F,C!==void 0?C:te?{limit:3}:void 0),Me=d(r,n,H);console.log(`
127
+ ${J?"↻ Updated":"✎ Wrote"} fixture: ${Me}`);console.log(" Review and hand-tune the derived expectations (add patterns / notEmpty, tighten rowCount).");J=H}if(!J){console.log(`
128
+ ✓ Adapter runs. (No fixture at ${x(r,n)} — consider --write-fixture to seed one.)`);const P=checkSiteMemory(r);printSiteMemoryReport(P,t.strictMemory);if(!P.ok&&t.strictMemory)process.exitCode=f.GENERIC_ERROR;return}const ie=m(F,J);if(ie.length===0){console.log(`
129
+ ✓ Adapter matches fixture (${x(r,n)}).`);const P=checkSiteMemory(r);printSiteMemoryReport(P,t.strictMemory);if(!P.ok&&t.strictMemory)process.exitCode=f.GENERIC_ERROR;return}console.log(`
130
+ ✗ Adapter output does not match fixture:`);for(const P of ie.slice(0,20)){const H=P.rowIndex!==void 0?`row[${P.rowIndex}] `:"";console.log(` - [${P.rule}] ${H}${P.detail}`)}if(ie.length>20)console.log(` ... and ${ie.length-20} more failure(s)`);process.exitCode=f.GENERIC_ERROR}catch(o){console.error(`Error: ${o instanceof Error?o.message:String(o)}`);process.exitCode=f.GENERIC_ERROR}});g.command("close").description("Release the current browser session tab lease").action(S(async(e)=>{await e.closeWindow?.();console.log("Browser session tab lease released")}));i.command("doctor").description("Diagnose ppcli browser bridge connectivity").option("-v, --verbose","Debug output").action(async(e)=>{xr(e);const{runBrowserDoctor:t,renderBrowserDoctorReport:o}=await import("./doctor.js"),r=await t({cliVersion:_e});console.log(o(r))});i.command("completion").description("Output shell completion script").argument("<shell>","Shell type: bash, zsh, or fish").action((e)=>{uo(e)});const se=i.command("plugin").description("Manage ppcli plugins"),Xt=se.description();se.command("install").description("Install a plugin from a git repository").argument("<source>","Plugin source (e.g. github:user/repo)").action(async(e)=>{const{installPlugin:t}=await import("./plugin.js"),{discoverPlugins:o}=await import("./discovery.js");try{const r=t(e);await o();if(Array.isArray(r))if(r.length===0)console.log("No plugins were installed (all skipped or incompatible).");else console.log(`✅ Installed ${r.length} plugin(s) from monorepo: ${r.join(", ")}`);else console.log(`✅ Plugin "${r}" installed successfully. Commands are ready to use.`)}catch(r){console.error(`Error: ${j(r)}`);process.exitCode=f.GENERIC_ERROR}});se.command("uninstall").description("Uninstall a plugin").argument("<name>","Plugin name").action(async(e)=>{const{uninstallPlugin:t}=await import("./plugin.js");try{t(e);console.log(`✅ Plugin "${e}" uninstalled.`)}catch(o){console.error(`Error: ${j(o)}`);process.exitCode=f.GENERIC_ERROR}});se.command("update").description("Update a plugin (or all plugins) to the latest version").argument("[name]","Plugin name (required unless --all is passed)").option("--all","Update all installed plugins").action(async(e,t)=>{if(!e&&!t.all){console.error("Error: Please specify a plugin name or use the --all flag.");process.exitCode=f.USAGE_ERROR;return}if(e&&t.all){console.error("Error: Cannot specify both a plugin name and --all.");process.exitCode=f.USAGE_ERROR;return}const{updatePlugin:o,updateAllPlugins:r}=await import("./plugin.js"),{discoverPlugins:n}=await import("./discovery.js");if(t.all){const s=r();if(s.length>0)await n();let l=!1;console.log(" Update Results:");for(const d of s){if(d.success){console.log(` ✓ ${d.name}`);continue}l=!0;console.log(` ✗ ${d.name} — ${String(d.error)}`)}if(s.length===0){console.log(" No plugins installed.");return}console.log();if(l){console.error("Completed with some errors.");process.exitCode=f.GENERIC_ERROR}else console.log("✅ All plugins updated successfully.");return}try{o(e);await n();console.log(`✅ Plugin "${e}" updated successfully.`)}catch(s){console.error(`Error: ${j(s)}`);process.exitCode=f.GENERIC_ERROR}});se.command("list").description("List installed plugins").option("-f, --format <fmt>","Output format: table, json","table").action(async(e)=>{const{listPlugins:t}=await import("./plugin.js"),o=t();if(o.length===0){console.log(" No plugins installed.");console.log(" Install one with: ppcli plugin install github:user/repo");return}if(e.format==="json"){Re(o,{fmt:"json",columns:["name","commands","source"],title:"ppcli/plugins",source:"ppcli plugin list"});return}console.log();console.log(" Installed plugins");console.log();const r=o.filter((s)=>!s.monorepoName),n=new Map;for(const s of o){if(!s.monorepoName)continue;const l=n.get(s.monorepoName)??[];l.push(s);n.set(s.monorepoName,l)}for(const s of r){const l=s.version?` @${s.version}`:"",d=s.description?` — ${s.description}`:"",u=s.commands.length>0?` (${s.commands.join(", ")})`:"",m=s.source?` ← ${s.source}`:"";console.log(` ${s.name}${l}${d}${u}${m}`)}for(const[s,l]of n){console.log();console.log(` \uD83D\uDCE6 ${s} (monorepo)`);for(const d of l){const u=d.version?` @${d.version}`:"",m=d.description?` — ${d.description}`:"",w=d.commands.length>0?` (${d.commands.join(", ")})`:"";console.log(` ${d.name}${u}${m}${w}`)}}console.log();console.log(` ${o.length} plugin(s) installed`);console.log()});se.command("create").description("Create a new plugin scaffold").argument("<name>","Plugin name (lowercase, hyphens allowed)").option("-d, --dir <path>","Output directory (default: ./<name>)").option("--description <text>","Plugin description").action(async(e,t)=>{const{createPluginScaffold:o}=await import("./plugin-scaffold.js");try{const r=o(e,{dir:t.dir,description:t.description});console.log(`✅ Plugin scaffold created at ${r.dir}`);console.log();console.log(" Files created:");for(const n of r.files)console.log(` ${n}`);console.log();console.log(" Next steps:");console.log(` cd ${r.dir}`);console.log(` ppcli plugin install file://${r.dir}`);console.log(` ppcli ${e} hello`)}catch(r){console.error(`Error: ${j(r)}`);process.exitCode=f.GENERIC_ERROR}});const Se=i.command("adapter").description("Manage CLI adapters"),Kt=Se.description();Se.command("status").description("Show which sites have local overrides vs using official baseline").action(async()=>{const e=await import("node:os"),t=O.join(e.homedir(),".ppcli","clis"),o=a;try{const n=(await k.promises.readdir(t,{withFileTypes:!0})).filter((l)=>l.isDirectory()).map((l)=>l.name).sort();let s=[];try{s=(await k.promises.readdir(o,{withFileTypes:!0})).filter((d)=>d.isDirectory()).map((d)=>d.name).sort()}catch{}if(n.length===0){console.log("No local adapter overrides. All sites use the official baseline.");return}console.log(`Local overrides in ~/.ppcli/clis/ (${n.length} sites):
131
131
  `);for(const l of n){const u=s.includes(l)?"override":"custom";console.log(` ${l} [${u}]`)}console.log(`
132
- Official baseline: ${s.length} sites in package`)}catch{console.log("No local adapter overrides. All sites use the official baseline.")}});ye.command("eject").description("Copy an official adapter to ~/.ppcli/clis/ for local editing").argument("<site>","Site name (e.g. twitter, bilibili)").action(async(e)=>{const t=await import("node:os"),o=k.join(t.homedir(),".ppcli","clis"),r=k.join(a,e),n=k.join(o,e);try{await O.promises.access(r)}catch{console.error(`Error: Site "${e}" not found in official adapters.`);process.exitCode=f.USAGE_ERROR;return}try{await O.promises.access(n);console.error(`Site "${e}" already exists in ~/.ppcli/clis/. Use "ppcli adapter reset ${e}" first to restore official version.`);process.exitCode=f.USAGE_ERROR;return}catch{}O.cpSync(r,n,{recursive:!0});console.log(`✅ Ejected "${e}" to ~/.ppcli/clis/${e}/`);console.log("You can now edit the adapter files. Changes take effect immediately.");console.log("Note: Official updates to this adapter will overwrite your changes.")});ye.command("reset").description("Remove local override and restore official adapter version").argument("[site]","Site name (e.g. twitter, bilibili)").option("--all","Reset all local overrides").action(async(e,t)=>{const o=await import("node:os"),r=k.join(o.homedir(),".ppcli","clis");if(t.all){try{const d=(await O.promises.readdir(r,{withFileTypes:!0})).filter((u)=>u.isDirectory());if(d.length===0){console.log("No local sites to reset.");return}for(const u of d)O.rmSync(k.join(r,u.name),{recursive:!0,force:!0});console.log(`✅ Reset ${d.length} site(s). All adapters now use official baseline.`)}catch{console.log("No local sites to reset.")}return}if(!e){console.error("Error: Please specify a site name or use --all.");process.exitCode=f.USAGE_ERROR;return}const n=k.join(r,e);try{await O.promises.access(n)}catch{console.error(`Site "${e}" has no local override.`);return}const s=O.existsSync(k.join(a,e));O.rmSync(n,{recursive:!0,force:!0});console.log(s?`✅ Reset "${e}". Now using official baseline.`:`✅ Removed custom site "${e}".`)});const U=i.command("profile").description("Manage Browser Bridge Chrome profiles"),Kt=U.description();U.command("list").description("List Chrome profiles: extension-connected and managed (dedicated Chrome instances)").option("-f, --format <fmt>","Output format: text, json","text").action(async(e)=>{const t=await qo(),o=Xo(),r=t?.profiles??[],n=!!t&&!ir(t,Ee)&&Array.isArray(t.profiles),s=await Promise.all(De().map(async({name:u,entry:m})=>({name:u,port:m.port,userDataDir:m.userDataDir,running:await er(m),isDefault:o.defaultContextId===u,createdAt:m.createdAt??"",label:m.label??"",proxy:m.proxy?{scheme:m.proxy.scheme,host:m.proxy.host,port:m.proxy.port,hasAuth:!!m.proxy.username,username:m.proxy.username??""}:null,fingerprint:m.fingerprint?.enabled?{enabled:!0,timezone:m.fingerprint.timezone??"",locale:m.fingerprint.locale??"",hardwareConcurrency:m.fingerprint.hardwareConcurrency??0,deviceMemory:m.fingerprint.deviceMemory??0,screen:m.fingerprint.screen??null,webglVendor:m.fingerprint.webglVendor??"",webglRenderer:m.fingerprint.webglRenderer??"",canvasNoise:m.fingerprint.canvasNoise===!0}:{enabled:!1},webrtc:m.webrtc!==!1,clean:m.clean!==!1})));if(e.format==="json"){const u=n?r.map((m)=>({contextId:m.contextId,alias:_t(o,m.contextId)??"",connected:!0,version:m.extensionVersion??"",isDefault:o.defaultContextId===m.contextId})):[];console.log(JSON.stringify({managed:s,extension:u,daemonRunning:!!t,daemonStale:!!t&&!n,defaultProfile:o.defaultContextId??""},null,2));return}if(s.length>0){console.log("Managed profiles (dedicated Chrome instances)");console.log();for(const u of s){const m=u.isDefault?" default":"";console.log(` ${u.name}${m} — ${u.running?`running on port ${u.port}`:"stopped"}`)}console.log()}if(!t){console.log("Daemon is not running. Run ppcli doctor after opening Chrome.");return}if(!n){console.log(`Daemon ${sr(t)} is stale for CLI v${Ee}.`);console.log("Run: ppcli daemon restart");return}if(r.length===0){console.log("No Browser Bridge profiles connected.");console.log("Open a Chrome profile with the ppcli extension installed, then run ppcli profile list again.");return}const l=new Set(r.map((u)=>u.contextId));console.log("Connected Browser Bridge profiles");console.log();for(const u of r){const m=_t(o,u.contextId),y=o.defaultContextId===u.contextId?" default":"",x=m?` ${m}`:"",_=u.extensionVersion?` v${u.extensionVersion}`:" version unknown";console.log(` ${u.contextId}${x}${y} — connected${_}`)}if(s.some((u)=>u.running)){console.log();console.log("注意:托管 Chrome 也装了同一个扩展,上面的某个 contextId 可能就是它,");console.log(" 无法从这份列表分辨。写操作请显式带 --profile <名字>,不要依赖默认路由。")}const d=Object.entries(o.aliases).filter(([,u])=>!l.has(u));if(d.length>0||o.defaultContextId&&!l.has(o.defaultContextId)){console.log();console.log("Disconnected saved profiles:");const u=new Set;for(const[m,y]of d){u.add(y);console.log(` ${y} ${m} — not connected`)}if(o.defaultContextId&&!u.has(o.defaultContextId)&&!l.has(o.defaultContextId))console.log(` ${o.defaultContextId} — default, not connected`)}});const nt=(e)=>{if(e.config){const r=JSON.parse(e.config);if(typeof r.proxy==="string")r.proxy=Be(r.proxy);return r}const t={};if(e.label)t.label=e.label;if(e.proxy)t.proxy=Be(e.proxy);if(e.webrtc===!1)t.webrtc=!1;if(e.clean===!1)t.clean=!1;const o=e.fingerprint;if(o&&o!=="off")t.fingerprint={enabled:!0,spoof:o!=="lite",...e.fpTimezone?{timezone:e.fpTimezone}:{},...e.fpLocale?{locale:e.fpLocale}:{},...e.fpUa?{userAgent:e.fpUa}:{},...e.fpPlatform?{platform:e.fpPlatform}:{},...e.fpSeed?{seed:Number(e.fpSeed)}:{}};return t},st=(e)=>e?{scheme:e.scheme,host:e.host,port:e.port,hasAuth:!!e.username,username:e.username??""}:null,it=(e)=>e?.enabled?{enabled:!0,seed:e.seed,timezone:e.timezone??"",locale:e.locale??"",userAgent:e.userAgent??"",platform:e.platform??"",hardwareConcurrency:e.hardwareConcurrency??0,deviceMemory:e.deviceMemory??0,screen:e.screen??null,webglVendor:e.webglVendor??"",webglRenderer:e.webglRenderer??"",canvasNoise:e.canvasNoise===!0}:{enabled:!1},at=(e)=>e.option("--label <text>","Display label / note for the environment").option("--proxy <url>","Per-env proxy: scheme://[user:pass@]host:port (scheme = http/https/socks5)").option("--fingerprint <mode>","Fingerprint mode: off | on (spoof soft signals) | lite (timezone/locale follow only)").option("--fp-timezone <iana>","Fingerprint timezone, e.g. America/New_York (must be set explicitly)").option("--fp-locale <locale>","Fingerprint locale, e.g. en-US (must be set explicitly)").option("--fp-ua <ua>","Override navigator.userAgent (use with care)").option("--fp-platform <p>","Override navigator.platform, e.g. Win32").option("--fp-seed <n>","Fixed fingerprint seed (for reproducible fingerprint)").option("--no-webrtc","Disable WebRTC leak protection (on by default)").option("--no-clean","Disable lean launch flags / telemetry suppression (on by default)").option("--config <json>","Full config as JSON: { label, proxy, fingerprint } — overrides granular flags");U.command("create").description("Create a managed profile: a dedicated Chrome instance with its own user data dir (for a second account)").argument("<name>","Profile name, e.g. work / brand2").option("--browser-path <path>","Explicit browser executable (defaults to auto-discovered Chrome)").option("--no-start","Create only; do not launch Chrome now").option("-f, --format <fmt>","Output format: text, json","text").action(async(e,t)=>{try{const o=nt(t),{opts:r}=await $t({...o,browserPath:t.browserPath}),n=await Qo(e,{...r,browserPath:t.browserPath});if(t.start!==!1)await Ge(e,n);if(t.format==="json"){console.log(JSON.stringify({ok:!0,name:e,port:n.port,userDataDir:n.userDataDir,label:n.label??"",proxy:st(n.proxy),fingerprint:it(n.fingerprint),webrtc:n.webrtc!==!1,clean:n.clean!==!1,started:t.start!==!1},null,2));return}console.log(`✅ 托管 profile "${e}" 已创建(端口 ${n.port})`);console.log(` 数据目录:${n.userDataDir}`);if(n.proxy)console.log(` 代理:${n.proxy.scheme}://${n.proxy.host}:${n.proxy.port}`);if(n.fingerprint?.enabled)console.log(` 指纹:已开启${n.fingerprint.timezone?` 时区 ${n.fingerprint.timezone}`:""}${n.fingerprint.locale?` 语言 ${n.fingerprint.locale}`:""}`);if(t.start!==!1)console.log(` Chrome 已启动。用 ppcli <site> login --profile ${e} 在新窗口里登录账号。`)}catch(o){console.error(`Error: ${M(o)}`);process.exitCode=f.USAGE_ERROR}});at(U.commands[U.commands.length-1]);U.command("start").description("Launch the dedicated Chrome instance of a managed profile").argument("<name>","Managed profile name").action(async(e)=>{try{const t=De().find((r)=>r.name===e.trim());if(!t)throw Error(`托管 profile "${e}" 不存在,先 ppcli profile create ${e}`);const o=await Ge(t.name,t.entry);console.log(`✅ profile "${e}" 运行中(${o})`)}catch(t){console.error(`Error: ${M(t)}`);process.exitCode=f.USAGE_ERROR}});U.command("stop").description("Gracefully close the dedicated Chrome instance of a managed profile").argument("<name>","Managed profile name").action(async(e)=>{try{const t=De().find((r)=>r.name===e.trim());if(!t)throw Error(`托管 profile "${e}" 不存在`);const o=await or(t.entry);console.log(o?`✅ profile "${e}" 已关闭`:`profile "${e}" 本来就没在运行`)}catch(t){console.error(`Error: ${M(t)}`);process.exitCode=f.USAGE_ERROR}});U.command("remove").description("Remove a managed profile (closes Chrome and deletes its login data)").argument("<name>","Managed profile name").option("--keep-data","Keep the user data dir on disk",!1).action(async(e,t)=>{try{await tr(e,{keepData:t.keepData===!0});console.log(`✅ 托管 profile "${e}" 已删除${t.keepData?"(保留数据目录)":"(含登录数据)"}`)}catch(o){console.error(`Error: ${M(o)}`);process.exitCode=f.USAGE_ERROR}});U.command("update").description("Reconfigure a managed profile (label / proxy / fingerprint); takes effect on next start").argument("<name>","Managed profile name").option("--clear-proxy","Remove the proxy from this environment").option("--restart","Relaunch the environment after updating",!1).option("-f, --format <fmt>","Output format: text, json","text").action(async(e,t)=>{try{const o=nt(t),{opts:r}=await $t(o),n={};if(o.label!==void 0)n.label=o.label??null;if(t.clearProxy)n.proxy=null;else if(r.proxy)n.proxy=r.proxy;if(t.fingerprint==="off")n.fingerprint=null;else if(r.fingerprint)n.fingerprint=r.fingerprint;if(o.webrtc!==void 0)n.webrtc=o.webrtc;if(o.clean!==void 0)n.clean=o.clean;const{entry:s,wasRunning:l}=await rr(e,n);if(t.restart&&l)await Ge(e,s);if(t.format==="json"){console.log(JSON.stringify({ok:!0,name:e,label:s.label??"",proxy:st(s.proxy),fingerprint:it(s.fingerprint),webrtc:s.webrtc!==!1,clean:s.clean!==!1,wasRunning:l,restarted:!!(t.restart&&l)},null,2));return}console.log(`✅ 托管 profile "${e}" 配置已更新${l?"(已关闭,重启后生效)":""}`)}catch(o){console.error(`Error: ${M(o)}`);process.exitCode=f.USAGE_ERROR}});at(U.commands[U.commands.length-1]);U.command("test-proxy").description("Test proxy connectivity and detect exit IP / country / timezone").argument("<url>","Proxy: scheme://[user:pass@]host:port (scheme = http/https/socks5)").option("-f, --format <fmt>","Output format: text, json","text").action(async(e,t)=>{try{const o=Be(e),r=await nr(o);if(t.format==="json"){console.log(JSON.stringify(r,null,2));return}if(r.ok){console.log(`✅ 代理可用 — 出口 IP ${r.ip}`);console.log(` 位置:${r.country??"?"}${r.city?" / "+r.city:""}`);console.log(` 时区:${r.timezone??"?"} 语言:${r.locale??"?"}`)}else{console.log(`❌ 代理不可用:${r.error}`);process.exitCode=f.USAGE_ERROR}}catch(o){console.error(`Error: ${M(o)}`);process.exitCode=f.USAGE_ERROR}});U.command("rename").description("Assign a local alias to a connected Browser Bridge profile").argument("<contextId>","Profile contextId from ppcli profile list").argument("<alias>","Local alias, e.g. work or personal").action((e,t)=>{try{Ko(e,t);console.log(`Profile ${e} is now aliased as ${t}.`)}catch(o){console.error(`Error: ${M(o)}`);process.exitCode=f.USAGE_ERROR}});U.command("use").description("Set the default Browser Bridge profile for future commands").argument("<profile>","Profile alias or contextId").action((e)=>{try{const t=Yo(e);console.log(`Default Browser Bridge profile: ${t.defaultContextId??e}`)}catch(t){console.error(`Error: ${M(t)}`);process.exitCode=f.USAGE_ERROR}});const ue=i.command("daemon").description("Manage the ppcli daemon"),Zt=ue.description();ue.command("status").description("Show daemon status").option("--json","Machine-readable status (includes bridgeReady)").action(async(e)=>{await Lo(e)});ue.command("stop").description("Stop the daemon").action(async()=>{await zo()});ue.command("restart").description("Restart the daemon").action(async()=>{await Fo()});ue.command("warm").description("Pre-open the background automation window (keeps a tab alive for reuse)").option("--url <url>","http(s) info page to keep in the warm tab (falls back to about:blank)").action(async(e)=>{await Wo(e.url)});const be=Me(),Te=i.command("external").description("Manage external CLI passthrough commands");Te.command("install").description("Install an external CLI").argument("<name>","Name of the external CLI").action((e)=>{const t=be.find((o)=>o.name===e);if(!t){console.error(`External CLI '${e}' not found in registry.`);process.exitCode=f.USAGE_ERROR;return}po(t)});Te.command("register").description("Register an external CLI").argument("<name>","Name of the CLI").option("--binary <bin>","Binary name if different from name").option("--install <cmd>","Auto-install command").option("--desc <text>","Description").action((e,t)=>{fo(e,{binary:t.binary,install:t.install,description:t.desc})});Te.command("list").description("List registered external CLIs").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((e)=>{const t=Me().map((o)=>({name:o.name,package:o.package??"",binary:o.binary,installed:je(o.binary),description:o.description??"",homepage:o.homepage??"",tags:o.tags?.join(", ")??""}));xe(t,{fmt:e.format,columns:["name","package","binary","installed","description","homepage","tags"],title:"ppcli/external/list",source:"ppcli external list"})});function Yt(e,t){const o=t??(()=>{const r=process.argv.indexOf(e);return process.argv.slice(r+1)})();try{mo(e,o,be)}catch(r){if(r instanceof Ue){process.stderr.write(io.dump(Eo(r),{sortKeys:!1,lineWidth:120,noRefs:!0}));process.exitCode=r.exitCode}else{console.error(`Error: ${M(r)}`);process.exitCode=f.GENERIC_ERROR}}}for(const e of be){if(i.commands.some((t)=>t.name()===e.name))continue;i.command(e.name).description(`(External) ${e.description||e.name}`).argument("[args...]").allowUnknownOption().passThroughOptions().helpOption(!1).action((t)=>Yt(e.name,t))}const ct=i.command("antigravity").description("antigravity commands");ct.command("serve").description("Start Anthropic-compatible API proxy for Antigravity").option("--port <port>","Server port (default: 8082)","8082").option("--timeout <seconds>","Maximum time to wait for a reply (default: 120s)").action(async(e)=>{const{startServe:t}=await import("../../clis/antigravity/serve.js");await t({port:parseInt(e.port,10),timeout:e.timeout?Ft(e.timeout,"--timeout",120):void 0})});const lt=new Map;lt.set("antigravity",ct);const dt=wo(i,lt);Rr(i);const Qt=be.map((e)=>e.name),eo=be.map((e)=>({name:e.name,label:wt(e)})),Ie=new Map;for(const[,e]of Se())if(!Ie.has(e.site))Ie.set(e.site,e.domain);const ut=[],mt=[];for(const e of dt)if(yt(Ie.get(e))==="app")ut.push(e);else mt.push(e);const pt={external:eo,apps:ut,sites:mt},to=new Set([...Qt,...dt]);pe(g,{globalCommand:i,description:N});pe(b,{globalCommand:i,description:"Inspect website login status"});pe(ue,{globalCommand:i,description:Zt});pe(se,{globalCommand:i,description:qt});pe(ye,{globalCommand:i,description:Xt});pe(U,{globalCommand:i,description:Kt});i.configureHelp({visibleCommands:(e)=>e.commands.filter((t)=>e!==i||!to.has(t.name()))});const oo=(e)=>{const t=[];let o=e.parent;while(o){const r=So(o);t.unshift(r?`${o.name()} ${r}`:o.name());o=o.parent}return[...t,e.name(),e.usage()].filter(Boolean).join(" ").trim()};function ft(e){e.configureHelp({commandUsage:oo});for(const t of e.commands)ft(t)}ft(g);bo(i,()=>xo(i,pt),()=>yo(pt));i.on("command:*",(e)=>{const t=e[0];console.error(`error: unknown command '${t}'`);if(je(t))console.error(` Tip: '${t}' exists on your PATH. Use 'ppcli external register ${t}' to add it as an external CLI.`);i.outputHelp();process.exitCode=f.USAGE_ERROR});return i}export function runCli(a,c){createProgram(a,c).parse()}export{findPackageRoot};export function resolveBrowserVerifyInvocation(a={}){const c=a.platform??process.platform,i=a.fileExists??O.existsSync,p=a.readFile??((v)=>O.readFileSync(v,"utf-8")),b=a.projectRoot??findPackageRoot(Le,i);for(const v of ao(b,p))if(i(v))return{binary:process.execPath,args:[v],cwd:b};const g=k.join(b,"src","main.ts");if(!i(g))throw Error(`Could not find ppcli entrypoint under ${b}. Expected built entry from package.json or src/main.ts.`);const N=k.join(b,"node_modules",".bin",c==="win32"?"tsx.cmd":"tsx");if(i(N))return{binary:N,args:[g],cwd:b,...c==="win32"?{shell:!0}:{}};return{binary:c==="win32"?"npx.cmd":"npx",args:["tsx",g],cwd:b,...c==="win32"?{shell:!0}:{}}}
132
+ Official baseline: ${s.length} sites in package`)}catch{console.log("No local adapter overrides. All sites use the official baseline.")}});Se.command("eject").description("Copy an official adapter to ~/.ppcli/clis/ for local editing").argument("<site>","Site name (e.g. twitter, bilibili)").action(async(e)=>{const t=await import("node:os"),o=O.join(t.homedir(),".ppcli","clis"),r=O.join(a,e),n=O.join(o,e);try{await k.promises.access(r)}catch{console.error(`Error: Site "${e}" not found in official adapters.`);process.exitCode=f.USAGE_ERROR;return}try{await k.promises.access(n);console.error(`Site "${e}" already exists in ~/.ppcli/clis/. Use "ppcli adapter reset ${e}" first to restore official version.`);process.exitCode=f.USAGE_ERROR;return}catch{}k.cpSync(r,n,{recursive:!0});console.log(`✅ Ejected "${e}" to ~/.ppcli/clis/${e}/`);console.log("You can now edit the adapter files. Changes take effect immediately.");console.log("Note: Official updates to this adapter will overwrite your changes.")});Se.command("reset").description("Remove local override and restore official adapter version").argument("[site]","Site name (e.g. twitter, bilibili)").option("--all","Reset all local overrides").action(async(e,t)=>{const o=await import("node:os"),r=O.join(o.homedir(),".ppcli","clis");if(t.all){try{const d=(await k.promises.readdir(r,{withFileTypes:!0})).filter((u)=>u.isDirectory());if(d.length===0){console.log("No local sites to reset.");return}for(const u of d)k.rmSync(O.join(r,u.name),{recursive:!0,force:!0});console.log(`✅ Reset ${d.length} site(s). All adapters now use official baseline.`)}catch{console.log("No local sites to reset.")}return}if(!e){console.error("Error: Please specify a site name or use --all.");process.exitCode=f.USAGE_ERROR;return}const n=O.join(r,e);try{await k.promises.access(n)}catch{console.error(`Site "${e}" has no local override.`);return}const s=k.existsSync(O.join(a,e));k.rmSync(n,{recursive:!0,force:!0});console.log(s?`✅ Reset "${e}". Now using official baseline.`:`✅ Removed custom site "${e}".`)});const U=i.command("profile").description("Manage Browser Bridge Chrome profiles"),Zt=U.description();U.command("list").description("List Chrome profiles: extension-connected and managed (dedicated Chrome instances)").option("-f, --format <fmt>","Output format: text, json","text").action(async(e)=>{const t=await qo(),o=Xo(),r=t?.profiles??[],n=!!t&&!ir(t,_e)&&Array.isArray(t.profiles),s=await Promise.all(Be().map(async({name:u,entry:m})=>({name:u,port:m.port,userDataDir:m.userDataDir,running:await er(m),isDefault:o.defaultContextId===u,createdAt:m.createdAt??"",label:m.label??"",proxy:m.proxy?{scheme:m.proxy.scheme,host:m.proxy.host,port:m.proxy.port,hasAuth:!!m.proxy.username,username:m.proxy.username??""}:null,fingerprint:m.fingerprint?.enabled?{enabled:!0,timezone:m.fingerprint.timezone??"",locale:m.fingerprint.locale??"",hardwareConcurrency:m.fingerprint.hardwareConcurrency??0,deviceMemory:m.fingerprint.deviceMemory??0,screen:m.fingerprint.screen??null,webglVendor:m.fingerprint.webglVendor??"",webglRenderer:m.fingerprint.webglRenderer??"",canvasNoise:m.fingerprint.canvasNoise===!0}:{enabled:!1},webrtc:m.webrtc!==!1,clean:m.clean!==!1})));if(e.format==="json"){const u=n?r.map((m)=>({contextId:m.contextId,alias:$t(o,m.contextId)??"",connected:!0,version:m.extensionVersion??"",isDefault:o.defaultContextId===m.contextId})):[];console.log(JSON.stringify({managed:s,extension:u,daemonRunning:!!t,daemonStale:!!t&&!n,defaultProfile:o.defaultContextId??""},null,2));return}if(s.length>0){console.log("Managed profiles (dedicated Chrome instances)");console.log();for(const u of s){const m=u.isDefault?" default":"";console.log(` ${u.name}${m} — ${u.running?`running on port ${u.port}`:"stopped"}`)}console.log()}if(!t){console.log("Daemon is not running. Run ppcli doctor after opening Chrome.");return}if(!n){console.log(`Daemon ${sr(t)} is stale for CLI v${_e}.`);console.log("Run: ppcli daemon restart");return}if(r.length===0){console.log("No Browser Bridge profiles connected.");console.log("Open a Chrome profile with the ppcli extension installed, then run ppcli profile list again.");return}const l=new Set(r.map((u)=>u.contextId));console.log("Connected Browser Bridge profiles");console.log();for(const u of r){const m=$t(o,u.contextId),w=o.defaultContextId===u.contextId?" default":"",x=m?` ${m}`:"",_=u.extensionVersion?` v${u.extensionVersion}`:" version unknown";console.log(` ${u.contextId}${x}${w} — connected${_}`)}if(s.some((u)=>u.running)){console.log();console.log("注意:托管 Chrome 也装了同一个扩展,上面的某个 contextId 可能就是它,");console.log(" 无法从这份列表分辨。写操作请显式带 --profile <名字>,不要依赖默认路由。")}const d=Object.entries(o.aliases).filter(([,u])=>!l.has(u));if(d.length>0||o.defaultContextId&&!l.has(o.defaultContextId)){console.log();console.log("Disconnected saved profiles:");const u=new Set;for(const[m,w]of d){u.add(w);console.log(` ${w} ${m} — not connected`)}if(o.defaultContextId&&!u.has(o.defaultContextId)&&!l.has(o.defaultContextId))console.log(` ${o.defaultContextId} — default, not connected`)}});const it=(e)=>{if(e.config){const r=JSON.parse(e.config);if(typeof r.proxy==="string")r.proxy=Le(r.proxy);return r}const t={};if(e.label)t.label=e.label;if(e.proxy)t.proxy=Le(e.proxy);if(e.webrtc===!1)t.webrtc=!1;if(e.clean===!1)t.clean=!1;const o=e.fingerprint;if(o&&o!=="off")t.fingerprint={enabled:!0,spoof:o!=="lite",...e.fpTimezone?{timezone:e.fpTimezone}:{},...e.fpLocale?{locale:e.fpLocale}:{},...e.fpUa?{userAgent:e.fpUa}:{},...e.fpPlatform?{platform:e.fpPlatform}:{},...e.fpSeed?{seed:Number(e.fpSeed)}:{}};return t},at=(e)=>e?{scheme:e.scheme,host:e.host,port:e.port,hasAuth:!!e.username,username:e.username??""}:null,ct=(e)=>e?.enabled?{enabled:!0,seed:e.seed,timezone:e.timezone??"",locale:e.locale??"",userAgent:e.userAgent??"",platform:e.platform??"",hardwareConcurrency:e.hardwareConcurrency??0,deviceMemory:e.deviceMemory??0,screen:e.screen??null,webglVendor:e.webglVendor??"",webglRenderer:e.webglRenderer??"",canvasNoise:e.canvasNoise===!0}:{enabled:!1},lt=(e)=>e.option("--label <text>","Display label / note for the environment").option("--proxy <url>","Per-env proxy: scheme://[user:pass@]host:port (scheme = http/https/socks5)").option("--fingerprint <mode>","Fingerprint mode: off | on (spoof soft signals) | lite (timezone/locale follow only)").option("--fp-timezone <iana>","Fingerprint timezone, e.g. America/New_York (must be set explicitly)").option("--fp-locale <locale>","Fingerprint locale, e.g. en-US (must be set explicitly)").option("--fp-ua <ua>","Override navigator.userAgent (use with care)").option("--fp-platform <p>","Override navigator.platform, e.g. Win32").option("--fp-seed <n>","Fixed fingerprint seed (for reproducible fingerprint)").option("--no-webrtc","Disable WebRTC leak protection (on by default)").option("--no-clean","Disable lean launch flags / telemetry suppression (on by default)").option("--config <json>","Full config as JSON: { label, proxy, fingerprint } — overrides granular flags");U.command("create").description("Create a managed profile: a dedicated Chrome instance with its own user data dir (for a second account)").argument("<name>","Profile name, e.g. work / brand2").option("--browser-path <path>","Explicit browser executable (defaults to auto-discovered Chrome)").option("--no-start","Create only; do not launch Chrome now").option("-f, --format <fmt>","Output format: text, json","text").action(async(e,t)=>{try{const o=it(t),{opts:r}=await Nt({...o,browserPath:t.browserPath}),n=await Qo(e,{...r,browserPath:t.browserPath});if(t.start!==!1)await Fe(e,n);if(t.format==="json"){console.log(JSON.stringify({ok:!0,name:e,port:n.port,userDataDir:n.userDataDir,label:n.label??"",proxy:at(n.proxy),fingerprint:ct(n.fingerprint),webrtc:n.webrtc!==!1,clean:n.clean!==!1,started:t.start!==!1},null,2));return}console.log(`✅ 托管 profile "${e}" 已创建(端口 ${n.port})`);console.log(` 数据目录:${n.userDataDir}`);if(n.proxy)console.log(` 代理:${n.proxy.scheme}://${n.proxy.host}:${n.proxy.port}`);if(n.fingerprint?.enabled)console.log(` 指纹:已开启${n.fingerprint.timezone?` 时区 ${n.fingerprint.timezone}`:""}${n.fingerprint.locale?` 语言 ${n.fingerprint.locale}`:""}`);if(t.start!==!1)console.log(` Chrome 已启动。用 ppcli <site> login --profile ${e} 在新窗口里登录账号。`)}catch(o){console.error(`Error: ${j(o)}`);process.exitCode=f.USAGE_ERROR}});lt(U.commands[U.commands.length-1]);U.command("start").description("Launch the dedicated Chrome instance of a managed profile").argument("<name>","Managed profile name").action(async(e)=>{try{const t=Be().find((r)=>r.name===e.trim());if(!t)throw Error(`托管 profile "${e}" 不存在,先 ppcli profile create ${e}`);const o=await Fe(t.name,t.entry);console.log(`✅ profile "${e}" 运行中(${o})`)}catch(t){console.error(`Error: ${j(t)}`);process.exitCode=f.USAGE_ERROR}});U.command("stop").description("Gracefully close the dedicated Chrome instance of a managed profile").argument("<name>","Managed profile name").action(async(e)=>{try{const t=Be().find((r)=>r.name===e.trim());if(!t)throw Error(`托管 profile "${e}" 不存在`);const o=await or(t.entry);console.log(o?`✅ profile "${e}" 已关闭`:`profile "${e}" 本来就没在运行`)}catch(t){console.error(`Error: ${j(t)}`);process.exitCode=f.USAGE_ERROR}});U.command("remove").description("Remove a managed profile (closes Chrome and deletes its login data)").argument("<name>","Managed profile name").option("--keep-data","Keep the user data dir on disk",!1).action(async(e,t)=>{try{await tr(e,{keepData:t.keepData===!0});console.log(`✅ 托管 profile "${e}" 已删除${t.keepData?"(保留数据目录)":"(含登录数据)"}`)}catch(o){console.error(`Error: ${j(o)}`);process.exitCode=f.USAGE_ERROR}});U.command("update").description("Reconfigure a managed profile (label / proxy / fingerprint); takes effect on next start").argument("<name>","Managed profile name").option("--clear-proxy","Remove the proxy from this environment").option("--restart","Relaunch the environment after updating",!1).option("-f, --format <fmt>","Output format: text, json","text").action(async(e,t)=>{try{const o=it(t),{opts:r}=await Nt(o),n={};if(o.label!==void 0)n.label=o.label??null;if(t.clearProxy)n.proxy=null;else if(r.proxy)n.proxy=r.proxy;if(t.fingerprint==="off")n.fingerprint=null;else if(r.fingerprint)n.fingerprint=r.fingerprint;if(o.webrtc!==void 0)n.webrtc=o.webrtc;if(o.clean!==void 0)n.clean=o.clean;const{entry:s,wasRunning:l}=await rr(e,n);if(t.restart&&l)await Fe(e,s);if(t.format==="json"){console.log(JSON.stringify({ok:!0,name:e,label:s.label??"",proxy:at(s.proxy),fingerprint:ct(s.fingerprint),webrtc:s.webrtc!==!1,clean:s.clean!==!1,wasRunning:l,restarted:!!(t.restart&&l)},null,2));return}console.log(`✅ 托管 profile "${e}" 配置已更新${l?"(已关闭,重启后生效)":""}`)}catch(o){console.error(`Error: ${j(o)}`);process.exitCode=f.USAGE_ERROR}});lt(U.commands[U.commands.length-1]);U.command("test-proxy").description("Test proxy connectivity and detect exit IP / country / timezone").argument("<url>","Proxy: scheme://[user:pass@]host:port (scheme = http/https/socks5)").option("-f, --format <fmt>","Output format: text, json","text").action(async(e,t)=>{try{const o=Le(e),r=await nr(o);if(t.format==="json"){console.log(JSON.stringify(r,null,2));return}if(r.ok){console.log(`✅ 代理可用 — 出口 IP ${r.ip}`);console.log(` 位置:${r.country??"?"}${r.city?" / "+r.city:""}`);console.log(` 时区:${r.timezone??"?"} 语言:${r.locale??"?"}`)}else{console.log(`❌ 代理不可用:${r.error}`);process.exitCode=f.USAGE_ERROR}}catch(o){console.error(`Error: ${j(o)}`);process.exitCode=f.USAGE_ERROR}});U.command("rename").description("Assign a local alias to a connected Browser Bridge profile").argument("<contextId>","Profile contextId from ppcli profile list").argument("<alias>","Local alias, e.g. work or personal").action((e,t)=>{try{Ko(e,t);console.log(`Profile ${e} is now aliased as ${t}.`)}catch(o){console.error(`Error: ${j(o)}`);process.exitCode=f.USAGE_ERROR}});U.command("use").description("Set the default Browser Bridge profile for future commands").argument("<profile>","Profile alias or contextId").action((e)=>{try{const t=Yo(e);console.log(`Default Browser Bridge profile: ${t.defaultContextId??e}`)}catch(t){console.error(`Error: ${j(t)}`);process.exitCode=f.USAGE_ERROR}});const me=i.command("daemon").description("Manage the ppcli daemon"),Yt=me.description();me.command("status").description("Show daemon status").option("--json","Machine-readable status (includes bridgeReady)").action(async(e)=>{await Lo(e)});me.command("stop").description("Stop the daemon").action(async()=>{await zo()});me.command("restart").description("Restart the daemon").action(async()=>{await Fo()});me.command("warm").description("Pre-open the background automation window (keeps a tab alive for reuse)").option("--url <url>","http(s) info page to keep in the warm tab (falls back to about:blank)").action(async(e)=>{await Wo(e.url)});const xe=Ue(),Pe=i.command("external").description("Manage external CLI passthrough commands");Pe.command("install").description("Install an external CLI").argument("<name>","Name of the external CLI").action((e)=>{const t=xe.find((o)=>o.name===e);if(!t){console.error(`External CLI '${e}' not found in registry.`);process.exitCode=f.USAGE_ERROR;return}po(t)});Pe.command("register").description("Register an external CLI").argument("<name>","Name of the CLI").option("--binary <bin>","Binary name if different from name").option("--install <cmd>","Auto-install command").option("--desc <text>","Description").action((e,t)=>{fo(e,{binary:t.binary,install:t.install,description:t.desc})});Pe.command("list").description("List registered external CLIs").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((e)=>{const t=Ue().map((o)=>({name:o.name,package:o.package??"",binary:o.binary,installed:De(o.binary),description:o.description??"",homepage:o.homepage??"",tags:o.tags?.join(", ")??""}));Re(t,{fmt:e.format,columns:["name","package","binary","installed","description","homepage","tags"],title:"ppcli/external/list",source:"ppcli external list"})});function Qt(e,t){const o=t??(()=>{const r=process.argv.indexOf(e);return process.argv.slice(r+1)})();try{mo(e,o,xe)}catch(r){if(r instanceof Ge){process.stderr.write(io.dump(Eo(r),{sortKeys:!1,lineWidth:120,noRefs:!0}));process.exitCode=r.exitCode}else{console.error(`Error: ${j(r)}`);process.exitCode=f.GENERIC_ERROR}}}for(const e of xe){if(i.commands.some((t)=>t.name()===e.name))continue;i.command(e.name).description(`(External) ${e.description||e.name}`).argument("[args...]").allowUnknownOption().passThroughOptions().helpOption(!1).action((t)=>Qt(e.name,t))}const dt=i.command("antigravity").description("antigravity commands");dt.command("serve").description("Start Anthropic-compatible API proxy for Antigravity").option("--port <port>","Server port (default: 8082)","8082").option("--timeout <seconds>","Maximum time to wait for a reply (default: 120s)").action(async(e)=>{const{startServe:t}=await import("../../clis/antigravity/serve.js");await t({port:parseInt(e.port,10),timeout:e.timeout?zt(e.timeout,"--timeout",120):void 0})});const ut=new Map;ut.set("antigravity",dt);const mt=wo(i,ut);Rr(i);const eo=xe.map((e)=>e.name),to=xe.map((e)=>({name:e.name,label:bt(e)})),Je=new Map;for(const[,e]of ve())if(!Je.has(e.site))Je.set(e.site,e.domain);const pt=[],ft=[];for(const e of mt)if(St(Je.get(e))==="app")pt.push(e);else ft.push(e);const gt={external:to,apps:pt,sites:ft},oo=new Set([...eo,...mt]);fe(g,{globalCommand:i,description:N});fe(b,{globalCommand:i,description:"Inspect website login status"});fe(me,{globalCommand:i,description:Yt});fe(se,{globalCommand:i,description:Xt});fe(Se,{globalCommand:i,description:Kt});fe(U,{globalCommand:i,description:Zt});i.configureHelp({visibleCommands:(e)=>e.commands.filter((t)=>e!==i||!oo.has(t.name()))});const ro=(e)=>{const t=[];let o=e.parent;while(o){const r=So(o);t.unshift(r?`${o.name()} ${r}`:o.name());o=o.parent}return[...t,e.name(),e.usage()].filter(Boolean).join(" ").trim()};function ht(e){e.configureHelp({commandUsage:ro});for(const t of e.commands)ht(t)}ht(g);bo(i,()=>xo(i,gt),()=>yo(gt));i.on("command:*",(e)=>{const t=e[0];console.error(`error: unknown command '${t}'`);if(De(t))console.error(` Tip: '${t}' exists on your PATH. Use 'ppcli external register ${t}' to add it as an external CLI.`);i.outputHelp();process.exitCode=f.USAGE_ERROR});return i}export function runCli(a,c){createProgram(a,c).parse()}export{findPackageRoot};export function resolveBrowserVerifyInvocation(a={}){const c=a.platform??process.platform,i=a.fileExists??k.existsSync,p=a.readFile??((v)=>k.readFileSync(v,"utf-8")),b=a.projectRoot??findPackageRoot(We,i);for(const v of ao(b,p))if(i(v))return{binary:process.execPath,args:[v],cwd:b};const g=O.join(b,"src","main.ts");if(!i(g))throw Error(`Could not find ppcli entrypoint under ${b}. Expected built entry from package.json or src/main.ts.`);const N=O.join(b,"node_modules",".bin",c==="win32"?"tsx.cmd":"tsx");if(i(N))return{binary:N,args:[g],cwd:b,...c==="win32"?{shell:!0}:{}};return{binary:c==="win32"?"npx.cmd":"npx",args:["tsx",g],cwd:b,...c==="win32"?{shell:!0}:{}}}