@buygent/cli 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js
CHANGED
|
@@ -325,4 +325,4 @@ return JSON.stringify({ restoredNames: ${JSON.stringify($.filter((X)=>!X.httpOnl
|
|
|
325
325
|
`)){let{value:Y,done:Q}=await $.read();if(Q)break;X+=J.decode(Y,{stream:!0})}}finally{$.releaseLock()}return X.split(/\r?\n/)[0]??""},N70=($)=>{let J=$.trim().toLowerCase();return J==="y"||J==="yes"},RT=($)=>({...$,...typeof $.payPassword==="string"?{payPassword:"[redacted]"}:{}}),xn0=($,J)=>{let X=J.quantity===void 0?void 0:Number.parseInt(String(J.quantity),10);if(X!==void 0&&(!Number.isInteger(X)||X<=0))throw Error("--quantity must be a positive integer");let Y=J.maxPriceUsd===void 0?void 0:Number.parseFloat(String(J.maxPriceUsd));if(Y!==void 0&&(!Number.isFinite(Y)||Y<=0))throw Error("--max-price-usd must be a positive number");let Q=J.itemId??J.productId,G=J.maxPriceKrw===void 0?void 0:Number.parseInt(String(J.maxPriceKrw),10);if(G!==void 0&&(!Number.isInteger(G)||G<=0))throw Error("--max-price-krw must be a positive integer");if(!Q&&!J.url&&!J.query)throw Error("Provide one of --item-id, --url, or --query (or <productId>)");return{platform:$,...Q?{itemId:String(Q)}:{},...J.url?{url:String(J.url)}:{},...J.query?{query:String(J.query)}:{},...X!==void 0?{quantity:X}:{},...J.variant?{variant:String(J.variant)}:{},...Y!==void 0?{maxPriceUsdCents:Math.round(Y*100)}:{},...G!==void 0?{maxPriceKrw:G}:{},...J.payPassword?{payPassword:String(J.payPassword)}:{},...J.dryRun!==void 0?{dryRun:J.dryRun}:{},...J.confirm?{confirmToken:String(J.confirm)}:{},...J.shippingAddress?{shippingAddress:D70(J.shippingAddress,"--shipping-address")}:{},...J.accountId?{accountId:String(J.accountId)}:{},...J.metadata?{metadata:D70(J.metadata,"--metadata")}:{}}},A70=($)=>{$.command("order <platform> [productId]").description("Create an external platform order after explicit y/n buyer approval").option("--item-id <itemId>","Platform item/listing id").option("--url <url>","Platform product URL").option("--query <query>","Natural-language order request").option("--quantity <count>","Quantity to order","1").option("--variant <variant>","Variant or option selector").option("--max-price-usd <usd>","Maximum approved item/order price in USD").option("--max-price-krw <amount>","Maximum approved price in KRW").option("--pay-password <digits>","Coupang Pay 6-digit password for live Coupang orders").option("--confirm <token>","Order confirmation token").option("--shipping-address <json>","Shipping address JSON object").option("--account-id <platformAccountId>","Connected platform account id").option("--metadata <json>","Optional JSON metadata for the order").option("-y, --yes","Approve without prompting").option("--dry-run","Print the payload without sending it").option("--no-dry-run","Send the order request").action(async(J,X,Y)=>{let Q=X$(),G=String(J).toLowerCase(),K=xn0(String(J),{...Y,...X?{productId:String(X)}:{}});if(Y.dryRun){console.log(JSON.stringify({approved:!1,request:RT(K)},null,2));return}if(G==="coupang"){let H=o40();if(!H)throw Error("Coupang is not connected locally. Run: buygent connect coupang");if(typeof K.url!=="string"||!K.url)throw Error("Coupang live orders require --url <product-url>");if(typeof K.payPassword!=="string"||!K.payPassword)throw Error("Coupang live orders require --pay-password <digits>");if(!Y.yes){process.stderr.write(`Approve order on ${String(J)}? ${JSON.stringify(RT(K),null,2)}
|
|
326
326
|
[y/N] `);let V=await F70();if(!N70(V)){console.log(JSON.stringify({ok:!1,cancelled:!0},null,2));return}}let Z=await n4(Q,"/executions/reserve",{capability:"coupang.order",executionPlane:"local_executor",reservedUsdCents:kn0,request:{platform:G,productUrl:K.url,...K.maxPriceKrw?{maxPriceKrw:K.maxPriceKrw}:{}},metadata:{platform:G}});try{let V=await d40({credential:H,productUrl:K.url,payPassword:K.payPassword,...typeof K.maxPriceKrw==="number"?{maxPriceKrw:K.maxPriceKrw}:{}}),z=await n4(Q,`/executions/${encodeURIComponent(Z.reservationId)}/commit`,{committedUsdCents:Z.reservedUsdCents,providerReference:V.orderNumber,result:{platform:G,...V},metadata:{platform:G},order:{adapterId:"coupang-live",listingId:"product-url",durationMin:60,platformFeeUsdCents:0,resourceClass:"service-access",requestSnapshot:{platform:G,productUrl:K.url,...typeof K.maxPriceKrw==="number"?{maxPriceKrw:K.maxPriceKrw}:{}},credential:{kind:"opaque",fields:{capability:"commerce-order",provider:"coupang",productId:K.url,productTitle:V.productTitle,finalUrl:V.finalUrl,orderNumber:V.orderNumber??"",totalKrw:V.totalKrw,totalUsdCents:V.totalUsdCents,demo:!1}},revoke:{kind:"coupang-local-order",fields:{reservationId:Z.reservationId,platform:G}},metadata:{platform:G,productTitle:V.productTitle,finalUrl:V.finalUrl,orderNumber:V.orderNumber,totalKrw:V.totalKrw,totalUsdCents:V.totalUsdCents,demo:!1}}});console.log(JSON.stringify({ok:!0,platform:G,reservationId:Z.reservationId,localResult:V,settlement:z},null,2));return}catch(V){throw await n4(Q,`/executions/${encodeURIComponent(Z.reservationId)}/cancel`,{failureCode:"local_execution_failed",failureMessage:V instanceof Error?V.message:"Local Coupang execution failed",metadata:{platform:G}}).catch(()=>{return}),V}}if(!Y.yes){process.stderr.write(`Approve order on ${String(J)}? ${JSON.stringify(RT(K),null,2)}
|
|
327
327
|
[y/N] `);let H=await F70();if(!N70(H)){console.log(JSON.stringify({ok:!1,cancelled:!0},null,2));return}}let W=await n4(Q,`/platforms/${encodeURIComponent(String(J))}/orders`,{...K,approved:!0});console.log(JSON.stringify(W,null,2))})};var jT=($,J,X)=>{if(X!==void 0&&X!==null&&String(X).trim().length>0)$.set(J,String(X))},yn0=($={})=>{let J=new URLSearchParams;jT(J,"platform",$.platform),jT(J,"status",$.status),jT(J,"adapterId",$.adapterId);let X=J.toString();return X?`/platforms?${X}`:"/platforms"},M70=($)=>{$.command("platforms").description("List connected external commerce platforms").option("--platform <platform>","Filter by platform").option("--status <status>","Filter by connection status").option("--adapter-id <adapterId>","Filter by Buygent adapter id").action(async(J)=>{let X=X$(),Y=await j9(X,yn0(J));console.log(JSON.stringify(Y,null,2))})};import{existsSync as bn0,mkdirSync as vn0,readFileSync as hn0,writeFileSync as fn0}from"node:fs";import{homedir as gn0}from"node:os";import{dirname as un0,join as mn0}from"node:path";var j70=($)=>Boolean($)&&typeof $==="object"&&!Array.isArray($),P70=($=process.env)=>$.BUYGENT_PROFILE_PATH??mn0($.HOME??gn0(),".buygent","profile.json"),KX=($)=>typeof $==="string"&&$.trim().length>0?$.trim():void 0,cn0=($,J)=>{if($===void 0||$===null||$==="")return;let X=typeof $==="number"?$:Number.parseInt(String($),10);if(!Number.isInteger(X)||X<0)throw Error(`${J} must be a non-negative integer`);return X},ln0=($)=>{if($===void 0||$===null||$==="")return;let J=typeof $==="number"?$:Number.parseFloat(String($));if(!Number.isFinite(J)||J<0)throw Error("--budget-per-order-usd must be a non-negative number");return Math.round(J*100)},I70=($,J="defaultAddress")=>{if($===void 0||$===null)return;if(!j70($))throw Error(`${J} must be an object`);let X=KX($.street)??"",Y=KX($.city)??"",Q=KX($.zipCode)??"",G=KX($.note);if(!X||!Y||!Q)throw Error(`${J} requires street, city, and zipCode`);return{street:X,city:Y,zipCode:Q,...G?{note:G}:{}}},T70=($,J="profile")=>{if($===void 0||$===null)return{};if(!j70($))throw Error(`${J} must be an object`);let X=KX($.defaultPhone),Y=KX($.defaultPaymentMethodId),Q=cn0($.budgetPerOrderUsdCents,`${J}.budgetPerOrderUsdCents`),G=(()=>{if($.preferCredits===void 0)return;if(typeof $.preferCredits!=="boolean")throw Error(`${J}.preferCredits must be a boolean`);return $.preferCredits})();return{...$.defaultAddress!==void 0?{defaultAddress:I70($.defaultAddress,`${J}.defaultAddress`)}:{},...X?{defaultPhone:X}:{},...Y?{defaultPaymentMethodId:Y}:{},...Q!==void 0?{budgetPerOrderUsdCents:Q}:{},...G!==void 0?{preferCredits:G}:{}}},E70=($=process.env)=>{let J=P70($);if(!bn0(J))return{};return T70(JSON.parse(hn0(J,"utf8")),"profile")},dn0=($,J=process.env)=>{let X=T70($,"profile"),Y=P70(J);return vn0(un0(Y),{recursive:!0}),fn0(Y,`${JSON.stringify(X,null,2)}
|
|
328
|
-
`,"utf8"),X},pn0=($)=>$.defaultAddressStreet!==void 0||$.defaultAddressCity!==void 0||$.defaultAddressZip!==void 0||$.defaultAddressNote!==void 0,in0=($,J={})=>{let X={};if(pn0($))X.defaultAddress=I70({...J.defaultAddress??{},...$.defaultAddressStreet!==void 0?{street:String($.defaultAddressStreet)}:{},...$.defaultAddressCity!==void 0?{city:String($.defaultAddressCity)}:{},...$.defaultAddressZip!==void 0?{zipCode:String($.defaultAddressZip)}:{},...$.defaultAddressNote!==void 0?{note:String($.defaultAddressNote)}:{}},"defaultAddress");let Y=KX($.defaultPhone);if(Y)X.defaultPhone=Y;let Q=KX($.defaultPaymentMethodId);if(Q)X.defaultPaymentMethodId=Q;let G=ln0($.budgetPerOrderUsd);if(G!==void 0)X.budgetPerOrderUsdCents=G;if(typeof $.preferCredits==="boolean")X.preferCredits=$.preferCredits;return X},R70=($)=>{console.log(JSON.stringify($,null,2))},w70=($)=>{let J=$.command("profile").description("Manage the local Buygent buyer profile");J.command("get").description("Print the local buyer profile JSON").action(()=>{R70(E70())}),J.command("set").description("Set local buyer profile defaults used by CLI and MCP").option("--default-address-street <street>").option("--default-address-city <city>").option("--default-address-zip <zipCode>").option("--default-address-note <note>").option("--default-phone <phone>").option("--default-payment-method-id <paymentMethodId>").option("--prefer-credits","Default orders to Buygent credits").option("--budget-per-order-usd <usd>").action((X)=>{let Y=E70(),Q=dn0({...Y,...in0(X,Y)});R70(Q)})};var vY=($,J,X)=>{if(X!==void 0&&X!==null&&String(X).trim().length>0)$.set(J,String(X))},nn0=($,J,X={})=>{let Y=new URLSearchParams;return vY(Y,"query",J),vY(Y,"limit",X.limit),vY(Y,"cursor",X.cursor),vY(Y,"category",X.category),vY(Y,"sort",X.sort),vY(Y,"accountId",X.accountId),vY(Y,"filters",X.filters),`/platforms/${encodeURIComponent($)}/search?${Y.toString()}`},S70=($)=>{$.command("search <platform> <query...>").description("Search an external commerce platform").option("--limit <count>","Maximum number of results to return").option("--cursor <cursor>","Pagination cursor from a previous search response").option("--category <category>","Platform category filter").option("--sort <sort>","Platform sort mode").option("--account-id <platformAccountId>","Connected platform account id to search with").option("--filters <json>","Platform-specific filters encoded as JSON").action(async(J,X,Y)=>{let Q=X.join(" ").trim();if(!Q)throw Error("Search query is required");let G=X$(),K=await j9(G,nn0(String(J),Q,Y));console.log(JSON.stringify(K,null,2))})};var IH=($,J,X)=>{if(X!==void 0&&X!==null&&String(X).trim().length>0)$.set(J,String(X))},on0=($,J,X={})=>{if(!J&&X.orderId&&!X.carrier&&!X.accountId&&!X.platformReference)return`/platforms/${encodeURIComponent($)}/orders/${encodeURIComponent(String(X.orderId))}`;let Y=new URLSearchParams;IH(Y,"trackingRef",J),IH(Y,"orderId",X.orderId),IH(Y,"carrier",X.carrier),IH(Y,"accountId",X.accountId),IH(Y,"platformReference",X.platformReference);let Q=Y.toString();if(!Q)throw Error("Provide a tracking reference or --order-id");return`/platforms/${encodeURIComponent($)}/track?${Q}`},C70=($)=>{$.command("track <platform> [trackingRef]").description("Track shipping or delivery status for a platform order").option("--order-id <orderId>","Buygent order id").option("--carrier <carrier>","Carrier name or code").option("--account-id <platformAccountId>","Connected platform account id").option("--platform-reference <reference>","Platform order/reference id").action(async(J,X,Y)=>{let Q=X$(),G=await j9(Q,on0(String(J),X?String(X):void 0,Y));console.log(JSON.stringify(G,null,2))})};var _70=($)=>($/100).toFixed(2);import{existsSync as x70,readFileSync as sn0}from"node:fs";import{dirname as k70,join as y70}from"node:path";import{fileURLToPath as an0}from"node:url";var rn0="0.0.0-dev",b70="0.3.2",tn0=()=>b70!=="0.3.2",en0=($)=>{let J=y70($,"package.json");if(!x70(J))return;return JSON.parse(sn0(J,"utf8"))},$o0=($=import.meta.url)=>{let J=k70(an0($));while(!0){if(x70(y70(J,"package.json")))return J;let X=k70(J);if(X===J)return J;J=X}},v70=($=import.meta.url)=>{let J=en0($o0($));if(typeof J?.version==="string"&&J.version.trim().length>0)return J.version;return tn0()?b70:rn0};var z6=new pT,h70=($)=>{let[J,X]=$.split("/");if(!J||!X)throw Error(`Invalid resource reference: ${$}. Use adapterId/listingId.`);return{adapterId:J,listingId:X}},Jo0=($)=>{if($.length<=8)return"[redacted]";return`${$.startsWith("bg_live_")?"bg_live_":$.slice(0,3)}...${$.slice(-4)}`},Xo0=($)=>({...$,...$.agentKey?{agentKey:Jo0($.agentKey)}:{}}),d1=($)=>{console.log(JSON.stringify($,null,2))},Yo0=($)=>{if(!$||typeof $!=="object")return 0;let J=$;if(typeof J.availableCents==="number")return J.availableCents;let X=J.balance;if(X&&typeof X==="object"&&typeof X.availableCents==="number")return X.availableCents;return 0},f70=($)=>{let J=Yo0($);console.log(`Balance: $${_70(J)} (${J}\xA2)`)},Qo0=($)=>{if($==="external")return $;throw Error(`Invalid signer mode: ${$}. Use external.`)},g70=($)=>{if(!$.agentKey)throw Error(AZ)};z6.name("buygent").description("Buygent CLI").version(v70(import.meta.url));z6.command("health").description("Print CLI scaffold readiness").action(()=>{console.log("buygent cli ready")});a40(z6);F90(z6);$70(z6);S70(z6);A70(z6);M70(z6);C70(z6);w70(z6);W70(z6);U70(z6);z6.command("mcp").description("Run the Buygent MCP stdio server").option("--serve","Start the stdio MCP server").action(async($)=>{if(!$.serve)throw Error("Use: buygent mcp --serve");await Qv()});var Go0=z6.command("config").description("Manage local CLI configuration"),TH=z6.command("auth").description("Manage buyer and worker sign-in"),Ko0=z6.command("bounty").description("Create and inspect buyer human bounties"),Wo0=z6.command("credits").description("Manage buyer prepaid credits");Go0.command("set").option("--wallet-address <address>").option("--signer-mode <mode>","external",Qo0).option("--signer-endpoint <url>").option("--session-id <sessionId>").option("--account-email <email>").option("--account-role <role>").option("--api-url <url>").option("--agent-key <key>").option("--soft-limit <usd>").option("--hard-limit <usd>").action(($)=>{let J=ET({walletAddress:$.walletAddress,signerMode:$.signerMode,signerEndpoint:$.signerEndpoint,sessionId:$.sessionId,accountEmail:$.accountEmail,accountRole:$.accountRole==="buyer"||$.accountRole==="worker"?$.accountRole:void 0,apiUrl:$.apiUrl,agentKey:$.agentKey,softLimitUsd:$.softLimit!==void 0?Number.parseFloat(String($.softLimit)):void 0,hardLimitUsd:$.hardLimit!==void 0?Number.parseFloat(String($.hardLimit)):void 0});d1(Xo0(J))});TH.command("request-code").requiredOption("--email <email>").option("--role <role>","buyer or worker","buyer").option("--debug","Expose debug auth code when the server supports it").action(async($)=>{let J=_1(),X=FZ(J);if(!X)throw Error("Missing apiUrl. Run: buygent config set --api-url <url> or set BUYGENT_API_URL");let Y=String($.role)==="worker"?"worker":"buyer",Q=await fetch(`${X}/auth/email/request-code`,{method:"POST",headers:{"Content-Type":"application/json",...$.debug?{"x-buygent-debug-auth":"true"}:{},...J.agentKey?{Authorization:`Bearer ${J.agentKey}`}:{},...J.sessionId?{Cookie:`buygent_session=${encodeURIComponent(J.sessionId)}`}:{}},body:JSON.stringify({email:String($.email),role:Y})});if(!Q.ok)throw Error(await Q.text());d1(await Q.json())});TH.command("verify").requiredOption("--email <email>").requiredOption("--code <code>").option("--role <role>","buyer or worker","buyer").action(async($)=>{let J=_1(),X=FZ(J);if(!X)throw Error("Missing apiUrl. Run: buygent config set --api-url <url> or set BUYGENT_API_URL");let Y=String($.role)==="worker"?"worker":"buyer",Q=await fetch(`${X}/auth/email/verify`,{method:"POST",headers:{"Content-Type":"application/json",...J.agentKey?{Authorization:`Bearer ${J.agentKey}`}:{}},body:JSON.stringify({email:String($.email),role:Y,code:String($.code)})});if(!Q.ok)throw Error(await Q.text());let G=await Q.json(),K=ET({sessionId:G.sessionId,accountEmail:G.user.email,accountRole:G.user.role});d1({ok:!0,sessionId:G.sessionId,accountEmail:K.accountEmail,accountRole:K.accountRole,expiresAt:G.expiresAt})});TH.command("device-code").action(async()=>{await qv(_1())});TH.command("whoami").action(async()=>{let $=_1();d1(await F8($,"/auth/session"))});TH.command("logout").action(async()=>{let $=_1();await N8($,"/auth/logout",{});let J={...$};delete J.agentKey,delete J.sessionId,delete J.accountEmail,delete J.accountRole,MT(J),d1({ok:!0})});var u70=z6.command("catalog").description("Browse provider listings");u70.command("list").option("--type <type>").action(async($)=>{let J=_1(),X=$.type?`?type=${encodeURIComponent(String($.type))}`:"";d1(await F8(J,`/catalog${X}`))});u70.command("show <resource>").action(async($)=>{let J=_1(),{adapterId:X,listingId:Y}=h70($);d1(await F8(J,`/catalog/${X}/${Y}`))});var PT=($,J)=>[...J,$];Ko0.command("create").requiredOption("--intent <intent>").requiredOption("--market <market>").requiredOption("--specialty <specialty>").requiredOption("--deliverable <deliverable>").requiredOption("--duration <minutes>").option("--language <language>").option("--execution-mode <executionMode>").option("--credential <credential>","repeat for multiple credentials",PT,[]).option("--jurisdiction <jurisdiction>","repeat for multiple jurisdictions",PT,[]).option("--sla-min <minutes>").option("--wallet-address <address>").option("--output <mode>","summary, json, or url","summary").action(async($)=>{let J=_1();g70(J);let X=Number.parseInt(String($.duration),10),Y=Wv({intent:String($.intent),market:String($.market),durationMin:X,specialty:String($.specialty),deliverable:String($.deliverable),...$.language?{language:String($.language)}:{},...$.executionMode?{executionMode:String($.executionMode)}:{},...Array.isArray($.credential)&&$.credential.length>0?{credential:$.credential.map((H)=>String(H))}:{},...Array.isArray($.jurisdiction)&&$.jurisdiction.length>0?{jurisdiction:$.jurisdiction.map((H)=>String(H))}:{},...$.slaMin?{slaMin:Number.parseInt(String($.slaMin),10)}:{}}),Q=await MZ(J,{adapterId:"",listingId:"",durationMin:X,...$.walletAddress?{walletAddress:String($.walletAddress)}:{},request:Y}),G=Q.body??Q,K=G.credential&&typeof G.credential==="object"&&"fields"in G.credential&&G.credential.fields&&typeof G.credential.fields==="object"&&"taskId"in G.credential.fields&&typeof G.credential.fields.taskId==="string"?G.credential.fields.taskId:void 0,W=G.orderId&&typeof G.orderId==="string"&&J.apiUrl?`${J.apiUrl}/human-tasks/${G.orderId}`:void 0;if($.output==="json"){d1({...Q,taskId:K,taskStatusUrl:W});return}if($.output==="url"&&W){console.log(W);return}console.log(Hv({apiUrl:String(J.apiUrl),responseBody:G}))});Wo0.command("show").action(async()=>{let $=_1();g70($);let J=await F8($,"/credits");f70(J),d1(J)});z6.command("buy [resource]").option("--duration <minutes>").option("--billing <model>").option("--unit <unit>").option("--auto-renew").option("--interval-count <count>").option("--cancel-at-period-end").option("--type <type>").option("--resource-class <resourceClass>").option("--intent <intent>").option("--market <market>").option("--provider <provider>").option("--channel <channel>").option("--credential-kind <kind>").option("--specialty <specialty>").option("--jurisdiction <jurisdiction>").option("--credential <credential>").option("--execution-mode <executionMode>").option("--deliverable <deliverable>").option("--language <language>").option("--sla-min <minutes>").option("--task <task>").option("--environment <environment>").option("--gpu-type <type>").option("--gpu-count <count>").option("--public-endpoint").option("--output <mode>","json or key","json").action(async($,J)=>{let X=_1(),Y=J.task||J.environment||J.gpuType||J.gpuCount||J.publicEndpoint||J.provider||J.channel||J.credentialKind||J.specialty||J.jurisdiction||J.credential||J.executionMode||J.deliverable||J.language||J.slaMin?{...J.task?{task:String(J.task)}:{},...J.environment?{environment:String(J.environment)}:{},...J.gpuType?{gpuType:String(J.gpuType)}:{},...J.gpuCount?{gpuCount:Number.parseInt(String(J.gpuCount),10)}:{},...J.publicEndpoint?{publicEndpoint:!0}:{},...J.provider?{provider:String(J.provider)}:{},...J.channel?{channel:String(J.channel)}:{},...J.credentialKind?{credentialKind:String(J.credentialKind)}:{},...J.specialty?{specialty:String(J.specialty)}:{},...J.jurisdiction?{jurisdiction:String(J.jurisdiction)}:{},...J.credential?{credential:String(J.credential)}:{},...J.executionMode?{executionMode:String(J.executionMode)}:{},...J.deliverable?{deliverable:String(J.deliverable)}:{},...J.language?{language:String(J.language)}:{},...J.slaMin?{slaMin:Number.parseInt(String(J.slaMin),10)}:{}}:void 0,Q=await($?(()=>{let G=lN(J.duration);if(G===void 0)throw Error("--duration is required when buying a concrete resource listing");return MZ(X,{...h70($),durationMin:G,requirements:Y,billing:dN(J)?{model:String(J.billing??"lease"),unit:String(J.unit??"minute"),autoRenew:Boolean(J.autoRenew),...J.intervalCount?{intervalCount:Number.parseInt(String(J.intervalCount),10)}:{},...J.cancelAtPeriodEnd?{cancelAtPeriodEnd:!0}:{}}:void 0})})():(()=>{let G=Uv(J);return MZ(X,{adapterId:"",listingId:"",durationMin:G.durationMin,request:G.request})})());if(J.output==="key"){let G="body"in Q&&Q.body&&typeof Q.body==="object"?Q.body:Q,K=G.credential,W=K?.fields?.apiKeySecret??K?.fields?.secret??K?.fields?.token??JSON.stringify(G);console.log(W);return}d1(Q)});var m70=z6.command("orders").description("Inspect purchase orders");m70.command("list").action(async()=>{let $=_1();d1(await F8($,"/orders"))});m70.command("show <orderId>").action(async($)=>{let J=_1();d1(await F8(J,`/orders/${$}/status`))});var c70=z6.command("credentials").description("Inspect issued credentials"),l70=z6.command("compute").description("Use compute capabilities"),Ho0=z6.command("email").description("Use email capabilities"),Vo0=z6.command("sms").description("Use SMS capabilities"),d70=z6.command("human").description("Use human execution primitives");c70.command("list").action(async()=>{let $=_1();d1(await F8($,"/credentials"))});c70.command("show <orderId>").action(async($)=>{let J=_1();d1(await F8(J,`/credentials/${$}`))});Ho0.command("send").option("--order-id <orderId>").requiredOption("--to <email>").requiredOption("--subject <subject>").option("--text <text>").option("--html <html>").action(async($)=>{let J=_1();d1(await N8(J,"/actions/email/send",{to:String($.to),subject:String($.subject),...$.text?{text:String($.text)}:{},...$.html?{html:String($.html)}:{}}))});Vo0.command("send").option("--order-id <orderId>").requiredOption("--to <number>").requiredOption("--text <text>").option("--from <number>").action(async($)=>{let J=_1();d1(await N8(J,"/actions/sms/send",{to:String($.to),text:String($.text),...$.from?{from:String($.from)}:{}}))});var hY=d70.command("task").description("Use buyer-side human task primitives"),wH=d70.command("work").description("Use worker-side human task primitives");hY.command("show").requiredOption("--order-id <orderId>").action(async($)=>{let J=_1();d1(await F8(J,`/human-tasks/${encodeURIComponent(String($.orderId))}`))});hY.command("events").requiredOption("--task-id <taskId>").action(async($)=>{let J=_1();d1(await F8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/events`))});hY.command("applicants").requiredOption("--task-id <taskId>").action(async($)=>{let J=_1();d1(await F8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/applicants`))});hY.command("select").requiredOption("--task-id <taskId>").requiredOption("--human-profile-id <humanProfileId>").option("--selected-by <selectedBy>").action(async($)=>{let J=_1();d1(await N8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/select`,{humanProfileId:String($.humanProfileId),...$.selectedBy?{selectedBy:String($.selectedBy)}:{}}))});hY.command("message").requiredOption("--task-id <taskId>").requiredOption("--message <message>").option("--actor-id <actorId>").action(async($)=>{let J=_1();d1(await N8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/messages`,{actorType:"buyer",...$.actorId?{actorId:String($.actorId)}:{},message:String($.message)}))});hY.command("approve").requiredOption("--task-id <taskId>").option("--buyer-id <buyerId>").action(async($)=>{let J=_1();d1(await N8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/approve`,{...$.buyerId?{buyerId:String($.buyerId)}:{}}))});hY.command("reject").requiredOption("--task-id <taskId>").requiredOption("--reason <reason>").option("--buyer-id <buyerId>").option("--final","Mark as final rejection instead of revision requested").action(async($)=>{let J=_1();d1(await N8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/reject`,{reason:String($.reason),revisionRequested:!Boolean($.final),...$.buyerId?{buyerId:String($.buyerId)}:{}}))});wH.command("available").option("--human-profile-id <humanProfileId>").action(async($)=>{let J=_1(),X=$.humanProfileId?`?humanProfileId=${encodeURIComponent(String($.humanProfileId))}`:"";d1(await F8(J,`/human-work/available${X}`))});wH.command("apply").requiredOption("--task-id <taskId>").requiredOption("--human-profile-id <humanProfileId>").option("--note <note>").action(async($)=>{let J=_1();d1(await N8(J,`/human-work/${encodeURIComponent(String($.taskId))}/apply`,{humanProfileId:String($.humanProfileId),...$.note?{note:String($.note)}:{}}))});wH.command("start").requiredOption("--task-id <taskId>").requiredOption("--human-profile-id <humanProfileId>").action(async($)=>{let J=_1();d1(await N8(J,`/human-work/${encodeURIComponent(String($.taskId))}/start`,{humanProfileId:String($.humanProfileId)}))});wH.command("submit").requiredOption("--task-id <taskId>").requiredOption("--human-profile-id <humanProfileId>").requiredOption("--summary <summary>").option("--time-spent-min <minutes>").option("--artifact <artifact>","repeatable artifact values",PT,[]).action(async($)=>{let J=_1();d1(await N8(J,`/human-work/${encodeURIComponent(String($.taskId))}/submit`,{humanProfileId:String($.humanProfileId),summary:String($.summary),...Array.isArray($.artifact)&&$.artifact.length>0?{artifacts:$.artifact.map((X)=>({label:"artifact",value:String(X)}))}:{},...$.timeSpentMin?{timeSpentMin:Number.parseInt(String($.timeSpentMin),10)}:{}}))});wH.command("message").requiredOption("--task-id <taskId>").requiredOption("--human-profile-id <humanProfileId>").requiredOption("--message <message>").action(async($)=>{let J=_1();d1(await N8(J,`/human-work/${encodeURIComponent(String($.taskId))}/messages`,{humanProfileId:String($.humanProfileId),message:String($.message)}))});l70.command("exec").option("--order-id <orderId>").requiredOption("--command <command>").action(async($)=>{let J=_1();d1(await N8(J,"/actions/compute/exec",{command:String($.command)}))});var MO=l70.command("session").description("Manage mediated compute sessions");MO.command("open").option("--order-id <orderId>").action(async($)=>{let J=_1();d1(await N8(J,"/actions/compute/session",{}))});MO.command("send").requiredOption("--token <token>").requiredOption("--data <data>").action(async($)=>{let J=_1();d1(await fetch(`${J.apiUrl}/actions/compute/session/input`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${String($.token)}`},body:JSON.stringify({data:String($.data)})}).then(async(X)=>{if(!X.ok)throw Error(await X.text());return X.json()}))});MO.command("read").requiredOption("--token <token>").option("--cursor <cursor>").action(async($)=>{let J=_1(),X=$.cursor!==void 0?`?cursor=${encodeURIComponent(String($.cursor))}`:"";d1(await fetch(`${J.apiUrl}/actions/compute/session/output${X}`,{method:"GET",headers:{Authorization:`Bearer ${String($.token)}`}}).then(async(Y)=>{if(!Y.ok)throw Error(await Y.text());return Y.json()}))});MO.command("close").requiredOption("--token <token>").action(async($)=>{let J=_1();d1(await fetch(`${J.apiUrl}/actions/compute/session/close`,{method:"POST",headers:{Authorization:`Bearer ${String($.token)}`}}).then(async(X)=>{if(!X.ok)throw Error(await X.text());return X.json()}))});z6.command("spending").action(async()=>{let $=_1(),J=await F8($,"/credits");f70(J),d1(J)});z6.parseAsync().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});
|
|
328
|
+
`,"utf8"),X},pn0=($)=>$.defaultAddressStreet!==void 0||$.defaultAddressCity!==void 0||$.defaultAddressZip!==void 0||$.defaultAddressNote!==void 0,in0=($,J={})=>{let X={};if(pn0($))X.defaultAddress=I70({...J.defaultAddress??{},...$.defaultAddressStreet!==void 0?{street:String($.defaultAddressStreet)}:{},...$.defaultAddressCity!==void 0?{city:String($.defaultAddressCity)}:{},...$.defaultAddressZip!==void 0?{zipCode:String($.defaultAddressZip)}:{},...$.defaultAddressNote!==void 0?{note:String($.defaultAddressNote)}:{}},"defaultAddress");let Y=KX($.defaultPhone);if(Y)X.defaultPhone=Y;let Q=KX($.defaultPaymentMethodId);if(Q)X.defaultPaymentMethodId=Q;let G=ln0($.budgetPerOrderUsd);if(G!==void 0)X.budgetPerOrderUsdCents=G;if(typeof $.preferCredits==="boolean")X.preferCredits=$.preferCredits;return X},R70=($)=>{console.log(JSON.stringify($,null,2))},w70=($)=>{let J=$.command("profile").description("Manage the local Buygent buyer profile");J.command("get").description("Print the local buyer profile JSON").action(()=>{R70(E70())}),J.command("set").description("Set local buyer profile defaults used by CLI and MCP").option("--default-address-street <street>").option("--default-address-city <city>").option("--default-address-zip <zipCode>").option("--default-address-note <note>").option("--default-phone <phone>").option("--default-payment-method-id <paymentMethodId>").option("--prefer-credits","Default orders to Buygent credits").option("--budget-per-order-usd <usd>").action((X)=>{let Y=E70(),Q=dn0({...Y,...in0(X,Y)});R70(Q)})};var vY=($,J,X)=>{if(X!==void 0&&X!==null&&String(X).trim().length>0)$.set(J,String(X))},nn0=($,J,X={})=>{let Y=new URLSearchParams;return vY(Y,"query",J),vY(Y,"limit",X.limit),vY(Y,"cursor",X.cursor),vY(Y,"category",X.category),vY(Y,"sort",X.sort),vY(Y,"accountId",X.accountId),vY(Y,"filters",X.filters),`/platforms/${encodeURIComponent($)}/search?${Y.toString()}`},S70=($)=>{$.command("search <platform> <query...>").description("Search an external commerce platform").option("--limit <count>","Maximum number of results to return").option("--cursor <cursor>","Pagination cursor from a previous search response").option("--category <category>","Platform category filter").option("--sort <sort>","Platform sort mode").option("--account-id <platformAccountId>","Connected platform account id to search with").option("--filters <json>","Platform-specific filters encoded as JSON").action(async(J,X,Y)=>{let Q=X.join(" ").trim();if(!Q)throw Error("Search query is required");let G=X$(),K=await j9(G,nn0(String(J),Q,Y));console.log(JSON.stringify(K,null,2))})};var IH=($,J,X)=>{if(X!==void 0&&X!==null&&String(X).trim().length>0)$.set(J,String(X))},on0=($,J,X={})=>{if(!J&&X.orderId&&!X.carrier&&!X.accountId&&!X.platformReference)return`/platforms/${encodeURIComponent($)}/orders/${encodeURIComponent(String(X.orderId))}`;let Y=new URLSearchParams;IH(Y,"trackingRef",J),IH(Y,"orderId",X.orderId),IH(Y,"carrier",X.carrier),IH(Y,"accountId",X.accountId),IH(Y,"platformReference",X.platformReference);let Q=Y.toString();if(!Q)throw Error("Provide a tracking reference or --order-id");return`/platforms/${encodeURIComponent($)}/track?${Q}`},C70=($)=>{$.command("track <platform> [trackingRef]").description("Track shipping or delivery status for a platform order").option("--order-id <orderId>","Buygent order id").option("--carrier <carrier>","Carrier name or code").option("--account-id <platformAccountId>","Connected platform account id").option("--platform-reference <reference>","Platform order/reference id").action(async(J,X,Y)=>{let Q=X$(),G=await j9(Q,on0(String(J),X?String(X):void 0,Y));console.log(JSON.stringify(G,null,2))})};var _70=($)=>($/100).toFixed(2);import{existsSync as x70,readFileSync as sn0}from"node:fs";import{dirname as k70,join as y70}from"node:path";import{fileURLToPath as an0}from"node:url";var rn0="0.0.0-dev",b70="0.3.3",tn0=()=>b70!=="0.3.3",en0=($)=>{let J=y70($,"package.json");if(!x70(J))return;return JSON.parse(sn0(J,"utf8"))},$o0=($=import.meta.url)=>{let J=k70(an0($));while(!0){if(x70(y70(J,"package.json")))return J;let X=k70(J);if(X===J)return J;J=X}},v70=($=import.meta.url)=>{let J=en0($o0($));if(typeof J?.version==="string"&&J.version.trim().length>0)return J.version;return tn0()?b70:rn0};var z6=new pT,h70=($)=>{let[J,X]=$.split("/");if(!J||!X)throw Error(`Invalid resource reference: ${$}. Use adapterId/listingId.`);return{adapterId:J,listingId:X}},Jo0=($)=>{if($.length<=8)return"[redacted]";return`${$.startsWith("bg_live_")?"bg_live_":$.slice(0,3)}...${$.slice(-4)}`},Xo0=($)=>({...$,...$.agentKey?{agentKey:Jo0($.agentKey)}:{}}),d1=($)=>{console.log(JSON.stringify($,null,2))},Yo0=($)=>{if(!$||typeof $!=="object")return 0;let J=$;if(typeof J.availableCents==="number")return J.availableCents;let X=J.balance;if(X&&typeof X==="object"&&typeof X.availableCents==="number")return X.availableCents;return 0},f70=($)=>{let J=Yo0($);console.log(`Balance: $${_70(J)} (${J}\xA2)`)},Qo0=($)=>{if($==="external")return $;throw Error(`Invalid signer mode: ${$}. Use external.`)},g70=($)=>{if(!$.agentKey)throw Error(AZ)};z6.name("buygent").description("Buygent CLI").version(v70(import.meta.url));z6.command("health").description("Print CLI scaffold readiness").action(()=>{console.log("buygent cli ready")});a40(z6);F90(z6);$70(z6);S70(z6);A70(z6);M70(z6);C70(z6);w70(z6);W70(z6);U70(z6);z6.command("mcp").description("Run the Buygent MCP stdio server").option("--serve","Start the stdio MCP server").action(async($)=>{if(!$.serve)throw Error("Use: buygent mcp --serve");await Qv()});var Go0=z6.command("config").description("Manage local CLI configuration"),TH=z6.command("auth").description("Manage buyer and worker sign-in"),Ko0=z6.command("bounty").description("Create and inspect buyer human bounties"),Wo0=z6.command("credits").description("Manage buyer prepaid credits");Go0.command("set").option("--wallet-address <address>").option("--signer-mode <mode>","external",Qo0).option("--signer-endpoint <url>").option("--session-id <sessionId>").option("--account-email <email>").option("--account-role <role>").option("--api-url <url>").option("--agent-key <key>").option("--soft-limit <usd>").option("--hard-limit <usd>").action(($)=>{let J=ET({walletAddress:$.walletAddress,signerMode:$.signerMode,signerEndpoint:$.signerEndpoint,sessionId:$.sessionId,accountEmail:$.accountEmail,accountRole:$.accountRole==="buyer"||$.accountRole==="worker"?$.accountRole:void 0,apiUrl:$.apiUrl,agentKey:$.agentKey,softLimitUsd:$.softLimit!==void 0?Number.parseFloat(String($.softLimit)):void 0,hardLimitUsd:$.hardLimit!==void 0?Number.parseFloat(String($.hardLimit)):void 0});d1(Xo0(J))});TH.command("request-code").requiredOption("--email <email>").option("--role <role>","buyer or worker","buyer").option("--debug","Expose debug auth code when the server supports it").action(async($)=>{let J=_1(),X=FZ(J);if(!X)throw Error("Missing apiUrl. Run: buygent config set --api-url <url> or set BUYGENT_API_URL");let Y=String($.role)==="worker"?"worker":"buyer",Q=await fetch(`${X}/auth/email/request-code`,{method:"POST",headers:{"Content-Type":"application/json",...$.debug?{"x-buygent-debug-auth":"true"}:{},...J.agentKey?{Authorization:`Bearer ${J.agentKey}`}:{},...J.sessionId?{Cookie:`buygent_session=${encodeURIComponent(J.sessionId)}`}:{}},body:JSON.stringify({email:String($.email),role:Y})});if(!Q.ok)throw Error(await Q.text());d1(await Q.json())});TH.command("verify").requiredOption("--email <email>").requiredOption("--code <code>").option("--role <role>","buyer or worker","buyer").action(async($)=>{let J=_1(),X=FZ(J);if(!X)throw Error("Missing apiUrl. Run: buygent config set --api-url <url> or set BUYGENT_API_URL");let Y=String($.role)==="worker"?"worker":"buyer",Q=await fetch(`${X}/auth/email/verify`,{method:"POST",headers:{"Content-Type":"application/json",...J.agentKey?{Authorization:`Bearer ${J.agentKey}`}:{}},body:JSON.stringify({email:String($.email),role:Y,code:String($.code)})});if(!Q.ok)throw Error(await Q.text());let G=await Q.json(),K=ET({sessionId:G.sessionId,accountEmail:G.user.email,accountRole:G.user.role});d1({ok:!0,sessionId:G.sessionId,accountEmail:K.accountEmail,accountRole:K.accountRole,expiresAt:G.expiresAt})});TH.command("device-code").action(async()=>{await qv(_1())});TH.command("whoami").action(async()=>{let $=_1();d1(await F8($,"/auth/session"))});TH.command("logout").action(async()=>{let $=_1();await N8($,"/auth/logout",{});let J={...$};delete J.agentKey,delete J.sessionId,delete J.accountEmail,delete J.accountRole,MT(J),d1({ok:!0})});var u70=z6.command("catalog").description("Browse provider listings");u70.command("list").option("--type <type>").action(async($)=>{let J=_1(),X=$.type?`?type=${encodeURIComponent(String($.type))}`:"";d1(await F8(J,`/catalog${X}`))});u70.command("show <resource>").action(async($)=>{let J=_1(),{adapterId:X,listingId:Y}=h70($);d1(await F8(J,`/catalog/${X}/${Y}`))});var PT=($,J)=>[...J,$];Ko0.command("create").requiredOption("--intent <intent>").requiredOption("--market <market>").requiredOption("--specialty <specialty>").requiredOption("--deliverable <deliverable>").requiredOption("--duration <minutes>").option("--language <language>").option("--execution-mode <executionMode>").option("--credential <credential>","repeat for multiple credentials",PT,[]).option("--jurisdiction <jurisdiction>","repeat for multiple jurisdictions",PT,[]).option("--sla-min <minutes>").option("--wallet-address <address>").option("--output <mode>","summary, json, or url","summary").action(async($)=>{let J=_1();g70(J);let X=Number.parseInt(String($.duration),10),Y=Wv({intent:String($.intent),market:String($.market),durationMin:X,specialty:String($.specialty),deliverable:String($.deliverable),...$.language?{language:String($.language)}:{},...$.executionMode?{executionMode:String($.executionMode)}:{},...Array.isArray($.credential)&&$.credential.length>0?{credential:$.credential.map((H)=>String(H))}:{},...Array.isArray($.jurisdiction)&&$.jurisdiction.length>0?{jurisdiction:$.jurisdiction.map((H)=>String(H))}:{},...$.slaMin?{slaMin:Number.parseInt(String($.slaMin),10)}:{}}),Q=await MZ(J,{adapterId:"",listingId:"",durationMin:X,...$.walletAddress?{walletAddress:String($.walletAddress)}:{},request:Y}),G=Q.body??Q,K=G.credential&&typeof G.credential==="object"&&"fields"in G.credential&&G.credential.fields&&typeof G.credential.fields==="object"&&"taskId"in G.credential.fields&&typeof G.credential.fields.taskId==="string"?G.credential.fields.taskId:void 0,W=G.orderId&&typeof G.orderId==="string"&&J.apiUrl?`${J.apiUrl}/human-tasks/${G.orderId}`:void 0;if($.output==="json"){d1({...Q,taskId:K,taskStatusUrl:W});return}if($.output==="url"&&W){console.log(W);return}console.log(Hv({apiUrl:String(J.apiUrl),responseBody:G}))});Wo0.command("show").action(async()=>{let $=_1();g70($);let J=await F8($,"/credits");f70(J),d1(J)});z6.command("buy [resource]").option("--duration <minutes>").option("--billing <model>").option("--unit <unit>").option("--auto-renew").option("--interval-count <count>").option("--cancel-at-period-end").option("--type <type>").option("--resource-class <resourceClass>").option("--intent <intent>").option("--market <market>").option("--provider <provider>").option("--channel <channel>").option("--credential-kind <kind>").option("--specialty <specialty>").option("--jurisdiction <jurisdiction>").option("--credential <credential>").option("--execution-mode <executionMode>").option("--deliverable <deliverable>").option("--language <language>").option("--sla-min <minutes>").option("--task <task>").option("--environment <environment>").option("--gpu-type <type>").option("--gpu-count <count>").option("--public-endpoint").option("--output <mode>","json or key","json").action(async($,J)=>{let X=_1(),Y=J.task||J.environment||J.gpuType||J.gpuCount||J.publicEndpoint||J.provider||J.channel||J.credentialKind||J.specialty||J.jurisdiction||J.credential||J.executionMode||J.deliverable||J.language||J.slaMin?{...J.task?{task:String(J.task)}:{},...J.environment?{environment:String(J.environment)}:{},...J.gpuType?{gpuType:String(J.gpuType)}:{},...J.gpuCount?{gpuCount:Number.parseInt(String(J.gpuCount),10)}:{},...J.publicEndpoint?{publicEndpoint:!0}:{},...J.provider?{provider:String(J.provider)}:{},...J.channel?{channel:String(J.channel)}:{},...J.credentialKind?{credentialKind:String(J.credentialKind)}:{},...J.specialty?{specialty:String(J.specialty)}:{},...J.jurisdiction?{jurisdiction:String(J.jurisdiction)}:{},...J.credential?{credential:String(J.credential)}:{},...J.executionMode?{executionMode:String(J.executionMode)}:{},...J.deliverable?{deliverable:String(J.deliverable)}:{},...J.language?{language:String(J.language)}:{},...J.slaMin?{slaMin:Number.parseInt(String(J.slaMin),10)}:{}}:void 0,Q=await($?(()=>{let G=lN(J.duration);if(G===void 0)throw Error("--duration is required when buying a concrete resource listing");return MZ(X,{...h70($),durationMin:G,requirements:Y,billing:dN(J)?{model:String(J.billing??"lease"),unit:String(J.unit??"minute"),autoRenew:Boolean(J.autoRenew),...J.intervalCount?{intervalCount:Number.parseInt(String(J.intervalCount),10)}:{},...J.cancelAtPeriodEnd?{cancelAtPeriodEnd:!0}:{}}:void 0})})():(()=>{let G=Uv(J);return MZ(X,{adapterId:"",listingId:"",durationMin:G.durationMin,request:G.request})})());if(J.output==="key"){let G="body"in Q&&Q.body&&typeof Q.body==="object"?Q.body:Q,K=G.credential,W=K?.fields?.apiKeySecret??K?.fields?.secret??K?.fields?.token??JSON.stringify(G);console.log(W);return}d1(Q)});var m70=z6.command("orders").description("Inspect purchase orders");m70.command("list").action(async()=>{let $=_1();d1(await F8($,"/orders"))});m70.command("show <orderId>").action(async($)=>{let J=_1();d1(await F8(J,`/orders/${$}/status`))});var c70=z6.command("credentials").description("Inspect issued credentials"),l70=z6.command("compute").description("Use compute capabilities"),Ho0=z6.command("email").description("Use email capabilities"),Vo0=z6.command("sms").description("Use SMS capabilities"),d70=z6.command("human").description("Use human execution primitives");c70.command("list").action(async()=>{let $=_1();d1(await F8($,"/credentials"))});c70.command("show <orderId>").action(async($)=>{let J=_1();d1(await F8(J,`/credentials/${$}`))});Ho0.command("send").option("--order-id <orderId>").requiredOption("--to <email>").requiredOption("--subject <subject>").option("--text <text>").option("--html <html>").action(async($)=>{let J=_1();d1(await N8(J,"/actions/email/send",{to:String($.to),subject:String($.subject),...$.text?{text:String($.text)}:{},...$.html?{html:String($.html)}:{}}))});Vo0.command("send").option("--order-id <orderId>").requiredOption("--to <number>").requiredOption("--text <text>").option("--from <number>").action(async($)=>{let J=_1();d1(await N8(J,"/actions/sms/send",{to:String($.to),text:String($.text),...$.from?{from:String($.from)}:{}}))});var hY=d70.command("task").description("Use buyer-side human task primitives"),wH=d70.command("work").description("Use worker-side human task primitives");hY.command("show").requiredOption("--order-id <orderId>").action(async($)=>{let J=_1();d1(await F8(J,`/human-tasks/${encodeURIComponent(String($.orderId))}`))});hY.command("events").requiredOption("--task-id <taskId>").action(async($)=>{let J=_1();d1(await F8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/events`))});hY.command("applicants").requiredOption("--task-id <taskId>").action(async($)=>{let J=_1();d1(await F8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/applicants`))});hY.command("select").requiredOption("--task-id <taskId>").requiredOption("--human-profile-id <humanProfileId>").option("--selected-by <selectedBy>").action(async($)=>{let J=_1();d1(await N8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/select`,{humanProfileId:String($.humanProfileId),...$.selectedBy?{selectedBy:String($.selectedBy)}:{}}))});hY.command("message").requiredOption("--task-id <taskId>").requiredOption("--message <message>").option("--actor-id <actorId>").action(async($)=>{let J=_1();d1(await N8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/messages`,{actorType:"buyer",...$.actorId?{actorId:String($.actorId)}:{},message:String($.message)}))});hY.command("approve").requiredOption("--task-id <taskId>").option("--buyer-id <buyerId>").action(async($)=>{let J=_1();d1(await N8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/approve`,{...$.buyerId?{buyerId:String($.buyerId)}:{}}))});hY.command("reject").requiredOption("--task-id <taskId>").requiredOption("--reason <reason>").option("--buyer-id <buyerId>").option("--final","Mark as final rejection instead of revision requested").action(async($)=>{let J=_1();d1(await N8(J,`/human-tasks/${encodeURIComponent(String($.taskId))}/reject`,{reason:String($.reason),revisionRequested:!Boolean($.final),...$.buyerId?{buyerId:String($.buyerId)}:{}}))});wH.command("available").option("--human-profile-id <humanProfileId>").action(async($)=>{let J=_1(),X=$.humanProfileId?`?humanProfileId=${encodeURIComponent(String($.humanProfileId))}`:"";d1(await F8(J,`/human-work/available${X}`))});wH.command("apply").requiredOption("--task-id <taskId>").requiredOption("--human-profile-id <humanProfileId>").option("--note <note>").action(async($)=>{let J=_1();d1(await N8(J,`/human-work/${encodeURIComponent(String($.taskId))}/apply`,{humanProfileId:String($.humanProfileId),...$.note?{note:String($.note)}:{}}))});wH.command("start").requiredOption("--task-id <taskId>").requiredOption("--human-profile-id <humanProfileId>").action(async($)=>{let J=_1();d1(await N8(J,`/human-work/${encodeURIComponent(String($.taskId))}/start`,{humanProfileId:String($.humanProfileId)}))});wH.command("submit").requiredOption("--task-id <taskId>").requiredOption("--human-profile-id <humanProfileId>").requiredOption("--summary <summary>").option("--time-spent-min <minutes>").option("--artifact <artifact>","repeatable artifact values",PT,[]).action(async($)=>{let J=_1();d1(await N8(J,`/human-work/${encodeURIComponent(String($.taskId))}/submit`,{humanProfileId:String($.humanProfileId),summary:String($.summary),...Array.isArray($.artifact)&&$.artifact.length>0?{artifacts:$.artifact.map((X)=>({label:"artifact",value:String(X)}))}:{},...$.timeSpentMin?{timeSpentMin:Number.parseInt(String($.timeSpentMin),10)}:{}}))});wH.command("message").requiredOption("--task-id <taskId>").requiredOption("--human-profile-id <humanProfileId>").requiredOption("--message <message>").action(async($)=>{let J=_1();d1(await N8(J,`/human-work/${encodeURIComponent(String($.taskId))}/messages`,{humanProfileId:String($.humanProfileId),message:String($.message)}))});l70.command("exec").option("--order-id <orderId>").requiredOption("--command <command>").action(async($)=>{let J=_1();d1(await N8(J,"/actions/compute/exec",{command:String($.command)}))});var MO=l70.command("session").description("Manage mediated compute sessions");MO.command("open").option("--order-id <orderId>").action(async($)=>{let J=_1();d1(await N8(J,"/actions/compute/session",{}))});MO.command("send").requiredOption("--token <token>").requiredOption("--data <data>").action(async($)=>{let J=_1();d1(await fetch(`${J.apiUrl}/actions/compute/session/input`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${String($.token)}`},body:JSON.stringify({data:String($.data)})}).then(async(X)=>{if(!X.ok)throw Error(await X.text());return X.json()}))});MO.command("read").requiredOption("--token <token>").option("--cursor <cursor>").action(async($)=>{let J=_1(),X=$.cursor!==void 0?`?cursor=${encodeURIComponent(String($.cursor))}`:"";d1(await fetch(`${J.apiUrl}/actions/compute/session/output${X}`,{method:"GET",headers:{Authorization:`Bearer ${String($.token)}`}}).then(async(Y)=>{if(!Y.ok)throw Error(await Y.text());return Y.json()}))});MO.command("close").requiredOption("--token <token>").action(async($)=>{let J=_1();d1(await fetch(`${J.apiUrl}/actions/compute/session/close`,{method:"POST",headers:{Authorization:`Bearer ${String($.token)}`}}).then(async(X)=>{if(!X.ok)throw Error(await X.text());return X.json()}))});z6.command("spending").action(async()=>{let $=_1(),J=await F8($,"/credits");f70(J),d1(J)});z6.parseAsync().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});
|
|
@@ -151,6 +151,9 @@ var BUNDLED_COUPANG_SELECTOR_CONFIG = {
|
|
|
151
151
|
"[data-cy='add-to-cart-button']"
|
|
152
152
|
],
|
|
153
153
|
cartCheckoutButton: [
|
|
154
|
+
"#btnPay",
|
|
155
|
+
"a#btnPay",
|
|
156
|
+
"a.goPayment",
|
|
154
157
|
"[data-testid='cart-order-button']",
|
|
155
158
|
"[data-cy='cart-order-button']",
|
|
156
159
|
"[data-automation-id='cart-order-button']"
|
|
@@ -171,6 +171,9 @@
|
|
|
171
171
|
"[data-cy='add-to-cart-button']"
|
|
172
172
|
],
|
|
173
173
|
cartCheckoutButton: [
|
|
174
|
+
"#btnPay",
|
|
175
|
+
"a#btnPay",
|
|
176
|
+
"a.goPayment",
|
|
174
177
|
"[data-testid='cart-order-button']",
|
|
175
178
|
"[data-cy='cart-order-button']",
|
|
176
179
|
"[data-automation-id='cart-order-button']"
|
|
@@ -870,7 +873,7 @@
|
|
|
870
873
|
await clickElement(selectAll, "Unable to toggle the Coupang cart selection state.");
|
|
871
874
|
},
|
|
872
875
|
async startCheckout() {
|
|
873
|
-
const button = queryFirstVisibleBySelectorGroup(document2, selectorConfig.selectors.cartCheckoutButton) ?? queryFirstVisibleByText(document2,
|
|
876
|
+
const button = queryFirstVisibleBySelectorGroup(document2, selectorConfig.selectors.cartCheckoutButton) ?? queryFirstVisibleByText(document2, /(주문하기|구매하기)/u);
|
|
874
877
|
await clickElement(button, "Unable to find the Coupang cart order button.");
|
|
875
878
|
}
|
|
876
879
|
};
|
package/dist/native-host.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// @bun
|
|
3
|
-
import{createServer as q}from"net";import{existsSync as f,mkdirSync as w,readFileSync as b,rmSync as m}from"fs";import{homedir as R}from"os";import{dirname as g,join as h}from"path";import{fileURLToPath as V}from"url";var x="0.0.0-dev",E="0.3.
|
|
3
|
+
import{createServer as q}from"net";import{existsSync as f,mkdirSync as w,readFileSync as b,rmSync as m}from"fs";import{homedir as R}from"os";import{dirname as g,join as h}from"path";import{fileURLToPath as V}from"url";var x="0.0.0-dev",E="0.3.3",A=()=>{let e=g(V(import.meta.url));while(!0){let t=h(e,"package.json");if(f(t)){let o=JSON.parse(b(t,"utf8"));if(typeof o.version==="string"&&o.version.trim().length>0)return o.version}let r=g(e);if(r===e)break;e=r}return E==="0.3.3"?x:E},B=A(),T=1,c=h(R(),".buygent","chrome-extension","com.buygent.host.sock"),n=Buffer.alloc(0),s=new Map,p=new Map,l=new WeakMap,i=()=>globalThis.crypto?.randomUUID?.()??`req_${Date.now()}_${Math.random().toString(16).slice(2)}`,_=(e,t,r)=>({protocolVersion:T,type:e,messageId:r.messageId,...r.requestId?{requestId:r.requestId}:{},sentAt:r.sentAt??new Date().toISOString(),source:r.source,payload:t}),d=(e,t)=>_("error",e,t),O=(e)=>{if(!e||typeof e!=="object"||Array.isArray(e))return{ok:!1,error:d({code:"invalid_envelope",message:"Expected a JSON object envelope."},{source:"native-host",messageId:i()})};let t=e;if(t.protocolVersion!==T)return{ok:!1,error:d({code:"unsupported_protocol_version",message:`Unsupported protocolVersion: ${String(t.protocolVersion??"missing")}`},{source:"native-host",messageId:i()})};if(typeof t.type!=="string"||typeof t.messageId!=="string"||typeof t.sentAt!=="string"||typeof t.source!=="string")return{ok:!1,error:d({code:"invalid_envelope",message:"Envelope must include type, messageId, sentAt, and source fields."},{source:"native-host",messageId:i()})};return{ok:!0,envelope:e}},D=(e)=>JSON.stringify(e),u=(e)=>{let t=Buffer.from(JSON.stringify(e),"utf8"),r=Buffer.alloc(4);r.writeUInt32LE(t.length,0),process.stdout.write(r),process.stdout.write(t)},a=(e,t)=>{e.write(`${D(t)}
|
|
4
4
|
`)},P=(e,t)=>{let r=p.get(e)??new Set;r.add(t),p.set(e,r)},S=(e)=>{for(let[t,r]of p.entries())if(r.delete(e),r.size===0)p.delete(t);for(let[t,r]of s.entries())if(r===e)s.delete(t)},k=(e,t)=>{let r=p.get(e);if(!r)return;for(let o of r)a(o,t)},U=(e)=>{if(e.type==="native:ping"){u(_("native:pong",{hostVersion:B,receivedAt:new Date().toISOString()},{source:"native-host",messageId:i(),requestId:e.messageId}));return}if(e.type==="order:ack"){if(e.requestId){let t=s.get(e.requestId);if(t)P(e.payload.orderId,t),a(t,e)}return}if(e.type==="runtime:state"){if(e.requestId){let t=s.get(e.requestId);if(t)s.delete(e.requestId),a(t,e)}return}if(e.type==="order:status"||e.type==="order:checkpoint"){k(e.payload.orderId,e);return}if(e.type==="error"){let t=typeof e.payload.details==="object"&&e.payload.details&&!Array.isArray(e.payload.details)?e.payload.details.orderId:void 0;if(typeof t==="string"){k(t,e);return}if(e.requestId){let r=s.get(e.requestId);if(r)s.delete(e.requestId),a(r,e)}}},L=(e)=>{let t=O(e);if(!t.ok){u(t.error);return}U(t.envelope)},H=(e,t)=>{let r=O(JSON.parse(t));if(!r.ok){a(e,r.error);return}let o=r.envelope;if(o.type==="order:start"||o.type==="runtime:get-state"){s.set(o.messageId,e),u(o);return}a(e,d({code:"unsupported_message",message:`Unsupported CLI/native-host message: ${o.type}`},{source:"native-host",messageId:i(),requestId:o.messageId}))},J=()=>{if(w(g(c),{recursive:!0,mode:448}),f(c))m(c,{force:!0})};J();var M=q((e)=>{e.setEncoding("utf8"),l.set(e,""),e.on("data",(t)=>{let o=`${l.get(e)??""}${t}`.split(/\r?\n/u);l.set(e,o.pop()??"");for(let N of o){let y=N.trim();if(!y)continue;try{H(e,y)}catch(I){a(e,d({code:"invalid_message",message:I instanceof Error?I.message:"Invalid CLI/native-host payload."},{source:"native-host",messageId:i()}))}}}),e.on("close",()=>{S(e)}),e.on("error",()=>{S(e)})});M.listen(c);process.stdin.on("data",(e)=>{n=Buffer.concat([n,e]);while(n.length>=4){let t=n.readUInt32LE(0);if(n.length<4+t)return;let r=n.subarray(4,4+t);n=n.subarray(4+t);try{L(JSON.parse(r.toString("utf8")))}catch(o){u(d({code:"invalid_message",message:o instanceof Error?o.message:"Invalid JSON payload."},{source:"native-host",messageId:i()}))}}});var v=()=>{if(M.close(),f(c))m(c,{force:!0})};process.stdin.on("end",()=>{v(),process.exit(0)});process.on("SIGTERM",()=>{v(),process.exit(0)});process.on("SIGINT",()=>{v(),process.exit(0)});process.stdin.resume();
|