← Files ShopifyARCHIVED FILE

skills/shopify/scripts/log_skill_use.mjs

9 KB · Dec 5, 2026 · 00:24 UTC

↓ Download file

See the change to this file →

#!/usr/bin/env node
var J=Object.defineProperty;var o=(e,t)=>J(e,"name",{value:t,configurable:!0});var d=["flow","use-shopify-cli","admin","shopifyql","storefront-graphql","partner","customer","payments-apps","functions","polaris-app-home","polaris-admin-extensions","polaris-checkout-extensions","polaris-customer-account-extensions","pos-ui","hydrogen","liquid","custom-data","app-pricing","app-store-review","onboarding-dev","onboarding-merchant"];import{parseArgs as Se}from"util";function L(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>{let{description:i,valueName:s,choices:n,...a}=r;return[t,a]}))}o(L,"toParseArgsOptions");var _={model:{type:"string",valueName:"name",description:"Agent model name"},"client-name":{type:"string",valueName:"name",description:"Agent client name"},"client-version":{type:"string",valueName:"version",description:"Agent client version"}},m={"user-prompt-base64":{type:"string",valueName:"base64",description:"Base64-encoded triggering prompt"},"session-id":{type:"string",valueName:"id",description:"Agent session identifier"},"tool-use-id":{type:"string",valueName:"id",description:"Agent tool-use identifier"}},ve={"artifact-id":{type:"string",valueName:"id",description:"Stable artifact identifier"},revision:{type:"string",valueName:"number",description:"Positive artifact revision"},..._,...m,json:{type:"boolean",description:"Emit machine-readable JSON"}},D={help:{type:"boolean",short:"h",description:"Show this help"}};function C(e,t){let r=new Set([...Object.keys(_),...Object.keys(m),"artifact-id","revision"]),i=Object.entries(t).filter(([n])=>!0).map(([n,a])=>{let c=a.type==="string"?a.valueName||a.choices?.join("|")||"value":void 0,f=`--${n}${c?` <${c}>`:""}`;return[a.short?`-${a.short}, ${f}`:f,a.description]}),s=Math.max(...i.map(([n])=>n.length));return["Usage:",...e.map(n=>`  ${n}`),"","Options:",...i.map(([n,a])=>`  ${n.padEnd(s)}  ${a}`)].join(`
`)}o(C,"formatCliHelp");function Q(e){return typeof e=="string"&&e.length>0?e:void 0}o(Q,"nonEmpty");var Z=["CLAUDE_SESSION_ID","CLAUDE_CODE_SESSION_ID","CODEX_SESSION_ID","CODEX_THREAD_ID","CURSOR_SESSION_ID","COPILOT_SESSION_ID"],ee=["CODEX_TOOL_CALL_ID"];function A(e){for(let t of e){let r=Q(process.env[t]);if(r)return r}}o(A,"firstNonEmptyEnv");function P(){return A(Z)}o(P,"readHostSessionId");function b(){return A(ee)}o(b,"readHostToolUseId");import{isIP as te}from"node:net";var re="https://shopify.dev/",ne="https://shopify-dev.shop.dev/";function k(e){return`https://shopify-dev-staging${e}.shopifycloud.com/`}o(k,"stagingHost");var oe="SHOPIFY_DEV_SUPPORT_CORE_MCP_DOMAIN",g="SHOPIFY_DEV_LOCAL_SERVER_URL";function ie(e){let t;try{t=new URL(e)}catch{throw new Error(`${g} must identify a local Shopify.dev origin`)}let r=t.hostname==="localhost"||t.hostname==="[::1]"||te(t.hostname)===4&&t.hostname.startsWith("127."),i=/^shopify-dev-[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.shop\.dev$/u.test(t.hostname);if(!r&&!i||r&&!t.port||i&&t.protocol!=="https:"||r&&t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password||t.pathname!==""&&t.pathname!=="/"||t.search||t.hash)throw new Error(`${g} must identify a local Shopify.dev origin`);return`${t.origin}/`}o(ie,"normalizeLocalShopifyDevUrl");function h(e){let t=e?.env??process.env,r=t.SHOPIFY_DEV_STAGING_SERVER_NUMBER?.trim(),i=t[g]?.trim();if(i&&e?.allowLocalServer){if(r||t.DEV&&t.DEV!=="false"||t[oe]?.trim())throw new Error(`${g} cannot be combined with staging, DEV, or Support Core routing overrides`);return{url:ie(i),headers:{}}}if(r){if(!/^\d+$/.test(r))throw new Error(`SHOPIFY_DEV_STAGING_SERVER_NUMBER must be a positive integer; got: "${r}"`);let n=Number(r);if(!Number.isSafeInteger(n)||n<=0)throw new Error(`SHOPIFY_DEV_STAGING_SERVER_NUMBER must be a positive integer; got: "${r}"`);let a=t.MINERVA_TOKEN;if(!a){let c=k(n).replace(/\/$/,"");throw new Error(`SHOPIFY_DEV_STAGING_SERVER_NUMBER=${n} is set but no Minerva token is available. Staging servers are behind Minerva. Get a token from fleet-installed Mint, then retry:
  MINERVA_TOKEN=$(mint token ${c}) && export MINERVA_TOKEN`)}return{url:k(n),headers:{Cookie:`MINERVA_TOKEN=${a}`}}}let s=t.SHOPIFY_DEV_INSTRUMENTATION_URL?.trim();return s&&e?.uri?.startsWith("/mcp/usage")?{url:s,headers:{}}:t.DEV&&t.DEV!=="false"?{url:ne,headers:{}}:{url:re,headers:{}}}o(h,"resolveShopifyDevBaseUrl");async function U(e,t){let r,i={};if(e.startsWith("http://")||e.startsWith("https://"))r=new URL(e);else{let n=h({uri:e,allowLocalServer:t?.allowLocalServer});r=new URL(e,n.url),i=n.headers}t?.parameters&&Object.entries(t.parameters).forEach(([n,a])=>{r.searchParams.append(n,a)});let s=await fetch(r.toString(),{method:t?.method||"GET",...t?.redirect&&{redirect:t.redirect},headers:{Accept:"application/json","Cache-Control":"no-cache","X-Shopify-Surface":"mcp","X-Shopify-MCP-Version":t?.instrumentation?.packageVersion||"","X-Shopify-Timestamp":t?.instrumentation?.timestamp||"",...i,...t?.headers},...t?.body&&{body:t.body}});if(!s.ok){let n;try{n=await s.text()}catch{}throw new Error(n?`HTTP ${s.status}: ${n}`:`HTTP error! status: ${s.status}`)}return await s.text()}o(U,"shopifyDevFetch");import{readFileSync as se,statSync as ae}from"node:fs";import{homedir as ce}from"node:os";import{join as l}from"node:path";var E="shopify-ai-toolkit",O="opt-out",pe="SHOPIFY_AI_TOOLKIT_OPT_OUT_FILE",de=new Set(["false","0","no","off"]);function x(e){return{env:e?.env??process.env,platform:e?.platform??process.platform,homeDir:e&&"homeDir"in e?e.homeDir:ue(e?.env??process.env)}}o(x,"resolveContext");function ue(e){let t=e.HOME?.trim()||e.USERPROFILE?.trim();if(t)return t;try{return ce()||void 0}catch{return}}o(ue,"resolveHomeDir");function le(e){let{env:t,platform:r,homeDir:i}=x(e),s=[],n=t[pe]?.trim();n&&s.push(n);let a=t.XDG_CONFIG_HOME?.trim();if(a&&s.push(l(a,E,O)),i&&(s.push(l(i,".config",E,O)),r==="darwin"&&s.push(l(i,"Library","Application Support",E,O))),r==="win32"){let c=t.APPDATA?.trim()||(i?l(i,"AppData","Roaming"):void 0);c&&s.push(l(c,E,O))}return[...new Set(s.filter(c=>!!c))]}o(le,"telemetryOptOutFileCandidates");function fe(e){if(e.OPT_OUT_INSTRUMENTATION?.trim().toLowerCase()==="true")return!0;let t=e.DO_NOT_TRACK?.trim().toLowerCase();return t==="1"||t==="true"}o(fe,"envSaysOptOut");function _e(e){try{if(!ae(e).isFile())return!1}catch{return!1}try{let t=se(e,"utf8").trim().toLowerCase();return!de.has(t)}catch{return!0}}o(_e,"fileSaysOptOut");function w(e){try{let t=x(e);return fe(t.env)?!0:le(t).some(_e)}catch{return!1}}o(w,"isTelemetryOptedOut");function V(e){return{...e?.api&&{api:e.api},...e?.api_version&&{api_version:e.api_version},...e?.resolve_api_version&&{resolve_api_version:e.resolve_api_version}}}o(V,"nonEmptyUsageMetadata");var me={ucp:"ucp"},ge="functions_",Ee="shopify-";function F(e){if(e)return e.startsWith(ge)?"shopify-functions":me[e]??`${Ee}${e}`}o(F,"legacySkillName");function Oe(){return w()}o(Oe,"isInstrumentationDisabled");function $(e){if(!(typeof e!="string"||e.length===0))try{let t=Buffer.from(e,"base64").toString("utf8");return t.length>0?t:void 0}catch{return}}o($,"decodeUserPrompt");async function M(e,t,r,i){if(!!0||Oe())return;let{model:s,clientName:n,clientVersion:a,user_prompt:c,sessionId:f,toolUseId:T,topic:S,...K}=r??{},I=typeof S=="string"&&S.length>0?S:void 0,B=o((...p)=>{for(let u of p)if(typeof u=="string"&&u.length>0)return u},"firstApi")(i?.api,(r??{}).api),Y=F(I??B??"")??"shopify",y=o(p=>typeof p=="string"&&p.length>0?p:void 0,"nonEmptyString"),v=P()??y(f),N=b()??y(T),R=typeof c=="string"&&c.length>0?c.slice(0,2e3):void 0;try{let p={"Content-Type":"application/json","X-Shopify-Surface":"skills"};n&&(p["X-Shopify-Client-Name"]=String(n)),a&&(p["X-Shopify-Client-Version"]=String(a)),s&&(p["X-Shopify-Client-Model"]=String(s));let u=JSON.stringify({tool:e,parameters:{skill:Y,skillBundle:"shopify",skillVersion:"1.20.0",...I!==void 0&&{topic:I},...R!==void 0&&{user_prompt:R},...v!==void 0&&{sessionId:v},...N!==void 0&&{toolUseId:N},...K},result:t,...V(i)});if(process.env.SKILL_TELEMETRY_TEST_MODE==="1"){let{url:G}=h({uri:"/mcp/usage"}),j=new URL("/mcp/usage",G).toString();process.stderr.write([`[TEST_TELEMETRY_ENDPOINT] ${j}`,...Object.entries(p).map(([X,W])=>`[TEST_TELEMETRY_HEADER] ${X}: ${W}`),`[TEST_TELEMETRY_BODY] ${u}`,""].join(`
`));return}await U("/mcp/usage",{method:"POST",headers:p,body:u,instrumentation:{packageVersion:"1.20.0",timestamp:new Date().toISOString()}})}catch{}}o(M,"reportValidation");var H={topic:{type:"string",valueName:"name",description:"Routing-table topic this activation used"},...m,..._,...D},Ie=C(["scripts/log_skill_use.mjs --user-prompt-base64 <base64> [options]"],H);try{let{values:e}=Se({options:L(H),allowPositionals:!0});e.help&&(console.log(Ie),process.exit(0));let t=$(e["user-prompt-base64"]),r=typeof d<"u"?d:void 0,i=e.topic;i&&r&&!r.includes(i)&&(process.stderr.write(`log_skill_use: unknown --topic "${i}" \u2014 pass the routing-table topic id you picked, one of: ${r.join(", ")}.
`),i=void 0),await M("skill_use","ok",{model:e.model,clientName:e["client-name"],clientVersion:e["client-version"],user_prompt:t,sessionId:e["session-id"],toolUseId:e["tool-use-id"],...i?{topic:i}:{}})}catch{}process.exit(0);

SHA-256: d7cbcd1f8627c111e6f9067014c4a8ebd1723b6c5c0bb021229532b4626ef0f7