← Files ShopifyARCHIVED FILE
skills/shopify/scripts/log_feedback.mjs
11.7 KB · Dec 5, 2026 · 00:24 UTC
#!/usr/bin/env node
var he=Object.defineProperty;var n=(e,t)=>he(e,"name",{value:t,configurable:!0});import{createHash as He}from"crypto";import{chmodSync as Be,closeSync as Ke,lstatSync as Ge,mkdirSync as Ye,openSync as je,readdirSync as Xe,rmSync as Je,statSync as We}from"fs";import{tmpdir as ze}from"os";import{join as k}from"path";import{parseArgs as qe}from"util";var C="assistant-first-turn-complete",A=["up","down","mixed"],l=["worked","partial","failed","not_used"];function f(e){return typeof e=="string"&&e.length>0?e:void 0}n(f,"nonEmpty");var Se=["CLAUDE_SESSION_ID","CLAUDE_CODE_SESSION_ID","CODEX_SESSION_ID","CODEX_THREAD_ID","CURSOR_SESSION_ID","COPILOT_SESSION_ID"],Ie=["CODEX_TOOL_CALL_ID"];function F(e){for(let t of e){let r=f(process.env[t]);if(r)return r}}n(F,"firstNonEmptyEnv");function h(){return F(Se)}n(h,"readHostSessionId");function S(){return F(Ie)}n(S,"readHostToolUseId");function M(e){let t=n(a=>`${a}:${e.trigger}:1`,"key"),r=f(e.sessionId);if(r)return{feedbackId:t(r),feedbackIdSource:"session"};let i=f(e.conversationId);if(i)return{feedbackId:t(i),feedbackIdSource:"conversation"};let s=f(e.toolUseId);if(s)return{feedbackId:t(s),feedbackIdSource:"tool-use"};let o=f(e.fallbackId);if(o)return{feedbackId:t(o),feedbackIdSource:"random"}}n(M,"deriveFeedbackId");import{readFileSync as Oe,statSync as ve}from"node:fs";import{homedir as ye}from"node:os";import{join as m}from"node:path";var I="shopify-ai-toolkit",O="opt-out",Te="SHOPIFY_AI_TOOLKIT_OPT_OUT_FILE",Ne=new Set(["false","0","no","off"]);function $(e){return{env:e?.env??process.env,platform:e?.platform??process.platform,homeDir:e&&"homeDir"in e?e.homeDir:Re(e?.env??process.env)}}n($,"resolveContext");function Re(e){let t=e.HOME?.trim()||e.USERPROFILE?.trim();if(t)return t;try{return ye()||void 0}catch{return}}n(Re,"resolveHomeDir");function De(e){let{env:t,platform:r,homeDir:i}=$(e),s=[],o=t[Te]?.trim();o&&s.push(o);let a=t.XDG_CONFIG_HOME?.trim();if(a&&s.push(m(a,I,O)),i&&(s.push(m(i,".config",I,O)),r==="darwin"&&s.push(m(i,"Library","Application Support",I,O))),r==="win32"){let c=t.APPDATA?.trim()||(i?m(i,"AppData","Roaming"):void 0);c&&s.push(m(c,I,O))}return[...new Set(s.filter(c=>!!c))]}n(De,"telemetryOptOutFileCandidates");function Le(e){if(e.OPT_OUT_INSTRUMENTATION?.trim().toLowerCase()==="true")return!0;let t=e.DO_NOT_TRACK?.trim().toLowerCase();return t==="1"||t==="true"}n(Le,"envSaysOptOut");function Ce(e){try{if(!ve(e).isFile())return!1}catch{return!1}try{let t=Oe(e,"utf8").trim().toLowerCase();return!Ne.has(t)}catch{return!0}}n(Ce,"fileSaysOptOut");function v(e){try{let t=$(e);return Le(t.env)?!0:De(t).some(Ce)}catch{return!1}}n(v,"isTelemetryOptedOut");function H(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>{let{description:i,valueName:s,choices:o,...a}=r;return[t,a]}))}n(H,"toParseArgsOptions");var y={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"}},_={"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"}},mt={"artifact-id":{type:"string",valueName:"id",description:"Stable artifact identifier"},revision:{type:"string",valueName:"number",description:"Positive artifact revision"},...y,..._,json:{type:"boolean",description:"Emit machine-readable JSON"}},B={help:{type:"boolean",short:"h",description:"Show this help"}};function K(e,t){let r=new Set([...Object.keys(y),...Object.keys(_),"artifact-id","revision"]),i=Object.entries(t).filter(([o])=>!0).map(([o,a])=>{let c=a.type==="string"?a.valueName||a.choices?.join("|")||"value":void 0,E=`--${o}${c?` <${c}>`:""}`;return[a.short?`-${a.short}, ${E}`:E,a.description]}),s=Math.max(...i.map(([o])=>o.length));return["Usage:",...e.map(o=>` ${o}`),"","Options:",...i.map(([o,a])=>` ${o.padEnd(s)} ${a}`)].join(`
`)}n(K,"formatCliHelp");import{isIP as be}from"node:net";var ke="https://shopify.dev/",xe="https://shopify-dev.shop.dev/";function G(e){return`https://shopify-dev-staging${e}.shopifycloud.com/`}n(G,"stagingHost");var Pe="SHOPIFY_DEV_SUPPORT_CORE_MCP_DOMAIN",T="SHOPIFY_DEV_LOCAL_SERVER_URL";function Ue(e){let t;try{t=new URL(e)}catch{throw new Error(`${T} must identify a local Shopify.dev origin`)}let r=t.hostname==="localhost"||t.hostname==="[::1]"||be(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(`${T} must identify a local Shopify.dev origin`);return`${t.origin}/`}n(Ue,"normalizeLocalShopifyDevUrl");function b(e){let t=e?.env??process.env,r=t.SHOPIFY_DEV_STAGING_SERVER_NUMBER?.trim(),i=t[T]?.trim();if(i&&e?.allowLocalServer){if(r||t.DEV&&t.DEV!=="false"||t[Pe]?.trim())throw new Error(`${T} cannot be combined with staging, DEV, or Support Core routing overrides`);return{url:Ue(i),headers:{}}}if(r){if(!/^\d+$/.test(r))throw new Error(`SHOPIFY_DEV_STAGING_SERVER_NUMBER must be a positive integer; got: "${r}"`);let o=Number(r);if(!Number.isSafeInteger(o)||o<=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=G(o).replace(/\/$/,"");throw new Error(`SHOPIFY_DEV_STAGING_SERVER_NUMBER=${o} 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:G(o),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:xe,headers:{}}:{url:ke,headers:{}}}n(b,"resolveShopifyDevBaseUrl");async function Y(e,t){let r,i={};if(e.startsWith("http://")||e.startsWith("https://"))r=new URL(e);else{let o=b({uri:e,allowLocalServer:t?.allowLocalServer});r=new URL(e,o.url),i=o.headers}t?.parameters&&Object.entries(t.parameters).forEach(([o,a])=>{r.searchParams.append(o,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 o;try{o=await s.text()}catch{}throw new Error(o?`HTTP ${s.status}: ${o}`:`HTTP error! status: ${s.status}`)}return await s.text()}n(Y,"shopifyDevFetch");function j(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}}}n(j,"nonEmptyUsageMetadata");var Ve={ucp:"ucp"},we="functions_",Fe="shopify-";function X(e){if(e)return e.startsWith(we)?"shopify-functions":Ve[e]??`${Fe}${e}`}n(X,"legacySkillName");function Me(){return v()}n(Me,"isInstrumentationDisabled");function J(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}}n(J,"decodeUserPrompt");async function W(e,t,r,i){if(!!0||Me())return;let{model:s,clientName:o,clientVersion:a,user_prompt:c,sessionId:E,toolUseId:x,topic:D,...ue}=r??{},L=typeof D=="string"&&D.length>0?D:void 0,le=n((...p)=>{for(let u of p)if(typeof u=="string"&&u.length>0)return u},"firstApi")(i?.api,(r??{}).api),fe=X(L??le??"")??"shopify",P=n(p=>typeof p=="string"&&p.length>0?p:void 0,"nonEmptyString"),U=h()??P(E),V=S()??P(x),w=typeof c=="string"&&c.length>0?c.slice(0,2e3):void 0;try{let p={"Content-Type":"application/json","X-Shopify-Surface":"skills"};o&&(p["X-Shopify-Client-Name"]=String(o)),a&&(p["X-Shopify-Client-Version"]=String(a)),s&&(p["X-Shopify-Client-Model"]=String(s));let u=JSON.stringify({tool:e,parameters:{skill:fe,skillBundle:"shopify",skillVersion:"1.20.0",...L!==void 0&&{topic:L},...w!==void 0&&{user_prompt:w},...U!==void 0&&{sessionId:U},...V!==void 0&&{toolUseId:V},...ue},result:t,...j(i)});if(process.env.SKILL_TELEMETRY_TEST_MODE==="1"){let{url:me}=b({uri:"/mcp/usage"}),_e=new URL("/mcp/usage",me).toString();process.stderr.write([`[TEST_TELEMETRY_ENDPOINT] ${_e}`,...Object.entries(p).map(([ge,Ee])=>`[TEST_TELEMETRY_HEADER] ${ge}: ${Ee}`),`[TEST_TELEMETRY_BODY] ${u}`,""].join(`
`));return}await Y("/mcp/usage",{method:"POST",headers:p,body:u,instrumentation:{packageVersion:"1.20.0",timestamp:new Date().toISOString()}})}catch{}}n(W,"reportValidation");var Q=".feedback",Qe=1440*60*1e3;function Ze(){let e=process.getuid?.()??0;return k(ze(),`shopify-ai-toolkit-telemetry-${e}`)}n(Ze,"markerDir");function et(e,t){let r=He("sha256").update(t).digest("hex").slice(0,32);return k(e,`${r}${Q}`)}n(et,"markerPath");function tt(e){try{let t=Date.now()-Qe;for(let r of Xe(e)){if(!r.endsWith(Q))continue;let i=k(e,r);try{We(i).mtimeMs<t&&Je(i,{force:!0})}catch{}}}catch{}}n(tt,"pruneStaleMarkers");function rt(e){let t;try{t=Ze(),Ye(t,{recursive:!0,mode:448});let r=Ge(t),i=process.getuid?.();if(r.isSymbolicLink()||!r.isDirectory()||i!==void 0&&r.uid!==i)return!0;try{Be(t,448)}catch{return!0}tt(t)}catch{return!0}try{return Ke(je(et(t,e),"wx",384)),!0}catch(r){return r?.code!=="EEXIST"}}n(rt,"claimOnceMarker");function g(e,t){return e.includes(t)?t:void 0}n(g,"parseEnum");function Z(e){return typeof e=="string"&&e.length>0?e:void 0}n(Z,"nonEmptyFlag");function N(e){return{type:"string",choices:l,description:e}}n(N,"verdictOption");var ee={overall:{type:"string",choices:A,description:"Overall toolkit verdict for this turn"},"docs-context":N("Verdict for docs/search context"),"schema-validation":N("Verdict for schema/code validation"),"api-version":N("Verdict for API version targeting"),codegen:N("Verdict for generated code"),"comment-base64":{type:"string",valueName:"base64",description:`Base64-encoded rationale, decoded and truncated to ${500} chars (base64 keeps arbitrary text inert in the shell)`},"session-id":_["session-id"],"tool-use-id":_["tool-use-id"],...y,...B},nt=[K(["scripts/log_feedback.mjs --overall <up|down|mixed> --docs-context <verdict>"," --schema-validation <verdict> --api-version <verdict> --codegen <verdict>"," --comment-base64 <base64> [--session-id <id>] [--tool-use-id <id>]"," [--model <name>] [--client-name <name>] [--client-version <version>]"],ee),"","Each <verdict> is one of: worked | partial | failed | not_used.","Run once per turn. Without a session id or tool-use id there is no dedupe","key, so nothing is sent."].join(`
`);function te(){console.error("Usage: scripts/log_feedback.mjs --overall <up|down|mixed> --docs-context <verdict> --schema-validation <verdict> --api-version <verdict> --codegen <verdict> --comment-base64 <base64> [options] (run with --help for details)"),process.exit(1)}n(te,"exitWithUsageHint");var re=(()=>{try{return qe({options:H(ee),allowPositionals:!0})}catch{return}})();re||te();var{values:d}=re;d.help&&(console.log(nt),process.exit(0));v()&&process.exit(0);var ne=g(A,d.overall),oe=g(l,d["docs-context"]),ie=g(l,d["schema-validation"]),se=g(l,d["api-version"]),ae=g(l,d.codegen),z=d["comment-base64"],ot=z===""?"":J(z),ce=ot?.slice(0,500);(!ne||!oe||!ie||!se||!ae||ce===void 0)&&te();var de=h()??Z(d["session-id"]),pe=S()??Z(d["tool-use-id"]),R=M({trigger:C,sessionId:de,toolUseId:pe});R&&rt(R.feedbackId)&&await W("feedback","ok",{model:d.model,clientName:d["client-name"],clientVersion:d["client-version"],sessionId:de,toolUseId:pe,feedbackVersion:1,feedbackId:R.feedbackId,feedbackIdSource:R.feedbackIdSource,trigger:C,overall:ne,docsContext:oe,schemaValidation:ie,apiVersion:se,codegen:ae,comment:ce});process.exit(0);
SHA-256: 09586a1b5d6c935b0080e89a5ec025f00c0533e7b2215a9479fd5eb78b82b177