publishport-opencli 1.0.28 → 1.0.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli-manifest.json +1297 -13
- package/clis/_shared/publish-controls.js +11 -0
- package/clis/douyin/_shared/ai-declaration.js +1 -0
- package/clis/douyin/_shared/browser-fetch.js +31 -13
- package/clis/douyin/_shared/comments.js +1 -0
- package/clis/douyin/_shared/publish-settings.js +1 -0
- package/clis/douyin/activities.js +1 -1
- package/clis/douyin/collections.js +1 -1
- package/clis/douyin/comment-like.js +1 -0
- package/clis/douyin/comment.js +1 -0
- package/clis/douyin/comments.js +1 -0
- package/clis/douyin/draft.js +8 -8
- package/clis/douyin/hashtag.js +1 -1
- package/clis/douyin/location.js +1 -1
- package/clis/douyin/music-categories.js +1 -0
- package/clis/douyin/music.js +1 -0
- package/clis/douyin/publish-image.js +12 -12
- package/clis/douyin/publish.js +9 -8
- package/clis/xiaohongshu/_shared/ai-declaration.js +1 -0
- package/clis/xiaohongshu/_shared/comment-actions.js +9 -0
- package/clis/xiaohongshu/_shared/comment-state.js +1 -0
- package/clis/xiaohongshu/_shared/publish-discovery.js +19 -0
- package/clis/xiaohongshu/_shared/publish-editors.js +1 -0
- package/clis/xiaohongshu/_shared/publish-settings.js +1 -0
- package/clis/xiaohongshu/_shared/topics.js +21 -0
- package/clis/xiaohongshu/activities.js +1 -0
- package/clis/xiaohongshu/collections.js +1 -0
- package/clis/xiaohongshu/comment-like.js +1 -0
- package/clis/xiaohongshu/comment.js +1 -0
- package/clis/xiaohongshu/comments.js +33 -5
- package/clis/xiaohongshu/groups.js +1 -0
- package/clis/xiaohongshu/location.js +1 -0
- package/clis/xiaohongshu/publish-video.js +10 -28
- package/clis/xiaohongshu/publish.js +43 -165
- package/clis/xiaohongshu/replies.js +1 -0
- package/clis/xiaohongshu/reply.js +1 -0
- package/clis/xiaohongshu/topics.js +1 -0
- package/dist/src/cli.js +27 -25
- package/package.json +1 -1
- package/skills/opencli-browser/SKILL.md +14 -3
package/dist/src/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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
|
|
1
|
+
import*as k from"node:fs";import*as fe from"node:os";import*as N from"node:path";import{fileURLToPath as io}from"node:url";import{Command as Oe,InvalidArgumentError as yt,Option as ao}from"commander";import co from"js-yaml";import{findPackageRoot,getBuiltEntryCandidates as lo}from"./package-paths.js";import{fullName as Ge,getRegistry as Re,strategyLabel as bt}from"./registry.js";import{serializeCommand as uo,formatArgSummary as mo}from"./serialization.js";import{render as Ce}from"./output.js";import{PKG_VERSION as $e}from"./version.js";import{printCompletionScript as po}from"./completion.js";import{loadExternalClis as Be,executeExternalCli as fo,installExternalCli as go,registerExternalCli as ho,isBinaryInstalled as Fe,formatExternalCliLabel as St}from"./external.js";import{listOpenCliSkills as wo,readOpenCliSkill as yo}from"./skills.js";import{registerAllCommands as bo}from"./commanderAdapter.js";import{classifyAdapter as xt,formatRootAdapterHelpText as So,installCommanderNamespaceStructuredHelp as ge,installStructuredHelp as xo,leadingPositionalFromUsage as vo,rootHelpData as Ro}from"./help.js";import{EXIT_CODES as f,getErrorMessage as j,BrowserConnectError as Co,CliError as Le,CommandExecutionError as ee,toEnvelope as Eo}from"./errors.js";import{TargetError as vt}from"./browser/target-errors.js";import{resolveTargetJs as _o,getTextResolvedJs as Oo,getValueResolvedJs as $o,getAttributesResolvedJs as No,selectResolvedJs as ko,isAutocompleteResolvedJs as Ao}from"./browser/target-resolver.js";import{buildFindJs as To,buildSemanticFindJs as Rt,isFindError as Ct}from"./browser/find.js";import{inferShape as Et}from"./browser/shape.js";import{assignKeys as _t}from"./browser/network-key.js";import{DEFAULT_TTL_MS as Ot,findEntry as Io,loadNetworkCache as Po,saveNetworkCache as Jo}from"./browser/network-cache.js";import{NETWORK_INTERCEPTOR_JS as Ne}from"./browser/network-interceptor.js";import{parseFilter as Mo,shapeMatchesFilter as jo}from"./browser/shape-filter.js";import{buildHtmlTreeJs as Uo}from"./browser/html-tree.js";import{buildExtractHtmlJs as Do,runExtractFromHtml as Go}from"./browser/extract.js";import{analyzeSite as Bo}from"./browser/analyze.js";import{registerAuthCommands as Fo}from"./commands/auth.js";import{daemonRestart as Lo,daemonStatus as zo,daemonStop as Wo,daemonWarm as Ho}from"./commands/daemon.js";import{log as Y}from"./logger.js";import{bindTab as Vo,BrowserCommandError as $t,sendCommand as qo}from"./browser/daemon-client.js";import{fetchDaemonStatus as Xo}from"./browser/daemon-transport.js";import{aliasForContextId as Nt,listManagedProfiles as ze,loadProfileConfig as Ko,renameProfile as Zo,resolveProfile as kt,resolveProfileContextId as Yo,setDefaultProfile as Qo}from"./browser/profile.js";import{createManagedProfile as er,ensureManagedChrome as We,isManagedChromeRunning as tr,removeManagedProfile as or,stopManagedChrome as rr,resolveManagedOpts as At,updateManagedProfileConfig as nr}from"./browser/managed-chrome.js";import{testProxy as sr,parseProxyUrl as He}from"./browser/proxy-test.js";import{formatDaemonVersion as ir,isDaemonStale as ar}from"./browser/daemon-version.js";import{DEFAULT_BROWSER_CONNECT_TIMEOUT as Ve}from"./browser/config.js";const qe=io(import.meta.url),cr='Target tab/page identity returned by "browser open", "browser tab new", or "browser tab list"',Tt=1000;function ke(a,c){if(a===void 0||a===null||a==="")return null;const i=String(a).trim(),m=/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(i);if(!m)return{error:`--${c} must be a duration like 500ms, 30s, 2m, got "${i}"`};const x=Number.parseFloat(m[1]),g=m[2]??"ms";return Math.round(x*(g==="h"?3600000:g==="m"?60000:g==="s"?1000:1))}function Xe(a){return typeof a==="number"&&Number.isFinite(a)&&a>0?a:Date.now()}function he(a){if(typeof a!=="number"||!Number.isFinite(a)||a<=0)return;return new Date(a).toISOString()}function Ke(a,c,i=Date.now()){const m=c.sinceMs!=null?i-c.sinceMs:void 0,x=c.untilMs!=null?i-c.untilMs:void 0;return a.filter((g)=>{const A=g.timestamp??i;if(m!==void 0&&A<m)return!1;if(x!==void 0&&A>x)return!1;return!0})}export function selectFreshByTimestamp(a,c){const i=a.filter((x)=>Number(x.timestamp??0)>c),m=i.length>0?Math.max(c,...i.map((x)=>Number(x.timestamp??0)).filter(Number.isFinite)):c;return{fresh:i,lastSeenTs:m}}async function we(a){if(a.readNetworkCapture){const i=await a.readNetworkCapture();if(Array.isArray(i)&&i.length>0)return i.map((m)=>{const x=m.responsePreview??null;let g=null;if(x)try{g=JSON.parse(x)}catch{g=x}const A=typeof m.responseBodyFullSize==="number"?m.responseBodyFullSize:x?x.length:0,R=m.responseBodyTruncated===!0;return{url:m.url||"",method:m.method||"GET",status:m.responseStatus||0,size:A,ct:m.responseContentType||"",body:g,bodyFullSize:A,bodyTruncated:R,timestamp:Xe(m.timestamp),...m.channel?{channel:m.channel}:{},...m.direction?{direction:m.direction}:{},...m.eventName?{eventName:String(m.eventName)}:{},...m.eventId?{eventId:String(m.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((m)=>({...m,timestamp:Xe(m.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 It=4000;function lr(a){if(typeof a!=="string")return a??null;return a.length>It?`${a.slice(0,It)}…[truncated ${a.length} chars]`:a}function Pt(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 dr={invalid_args:f.USAGE_ERROR,invalid_filter:f.USAGE_ERROR,invalid_max_body:f.USAGE_ERROR};function K(a,c,i={}){console.log(JSON.stringify({error:{code:a,message:c,...i}},null,2));process.exitCode=dr[a]??f.GENERIC_ERROR}const ur="Site sitemap available. For navigation context, use the opencli-browser-sitemap skill; treat browser state as truth if it disagrees.";function mr(a,c=Re()){let i;try{i=new URL(a).hostname.toLowerCase().replace(/^www\./,"")}catch{return[]}const m=new Map;for(const R of c.values()){if(!R.domain)continue;let O=R.domain.toLowerCase().trim();try{O=new URL(O.includes("://")?O:`https://${O}`).hostname.toLowerCase()}catch{O=O.split("/")[0]??O}O=O.replace(/^www\./,"");if(!O)continue;if(i===O||i.endsWith(`.${O}`))m.set(R.site,Math.max(m.get(R.site)??0,O.length))}const x=[...m.entries()].sort((R,O)=>O[1]-R[1]||R[0].localeCompare(O[0])).map(([R])=>R),g=i.split(".").filter(Boolean),A=g.length>=2?g[g.length-2]:g[0];return[...new Set([...x,...A?[A]:[]])]}function Jt(a,c){return a.find((i)=>c(i))}function pr(a,c){const i=a.replace(/[^a-zA-Z0-9_-]+/g,"-");if(!i)return{};const m=N.join(c.homeDir,".ppcli","sites",i);return{local:Jt([N.join(m,"sitemap"),N.join(m,"sitemap.md")],c.fileExists),global:Jt([N.join(c.packageRoot,"sitemaps",i),N.join(c.packageRoot,"sitemaps",`${i}.md`)],c.fileExists)}}export function resolveSitemapAvailabilityForUrl(a,c={}){const i=c.homeDir??fe.homedir(),m=c.packageRoot??findPackageRoot(qe),x=c.registry??Re(),g=c.fileExists??k.existsSync;for(const A of mr(a,x)){const R=pr(A,{homeDir:i,packageRoot:m,fileExists:g});if(!R.local&&!R.global)continue;const O=R.local&&R.global?"local+global":R.local?"local":"global";return{site:A,available:!0,source:O,hint:ur,paths:R}}return null}function Mt(a){const c=a.replace(/[^a-zA-Z0-9_-]+/g,"_");return N.join(Ut(),"browser-sitemap-hints",`${c}.json`)}function jt(a){try{const c=JSON.parse(k.readFileSync(Mt(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 fr(a,c){const i=jt(a);if(!i.seenSites.includes(c))i.seenSites.push(c);const m=Mt(a);k.mkdirSync(N.dirname(m),{recursive:!0});k.writeFileSync(m,JSON.stringify({seenSites:i.seenSites,updatedAt:new Date().toISOString()}),"utf-8")}function gr(a,c,i){const m=resolveSitemapAvailabilityForUrl(a);if(!m)return null;if(!i.oncePerSession)return m;if(jt(c).seenSites.includes(m.site))return null;fr(c,m.site);return m}export function checkSiteMemory(a){const c=N.join(fe.homedir(),".ppcli","sites",a),i=N.join(c,"endpoints.json"),m=N.join(c,"notes.md");let x=0,g=k.existsSync(i);if(g)try{const R=JSON.parse(k.readFileSync(i,"utf-8"));if(R&&typeof R==="object"&&!Array.isArray(R))x=Object.keys(R).length;else if(Array.isArray(R))x=R.length}catch{g=!1}const A=k.existsSync(m);return{ok:g&&x>0&&A,siteDir:c,endpoints:{present:g,count:x,path:i},notes:{present:A,path:m}}}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?"✗":"⚠",m=[];if(!a.endpoints.present)m.push("endpoints.json");else if(a.endpoints.count===0)m.push("endpoints.json (empty)");if(!a.notes.present)m.push("notes.md");console.log(` ${i} Memory: missing ${m.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((m)=>m&&typeof m==="object"?m:{value:m});return[c]}return[]}export function renderVerifyPreview(a,c={}){const i=c.maxRows??10,m=c.maxCols??6,x=c.cellMax??40;if(a.length===0)return" (no rows)";const g=Array.from(new Set(a.flatMap((T)=>Object.keys(T)))),A=g.slice(0,m),R=a.slice(0,i),O=(T)=>{if(T===null||T===void 0)return"";return(typeof T==="object"?JSON.stringify(T):String(T)).replace(/\s+/g," ").slice(0,x)},te=A.map((T)=>Math.max(T.length,...R.map((q)=>O(q[T]).length))),Z=(T)=>T.map((q,S)=>q.padEnd(te[S])).join(" "),V=[];V.push(` ${Z(A)}`);V.push(` ${te.map((T)=>"-".repeat(T)).join(" ")}`);for(const T of R)V.push(` ${Z(A.map((q)=>O(T[q])))}`);if(a.length>i)V.push(` ... and ${a.length-i} more row(s)`);if(g.length>m)V.push(` (${g.length-m} more column(s) hidden)`);return V.join(`
|
|
2
|
+
`)}function Ut(){return process.env.OPENCLI_CACHE_DIR||N.join(fe.homedir(),".ppcli","cache")}function Dt(a){const c=a.replace(/[^a-zA-Z0-9_-]+/g,"_");return N.join(Ut(),"browser-state",`${c}.json`)}function Gt(a){try{const c=k.readFileSync(Dt(a),"utf-8"),i=JSON.parse(c);return i&&typeof i==="object"?i:null}catch{return null}}function ye(a,c){const i=Dt(c);if(!a){k.rmSync(i,{force:!0});return}k.mkdirSync(N.dirname(i),{recursive:!0});k.writeFileSync(i,JSON.stringify({defaultPage:a,updatedAt:new Date().toISOString()}),"utf-8")}function hr(a,c){return a.some((i)=>{return typeof i==="object"&&i!==null&&"page"in i&&typeof i.page==="string"&&i.page===c})}async function Ze(a,c,i){const m=c.trim();if(!m)return;let x;try{x=await a.tabs()}catch(g){if(i.source==="saved"){ye(void 0,i.scope);return}throw Error(`Target tab ${m} 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(x)&&hr(x,m))return m;if(i.source==="saved"){ye(void 0,i.scope);return}throw Error(`Target tab ${m} 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 Ae(a,c){return c?`${c}:${a}`:a}async function wr(a,c){const i=Gt(c)?.defaultPage?.trim();if(!i)return;return Ze(a,i,{scope:c,source:"saved"})}async function yr(a,c,i,m={}){if(m.adapter&&!/^site:[a-z0-9][a-z0-9_-]*$/.test(a))throw new ee("--adapter requires the existing adapter session name: site:<site>, e.g. site:douyin");const x=m.adapter?"adapter":"browser",g=kt(m.profile);if(g.kind==="managed"){if(c)throw Error(`托管环境「${g.name}」是单窗口复用标签模型,不支持 --tab 定位。直接省略 --tab 即可。`);const q=m.windowMode??Ye(void 0,"background"),{ensureManagedChrome:S}=await import("./browser/managed-chrome.js"),{CDPBridge:Ee}=await import("./browser/cdp.js"),{generateFingerprintJs:ae}=await import("./browser/fingerprint.js"),be=await S(g.name,g.entry,{windowMode:q}),oe=g.entry.fingerprint,ce=g.entry.proxy,_e=new Ee;return{page:await _e.connect({timeout:Ve,session:a,surface:x,...m.adapter?{siteSession:"persistent"}:{},cdpEndpoint:be,contextId:g.name,windowMode:q,...oe?.enabled?{initScript:ae(oe)}:{},...ce?.username?{proxyAuth:{username:ce.username,password:ce.password??""}}:{}}),close:()=>_e.close()}}const{BrowserBridge:A}=await import("./browser/index.js"),R=new A,O=process.env.OPENCLI_BROWSER_IDLE_TIMEOUT,te=O?parseInt(O,10):void 0,Z=await R.connect({timeout:Ve,session:a,surface:x,...m.adapter?{siteSession:"persistent"}:{},...i&&{contextId:i},...te&&te>0&&{idleTimeout:te},windowMode:m.windowMode??Ye(void 0,"background")}),V=Ae(m.adapter?`adapter:${a}`:a,i),T=c?await Ze(Z,c,{scope:V,source:"explicit"}):await wr(Z,V);if(T){if(!Z.setActivePage)throw Error("This browser session does not support explicit tab targeting");Z.setActivePage(T)}return{page:Z,close:()=>R.close()}}function Ye(a,c){const i=Te(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 m=process.env.OPENCLI_WINDOW;if(m!==void 0&&m!==""){if(m==="foreground"||m==="background")return m;throw Error(`OPENCLI_WINDOW must be one of: foreground, background. Received: "${m}"`)}return c}function C(a){return a.option("--tab <targetId>",cr)}function br(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 Te(a,c){let i=a;while(i){const m=i.opts();if(Object.prototype.hasOwnProperty.call(m,c)&&m[c]!==void 0)return m[c];i=i.parent}return}function Bt(a){const c=Te(a,"session");if(typeof c==="string"&&c.trim())return c.trim();throw Error("<session> is a required positional argument: ppcli browser <session> <command>")}function Ft(a){return Yo(Qe(a))}function Qe(a){const c=Te(a,"profile");return typeof c==="string"&&c.trim()?c.trim():void 0}function et(a){const c=a.session;if(typeof c==="string"&&c.trim())return c.trim();throw Error("Browser page is missing a session")}function Ie(a){const c=a.contextId;return Ae(et(a),typeof c==="string"&&c.trim()?c.trim():void 0)}function Sr(a){return typeof a==="string"?a:JSON.stringify(a,null,2)}function xr(a,c){const i=Sr(a),m=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,...m?{interactive:Number(m[1])}:{},elapsed_ms:c}}async function Lt(a,c){const i=Date.now();try{const m=await a.snapshot({viewportExpand:2000,source:c});return xr(m,Date.now()-i)}catch(m){return{ok:!1,elapsed_ms:Date.now()-i,error:{...m instanceof Error&&"code"in m?{code:String(m.code)}:{},message:m instanceof Error?m.message:String(m)}}}}function zt(a,c){if(typeof a==="string"&&a.trim())return a.trim();const i=c instanceof Oe?c.opts().tab:c?.tab;if(typeof i==="string"&&i.trim())return i.trim();return}function Wt(a,c,i){if(a===void 0)return i;const m=parseInt(a,10);if(Number.isNaN(m)||m<=0){console.error(`[cli] Invalid ${c}="${a}", using default ${i}`);return i}return m}function Ht(a,c){if(!/^\d+$/.test(a))throw new yt(`--${c} must be a positive integer (got "${a}")`);const i=parseInt(a,10);if(i<=0)throw new yt(`--${c} must be a positive integer (got "${a}")`);return i}function vr(a){if(a.verbose)process.env.OPENCLI_VERBOSE="1"}function Rr(a){return[...new Set(a.commands.map((c)=>c.name()))].sort((c,i)=>c.localeCompare(i)).join(", ")}function Cr(a){for(const c of a.commands){if(c.commands.length===0)continue;const i=Rr(c);if(i)c.description(i)}}export function createProgram(a,c){const i=new Oe;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=Re(),o=[...new Set(t.values())].sort((p,h)=>Ge(p).localeCompare(Ge(h))),r=e.format,n=r==="json"||r==="yaml";if(r!=="table"){const p=n?o.map(uo):o.map((h)=>({command:Ge(h),site:h.site,name:h.name,aliases:h.aliases?.join(", ")??"",description:h.description,access:h.access,strategy:bt(h),browser:!!h.browser,args:mo(h.args)}));Ce(p,{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 p of o){const h=xt(p.domain)==="app"?s:l,v=h.get(p.site)??[];v.push(p);h.set(p.site,v)}const d=(p,h)=>{console.log(` ${p}`);for(const v of h){const E=bt(v),I=E==="public"?"[public]":`[${E}]`,D=v.aliases?.length?` (aliases: ${v.aliases.join(", ")})`:"";console.log(` ${v.name} ${I}${D}${v.description?` — ${v.description}`:""}`)}console.log()};console.log();console.log(" ppcli"+" — available commands");console.log();if(s.size>0){console.log(" App adapters");console.log();for(const[p,h]of s)d(p,h)}if(l.size>0){console.log(" Site adapters");console.log();for(const[p,h]of l)d(p,h)}const u=Be();if(u.length>0){console.log(" external CLIs");for(const p of u){const v=Fe(p.binary)?"[installed]":"[auto-install]";console.log(` ${St(p)} ${v}${p.description?` — ${p.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 m=i.command("skills").description("Read bundled ppcli skills");m.command("list").description("List bundled ppcli-* skills").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((e)=>{const t=wo();Ce(t,{fmt:e.format,fmtExplicit:!!e.format,columns:["name","description","version","path"],title:"ppcli/skills/list",source:"ppcli skills list"})});m.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=yo(e,t??"")}catch(n){console.error(`Error: ${j(n)}`);if(n instanceof Le&&n.hint)console.error(`Hint: ${n.hint}`);process.exitCode=n instanceof Le?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
|
|
4
|
+
`)});const x=Fo(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(qe),target:e,site:t.site}),s=String(t.format??"table").toLowerCase();if(s==="json"||s==="yaml"||s==="yml")Ce(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 ao("--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
|
-
`),
|
|
15
|
-
`);console.log(typeof r==="string"?r:JSON.stringify(r,null,2))}));
|
|
14
|
+
`),A=g.description();async function R(e,t,o={}){const r=await e.evaluate(_o(t,o));if(!r.ok)throw new vt({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 O(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 te(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 Z(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 q(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 Oe?t.at(-1):void 0,n=br(r),s=Bt(r),l=Ft(r),d=Ye(r,"background");o=await yr(s,n,l,{windowMode:d,profile:Qe(r),adapter:Te(r,"adapter")===!0});await e(o.page,...t)}catch(r){if(r instanceof Co){Y.error(r.message);if(r.hint)Y.error(`Hint: ${r.hint}`)}else if(r instanceof $t){if(Z(r.message))V(r.message);else T(r);q(r)}else if(r instanceof vt){te(r);Y.error(`[${r.code}] ${r.message}`);if(r.hint)Y.error(`Hint: ${r.hint}`)}else{const n=j(r);if(Z(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 Oe?o:r,s=Bt(n),l=Ft(n);try{if(t?.managedGuardMessage&&kt(Qe(n)).kind==="managed")throw Error(t.managedGuardMessage);const{BrowserBridge:d}=await import("./browser/index.js");await new d().connect({timeout:Ve,session:s,surface:"browser",...l&&{contextId:l}});await e({session:s,contextId:l})}catch(d){if(d instanceof $t){T(d);q(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 Vo(e,{...t&&{contextId:t}});ye(void 0,Ae(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 qo("close-window",{session:e,surface:"browser",...t&&{contextId:t}});ye(void 0,Ae(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))}));C(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=zt(t,o);if(!r)throw Error("Target tab required. Pass it as an argument or --tab <targetId>.");await e.selectTab(r);ye(r,Ie(e));console.log(JSON.stringify({selected:r},null,2))}));C(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=zt(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 Ze(e,r,{scope:Ie(e),source:"explicit"});if(!n)throw Error(`Target tab ${r} is not part of the current browser session.`);await e.closeTab(n);const s=Ie(e);if(Gt(s)?.defaultPage===n)ye(void 0,s);console.log(JSON.stringify({closed:n},null,2))}));C(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(Ne)}catch{}const n=await e.getCurrentUrl?.()??t,s=gr(n,Ie(e),{oncePerSession:!0});console.log(JSON.stringify({url:n,...e.getActivePage?.()?{page:e.getActivePage?.()}:{},...s?{sitemap:s}:{}},null,2))}));C(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")}));C(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}`)}));C(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([Lt(e,"dom"),Lt(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))}));C(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))}));C(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)=>Ht(e,"width")).option("--height <n>","Override viewport height in CSS pixels for this screenshot only (ignored with --full-page)",(e)=>Ht(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 ee(`--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 be=['iframe[src*="/verifycenter/captcha/"]',".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]'],oe=6;function ce(e){const t=e&&e.trim()?[e.trim()]:be;return`(() => {
|
|
16
16
|
var sels = ${JSON.stringify(t)};
|
|
17
17
|
var el = null, used = '';
|
|
18
18
|
for (var i = 0; i < sels.length; i++) {
|
|
@@ -20,7 +20,7 @@ Examples:
|
|
|
20
20
|
var cands = Array.from(document.querySelectorAll(sels[i]));
|
|
21
21
|
for (var j = 0; j < cands.length; j++) {
|
|
22
22
|
var r0 = cands[j].getBoundingClientRect();
|
|
23
|
-
if (r0.width > 20 && r0.height > 20) { el = cands[j]; used = sels[i]; break; }
|
|
23
|
+
if (r0.width > 20 && r0.height > 20 && r0.right > 0 && r0.bottom > 0 && r0.left < innerWidth && r0.top < innerHeight && getComputedStyle(cands[j]).visibility === 'visible') { el = cands[j]; used = sels[i]; break; }
|
|
24
24
|
}
|
|
25
25
|
} catch (e) {}
|
|
26
26
|
if (el) break;
|
|
@@ -45,8 +45,10 @@ Examples:
|
|
|
45
45
|
dpr: window.devicePixelRatio || 1,
|
|
46
46
|
viewport: { w: window.innerWidth, h: window.innerHeight },
|
|
47
47
|
prompt: prompt,
|
|
48
|
+
iframe: el.tagName === 'IFRAME',
|
|
49
|
+
scroll: { x: window.scrollX, y: window.scrollY },
|
|
48
50
|
};
|
|
49
|
-
})()`}function
|
|
51
|
+
})()`}function _e(e){const t=e&&e.trim()?[e.trim()]:be;return`(() => {
|
|
50
52
|
var sels = ${JSON.stringify(t)};
|
|
51
53
|
var present = false;
|
|
52
54
|
for (var i = 0; i < sels.length; i++) {
|
|
@@ -54,7 +56,7 @@ Examples:
|
|
|
54
56
|
var cands = Array.from(document.querySelectorAll(sels[i]));
|
|
55
57
|
for (var j = 0; j < cands.length; j++) {
|
|
56
58
|
var r = cands[j].getBoundingClientRect();
|
|
57
|
-
if (r.width > 20 && r.height > 20) { present = true; break; }
|
|
59
|
+
if (r.width > 20 && r.height > 20 && getComputedStyle(cands[j]).visibility === 'visible') { present = true; break; }
|
|
58
60
|
}
|
|
59
61
|
} catch (e) {}
|
|
60
62
|
if (present) break;
|
|
@@ -69,7 +71,7 @@ Examples:
|
|
|
69
71
|
}
|
|
70
72
|
} catch (e) {}
|
|
71
73
|
return { captcha_present: present, status_text: status, url: (location.href || '').slice(0, 100) };
|
|
72
|
-
})()`}
|
|
74
|
+
})()`}function Pe(e,t){const o=Math.max(0,e.x-oe),r=Math.max(0,e.y-oe),n=Math.min(t.w,e.x+e.w+oe)-o,s=Math.min(t.h,e.y+e.h+oe)-r;if(n<=0||s<=0)throw new ee("验证码区域不在可见视口内,请重新截图定位");return{x:o,y:r,w:n,h:s}}C(g.command("captcha").argument("[selector]","验证码图片元素 CSS 选择器(缺省自动探测常见点选验证码)")).option("--adapter","定位已有平台适配器会话;session 必须是 site:<site>,如 site:douyin").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(ce(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:be}},null,2));process.exitCode=f.USAGE_ERROR;return}const n=o?.save&&String(o.save)||N.join(fe.tmpdir(),`opencli-captcha-${Date.now()}.png`);await e.screenshot({format:"png",path:n});const s=r.rect,l=r.dpr||1,d=Pe(s,r.viewport),u=Math.max(1,Math.min(6,Number(o?.scale??3)||3)),p=oe;let h=null;const v=e.cdp;if(typeof v==="function"){const E={x:d.x+(r.scroll?.x??0),y:d.y+(r.scroll?.y??0),width:d.w,height:d.h,scale:u},I=await v.call(e,"Page.captureScreenshot",{format:"jpeg",quality:82,clip:E,captureBeyondViewport:!1});if(I&&I.data){h=n.replace(/\.png$/i,"")+".crop.jpg";k.writeFileSync(h,Buffer.from(I.data,"base64"))}}console.log(JSON.stringify({ok:!0,selector:r.selector,iframe:r.iframe===!0,crop_rect_css:h?d:null,prompt:r.prompt||"",crop:h,crop_scale:h?u:null,crop_pad:h?p: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"+(o.adapter?" --adapter":"")+" --crop --in '"+r.selector.replace(/'/g,"'\\''")+"'"+' "x1,y1 x2,y2 ..."(--crop 表示坐标是 crop 图比例;空格分隔,顺序即点击顺序)。'+"iframe 的提示与确认按钮请从截图读取;点完文字后可能仍需点确认。验证码仍在不代表可以重复点字;先截图检查。"},null,2))}));C(g.command("captcha-click").argument("<points>",'待点击坐标,空格分隔且顺序即点击顺序,如 "0.30,0.46 0.68,0.66"')).option("--adapter","定位已有平台适配器会话;session 必须是 site:<site>,如 site:douyin").option("--save <path>","点击后保存全视口截图,以核对点选标记、确认按钮及验证结果").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((y)=>{const b=y.split(",");if(b.length!==2||b.some((M)=>!M.trim()))return{x:NaN,y:NaN};return{x:Number(b[0]),y:Number(b[1])}});if(n.length===0||n.some((y)=>!Number.isFinite(y.x)||!Number.isFinite(y.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}if([o?.css,o?.px,o?.crop].filter(Boolean).length>1)throw new ee("--css / --px / --crop 不能同时使用");const s=o?.css?"css":o?.px?"px":o?.crop?"crop":"frac";if(n.some((y)=>y.x<0||y.y<0||(s==="frac"||s==="crop")&&(y.x>1||y.y>1)))throw new ee("相对坐标必须在 0..1 内,绝对坐标必须非负;尚未点击");const l=Number(o?.delay??250);if(!Number.isFinite(l)||l<0||l>1e4)throw new ee("--delay 必须在 0..10000 毫秒内");let d={x:0,y:0,w:0,h:0},u=1,p;if(s==="css"||s==="px"){const y=await e.evaluate("({w: innerWidth, h: innerHeight, dpr: devicePixelRatio})");p=y;u=y.dpr}else{const y=await e.evaluate(ce(typeof o?.in==="string"?o.in:void 0));if(!y||!y.found||!y.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=y.rect;u=y.dpr||1;p=y.viewport}const h=s==="crop"?Pe(d,p):d,v=(y)=>{if(s==="css")return y;if(s==="px")return{x:y.x/u,y:y.y/u};if(s==="crop")return{x:h.x+y.x*h.w,y:h.y+y.y*h.h};return{x:d.x+y.x*d.w,y:d.y+y.y*d.h}},{cdp:E,nativeClick:I}=e,D=n.map(v).map((y)=>({x:Math.round(y.x),y:Math.round(y.y)}));if(D.some((y)=>y.x<0||y.y<0||y.x>=p.w||y.y>=p.h))throw new ee("点击坐标超出视口;尚未点击,请重新截图定位");if(typeof E!=="function"&&typeof I!=="function")throw new ee("当前浏览器不支持原生坐标点击");const P=(y)=>new Promise((b)=>setTimeout(b,y));async function X(y,b,M,G){if(typeof E==="function"){const se=12+G%4;for(let W=1;W<=se;W++){const z=W/se,ie=z*z*(3-2*z),pe=Math.sin(z*Math.PI)*10*(G%2===0?1:-1),J=M.x+(y-M.x)*ie,H=M.y+(b-M.y)*ie+pe;await E.call(e,"Input.dispatchMouseEvent",{type:"mouseMoved",x:Math.round(J),y:Math.round(H)});await P(8+W%3*6)}await E.call(e,"Input.dispatchMouseEvent",{type:"mouseMoved",x:y,y:b});await P(40+G%3*25);await E.call(e,"Input.dispatchMouseEvent",{type:"mousePressed",x:y,y:b,button:"left",clickCount:1});await P(45+G%4*20);await E.call(e,"Input.dispatchMouseEvent",{type:"mouseReleased",x:y,y:b,button:"left",clickCount:1});return"cdp"}if(typeof I==="function"){await I.call(e,y,b);return"native"}throw new ee("当前浏览器不支持原生坐标点击")}const U=[];let L="",re={x:Math.round(d.x+d.w/2)||400,y:Math.round(d.y-40)||200};for(let y=0;y<D.length;y++){const b=D[y],M=Math.round(b.x),G=Math.round(b.y);L=await X(M,G,re,y);re={x:M,y:G};U.push({x:M,y:G});if(y<n.length-1&&l>0)await P(l)}await P(700);let w={};try{w=await e.evaluate(_e(typeof o?.in==="string"?o.in:void 0))}catch(y){w={read_error:j(y)}}const _=o.save?String(o.save):void 0;if(_)await e.screenshot({path:_,format:"png"});console.log(JSON.stringify({ok:!0,mode:s,method:L,clicked_n:U.length,points_css:U,after:w,..._?{saved:_}:{}},null,2))}));C(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=ke(t.since,"since"),r=ke(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 p=u;return{...p,timestamp:Xe(p.timestamp)}}return{type:"log",text:String(u),timestamp:Date.now()}}),s=(d)=>Ke(d,{sinceMs:o,untilMs:r}).filter((u)=>{if(t.level==="all")return!0;const p=String(u.type??u.level??"").toLowerCase();return t.level==="error"?p==="error"||p==="warning":p===String(t.level).toLowerCase()});if(t.follow){let d=0;while(!0){const u=s(n(await e.consoleMessages("all"))),p=selectFreshByTimestamp(u,d);for(const h of p.fresh)console.log(JSON.stringify({...h,timestamp:he(h.timestamp)}));d=p.lastSeenTs;await new Promise((h)=>setTimeout(h,Tt))}}const l=s(n(await e.consoleMessages(t.level)));console.log(JSON.stringify({session:et(e),captured_at:new Date().toISOString(),count:l.length,messages:l.map((d)=>({...d,timestamp:he(d.timestamp)}))},null,2))}));C(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(Ne)}catch{}await we(e);await e.wait(1);const n=(await we(e)).map((E)=>({url:E.url,status:E.status,contentType:E.ct,bodyPreview:typeof E.body==="string"?E.body.slice(0,2000):E.body?JSON.stringify(E.body).slice(0,2000):null})),s=`(function(){
|
|
73
75
|
return {
|
|
74
76
|
cookieNames: (document.cookie || '').split(';').map(function(c){ return c.trim().split('=')[0]; }).filter(Boolean),
|
|
75
77
|
initialState: {
|
|
@@ -81,7 +83,7 @@ Examples:
|
|
|
81
83
|
title: document.title || '',
|
|
82
84
|
finalUrl: location.href,
|
|
83
85
|
};
|
|
84
|
-
})()`,l=await e.evaluate(s),d=(await e.getCookies({url:l.finalUrl||t}).catch(()=>[])).map((
|
|
86
|
+
})()`,l=await e.evaluate(s),d=(await e.getCookies({url:l.finalUrl||t}).catch(()=>[])).map((E)=>E.name).filter(Boolean),u=[...new Set([...l.cookieNames,...d])],p={requestedUrl:t,finalUrl:l.finalUrl,cookieNames:u,networkEntries:n,initialState:l.initialState,title:l.title},h=Bo(p,Re()),v=resolveSitemapAvailabilityForUrl(l.finalUrl||t);console.log(JSON.stringify({...h,...v?{sitemap:v}:{}},null,2))}));const F=(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"),tt=(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`),Se=(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},Vt=(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},ot=async(e,t,o)=>{const r=await e.evaluate(Rt({...t,limit:6}));if(Ct(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},qt=async(e,t,o)=>{const r=Se(t);if(!r)return null;return ot(e,r,o)},Je=async(e,t,o,r)=>{const n=typeof t==="string"&&t.trim()?t.trim():"",s=!!Se(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 qt(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 Je(e,t,o,"write");if(typeof r==="string")return r;if("error"in r)le(r);return null},Me=async(e,t,o,r,n)=>{const s=!!Se(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)}},rt=async(e,t,o,r,n)=>{const s=typeof t==="string"&&t.trim()?t.trim():"",l=Vt(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 ot(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};C(F(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=Se(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=O(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=O(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?Rt({...o,limit:r??void 0,textMax:n??void 0}):To(t.css,{limit:r??void 0,textMax:n??void 0}));if(Ct(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");C(ue.command("title").description("Page title")).action(S(async(e)=>{console.log(await e.evaluate("document.title"))}));C(ue.command("url").description("Current page URL")).action(S(async(e)=>{console.log(await e.getCurrentUrl?.()??await e.evaluate("location.href"))}));const je=async(e,t,o,r,n)=>{const s=await Je(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=O(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:p,match_level:h}=await R(e,l,{firstOnMulti:u===null,...typeof u==="number"?{nth:u}:{}}),v=await e.evaluate(r);let E;if(n==="attributes")try{E=v==null?{}:JSON.parse(String(v))}catch{E=v}else E=v??null;console.log(JSON.stringify({value:E,matches_n:p,match_level:h,...d&&d>1?{total_matches:d}:{}},null,2))};C(F(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)=>je(e,t,o??{},Oo(),"text")));C(F(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)=>je(e,t,o??{},$o(),"value")));C(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=(P,X)=>{const U=X===void 0||X===null?"":String(X);if(U==="")return null;if(!/^\d+$/.test(U))return{error:`${P} must be a non-negative integer, got "${U}"`};return Number.parseInt(U,10)},p=u("--depth",t.depth),h=u("--children-max",t.childrenMax),v=u("--text-max",t.textMax);for(const P of[p,h,v])if(P&&typeof P==="object"&&"error"in P){console.log(JSON.stringify({error:{code:"invalid_budget",message:P.error}},null,2));process.exitCode=f.USAGE_ERROR;return}const E=Uo({selector:t.selector??null,depth:p,childrenMax:h,textMax:v}),I=await e.evaluate(E);if(I&&typeof I==="object"&&"invalidSelector"in I&&I.invalidSelector){console.log(JSON.stringify({error:{code:"invalid_selector",message:`Selector "${t.selector}" is not a valid CSS selector: ${I.reason}`}},null,2));process.exitCode=f.USAGE_ERROR;return}const D=I;if(!D||D.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(D,null,2));return}const s=t.selector?JSON.stringify(t.selector):"null",l=await e.evaluate(`(() => {
|
|
85
87
|
const s = ${s};
|
|
86
88
|
if (s) {
|
|
87
89
|
try {
|
|
@@ -93,7 +95,7 @@ Examples:
|
|
|
93
95
|
}
|
|
94
96
|
return { kind: 'ok', html: document.documentElement ? document.documentElement.outerHTML : null };
|
|
95
97
|
})()`);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(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';
|
|
98
|
+
${d.slice(0,n)}`);return}console.log(d)}));C(F(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)=>je(e,t,o??{},No(),"attributes")));function Q(e){const t=O(e);if(t&&typeof t==="object"&&"error"in t)return t;if(typeof t==="number")return{opts:{nth:t}};return{opts:{}}}function Xt(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(`~${N.sep}`)?N.join(fe.homedir(),n.slice(2)):n,l=N.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 nt(e,t){const o=O(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:{}}}C(F(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 Je(e,t,o??{},"write");if(typeof r!=="string"){console.log(JSON.stringify(r,null,2));process.exitCode=f.USAGE_ERROR;return}const n=Q(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:p}=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},...p&&{retargeted:p}},null,2))}));C(F(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 Me(e,t,o,r??{},"text");if(!n)return;const s=Q(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(Ao());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))}));C(F(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=Q(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))}));C(F(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=Q(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))}));C(F(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=Q(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 st=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=Q(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))};C(F(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 st(e,t,o??{},!0)}));C(F(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 st(e,t,o??{},!1)}));C(F(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=!!Se(r??{}),l=await de(e,n?void 0:t,r??{});if(!l)return;const d=Q(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((v)=>v!==void 0):o,p=Xt(u);if("error"in p){console.log(JSON.stringify({error:p.error},null,2));process.exitCode=f.USAGE_ERROR;return}const h=await e.uploadFiles(l,p.files,d.opts);console.log(JSON.stringify(h,null,2))}));C(tt(tt(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 rt(e,t,r??{},"from","source");if(!n)return;const s=await rt(e,o,r??{},"to","target");if(!s)return;const l=nt(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=nt(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))}));C(F(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 Me(e,t,o,r??{},"text");if(!n)return;const s=Q(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))}));C(F(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 Me(e,t,o,r??{},"option");if(!n)return;const s=Q(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 R(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))}));C(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 it=g.command("dialog").description("Handle a blocking JavaScript alert/confirm/prompt dialog");C(it.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))}));C(it.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))}));C(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(h){console.error(`Invalid regex "${o}": ${h instanceof Error?h.message:String(h)}`);process.exitCode=f.USAGE_ERROR;return}if(!(await e.startNetworkCapture?.()??!1))try{await e.evaluate(Ne)}catch{}await we(e);const d=Date.now()+n,u=400;let p=null;while(Date.now()<d&&!p){p=(await we(e)).find((v)=>s.test(v.url))??null;if(!p)await new Promise((v)=>setTimeout(v,u))}if(!p){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:p.url,status:p.status,contentType:p.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}}));C(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))}));C(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=Do(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 p=Go({html:u.html,url:u.url,title:u.title,selector:l,start:s,chunkSize:n});console.log(JSON.stringify(p,null,2))}));C(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(Ot)).description("Capture network requests as shape previews; retrieve full bodies by key").action(S(async(e,t)=>{const o=Wt(t.ttl,"ttl",Ot),r=et(e),n=typeof t.detail==="string"&&t.detail.length>0,s=typeof t.filter==="string",l=ke(t.since,"since"),d=ke(t.until,"until");if(l&&typeof l==="object"){K("invalid_since",l.error);return}if(d&&typeof d==="object"){K("invalid_until",d.error);return}if(n&&s){K("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 w=Mo(t.filter);if("reason"in w){K("invalid_filter",w.reason);return}u=w.fields}if(n&&t.follow){K("invalid_args","--follow cannot be used with --detail.");return}if(n){const w=Po(r,{ttlMs:o});if(w.status==="missing"){K("cache_missing",`No cached capture. Run "browser network" first (in session "${r}").`);return}if(w.status==="expired"){K("cache_expired",`Cache is stale (age ${w.ageMs}ms > ttl ${o}ms). Re-run "browser network" to refresh.`);return}if(w.status==="corrupt"||!w.file){K("cache_corrupt",'Cache file is malformed; re-run "browser network" to regenerate.');return}const _=Io(w.file,t.detail);if(!_){K("key_not_found",`Key "${t.detail}" not in cache.`,{available_keys:w.file.entries.map((z)=>z.key)});return}const y=String(t.maxBody??"0");if(!/^\d+$/.test(y)){K("invalid_max_body",`--max-body must be a non-negative integer, got "${t.maxBody}"`);return}const b=Number.parseInt(y,10);let M=_.body,G=!1;if(b>0&&typeof _.body==="string"&&_.body.length>b){M=_.body.slice(0,b);G=!0}const se=_.body_truncated===!0,W={key:_.key,url:_.url,method:_.method,status:_.status,ct:_.ct,size:_.size,...typeof _.timestamp==="number"?{timestamp:he(_.timestamp)}:{},shape:Et(_.body),body:M};if(se||G){W.body_truncated=!0;W.body_full_size=_.body_full_size??_.size;W.body_truncation_reason=se?"capture-limit":"max-body"}console.log(JSON.stringify(W,null,2));return}if(t.follow){if(!await e.startNetworkCapture?.())try{await e.evaluate(Ne)}catch{}while(!0){const w=await we(e).catch((b)=>{K("capture_failed",`Could not read network capture: ${b.message}`);return[]});let _=t.all?w:Pt(w);_=Ke(_,{sinceMs:l,untilMs:d});if(t.failed)_=_.filter((b)=>b.status===0||b.status>=400);const y=_t(_);for(const b of y){const M=b.channel==="websocket"||b.channel==="eventsource";console.log(JSON.stringify({key:b.key,timestamp:he(b.timestamp),method:b.method,status:b.status,url:b.url,ct:b.ct,size:b.size,...M?{channel:b.channel,direction:b.direction}:{},...b.eventName?{event_name:b.eventName}:{},...M?{body:lr(b.body)}:{},...b.bodyTruncated?{body_truncated:!0}:{}}))}await new Promise((b)=>setTimeout(b,Tt))}}let p;try{p=await we(e)}catch(w){K("capture_failed",`Could not read network capture: ${w.message}`);return}let h=t.all?p:Pt(p);h=Ke(h,{sinceMs:l,untilMs:d});if(t.failed)h=h.filter((w)=>w.status===0||w.status>=400);const v=p.length-h.length,I=_t(h).map((w)=>({key:w.key,url:w.url,method:w.method,status:w.status,size:w.size,ct:w.ct,body:w.body,...typeof w.timestamp==="number"?{timestamp:w.timestamp}:{},...w.bodyTruncated?{body_truncated:!0}:{},...w.bodyTruncated&&typeof w.bodyFullSize==="number"?{body_full_size:w.bodyFullSize}:{}}));let D=null;try{Jo(r,I)}catch(w){D=`Could not persist capture cache: ${w.message}. --detail lookups may miss this capture.`}const P=I.map((w)=>({entry:w,shape:Et(w.body)})),X=u?P.filter((w)=>jo(w.shape,u)):P,U=u?P.length-X.length:0,L={session:r,captured_at:new Date().toISOString(),count:X.length,filtered_out:v};if(u){L.filter=u;L.filter_dropped=U}if(D)L.cache_warning=D;const re=X.filter((w)=>w.entry.body_truncated).length;if(re>0){L.body_truncated_count=re;L.body_truncated_hint="Some bodies exceeded the capture limit; their `shape` reflects only the captured prefix."}if(t.raw)L.entries=X.map((w)=>({...w.entry,...typeof w.entry.timestamp==="number"?{timestamp:he(w.entry.timestamp)}:{}}));else{L.entries=X.map((w)=>({key:w.entry.key,method:w.entry.method,...typeof w.entry.timestamp==="number"?{timestamp:he(w.entry.timestamp)}:{},status:w.entry.status,url:w.entry.url,ct:w.entry.ct,size:w.entry.size,shape:w.shape,...w.entry.body_truncated?{body_truncated:!0}:{}}));L.detail_hint='Run "browser network --detail <key>" for full body.'}console.log(JSON.stringify(L,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 h=`import { cli, Strategy } from '@jackwener/opencli/registry';
|
|
97
99
|
|
|
98
100
|
cli({
|
|
99
101
|
site: '${o}',
|
|
@@ -115,18 +117,18 @@ cli({
|
|
|
115
117
|
return [];
|
|
116
118
|
},
|
|
117
119
|
});
|
|
118
|
-
`;s.mkdirSync(d,{recursive:!0});s.writeFileSync(u,
|
|
119
|
-
`);console.log(` Loading: ${
|
|
120
|
-
`);const H=
|
|
121
|
-
✗ Adapter failed. Fix the code and try again.`);process.exitCode=f.GENERIC_ERROR;return}console.log(` Executing: ppcli ${r} ${n} ${
|
|
122
|
-
`);let
|
|
123
|
-
→ ${
|
|
124
|
-
✗ Adapter output violates row shape conventions:`);for(const
|
|
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(
|
|
126
|
-
Fixture already exists at ${
|
|
127
|
-
${
|
|
128
|
-
✓ Adapter runs. (No fixture at ${
|
|
129
|
-
✓ Adapter matches fixture (${
|
|
130
|
-
✗ Adapter output does not match fixture:`);for(const
|
|
120
|
+
`;s.mkdirSync(d,{recursive:!0});s.writeFileSync(u,h,"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:p,validateRowShape:h,fixturePath:v,expandFixtureArgs:E,parseSeedArgs:I}=await import("./browser/verify-fixture.js"),D=N.join(c||N.join(fe.homedir(),".ppcli","clis"),r,`${n}.js`),P=k.existsSync(D)||!a?D:N.join(a,r,`${n}.js`);if(!k.existsSync(P)){console.error(`Adapter not found: ${P}`);console.error(`Run "ppcli browser init ${e}" to create it.`);process.exitCode=f.GENERIC_ERROR;return}console.log(`\uD83D\uDD0D Verifying ${e}...
|
|
121
|
+
`);console.log(` Loading: ${P}`);let U=t.fixture!==!1?l(r,n):null;const L=k.readFileSync(P,"utf-8"),re=/['"]limit['"]/.test(L),w=I(t.seedArgs),_=U?.args??w,y=E(_);if(_===void 0&&y.length===0&&re)y.push("--limit","3");const b=t.trace&&t.trace!=="off"?["--trace",t.trace]:[],M=[...y,...b].join(" "),G=resolveBrowserVerifyInvocation(),se=[...G.args,r,n,...y,...b,"--format","json"];let W;try{W=s(G.binary,se,{cwd:G.cwd,timeout:30000,encoding:"utf-8",env:process.env,stdio:["pipe","pipe","pipe"],...G.shell?{shell:!0}:{}})}catch(J){console.log(` Executing: ppcli ${r} ${n} ${M}
|
|
122
|
+
`);const H=J;if(H.stdout)console.log(String(H.stdout));if(H.stderr)console.error(String(H.stderr).slice(0,500));console.log(`
|
|
123
|
+
✗ Adapter failed. Fix the code and try again.`);process.exitCode=f.GENERIC_ERROR;return}console.log(` Executing: ppcli ${r} ${n} ${M}
|
|
124
|
+
`);let z;try{z=normalizeVerifyRows(JSON.parse(W))}catch{console.log(W);console.log("\n ✗ Could not parse adapter output as JSON. Is `--format json` broken?");process.exitCode=f.GENERIC_ERROR;return}console.log(renderVerifyPreview(z));console.log(`
|
|
125
|
+
→ ${z.length} row${z.length===1?"":"s"}`);const ie=h(z);if(ie.length>0){console.log(`
|
|
126
|
+
✗ Adapter output violates row shape conventions:`);for(const J of ie.slice(0,20)){const H=J.rowIndex!==void 0?`row[${J.rowIndex}] `:"";console.log(` - [${J.rule}] ${H}${J.detail}`)}if(ie.length>20)console.log(` ... and ${ie.length-20} more failure(s)`);console.log(`
|
|
127
|
+
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(U&&!t.updateFixture){console.log(`
|
|
128
|
+
Fixture already exists at ${v(r,n)}.`);console.log(" Use --update-fixture to overwrite.")}else{const H=u(z,_!==void 0?_:re?{limit:3}:void 0),so=d(r,n,H);console.log(`
|
|
129
|
+
${U?"↻ Updated":"✎ Wrote"} fixture: ${so}`);console.log(" Review and hand-tune the derived expectations (add patterns / notEmpty, tighten rowCount).");U=H}if(!U){console.log(`
|
|
130
|
+
✓ Adapter runs. (No fixture at ${v(r,n)} — consider --write-fixture to seed one.)`);const J=checkSiteMemory(r);printSiteMemoryReport(J,t.strictMemory);if(!J.ok&&t.strictMemory)process.exitCode=f.GENERIC_ERROR;return}const pe=p(z,U);if(pe.length===0){console.log(`
|
|
131
|
+
✓ Adapter matches fixture (${v(r,n)}).`);const J=checkSiteMemory(r);printSiteMemoryReport(J,t.strictMemory);if(!J.ok&&t.strictMemory)process.exitCode=f.GENERIC_ERROR;return}console.log(`
|
|
132
|
+
✗ Adapter output does not match fixture:`);for(const J of pe.slice(0,20)){const H=J.rowIndex!==void 0?`row[${J.rowIndex}] `:"";console.log(` - [${J.rule}] ${H}${J.detail}`)}if(pe.length>20)console.log(` ... and ${pe.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)=>{vr(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)=>{po(e)});const ne=i.command("plugin").description("Manage ppcli plugins"),Kt=ne.description();ne.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}});ne.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}});ne.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}});ne.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"){Ce(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(", ")})`:"",p=s.source?` ← ${s.source}`:"";console.log(` ${s.name}${l}${d}${u}${p}`)}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}`:"",p=d.description?` — ${d.description}`:"",h=d.commands.length>0?` (${d.commands.join(", ")})`:"";console.log(` ${d.name}${u}${p}${h}`)}}console.log();console.log(` ${o.length} plugin(s) installed`);console.log()});ne.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 xe=i.command("adapter").description("Manage CLI adapters"),Zt=xe.description();xe.command("status").description("Show which sites have local overrides vs using official baseline").action(async()=>{const e=await import("node:os"),t=N.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
133
|
`);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.")}});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}:{}}}
|
|
134
|
+
Official baseline: ${s.length} sites in package`)}catch{console.log("No local adapter overrides. All sites use the official baseline.")}});xe.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=N.join(t.homedir(),".ppcli","clis"),r=N.join(a,e),n=N.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.")});xe.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=N.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(N.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=N.join(r,e);try{await k.promises.access(n)}catch{console.error(`Site "${e}" has no local override.`);return}const s=k.existsSync(N.join(a,e));k.rmSync(n,{recursive:!0,force:!0});console.log(s?`✅ Reset "${e}". Now using official baseline.`:`✅ Removed custom site "${e}".`)});const B=i.command("profile").description("Manage Browser Bridge Chrome profiles"),Yt=B.description();B.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 Xo(),o=Ko(),r=t?.profiles??[],n=!!t&&!ar(t,$e)&&Array.isArray(t.profiles),s=await Promise.all(ze().map(async({name:u,entry:p})=>({name:u,port:p.port,userDataDir:p.userDataDir,running:await tr(p),isDefault:o.defaultContextId===u,createdAt:p.createdAt??"",label:p.label??"",proxy:p.proxy?{scheme:p.proxy.scheme,host:p.proxy.host,port:p.proxy.port,hasAuth:!!p.proxy.username,username:p.proxy.username??""}:null,fingerprint:p.fingerprint?.enabled?{enabled:!0,timezone:p.fingerprint.timezone??"",locale:p.fingerprint.locale??"",hardwareConcurrency:p.fingerprint.hardwareConcurrency??0,deviceMemory:p.fingerprint.deviceMemory??0,screen:p.fingerprint.screen??null,webglVendor:p.fingerprint.webglVendor??"",webglRenderer:p.fingerprint.webglRenderer??"",canvasNoise:p.fingerprint.canvasNoise===!0}:{enabled:!1},webrtc:p.webrtc!==!1,clean:p.clean!==!1})));if(e.format==="json"){const u=n?r.map((p)=>({contextId:p.contextId,alias:Nt(o,p.contextId)??"",connected:!0,version:p.extensionVersion??"",isDefault:o.defaultContextId===p.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 p=u.isDefault?" default":"";console.log(` ${u.name}${p} — ${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 ${ir(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 p=Nt(o,u.contextId),h=o.defaultContextId===u.contextId?" default":"",v=p?` ${p}`:"",E=u.extensionVersion?` v${u.extensionVersion}`:" version unknown";console.log(` ${u.contextId}${v}${h} — connected${E}`)}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[p,h]of d){u.add(h);console.log(` ${h} ${p} — not connected`)}if(o.defaultContextId&&!u.has(o.defaultContextId)&&!l.has(o.defaultContextId))console.log(` ${o.defaultContextId} — default, not connected`)}});const at=(e)=>{if(e.config){const r=JSON.parse(e.config);if(typeof r.proxy==="string")r.proxy=He(r.proxy);return r}const t={};if(e.label)t.label=e.label;if(e.proxy)t.proxy=He(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},ct=(e)=>e?{scheme:e.scheme,host:e.host,port:e.port,hasAuth:!!e.username,username:e.username??""}:null,lt=(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},dt=(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");B.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=at(t),{opts:r}=await At({...o,browserPath:t.browserPath}),n=await er(e,{...r,browserPath:t.browserPath});if(t.start!==!1)await We(e,n);if(t.format==="json"){console.log(JSON.stringify({ok:!0,name:e,port:n.port,userDataDir:n.userDataDir,label:n.label??"",proxy:ct(n.proxy),fingerprint:lt(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}});dt(B.commands[B.commands.length-1]);B.command("start").description("Launch the dedicated Chrome instance of a managed profile").argument("<name>","Managed profile name").action(async(e)=>{try{const t=ze().find((r)=>r.name===e.trim());if(!t)throw Error(`托管 profile "${e}" 不存在,先 ppcli profile create ${e}`);const o=await We(t.name,t.entry);console.log(`✅ profile "${e}" 运行中(${o})`)}catch(t){console.error(`Error: ${j(t)}`);process.exitCode=f.USAGE_ERROR}});B.command("stop").description("Gracefully close the dedicated Chrome instance of a managed profile").argument("<name>","Managed profile name").action(async(e)=>{try{const t=ze().find((r)=>r.name===e.trim());if(!t)throw Error(`托管 profile "${e}" 不存在`);const o=await rr(t.entry);console.log(o?`✅ profile "${e}" 已关闭`:`profile "${e}" 本来就没在运行`)}catch(t){console.error(`Error: ${j(t)}`);process.exitCode=f.USAGE_ERROR}});B.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 or(e,{keepData:t.keepData===!0});console.log(`✅ 托管 profile "${e}" 已删除${t.keepData?"(保留数据目录)":"(含登录数据)"}`)}catch(o){console.error(`Error: ${j(o)}`);process.exitCode=f.USAGE_ERROR}});B.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=at(t),{opts:r}=await At(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 nr(e,n);if(t.restart&&l)await We(e,s);if(t.format==="json"){console.log(JSON.stringify({ok:!0,name:e,label:s.label??"",proxy:ct(s.proxy),fingerprint:lt(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}});dt(B.commands[B.commands.length-1]);B.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=He(e),r=await sr(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}});B.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{Zo(e,t);console.log(`Profile ${e} is now aliased as ${t}.`)}catch(o){console.error(`Error: ${j(o)}`);process.exitCode=f.USAGE_ERROR}});B.command("use").description("Set the default Browser Bridge profile for future commands").argument("<profile>","Profile alias or contextId").action((e)=>{try{const t=Qo(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"),Qt=me.description();me.command("status").description("Show daemon status").option("--json","Machine-readable status (includes bridgeReady)").action(async(e)=>{await zo(e)});me.command("stop").description("Stop the daemon").action(async()=>{await Wo()});me.command("restart").description("Restart the daemon").action(async()=>{await Lo()});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 Ho(e.url)});const ve=Be(),Ue=i.command("external").description("Manage external CLI passthrough commands");Ue.command("install").description("Install an external CLI").argument("<name>","Name of the external CLI").action((e)=>{const t=ve.find((o)=>o.name===e);if(!t){console.error(`External CLI '${e}' not found in registry.`);process.exitCode=f.USAGE_ERROR;return}go(t)});Ue.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)=>{ho(e,{binary:t.binary,install:t.install,description:t.desc})});Ue.command("list").description("List registered external CLIs").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((e)=>{const t=Be().map((o)=>({name:o.name,package:o.package??"",binary:o.binary,installed:Fe(o.binary),description:o.description??"",homepage:o.homepage??"",tags:o.tags?.join(", ")??""}));Ce(t,{fmt:e.format,columns:["name","package","binary","installed","description","homepage","tags"],title:"ppcli/external/list",source:"ppcli external list"})});function eo(e,t){const o=t??(()=>{const r=process.argv.indexOf(e);return process.argv.slice(r+1)})();try{fo(e,o,ve)}catch(r){if(r instanceof Le){process.stderr.write(co.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 ve){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)=>eo(e.name,t))}const ut=i.command("antigravity").description("antigravity commands");ut.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?Wt(e.timeout,"--timeout",120):void 0})});const mt=new Map;mt.set("antigravity",ut);const pt=bo(i,mt);Cr(i);const to=ve.map((e)=>e.name),oo=ve.map((e)=>({name:e.name,label:St(e)})),De=new Map;for(const[,e]of Re())if(!De.has(e.site))De.set(e.site,e.domain);const ft=[],gt=[];for(const e of pt)if(xt(De.get(e))==="app")ft.push(e);else gt.push(e);const ht={external:oo,apps:ft,sites:gt},ro=new Set([...to,...pt]);ge(g,{globalCommand:i,description:A});ge(x,{globalCommand:i,description:"Inspect website login status"});ge(me,{globalCommand:i,description:Qt});ge(ne,{globalCommand:i,description:Kt});ge(xe,{globalCommand:i,description:Zt});ge(B,{globalCommand:i,description:Yt});i.configureHelp({visibleCommands:(e)=>e.commands.filter((t)=>e!==i||!ro.has(t.name()))});const no=(e)=>{const t=[];let o=e.parent;while(o){const r=vo(o);t.unshift(r?`${o.name()} ${r}`:o.name());o=o.parent}return[...t,e.name(),e.usage()].filter(Boolean).join(" ").trim()};function wt(e){e.configureHelp({commandUsage:no});for(const t of e.commands)wt(t)}wt(g);xo(i,()=>Ro(i,ht),()=>So(ht));i.on("command:*",(e)=>{const t=e[0];console.error(`error: unknown command '${t}'`);if(Fe(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,m=a.readFile??((R)=>k.readFileSync(R,"utf-8")),x=a.projectRoot??findPackageRoot(qe,i);for(const R of lo(x,m))if(i(R))return{binary:process.execPath,args:[R],cwd:x};const g=N.join(x,"src","main.ts");if(!i(g))throw Error(`Could not find ppcli entrypoint under ${x}. Expected built entry from package.json or src/main.ts.`);const A=N.join(x,"node_modules",".bin",c==="win32"?"tsx.cmd":"tsx");if(i(A))return{binary:A,args:[g],cwd:x,...c==="win32"?{shell:!0}:{}};return{binary:c==="win32"?"npx.cmd":"npx",args:["tsx",g],cwd:x,...c==="win32"?{shell:!0}:{}}}
|