@oracle-agent/oracle 0.35.38 → 0.35.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-sessions.mjs +13 -13
  3. package/dist/assets/skills/blocked-page-recovery.md +16 -0
  4. package/dist/assets/skills/browser-use.md +19 -0
  5. package/dist/assets/skills/chrome-profile-browser.md +21 -0
  6. package/dist/assets/skills/oracle-agentic-crypto/SKILL.md +27 -0
  7. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  8. package/dist/assets/skills/oracle-x402/SKILL.md +54 -11
  9. package/dist/assets/skills/web-form-filling.md +19 -0
  10. package/dist/assets/skills/web-research.md +17 -0
  11. package/dist/assets/skills/x-read-browser.md +17 -0
  12. package/dist/assets/skills/xurl.md +1 -1
  13. package/dist/bin/desk-server.mjs +30 -30
  14. package/dist/bin/oracle-data-mcp.mjs +17 -13
  15. package/dist/bin/oracle-public-server.mjs +1 -1
  16. package/dist/bin/oracle-route.mjs +26 -14
  17. package/dist/bin/oracle-scan.mjs +4 -4
  18. package/dist/bin/oracle.mjs +11 -10
  19. package/dist/cli/commands/agent-session.mjs +18 -18
  20. package/dist/cli/commands/auth.mjs +20 -17
  21. package/dist/cli/commands/chat.mjs +231 -228
  22. package/dist/cli/commands/data.mjs +5 -5
  23. package/dist/cli/commands/doctor.mjs +1 -1
  24. package/dist/cli/commands/eval.mjs +154 -152
  25. package/dist/cli/commands/extension-policy.mjs +1 -1
  26. package/dist/cli/commands/follow.mjs +57 -19
  27. package/dist/cli/commands/governance-prepare.mjs +1 -1
  28. package/dist/cli/commands/init.mjs +2 -2
  29. package/dist/cli/commands/model.mjs +235 -232
  30. package/dist/cli/commands/public.mjs +3 -3
  31. package/dist/cli/commands/route.mjs +1 -1
  32. package/dist/cli/commands/setup.mjs +62 -59
  33. package/dist/cli/commands/signer.mjs +4 -4
  34. package/dist/cli/commands/upgrade.mjs +2 -2
  35. package/dist/cli/commands/x402.mjs +19 -0
  36. package/dist/control-plane/index.mjs +1 -1
  37. package/dist/data/desk-data.mjs +28 -28
  38. package/dist/index.mjs +46 -46
  39. package/dist/local-signer/runtime.mjs +6 -6
  40. package/dist/teams/index.mjs +6 -5
  41. package/dist/tui/standalone-client.mjs +84 -82
  42. package/package.json +1 -1
  43. package/public/eval-report.json +2 -2
  44. package/public/oracle-splash/docs/browser-and-web/index.html +32 -0
  45. package/public/oracle-splash/docs/connectors/index.html +18 -0
  46. package/public/oracle-splash/docs/docs.css +21 -0
  47. package/public/oracle-splash/docs/docs.js +108 -0
  48. package/public/oracle-splash/docs/getting-started/index.html +36 -0
  49. package/public/oracle-splash/docs/index.html +26 -0
  50. package/public/oracle-splash/docs/reference/index.html +20 -0
  51. package/public/oracle-splash/docs/security/index.html +19 -0
  52. package/public/oracle-splash/docs/using-oracle/index.html +32 -0
  53. package/public/oracle-splash/download/index.html +2584 -0
  54. package/public/oracle-splash/index.html +313 -942
  55. package/public/oracle-splash/pricing/index.html +2570 -0
  56. package/public/oracle-splash/security/index.html +2574 -0
  57. package/public/oracle-splash/what-it-does/index.html +2608 -0
  58. package/public/oracle-splash/where-it-works/index.html +2635 -0
  59. package/server.json +2 -2
  60. package/dist/assets/equities-fixtures/bridge_routes.json +0 -159
@@ -7,12 +7,12 @@ var Za=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r
7
7
  `),a=[],c=new Map,d=new Set,l=new Set;for(let f=0;f<u.length;f+=1){let p=u[f];if(Buffer.byteLength(p,"utf8")>Os)return{ok:!1,reason:"event-size-limit",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};let w;try{w=JSON.parse(p)}catch{return{ok:!1,reason:"malformed-json",line:f+1,count:a.length,workflows:c.size,events:a,paths:n}}let g;try{g=Kd(w)}catch(A){return{ok:!1,reason:"event-invalid",line:f+1,detail:String(A?.message||A),count:a.length,workflows:c.size,events:a,paths:n}}if(d.has(g.id))return{ok:!1,reason:"duplicate-event-id",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};let h=Jn(g),y=Hn(g.tenantId,g.workflowId,g.idempotencyKey);if(l.has(y))return{ok:!1,reason:"duplicate-idempotency-key",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};let b=c.get(h)??null,S=String(BigInt(b?.sequence??"0")+1n);if(g.sequence!==S)return{ok:!1,reason:"sequence-gap",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};if(g.previousEventHash!==(b?.eventHash??null))return{ok:!1,reason:"previous-event-hash-mismatch",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};if(b&&Date.parse(g.recordedAt)<Date.parse(b.recordedAt))return{ok:!1,reason:"recorded-at-regression",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};d.add(g.id),l.add(y),c.set(h,g),a.push(g)}let m=new Map;for(let f of a){let p=Jn(f);m.has(p)||m.set(p,[]),m.get(p).push(f)}for(let[f,p]of m)try{Rr(p)}catch(w){return{ok:!1,reason:"workflow-invalid",streamKey:f,detail:String(w?.message||w),count:a.length,workflows:c.size,events:a,heads:c,paths:n}}if(r){if(!it(n.checkpoint))return a.length===0?{ok:!0,count:0,workflows:0,events:a,heads:c,paths:n,empty:!0}:{ok:!1,reason:"checkpoint-missing",recoverable:!0,count:a.length,workflows:c.size,events:a,heads:c,paths:n};let f;try{Br(n.checkpoint,"checkpoint");let g=Pr(n.checkpoint,"utf8");if(!g.endsWith(`
8
8
  `))throw new B("checkpoint truncated","CHECKPOINT_INVALID");f=JSON.parse(g),Yd(f)}catch(g){return{ok:!1,reason:"checkpoint-invalid",recoverable:!1,detail:String(g?.message||g),count:a.length,workflows:c.size,events:a,heads:c,paths:n}}let p=Ts(n.ledger,a,i),w=Zd(f,p);if(!w.ok)return{...w,count:a.length,workflows:c.size,events:a,heads:c,paths:n}}return{ok:!0,count:a.length,workflows:c.size,events:a,heads:c,paths:n,raw:i,lastEventHash:a.at(-1)?.eventHash??null}}catch(o){return{ok:!1,reason:"io-error",detail:String(o?.message||o),count:0,workflows:0,events:[],paths:n}}}function ef(e){let t={ok:e.ok,count:e.count,workflows:e.workflows,...e.reason?{reason:e.reason}:{},...e.line?{line:e.line}:{},...e.detail?{detail:e.detail}:{},...e.recoverable!==void 0?{recoverable:e.recoverable}:{},...e.lastEventHash!==void 0?{lastEventHash:e.lastEventHash}:{}};return se(t)}function tf(e){if(!Number.isSafeInteger(e)||e<=0)return"invalid";try{return process.kill(e,0),"active"}catch(t){return t?.code==="ESRCH"?"stale":"active"}}function Cs(e){let{lock:t}=at(e);Br(t,"lock");let r=JSON.parse(Pr(t,"utf8"));if(Se(r,Ss,Ss,"workflow ledger lock"),r.schemaVersion!==Yn)throw new B("lock schema mismatch","LOCK_INVALID");if(V(r.token,"workflow ledger lock.token"),!Number.isSafeInteger(r.pid)||r.pid<=0)throw new B("lock pid invalid","LOCK_INVALID");return Pe(r.createdAt,"workflow ledger lock.createdAt"),r}function _s({path:e}={}){let{lock:t}=at(e);if(!it(t))return se({state:"unlocked",lock:null});try{let r=Cs(e);return se({state:tf(r.pid),lock:r})}catch(r){return se({state:"invalid",lock:null,error:String(r?.message||r)})}}function rf(e){let t=at(e);Vd(t.directory);let r={schemaVersion:Yn,token:As(),pid:process.pid,createdAt:new Date().toISOString()},n;try{return n=Fr(t.lock,ce.O_WRONLY|ce.O_CREAT|ce.O_EXCL|(ce.O_NOFOLLOW||0),384),Zn(n,Buffer.from(`${JSON.stringify(r)}
9
9
  `,"utf8")),Dr(n),st(n),n=void 0,Kn(t.lock,384),jr(t.directory),r}catch(o){throw n!==void 0&&st(n),o}}async function nf(e,t){if(!Number.isSafeInteger(t)||t<0||t>12e4)throw new B("lockTimeoutMs out of bounds","LOCK_TIMEOUT_INVALID");let r=Date.now();for(;;)try{return rf(e)}catch(n){if(n?.code!=="EEXIST")throw n;if(Date.now()-r>=t){let o=_s({path:e});throw new B(`ledger busy (${o.state} lock); explicit token-bound recovery is required for stale locks`,"LEDGER_BUSY",o)}await Ud(10)}}function $r(e,t){let r=Cs(e);if(r.token!==t||r.pid!==process.pid)throw new B("lock fencing token no longer owned","LOCK_FENCED");return!0}function of(e,t){let r=at(e);$r(e,t),vs(r.lock),jr(r.directory)}function sf(e){return{tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,idempotencyKey:e.idempotencyKey,occurredAt:e.occurredAt,recordedAt:e.recordedAt,type:e.type,external:e.external,evidence:e.evidence,data:e.data}}async function Qn(e={}){Se(e,["path","event","lockTimeoutMs","maxBytes"],["path","event"],"appendWorkflowEvent options");let t=at(e.path).ledger,r=Vn(e.event),n=e.lockTimeoutMs??ks,o=e.maxBytes??Xn,i=await nf(t,n),s=null;try{$r(t,i.token);let u=Qd({path:t,maxBytes:o});if(!u.ok)throw new B(`append refused until ledger recovery: ${u.reason}`,"LEDGER_CORRUPT",ef(u));let a=u.events.find(b=>b.tenantId===r.tenantId&&b.workflowId===r.workflowId&&b.idempotencyKey===r.idempotencyKey);if(a){if(ot(sf(a))!==ot(r))throw new B("idempotency key reused with different payload","IDEMPOTENCY_CONFLICT");return se({event:a,duplicate:!0})}if(u.events.some(b=>b.id===r.id))throw new B("event id already exists","EVENT_ID_CONFLICT");let c=Ne(r.tenantId,r.workflowId),d=u.heads.get(c)??null,l=Lr({...r,sequence:String(BigInt(d?.sequence??"0")+1n),previousEventHash:d?.eventHash??null}),m=u.events.filter(b=>Ne(b.tenantId,b.workflowId)===c);Rr([...m,l]);let f=Buffer.from(`${JSON.stringify(l)}
10
- `,"utf8");if(f.length>Os)throw new B("event exceeds size limit","EVENT_SIZE_LIMIT");let p=Buffer.concat([u.raw??Buffer.alloc(0),f]);if(p.length>o)throw new B("append would exceed ledger size limit","LEDGER_SIZE_LIMIT");let w=[...u.events,l],g=Ns(t,w,p),h=it(t);h&&Br(t,"ledger"),$r(t,i.token);let y;try{y=Jd(t),Zn(y,f),Dr(y)}finally{y!==void 0&&st(y)}return Kn(t,384),h||jr(Is(t)),$r(t,i.token),Xd(t,w,p,g),se({event:l,duplicate:!1})}catch(u){throw s=u,u}finally{try{of(t,i.token)}catch(u){if(s===null)throw u}}}var qy=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),My=Object.freeze(["read","simulate"]);var Hy=1440*60;var Xy=Object.freeze(["privkey","wif","xprv","seed"]);var Zy=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),Qy=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);var eo=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),nb=Object.freeze(Object.fromEntries(eo.map((e,t)=>[e,Object.freeze(t+1<eo.length?[eo[t+1]]:[])])));var af=Object.freeze({intent:"draft",quote_comparison:"draft",simulation:"draft",prepared:"checked",approval:"approval",signed:"signed",broadcast:"submitted",settlement:"finalized",balance_delta:"compensated",position:"compensated"});import{createHash as pf,randomBytes as mf}from"node:crypto";var cf=Object.freeze(["owner","operator","agent","viewer"]),uf=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),lf=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),Pb=Object.freeze(["owner"]),Bb=Object.freeze({ALLOW_ROLE_PERMISSION:"allow.role_permission",DENY_MISSING_CONTEXT:"deny.missing_context",DENY_INVALID_CONTEXT:"deny.invalid_context",DENY_INVALID_REQUEST:"deny.invalid_request",DENY_UNKNOWN_RESOURCE:"deny.unknown_resource",DENY_UNKNOWN_ACTION:"deny.unknown_action",DENY_UNBOUND_OBJECT:"deny.unbound_object",DENY_TENANT_MISMATCH:"deny.tenant_mismatch",DENY_RESOURCE_MISMATCH:"deny.resource_mismatch",DENY_ROLE_PERMISSION:"deny.role_permission",DENY_POLICY_NOT_APPROVER:"deny.policy_not_approver"}),Db=new Set(cf),Fb=new Set(uf),jb=new Set(Object.values(lf));var df=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/;var ff=Object.freeze({owner:Object.freeze(["tenant:read","tenant:manage","config:read","config:manage","policy:read","policy:manage","grant:read","grant:create","grant:update","grant:delete","grant:manage","workflow:read","workflow:create","workflow:update","workflow:delete","workflow:cancel","workflow:approve","trade:read","trade:prepare","receipt:read","receipt:export","audit:read","audit:export","telemetry:read","telemetry:create","telemetry:export","context:read","context:create","context:update","context:delete","context:manage","context:export","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:delete","lifecycle:manage","lifecycle:approve","lifecycle:export"]),operator:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","workflow:cancel","trade:read","trade:prepare","receipt:read","audit:read","telemetry:read","telemetry:create","context:read","context:create","context:update","context:delete","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:manage"]),agent:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","trade:read","trade:prepare","receipt:read","telemetry:create","context:read","context:create","context:update","lifecycle:read"]),viewer:Object.freeze(["tenant:read","config:read","grant:read","workflow:read","trade:read","receipt:read","audit:read","telemetry:read","context:read","lifecycle:read"])}),qb=Object.freeze(Object.fromEntries(Object.entries(ff).map(([e,t])=>[e,Object.freeze([...t])]))),qr=class extends Error{constructor(t,r="invalid-context"){super(t),this.name="TenantContextError",this.code=r}};function Ls(e,t){let r=String(e??"").trim();if(!df.test(r))throw new qr(`${t} is invalid`);return r}function Rs(e,t){let r=Ls(e,"tenantId"),n=Ls(t,"workflowId");if(r.includes(":")||n.includes(":"))throw new qr("stream key parts must not contain ':'","invalid-stream-key");return`${r}:${n}`}var js=1,qs=1,wf=Object.freeze(["succeeded","denied","invalid","failed","cancelled","timed_out","unavailable","skipped"]),hf=Object.freeze(["workflow","task","intent","plan","run","event","eval"]),Ms=Object.freeze(["taskId","intentId","planId","runId","eventId"]);function $s(e,t){return Rs(e,t)}var nr=Object.freeze({maxAttributes:24,maxKeyLength:48,maxStringLength:256,maxArrayLength:8}),gf=new Set(wf),yf=new Set(hf),bf=new Set(Ms),Ef=/^[0-9a-f]{32}$/,Ps=/^[0-9a-f]{16}$/;var xf=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,95}$/,Sf=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/,Af=/^[A-Za-z][A-Za-z0-9_.-]*$/,vf=Object.freeze(["authorization","bearer","cookie","credential","password","passphrase","secret","token","privatekey","privkey","seed","mnemonic","keystore","signature","prompt","systemmessage","usermessage","assistantmessage","rawtransaction","signedtransaction","serializedtransaction","transactionbytes","calldata","callbytes","inputdata"]),If=/(?:^|\s)Bearer\s+\S+|-----BEGIN [A-Z ]*PRIVATE KEY-----|\bxprv[0-9A-Za-z]{20,}\b|\bsk-[A-Za-z0-9_-]{16,}\b|[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{16,}/i,kf=/(?:0x)?[0-9a-fA-F]{66,}/,Of=/[A-Za-z0-9+/=_-]{96,}/,F=class extends Error{constructor(t,r="invalid-telemetry"){super(t),this.name="WorkflowTelemetryError",this.code=r}};function Mr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Hr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))Hr(t)}return e}function to(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(to).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${to(e[t])}`).join(",")}}`}function Hs(e){return pf("sha256").update(to(e)).digest("hex")}function Bs(e,t,r){let n=r?r(e,t):mf(e).toString("hex");return String(n??"").trim().toLowerCase()}function zs(e={}){if(e==null)return{};if(!Mr(e))throw new F("correlation must be a plain object");let t=Object.keys(e).filter(n=>!bf.has(n));if(t.length)throw new F(`unknown correlation fields: ${t.sort().join(", ")}`);let r={};for(let n of Ms){if(e[n]==null)continue;let o=String(e[n]).trim();if(!Sf.test(o))throw new F(`${n} is invalid`);r[n]=o}return r}function Ws(e){if(!Mr(e)||e.schemaVersion!==js)throw new F("trace context version is invalid","invalid-trace");if(!Ef.test(e.traceId||"")||!Ps.test(e.spanId||"")||/^0+$/.test(e.traceId)||/^0+$/.test(e.spanId))throw new F("trace or span id is invalid","invalid-trace");if(e.parentSpanId!==null&&!Ps.test(e.parentSpanId||""))throw new F("parent span id is invalid","invalid-trace");if(typeof e.sampled!="boolean")throw new F("sampled must be boolean","invalid-trace");return zs(e.correlation),e}function Tf({traceId:e,spanId:t,parentSpanId:r=null,sampled:n=!1,correlation:o={}}={},{idFactory:i}={}){let s=e==null?Bs(16,"trace",i):String(e).trim().toLowerCase(),u=t==null?Bs(8,"span",i):String(t).trim().toLowerCase(),a=r==null?null:String(r).trim().toLowerCase(),c=Hr({schemaVersion:js,traceId:s,spanId:u,parentSpanId:a,sampled:n===!0,correlation:zs(o)});return Ws(c)}var Us=Tf;var Wb=Object.freeze({taskId:"x-oracle-task-id",intentId:"x-oracle-intent-id",planId:"x-oracle-plan-id",runId:"x-oracle-run-id",eventId:"x-oracle-event-id"});function Ds(e){let t=String(e).replace(/[^a-z0-9]/gi,"").toLowerCase();return vf.some(r=>t.includes(r))}function Nf(e){return If.test(e)||kf.test(e)||Of.test(e)?{value:"[REDACTED]",redacted:!0,truncated:!1}:e.length>nr.maxStringLength?{value:`${e.slice(0,nr.maxStringLength-1)}\u2026`,redacted:!1,truncated:!0}:{value:e,redacted:!1,truncated:!1}}function Vs(e){if(typeof e=="string")return Nf(e);if(typeof e=="boolean")return{value:e,redacted:!1,truncated:!1};if(typeof e=="number"&&Number.isFinite(e))return{value:e,redacted:!1,truncated:!1};if(Array.isArray(e)){let t=e.slice(0,nr.maxArrayLength),r=[],n=!1,o=e.length>t.length;for(let i of t){if(!["string","boolean","number"].includes(typeof i))return null;let s=Vs(i);if(!s)return null;r.push(s.value),n||=s.redacted,o||=s.truncated}return{value:r,redacted:n,truncated:o}}return null}function Cf(e={}){if(!Mr(e))throw new F("telemetry attributes must be a plain object");let t={},r=0,n=0,o=0,i=Object.keys(e).sort();for(let s of i){if(Object.keys(t).length>=nr.maxAttributes){n+=1;continue}if(s.length>nr.maxKeyLength||!Af.test(s)||Ds(s)){n+=1,Ds(s)&&(r+=1);continue}let u=Vs(e[s]);if(!u){n+=1;continue}t[s]=u.value,u.redacted&&(r+=1),u.truncated&&(o+=1)}return Hr({attributes:t,redactedCount:r,droppedCount:n,truncatedCount:o})}function Fs(e,t){if(!Number.isSafeInteger(e)||e<0)throw new F(`${t} must be a non-negative integer milliseconds value`);return e}function _f(e){if(e==null)return null;let t=String(e).trim();if(!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(t))throw new F("outcomeCode is invalid");return t}function Lf({streamKey:e,tenantId:t,workflowId:r,sourceEvent:n}){let o=e??n?.streamKey??null,i=t??n?.tenantId??null,s=r??n?.workflowId??null;if(o!=null){let u=String(o).trim();if(i!=null&&s!=null){let a=$s(i,s);if(u!==a)throw new F("streamKey must equal tenantId:workflowId","invalid-stream-key");return a}if(!/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}:[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/.test(u)||u.split(":").length!==2)throw new F("streamKey must be tenantId:workflowId","invalid-stream-key");return u}return i!=null&&s!=null?$s(i,s):null}function Rf({trace:e,name:t,kind:r,diagnosticOutcome:n=null,outcome:o=null,outcomeCode:i=null,startedAt:s,endedAt:u,attributes:a,authority:c,sourceEvent:d=null,streamKey:l=null,tenantId:m=null,workflowId:f=null}){Ws(e);let p=String(t??"").trim();if(!xf.test(p))throw new F("workflow telemetry name is invalid");if(!yf.has(r))throw new F("workflow telemetry kind is invalid");let w=c==="ledger_projection"?o:n;if(!gf.has(w))throw new F("workflow telemetry outcome is invalid");let g=Fs(s,"startedAt"),h=Fs(u,"endedAt");if(h<g)throw new F("endedAt must not be before startedAt");let y=Cf(a),b=Lf({streamKey:l,tenantId:m,workflowId:f,sourceEvent:d}),S={schemaVersion:qs,recordType:"oracle.workflow.telemetry",authority:c,streamKey:b,trace:{traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,sampled:e.sampled},correlation:{...e.correlation},name:p,kind:r,...c==="ledger_projection"?{outcome:o,sourceEvent:{...d}}:{diagnosticOutcome:n},outcomeCode:_f(i),startedAt:g,endedAt:h,durationMs:h-g,attributes:{...y.attributes},attributePolicy:{redactedCount:y.redactedCount,droppedCount:y.droppedCount,truncatedCount:y.truncatedCount}};return Hr({...S,recordId:Hs(S)})}function ro({trace:e,name:t,kind:r="workflow",outcome:n,outcomeCode:o=null,startedAt:i,endedAt:s,attributes:u={},tenantId:a=null,workflowId:c=null,streamKey:d=null}={}){return Rf({trace:e,name:t,kind:r,diagnosticOutcome:n,outcomeCode:o,startedAt:i,endedAt:s,attributes:u,authority:"diagnostic",tenantId:a,workflowId:c,streamKey:d})}function no(e){if(!Mr(e)||!Object.isFrozen(e)||e.schemaVersion!==qs||e.recordType!=="oracle.workflow.telemetry")return!1;let{recordId:t,...r}=e;return typeof t=="string"&&t===Hs(r)}function oo({exporter:e=null}={}){if(e!=null&&typeof e!="function"&&typeof e?.export!="function")throw new F("exporter must be a function or expose export(record)");let t=typeof e=="function"?e:e?.export?.bind(e);return Object.freeze({exporterConfigured:!!t,defaultExporter:"none",async emit(r){let n=no(r)?r:ro(r);if(!t)return Object.freeze({record:n,exported:!1,exporterFailed:!1});try{return await t(n),Object.freeze({record:n,exported:!0,exporterFailed:!1})}catch{return Object.freeze({record:n,exported:!1,exporterFailed:!0})}}})}var $f="ORACLE_LEDGER_DUAL_WRITE",Js=/^[a-f0-9]{64}$/,Pf=/^0x[a-f0-9]{64}$/,Bf=Object.freeze({"workflow.cancelled":"cancelled","workflow.failed":"failed"});function Lt(e,t){return String(e??"").slice(0,t)}function Ks(e=process.env){return String(e?.[$f]??"")==="1"}function Gs({path:e,tenantId:t="local-signer",nowMs:r=Date.now,onError:n=null,telemetry:o=null,append:i=Qn}={}){if(typeof e!="string"||e.trim().length===0)throw new Error("ledger observer requires an explicit ledger path");if(typeof i!="function")throw new Error("ledger observer requires an append function");let s=typeof n=="function"?n:()=>{},u=new Map,a=Promise.resolve(),c=()=>new Date(r()).toISOString();function d(f,p,w){if(!(!o||typeof o.emit!="function"))try{let g=r(),h=ro({trace:f.trace,name:p,kind:"workflow",outcome:Bf[p]??"succeeded",startedAt:g,endedAt:g,attributes:w,tenantId:t,workflowId:f.workflowId});a=a.then(()=>o.emit(h)).catch(y=>{s(`signer telemetry emit failed: ${Lt(y?.message||y,200)}`)})}catch(g){s(`signer telemetry record failed: ${Lt(g?.message||g,200)}`)}}function l(f,p,{external:w=!1,source:g="local-signer",reference:h=null,data:y={}}={}){let b=c(),S={tenantId:t,id:`${f.workflowId}:${p}`,workflowId:f.workflowId,idempotencyKey:`${f.workflowId}:${p}`,occurredAt:b,recordedAt:b,type:p,external:w,evidence:{status:"verified",source:w?"external":g,reference:`${w?`${g}:`:""}${h??`${p}:${f.workflowId}`}`},data:y};return a=a.then(()=>i({path:e,event:S})).catch(A=>{s(`workflow ledger dual-write failed for ${p}: ${Lt(A?.message||A,200)}`)}),d(f,p,{digest:f.digest}),a}function m(f){let p=String(f??"").toLowerCase();return Js.test(p)?u.get(p)??null:null}return Object.freeze({queued({digest:f,createdAtMs:p}={}){let w=String(f??"").toLowerCase();if(!Js.test(w))return s("ledger observer: queued without a valid artifact digest"),a;let g=Number.isFinite(Number(p))?Number(p):r(),h={workflowId:`signer-${w}-${g}`,digest:w,trace:Us()};return u.set(w,h),l(h,"workflow.drafted",{source:"local-signer-queue",reference:`artifact:${w}`,data:{intentSpecId:`${h.workflowId}:intent`}}),l(h,"workflow.checked",{source:"local-signer-policy",reference:`artifact:${w}`,data:{checksPassed:!0}}),l(h,"workflow.approval_requested",{source:"local-signer-queue",reference:`artifact:${w}`}),a},denied({digest:f}={}){let p=m(f);return p&&(u.delete(p.digest),l(p,"workflow.cancelled",{source:"owner-ack",reference:`deny:${p.digest}`})),a},approved({digest:f,channel:p="owner-ack"}={}){let w=m(f);return w&&l(w,"workflow.approval_granted",{external:!0,source:p,reference:`ack:${w.digest}`}),a},executed({digest:f,owner:p=null,result:w=null}={}){let g=m(f);if(!g)return a;u.delete(g.digest),l(g,"workflow.signed",{external:!0,reference:`signed:${g.digest}`,data:{artifactHash:g.digest,signer:Lt(p||"owner-wallet",256)}});let h=w?.hash??w?.txHash??w?.transactionHash??w?.signature??null,y=typeof h=="string"?h.trim().toLowerCase():null;return y&&Pf.test(y)?l(g,"workflow.submitted",{external:!0,reference:`submitted:${g.digest}`,data:{transactionHash:y,endpoint:"local-signer-broadcast"}}):h&&l(g,"workflow.annotated",{reference:`submission:${g.digest}`,data:{note:"non-evm-submission-reference",reference:Lt(h,512)}}),a},failed({digest:f,reason:p=""}={}){let w=m(f);return w&&(u.delete(w.digest),l(w,"workflow.failed",{reference:`failed:${w.digest}`,data:{reason:Lt(p,300)}})),a},flush(){return a}})}import{appendFileSync as Df,existsSync as Ff,mkdirSync as jf,renameSync as qf,statSync as Mf}from"node:fs";import{dirname as Hf}from"node:path";var zf="ORACLE_TELEMETRY_JSONL",Wf=32*1024*1024,Ys=4096;function Uf({path:e,maxBytes:t=Wf}={}){if(typeof e!="string"||e.trim().length===0)throw new F("jsonl exporter requires an explicit file path","invalid-exporter-path");let r=Number(t);if(!Number.isFinite(r)||r<Ys)throw new F(`jsonl exporter maxBytes must be >= ${Ys}`,"invalid-exporter-cap");let n=e;return Object.freeze({path:n,maxBytes:r,export(o){if(!no(o))throw new F("jsonl exporter accepts only sealed workflow telemetry records","invalid-record");let i=`${JSON.stringify(o)}
11
- `;jf(Hf(n),{recursive:!0,mode:448}),Ff(n)&&Mf(n).size+Buffer.byteLength(i)>r&&qf(n,`${n}.1`),Df(n,i,{mode:384})}})}function Xs(e=process.env,{maxBytes:t}={}){let r=String(e?.[zf]??"").trim();return r?oo({exporter:Uf({path:r,...t===void 0?{}:{maxBytes:t}})}):oo({})}import{createCipheriv as e0,createDecipheriv as Vf,randomBytes as Jf,scryptSync as Kf}from"node:crypto";import D from"node:fs";import Rt from"node:path";var Gf="ORACLE-LOCAL-VAULT",Yf=1,Wr=Object.freeze({N:1<<17,r:8,p:1}),Xf=256*1024*1024,Zf=16*1024;function zr(e,t,r,{max:n=t}={}){if(typeof e!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`local-vault: invalid ${r} encoding`);let o=Buffer.from(e,"base64");if(o.toString("base64")!==e||o.length<t||o.length>n)throw new Error(`local-vault: invalid ${r} length`);return o}function Qf(e,t,r=Wr){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");if(n.includes("\0"))throw new Error("local-vault: refusing zeroed passphrase material");return Kf(n,t,32,{...r,maxmem:Xf})}function Zs(e,t){if(e?.magic!==Gf||e?.version!==Yf)throw new Error("local-vault: unsupported vault file");if(e?.kdf?.name!=="scrypt"||e?.cipher?.name!=="aes-256-gcm")throw new Error("local-vault: unsupported cryptography");if(e.kdf.N!==Wr.N||e.kdf.r!==Wr.r||e.kdf.p!==Wr.p)throw new Error("local-vault: unsupported KDF parameters");if(Object.keys(e.kdf).sort().join(",")!=="N,name,p,r,salt"||Object.keys(e.cipher).sort().join(",")!=="iv,name")throw new Error("local-vault: unexpected cryptography field");if(!e.meta||Object.keys(e.meta).some(l=>!["address","addresses","kind","createdAt"].includes(l))||String(e.meta.kind||"").length>16||String(e.meta.address||"").length>128||JSON.stringify(e.meta.addresses||{}).length>1024||!Number.isFinite(Date.parse(e.meta.createdAt)))throw new Error("local-vault: invalid metadata");let r=["magic","version","kdf","cipher","meta","ciphertext","tag"];if(Object.keys(e).some(l=>!r.includes(l)))throw new Error("local-vault: unexpected vault field");let n=zr(e.kdf.salt,32,"salt"),o=zr(e.cipher.iv,12,"iv"),i=zr(e.tag,16,"tag"),s=zr(e.ciphertext,1,"ciphertext",{max:Zf}),{ciphertext:u,tag:a,...c}=e,d=Qf(t,n);try{let l=Vf("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(c))),l.setAuthTag(i),Buffer.concat([l.update(s),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function ep(e){if(!e.isFile())throw new Error("local-vault: secret source must be a regular file");if(e.uid!==process.getuid?.())throw new Error("local-vault: secret source must be owned by this user");if(e.nlink!==1)throw new Error("local-vault: refusing hard-linked secret source");if((e.mode&63)!==0)throw new Error("local-vault: secret source must be owner-only (0600)")}function tp(e){let t=Rt.dirname(e),r=D.lstatSync(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("local-vault: unsafe destination directory");if(r.uid!==process.getuid?.())throw new Error("local-vault: destination directory must be owned by this user");if((r.mode&63)!==0)throw new Error("local-vault: destination directory must be owner-only (0700)");try{let n=D.lstatSync(e);if(n.isSymbolicLink())throw new Error("local-vault: refusing symlink destination");if(!n.isFile()||n.uid!==process.getuid?.()||n.nlink!==1)throw new Error("local-vault: unsafe destination file");if(n.dev!==r.dev)throw new Error("local-vault: destination device mismatch")}catch(n){if(n.code!=="ENOENT")throw n}}function R(e){let t;try{t=D.openSync(e,D.constants.O_RDONLY|D.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=D.fstatSync(t);if(ep(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=D.lstatSync(e);if(n.isSymbolicLink()||n.dev!==r.dev||n.ino!==r.ino)throw new Error("local-vault: secret source changed or is too large");return D.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{D.closeSync(t)}}function Qs(e){return JSON.parse(R(e))}function Ae(e,t){D.mkdirSync(Rt.dirname(e),{recursive:!0,mode:448}),tp(e);let r=Rt.join(Rt.dirname(e),`.${Rt.basename(e)}.${process.pid}.${Jf(6).toString("hex")}.tmp`);try{let n=D.openSync(r,D.constants.O_CREAT|D.constants.O_EXCL|D.constants.O_WRONLY|D.constants.O_NOFOLLOW,384);try{D.writeFileSync(n,String(t)),D.fsyncSync(n)}finally{D.closeSync(n)}D.renameSync(r,e),D.chmodSync(e,384);let o=D.openSync(Rt.dirname(e),"r");try{D.fsyncSync(o)}finally{D.closeSync(o)}}catch(n){try{D.unlinkSync(r)}catch{}throw n}}var ea=/^0x[0-9a-fA-F]+$/,rp=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}});function np(e){let t=process.env[`ORACLE_PRIVATE_RELAY_${Number(e)}`];if(!t)return null;let r=t.split(",").map(n=>n.trim()).filter(Boolean);return r.length?r:null}function op(e,{requirePrivate:t=!1}={}){let r=Number(e);if(!Number.isInteger(r))throw new Error("resolvePrivateRelay: chainId must be an integer");let n=rp[r]||{name:`chain-${r}`,mode:"public-only",endpoints:[]},o=np(r),i=o||n.endpoints,s=o&&n.mode==="public-only"?"mempool-private":n.mode,u=i.length>0&&s!=="public-only";if(t&&!u)throw new Error(`private relay: no keyless private endpoint for chain ${r} (${n.name}); set ORACLE_PRIVATE_RELAY_${r} to force one, or allow public fallback`);return{chainId:r,name:n.name,mode:s,endpoints:[...i],source:o?"env":"builtin",hasPrivate:u}}async function ta(e,{chainId:t,requirePrivate:r=!1,allowPublicFallback:n=!0,fetchImpl:o,timeoutMs:i=8e3}={}){if(typeof e!="string"||!ea.test(e))throw new Error("submitPrivate: signedRawTx must be a 0x-hex string");let s=op(t,{requirePrivate:r}),u=o||globalThis.fetch;if(!u)throw new Error("submitPrivate: no fetch implementation available");let a=[];for(let c of s.endpoints){let d=new AbortController,l=setTimeout(()=>d.abort(),i);try{let m=await u(c,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_sendRawTransaction",params:[e]}),signal:d.signal}),f=await m.text(),p=null;try{p=JSON.parse(f)}catch{}if(p&&p.result&&ea.test(p.result))return{hash:p.result,endpoint:c,mode:s.mode,chainId:s.chainId,fellBack:!1};a.push({endpoint:c,error:p&&p.error&&p.error.message||`http ${m.status}`})}catch(m){a.push({endpoint:c,error:String(m&&m.message||m).slice(0,160)})}finally{clearTimeout(l)}}if(n&&!r)return{fellBack:!0,mode:s.mode,chainId:s.chainId,attempts:a};throw new Error(`submitPrivate: all private endpoints failed for chain ${s.chainId} (${a.map(c=>`${c.endpoint}:${c.error}`).join("; ")||"none configured"})`)}import{createHmac as sp,randomBytes as ap,timingSafeEqual as cp}from"node:crypto";import te from"node:fs";import ct from"node:path";import{homedir as io}from"node:os";import{join as so}from"node:path";var ra=process.env.ORACLE_PUBLIC_DESKTOP==="1",ip=ra?process.env.ORACLE_CONFIG_DIR||so(io(),".config","oracle"):so(io(),".config","oracle"),a0=ra?ip:so(io(),".config","mad-desk");var f0="0".repeat(64),p0=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});function Ur(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(Ur).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+Ur(e[r])).join(",")+"}"}var m0=Promise.resolve();function ut(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=s=>{try{return te.realpathSync(s)}catch{return ct.resolve(s)}},n=r(ct.dirname(ct.resolve(e))),o=r(ct.dirname(ct.resolve(t))),i=(s,u)=>u===s||u.startsWith(s+ct.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var up=864e5,ue=(e,t)=>sp("sha256",t).update(Ur(e)).digest("hex"),Ce=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&cp(r,n)},lp=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function dp(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(e.integrity.mac,ue(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function Jr(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=R(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(r)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!Ce(n?.integrity?.mac,ue(n?.marker,t)))throw new Error("policy: sequence anchor integrity failed");return{sequence:Number(n?.marker?.policySequence||0),policyMac:n?.marker?.policyMac??null,present:!0,ledgerInitialized:n?.marker?.ledgerInitialized===!0}}function fp(e,t,r,n=null,{ledgerInitialized:o}={}){if(n==null||!String(n))throw new Error("policy: sequence anchor must bind the sealed policy MAC");let i=o===!0;if(o===void 0)try{let u=Jr(e,r);i=u.present&&u.ledgerInitialized===!0}catch{i=!1}let s={policySequence:Number(t),policyMac:String(n)};i&&(s.ledgerInitialized=!0),Ae(e,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(s,r)}})+`
10
+ `,"utf8");if(f.length>Os)throw new B("event exceeds size limit","EVENT_SIZE_LIMIT");let p=Buffer.concat([u.raw??Buffer.alloc(0),f]);if(p.length>o)throw new B("append would exceed ledger size limit","LEDGER_SIZE_LIMIT");let w=[...u.events,l],g=Ns(t,w,p),h=it(t);h&&Br(t,"ledger"),$r(t,i.token);let y;try{y=Jd(t),Zn(y,f),Dr(y)}finally{y!==void 0&&st(y)}return Kn(t,384),h||jr(Is(t)),$r(t,i.token),Xd(t,w,p,g),se({event:l,duplicate:!1})}catch(u){throw s=u,u}finally{try{of(t,i.token)}catch(u){if(s===null)throw u}}}var jy=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),qy=Object.freeze(["read","simulate"]);var My=1440*60;var Yy=Object.freeze(["privkey","wif","xprv","seed"]);var Xy=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),Zy=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);var eo=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),rb=Object.freeze(Object.fromEntries(eo.map((e,t)=>[e,Object.freeze(t+1<eo.length?[eo[t+1]]:[])])));var af=Object.freeze({intent:"draft",quote_comparison:"draft",simulation:"draft",prepared:"checked",approval:"approval",signed:"signed",broadcast:"submitted",settlement:"finalized",balance_delta:"compensated",position:"compensated"});import{createHash as pf,randomBytes as mf}from"node:crypto";var cf=Object.freeze(["owner","operator","agent","viewer"]),uf=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),lf=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),$b=Object.freeze(["owner"]),Pb=Object.freeze({ALLOW_ROLE_PERMISSION:"allow.role_permission",DENY_MISSING_CONTEXT:"deny.missing_context",DENY_INVALID_CONTEXT:"deny.invalid_context",DENY_INVALID_REQUEST:"deny.invalid_request",DENY_UNKNOWN_RESOURCE:"deny.unknown_resource",DENY_UNKNOWN_ACTION:"deny.unknown_action",DENY_UNBOUND_OBJECT:"deny.unbound_object",DENY_TENANT_MISMATCH:"deny.tenant_mismatch",DENY_RESOURCE_MISMATCH:"deny.resource_mismatch",DENY_ROLE_PERMISSION:"deny.role_permission",DENY_POLICY_NOT_APPROVER:"deny.policy_not_approver"}),Bb=new Set(cf),Db=new Set(uf),Fb=new Set(Object.values(lf));var df=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/;var ff=Object.freeze({owner:Object.freeze(["tenant:read","tenant:manage","config:read","config:manage","policy:read","policy:manage","grant:read","grant:create","grant:update","grant:delete","grant:manage","workflow:read","workflow:create","workflow:update","workflow:delete","workflow:cancel","workflow:approve","trade:read","trade:prepare","receipt:read","receipt:export","audit:read","audit:export","telemetry:read","telemetry:create","telemetry:export","context:read","context:create","context:update","context:delete","context:manage","context:export","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:delete","lifecycle:manage","lifecycle:approve","lifecycle:export"]),operator:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","workflow:cancel","trade:read","trade:prepare","receipt:read","audit:read","telemetry:read","telemetry:create","context:read","context:create","context:update","context:delete","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:manage"]),agent:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","trade:read","trade:prepare","receipt:read","telemetry:create","context:read","context:create","context:update","lifecycle:read"]),viewer:Object.freeze(["tenant:read","config:read","grant:read","workflow:read","trade:read","receipt:read","audit:read","telemetry:read","context:read","lifecycle:read"])}),jb=Object.freeze(Object.fromEntries(Object.entries(ff).map(([e,t])=>[e,Object.freeze([...t])]))),qr=class extends Error{constructor(t,r="invalid-context"){super(t),this.name="TenantContextError",this.code=r}};function Ls(e,t){let r=String(e??"").trim();if(!df.test(r))throw new qr(`${t} is invalid`);return r}function Rs(e,t){let r=Ls(e,"tenantId"),n=Ls(t,"workflowId");if(r.includes(":")||n.includes(":"))throw new qr("stream key parts must not contain ':'","invalid-stream-key");return`${r}:${n}`}var js=1,qs=1,wf=Object.freeze(["succeeded","denied","invalid","failed","cancelled","timed_out","unavailable","skipped"]),hf=Object.freeze(["workflow","task","intent","plan","run","event","eval"]),Ms=Object.freeze(["taskId","intentId","planId","runId","eventId"]);function $s(e,t){return Rs(e,t)}var nr=Object.freeze({maxAttributes:24,maxKeyLength:48,maxStringLength:256,maxArrayLength:8}),gf=new Set(wf),yf=new Set(hf),bf=new Set(Ms),Ef=/^[0-9a-f]{32}$/,Ps=/^[0-9a-f]{16}$/;var xf=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,95}$/,Sf=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/,Af=/^[A-Za-z][A-Za-z0-9_.-]*$/,vf=Object.freeze(["authorization","bearer","cookie","credential","password","passphrase","secret","token","privatekey","privkey","seed","mnemonic","keystore","signature","prompt","systemmessage","usermessage","assistantmessage","rawtransaction","signedtransaction","serializedtransaction","transactionbytes","calldata","callbytes","inputdata"]),If=/(?:^|\s)Bearer\s+\S+|-----BEGIN [A-Z ]*PRIVATE KEY-----|\bxprv[0-9A-Za-z]{20,}\b|\bsk-[A-Za-z0-9_-]{16,}\b|[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{16,}/i,kf=/(?:0x)?[0-9a-fA-F]{66,}/,Of=/[A-Za-z0-9+/=_-]{96,}/,F=class extends Error{constructor(t,r="invalid-telemetry"){super(t),this.name="WorkflowTelemetryError",this.code=r}};function Mr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Hr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))Hr(t)}return e}function to(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(to).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${to(e[t])}`).join(",")}}`}function Hs(e){return pf("sha256").update(to(e)).digest("hex")}function Bs(e,t,r){let n=r?r(e,t):mf(e).toString("hex");return String(n??"").trim().toLowerCase()}function zs(e={}){if(e==null)return{};if(!Mr(e))throw new F("correlation must be a plain object");let t=Object.keys(e).filter(n=>!bf.has(n));if(t.length)throw new F(`unknown correlation fields: ${t.sort().join(", ")}`);let r={};for(let n of Ms){if(e[n]==null)continue;let o=String(e[n]).trim();if(!Sf.test(o))throw new F(`${n} is invalid`);r[n]=o}return r}function Ws(e){if(!Mr(e)||e.schemaVersion!==js)throw new F("trace context version is invalid","invalid-trace");if(!Ef.test(e.traceId||"")||!Ps.test(e.spanId||"")||/^0+$/.test(e.traceId)||/^0+$/.test(e.spanId))throw new F("trace or span id is invalid","invalid-trace");if(e.parentSpanId!==null&&!Ps.test(e.parentSpanId||""))throw new F("parent span id is invalid","invalid-trace");if(typeof e.sampled!="boolean")throw new F("sampled must be boolean","invalid-trace");return zs(e.correlation),e}function Tf({traceId:e,spanId:t,parentSpanId:r=null,sampled:n=!1,correlation:o={}}={},{idFactory:i}={}){let s=e==null?Bs(16,"trace",i):String(e).trim().toLowerCase(),u=t==null?Bs(8,"span",i):String(t).trim().toLowerCase(),a=r==null?null:String(r).trim().toLowerCase(),c=Hr({schemaVersion:js,traceId:s,spanId:u,parentSpanId:a,sampled:n===!0,correlation:zs(o)});return Ws(c)}var Us=Tf;var zb=Object.freeze({taskId:"x-oracle-task-id",intentId:"x-oracle-intent-id",planId:"x-oracle-plan-id",runId:"x-oracle-run-id",eventId:"x-oracle-event-id"});function Ds(e){let t=String(e).replace(/[^a-z0-9]/gi,"").toLowerCase();return vf.some(r=>t.includes(r))}function Nf(e){return If.test(e)||kf.test(e)||Of.test(e)?{value:"[REDACTED]",redacted:!0,truncated:!1}:e.length>nr.maxStringLength?{value:`${e.slice(0,nr.maxStringLength-1)}\u2026`,redacted:!1,truncated:!0}:{value:e,redacted:!1,truncated:!1}}function Vs(e){if(typeof e=="string")return Nf(e);if(typeof e=="boolean")return{value:e,redacted:!1,truncated:!1};if(typeof e=="number"&&Number.isFinite(e))return{value:e,redacted:!1,truncated:!1};if(Array.isArray(e)){let t=e.slice(0,nr.maxArrayLength),r=[],n=!1,o=e.length>t.length;for(let i of t){if(!["string","boolean","number"].includes(typeof i))return null;let s=Vs(i);if(!s)return null;r.push(s.value),n||=s.redacted,o||=s.truncated}return{value:r,redacted:n,truncated:o}}return null}function Cf(e={}){if(!Mr(e))throw new F("telemetry attributes must be a plain object");let t={},r=0,n=0,o=0,i=Object.keys(e).sort();for(let s of i){if(Object.keys(t).length>=nr.maxAttributes){n+=1;continue}if(s.length>nr.maxKeyLength||!Af.test(s)||Ds(s)){n+=1,Ds(s)&&(r+=1);continue}let u=Vs(e[s]);if(!u){n+=1;continue}t[s]=u.value,u.redacted&&(r+=1),u.truncated&&(o+=1)}return Hr({attributes:t,redactedCount:r,droppedCount:n,truncatedCount:o})}function Fs(e,t){if(!Number.isSafeInteger(e)||e<0)throw new F(`${t} must be a non-negative integer milliseconds value`);return e}function _f(e){if(e==null)return null;let t=String(e).trim();if(!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(t))throw new F("outcomeCode is invalid");return t}function Lf({streamKey:e,tenantId:t,workflowId:r,sourceEvent:n}){let o=e??n?.streamKey??null,i=t??n?.tenantId??null,s=r??n?.workflowId??null;if(o!=null){let u=String(o).trim();if(i!=null&&s!=null){let a=$s(i,s);if(u!==a)throw new F("streamKey must equal tenantId:workflowId","invalid-stream-key");return a}if(!/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}:[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/.test(u)||u.split(":").length!==2)throw new F("streamKey must be tenantId:workflowId","invalid-stream-key");return u}return i!=null&&s!=null?$s(i,s):null}function Rf({trace:e,name:t,kind:r,diagnosticOutcome:n=null,outcome:o=null,outcomeCode:i=null,startedAt:s,endedAt:u,attributes:a,authority:c,sourceEvent:d=null,streamKey:l=null,tenantId:m=null,workflowId:f=null}){Ws(e);let p=String(t??"").trim();if(!xf.test(p))throw new F("workflow telemetry name is invalid");if(!yf.has(r))throw new F("workflow telemetry kind is invalid");let w=c==="ledger_projection"?o:n;if(!gf.has(w))throw new F("workflow telemetry outcome is invalid");let g=Fs(s,"startedAt"),h=Fs(u,"endedAt");if(h<g)throw new F("endedAt must not be before startedAt");let y=Cf(a),b=Lf({streamKey:l,tenantId:m,workflowId:f,sourceEvent:d}),S={schemaVersion:qs,recordType:"oracle.workflow.telemetry",authority:c,streamKey:b,trace:{traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,sampled:e.sampled},correlation:{...e.correlation},name:p,kind:r,...c==="ledger_projection"?{outcome:o,sourceEvent:{...d}}:{diagnosticOutcome:n},outcomeCode:_f(i),startedAt:g,endedAt:h,durationMs:h-g,attributes:{...y.attributes},attributePolicy:{redactedCount:y.redactedCount,droppedCount:y.droppedCount,truncatedCount:y.truncatedCount}};return Hr({...S,recordId:Hs(S)})}function ro({trace:e,name:t,kind:r="workflow",outcome:n,outcomeCode:o=null,startedAt:i,endedAt:s,attributes:u={},tenantId:a=null,workflowId:c=null,streamKey:d=null}={}){return Rf({trace:e,name:t,kind:r,diagnosticOutcome:n,outcomeCode:o,startedAt:i,endedAt:s,attributes:u,authority:"diagnostic",tenantId:a,workflowId:c,streamKey:d})}function no(e){if(!Mr(e)||!Object.isFrozen(e)||e.schemaVersion!==qs||e.recordType!=="oracle.workflow.telemetry")return!1;let{recordId:t,...r}=e;return typeof t=="string"&&t===Hs(r)}function oo({exporter:e=null}={}){if(e!=null&&typeof e!="function"&&typeof e?.export!="function")throw new F("exporter must be a function or expose export(record)");let t=typeof e=="function"?e:e?.export?.bind(e);return Object.freeze({exporterConfigured:!!t,defaultExporter:"none",async emit(r){let n=no(r)?r:ro(r);if(!t)return Object.freeze({record:n,exported:!1,exporterFailed:!1});try{return await t(n),Object.freeze({record:n,exported:!0,exporterFailed:!1})}catch{return Object.freeze({record:n,exported:!1,exporterFailed:!0})}}})}var $f="ORACLE_LEDGER_DUAL_WRITE",Js=/^[a-f0-9]{64}$/,Pf=/^0x[a-f0-9]{64}$/,Bf=Object.freeze({"workflow.cancelled":"cancelled","workflow.failed":"failed"});function Lt(e,t){return String(e??"").slice(0,t)}function Ks(e=process.env){return String(e?.[$f]??"")==="1"}function Gs({path:e,tenantId:t="local-signer",nowMs:r=Date.now,onError:n=null,telemetry:o=null,append:i=Qn}={}){if(typeof e!="string"||e.trim().length===0)throw new Error("ledger observer requires an explicit ledger path");if(typeof i!="function")throw new Error("ledger observer requires an append function");let s=typeof n=="function"?n:()=>{},u=new Map,a=Promise.resolve(),c=()=>new Date(r()).toISOString();function d(f,p,w){if(!(!o||typeof o.emit!="function"))try{let g=r(),h=ro({trace:f.trace,name:p,kind:"workflow",outcome:Bf[p]??"succeeded",startedAt:g,endedAt:g,attributes:w,tenantId:t,workflowId:f.workflowId});a=a.then(()=>o.emit(h)).catch(y=>{s(`signer telemetry emit failed: ${Lt(y?.message||y,200)}`)})}catch(g){s(`signer telemetry record failed: ${Lt(g?.message||g,200)}`)}}function l(f,p,{external:w=!1,source:g="local-signer",reference:h=null,data:y={}}={}){let b=c(),S={tenantId:t,id:`${f.workflowId}:${p}`,workflowId:f.workflowId,idempotencyKey:`${f.workflowId}:${p}`,occurredAt:b,recordedAt:b,type:p,external:w,evidence:{status:"verified",source:w?"external":g,reference:`${w?`${g}:`:""}${h??`${p}:${f.workflowId}`}`},data:y};return a=a.then(()=>i({path:e,event:S})).catch(A=>{s(`workflow ledger dual-write failed for ${p}: ${Lt(A?.message||A,200)}`)}),d(f,p,{digest:f.digest}),a}function m(f){let p=String(f??"").toLowerCase();return Js.test(p)?u.get(p)??null:null}return Object.freeze({queued({digest:f,createdAtMs:p}={}){let w=String(f??"").toLowerCase();if(!Js.test(w))return s("ledger observer: queued without a valid artifact digest"),a;let g=Number.isFinite(Number(p))?Number(p):r(),h={workflowId:`signer-${w}-${g}`,digest:w,trace:Us()};return u.set(w,h),l(h,"workflow.drafted",{source:"local-signer-queue",reference:`artifact:${w}`,data:{intentSpecId:`${h.workflowId}:intent`}}),l(h,"workflow.checked",{source:"local-signer-policy",reference:`artifact:${w}`,data:{checksPassed:!0}}),l(h,"workflow.approval_requested",{source:"local-signer-queue",reference:`artifact:${w}`}),a},denied({digest:f}={}){let p=m(f);return p&&(u.delete(p.digest),l(p,"workflow.cancelled",{source:"owner-ack",reference:`deny:${p.digest}`})),a},approved({digest:f,channel:p="owner-ack"}={}){let w=m(f);return w&&l(w,"workflow.approval_granted",{external:!0,source:p,reference:`ack:${w.digest}`}),a},executed({digest:f,owner:p=null,result:w=null}={}){let g=m(f);if(!g)return a;u.delete(g.digest),l(g,"workflow.signed",{external:!0,reference:`signed:${g.digest}`,data:{artifactHash:g.digest,signer:Lt(p||"owner-wallet",256)}});let h=w?.hash??w?.txHash??w?.transactionHash??w?.signature??null,y=typeof h=="string"?h.trim().toLowerCase():null;return y&&Pf.test(y)?l(g,"workflow.submitted",{external:!0,reference:`submitted:${g.digest}`,data:{transactionHash:y,endpoint:"local-signer-broadcast"}}):h&&l(g,"workflow.annotated",{reference:`submission:${g.digest}`,data:{note:"non-evm-submission-reference",reference:Lt(h,512)}}),a},failed({digest:f,reason:p=""}={}){let w=m(f);return w&&(u.delete(w.digest),l(w,"workflow.failed",{reference:`failed:${w.digest}`,data:{reason:Lt(p,300)}})),a},flush(){return a}})}import{appendFileSync as Df,existsSync as Ff,mkdirSync as jf,renameSync as qf,statSync as Mf}from"node:fs";import{dirname as Hf}from"node:path";var zf="ORACLE_TELEMETRY_JSONL",Wf=32*1024*1024,Ys=4096;function Uf({path:e,maxBytes:t=Wf}={}){if(typeof e!="string"||e.trim().length===0)throw new F("jsonl exporter requires an explicit file path","invalid-exporter-path");let r=Number(t);if(!Number.isFinite(r)||r<Ys)throw new F(`jsonl exporter maxBytes must be >= ${Ys}`,"invalid-exporter-cap");let n=e;return Object.freeze({path:n,maxBytes:r,export(o){if(!no(o))throw new F("jsonl exporter accepts only sealed workflow telemetry records","invalid-record");let i=`${JSON.stringify(o)}
11
+ `;jf(Hf(n),{recursive:!0,mode:448}),Ff(n)&&Mf(n).size+Buffer.byteLength(i)>r&&qf(n,`${n}.1`),Df(n,i,{mode:384})}})}function Xs(e=process.env,{maxBytes:t}={}){let r=String(e?.[zf]??"").trim();return r?oo({exporter:Uf({path:r,...t===void 0?{}:{maxBytes:t}})}):oo({})}import{createCipheriv as Qb,createDecipheriv as Vf,randomBytes as Jf,scryptSync as Kf}from"node:crypto";import D from"node:fs";import Rt from"node:path";var Gf="ORACLE-LOCAL-VAULT",Yf=1,Wr=Object.freeze({N:1<<17,r:8,p:1}),Xf=256*1024*1024,Zf=16*1024;function zr(e,t,r,{max:n=t}={}){if(typeof e!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`local-vault: invalid ${r} encoding`);let o=Buffer.from(e,"base64");if(o.toString("base64")!==e||o.length<t||o.length>n)throw new Error(`local-vault: invalid ${r} length`);return o}function Qf(e,t,r=Wr){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");if(n.includes("\0"))throw new Error("local-vault: refusing zeroed passphrase material");return Kf(n,t,32,{...r,maxmem:Xf})}function Zs(e,t){if(e?.magic!==Gf||e?.version!==Yf)throw new Error("local-vault: unsupported vault file");if(e?.kdf?.name!=="scrypt"||e?.cipher?.name!=="aes-256-gcm")throw new Error("local-vault: unsupported cryptography");if(e.kdf.N!==Wr.N||e.kdf.r!==Wr.r||e.kdf.p!==Wr.p)throw new Error("local-vault: unsupported KDF parameters");if(Object.keys(e.kdf).sort().join(",")!=="N,name,p,r,salt"||Object.keys(e.cipher).sort().join(",")!=="iv,name")throw new Error("local-vault: unexpected cryptography field");if(!e.meta||Object.keys(e.meta).some(l=>!["address","addresses","kind","createdAt"].includes(l))||String(e.meta.kind||"").length>16||String(e.meta.address||"").length>128||JSON.stringify(e.meta.addresses||{}).length>1024||!Number.isFinite(Date.parse(e.meta.createdAt)))throw new Error("local-vault: invalid metadata");let r=["magic","version","kdf","cipher","meta","ciphertext","tag"];if(Object.keys(e).some(l=>!r.includes(l)))throw new Error("local-vault: unexpected vault field");let n=zr(e.kdf.salt,32,"salt"),o=zr(e.cipher.iv,12,"iv"),i=zr(e.tag,16,"tag"),s=zr(e.ciphertext,1,"ciphertext",{max:Zf}),{ciphertext:u,tag:a,...c}=e,d=Qf(t,n);try{let l=Vf("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(c))),l.setAuthTag(i),Buffer.concat([l.update(s),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function ep(e){if(!e.isFile())throw new Error("local-vault: secret source must be a regular file");if(e.uid!==process.getuid?.())throw new Error("local-vault: secret source must be owned by this user");if(e.nlink!==1)throw new Error("local-vault: refusing hard-linked secret source");if((e.mode&63)!==0)throw new Error("local-vault: secret source must be owner-only (0600)")}function tp(e){let t=Rt.dirname(e),r=D.lstatSync(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("local-vault: unsafe destination directory");if(r.uid!==process.getuid?.())throw new Error("local-vault: destination directory must be owned by this user");if((r.mode&63)!==0)throw new Error("local-vault: destination directory must be owner-only (0700)");try{let n=D.lstatSync(e);if(n.isSymbolicLink())throw new Error("local-vault: refusing symlink destination");if(!n.isFile()||n.uid!==process.getuid?.()||n.nlink!==1)throw new Error("local-vault: unsafe destination file");if(n.dev!==r.dev)throw new Error("local-vault: destination device mismatch")}catch(n){if(n.code!=="ENOENT")throw n}}function R(e){let t;try{t=D.openSync(e,D.constants.O_RDONLY|D.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=D.fstatSync(t);if(ep(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=D.lstatSync(e);if(n.isSymbolicLink()||n.dev!==r.dev||n.ino!==r.ino)throw new Error("local-vault: secret source changed or is too large");return D.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{D.closeSync(t)}}function Qs(e){return JSON.parse(R(e))}function Ae(e,t){D.mkdirSync(Rt.dirname(e),{recursive:!0,mode:448}),tp(e);let r=Rt.join(Rt.dirname(e),`.${Rt.basename(e)}.${process.pid}.${Jf(6).toString("hex")}.tmp`);try{let n=D.openSync(r,D.constants.O_CREAT|D.constants.O_EXCL|D.constants.O_WRONLY|D.constants.O_NOFOLLOW,384);try{D.writeFileSync(n,String(t)),D.fsyncSync(n)}finally{D.closeSync(n)}D.renameSync(r,e),D.chmodSync(e,384);let o=D.openSync(Rt.dirname(e),"r");try{D.fsyncSync(o)}finally{D.closeSync(o)}}catch(n){try{D.unlinkSync(r)}catch{}throw n}}var ea=/^0x[0-9a-fA-F]+$/,rp=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}});function np(e){let t=process.env[`ORACLE_PRIVATE_RELAY_${Number(e)}`];if(!t)return null;let r=t.split(",").map(n=>n.trim()).filter(Boolean);return r.length?r:null}function op(e,{requirePrivate:t=!1}={}){let r=Number(e);if(!Number.isInteger(r))throw new Error("resolvePrivateRelay: chainId must be an integer");let n=rp[r]||{name:`chain-${r}`,mode:"public-only",endpoints:[]},o=np(r),i=o||n.endpoints,s=o&&n.mode==="public-only"?"mempool-private":n.mode,u=i.length>0&&s!=="public-only";if(t&&!u)throw new Error(`private relay: no keyless private endpoint for chain ${r} (${n.name}); set ORACLE_PRIVATE_RELAY_${r} to force one, or allow public fallback`);return{chainId:r,name:n.name,mode:s,endpoints:[...i],source:o?"env":"builtin",hasPrivate:u}}async function ta(e,{chainId:t,requirePrivate:r=!1,allowPublicFallback:n=!0,fetchImpl:o,timeoutMs:i=8e3}={}){if(typeof e!="string"||!ea.test(e))throw new Error("submitPrivate: signedRawTx must be a 0x-hex string");let s=op(t,{requirePrivate:r}),u=o||globalThis.fetch;if(!u)throw new Error("submitPrivate: no fetch implementation available");let a=[];for(let c of s.endpoints){let d=new AbortController,l=setTimeout(()=>d.abort(),i);try{let m=await u(c,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_sendRawTransaction",params:[e]}),signal:d.signal}),f=await m.text(),p=null;try{p=JSON.parse(f)}catch{}if(p&&p.result&&ea.test(p.result))return{hash:p.result,endpoint:c,mode:s.mode,chainId:s.chainId,fellBack:!1};a.push({endpoint:c,error:p&&p.error&&p.error.message||`http ${m.status}`})}catch(m){a.push({endpoint:c,error:String(m&&m.message||m).slice(0,160)})}finally{clearTimeout(l)}}if(n&&!r)return{fellBack:!0,mode:s.mode,chainId:s.chainId,attempts:a};throw new Error(`submitPrivate: all private endpoints failed for chain ${s.chainId} (${a.map(c=>`${c.endpoint}:${c.error}`).join("; ")||"none configured"})`)}import{createHmac as sp,randomBytes as ap,timingSafeEqual as cp}from"node:crypto";import te from"node:fs";import ct from"node:path";import{homedir as io}from"node:os";import{join as so}from"node:path";var ra=process.env.ORACLE_PUBLIC_DESKTOP==="1",ip=ra?process.env.ORACLE_CONFIG_DIR||so(io(),".config","oracle"):so(io(),".config","oracle"),s0=ra?ip:so(io(),".config","mad-desk");var d0="0".repeat(64),f0=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});function Ur(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(Ur).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+Ur(e[r])).join(",")+"}"}var p0=Promise.resolve();function ut(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=s=>{try{return te.realpathSync(s)}catch{return ct.resolve(s)}},n=r(ct.dirname(ct.resolve(e))),o=r(ct.dirname(ct.resolve(t))),i=(s,u)=>u===s||u.startsWith(s+ct.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var up=864e5,ue=(e,t)=>sp("sha256",t).update(Ur(e)).digest("hex"),Ce=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&cp(r,n)},lp=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function dp(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(e.integrity.mac,ue(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function Jr(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=R(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(r)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!Ce(n?.integrity?.mac,ue(n?.marker,t)))throw new Error("policy: sequence anchor integrity failed");return{sequence:Number(n?.marker?.policySequence||0),policyMac:n?.marker?.policyMac??null,present:!0,ledgerInitialized:n?.marker?.ledgerInitialized===!0}}function fp(e,t,r,n=null,{ledgerInitialized:o}={}){if(n==null||!String(n))throw new Error("policy: sequence anchor must bind the sealed policy MAC");let i=o===!0;if(o===void 0)try{let u=Jr(e,r);i=u.present&&u.ledgerInitialized===!0}catch{i=!1}let s={policySequence:Number(t),policyMac:String(n)};i&&(s.ledgerInitialized=!0),Ae(e,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(s,r)}})+`
12
12
  `)}function pp(e,t){let r=Jr(e,t);if(!r.present)throw new Error("policy: sequence anchor required");if(r.ledgerInitialized)return!0;if(r.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");return fp(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function Kr(e,t,{sequenceAnchorFile:r}={}){if(!r)throw new Error("policy: sequence anchor required");let n=R(t),o;try{o=JSON.parse(R(e))}catch(a){throw new Error(`policy: cannot read sealed policy: ${a?.message||a}`)}let i=dp(o,n);ut(r,e);let s=Jr(r,n),u=Number(i.policySequence||0);if(!s.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(u!==s.sequence)throw new Error("policy: rolled back to a superseded policy");if(s.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");if(!Ce(s.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function Pt(e,t,r,n,o){let i=`${e}.continuity`,s;try{let u=JSON.parse(R(e));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(u?.integrity?.mac,ue(u.ledger,t)))throw new Error("integrity verification failed");if(s=u.ledger,!Number.isFinite(s?.windowStartMs)||!Array.isArray(s?.entries)||s.sequence!==void 0&&(!Number.isSafeInteger(s.sequence)||s.sequence<0))throw new Error("invalid ledger")}catch(u){if(u?.code==="ENOENT"){if(te.existsSync(i)||te.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let a=Jr(o,t);if(a.present&&a.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:r,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${u?.message||u}`)}try{let u=JSON.parse(R(i));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(u?.integrity?.mac,ue(u.marker,t)))throw new Error("continuity verification failed");if(u.marker?.version===2&&(u.marker.sequence!==s.sequence||!Ce(u.marker.ledgerMac,ue(s,t))))throw new Error("continuity rollback detected");if(u.marker?.version!==2&&s.sequence!==void 0)throw new Error("continuity rollback detected");if(te.existsSync(n)&&(u.marker?.version!==2||s.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(u.marker?.version===2){let a=JSON.parse(R(n));if(a?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(a?.integrity?.mac,ue(a.marker,t))||a.marker?.version!==1||a.marker.sequence!==s.sequence||!Ce(a.marker.ledgerMac,ue(s,t)))throw new Error("checkpoint rollback detected")}}catch(u){throw new Error(`ledger: corrupt or unreadable: ${u?.message||u}`)}if(r-s.windowStartMs>=up){let u=new Date(r).toISOString().slice(0,10),a=d=>String(d||"").startsWith("cex:")&&String(d).endsWith(`:${u}`),c=s.entries.map(d=>{if(d.state==="reserved"||d.state==="consumed")return d;if(Array.isArray(d.units)){let l=d.units.map(f=>a(f.unit)?f:{...f,value:"0",notional:"0"}),m=l.some(f=>BigInt(f.value??0)>0n||BigInt(f.notional??0)>0n);return{...d,state:m?d.state:"consumed",units:l}}return a(d.unit)?d:{...d,state:"consumed",value:"0",notional:"0"}});return{windowStartMs:r,entries:c,sequence:s.sequence??0}}return{...s,sequence:s.sequence??0}}function mp(e){return Array.isArray(e.units)?e.units:[{unit:e.unit||"wei",value:e.value,notional:e.notional,fee:e.fee}]}function ge(e,t,r){return e.reduce((n,o)=>{if(o.state==="released")return n;let i=mp(o).find(s=>s.unit===r);return i?n+BigInt(i[t]??0):n},0n)}function Vr(e){if(!Array.isArray(e)||e.length===0)throw new Error("ledger: units array required");let t=new Set,r=e.map(n=>{let o=String(n?.unit||"");if(!o)throw new Error("ledger: unit required");if(t.has(o))throw new Error("ledger: duplicate unit in units array");t.add(o);let i=BigInt(n.value??0),s=BigInt(n.notional??0);if(i<0n||s<0n)throw new Error("ledger: unit value/notional must be non-negative");let u=n.fee===void 0?0n:BigInt(n.fee);if(u<0n)throw new Error("ledger: unit fee must be non-negative");return{unit:o,value:i.toString(),notional:s.toString(),fee:u.toString()}});return r.sort((n,o)=>n.unit<o.unit?-1:n.unit>o.unit?1:0),r}function wp(e,t){let r=e[t];if(r==null||r==="")throw new Error(`ledger: ${t} required`);return ae(r,`ledger: ${t}`)}function $t(e,t){if(String(t).startsWith("cex:")){let[,n,o,i,s,u]=String(t).split(":");if(!/^[A-Za-z0-9._-]{1,64}$/.test(n||"")||!/^[A-Za-z0-9._-]{1,64}$/.test(o||"")||!/^[a-z0-9._-]{1,32}$/.test(i||"")||!/^[A-Z0-9._-]{1,24}$/.test(s||"")||!/^\d{4}-\d{2}-\d{2}$/.test(u||""))throw new Error("ledger: invalid CEX accounting unit");let a=e.cexAccounts?.[n];if(!a||String(a.accountId)!==o||!Array.isArray(a.venues)||!a.venues.includes(i))throw new Error("ledger: CEX account/venue policy required");if(!a.symbolQuotes||!Object.values(a.symbolQuotes).includes(s))throw new Error("ledger: CEX quote policy required");let c=ae(a.dailyGrossQuoteCap,"ledger: dailyGrossQuoteCap"),d=ae(a.perOrderQuoteCap,"ledger: perOrderQuoteCap");return[c,c,d]}if(String(t).startsWith("erc20:")){let n=String(t).slice(6).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("ledger: invalid ERC20 accounting unit");let o=Object.entries(e.tokenCaps||e.nftPaymentTokenCaps||{}).find(([s])=>String(s).toLowerCase()===n)?.[1];if(!o)throw new Error("ledger: ERC-20 token caps required");let i=["maxDailyValueRaw","maxDailyNotionalRaw","maxPerTradeRaw"];for(let s of i)if(o[s]===void 0||o[s]===null||o[s]==="")throw new Error(`ledger: ${s} required`);return i.map(s=>BigInt(o[s]))}let r=t==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:t==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:t==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:t==="usdc"?["maxDailyValueUsdc","maxDailyNotionalUsdc","maxPerTradeUsdc"]:null;if(!r)throw new Error("ledger: unsupported accounting unit");if(t==="usdc"){let n=r.filter(a=>e[a]!==void 0&&e[a]!==null&&e[a]!=="");if(n.length===r.length)return r.map(a=>wp(e,a));if(n.length>0){let a=r.filter(c=>!n.includes(c));throw new Error(`ledger: ${a[0]} required`)}let o=e.maxDailyNotionalUsd??e.maxNotionalUsd??e.maxNotionalUsdc,i=e.maxPerTradeUsd??e.maxNotionalUsd??e.maxNotionalUsdc;if(o==null||o==="")throw new Error("ledger: maxDailyValueUsdc required");if(i==null||i==="")throw new Error("ledger: maxPerTradeUsdc required");let s=M(o,6,"ledger: maxDailyNotionalUsdc"),u=M(i,6,"ledger: maxPerTradeUsdc");return[s,s,u]}for(let n of r)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error(`ledger: ${n} required`);return r.map(n=>BigInt(e[n]))}function Bt(e,t){let r=`${e}.lock`,n=ap(16).toString("hex"),o;try{o=te.openSync(r,te.constants.O_CREAT|te.constants.O_EXCL|te.constants.O_WRONLY|(te.constants.O_NOFOLLOW||0),384),te.writeFileSync(o,n),te.fsyncSync(o)}catch(i){throw o!==void 0&&te.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return t()}finally{te.closeSync(o);try{R(r)===n&&te.unlinkSync(r)}catch{}}}function De(e,t,r,n,o){let i=`${e}.continuity`,s={...t,sequence:(t.sequence??0)+1},u=ue(s,r);Ae(e,JSON.stringify({ledger:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:u}})+`
13
13
  `);let a={version:2,sequence:s.sequence,ledgerMac:u};Ae(i,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(a,r)}})+`
14
14
  `);let c={version:1,sequence:s.sequence,ledgerMac:u};te.mkdirSync(ct.dirname(n),{recursive:!0,mode:448}),Ae(n,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(c,r)}})+`
15
- `),o&&pp(o,r)}function or({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:s=0,notional:u=0,fee:a,units:c,policy:d,retryReleasedTradeId:l,nowMs:m=Date.now()}){let f=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(f))throw new Error("ledger: bounded tradeId required");ut(r,e);let p=R(t);return Bt(e,()=>{let w=Pt(e,p,m,r,n),g=w.entries.find(y=>String(y.tradeId)===f);if(g){if(g.state!=="released"||String(l||"")!==f)throw new Error("ledger: replayed tradeId");if(c!==void 0){let y=Vr(c);if(!Array.isArray(g.units)||JSON.stringify(g.units)!==JSON.stringify(y))throw new Error("ledger: released reservation mismatch");for(let b of y){let[S,A,k]=$t(d,b.unit);if(BigInt(b.notional)>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",b.unit)+BigInt(b.value)>S||ge(w.entries,"notional",b.unit)+BigInt(b.notional)>A)throw new Error("ledger: daily cap exceeded")}}else{let y={unit:i,value:BigInt(s).toString(),notional:BigInt(u).toString(),fee:a===void 0?"0":BigInt(a).toString()};if(Array.isArray(g.units)||g.unit!==y.unit||g.value!==y.value||g.notional!==y.notional||String(g.fee??"0")!==y.fee)throw new Error("ledger: released reservation mismatch");let[b,S,A]=$t(d,i);if(BigInt(y.notional)>A)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",i)+BigInt(y.value)>b||ge(w.entries,"notional",i)+BigInt(y.notional)>S)throw new Error("ledger: daily cap exceeded")}return g.state="reserved",g.atMs=m,g.retriedAtMs=m,delete g.releasedAtMs,De(e,w,p,r,n),structuredClone(g)}let h;if(c!==void 0){let y=Vr(c);for(let b of y){let[S,A,k]=$t(d,b.unit),v=BigInt(b.value),_=BigInt(b.notional);if(_>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",b.unit)+v>S||ge(w.entries,"notional",b.unit)+_>A)throw new Error("ledger: daily cap exceeded")}h={tradeId:f,units:y,state:"reserved",atMs:m}}else{let y=BigInt(s),b=BigInt(u),[S,A,k]=$t(d,i);if(y<0n||b<0n||b>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",i)+y>S||ge(w.entries,"notional",i)+b>A)throw new Error("ledger: daily cap exceeded");h={tradeId:f,unit:i,value:y.toString(),notional:b.toString(),fee:a===void 0?"0":BigInt(a).toString(),state:"reserved",atMs:m}}return w.entries.push(h),De(e,w,p,r,n),structuredClone(h)})}function na({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:s,nowMs:u=Date.now()}){ut(r,e);let a=R(t);return Bt(e,()=>{let c=Pt(e,a,u,r,n),d=c.entries.find(w=>String(w.tradeId)===String(o?.tradeId??"")&&w.state==="reserved");if(!d)throw new Error("ledger: reservation unavailable");if(Array.isArray(o?.units)||Array.isArray(d.units)){if(!Array.isArray(o?.units)||!Array.isArray(d.units))throw new Error("ledger: reservation unavailable");let w=Vr(o.units);if(JSON.stringify(w)!==JSON.stringify(d.units))throw new Error("ledger: reservation unavailable");if(s){if(!Array.isArray(s.units))throw new Error("ledger: reserved units no longer match decoded economics");let g=Vr(s.units);if(g.length!==d.units.length||g.some((h,y)=>h.unit!==d.units[y].unit))throw new Error("ledger: reserved units no longer match decoded economics");for(let h=0;h<g.length;h++)if(BigInt(g[h].value)>BigInt(d.units[h].value)||BigInt(g[h].notional)>BigInt(d.units[h].notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}for(let g of d.units){let[h,y,b]=$t(i,g.unit);if(BigInt(g.notional)>b)throw new Error("ledger: per-trade cap exceeded");if(ge(c.entries,"value",g.unit)>h||ge(c.entries,"notional",g.unit)>y)throw new Error("ledger: daily cap exceeded")}return structuredClone(d)}if(d.unit!==o.unit||d.value!==o.value||d.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(s){if(s.unit!==d.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(s.value)>BigInt(d.value)||BigInt(s.notional)>BigInt(d.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=d.unit||"wei",[m,f,p]=$t(i,l);if(BigInt(d.notional)>p)throw new Error("ledger: per-trade cap exceeded");if(ge(c.entries,"value",l)>m||ge(c.entries,"notional",l)>f)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function oa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=R(t);return Bt(e,()=>{let u=Pt(e,s,i,r,n),a=u.entries.find(c=>String(c.tradeId)===String(o??""));if(!a)throw new Error("ledger: reservation unavailable");if(a.state==="committed"&&["fee-only","no-fee"].includes(a.settledAs))throw new Error("ledger: reservation unavailable");if(a.state==="committed")return structuredClone(a);if(a.state!=="reserved")throw new Error("ledger: reservation unavailable");return a.state="committed",a.committedAtMs=i,De(e,u,s,r,n),structuredClone(a)})}function ia({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=R(t);return Bt(e,()=>{let u=Pt(e,s,i,r,n),a=u.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!a)throw new Error("ledger: reservation unavailable");let c=structuredClone(a);return a.state="released",a.releasedAtMs=i,De(e,u,s,r,n),c})}function hp(e,t){if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(String(e)))throw new Error("ledger: authoritative CEX fill invalid");let[r,n=""]=String(e).split("."),o=n.length;return BigInt(r+n)>BigInt(t)*10n**BigInt(o)}function sa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,expectedUnit:i,filledQuote:s,disposition:u,nowMs:a=Date.now()}){if(ut(r,e),!/^cex:/.test(String(i||""))||!["release","commit"].includes(u))throw new Error("ledger: CEX settlement binding refused");let c=R(t);return Bt(e,()=>{let d=Pt(e,c,a,r,n),l=d.entries.find(m=>m.tradeId===o&&m.state==="reserved"&&m.unit===i);if(!l)throw new Error("ledger: exact held CEX reservation unavailable");if(hp(s,l.notional))throw new Error("ledger: CEX overfill refused; reservation retained");if(u==="release"){if(!/^0(?:\.0+)?$/.test(s))throw new Error("ledger: nonzero CEX fill cannot release");let m=structuredClone(l);return l.state="consumed",l.releasedAtMs=a,l.value="0",l.notional="0",l.fee="0",De(e,d,c,r,n),m}return l.state="committed",l.committedAtMs=a,l.filledQuote=s,De(e,d,c,r,n),structuredClone(l)})}function aa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=R(t);return Bt(e,()=>{let u=Pt(e,s,i,r,n),a=u.entries.find(d=>String(d.tradeId)===String(o??""));if(!a)throw new Error("ledger: reservation unavailable");if(a.state==="committed"&&["fee-only","no-fee"].includes(a.settledAs))return structuredClone(a);if(a.state!=="reserved")throw new Error("ledger: reservation unavailable");if(Array.isArray(a.units))return a.state="committed",a.committedAtMs=i,a.units=a.units.map(d=>{let l=BigInt(d.fee??0);return{...d,value:"0",notional:l.toString()}}),a.settledAs=a.units.some(d=>BigInt(d.notional)>0n)?"fee-only":"no-fee",De(e,u,s,r,n),structuredClone(a);let c=BigInt(a.fee??0);return c<=0n?(a.state="committed",a.committedAtMs=i,a.value="0",a.notional="0",a.settledAs="no-fee",De(e,u,s,r,n),structuredClone(a)):(a.state="committed",a.committedAtMs=i,a.value="0",a.notional=c.toString(),a.settledAs="fee-only",De(e,u,s,r,n),structuredClone(a))})}function ca(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.triggerId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={triggerId:e.triggerId,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(lp(t))};return Ce(e.mac,ue(o,R(r)))}function gp(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function ua(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.waiverId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={waiverId:e.waiverId,owner:String(t.owner).toLowerCase(),action:String(t.action),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(gp(t))};return Ce(e.mac,ue(o,R(r)))}import{spawnSync as yp}from"node:child_process";function la(e="oracle-local-signer",t=process.env.USER||process.env.USERNAME||"oracle"){let r,n;if(process.platform==="darwin")r="/usr/bin/security",n=["find-generic-password","-s",e,"-a",t,"-w"];else if(process.platform==="linux")r="secret-tool",n=["lookup","service",e,"account",t];else throw new Error("signer: OS credential lookup is supported on macOS and Linux; use a protected passphrase file on this platform");let o=yp(r,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}var bp=/^0x[0-9a-f]{40}$/,Ep=/^0x(?:[0-9a-f]{2})*$/,xp=/^(?:0x)?[0-9a-f]{64}$/,Sp=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,Ap=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,vp=new Set([12,15,18,21,24]),Gr=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}};function ao(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(Ap.test(e)||vp.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new Gr(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,i)=>ao(o,`${t}[${i}]`,r));lt(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(Sp.test(i))throw new Gr(`${t}.${o}`);e[o]!==void 0&&(n[o]=ao(e[o],`${t}.${o}`,o))}return n}function lt(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function ir(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function Dt(e,t){let r=String(ir(e,t)).toLowerCase();if(!bp.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function Fe(e,t,{positive:r=!1}={}){try{let n=BigInt(ir(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function co(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function da(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))da(t);Object.freeze(e)}return e}function Ip(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};lt(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:co(String(n),`${t}.reason`)}}function kp(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>Ip(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function Op(e){if(e==null)return null;if(lt(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:co(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=Fe(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=Fe(e.gasLimit,"simulation.gasLimit")),t}function Tp(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{lt(t,`assetDeltas[${r}]`);let n=Fe(t.before,`assetDeltas[${r}].before`),o=Fe(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),s;try{s=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(s!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:co(String(ir(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:s}})}function Np(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{lt(t,`approvalDeltas[${r}]`);let n=Fe(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:Dt(t.token,`approvalDeltas[${r}].token`),spender:Dt(t.spender,`approvalDeltas[${r}].spender`),owner:Dt(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function fa(e={}){lt(e,"input");let t=ao(e),r=t.tx==null?t:lt(t.tx,"tx"),n=Fe(t.chainId??r.chainId,"chainId",{positive:!0}),o=Dt(t.account??t.from??r.from,"account/from"),i=Dt(t.destination??t.to??r.to,"destination/to"),s=String(ir(t.prepareHash,"prepareHash")).toLowerCase();if(!xp.test(s))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let u=t.route??t.venue;if(u==null)throw new TypeError("sign-time review: route/venue required");let a=t.decodedCalldata??t.decodedAction;if(a==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let c=String(ir(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!Ep.test(c))throw new TypeError("sign-time review: calldata/data must be even-length hex");let d=t.policyChecks!==void 0&&t.policyChecks!==null,l=kp(d?t.policyChecks:[]),m=Op(t.simulation),f=Tp(t.assetDeltas),p=Np(t.approvalDeltas),w=t.allowlistHits??[];if(!Array.isArray(w))throw new TypeError("sign-time review: allowlistHits must be an array");let g=m?.willRevert===!0||["failed","error"].includes(m?.status),h=m!=null&&m.willRevert===!1&&["ok","success"].includes(m.status),y=g||l.failed>0?"BLOCKED":h&&d&&l.checks.length>0&&f!=null?"READY":"UNKNOWN",b=typeof a=="string"?a:a.method??a.action??a.type??"transaction",S=`${y}: review ${b} on chain ${n}; policy ${l.passed} passed, ${l.failed} failed; ${f?.length??0} asset delta${f?.length===1?"":"s"}; local signature required`,A={reviewVersion:1,status:y,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:u,venue:t.venue??(typeof u=="string"?u:u.venue??u.provider??null),destination:i,to:i,...t.spender==null?{}:{spender:Dt(t.spender,"spender")},prepareHash:s,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:c,data:c,selector:c.length>=10?c.slice(0,10):null,value:Fe(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:Fe(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:Fe(t.gasLimit??r.gasLimit,"gasLimit")},simulation:m,policyChecks:l,allowlistHits:w,assetDeltas:f,approvalDeltas:p,summary:S};return da(A)}import{readFileSync as Cp,readdirSync as _p,existsSync as wa}from"node:fs";import{dirname as Lp,join as Ft}from"node:path";import{fileURLToPath as Rp}from"node:url";var sr=Lp(Rp(import.meta.url));function $p(){let e=[Ft(sr,"descriptors"),Ft(sr,"clear-sign","descriptors"),Ft(sr,"..","clear-sign","descriptors"),Ft(sr,"..","..","clear-sign","descriptors"),Ft(sr,"..","..","..","clear-sign","descriptors")];for(let t of e)if(wa(t))return t;return e[0]}var Pp=$p(),Bp=/^0x[0-9a-f]{8}/,Dp=/^0x[0-9a-fA-F]{40}$/;function Fp(e=Pp){if(!wa(e))return[];let t=[];for(let r of _p(e).filter(n=>n.endsWith(".json")).sort()){let n=Cp(Ft(e,r),"utf8"),o;try{o=JSON.parse(n)}catch(i){throw new Error(`clear-sign descriptor ${r} is not valid JSON: ${i.message}`)}t.push({file:r,doc:o})}return t}function jp(e,{to:t=null,chainId:r=null}={},n=Fp()){let o=String(e||"").toLowerCase(),i=Bp.test(o)?o.slice(0,10):null;if(!i)return null;let s=t&&Dp.test(String(t))?String(t).toLowerCase():null;for(let{file:u,doc:a}of n){let c=a?.display?.formats||{};for(let[d,l]of Object.entries(c)){if(String(l?.$selector||"").toLowerCase()!==i)continue;let m=a?.context?.contract?.deployments||[],f=m.length===0,p=m.some(w=>(r==null||Number(w.chainId)===Number(r))&&s&&String(w.address||"").toLowerCase()===s);if(f||p)return{file:u,signature:d,format:l,doc:a,selector:i,generic:f}}}return null}function ha(e,t){let r=e.slice(t*64,t*64+64);return r.length===64?r:null}function qp(e,t){let r=ha(e,t);return r?`0x${r.slice(24)}`:null}function pa(e,t){let r=ha(e,t);return r?BigInt(`0x${r}`).toString():null}var Mp=(1n<<256n)-1n;function ma(e){if(e==null)return"unknown";let t=BigInt(e);return t>=Mp/2n?"UNLIMITED":t.toString()}function ga(e,{to:t=null,chainId:r=null}={},n=void 0){let o=jp(e,{to:t,chainId:r},n);if(!o)return null;let i=String(e||"").toLowerCase(),s=i.slice(10),u=[],a=[];for(let c of o.format.fields||[]){if(c.visible==="never")continue;let d=c.$wordIndex,l=null;Number.isInteger(d)&&(l=c.format==="addressName"||c.format==="raw-address"?qp(s,d):c.format==="amount"||c.format==="tokenAmount"?ma(pa(s,d)):pa(s,d)),l!=null&&(a.push({label:c.label,value:l}),u.push(`${c.label}: ${l}`))}if(oe(i)){let c=null,d=null;try{c=Re(i)}catch(l){let m=String(l?.message||l);if(/unlimited approvals are refused/i.test(m))d="ORACLE POLICY: unlimited approval \u2014 Oracle refuses to prepare this; bound the amount";else return{ok:!1,refused:`descriptor matched but reviewed decoder refused: ${m}`,intent:o.format.intent}}if(c){let l=a.find(p=>/spender/i.test(p.label))?.value?.toLowerCase();if(l&&c.spender&&l!==c.spender.toLowerCase())return{ok:!1,refused:"descriptor spender disagrees with reviewed decoder",intent:o.format.intent};let m=a.find(p=>/amount|allowance/i.test(p.label))?.value,f=ma(c.amount);if(m!=null&&c.amount!=null&&String(m)!==f)return{ok:!1,refused:"descriptor amount disagrees with reviewed decoder",intent:o.format.intent}}return d&&u.push(d),{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:a,lines:u,...d?{policyNote:d}:{}}}return{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:a,lines:u}}var Hp=/^0x[0-9a-f]{40}$/;function ar(e){let t=String(e??"").toLowerCase();return Hp.test(t)?t:null}function zp(e,{token:t,owner:r}){if(!oe(e))return[];let n;try{n=Re(e)}catch{return[]}let o={token:ar(n.token??t),spender:ar(n.spender),owner:ar(r),amount:n.amount};return o.token&&o.spender&&o.owner&&o.amount!=null?[o]:[]}function Wp(e,t,r={}){let n=e?.version===1&&e?.surface?e:null,o=n?.surface||"evm";if(o!=="evm"&&o!=="evm-nft")return null;let i=n?.artifact||e||{},s=ar(n?.owner??i.from),u=ar(i.to??n?.destination),a=String(i.data??"0x").toLowerCase();if(!s||!u)return null;let c=[],d=r?.destinationAllowlist;if(Array.isArray(d)&&d.length){let l=d.map(m=>String(m).toLowerCase()).includes(u);c.push({name:"destination-allowlist",passed:l,reason:l?"destination is allowlisted":"destination is not on the allowlist"})}try{return fa({chainId:i.chainId,account:s,destination:u,calldata:a,value:i.value??0,prepareHash:t,route:n?.provider??n?.venue??o,decodedAction:n?.action??"transaction",...i.gasLimit==null?{}:{gasLimit:i.gasLimit},...c.length?{policyChecks:c}:{},approvalDeltas:zp(a,{token:u,owner:s})})}catch{return null}}function ya(e,t,r={}){let n=Wp(e,t,r);if(!n)return[];let o=[`REVIEW status=${n.status} action=${n.decodedAction??"transaction"} selector=${n.selector??"none"}`,`REVIEW route=${typeof n.route=="string"?n.route:n.venue??"n/a"} value=${n.value} signing=local custody=${n.custody}`];n.policyChecks.checks.length&&o.push(`REVIEW policy passed=${n.policyChecks.passed} failed=${n.policyChecks.failed}${n.policyChecks.failed?` reasons=${n.policyChecks.reasons.join("; ")}`:""}`);for(let i of n.approvalDeltas)o.push(`REVIEW APPROVAL token=${i.token} spender=${i.spender} amount=${i.amount} revokeLike=${i.revokeLike}`);n.assetDeltas==null&&o.push("REVIEW assetDeltas=unavailable (no simulated balance change supplied)"),n.status!=="READY"&&o.push("REVIEW status is not READY: these facts are decoded, not proven safe.");try{let i=e?.artifact||e||{},s=ga(String(i.data??"0x"),{to:i.to??null,chainId:i.chainId??null});if(s?.ok){o.push(`CLEAR-SIGN intent=${s.intent} [${s.descriptor}]`);for(let u of s.lines)o.push(`CLEAR-SIGN ${u}`)}else s&&s.refused&&o.push(`CLEAR-SIGN REFUSED: ${s.refused}`)}catch{}return o}import{Wallet as uo}from"ethers";import{base58 as lo}from"@scure/base";import{ed25519 as Aa}from"@noble/curves/ed25519.js";import{NETWORK as va,TEST_NETWORK as Ia,WIF as Up,p2wpkh as ba}from"@scure/btc-signer";import{pubECDSA as Vp}from"@scure/btc-signer/utils.js";var Yr=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Jp=e=>{let t=String(e||"").trim();if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return null;let r=Buffer.from(t,"base64");return r.toString("base64")===t?r:null},Ea=e=>{let t=String(e||"").trim();try{let r=Buffer.from(lo.decode(t));return lo.encode(r)===t?r:null}catch{return null}},fo=e=>{if(!(e instanceof Uint8Array))throw new Error("sol: key bytes required");if(e.length!==32&&e.length!==64)throw new Error("sol: expected 32-byte private key material");let t=Buffer.from(e.subarray(0,32));if(e.length===64){let r=Buffer.from(e.subarray(32,64)),n=Buffer.from(Aa.getPublicKey(t));if(!r.equals(n))throw new Error("sol: supplied public key does not match seed")}return t},xa=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),je=(e,t)=>{if(t==="sol")return fo(e);if(!(e instanceof Uint8Array))throw new Error(`${t}: key bytes required`);if(e.length===32)return Buffer.from(e);if(e.length===64)return Buffer.from(e.subarray(0,32));throw new Error(`${t}: expected 32-byte private key material`)},Kp=(e,t)=>{if(!Array.isArray(e))throw new Error(`${t}: expected byte array`);let r=Buffer.alloc(e.length);for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>255)throw new Error(`${t}: expected integer bytes in 0..255`);r[n]=o}return je(r,t)};function po(e,t){let r=String(t||"").trim();if(e==="evm")return new uo(r).privateKey;if(e==="btc")for(let i of[va,Ia])try{return Buffer.from(Up(i).decode(r))}catch{}if(e==="sol"){if(/^hex:/i.test(r)){let c=Yr(r.slice(4));if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}if(/^base58:/i.test(r)){let c=Ea(r.slice(7));if(!xa(c))throw new Error("sol: invalid explicit base58 private key");return fo(c)}if(/^0x/i.test(r)){let c=Yr(r);if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}let i=Yr(r),s=i&&(i.length===32||i.length===64)?je(i,"sol"):null,u=Ea(r),a=xa(u);if(s&&a&&!s.equals(a))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(a)return fo(u);if(i)return je(i,"sol")}let n=Yr(r);if(n)return e==="evm"?new uo(`0x${n.toString("hex")}`).privateKey:je(n,e);let o=Jp(r);if(o)return je(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Kp(i,e);let s=i.privateKey??i.secretKey??i.key;if(s)return po(e,Array.isArray(s)?JSON.stringify(s):String(s))}throw new Error(`${e}: unsupported private key format`)}function Sa(e,t){if(e==="evm"){let r=new uo(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=je(t,"btc"),n=Vp(r);return{kind:e,secret:r.toString("hex"),addresses:[ba(n,va).address,ba(n,Ia).address]}}if(e==="sol"){let r=je(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[lo.encode(Aa.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function ka(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:Sa(t.kind||"evm",po(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=Sa(i,po(i,n[i])));if(n.cex!==void 0){if(!n.cex||typeof n.cex!="object"||Array.isArray(n.cex))throw new Error("local-vault: cex credential records invalid");o.cex={};for(let[i,s]of Object.entries(n.cex)){if(!/^[A-Za-z0-9._-]{1,64}$/.test(i)||!s||typeof s!="object")throw new Error("local-vault: cex credential record invalid");if(!/^(?:binance|bybit|okx|coinbase)$/.test(s.venue)||!/^[A-Za-z0-9._-]{1,64}$/.test(s.accountId||""))throw new Error("local-vault: cex credential binding invalid");let u=(c,d=!0)=>{let l=s[c];if(!(!d&&l===void 0)){if(!Array.isArray(l)||l.length<4||l.some(m=>!Number.isInteger(m)||m<0||m>255))throw new Error("local-vault: cex credential bytes invalid");return Buffer.from(l)}},a=s.apiSecretEncoding;if(a!==(s.venue==="coinbase"?"base64":"raw"))throw new Error("local-vault: explicit cex secret encoding refused");o.cex[i]=Object.freeze({venue:s.venue,accountId:s.accountId,apiKeyBytes:u("apiKeyBytes"),apiSecretBytes:u("apiSecretBytes"),apiSecretEncoding:a,passphraseBytes:u("passphraseBytes",!1)})}if(!Object.keys(o.cex).length)throw new Error("local-vault: empty cex credential records refused");Object.freeze(o.cex)}if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function mo(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var Gp=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),Yp=Object.freeze(["binance","bybit","okx","coinbase"]),Xp=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),Zp=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),Qp=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),z0=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),em=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),W0=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),U0=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),V0=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),J0=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"});function wo(e,t){let r=String(e??"");if(!/^\d+$/.test(r))throw new Error(`cex-policy: ${t} must be an integer string`);return BigInt(r)}function le(e,t,r){let n=String(e??"");if(!r.test(n))throw new Error(`cex-policy: bounded ${t} required`);return n}function Oa(e,t){let r=String(e??"");if(!/^(?:0|[1-9]\d{0,29})(?:\.\d{1,18})?$/.test(r))throw new Error(`cex-policy: positive decimal ${t} required`);let[n,o=""]=r.split("."),i=BigInt(`${n}${o}`);if(i<=0n)throw new Error(`cex-policy: positive decimal ${t} required`);return{text:r,numerator:i,scale:o.length}}function tm(e,t){let r=e.numerator*t.numerator,n=10n**BigInt(e.scale+t.scale);return(r+n-1n)/n}function rm(e){return new Date(e).toISOString().slice(0,10)}function nm(e,t){let r=le(e.credentialRef,"credentialRef",/^[A-Za-z0-9._-]{1,64}$/),n=t.cexAccounts?.[r];if(!n||typeof n!="object")throw new Error("cex-policy: sealed account policy required");return{credentialRef:r,account:n}}function Xr(e={},t={},r=Date.now()){for(let C of Object.keys(e)){let z=C.toLowerCase();if(em.some(W=>W.toLowerCase()===z))throw new Error(`cex-policy: envelope field ${C} forbidden`);if(!Qp.includes(C))throw new Error(`cex-policy: envelope field ${C} not in allowlist`)}if(e.version!==1)throw new Error("cex-policy: version 1 required");if(e.surface!=="cex")throw new Error("cex-policy: surface cex required");let n=String(e.kind||"");if(!Gp.includes(n))throw new Error(`cex-policy: kind ${n||"(none)"} refused`);let o=le(e.venue,"venue",/^[a-z0-9._-]{1,32}$/);if(!Yp.includes(o)||!Xp[o]||!Zp[o])throw new Error(`cex-policy: venue ${o} unknown`);let{credentialRef:i,account:s}=nm(e,t);if(!Array.isArray(s.venues)||!s.venues.includes(o))throw new Error(`cex-policy: venue ${o} not allowlisted`);let u=le(e.symbol,"symbol",/^[A-Z0-9._/-]{1,32}$/);if(!Array.isArray(s.symbols)||!s.symbols.includes(u))throw new Error(`cex-policy: symbol ${u} not allowlisted`);let a=le(e.quote,"quote",/^[A-Z0-9._-]{1,24}$/);if(!s.symbolQuotes||typeof s.symbolQuotes!="object"||s.symbolQuotes[u]!==a)throw new Error("cex-policy: quote does not match sealed symbol policy");let c=le(s.accountId,"accountId",/^[A-Za-z0-9._-]{1,64}$/);if(!Array.isArray(s.allowedOperations)||!s.allowedOperations.includes(n))throw new Error("cex-policy: operation not in sealed allowlist");let d=le(e.base,"base",/^[A-Z0-9._-]{1,24}$/);if(s.base!==d||s.quote!==a)throw new Error("cex-policy: base/quote do not match sealed account policy");if(s.credentialRecordRef!==i)throw new Error("cex-policy: credential record reference mismatch");let l=s.filters?.[u];if(!l||typeof l.tickSize!="string"||typeof l.stepSize!="string"||typeof l.minNotional!="string")throw new Error("cex-policy: sealed symbol filters required");le(e.nonce,"nonce",/^[A-Za-z0-9._:-]{1,128}$/),le(e.grantId,"grantId",/^[A-Za-z0-9._:-]{1,128}$/),le(e.artifactHash,"artifactHash",/^[A-Za-z0-9._:-]{1,128}$/);let m=e.clientOrderId===void 0?void 0:le(e.clientOrderId,"clientOrderId",/^[A-Za-z0-9._-]{1,64}$/),f,p,w,g,h=0n,y=0n,b;if(n==="spot-limit-create"){if(f=le(e.side,"side",/^(?:buy|sell)$/),p=le(e.timeInForce,"timeInForce",/^GTC$/),w=Oa(e.baseSize,"baseSize"),g=Oa(e.limitPrice,"limitPrice"),!m)throw new Error("cex-policy: clientOrderId required");if(h=wo(e.maxQuoteNotional,"maxQuoteNotional"),y=tm(w,g),h<y)throw new Error("cex-policy: maxQuoteNotional understates baseSize times limitPrice")}else{for(let C of["side","baseSize","limitPrice","maxQuoteNotional","timeInForce"])if(e[C]!==void 0)throw new Error(`cex-policy: ${C} forbidden for cancel/status`);if(b=e.venueOrderId===void 0?void 0:le(e.venueOrderId,"venueOrderId",/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/),!b&&!m)throw new Error("cex-policy: exact prior order id required")}let S=wo(s.perOrderQuoteCap,"sealed perOrderQuoteCap"),A=wo(s.dailyGrossQuoteCap,"sealed dailyGrossQuoteCap");if(h>S)throw new Error("cex-policy: maxQuoteNotional exceeds sealed perOrderQuoteCap");if(h>A)throw new Error("cex-policy: maxQuoteNotional exceeds sealed dailyGrossQuoteCap");let k=Number(e.expiresAtMs);if(!Number.isSafeInteger(k)||k<=r||k-r>12e4)throw new Error("cex-policy: bounded expiry required");let v=`cex:${i}:${o}:${c}:${m||b}`,_=`cex:${i}:${c}:${o}:${a}:${rm(r)}`;return Object.freeze({kind:n,venue:o,symbol:u,base:d,quote:a,side:f,timeInForce:p,baseSize:w?.text,limitPrice:g?.text,clientOrderId:m,venueOrderId:b,filter:Object.freeze({...l}),accountId:c,credentialRef:i,tradeId:v,unit:_,notional:h.toString(),impliedNotional:y.toString()})}function Ta({envelope:e,paths:t,nowMs:r=Date.now()}){let n=Kr(t.policy,t.policyKey,{sequenceAnchorFile:t.policyAnchor}),o=Xr(e,n,r);return or({file:t.ledger,keyFile:t.policyKey,anchorFile:t.ledgerAnchor,policyAnchorFile:t.policyAnchor,tradeId:o.tradeId,unit:o.unit,value:o.notional,notional:o.notional,policy:n,nowMs:r})}import J from"node:fs";import dt from"node:path";import{createHmac as om,randomBytes as im,timingSafeEqual as sm}from"node:crypto";var Zr=(e,t)=>om("sha256",e).update(JSON.stringify(t)).digest("hex"),Na=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&sm(r,n)},Ca=e=>Buffer.from(R(e));function _a({file:e,keyFile:t,anchorFile:r}){if(!e||!t||!r)throw new Error("cex-state: protected paths required");if(dt.dirname(dt.resolve(e))===dt.dirname(dt.resolve(r)))throw new Error("cex-state: external rollback anchor required");let n=`${e}.lock`,o=(()=>{try{return J.readFileSync(`/proc/${process.pid}/stat`,"utf8").trim().split(/\s+/)[21]}catch{return null}})(),i=d=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,d),s=d=>{if(!Number.isSafeInteger(d.pid)||d.pid<1||typeof d.processStart!="string"||!d.processStart)return null;try{process.kill(d.pid,0)}catch(l){return l?.code==="ESRCH"?!1:null}try{return J.readFileSync(`/proc/${d.pid}/stat`,"utf8").trim().split(/\s+/)[21]===d.processStart}catch{return null}},u=d=>{J.mkdirSync(dt.dirname(n),{recursive:!0,mode:448});let l=im(16).toString("hex"),m=Date.now()+5e3,f=`${n}.${process.pid}.${l}.tmp`,p=JSON.stringify({version:1,pid:process.pid,processStart:o,token:l,createdAtMs:Date.now()})+`
15
+ `),o&&pp(o,r)}function or({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:s=0,notional:u=0,fee:a,units:c,policy:d,retryReleasedTradeId:l,nowMs:m=Date.now()}){let f=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(f))throw new Error("ledger: bounded tradeId required");ut(r,e);let p=R(t);return Bt(e,()=>{let w=Pt(e,p,m,r,n),g=w.entries.find(y=>String(y.tradeId)===f);if(g){if(g.state!=="released"||String(l||"")!==f)throw new Error("ledger: replayed tradeId");if(c!==void 0){let y=Vr(c);if(!Array.isArray(g.units)||JSON.stringify(g.units)!==JSON.stringify(y))throw new Error("ledger: released reservation mismatch");for(let b of y){let[S,A,k]=$t(d,b.unit);if(BigInt(b.notional)>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",b.unit)+BigInt(b.value)>S||ge(w.entries,"notional",b.unit)+BigInt(b.notional)>A)throw new Error("ledger: daily cap exceeded")}}else{let y={unit:i,value:BigInt(s).toString(),notional:BigInt(u).toString(),fee:a===void 0?"0":BigInt(a).toString()};if(Array.isArray(g.units)||g.unit!==y.unit||g.value!==y.value||g.notional!==y.notional||String(g.fee??"0")!==y.fee)throw new Error("ledger: released reservation mismatch");let[b,S,A]=$t(d,i);if(BigInt(y.notional)>A)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",i)+BigInt(y.value)>b||ge(w.entries,"notional",i)+BigInt(y.notional)>S)throw new Error("ledger: daily cap exceeded")}return g.state="reserved",g.atMs=m,g.retriedAtMs=m,delete g.releasedAtMs,De(e,w,p,r,n),structuredClone(g)}let h;if(c!==void 0){let y=Vr(c);for(let b of y){let[S,A,k]=$t(d,b.unit),v=BigInt(b.value),_=BigInt(b.notional);if(_>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",b.unit)+v>S||ge(w.entries,"notional",b.unit)+_>A)throw new Error("ledger: daily cap exceeded")}h={tradeId:f,units:y,state:"reserved",atMs:m}}else{let y=BigInt(s),b=BigInt(u),[S,A,k]=$t(d,i);if(y<0n||b<0n||b>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",i)+y>S||ge(w.entries,"notional",i)+b>A)throw new Error("ledger: daily cap exceeded");h={tradeId:f,unit:i,value:y.toString(),notional:b.toString(),fee:a===void 0?"0":BigInt(a).toString(),state:"reserved",atMs:m}}return w.entries.push(h),De(e,w,p,r,n),structuredClone(h)})}function na({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:s,nowMs:u=Date.now()}){ut(r,e);let a=R(t);return Bt(e,()=>{let c=Pt(e,a,u,r,n),d=c.entries.find(w=>String(w.tradeId)===String(o?.tradeId??"")&&w.state==="reserved");if(!d)throw new Error("ledger: reservation unavailable");if(Array.isArray(o?.units)||Array.isArray(d.units)){if(!Array.isArray(o?.units)||!Array.isArray(d.units))throw new Error("ledger: reservation unavailable");let w=Vr(o.units);if(JSON.stringify(w)!==JSON.stringify(d.units))throw new Error("ledger: reservation unavailable");if(s){if(!Array.isArray(s.units))throw new Error("ledger: reserved units no longer match decoded economics");let g=Vr(s.units);if(g.length!==d.units.length||g.some((h,y)=>h.unit!==d.units[y].unit))throw new Error("ledger: reserved units no longer match decoded economics");for(let h=0;h<g.length;h++)if(BigInt(g[h].value)>BigInt(d.units[h].value)||BigInt(g[h].notional)>BigInt(d.units[h].notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}for(let g of d.units){let[h,y,b]=$t(i,g.unit);if(BigInt(g.notional)>b)throw new Error("ledger: per-trade cap exceeded");if(ge(c.entries,"value",g.unit)>h||ge(c.entries,"notional",g.unit)>y)throw new Error("ledger: daily cap exceeded")}return structuredClone(d)}if(d.unit!==o.unit||d.value!==o.value||d.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(s){if(s.unit!==d.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(s.value)>BigInt(d.value)||BigInt(s.notional)>BigInt(d.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=d.unit||"wei",[m,f,p]=$t(i,l);if(BigInt(d.notional)>p)throw new Error("ledger: per-trade cap exceeded");if(ge(c.entries,"value",l)>m||ge(c.entries,"notional",l)>f)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function oa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=R(t);return Bt(e,()=>{let u=Pt(e,s,i,r,n),a=u.entries.find(c=>String(c.tradeId)===String(o??""));if(!a)throw new Error("ledger: reservation unavailable");if(a.state==="committed"&&["fee-only","no-fee"].includes(a.settledAs))throw new Error("ledger: reservation unavailable");if(a.state==="committed")return structuredClone(a);if(a.state!=="reserved")throw new Error("ledger: reservation unavailable");return a.state="committed",a.committedAtMs=i,De(e,u,s,r,n),structuredClone(a)})}function ia({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=R(t);return Bt(e,()=>{let u=Pt(e,s,i,r,n),a=u.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!a)throw new Error("ledger: reservation unavailable");let c=structuredClone(a);return a.state="released",a.releasedAtMs=i,De(e,u,s,r,n),c})}function hp(e,t){if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(String(e)))throw new Error("ledger: authoritative CEX fill invalid");let[r,n=""]=String(e).split("."),o=n.length;return BigInt(r+n)>BigInt(t)*10n**BigInt(o)}function sa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,expectedUnit:i,filledQuote:s,disposition:u,nowMs:a=Date.now()}){if(ut(r,e),!/^cex:/.test(String(i||""))||!["release","commit"].includes(u))throw new Error("ledger: CEX settlement binding refused");let c=R(t);return Bt(e,()=>{let d=Pt(e,c,a,r,n),l=d.entries.find(m=>m.tradeId===o&&m.state==="reserved"&&m.unit===i);if(!l)throw new Error("ledger: exact held CEX reservation unavailable");if(hp(s,l.notional))throw new Error("ledger: CEX overfill refused; reservation retained");if(u==="release"){if(!/^0(?:\.0+)?$/.test(s))throw new Error("ledger: nonzero CEX fill cannot release");let m=structuredClone(l);return l.state="consumed",l.releasedAtMs=a,l.value="0",l.notional="0",l.fee="0",De(e,d,c,r,n),m}return l.state="committed",l.committedAtMs=a,l.filledQuote=s,De(e,d,c,r,n),structuredClone(l)})}function aa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=R(t);return Bt(e,()=>{let u=Pt(e,s,i,r,n),a=u.entries.find(d=>String(d.tradeId)===String(o??""));if(!a)throw new Error("ledger: reservation unavailable");if(a.state==="committed"&&["fee-only","no-fee"].includes(a.settledAs))return structuredClone(a);if(a.state!=="reserved")throw new Error("ledger: reservation unavailable");if(Array.isArray(a.units))return a.state="committed",a.committedAtMs=i,a.units=a.units.map(d=>{let l=BigInt(d.fee??0);return{...d,value:"0",notional:l.toString()}}),a.settledAs=a.units.some(d=>BigInt(d.notional)>0n)?"fee-only":"no-fee",De(e,u,s,r,n),structuredClone(a);let c=BigInt(a.fee??0);return c<=0n?(a.state="committed",a.committedAtMs=i,a.value="0",a.notional="0",a.settledAs="no-fee",De(e,u,s,r,n),structuredClone(a)):(a.state="committed",a.committedAtMs=i,a.value="0",a.notional=c.toString(),a.settledAs="fee-only",De(e,u,s,r,n),structuredClone(a))})}function ca(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.triggerId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={triggerId:e.triggerId,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(lp(t))};return Ce(e.mac,ue(o,R(r)))}function gp(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function ua(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.waiverId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={waiverId:e.waiverId,owner:String(t.owner).toLowerCase(),action:String(t.action),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(gp(t))};return Ce(e.mac,ue(o,R(r)))}import{spawnSync as yp}from"node:child_process";function la(e="oracle-local-signer",t=process.env.USER||process.env.USERNAME||"oracle"){let r,n;if(process.platform==="darwin")r="/usr/bin/security",n=["find-generic-password","-s",e,"-a",t,"-w"];else if(process.platform==="linux")r="secret-tool",n=["lookup","service",e,"account",t];else throw new Error("signer: OS credential lookup is supported on macOS and Linux; use a protected passphrase file on this platform");let o=yp(r,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}var bp=/^0x[0-9a-f]{40}$/,Ep=/^0x(?:[0-9a-f]{2})*$/,xp=/^(?:0x)?[0-9a-f]{64}$/,Sp=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,Ap=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,vp=new Set([12,15,18,21,24]),Gr=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}};function ao(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(Ap.test(e)||vp.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new Gr(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,i)=>ao(o,`${t}[${i}]`,r));lt(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(Sp.test(i))throw new Gr(`${t}.${o}`);e[o]!==void 0&&(n[o]=ao(e[o],`${t}.${o}`,o))}return n}function lt(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function ir(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function Dt(e,t){let r=String(ir(e,t)).toLowerCase();if(!bp.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function Fe(e,t,{positive:r=!1}={}){try{let n=BigInt(ir(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function co(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function da(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))da(t);Object.freeze(e)}return e}function Ip(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};lt(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:co(String(n),`${t}.reason`)}}function kp(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>Ip(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function Op(e){if(e==null)return null;if(lt(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:co(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=Fe(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=Fe(e.gasLimit,"simulation.gasLimit")),t}function Tp(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{lt(t,`assetDeltas[${r}]`);let n=Fe(t.before,`assetDeltas[${r}].before`),o=Fe(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),s;try{s=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(s!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:co(String(ir(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:s}})}function Np(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{lt(t,`approvalDeltas[${r}]`);let n=Fe(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:Dt(t.token,`approvalDeltas[${r}].token`),spender:Dt(t.spender,`approvalDeltas[${r}].spender`),owner:Dt(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function fa(e={}){lt(e,"input");let t=ao(e),r=t.tx==null?t:lt(t.tx,"tx"),n=Fe(t.chainId??r.chainId,"chainId",{positive:!0}),o=Dt(t.account??t.from??r.from,"account/from"),i=Dt(t.destination??t.to??r.to,"destination/to"),s=String(ir(t.prepareHash,"prepareHash")).toLowerCase();if(!xp.test(s))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let u=t.route??t.venue;if(u==null)throw new TypeError("sign-time review: route/venue required");let a=t.decodedCalldata??t.decodedAction;if(a==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let c=String(ir(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!Ep.test(c))throw new TypeError("sign-time review: calldata/data must be even-length hex");let d=t.policyChecks!==void 0&&t.policyChecks!==null,l=kp(d?t.policyChecks:[]),m=Op(t.simulation),f=Tp(t.assetDeltas),p=Np(t.approvalDeltas),w=t.allowlistHits??[];if(!Array.isArray(w))throw new TypeError("sign-time review: allowlistHits must be an array");let g=m?.willRevert===!0||["failed","error"].includes(m?.status),h=m!=null&&m.willRevert===!1&&["ok","success"].includes(m.status),y=g||l.failed>0?"BLOCKED":h&&d&&l.checks.length>0&&f!=null?"READY":"UNKNOWN",b=typeof a=="string"?a:a.method??a.action??a.type??"transaction",S=`${y}: review ${b} on chain ${n}; policy ${l.passed} passed, ${l.failed} failed; ${f?.length??0} asset delta${f?.length===1?"":"s"}; local signature required`,A={reviewVersion:1,status:y,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:u,venue:t.venue??(typeof u=="string"?u:u.venue??u.provider??null),destination:i,to:i,...t.spender==null?{}:{spender:Dt(t.spender,"spender")},prepareHash:s,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:c,data:c,selector:c.length>=10?c.slice(0,10):null,value:Fe(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:Fe(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:Fe(t.gasLimit??r.gasLimit,"gasLimit")},simulation:m,policyChecks:l,allowlistHits:w,assetDeltas:f,approvalDeltas:p,summary:S};return da(A)}import{readFileSync as Cp,readdirSync as _p,existsSync as wa}from"node:fs";import{dirname as Lp,join as Ft}from"node:path";import{fileURLToPath as Rp}from"node:url";var sr=Lp(Rp(import.meta.url));function $p(){let e=[Ft(sr,"descriptors"),Ft(sr,"clear-sign","descriptors"),Ft(sr,"..","clear-sign","descriptors"),Ft(sr,"..","..","clear-sign","descriptors"),Ft(sr,"..","..","..","clear-sign","descriptors")];for(let t of e)if(wa(t))return t;return e[0]}var Pp=$p(),Bp=/^0x[0-9a-f]{8}/,Dp=/^0x[0-9a-fA-F]{40}$/;function Fp(e=Pp){if(!wa(e))return[];let t=[];for(let r of _p(e).filter(n=>n.endsWith(".json")).sort()){let n=Cp(Ft(e,r),"utf8"),o;try{o=JSON.parse(n)}catch(i){throw new Error(`clear-sign descriptor ${r} is not valid JSON: ${i.message}`)}t.push({file:r,doc:o})}return t}function jp(e,{to:t=null,chainId:r=null}={},n=Fp()){let o=String(e||"").toLowerCase(),i=Bp.test(o)?o.slice(0,10):null;if(!i)return null;let s=t&&Dp.test(String(t))?String(t).toLowerCase():null;for(let{file:u,doc:a}of n){let c=a?.display?.formats||{};for(let[d,l]of Object.entries(c)){if(String(l?.$selector||"").toLowerCase()!==i)continue;let m=a?.context?.contract?.deployments||[],f=m.length===0,p=m.some(w=>(r==null||Number(w.chainId)===Number(r))&&s&&String(w.address||"").toLowerCase()===s);if(f||p)return{file:u,signature:d,format:l,doc:a,selector:i,generic:f}}}return null}function ha(e,t){let r=e.slice(t*64,t*64+64);return r.length===64?r:null}function qp(e,t){let r=ha(e,t);return r?`0x${r.slice(24)}`:null}function pa(e,t){let r=ha(e,t);return r?BigInt(`0x${r}`).toString():null}var Mp=(1n<<256n)-1n;function ma(e){if(e==null)return"unknown";let t=BigInt(e);return t>=Mp/2n?"UNLIMITED":t.toString()}function ga(e,{to:t=null,chainId:r=null}={},n=void 0){let o=jp(e,{to:t,chainId:r},n);if(!o)return null;let i=String(e||"").toLowerCase(),s=i.slice(10),u=[],a=[];for(let c of o.format.fields||[]){if(c.visible==="never")continue;let d=c.$wordIndex,l=null;Number.isInteger(d)&&(l=c.format==="addressName"||c.format==="raw-address"?qp(s,d):c.format==="amount"||c.format==="tokenAmount"?ma(pa(s,d)):pa(s,d)),l!=null&&(a.push({label:c.label,value:l}),u.push(`${c.label}: ${l}`))}if(oe(i)){let c=null,d=null;try{c=Re(i)}catch(l){let m=String(l?.message||l);if(/unlimited approvals are refused/i.test(m))d="ORACLE POLICY: unlimited approval \u2014 Oracle refuses to prepare this; bound the amount";else return{ok:!1,refused:`descriptor matched but reviewed decoder refused: ${m}`,intent:o.format.intent}}if(c){let l=a.find(p=>/spender/i.test(p.label))?.value?.toLowerCase();if(l&&c.spender&&l!==c.spender.toLowerCase())return{ok:!1,refused:"descriptor spender disagrees with reviewed decoder",intent:o.format.intent};let m=a.find(p=>/amount|allowance/i.test(p.label))?.value,f=ma(c.amount);if(m!=null&&c.amount!=null&&String(m)!==f)return{ok:!1,refused:"descriptor amount disagrees with reviewed decoder",intent:o.format.intent}}return d&&u.push(d),{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:a,lines:u,...d?{policyNote:d}:{}}}return{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:a,lines:u}}var Hp=/^0x[0-9a-f]{40}$/;function ar(e){let t=String(e??"").toLowerCase();return Hp.test(t)?t:null}function zp(e,{token:t,owner:r}){if(!oe(e))return[];let n;try{n=Re(e)}catch{return[]}let o={token:ar(n.token??t),spender:ar(n.spender),owner:ar(r),amount:n.amount};return o.token&&o.spender&&o.owner&&o.amount!=null?[o]:[]}function Wp(e,t,r={}){let n=e?.version===1&&e?.surface?e:null,o=n?.surface||"evm";if(o!=="evm"&&o!=="evm-nft")return null;let i=n?.artifact||e||{},s=ar(n?.owner??i.from),u=ar(i.to??n?.destination),a=String(i.data??"0x").toLowerCase();if(!s||!u)return null;let c=[],d=r?.destinationAllowlist;if(Array.isArray(d)&&d.length){let l=d.map(m=>String(m).toLowerCase()).includes(u);c.push({name:"destination-allowlist",passed:l,reason:l?"destination is allowlisted":"destination is not on the allowlist"})}try{return fa({chainId:i.chainId,account:s,destination:u,calldata:a,value:i.value??0,prepareHash:t,route:n?.provider??n?.venue??o,decodedAction:n?.action??"transaction",...i.gasLimit==null?{}:{gasLimit:i.gasLimit},...c.length?{policyChecks:c}:{},approvalDeltas:zp(a,{token:u,owner:s})})}catch{return null}}function ya(e,t,r={}){let n=Wp(e,t,r);if(!n)return[];let o=[`REVIEW status=${n.status} action=${n.decodedAction??"transaction"} selector=${n.selector??"none"}`,`REVIEW route=${typeof n.route=="string"?n.route:n.venue??"n/a"} value=${n.value} signing=local custody=${n.custody}`];n.policyChecks.checks.length&&o.push(`REVIEW policy passed=${n.policyChecks.passed} failed=${n.policyChecks.failed}${n.policyChecks.failed?` reasons=${n.policyChecks.reasons.join("; ")}`:""}`);for(let i of n.approvalDeltas)o.push(`REVIEW APPROVAL token=${i.token} spender=${i.spender} amount=${i.amount} revokeLike=${i.revokeLike}`);n.assetDeltas==null&&o.push("REVIEW assetDeltas=unavailable (no simulated balance change supplied)"),n.status!=="READY"&&o.push("REVIEW status is not READY: these facts are decoded, not proven safe.");try{let i=e?.artifact||e||{},s=ga(String(i.data??"0x"),{to:i.to??null,chainId:i.chainId??null});if(s?.ok){o.push(`CLEAR-SIGN intent=${s.intent} [${s.descriptor}]`);for(let u of s.lines)o.push(`CLEAR-SIGN ${u}`)}else s&&s.refused&&o.push(`CLEAR-SIGN REFUSED: ${s.refused}`)}catch{}return o}import{Wallet as uo}from"ethers";import{base58 as lo}from"@scure/base";import{ed25519 as Aa}from"@noble/curves/ed25519.js";import{NETWORK as va,TEST_NETWORK as Ia,WIF as Up,p2wpkh as ba}from"@scure/btc-signer";import{pubECDSA as Vp}from"@scure/btc-signer/utils.js";var Yr=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Jp=e=>{let t=String(e||"").trim();if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return null;let r=Buffer.from(t,"base64");return r.toString("base64")===t?r:null},Ea=e=>{let t=String(e||"").trim();try{let r=Buffer.from(lo.decode(t));return lo.encode(r)===t?r:null}catch{return null}},fo=e=>{if(!(e instanceof Uint8Array))throw new Error("sol: key bytes required");if(e.length!==32&&e.length!==64)throw new Error("sol: expected 32-byte private key material");let t=Buffer.from(e.subarray(0,32));if(e.length===64){let r=Buffer.from(e.subarray(32,64)),n=Buffer.from(Aa.getPublicKey(t));if(!r.equals(n))throw new Error("sol: supplied public key does not match seed")}return t},xa=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),je=(e,t)=>{if(t==="sol")return fo(e);if(!(e instanceof Uint8Array))throw new Error(`${t}: key bytes required`);if(e.length===32)return Buffer.from(e);if(e.length===64)return Buffer.from(e.subarray(0,32));throw new Error(`${t}: expected 32-byte private key material`)},Kp=(e,t)=>{if(!Array.isArray(e))throw new Error(`${t}: expected byte array`);let r=Buffer.alloc(e.length);for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>255)throw new Error(`${t}: expected integer bytes in 0..255`);r[n]=o}return je(r,t)};function po(e,t){let r=String(t||"").trim();if(e==="evm")return new uo(r).privateKey;if(e==="btc")for(let i of[va,Ia])try{return Buffer.from(Up(i).decode(r))}catch{}if(e==="sol"){if(/^hex:/i.test(r)){let c=Yr(r.slice(4));if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}if(/^base58:/i.test(r)){let c=Ea(r.slice(7));if(!xa(c))throw new Error("sol: invalid explicit base58 private key");return fo(c)}if(/^0x/i.test(r)){let c=Yr(r);if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}let i=Yr(r),s=i&&(i.length===32||i.length===64)?je(i,"sol"):null,u=Ea(r),a=xa(u);if(s&&a&&!s.equals(a))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(a)return fo(u);if(i)return je(i,"sol")}let n=Yr(r);if(n)return e==="evm"?new uo(`0x${n.toString("hex")}`).privateKey:je(n,e);let o=Jp(r);if(o)return je(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Kp(i,e);let s=i.privateKey??i.secretKey??i.key;if(s)return po(e,Array.isArray(s)?JSON.stringify(s):String(s))}throw new Error(`${e}: unsupported private key format`)}function Sa(e,t){if(e==="evm"){let r=new uo(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=je(t,"btc"),n=Vp(r);return{kind:e,secret:r.toString("hex"),addresses:[ba(n,va).address,ba(n,Ia).address]}}if(e==="sol"){let r=je(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[lo.encode(Aa.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function ka(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:Sa(t.kind||"evm",po(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=Sa(i,po(i,n[i])));if(n.cex!==void 0){if(!n.cex||typeof n.cex!="object"||Array.isArray(n.cex))throw new Error("local-vault: cex credential records invalid");o.cex={};for(let[i,s]of Object.entries(n.cex)){if(!/^[A-Za-z0-9._-]{1,64}$/.test(i)||!s||typeof s!="object")throw new Error("local-vault: cex credential record invalid");if(!/^(?:binance|bybit|okx|coinbase)$/.test(s.venue)||!/^[A-Za-z0-9._-]{1,64}$/.test(s.accountId||""))throw new Error("local-vault: cex credential binding invalid");let u=(c,d=!0)=>{let l=s[c];if(!(!d&&l===void 0)){if(!Array.isArray(l)||l.length<4||l.some(m=>!Number.isInteger(m)||m<0||m>255))throw new Error("local-vault: cex credential bytes invalid");return Buffer.from(l)}},a=s.apiSecretEncoding;if(a!==(s.venue==="coinbase"?"base64":"raw"))throw new Error("local-vault: explicit cex secret encoding refused");o.cex[i]=Object.freeze({venue:s.venue,accountId:s.accountId,apiKeyBytes:u("apiKeyBytes"),apiSecretBytes:u("apiSecretBytes"),apiSecretEncoding:a,passphraseBytes:u("passphraseBytes",!1)})}if(!Object.keys(o.cex).length)throw new Error("local-vault: empty cex credential records refused");Object.freeze(o.cex)}if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function mo(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var Gp=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),Yp=Object.freeze(["binance","bybit","okx","coinbase"]),Xp=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),Zp=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),Qp=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),H0=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),em=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),z0=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),W0=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),U0=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),V0=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"});function wo(e,t){let r=String(e??"");if(!/^\d+$/.test(r))throw new Error(`cex-policy: ${t} must be an integer string`);return BigInt(r)}function le(e,t,r){let n=String(e??"");if(!r.test(n))throw new Error(`cex-policy: bounded ${t} required`);return n}function Oa(e,t){let r=String(e??"");if(!/^(?:0|[1-9]\d{0,29})(?:\.\d{1,18})?$/.test(r))throw new Error(`cex-policy: positive decimal ${t} required`);let[n,o=""]=r.split("."),i=BigInt(`${n}${o}`);if(i<=0n)throw new Error(`cex-policy: positive decimal ${t} required`);return{text:r,numerator:i,scale:o.length}}function tm(e,t){let r=e.numerator*t.numerator,n=10n**BigInt(e.scale+t.scale);return(r+n-1n)/n}function rm(e){return new Date(e).toISOString().slice(0,10)}function nm(e,t){let r=le(e.credentialRef,"credentialRef",/^[A-Za-z0-9._-]{1,64}$/),n=t.cexAccounts?.[r];if(!n||typeof n!="object")throw new Error("cex-policy: sealed account policy required");return{credentialRef:r,account:n}}function Xr(e={},t={},r=Date.now()){for(let C of Object.keys(e)){let z=C.toLowerCase();if(em.some(W=>W.toLowerCase()===z))throw new Error(`cex-policy: envelope field ${C} forbidden`);if(!Qp.includes(C))throw new Error(`cex-policy: envelope field ${C} not in allowlist`)}if(e.version!==1)throw new Error("cex-policy: version 1 required");if(e.surface!=="cex")throw new Error("cex-policy: surface cex required");let n=String(e.kind||"");if(!Gp.includes(n))throw new Error(`cex-policy: kind ${n||"(none)"} refused`);let o=le(e.venue,"venue",/^[a-z0-9._-]{1,32}$/);if(!Yp.includes(o)||!Xp[o]||!Zp[o])throw new Error(`cex-policy: venue ${o} unknown`);let{credentialRef:i,account:s}=nm(e,t);if(!Array.isArray(s.venues)||!s.venues.includes(o))throw new Error(`cex-policy: venue ${o} not allowlisted`);let u=le(e.symbol,"symbol",/^[A-Z0-9._/-]{1,32}$/);if(!Array.isArray(s.symbols)||!s.symbols.includes(u))throw new Error(`cex-policy: symbol ${u} not allowlisted`);let a=le(e.quote,"quote",/^[A-Z0-9._-]{1,24}$/);if(!s.symbolQuotes||typeof s.symbolQuotes!="object"||s.symbolQuotes[u]!==a)throw new Error("cex-policy: quote does not match sealed symbol policy");let c=le(s.accountId,"accountId",/^[A-Za-z0-9._-]{1,64}$/);if(!Array.isArray(s.allowedOperations)||!s.allowedOperations.includes(n))throw new Error("cex-policy: operation not in sealed allowlist");let d=le(e.base,"base",/^[A-Z0-9._-]{1,24}$/);if(s.base!==d||s.quote!==a)throw new Error("cex-policy: base/quote do not match sealed account policy");if(s.credentialRecordRef!==i)throw new Error("cex-policy: credential record reference mismatch");let l=s.filters?.[u];if(!l||typeof l.tickSize!="string"||typeof l.stepSize!="string"||typeof l.minNotional!="string")throw new Error("cex-policy: sealed symbol filters required");le(e.nonce,"nonce",/^[A-Za-z0-9._:-]{1,128}$/),le(e.grantId,"grantId",/^[A-Za-z0-9._:-]{1,128}$/),le(e.artifactHash,"artifactHash",/^[A-Za-z0-9._:-]{1,128}$/);let m=e.clientOrderId===void 0?void 0:le(e.clientOrderId,"clientOrderId",/^[A-Za-z0-9._-]{1,64}$/),f,p,w,g,h=0n,y=0n,b;if(n==="spot-limit-create"){if(f=le(e.side,"side",/^(?:buy|sell)$/),p=le(e.timeInForce,"timeInForce",/^GTC$/),w=Oa(e.baseSize,"baseSize"),g=Oa(e.limitPrice,"limitPrice"),!m)throw new Error("cex-policy: clientOrderId required");if(h=wo(e.maxQuoteNotional,"maxQuoteNotional"),y=tm(w,g),h<y)throw new Error("cex-policy: maxQuoteNotional understates baseSize times limitPrice")}else{for(let C of["side","baseSize","limitPrice","maxQuoteNotional","timeInForce"])if(e[C]!==void 0)throw new Error(`cex-policy: ${C} forbidden for cancel/status`);if(b=e.venueOrderId===void 0?void 0:le(e.venueOrderId,"venueOrderId",/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/),!b&&!m)throw new Error("cex-policy: exact prior order id required")}let S=wo(s.perOrderQuoteCap,"sealed perOrderQuoteCap"),A=wo(s.dailyGrossQuoteCap,"sealed dailyGrossQuoteCap");if(h>S)throw new Error("cex-policy: maxQuoteNotional exceeds sealed perOrderQuoteCap");if(h>A)throw new Error("cex-policy: maxQuoteNotional exceeds sealed dailyGrossQuoteCap");let k=Number(e.expiresAtMs);if(!Number.isSafeInteger(k)||k<=r||k-r>12e4)throw new Error("cex-policy: bounded expiry required");let v=`cex:${i}:${o}:${c}:${m||b}`,_=`cex:${i}:${c}:${o}:${a}:${rm(r)}`;return Object.freeze({kind:n,venue:o,symbol:u,base:d,quote:a,side:f,timeInForce:p,baseSize:w?.text,limitPrice:g?.text,clientOrderId:m,venueOrderId:b,filter:Object.freeze({...l}),accountId:c,credentialRef:i,tradeId:v,unit:_,notional:h.toString(),impliedNotional:y.toString()})}function Ta({envelope:e,paths:t,nowMs:r=Date.now()}){let n=Kr(t.policy,t.policyKey,{sequenceAnchorFile:t.policyAnchor}),o=Xr(e,n,r);return or({file:t.ledger,keyFile:t.policyKey,anchorFile:t.ledgerAnchor,policyAnchorFile:t.policyAnchor,tradeId:o.tradeId,unit:o.unit,value:o.notional,notional:o.notional,policy:n,nowMs:r})}import J from"node:fs";import dt from"node:path";import{createHmac as om,randomBytes as im,timingSafeEqual as sm}from"node:crypto";var Zr=(e,t)=>om("sha256",e).update(JSON.stringify(t)).digest("hex"),Na=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&sm(r,n)},Ca=e=>Buffer.from(R(e));function _a({file:e,keyFile:t,anchorFile:r}){if(!e||!t||!r)throw new Error("cex-state: protected paths required");if(dt.dirname(dt.resolve(e))===dt.dirname(dt.resolve(r)))throw new Error("cex-state: external rollback anchor required");let n=`${e}.lock`,o=(()=>{try{return J.readFileSync(`/proc/${process.pid}/stat`,"utf8").trim().split(/\s+/)[21]}catch{return null}})(),i=d=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,d),s=d=>{if(!Number.isSafeInteger(d.pid)||d.pid<1||typeof d.processStart!="string"||!d.processStart)return null;try{process.kill(d.pid,0)}catch(l){return l?.code==="ESRCH"?!1:null}try{return J.readFileSync(`/proc/${d.pid}/stat`,"utf8").trim().split(/\s+/)[21]===d.processStart}catch{return null}},u=d=>{J.mkdirSync(dt.dirname(n),{recursive:!0,mode:448});let l=im(16).toString("hex"),m=Date.now()+5e3,f=`${n}.${process.pid}.${l}.tmp`,p=JSON.stringify({version:1,pid:process.pid,processStart:o,token:l,createdAtMs:Date.now()})+`
16
16
  `;for(;;)try{let w=J.openSync(f,"wx",384);try{J.writeFileSync(w,p),J.fsyncSync(w)}finally{J.closeSync(w)}try{J.linkSync(f,n)}finally{J.unlinkSync(f)}break}catch(w){try{J.existsSync(f)&&J.unlinkSync(f)}catch{}if(w?.code!=="EEXIST")throw new Error("cex-state: lock refused");let g;try{g=J.readFileSync(n,"utf8")}catch(b){if(b?.code==="ENOENT")continue;throw new Error("cex-state: corrupt lock refused")}let h;try{h=JSON.parse(g)}catch{throw new Error("cex-state: corrupt lock refused")}if(h?.version!==1||!/^[0-9a-f]{32}$/.test(h.token||"")||!Number.isSafeInteger(h.createdAtMs))throw new Error("cex-state: corrupt lock refused");if(s(h)===!1&&Date.now()-h.createdAtMs>3e4){try{J.unlinkSync(n)}catch{throw new Error("cex-state: stale lock recovery refused")}continue}if(Date.now()>=m)throw new Error("cex-state: lock busy");i(10)}try{return d()}finally{let w;try{w=JSON.parse(J.readFileSync(n,"utf8"))}catch{throw new Error("cex-state: lock ownership lost")}if(w.token!==l||w.pid!==process.pid||w.processStart!==o)throw new Error("cex-state: lock ownership lost");J.unlinkSync(n)}},a=()=>{let d=Ca(t);try{if(!J.existsSync(e)){if(J.existsSync(r))throw new Error("cex-state: rollback detected");return{version:1,sequence:0,orders:[]}}let l=JSON.parse(R(e));if(!Na(l.mac,Zr(d,l.state)))throw new Error("cex-state: integrity failed");let m=JSON.parse(R(r));if(!Na(m.mac,Zr(d,m.marker))||m.marker.sequence!==l.state.sequence||m.marker.stateMac!==l.mac)throw new Error("cex-state: rollback detected");return l.state}finally{d.fill(0)}},c=d=>{let l=Ca(t);try{let m={...d,sequence:d.sequence+1},f=Zr(l,m),p={version:1,sequence:m.sequence,stateMac:f};return J.mkdirSync(dt.dirname(e),{recursive:!0,mode:448}),J.mkdirSync(dt.dirname(r),{recursive:!0,mode:448}),Ae(r,JSON.stringify({marker:p,mac:Zr(l,p)})+`
17
17
  `),Ae(e,JSON.stringify({state:m,mac:f})+`
18
18
  `),m}finally{l.fill(0)}};return Object.freeze({getByTradeId(d){return u(()=>a().orders.find(l=>l.tradeId===d)||null)},prepare(d){return u(()=>{let l=a(),m=l.orders.find(p=>p.tradeId===d.tradeId||p.requestDigest===d.requestDigest);if(m)throw new Error(`cex-state: ${m.state} order requires status reconciliation; create not resent`);let f={...d,state:"prepared",preparedAtMs:d.nowMs};return c({...l,orders:[...l.orders,f]}),Object.freeze(f)})},transition(d,l,m,f={}){return u(()=>{let p=a(),w=p.orders.findIndex(h=>h.tradeId===d);if(w<0)throw new Error("cex-state: durable prior order required");if(![].concat(l).includes(p.orders[w].state))throw new Error(`cex-state: ${p.orders[w].state} status requires reconciliation`);let g={...p.orders[w],...f,state:m};return p.orders[w]=g,c(p),Object.freeze(g)})},requirePrior({venue:d,accountId:l,credentialRef:m,symbol:f,venueOrderId:p}){return u(()=>{let w=a().orders.find(g=>g.venue===d&&g.accountId===l&&g.credentialRef===m&&g.symbol===f&&g.venueOrderId===p);if(!w)throw new Error("cex-state: exact durable prior order required");return Object.freeze(w)})}})}import{createHash as gm}from"node:crypto";import{createHash as am}from"node:crypto";var yo=Object.freeze({binance:Object.freeze({create:["POST","/api/v3/order"],cancel:["DELETE","/api/v3/order"],status:["GET","/api/v3/order"]}),bybit:Object.freeze({create:["POST","/v5/order/create"],cancel:["POST","/v5/order/cancel"],status:["GET","/v5/order/realtime"]}),okx:Object.freeze({create:["POST","/api/v5/trade/order"],cancel:["POST","/api/v5/trade/cancel-order"],status:["GET","/api/v5/trade/order"]}),coinbase:Object.freeze({create:["POST","/orders"],cancel:["DELETE","/orders/{order_id}"],status:["GET","/orders/{order_id}"]})}),cr=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),cm=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,um=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/,La=(e,t)=>{let r=String(e??"");if(!cm.test(r))throw new Error(`cex: ${t} must be a decimal string`);let[n,o=""]=r.split(".");return{text:r,integer:BigInt(n+o),scale:o.length}};var ho=(e,t)=>{let r=String(e??"");if(!um.test(r))throw new Error(`cex: bounded ${t} required`);return r},go=e=>{if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(go).join(",")}]`;if(e&&typeof e=="object")return`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${go(e[t])}`).join(",")}}`;throw new Error("cex: non-canonical request fact refused")};function lm(e){if(!e||!["create","cancel","status"].includes(e.operation))throw new Error("cex: operation refused");if(!/^[A-Z0-9._/-]{1,32}$/.test(String(e.symbol||"")))throw new Error("cex: symbol required");if(e.operation==="create"){if(!/^(?:buy|sell)$/.test(e.side)||e.timeInForce!==void 0&&e.timeInForce!=="GTC")throw new Error("cex: LIMIT GTC spot order required");La(e.baseSize,"baseSize"),La(e.limitPrice,"limitPrice"),ho(e.clientOrderId,"clientOrderId")}else ho(e.venueOrderId,"venueOrderId");return e}function dm(e,t){let r=t.side==="buy"?"BUY":"SELL";if(e==="binance")return t.operation==="create"?{params:{symbol:t.symbol,side:r,type:"LIMIT",timeInForce:"GTC",quantity:t.baseSize,price:t.limitPrice,newClientOrderId:t.clientOrderId}}:{params:{symbol:t.symbol,orderId:t.venueOrderId}};if(e==="bybit"){let n=t.operation==="create"?{category:"spot",symbol:t.symbol,side:r==="BUY"?"Buy":"Sell",orderType:"Limit",qty:t.baseSize,price:t.limitPrice,timeInForce:"GTC",orderLinkId:t.clientOrderId,isLeverage:0}:{category:"spot",symbol:t.symbol,orderId:t.venueOrderId};return t.operation==="status"?{params:n}:{body:n}}if(e==="okx"){let n=t.operation==="create"?{instId:t.symbol,tdMode:"cash",clOrdId:t.clientOrderId,side:t.side,ordType:"limit",sz:t.baseSize,px:t.limitPrice}:{instId:t.symbol,ordId:t.venueOrderId};return t.operation==="status"?{params:n}:{body:n}}if(e==="coinbase")return{body:t.operation==="create"?{type:"limit",side:t.side,product_id:t.symbol,size:t.baseSize,price:t.limitPrice,time_in_force:"GTC",client_oid:t.clientOrderId}:void 0};throw new Error("cex: venue refused")}function Ra({venue:e,order:t,timestamp:r,recvWindow:n=5e3}){lm(t);let o=yo[e]?.[t.operation];if(!o)throw new Error("cex: venue or operation refused");if(!Number.isSafeInteger(n)||n<1||n>5e3)throw new Error("cex: recvWindow refused");let i=String(r??"");if(!(e==="okx"?/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(i):e==="coinbase"?/^\d{10}(?:\.\d{1,3})?$/.test(i):/^\d{13}$/.test(i)))throw new Error("cex: timestamp refused");let[s,u]=o;u.includes("{order_id}")&&(u=u.replace("{order_id}",encodeURIComponent(ho(t.venueOrderId,"venueOrderId"))));let a={venue:e,operation:t.operation,method:s,path:u,timestamp:i,recvWindow:n,...dm(e,t)};return Object.freeze({...a,params:a.params&&Object.freeze(a.params),body:a.body&&Object.freeze(a.body),requestDigest:am("sha256").update(go(a)).digest("hex")})}import{createHmac as fm}from"node:crypto";var Qr=(e,t,r="hex")=>fm("sha256",e).update(t).digest(r),$a=e=>new URLSearchParams(Object.entries(e||{})).toString(),pm=e=>e===void 0?"":JSON.stringify(e),bo=(e,t)=>{if(!(Array.isArray(e)||e instanceof Uint8Array)||e.length<4||[...e].some(r=>!Number.isInteger(r)||r<0||r>255))throw new Error(`cex: invalid ${t}`);return Buffer.from(e)};function mm(e,t){let r=bo(e.apiSecretBytes,"credential"),n=t==="coinbase"?"base64":"raw";if(e.apiSecretEncoding!==n)throw r.fill(0),new Error("cex: explicit secret encoding refused");if(n==="raw")return r;try{let o=r.toString("ascii");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o))throw new Error("base64");let i=Buffer.from(o,"base64");if(i.length<4||i.toString("base64")!==o)throw i.fill(0),new Error("base64");return i}finally{r.fill(0)}}var ft=e=>Buffer.from(e).toString("utf8");function Pa(e,t){if(t?.venue!==e.venue)throw new Error("cex: credential venue mismatch");let r=bo(t.apiKeyBytes,"credential"),n=mm(t,e.venue),o=t.passphraseBytes?bo(t.passphraseBytes,"credential"):null;try{let i={accept:"application/json"},s=pm(e.body);s&&(i["content-type"]="application/json");let u=$a(e.params),a=e.path;if(e.venue==="binance"){let c=$a({...e.params,timestamp:e.timestamp,recvWindow:String(e.recvWindow)});u=`${c}&signature=${Qr(n,c)}`,i["X-MBX-APIKEY"]=ft(r)}else if(e.venue==="bybit"){let c=e.method==="GET"?u:s;Object.assign(i,{"X-BAPI-API-KEY":ft(r),"X-BAPI-TIMESTAMP":e.timestamp,"X-BAPI-RECV-WINDOW":String(e.recvWindow),"X-BAPI-SIGN":Qr(n,e.timestamp+ft(r)+e.recvWindow+c)})}else if(e.venue==="okx"){let c=a+(u?`?${u}`:"");Object.assign(i,{"OK-ACCESS-KEY":ft(r),"OK-ACCESS-SIGN":Qr(n,e.timestamp+e.method+c+s,"base64"),"OK-ACCESS-TIMESTAMP":e.timestamp,"OK-ACCESS-PASSPHRASE":ft(o||Buffer.alloc(0))})}else Object.assign(i,{"CB-ACCESS-KEY":ft(r),"CB-ACCESS-SIGN":Qr(n,e.timestamp+e.method+a+s,"base64"),"CB-ACCESS-TIMESTAMP":e.timestamp,"CB-ACCESS-PASSPHRASE":ft(o||Buffer.alloc(0))});return{url:cr[e.venue]+a+(u?`?${u}`:""),method:e.method,headers:i,body:s||void 0}}finally{r.fill(0),n.fill(0),o?.fill(0)}}var Ba=256*1024,wm=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/;function hm(e,t,r){if(!t.includes("{order_id}"))return r===t;let[n,o]=t.split("{order_id}");if(!r.startsWith(n)||!r.endsWith(o))return!1;let i=r.slice(n.length,r.length-o.length||void 0),s;try{s=decodeURIComponent(i)}catch{return!1}if(!wm.test(s)||encodeURIComponent(s)!==i)return!1;try{return new URL(r,e).pathname===r&&r===`${n}${i}${o}`}catch{return!1}}async function Eo(e,t){let r=yo[e.venue]?.[e.operation],n=cr[e.venue];if(!r||!n||r[0]!==e.method||!hm(n,r[1],e.path))throw new Error("cex transport refused");let o=Pa(e,t),i=new AbortController,s=setTimeout(()=>i.abort(),5e3);try{let u=await fetch(o.url,{method:o.method,headers:o.headers,body:o.body,redirect:"manual",signal:i.signal});if(u.status<200||u.status>=300)throw new Error("http status");if(u.status>=300&&u.status<400)throw new Error("redirect");let a=new URL(u.url||o.url),c=new URL(cr[e.venue]);if(a.origin!==c.origin)throw new Error("origin");if(!String(u.headers.get("content-type")||"").toLowerCase().startsWith("application/json"))throw new Error("content type");let d=Number(u.headers.get("content-length"));if(Number.isFinite(d)&&d>Ba)throw new Error("size");let l=new Uint8Array(await u.arrayBuffer());if(l.length>Ba)throw new Error("size");let m;try{m=JSON.parse(new TextDecoder().decode(l))}catch{throw new Error("json")}return{statusCode:u.status,value:m,responseBodyBytes:l}}catch{throw new Error("cex transport refused")}finally{clearTimeout(s);for(let u of Object.values(o.headers));o.headers=null,o.body=void 0}}var ym=e=>gm("sha256").update(e).digest("hex"),bm=(e,t)=>e==="okx"?new Date(t).toISOString():String(e==="coinbase"?t/1e3:t),xo=e=>/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/.test(String(e||""))?String(e):null,ur=e=>typeof e=="string"&&/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e)?e:null;var Da=e=>/^0(?:\.0+)?$/.test(String(e));function Em(e,t){if(!ur(e)||!ur(t))throw new Error("cex authoritative decimal refused");let[r,n=""]=e.split("."),[o,i=""]=t.split("."),s=n.length+i.length,u=BigInt(r+n)*BigInt(o+i);if(!s)return u.toString();let a=u.toString().padStart(s+1,"0");return`${a.slice(0,-s)}.${a.slice(-s)}`}function xm(e,t,r){let n,o,i;return e==="binance"&&t?.code===void 0?(n=t?.orderId,o=t?.symbol,i=t?.clientOrderId):e==="bybit"&&t?.retCode===0?(n=t?.result?.orderId,o=t?.result?.symbol,i=t?.result?.orderLinkId):e==="okx"&&t?.code==="0"&&t?.data?.length===1&&t.data[0]?.sCode==="0"?(n=t.data[0].ordId,o=t.data[0].instId,i=t.data[0].clOrdId):e==="coinbase"&&!t?.message&&(n=t?.id,o=t?.product_id,i=t?.client_oid),o!==void 0&&o!==r.symbol||i!==void 0&&i!==r.clientOrderId?null:xo(n)}function Sm(e,t,r){let n=null;return e==="binance"&&t&&typeof t=="object"&&t.code===void 0?n=t.orderId:e==="bybit"&&t?.retCode===0?n=t?.result?.orderId:e==="okx"&&t?.code==="0"&&t?.data?.length===1&&t.data[0]?.sCode==="0"?n=t.data[0].ordId:e==="coinbase"&&typeof t=="string"&&(n=t),xo(n)===r.venueOrderId}function Am(e,t,r){let n=t,o,i,s,u,a;if(e==="binance"?(o=t?.orderId,i=t?.clientOrderId,s=t?.symbol,u={CANCELED:"cancelled",REJECTED:"rejected",FILLED:"filled",PARTIALLY_FILLED:"partial",NEW:"open",PENDING_CANCEL:"open"}[t?.status],a=t?.cummulativeQuoteQty):e==="bybit"&&t?.retCode===0&&t?.result?.list?.length===1?(n=t.result.list[0],o=n.orderId,i=n.orderLinkId,s=n.symbol,u={Cancelled:"cancelled",Rejected:"rejected",Filled:"filled",PartiallyFilled:"partial",New:"open"}[n.orderStatus],a=n.cumExecValue):e==="okx"&&t?.code==="0"&&t?.data?.length===1?(n=t.data[0],o=n.ordId,i=n.clOrdId,s=n.instId,u={canceled:"cancelled",filled:"filled",partially_filled:"partial",live:"open"}[n.state],ur(n.accFillSz)&&ur(n.avgPx)&&(Da(n.accFillSz)||!Da(n.avgPx))&&(a=Em(n.accFillSz,n.avgPx))):e==="coinbase"&&(o=t?.id,i=t?.client_oid,s=t?.product_id,u=t?.status==="done"?t?.done_reason==="canceled"?"cancelled":"filled":{rejected:"rejected",open:"open",pending:"open",active:"open"}[t?.status],a=t?.executed_value),xo(o)!==r.venueOrderId||String(s||"")!==r.symbol||r.clientOrderId&&String(i||"")!==r.clientOrderId||!u||!ur(a))throw new Error("cex authoritative status identity refused");return{status:u,filledQuote:a}}async function vm(e,t){let r=t?.nowMs?.()??Date.now(),n=t?.transport||Eo,o=t.credential(e.credentialRef);if(!o||o.accountId!==e.accountId||o.venue!==e.venue)throw new Error("cex: credential binding refused");let i=e.order.operation!=="create"?e.store.requirePrior({...e,...e.order}):null,s=i?.tradeId||e.tradeId,u=Ra({venue:e.venue,order:e.order,timestamp:bm(e.venue,r),recvWindow:5e3}),a;e.order.operation==="create"?a=e.store.prepare({tradeId:e.tradeId,venue:e.venue,accountId:e.accountId,credentialRef:e.credentialRef,symbol:e.order.symbol,clientOrderId:e.order.clientOrderId,reservedNotional:e.reservedNotional,requestDigest:u.requestDigest,nowMs:r}):a=e.store.transition(s,["open","uncertain","sent","cancel-pending","settlement-pending"],"prepared",{operation:e.order.operation,requestDigest:u.requestDigest,nowMs:r}),e.store.transition(s,"prepared","sent",{sentAtMs:r});let c;try{c=await n(u,o)}catch{throw e.store.transition(s,"sent","uncertain",{uncertainAtMs:r}),new Error("cex transport refused; order is uncertain and requires status reconciliation")}let d=ym(c.responseBodyBytes);if(e.order.operation==="create"){let f=xm(e.venue,c.value,e.order);if(!f)throw e.store.transition(s,"sent","uncertain",{responseDigest:d}),new Error("cex response refused; order is uncertain and requires status reconciliation");return e.store.transition(s,"sent","open",{venueOrderId:f,responseDigest:d,openedAtMs:r})}if(e.order.operation==="cancel")return e.store.transition(s,"sent",Sm(e.venue,c.value,i)?"cancel-pending":"uncertain",{responseDigest:d,observedAtMs:r});let l;try{l=Am(e.venue,c.value,i)}catch{return e.store.transition(s,"sent","uncertain",{responseDigest:d,observedAtMs:r})}let m=["cancelled","rejected","filled"].includes(l.status);if(m||l.status==="partial"){e.store.transition(s,"sent","settlement-pending",{responseDigest:d,observedAtMs:r,status:l.status,filledQuote:l.filledQuote});let f=m&&(l.status==="cancelled"||l.status==="rejected")&&/^0(?:\.0+)?$/.test(l.filledQuote)?"release":"commit";return await t.settleLedger({tradeId:i.tradeId,filledQuote:l.filledQuote,disposition:f}),e.store.transition(s,"settlement-pending","terminal",{settledAtMs:r})}return e.store.transition(s,"sent","open",{responseDigest:d,observedAtMs:r,status:l.status,filledQuote:l.filledQuote})}function Fa(e){if(!e||typeof e.credential!="function"||typeof e.settleLedger!="function")throw new Error("cex: sealed runtime dependencies required");let t=Object.freeze({credential:e.credential,transport:e.transport||Eo,nowMs:e.nowMs||Date.now,settleLedger:e.settleLedger});return Object.freeze({execute:r=>vm(r,t)})}import{createHash as Im,createHmac as ja,randomBytes as km,timingSafeEqual as Om}from"node:crypto";var qa="oracle-local-signer-cex-owner-allow-v1",jt=e=>/^(?:0|[1-9]\d{0,19})$/.test(String(e||""))?String(e):null,Ma=e=>JSON.stringify(e),Tm=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Om(r,n)};function Ha({keyFile:e,approvedTelegramOwners:t,nowMs:r=Date.now}={}){if(!e)throw new Error("cex owner proof: signer policy key required");let n=new Set((t||[]).map(jt).filter(Boolean));if(!n.size)throw new Error("cex owner proof: approved owner context required");let o=new Set,i=u=>{let a=Buffer.from(R(e));try{return u(a)}finally{a.fill(0)}},s=i(u=>Im("sha256").update("cex-owner-instance\0").update(u).digest("hex"));return Object.freeze({mint({digest:u,senderId:a,chatId:c,platform:d,ttlMs:l=15e3}={}){let m=jt(a),f=jt(c),p=r();if(d!=="telegram"||!m||f!==m||!n.has(m))throw new Error("cex owner proof: exact Telegram owner DM required");if(!/^[0-9a-f]{64}$/.test(String(u||""))||!Number.isSafeInteger(l)||l<1||l>3e4)throw new Error("cex owner proof: binding refused");let w={version:1,decision:"Allow",digest:u,ownerSenderId:m,telegramChatId:f,audience:qa,instance:s,nonce:km(16).toString("hex"),issuedAtMs:p,expiresAtMs:p+l},g=i(h=>ja("sha256",h).update(Ma(w)).digest("hex"));return{claims:w,mac:g}},verify(u,{digest:a}={}){let c=u?.claims,d=r();if(!c||c.version!==1||c.decision!=="Allow"||c.digest!==a||c.audience!==qa||c.instance!==s||!/^[0-9a-f]{32}$/.test(c.nonce||"")||jt(c.ownerSenderId)!==jt(c.telegramChatId)||!n.has(jt(c.ownerSenderId))||!Number.isSafeInteger(c.issuedAtMs)||!Number.isSafeInteger(c.expiresAtMs)||c.expiresAtMs<=d||c.issuedAtMs>d||c.expiresAtMs-c.issuedAtMs>3e4||o.has(c.nonce))return!1;let l=i(m=>ja("sha256",m).update(Ma(c)).digest("hex"));return Tm(u.mac,l)?(o.add(c.nonce),!0):!1}})}var Le=new Oo(["function collection() view returns (address)","function token() view returns (address)","function robinhoodSwapFeeWei() view returns (uint256)","function quoteSpecificBuy(uint256 tokenId) view returns (uint256 totalCost,uint256 baseCost,uint256 fee,uint256 protocolFee,bool available)","function quoteSellNFT() view returns (uint256 netPayout,uint256 grossPayout,uint256 fee,uint256 protocolFee)","function inventory(uint256 tokenId) view returns (bool)","function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Wa=new Oo(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),Ao=new Oo(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function Bm({isArmed:e,disarmNow:t}){if(typeof e!="function"||typeof t!="function")throw new TypeError("signer: serialized arm fence callbacks required");let r=1,n=Promise.resolve(),o=i=>{let s=n.then(i,i);return n=s.then(()=>{},()=>{}),s};return Object.freeze({armGeneration:()=>r,disarm:()=>o(()=>(r+=1,t(),!0)),broadcastWithArmFence:(i,s)=>o(async()=>{if(i!==r||!e())throw new Error("signer: disarmed generation changed before broadcast handoff");return s()})})}function Dm(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||re.join(process.env.XDG_STATE_HOME||re.join(Nm.homedir(),".local","state"),"oracle"),r=Cm("sha256").update(re.resolve(e)).digest("hex").slice(0,16);return{vault:re.join(e,"vault.json"),policy:re.join(e,"signer-policy.json"),policyKey:re.join(e,"policy-integrity-key"),policyAnchor:re.join(t,`signer-policy-${r}.high-water`),ledger:re.join(e,"signer-ledger.json"),ledgerAnchor:re.join(t,`signer-ledger-${r}.high-water`),executionOutbox:re.join(e,"signer-execution-outbox.json"),cexOrders:re.join(e,"cex-orders.json"),cexOrdersAnchor:re.join(t,`cex-orders-${r}.high-water`),token:re.join(e,"signer-token"),lock:re.join(t,`signer-${r}.lock`),workflowLedger:re.join(e,"workflow-events.jsonl")}}function Fm(e){try{return R(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=_m(32).toString("hex");return Ae(e,t+`
@@ -24,4 +24,4 @@ Type digest ${t}: `}async function lr(e,t){let r=await fetch(e,{method:"POST",he
24
24
  `)}}),Me=Vi({host:o,port:i,token:Fm(c.token),policy:l,readPolicy:d,isArmed:Ze,disarm:q.disarm,armGeneration:q.armGeneration,broadcastWithArmFence:q.broadcastWithArmFence,sessionExpiresAtMs:mt,executionOutbox:as({path:c.executionOutbox,now:Date.now}),observeExecutionTransaction:Wm({provider:A,readPolicy:d}),nowMs:Date.now,simulate:async(E,I)=>(await W(I,d(),"before simulation"),xr(I,$).simulate(E,I)),estimateNetworkFees:_,sign:async(E,I)=>(await W(I,d(),"before signing"),xr(I,$).sign(E,I)),verifySigned:(E,I,T)=>Fi(T?.surface||"evm",E,I,T),broadcast:async(E,I,T)=>(await W(T,d(),"before broadcast"),xr(T,$).broadcast(E,I,T)),confirmArtifact:async(E,I,T)=>{let j=await W(E,T),G=await nw(E,I,T,j);return G===!0&&j&&C.set(I,j),G},decodeEconomics:(E,I)=>In(E,I),reserveLedger:(E,I,T={})=>{let j=E?.version===1&&E?.surface?E:null,G=j?.artifact||E;if(z(j)){let Qe=Q(j),He=C.get(Qe);if(!He||Date.now()-Number(He.verifiedAtMs)>15e3)throw new Error("signer: fresh independent Anvil attestation required before reservation");let Ht=Hm(I.rpcUrl,G.chainId,j,I,{nowMs:Date.now(),signerAddress:k.address});Ja(He,Ht,"before reservation"),C.set(Qe,Ht)}let dr=j?.tradeId||G?.tradeId;if(!dr)throw new Error("ledger: executable artifact requires a tradeId");let ye;if(j)ye=In(j,I);else{if(G?.value===void 0)throw new Error("ledger: executable artifact value required");let Qe=BigInt(G.value),He=BigInt(G.gasLimit??0),Ht=BigInt(G.maxFeePerGas??G.gasPrice??0);if(He<=0n||Ht<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let To=He*Ht+BigInt(G.l1FeeWei??0)+BigInt(G.operatorFeeWei??0);ye={unit:"wei",value:Qe.toString(),notional:(Qe+To).toString(),fee:To.toString()}}if(Array.isArray(ye.units))return or({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:dr,units:ye.units,policy:I,retryReleasedTradeId:T.retryReleasedTradeId});if(ye.value===void 0||ye.notional===void 0)throw new Error("ledger: decoded value and notional required");return or({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:dr,...ye,policy:I,retryReleasedTradeId:T.retryReleasedTradeId})},commitLedger:E=>oa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),releaseLedger:E=>ia({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),settleFailedLedger:E=>aa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),validateReservation:(E,I,T)=>na({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,reservation:E,policy:I,economics:T}),verifyFeeWaiver:(E,I)=>ua(E,I,c.policyKey),verifyTriggerAttestation:(E,I,T)=>ca(E,I,c.policyKey,T),inspectCex:Xr,verifyOwnerProof:f?(E,I)=>f.verify(E,I):void 0,verifyCexOwnerProof:f?(E,I)=>f.verify(E,I):void 0,cexExecute:K(l,"cex")?async E=>{let I=d(),T=Xr(E,I,Date.now()),j=T.kind==="spot-limit-create"?"create":T.kind==="spot-limit-cancel"?"cancel":"status";j==="create"&&Ta({envelope:E,paths:c,nowMs:Date.now()});let G=j==="create"?{operation:j,symbol:T.symbol,side:T.side,baseSize:T.baseSize,limitPrice:T.limitPrice,clientOrderId:T.clientOrderId}:{operation:j,symbol:T.symbol,venueOrderId:T.venueOrderId};return Fa({credential:ye=>y.cex[ye],settleLedger:({tradeId:ye,disposition:Qe,filledQuote:He})=>sa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:ye,expectedUnit:T.unit,filledQuote:He,disposition:Qe})}).execute({venue:T.venue,accountId:T.accountId,credentialRef:T.credentialRef,tradeId:T.tradeId,reservedNotional:T.notional,order:G,store:_a({file:c.cexOrders,keyFile:c.policyKey,anchorFile:c.cexOrdersAnchor})})}:void 0,ledgerObserver:Ks(process.env)?Gs({path:c.workflowLedger,telemetry:Xs(process.env),onError:E=>{try{console.error(`signer: ${E}`)}catch{}}}):null,autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),wt=setTimeout(()=>Me.close(),s);return wt.unref(),Me.on("close",()=>{clearTimeout(wt),Xe()}),Me.listen(i,o),Me}var en="0x420000000000000000000000000000000000000F";function Ka(e){let t=e?.code;if(t==="CALL_EXCEPTION"||t==="BAD_DATA")return!0;let r=String(e?.shortMessage||e?.message||e);return/network|timeout|ECONN|ENOTFOUND|EAI_AGAIN|server error|fetch failed|socket/i.test(r)?!1:/execution reverted|revert|invalid opcode|function selector|could not decode/i.test(r)}async function tw(e,t){if(!ve(t?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(!e||typeof e.call!="function")throw new Error("policy: rollup fee estimate required");let{Interface:r,Transaction:n}=await import("ethers"),o=new r(["function getL1Fee(bytes) view returns (uint256)","function getOperatorFee(uint256) view returns (uint256)","function operatorFeeScalar() view returns (uint32)","function operatorFeeConstant() view returns (uint64)"]),i;try{i=n.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce??0,type:t.type,accessList:t.accessList}).unsignedSerialized}catch{throw new Error("policy: rollup fee estimate required")}let s;try{let u=await e.call({to:en,data:o.encodeFunctionData("getL1Fee",[i])});s=o.decodeFunctionResult("getL1Fee",u)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:s,operatorFeeWei:await rw(e,o,t.gasLimit)}}async function rw(e,t,r){let n;try{n=BigInt(r)}catch{throw new Error("policy: rollup fee estimate required")}if(n<0n)throw new Error("policy: rollup fee estimate required");try{let o=await e.call({to:en,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Ka(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:en,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:en,data:t.encodeFunctionData("operatorFeeConstant")}),s=BigInt(t.decodeFunctionResult("operatorFeeScalar",o)[0]),u=BigInt(t.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*s/1000000n+u).toString()}catch(o){if(!Ka(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function nw(e,t,r,n=null){return process.stdin.isTTY?(process.stderr.write(zm(e,t,r,n)),process.stdin.resume(),new Promise(o=>{let i=s=>{process.stdin.off("data",i),process.stdin.pause(),o(String(s).trim()===t)};process.stdin.once("data",i)})):!1}var Xa=`oracle signer (--credential-service oracle-local-signer | --passphrase-file <0600 file>) [--port 9462] [--session-seconds 120]
25
25
  Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,tn=(e,t,r)=>{let n=e.indexOf(t);return n>=0?e[n+1]:r};async function iw(e=[],t={}){if(e.includes("--help"))return(t.out||process.stdout).write(Xa+`
26
26
  `),0;let r=tn(e,"--passphrase-file"),n=await Ya({configDir:ow.join(t.configDir||pr(),"signer"),passphraseFile:r,credentialService:tn(e,"--credential-service"),port:Number(tn(e,"--port",9462)),sessionMs:Number(tn(e,"--session-seconds",120))*1e3});return(t.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
27
- `),await new Promise(o=>n.on("close",o)),0}var ox={name:"signer",summary:"run the short-lived loopback signer",usage:Xa,run:e=>iw(e.argv||[])};export{ox as default,iw as run};
27
+ `),await new Promise(o=>n.on("close",o)),0}var nx={name:"signer",summary:"run the short-lived loopback signer",usage:Xa,run:e=>iw(e.argv||[])};export{nx as default,iw as run};
@@ -1,2 +1,2 @@
1
- import{spawnSync as s}from"node:child_process";var o={name:"upgrade",summary:"upgrade installed Hermes lanes",group:"read",usage:"oracle upgrade [--apply ...]",async run(e){let a=e.bin("oracle-upgrade.mjs"),r=s(process.execPath,[a,...e.argv],{stdio:"inherit"});return r.error?(process.stderr.write(`oracle: failed to spawn oracle-upgrade: ${r.error.message}
2
- `),1):typeof r.status=="number"?r.status:1}};export{o as default};
1
+ import{spawnSync as s}from"node:child_process";var n={name:"upgrade",summary:"upgrade installed Hermes lanes",group:"read",usage:"oracle upgrade [--apply ...]",async run(e){let a=e.bin("oracle-upgrade.mjs"),r=s(process.execPath,[a,...e.argv],{stdio:"inherit"});return r.error?(process.stderr.write(`oracle: failed to spawn oracle-upgrade: ${r.error.message}
2
+ `),1):typeof r.status=="number"?r.status:1}};export{n as default};
@@ -0,0 +1,19 @@
1
+ import{randomBytes as V}from"node:crypto";var h="ORACLE_X402_MAX_USD",D="1.00",p=2,S=/^0x[0-9a-fA-F]{40}$/,v=/^eip155:([1-9][0-9]*)$/,L=/^(?:0|[1-9][0-9]*)$/,W=/^0x[0-9a-fA-F]{130}$/,Y=96*1024,N=50;var y=6,w=class extends Error{constructor(n,t="X402_INVALID"){super(`x402: ${n}`),this.name="X402ClientError",this.code=t}};function s(e,n){throw new w(e,n)}function m(e,n,{max:t=2048}={}){let r=String(e??"").trim();return(!r||r.length>t)&&s(`${n} is missing or oversized`),r}function J(e,n){let t=m(e,n,{max:42});return S.test(t)||s(`${n} must be a 20-byte EVM address`),t}function C(e,n){let t=m(e,n,{max:80});return L.test(t)||s(`${n} must be atomic token units`),BigInt(t)<=0n&&s(`${n} must be positive`),t}function G(e=process.env){let n=String(e?.[h]??"").trim();if(!/^\d+(\.\d{1,6})?$/.test(n))return D;let[t,r=""]=n.split("."),o=BigInt(t)*10n**BigInt(y)+BigInt(r.padEnd(y,"0")||"0");return o<=0n?D:x(o)}function H(e){let[n,t=""]=String(e).split(".");return BigInt(n)*10n**BigInt(y)+BigInt(t.padEnd(y,"0")||"0")}function x(e){let n=10n**BigInt(y),t=e/n,r=(e%n).toString().padStart(y,"0").slice(0,2);return`${t}.${r}`}function Q(e){if(e&&typeof e=="object"&&!Array.isArray(e))return e;let n=String(e??"").trim();if((!n||n.length>Y)&&s("PAYMENT-REQUIRED payload is missing or oversized"),n.startsWith("{"))try{return JSON.parse(n)}catch{return s("PAYMENT-REQUIRED body is not valid JSON")}if(!/^[A-Za-z0-9+/_-]+={0,2}$/.test(n)||n.length%4===1)return s("PAYMENT-REQUIRED header is not valid Base64");let t=n.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4);try{let o=Buffer.from(r,"base64").toString("utf8");if(!o.trim().startsWith("{"))throw new Error("shape");return JSON.parse(o)}catch{return s("PAYMENT-REQUIRED header is not valid Base64 JSON")}}function F(e,n){let t=e?.resource;return!t||typeof t!="object"||Array.isArray(t)?Object.freeze({url:n,description:"",mimeType:""}):Object.freeze({url:m(t.url??n,"resource.url"),description:String(t.description??""),mimeType:String(t.mimeType??"")})}function Z(e){if(!e||typeof e!="object"||Array.isArray(e))return Object.freeze({});let n={};for(let t of["assetTransferMethod","name","version"])typeof e[t]=="string"&&e[t].trim()&&(n[t]=e[t].trim());return Object.freeze(n)}function K(e,n){(!e||typeof e!="object"||Array.isArray(e))&&s(`accepts[${n}] must be an object`);let t=Number(e.maxTimeoutSeconds);return(!Number.isInteger(t)||t<=0)&&s(`accepts[${n}].maxTimeoutSeconds must be a positive integer`),Object.freeze({scheme:m(e.scheme,`accepts[${n}].scheme`,{max:64}).toLowerCase(),network:m(e.network,`accepts[${n}].network`,{max:128}),amount:C(e.amount,`accepts[${n}].amount`),asset:m(e.asset,`accepts[${n}].asset`,{max:128}),payTo:m(e.payTo,`accepts[${n}].payTo`,{max:128}),maxTimeoutSeconds:t,extra:Z(e.extra)})}function ee(e,{url:n}={}){let t=Q(e);return t?.x402Version!==p&&s(`only x402Version ${p} is supported (saw ${JSON.stringify(t?.x402Version)})`,"X402_VERSION"),(!Array.isArray(t.accepts)||t.accepts.length===0||t.accepts.length>N)&&s(`accepts must contain 1-${N} requirements`),Object.freeze({x402Version:p,error:typeof t.error=="string"?t.error:"",resource:F(t,n),accepts:Object.freeze(t.accepts.map(K))})}function te(e){let n=e.accepts.filter(t=>t.scheme==="exact"&&v.test(t.network)&&S.test(t.asset)&&S.test(t.payTo)&&(t.extra.assetTransferMethod??"eip3009")==="eip3009");return n.length===0&&s(`no supported requirement: this client implements scheme=exact on eip155 networks with the eip3009 transfer method. Offered: ${e.accepts.map(t=>`${t.scheme}/${t.network}`).join(", ")}`,"X402_UNSUPPORTED"),n.sort((t,r)=>BigInt(t.amount)<BigInt(r.amount)?-1:BigInt(t.amount)>BigInt(r.amount)?1:0)[0]}function _(e,n){try{return e?.headers?.get?.(n)??null}catch{return null}}async function g(e){try{let n=await e.text();return n&&n.trim()?n:null}catch{return null}}function ne(e){if(!e)return null;try{let n=Buffer.from(String(e),"base64").toString("utf8"),t=JSON.parse(n);return t&&typeof t=="object"?t:null}catch{return null}}async function P(e,n={}){let t=m(e,"url"),r;try{r=new URL(t)}catch{return s("url must be an absolute http(s) URL")}["http:","https:"].includes(r.protocol)||s("url must be http or https"),(r.username||r.password)&&s("url must not carry credentials");let o=J(n.payer,"payer"),u=n.env??process.env,l=Number(n.nowMs??Date.now()),a=Math.floor(l/1e3),d=n.fetchImpl??globalThis.fetch;typeof d!="function"&&s("no fetch implementation available","X402_TRANSPORT");let i=await d(r.toString(),{method:n.method??"GET",headers:{accept:"application/json"},signal:n.signal,...n.timeoutMs===null?{}:{}}),f=Number(i?.status);if(f>=200&&f<300)return Object.freeze({kind:"x402-payment",x402Version:p,url:r.toString(),status:f,paymentRequired:!1,paid:!1,typedData:null,accepted:null,requiresWalletSignature:!1,backendSigner:!1,body:await g(i),note:"The resource answered without requiring payment. Nothing was signed and nothing is owed."});if(f!==402){let O=await g(i);s(`request failed with HTTP ${f}${O?`: ${String(O).slice(0,300)}`:""}. A non-402 failure is an upstream error, not a payment requirement.`,"X402_HTTP_ERROR")}let T=_(i,"PAYMENT-REQUIRED"),M=T?null:await g(i),E=ee(T??M,{url:r.toString()}),c=te(E),A=Number(v.exec(c.network)[1]),$=G(u),B=H($);BigInt(c.amount)>B&&s(`payment of ${x(BigInt(c.amount))} USD exceeds the ${$} USD cap. Raise ${h} deliberately if this spend is intended.`,"X402_CAP");let z=Math.min(Math.max(c.maxTimeoutSeconds,30),3600),k=String(a-60),X=String(a+z),q=`0x${(n.nonceBytes??V(32)).toString("hex")}`,R=c.extra.name,I=c.extra.version;return(!R||!I)&&s("the requirement is missing extra.name or extra.version, which are the token's EIP-712 domain fields. Without them a transferWithAuthorization signature cannot be built correctly.","X402_DOMAIN"),Object.freeze({kind:"x402-payment",x402Version:p,url:r.toString(),status:f,paymentRequired:!0,paid:!1,scheme:c.scheme,assetTransferMethod:c.extra.assetTransferMethod??"eip3009",chainId:A,capUsd:$,amountUsd:x(BigInt(c.amount)),resource:E.resource,accepted:c,payer:o,typedData:Object.freeze({domain:Object.freeze({name:R,version:I,chainId:A,verifyingContract:c.asset}),primaryType:"TransferWithAuthorization",types:Object.freeze({TransferWithAuthorization:Object.freeze([{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}])}),message:Object.freeze({from:o,to:c.payTo,value:c.amount,validAfter:k,validBefore:X,nonce:q})}),requiresWalletSignature:!0,backendSigner:!1,signingReady:!1,broadcastReady:!1,preparedAt:l,note:"Signable EIP-3009 authorization. The user's wallet signs it; oracle x402 submit then re-issues the request with that signature. Oracle holds no key and settles nothing."})}function re(e,n){(!e||e.kind!=="x402-payment"||!e.typedData)&&s("a prepared x402 payment artifact is required");let t=String(n??"").trim();t||s("a wallet signature is required; oracle does not create one"),W.test(t)||s("signature must be a 65-byte hex string (0x + 130 hex chars)");let r={x402Version:p,resource:e.resource,accepted:e.accepted,payload:{signature:t,authorization:{from:e.typedData.message.from,to:e.typedData.message.to,value:e.typedData.message.value,validAfter:e.typedData.message.validAfter,validBefore:e.typedData.message.validBefore,nonce:e.typedData.message.nonce}}};return Buffer.from(JSON.stringify(r),"utf8").toString("base64")}async function U(e,n,t={}){let r=re(e,n),o=t.fetchImpl??globalThis.fetch;typeof o!="function"&&s("no fetch implementation available","X402_TRANSPORT");let u=await o(e.url,{method:t.method??"GET",headers:{accept:"application/json","PAYMENT-SIGNATURE":r},signal:t.signal}),l=Number(u?.status),a=ne(_(u,"PAYMENT-RESPONSE")),d=l>=200&&l<300&&a?.success!==!1;return Object.freeze({kind:"x402-submit",url:e.url,status:l,ok:d,settlement:a?Object.freeze(a):null,body:await g(u),backendSigner:!1,settledByFacilitator:!0,attempts:1,note:d?"The resource server accepted the wallet-signed payment and a facilitator settled it. Oracle moved no funds.":"The payment was not settled. Inspect settlement.errorReason and prepare again deliberately; this client does not retry."})}var b=["oracle x402 prepare <url> --payer 0x.. [--json]","oracle x402 submit <url> --payer 0x.. --signature 0x.. [--json]"].join(`
2
+ `),se=["","prepare does a GET, parses a 402 PAYMENT-REQUIRED, and prints the EIP-3009","typed data your wallet must sign. It does not sign and holds no key.","","submit re-issues the request with the PAYMENT-SIGNATURE header built from a","signature YOU supply. That is the only network write, and it moves no funds","by itself: the facilitator settles the authorization your wallet signed.","",`Spend is capped by ${h} (default 1.00 USD). A payment above the`,"cap is refused, and a malformed cap value falls back to the default."].join(`
3
+ `);function j(e,n){let t=e.find(o=>o.startsWith(`--${n}=`));if(t)return t.slice(n.length+3);let r=e.indexOf(`--${n}`);return r===-1?void 0:e[r+1]}function ae(e){if(!e.paymentRequired){process.stdout.write(`no payment required: HTTP ${e.status}
4
+ ${e.note}
5
+ `);return}let n=[`resource: ${e.resource.url}`,`description: ${e.resource.description||"(none)"}`,`scheme: ${e.scheme} via ${e.assetTransferMethod}`,`network: ${e.accepted.network} (chainId ${e.chainId})`,`asset: ${e.accepted.asset} (${e.typedData.domain.name} v${e.typedData.domain.version})`,`payTo: ${e.accepted.payTo}`,`amount: ${e.accepted.amount} atomic units = ${e.amountUsd} USD`,`cap: ${e.capUsd} USD (${h})`,`payer: ${e.payer}`,`valid: ${e.typedData.message.validAfter} .. ${e.typedData.message.validBefore}`,"",`typed data: ${e.typedData.primaryType} (--json for the full EIP-712 payload)`,"","Sign the typed data with your wallet, then:",` oracle x402 submit ${e.url} --payer ${e.payer} --signature 0x<65-byte-sig>`,"",e.note];process.stdout.write(`${n.join(`
6
+ `)}
7
+ `)}var ue={name:"x402",summary:"prepare and submit x402 agent payments (never signs)",group:"prepare",usage:b,async run(e){let n=e.argv??[],[t,...r]=n;if(!t||t==="--help"||t==="-h")return process.stdout.write(`${b}
8
+ ${se}
9
+ `),t?0:1;if(!["prepare","submit"].includes(t))return process.stderr.write(`oracle x402: unknown verb "${t}"
10
+ ${b}
11
+ `),1;let o=r.includes("--json"),u=r.find(a=>!a.startsWith("--")&&/^https?:\/\//i.test(a)),l=j(r,"payer");if(!u)return process.stderr.write(`oracle x402: an absolute http(s) url is required
12
+ ${b}
13
+ `),1;try{let a=await P(u,{payer:l});if(t==="prepare")return o?process.stdout.write(`${JSON.stringify(a,null,2)}
14
+ `):ae(a),0;if(!a.paymentRequired)return process.stderr.write(`oracle x402: the resource answered HTTP ${a.status} without requiring payment; nothing to submit
15
+ `),1;let d=j(r,"signature"),i=await U(a,d);return o?process.stdout.write(`${JSON.stringify(i,null,2)}
16
+ `):process.stdout.write([`status: ${i.status}`,`settled: ${i.ok?"yes":"no"}`,i.settlement?.transaction?`transaction: ${i.settlement.transaction}`:null,i.settlement?.errorReason?`reason: ${i.settlement.errorReason}`:null,"",i.note].filter(Boolean).join(`
17
+ `)+`
18
+ `),i.ok?0:2}catch(a){return process.stderr.write(`oracle x402: ${a?.message||a}
19
+ `),1}}};export{ue as default};
@@ -3,4 +3,4 @@ import{createHash as $t}from"node:crypto";import{wordlists as vt}from"ethers";im
3
3
  `),a=[],l=new Map,v=new Set,N=new Set;for(let w=0;w<u.length;w+=1){let g=u[w];if(Buffer.byteLength(g,"utf8")>st)return{ok:!1,reason:"event-size-limit",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};let x;try{x=JSON.parse(g)}catch{return{ok:!1,reason:"malformed-json",line:w+1,count:a.length,workflows:l.size,events:a,paths:r}}let m;try{m=Nn(x)}catch(He){return{ok:!1,reason:"event-invalid",line:w+1,detail:String(He?.message||He),count:a.length,workflows:l.size,events:a,paths:r}}if(v.has(m.id))return{ok:!1,reason:"duplicate-event-id",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};let F=Ae(m),$=ye(m.tenantId,m.workflowId,m.idempotencyKey);if(N.has($))return{ok:!1,reason:"duplicate-idempotency-key",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};let A=l.get(F)??null,yt=String(BigInt(A?.sequence??"0")+1n);if(m.sequence!==yt)return{ok:!1,reason:"sequence-gap",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};if(m.previousEventHash!==(A?.eventHash??null))return{ok:!1,reason:"previous-event-hash-mismatch",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};if(A&&Date.parse(m.recordedAt)<Date.parse(A.recordedAt))return{ok:!1,reason:"recorded-at-regression",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};v.add(m.id),N.add($),l.set(F,m),a.push(m)}let z=new Map;for(let w of a){let g=Ae(w);z.has(g)||z.set(g,[]),z.get(g).push(w)}for(let[w,g]of z)try{T(g)}catch(x){return{ok:!1,reason:"workflow-invalid",streamKey:w,detail:String(x?.message||x),count:a.length,workflows:l.size,events:a,heads:l,paths:r}}if(n){if(!C(r.checkpoint))return a.length===0?{ok:!0,count:0,workflows:0,events:a,heads:l,paths:r,empty:!0}:{ok:!1,reason:"checkpoint-missing",recoverable:!0,count:a.length,workflows:l.size,events:a,heads:l,paths:r};let w;try{fe(r.checkpoint,"checkpoint");let m=le(r.checkpoint,"utf8");if(!m.endsWith(`
4
4
  `))throw new f("checkpoint truncated","CHECKPOINT_INVALID");w=JSON.parse(m),Hn(w)}catch(m){return{ok:!1,reason:"checkpoint-invalid",recoverable:!1,detail:String(m?.message||m),count:a.length,workflows:l.size,events:a,heads:l,paths:r}}let g=at(r.ledger,a,i),x=Tn(w,g);if(!x.ok)return{...x,count:a.length,workflows:l.size,events:a,heads:l,paths:r}}return{ok:!0,count:a.length,workflows:l.size,events:a,heads:l,paths:r,raw:i,lastEventHash:a.at(-1)?.eventHash??null}}catch(o){return{ok:!1,reason:"io-error",detail:String(o?.message||o),count:0,workflows:0,events:[],paths:r}}}function ee(e){let t={ok:e.ok,count:e.count,workflows:e.workflows,...e.reason?{reason:e.reason}:{},...e.line?{line:e.line}:{},...e.detail?{detail:e.detail}:{},...e.recoverable!==void 0?{recoverable:e.recoverable}:{},...e.lastEventHash!==void 0?{lastEventHash:e.lastEventHash}:{}};return y(t)}function Cn(e={}){return ee(Q(e))}function dt({path:e,tenantId:t,workflowId:n,maxBytes:r=j}={}){let o=Q({path:e,maxBytes:r});if(!o.ok)throw new f(`cannot read corrupt ledger: ${o.reason}`,"LEDGER_CORRUPT",ee(o));t!==void 0&&c(t,"tenantId"),n!==void 0&&c(n,"workflowId");let i=o.events.filter(d=>(t===void 0||d.tenantId===t)&&(n===void 0||d.workflowId===n));return y([...i])}function Pn({path:e,tenantId:t,workflowId:n,maxBytes:r=j}={}){c(t,"tenantId"),c(n,"workflowId");let o=dt({path:e,tenantId:t,workflowId:n,maxBytes:r});if(o.length===0)throw new f(`workflow ${t}:${n} not found`,"WORKFLOW_NOT_FOUND");return T(o)}function lt(e){if(!Number.isSafeInteger(e)||e<=0)return"invalid";try{return process.kill(e,0),"active"}catch(t){return t?.code==="ESRCH"?"stale":"active"}}function Re(e){let{lock:t}=R(e);fe(t,"lock");let n=JSON.parse(le(t,"utf8"));if(p(n,tt,tt,"workflow ledger lock"),n.schemaVersion!==Oe)throw new f("lock schema mismatch","LOCK_INVALID");if(c(n.token,"workflow ledger lock.token"),!Number.isSafeInteger(n.pid)||n.pid<=0)throw new f("lock pid invalid","LOCK_INVALID");return k(n.createdAt,"workflow ledger lock.createdAt"),n}function $e({path:e}={}){let{lock:t}=R(e);if(!C(t))return y({state:"unlocked",lock:null});try{let n=Re(e);return y({state:lt(n.pid),lock:n})}catch(n){return y({state:"invalid",lock:null,error:String(n?.message||n)})}}function ft(e){let t=R(e);$n(t.directory);let n={schemaVersion:Oe,token:nt(),pid:process.pid,createdAt:new Date().toISOString()},r;try{return r=we(t.lock,S.O_WRONLY|S.O_CREAT|S.O_EXCL|(S.O_NOFOLLOW||0),384),_e(r,Buffer.from(`${JSON.stringify(n)}
5
5
  `,"utf8")),ue(r),P(r),r=void 0,Ie(t.lock,384),te(t.directory),n}catch(o){throw r!==void 0&&P(r),o}}async function Wn(e,t){if(!Number.isSafeInteger(t)||t<0||t>12e4)throw new f("lockTimeoutMs out of bounds","LOCK_TIMEOUT_INVALID");let n=Date.now();for(;;)try{return ft(e)}catch(r){if(r?.code!=="EEXIST")throw r;if(Date.now()-n>=t){let o=$e({path:e});throw new f(`ledger busy (${o.state} lock); explicit token-bound recovery is required for stale locks`,"LEDGER_BUSY",o)}await _n(10)}}function q(e,t){let n=Re(e);if(n.token!==t||n.pid!==process.pid)throw new f("lock fencing token no longer owned","LOCK_FENCED");return!0}function ut(e,t){let n=R(e);q(e,t),Se(n.lock),te(n.directory)}function zn({path:e,expectedToken:t}={}){c(t,"expectedToken");let n=$e({path:e});if(n.state==="unlocked")throw new f("lock is already absent","LOCK_ABSENT");if(n.state==="invalid")throw new f("invalid lock is not recoverable automatically","LOCK_INVALID");if(n.lock.token!==t)throw new f("lock token mismatch","LOCK_TOKEN_MISMATCH");if(n.state==="active")throw new f("active lock owner cannot be recovered","LOCK_ACTIVE");let r=Re(e);if(r.token!==t||lt(r.pid)!=="stale")throw new f("lock changed during recovery","LOCK_FENCED");let o=R(e);return Se(o.lock),te(o.directory),y({recovered:!0,token:t})}function Kn(e){return{tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,idempotencyKey:e.idempotencyKey,occurredAt:e.occurredAt,recordedAt:e.recordedAt,type:e.type,external:e.external,evidence:e.evidence,data:e.data}}async function Dn(e={}){p(e,["path","event","lockTimeoutMs","maxBytes"],["path","event"],"appendWorkflowEvent options");let t=R(e.path).ledger,n=be(e.event),r=e.lockTimeoutMs??ot,o=e.maxBytes??j,i=await Wn(t,r),d=null;try{q(t,i.token);let u=Q({path:t,maxBytes:o});if(!u.ok)throw new f(`append refused until ledger recovery: ${u.reason}`,"LEDGER_CORRUPT",ee(u));let a=u.events.find(A=>A.tenantId===n.tenantId&&A.workflowId===n.workflowId&&A.idempotencyKey===n.idempotencyKey);if(a){if(L(Kn(a))!==L(n))throw new f("idempotency key reused with different payload","IDEMPOTENCY_CONFLICT");return y({event:a,duplicate:!0})}if(u.events.some(A=>A.id===n.id))throw new f("event id already exists","EVENT_ID_CONFLICT");let l=O(n.tenantId,n.workflowId),v=u.heads.get(l)??null,N=de({...n,sequence:String(BigInt(v?.sequence??"0")+1n),previousEventHash:v?.eventHash??null}),z=u.events.filter(A=>O(A.tenantId,A.workflowId)===l);T([...z,N]);let w=Buffer.from(`${JSON.stringify(N)}
6
- `,"utf8");if(w.length>st)throw new f("event exceeds size limit","EVENT_SIZE_LIMIT");let g=Buffer.concat([u.raw??Buffer.alloc(0),w]);if(g.length>o)throw new f("append would exceed ledger size limit","LEDGER_SIZE_LIMIT");let x=[...u.events,N],m=it(t,x,g),F=C(t);F&&fe(t,"ledger"),q(t,i.token);let $;try{$=vn(t),_e($,w),ue($)}finally{$!==void 0&&P($)}return Ie(t,384),F||te(rt(t)),q(t,i.token),ct(t,x,g,m),y({event:N,duplicate:!1})}catch(u){throw d=u,u}finally{try{ut(t,i.token)}catch(u){if(d===null)throw u}}}function qn({path:e,expectedLastEventHash:t,maxBytes:n=j}={}){let r=R(e).ledger,o=ft(r);try{q(r,o.token);let i=Q({path:r,maxBytes:n,checkCheckpoint:!1});if(!i.ok)throw new f(`ledger content is not recoverable: ${i.reason}`,"LEDGER_CORRUPT",ee(i));if(i.events.length===0)throw new f("empty ledger has no checkpoint head to recover","LEDGER_EMPTY");if(i.events.at(-1).eventHash!==t)throw new f("expected head does not match verified ledger head","RECOVERY_HEAD_MISMATCH");return q(r,o.token),ct(r,i.events,i.raw),ee(Q({path:r,maxBytes:n}))}finally{ut(r,o.token)}}import{createHash as Mn}from"node:crypto";var Er=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),gr=Object.freeze(["read","simulate"]);var br=1440*60;var ne=class extends Error{constructor(t,n){super(`secret material must never appear in a public API object (at ${t}, rule: ${n})`),this.name="SecretLeakError",this.path=t,this.rule=n}},jn=/(private[_-]?key|secret|bearer|keystore|mnemonic|seed[_-]?phrase|passphrase|password|api[_-]?key|access[_-]?token|auth[_-]?token|session[_-]?token|signer[_-]?url|signature)/i,Fn=Object.freeze(["privkey","wif","xprv","seed"]);function wt(e){let t=String(e),n=t.toLowerCase().replace(/[\s._-]+/g,"");return jn.test(t)||Fn.includes(n)}var Bn=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),Vn=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);function W(e,t="$",n=new Set,r=""){if(e==null)return e;if(typeof e=="string"){let o=Vn.includes(String(r).toLowerCase().replace(/[_-]/g,""));for(let{rule:i,re:d}of Bn)if(!(o&&i.startsWith("raw-32-byte-hex"))&&d.test(e))throw new ne(t,i);return e}if(typeof e!="object"||n.has(e)||(n.add(e),ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e;if(e instanceof Map){for(let[o,i]of e.entries()){if(typeof o=="string"&&wt(o))throw new ne(`${t}[${JSON.stringify(o)}]`,"forbidden-key-name");W(o,`${t}[key]`,n),W(i,`${t}[${String(o)}]`,n)}return e}if(e instanceof Set){let o=0;for(let i of e.values())W(i,`${t}[${o++}]`,n);return e}if(Array.isArray(e))return e.forEach((o,i)=>W(o,`${t}[${i}]`,n)),e;for(let[o,i]of Object.entries(e)){if(wt(o))throw new ne(`${t}.${o}`,"forbidden-key-name");W(i,`${t}.${o}`,n,o)}return e}var ve=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),Gn=Object.freeze(Object.fromEntries(ve.map((e,t)=>[e,Object.freeze(t+1<ve.length?[ve[t+1]]:[])]))),Yn=new Set(["signed","broadcast"]);function Ne(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Ne).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ne(e[t])}`).join(",")}}`}function Jn(e,t="fact"){try{W(e,t)}catch{throw new Error(`${t} contains custody material and is forbidden`)}}function Un(e){return Mn("sha256").update(Ne(e)).digest("hex")}function pt(e){if(!e||!Array.isArray(e.events)||e.events.length===0)throw new Error("invalid trade lifecycle");if(e.custody!=="none")throw new Error("trade lifecycle custody must be none");if(e.execution!=="prepare-only")throw new Error("trade lifecycle execution must be prepare-only");let t=null;for(let n=0;n<e.events.length;n+=1){let r=e.events[n],{hash:o,...i}=r;if(Un(i)!==o)throw new Error(`trade event ${n} hash mismatch`);if(Jn(r.fact,`trade event ${n} fact`),!Number.isFinite(Number(r.asOf))||t&&Number(r.asOf)<Number(t.asOf))throw new Error(`trade event ${n} asOf must be finite and monotonic`);if(r.tradeId!==e.tradeId||r.previousHash!==t?.hash&&n>0)throw new Error(`trade event ${n} chain mismatch`);if(n===0&&(r.state!=="intent"||r.previousHash!==null))throw new Error("trade lifecycle must start with intent");if(t&&!Gn[t.state]?.includes(r.state))throw new Error(`invalid recorded transition ${t.state} -> ${r.state}`);if(Yn.has(r.state)&&r.external!==!0)throw new Error(`${r.state} is not externally supplied`);t=r}if(e.state!==t.state||e.headHash!==t.hash)throw new Error("trade lifecycle head mismatch");return!0}var ht=Object.freeze({intent:"draft",quote_comparison:"draft",simulation:"draft",prepared:"checked",approval:"approval",signed:"signed",broadcast:"submitted",settlement:"finalized",balance_delta:"compensated",position:"compensated"});function Le(e,t,n){if(typeof e=="string")return e;if(Number.isFinite(Number(e)))return new Date(Number(e)).toISOString();if(t!==void 0)return t;throw new s(`${n} must be supplied explicitly`)}function Xn(e){return{status:"verified",source:"external",reference:`trade-lifecycle:${e.state}:${e.hash}`,observedAt:Le(e.asOf,void 0,"legacy trade event asOf")}}function Zn(e){if(e.state==="signed")return{artifactHash:e.hash,signer:e.evidence?.signer??e.evidence?.from??"legacy-owner-wallet"};if(e.state==="broadcast"){let t=e.evidence?.txHash??e.evidence?.transactionHash;return{transactionHash:typeof t=="string"&&/^0x[a-f0-9]{64}$/.test(t)?t:`0x${e.hash}`,endpoint:e.evidence?.endpoint??e.evidence?.provider??"legacy-broadcast-endpoint"}}return e.evidence&&typeof e.evidence=="object"?e.evidence:{}}function mt(e,t={}){p(t,["tenantId","runId","intentSpecId","createdAt","updatedAt","metadata"],["tenantId","runId","createdAt"],"bridgeTradeLifecycle options"),c(t.tenantId,"bridgeTradeLifecycle.tenantId"),pt(e);let n=ht[e.state];if(!n)throw new s(`legacy trade state ${String(e.state)} has no compatibility mapping`);let r=Le(t.createdAt,void 0,"bridgeTradeLifecycle.createdAt"),o=Le(t.updatedAt??r,r,"bridgeTradeLifecycle.updatedAt"),i=e.events.filter(d=>d.external===!0).map(d=>({source:"trade-lifecycle-v1",state:d.state,eventHash:d.hash,asOf:d.asOf,evidence:Xn(d),data:Zn(d)}));return X({tenantId:t.tenantId,id:t.runId,workflowId:e.tradeId,intentSpecId:t.intentSpecId??`${e.tradeId}:intent`,createdAt:r,updatedAt:o,state:n,eventCount:String(e.events.length),headEventHash:e.headHash,externalFacts:i,authority:"projection",sourceKind:"legacy-trade-lifecycle",metadata:{...t.metadata??{},compatibility:{source:"trade-lifecycle-v1",authority:"projection",legacyState:e.state,legacyHeadHash:e.headHash,legacyEventCount:String(e.events.length),mapping:"conservative-v1"}}})}var Qn=mt;export{_ as CONTROL_PLANE_BUILD_VERSION,We as CONTROL_PLANE_MAX_DEPTH,K as CONTROL_PLANE_MAX_RECORD_BYTES,D as CONTROL_PLANE_SCHEMA_VERSION,s as ControlPlaneValidationError,ot as DEFAULT_WORKFLOW_LEDGER_LOCK_TIMEOUT_MS,j as DEFAULT_WORKFLOW_LEDGER_MAX_BYTES,ht as LEGACY_TRADE_STATE_MAP,Je as WORKFLOW_EVENT_TYPES,xe as WORKFLOW_LEDGER_CHECKPOINT_VERSION,Oe as WORKFLOW_LEDGER_LOCK_VERSION,Rn as WORKFLOW_LEDGER_SCHEMA_VERSION,pn as WORKFLOW_STATES,f as WorkflowLedgerError,Dn as appendWorkflowEvent,Me as assertApprovalRequest,I as assertCanonicalIntegerString,Fe as assertIntentSpec,Be as assertPlan,Ve as assertPreview,Ge as assertRunRecord,Z as assertWorkflowEvent,mt as bridgeTradeLifecycle,L as canonicalControlPlaneJson,wn as createApprovalRequest,ln as createIntentSpec,fn as createPlan,un as createPreview,X as createRunRecord,kn as createRunRecordFromEvents,de as createWorkflowEvent,H as hashControlPlaneRecord,$e as inspectWorkflowLedgerLock,dt as readWorkflowEvents,qn as recoverWorkflowLedgerCheckpoint,zn as recoverWorkflowLedgerLock,T as reduceWorkflowEvents,En as replayWorkflowEvents,Pn as replayWorkflowLedger,Qn as runRecordFromTradeLifecycle,Cn as verifyWorkflowLedger,ye as workflowIdempotencyId,O as workflowStreamKey};
6
+ `,"utf8");if(w.length>st)throw new f("event exceeds size limit","EVENT_SIZE_LIMIT");let g=Buffer.concat([u.raw??Buffer.alloc(0),w]);if(g.length>o)throw new f("append would exceed ledger size limit","LEDGER_SIZE_LIMIT");let x=[...u.events,N],m=it(t,x,g),F=C(t);F&&fe(t,"ledger"),q(t,i.token);let $;try{$=vn(t),_e($,w),ue($)}finally{$!==void 0&&P($)}return Ie(t,384),F||te(rt(t)),q(t,i.token),ct(t,x,g,m),y({event:N,duplicate:!1})}catch(u){throw d=u,u}finally{try{ut(t,i.token)}catch(u){if(d===null)throw u}}}function qn({path:e,expectedLastEventHash:t,maxBytes:n=j}={}){let r=R(e).ledger,o=ft(r);try{q(r,o.token);let i=Q({path:r,maxBytes:n,checkCheckpoint:!1});if(!i.ok)throw new f(`ledger content is not recoverable: ${i.reason}`,"LEDGER_CORRUPT",ee(i));if(i.events.length===0)throw new f("empty ledger has no checkpoint head to recover","LEDGER_EMPTY");if(i.events.at(-1).eventHash!==t)throw new f("expected head does not match verified ledger head","RECOVERY_HEAD_MISMATCH");return q(r,o.token),ct(r,i.events,i.raw),ee(Q({path:r,maxBytes:n}))}finally{ut(r,o.token)}}import{createHash as Mn}from"node:crypto";var kr=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),Er=Object.freeze(["read","simulate"]);var gr=1440*60;var ne=class extends Error{constructor(t,n){super(`secret material must never appear in a public API object (at ${t}, rule: ${n})`),this.name="SecretLeakError",this.path=t,this.rule=n}},jn=/(private[_-]?key|secret|bearer|keystore|mnemonic|seed[_-]?phrase|passphrase|password|api[_-]?key|access[_-]?token|auth[_-]?token|session[_-]?token|signer[_-]?url|signature)/i,Fn=Object.freeze(["privkey","wif","xprv","seed"]);function wt(e){let t=String(e),n=t.toLowerCase().replace(/[\s._-]+/g,"");return jn.test(t)||Fn.includes(n)}var Bn=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),Vn=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);function W(e,t="$",n=new Set,r=""){if(e==null)return e;if(typeof e=="string"){let o=Vn.includes(String(r).toLowerCase().replace(/[_-]/g,""));for(let{rule:i,re:d}of Bn)if(!(o&&i.startsWith("raw-32-byte-hex"))&&d.test(e))throw new ne(t,i);return e}if(typeof e!="object"||n.has(e)||(n.add(e),ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e;if(e instanceof Map){for(let[o,i]of e.entries()){if(typeof o=="string"&&wt(o))throw new ne(`${t}[${JSON.stringify(o)}]`,"forbidden-key-name");W(o,`${t}[key]`,n),W(i,`${t}[${String(o)}]`,n)}return e}if(e instanceof Set){let o=0;for(let i of e.values())W(i,`${t}[${o++}]`,n);return e}if(Array.isArray(e))return e.forEach((o,i)=>W(o,`${t}[${i}]`,n)),e;for(let[o,i]of Object.entries(e)){if(wt(o))throw new ne(`${t}.${o}`,"forbidden-key-name");W(i,`${t}.${o}`,n,o)}return e}var ve=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),Gn=Object.freeze(Object.fromEntries(ve.map((e,t)=>[e,Object.freeze(t+1<ve.length?[ve[t+1]]:[])]))),Yn=new Set(["signed","broadcast"]);function Ne(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Ne).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ne(e[t])}`).join(",")}}`}function Jn(e,t="fact"){try{W(e,t)}catch{throw new Error(`${t} contains custody material and is forbidden`)}}function Un(e){return Mn("sha256").update(Ne(e)).digest("hex")}function pt(e){if(!e||!Array.isArray(e.events)||e.events.length===0)throw new Error("invalid trade lifecycle");if(e.custody!=="none")throw new Error("trade lifecycle custody must be none");if(e.execution!=="prepare-only")throw new Error("trade lifecycle execution must be prepare-only");let t=null;for(let n=0;n<e.events.length;n+=1){let r=e.events[n],{hash:o,...i}=r;if(Un(i)!==o)throw new Error(`trade event ${n} hash mismatch`);if(Jn(r.fact,`trade event ${n} fact`),!Number.isFinite(Number(r.asOf))||t&&Number(r.asOf)<Number(t.asOf))throw new Error(`trade event ${n} asOf must be finite and monotonic`);if(r.tradeId!==e.tradeId||r.previousHash!==t?.hash&&n>0)throw new Error(`trade event ${n} chain mismatch`);if(n===0&&(r.state!=="intent"||r.previousHash!==null))throw new Error("trade lifecycle must start with intent");if(t&&!Gn[t.state]?.includes(r.state))throw new Error(`invalid recorded transition ${t.state} -> ${r.state}`);if(Yn.has(r.state)&&r.external!==!0)throw new Error(`${r.state} is not externally supplied`);t=r}if(e.state!==t.state||e.headHash!==t.hash)throw new Error("trade lifecycle head mismatch");return!0}var ht=Object.freeze({intent:"draft",quote_comparison:"draft",simulation:"draft",prepared:"checked",approval:"approval",signed:"signed",broadcast:"submitted",settlement:"finalized",balance_delta:"compensated",position:"compensated"});function Le(e,t,n){if(typeof e=="string")return e;if(Number.isFinite(Number(e)))return new Date(Number(e)).toISOString();if(t!==void 0)return t;throw new s(`${n} must be supplied explicitly`)}function Xn(e){return{status:"verified",source:"external",reference:`trade-lifecycle:${e.state}:${e.hash}`,observedAt:Le(e.asOf,void 0,"legacy trade event asOf")}}function Zn(e){if(e.state==="signed")return{artifactHash:e.hash,signer:e.evidence?.signer??e.evidence?.from??"legacy-owner-wallet"};if(e.state==="broadcast"){let t=e.evidence?.txHash??e.evidence?.transactionHash;return{transactionHash:typeof t=="string"&&/^0x[a-f0-9]{64}$/.test(t)?t:`0x${e.hash}`,endpoint:e.evidence?.endpoint??e.evidence?.provider??"legacy-broadcast-endpoint"}}return e.evidence&&typeof e.evidence=="object"?e.evidence:{}}function mt(e,t={}){p(t,["tenantId","runId","intentSpecId","createdAt","updatedAt","metadata"],["tenantId","runId","createdAt"],"bridgeTradeLifecycle options"),c(t.tenantId,"bridgeTradeLifecycle.tenantId"),pt(e);let n=ht[e.state];if(!n)throw new s(`legacy trade state ${String(e.state)} has no compatibility mapping`);let r=Le(t.createdAt,void 0,"bridgeTradeLifecycle.createdAt"),o=Le(t.updatedAt??r,r,"bridgeTradeLifecycle.updatedAt"),i=e.events.filter(d=>d.external===!0).map(d=>({source:"trade-lifecycle-v1",state:d.state,eventHash:d.hash,asOf:d.asOf,evidence:Xn(d),data:Zn(d)}));return X({tenantId:t.tenantId,id:t.runId,workflowId:e.tradeId,intentSpecId:t.intentSpecId??`${e.tradeId}:intent`,createdAt:r,updatedAt:o,state:n,eventCount:String(e.events.length),headEventHash:e.headHash,externalFacts:i,authority:"projection",sourceKind:"legacy-trade-lifecycle",metadata:{...t.metadata??{},compatibility:{source:"trade-lifecycle-v1",authority:"projection",legacyState:e.state,legacyHeadHash:e.headHash,legacyEventCount:String(e.events.length),mapping:"conservative-v1"}}})}var Qn=mt;export{_ as CONTROL_PLANE_BUILD_VERSION,We as CONTROL_PLANE_MAX_DEPTH,K as CONTROL_PLANE_MAX_RECORD_BYTES,D as CONTROL_PLANE_SCHEMA_VERSION,s as ControlPlaneValidationError,ot as DEFAULT_WORKFLOW_LEDGER_LOCK_TIMEOUT_MS,j as DEFAULT_WORKFLOW_LEDGER_MAX_BYTES,ht as LEGACY_TRADE_STATE_MAP,Je as WORKFLOW_EVENT_TYPES,xe as WORKFLOW_LEDGER_CHECKPOINT_VERSION,Oe as WORKFLOW_LEDGER_LOCK_VERSION,Rn as WORKFLOW_LEDGER_SCHEMA_VERSION,pn as WORKFLOW_STATES,f as WorkflowLedgerError,Dn as appendWorkflowEvent,Me as assertApprovalRequest,I as assertCanonicalIntegerString,Fe as assertIntentSpec,Be as assertPlan,Ve as assertPreview,Ge as assertRunRecord,Z as assertWorkflowEvent,mt as bridgeTradeLifecycle,L as canonicalControlPlaneJson,wn as createApprovalRequest,ln as createIntentSpec,fn as createPlan,un as createPreview,X as createRunRecord,kn as createRunRecordFromEvents,de as createWorkflowEvent,H as hashControlPlaneRecord,$e as inspectWorkflowLedgerLock,dt as readWorkflowEvents,qn as recoverWorkflowLedgerCheckpoint,zn as recoverWorkflowLedgerLock,T as reduceWorkflowEvents,En as replayWorkflowEvents,Pn as replayWorkflowLedger,Qn as runRecordFromTradeLifecycle,Cn as verifyWorkflowLedger,ye as workflowIdempotencyId,O as workflowStreamKey};