openpond 0.2.49 → 0.2.51

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.
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{f as fn,h as hn}from"./chunk-DLZP22WV.js";import{b as Bo,c as Jo,d as Rc,e as pn,f as Vt,g as mn}from"./chunk-VOIH2BQA.js";import{a as Tc,c as vc,g as Ec,h as Sc}from"./chunk-QJRXTIOC.js";import{D as an,E as fr,F as Jt,G as hr,H as ic,I as cc,J as dc,K as cn,L as lc,M as Uo,N as uc,O as xe,P as pc,Q as mc,R as fc,S as hc,T as gc,U as dn,V as yc,W as ln,aa as un,e as oi,ea as wc,f as si,fa as Me,ja as kc,m as ac,n as Fo}from"./chunk-7MXZJQS7.js";import{b as gn,m as xc,p as bc,s as Ic,t as yn,y as Cc,z as wn}from"./chunk-2ZJJFBIA.js";import{d as Ve,g as Xe}from"./chunk-5CMKGD43.js";import{G as oc,P as sc}from"./chunk-HA7EFTPF.js";import{b as nc,e as on,f as sn}from"./chunk-7QEE4PBI.js";import{Ac as Ut,Ad as Ki,Bc as en,Bd as _i,Cc as tn,Cd as nn,Da as Hi,Dc as J,Ec as Xi,Ed as $i,Fa as _r,Fc as Bt,Fd as Rt,Gb as Fi,Gc as zi,Ib as re,Ic as Zi,Jb as Ui,Jc as jo,Kc as Yi,Kd as tc,La as Ho,Lb as Bi,Ld as tt,Ma as Wi,N as Mi,Oa as ji,Od as Se,Rd as mr,Sd as rc,Ta as qi,Y as Li,od as rn,pd as Qi,qd as Gi,rd as qo,va as Di,xc as $,yc as Ji,zc as Vi}from"./chunk-XDMUD4FW.js";import{c as ai,ga as Wo,z as Ni}from"./chunk-IKWDL3RB.js";import{Ba as Ci,Ca as pr,Oa as Ai,Qa as Je,Ra as Oi,Sa as Pi,Ta as et,ja as Ti,ka as vi,la as Ei,m as Ee,ma as Si,oa as xi,pc as $r,wc as ec,xa as bi,ya as Ii}from"./chunk-QRWPEW3Z.js";import{qa as ii,ra as Kr,sa as ci,ta as di,ua as lr,va as Ft,wa as li,x as _a}from"./chunk-WV2APYWG.js";import{Db as Gr,Eb as ri,Jb as qt,Qa as $a,Ra as Lo,Ta as ei,U as Qr,Vc as Ue,Wc as Be,a as Za,b as G,d as Ya,ga as $e,ha as Qa,ja as Ga,ka as Mo,la as ue,sd as ni,vb as Y,wb as ti,ya as Ka,z as Yr}from"./chunk-PJM2G7SG.js";import{A as ja,B as Ro,G as Jr,H as Vr,I as To,J as Fa,K as Ua,L as vo,M as Xr,N as Eo,O as So,P as cr,T as xo,U as Ba,V as Ja,W as Va,X as Xa,Y as za,Z as bo,_ as Io,e as Ma,ga as dr,ha as Co,ia as Ao,ja as Oo,ka as Po,la as zr,ma as Zr,n as La,na as jt,o as Da,oa as No,pa as Z,w as Ha,x as Wa}from"./chunk-SDEDAHV6.js";import{E as wi,F as ki,G as Ri,e as ui,f as wt}from"./chunk-DALJMSJG.js";import{B as pi,H as Do,N as mi,y as kt}from"./chunk-TGIB24K4.js";import{b as gt,c as he,d as yt,f as Aa,h as Oa,i as Pa,k as Na,l as ve,m as y,o as qa}from"./chunk-NNF6KCHD.js";import{b as g}from"./chunk-ES2ISFJC.js";import{h as ur,n as fi,o as hi,p as gi,q as yi}from"./chunk-H7IWJN7L.js";import{a as i,c as ko,e as Cp}from"./chunk-FTQLQJQV.js";var rd=ko((pv,td)=>{"use strict";var Im=["||","&&",";;","|&","<(","<<<",">>",">&","<&","&",";","(",")","|","<",">"],ed=/[\n\r\u2028\u2029]/,Cm=/[\s#!"$&'():;<=>@\\^`|]/g;td.exports=i(function(t){return t.map(function(r){if(r==="")return"''";if(r&&typeof r=="object"){if("op"in r&&r.op==="glob"){if(typeof r.pattern!="string")throw new TypeError("glob token requires a string `pattern`");if(ed.test(r.pattern))throw new TypeError("glob `pattern` must not contain line terminators");return r.pattern.replace(Cm,"\\$&")}if("op"in r&&typeof r.op=="string"){if(Im.indexOf(r.op)<0)throw new TypeError("invalid `op` value: "+JSON.stringify(r.op));return r.op.replace(/[\s\S]/g,"\\$&")}if("comment"in r&&typeof r.comment=="string"){if(ed.test(r.comment))throw new TypeError("`comment` must not contain line terminators");return"#"+r.comment}throw new TypeError("unrecognized object token shape")}return/["\s\\]/.test(r)&&!/'/.test(r)?"'"+r.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(r)?'"'+r.replace(/(["\\$`!])/g,"\\$1")+'"':String(r).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")},"quote")});var dd=ko((fv,cd)=>{"use strict";var id="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",nd=new RegExp("^"+id+"$"),od="|&;()<> \\t",Am="'([^']*?)'",Om='"((\\\\"|[^"])*?)"',Pm=/^#$/,sd="'",ad='"',In="$",Et="",Nm=4294967296;for($o=0;$o<4;$o++)Et+=(Nm*Math.random()).toString(16);var $o,Mm=new RegExp("^"+Et);function Lm(e,t){for(var r=t.lastIndex,n=[],o;o=t.exec(e);)n[n.length]=o,t.lastIndex===o.index&&(t.lastIndex+=1);return t.lastIndex=r,n}i(Lm,"matchAll");function Dm(e,t,r){var n=typeof e=="function"?e(r):e[r];return typeof n>"u"&&r!=""?n="":typeof n>"u"&&(n="$"),typeof n=="object"?t+Et+JSON.stringify(n)+Et:t+n}i(Dm,"getVar");function Hm(e,t,r){r||(r={});var n=r.escape||"\\",o=r.splitUnquoted===!0?`
2
+ import{f as fn,h as hn}from"./chunk-DLZP22WV.js";import{b as Bo,c as Jo,d as Rc,e as pn,f as Vt,g as mn}from"./chunk-OE2VF6KU.js";import{a as Tc,c as vc,g as Ec,h as Sc}from"./chunk-QJRXTIOC.js";import{D as an,E as fr,F as Jt,G as hr,H as ic,I as cc,J as dc,K as cn,L as lc,M as Uo,N as uc,O as xe,P as pc,Q as mc,R as fc,S as hc,T as gc,U as dn,V as yc,W as ln,aa as un,e as oi,ea as wc,f as si,fa as Me,ja as kc,m as ac,n as Fo}from"./chunk-7MXZJQS7.js";import{b as gn,m as xc,p as bc,s as Ic,t as yn,y as Cc,z as wn}from"./chunk-2ZJJFBIA.js";import{d as Ve,g as Xe}from"./chunk-5CMKGD43.js";import{G as oc,P as sc}from"./chunk-HA7EFTPF.js";import{b as nc,e as on,f as sn}from"./chunk-7QEE4PBI.js";import{Ac as Ut,Ad as Ki,Bc as en,Bd as _i,Cc as tn,Cd as nn,Da as Hi,Dc as J,Ec as Xi,Ed as $i,Fa as _r,Fc as Bt,Fd as Rt,Gb as Fi,Gc as zi,Ib as re,Ic as Zi,Jb as Ui,Jc as jo,Kc as Yi,Kd as tc,La as Ho,Lb as Bi,Ld as tt,Ma as Wi,N as Mi,Oa as ji,Od as Se,Rd as mr,Sd as rc,Ta as qi,Y as Li,od as rn,pd as Qi,qd as Gi,rd as qo,va as Di,xc as $,yc as Ji,zc as Vi}from"./chunk-XDMUD4FW.js";import{c as ai,ga as Wo,z as Ni}from"./chunk-IKWDL3RB.js";import{Ba as Ci,Ca as pr,Oa as Ai,Qa as Je,Ra as Oi,Sa as Pi,Ta as et,ja as Ti,ka as vi,la as Ei,m as Ee,ma as Si,oa as xi,pc as $r,wc as ec,xa as bi,ya as Ii}from"./chunk-QRWPEW3Z.js";import{qa as ii,ra as Kr,sa as ci,ta as di,ua as lr,va as Ft,wa as li,x as _a}from"./chunk-WV2APYWG.js";import{Db as Gr,Eb as ri,Jb as qt,Qa as $a,Ra as Lo,Ta as ei,U as Qr,Vc as Ue,Wc as Be,a as Za,b as G,d as Ya,ga as $e,ha as Qa,ja as Ga,ka as Mo,la as ue,sd as ni,vb as Y,wb as ti,ya as Ka,z as Yr}from"./chunk-PJM2G7SG.js";import{A as ja,B as Ro,G as Jr,H as Vr,I as To,J as Fa,K as Ua,L as vo,M as Xr,N as Eo,O as So,P as cr,T as xo,U as Ba,V as Ja,W as Va,X as Xa,Y as za,Z as bo,_ as Io,e as Ma,ga as dr,ha as Co,ia as Ao,ja as Oo,ka as Po,la as zr,ma as Zr,n as La,na as jt,o as Da,oa as No,pa as Z,w as Ha,x as Wa}from"./chunk-SDEDAHV6.js";import{E as wi,F as ki,G as Ri,e as ui,f as wt}from"./chunk-DALJMSJG.js";import{B as pi,H as Do,N as mi,y as kt}from"./chunk-TGIB24K4.js";import{b as gt,c as he,d as yt,f as Aa,h as Oa,i as Pa,k as Na,l as ve,m as y,o as qa}from"./chunk-NNF6KCHD.js";import{b as g}from"./chunk-ES2ISFJC.js";import{h as ur,n as fi,o as hi,p as gi,q as yi}from"./chunk-H7IWJN7L.js";import{a as i,c as ko,e as Cp}from"./chunk-FTQLQJQV.js";var rd=ko((pv,td)=>{"use strict";var Im=["||","&&",";;","|&","<(","<<<",">>",">&","<&","&",";","(",")","|","<",">"],ed=/[\n\r\u2028\u2029]/,Cm=/[\s#!"$&'():;<=>@\\^`|]/g;td.exports=i(function(t){return t.map(function(r){if(r==="")return"''";if(r&&typeof r=="object"){if("op"in r&&r.op==="glob"){if(typeof r.pattern!="string")throw new TypeError("glob token requires a string `pattern`");if(ed.test(r.pattern))throw new TypeError("glob `pattern` must not contain line terminators");return r.pattern.replace(Cm,"\\$&")}if("op"in r&&typeof r.op=="string"){if(Im.indexOf(r.op)<0)throw new TypeError("invalid `op` value: "+JSON.stringify(r.op));return r.op.replace(/[\s\S]/g,"\\$&")}if("comment"in r&&typeof r.comment=="string"){if(ed.test(r.comment))throw new TypeError("`comment` must not contain line terminators");return"#"+r.comment}throw new TypeError("unrecognized object token shape")}return/["\s\\]/.test(r)&&!/'/.test(r)?"'"+r.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(r)?'"'+r.replace(/(["\\$`!])/g,"\\$1")+'"':String(r).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")},"quote")});var dd=ko((fv,cd)=>{"use strict";var id="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",nd=new RegExp("^"+id+"$"),od="|&;()<> \\t",Am="'([^']*?)'",Om='"((\\\\"|[^"])*?)"',Pm=/^#$/,sd="'",ad='"',In="$",Et="",Nm=4294967296;for($o=0;$o<4;$o++)Et+=(Nm*Math.random()).toString(16);var $o,Mm=new RegExp("^"+Et);function Lm(e,t){for(var r=t.lastIndex,n=[],o;o=t.exec(e);)n[n.length]=o,t.lastIndex===o.index&&(t.lastIndex+=1);return t.lastIndex=r,n}i(Lm,"matchAll");function Dm(e,t,r){var n=typeof e=="function"?e(r):e[r];return typeof n>"u"&&r!=""?n="":typeof n>"u"&&(n="$"),typeof n=="object"?t+Et+JSON.stringify(n)+Et:t+n}i(Dm,"getVar");function Hm(e,t,r){r||(r={});var n=r.escape||"\\",o=r.splitUnquoted===!0?`
3
3
  `:typeof r.splitUnquoted=="string"?r.splitUnquoted:"",s="(\\"+n+`['"`+od+`]|[^\\s'"`+od+"])+",a=new RegExp(["("+id+")","("+s+"|"+Om+"|"+Am+")+"].join("|"),"g"),c=Lm(e,a);if(c.length===0)return[];t||(t={});var d=!1;return c.map(function(l){var p=l[0];if(!p||d)return;if(nd.test(p))return{op:p};var u=!1,m=!1,f="",h=[],R=!1,w=null,k=!1,x;function C(){x+=1;var E,b,D=p.charAt(x);if(D==="{"){if(x+=1,p.charAt(x)==="}")throw new Error("Bad substitution: "+p.slice(x-2,x+1));var F=1;for(E=x;F>0&&E<p.length;)p.charAt(E)==="{"&&p.charAt(E-1)==="$"?F+=1:p.charAt(E)==="}"&&(F-=1),E+=1;if(F!==0)throw new Error("Bad substitution: "+p.slice(x));E-=1,b=p.slice(x,E),x=E}else if(/[*@#?$!_-]/.test(D))b=D,x+=1;else{var V=p.slice(x);E=V.match(/[^\w\d_]/),E?(b=V.slice(0,E.index),x+=E.index-1):(b=V,x=p.length)}return Dm(t,"",b)}i(C,"parseEnvVar");function A(){if(w!==null){if(w===0)f!==""&&(h[h.length]=f,f="");else{h[h.length]=f,f="";for(var E=1;E<w;E+=1)h[h.length]=""}w=null}}for(i(A,"flushRun"),x=0;x<p.length;x++){var T=p.charAt(x);if(o&&T!==In&&A(),k=k||!u&&(T==="*"||T==="?"),m)f+=T,m=!1;else if(u)T===u?u=!1:u==sd?f+=T:T===n?(x+=1,T=p.charAt(x),T===ad||T===n||T===In?f+=T:f+=n+T):T===In?f+=C():f+=T;else if(T===ad||T===sd)u=T,R=!0;else{if(nd.test(T))return{op:p};if(Pm.test(T)){d=!0;var P={comment:e.slice(l.index+x+1)};return f.length?[f,P]:[P]}else if(T===n)m=!0;else if(T===In){var v=C();if(!o)f+=v;else for(var I=0;I<v.length;I+=1){var S=v.charAt(I);o.indexOf(S)<0?(A(),f+=S):w===null?w=S===" "||S===" "||S===`
4
4
  `?0:1:S!==" "&&S!==" "&&S!==`
5
5
  `&&(w+=1)}}else f+=T}}if(k)return{op:"glob",pattern:f};if(o){if(w!==null&&w>0){h[h.length]=f,f="";for(var N=1;N<w;N+=1)h[h.length]=""}return(f!==""||R&&h.length===0)&&(h[h.length]=f),h}return f}).reduce(function(l,p){return typeof p>"u"||[].concat(p).forEach(function(u){l[l.length]=u}),l},[])}i(Hm,"parseInternal");cd.exports=i(function(t,r,n){var o=Hm(t,r,n);return typeof r!="function"?o:o.reduce(function(s,a){if(typeof a=="object")return s[s.length]=a,s;var c=a.split(RegExp("("+Et+".*?"+Et+")","g"));return c.length===1?(s[s.length]=c[0],s):(c.filter(Boolean).forEach(function(d){s[s.length]=Mm.test(d)?JSON.parse(d.split(Et)[1]):d}),s)},[])},"parse")});var ld=ko(es=>{"use strict";es.quote=rd();es.parse=dd()});import{promises as Lc}from"node:fs";import rt from"node:path";var Ap="openpond.workEvidenceReceipt.v1",Op="openpond.workProcessTrace.v1",Pp="openpond.workFeedbackReceipt.v1",hk="openpond.workEvidenceEligibility.v1",Np=g.string().regex(/^urn:openpond:work:[a-f0-9]{64}$/,"Work source references must be opaque SHA-256 URNs."),Mp=g.string().regex(/^urn:openpond:workspace:[a-f0-9]{64}$/,"Workspace references must be opaque SHA-256 URNs."),Lp=g.string().regex(/^urn:openpond:artifact:[a-f0-9]{64}$/,"Evidence artifacts must use content-addressed SHA-256 URNs."),ie=Pa.extend({id:Lp}).strict().superRefine((e,t)=>{e.id!==Pc(e.contentHash)&&t.addIssue({code:"custom",message:"Evidence artifact id must contain its content hash.",path:["id"]})}),Dp=g.enum(["tool","validation","state_transition","approval","question","artifact","cleanup"]),Hp=g.enum(["agent","environment"]),Wp=g.enum(["turn_started","turn_completed","turn_failed","turn_cancelled","turn_timed_out","tool_invoked","tool_completed","tool_failed","validation_completed","validation_failed","approval_requested","approval_resolved","question_asked","question_answered","question_dismissed","artifact_created","workspace_changed","environment_created","environment_reset","environment_destroyed","cleanup_completed","cleanup_failed"]),jp=g.enum(["started","completed","failed","cancelled"]),qp=g.enum(["filesystem","source_control","command","browser","connected_app","sandbox","agent","other"]),Fp=g.enum(["structural","visual","test","user_review","other"]),Up=g.enum(["running","completed","failed","cancelled","timeout"]),Bp=g.enum(["requested","approved","denied","answered","dismissed"]),Jp=g.enum(["policy","validation","environment","infrastructure","timeout","cancelled","unknown"]),Vp=g.enum(["missing_start","missing_terminal","source_truncated","unsupported_events_dropped","uncorrelated_environment_step","artifact_unavailable"]),Xp=g.object({sequence:g.number().int().nonnegative().max(1e6),timestamp:yt,layer:Hp,kind:Dp,action:Wp,status:jp,inputHash:he.nullable(),outputHash:he.nullable(),receiptHash:he.nullable(),parentReceiptHash:he.nullable(),artifactRefs:g.array(ie).max(1e3),attributes:g.object({toolCategory:qp.nullable(),validationKind:Fp.nullable(),transitionState:Up.nullable(),interventionOutcome:Bp.nullable(),artifactCount:g.number().int().nonnegative().max(1e5),exitCode:g.number().int().min(-1).max(255).nullable(),durationMs:g.number().int().nonnegative().max(31536e6).nullable(),cpuTimeMs:g.number().int().nonnegative().max(31536e6).nullable(),memoryPeakBytes:g.number().int().nonnegative().max(0x4000000000000).nullable(),errorClass:Jp.nullable()}).strict()}).strict().superRefine((e,t)=>{e.layer==="agent"&&e.parentReceiptHash!==null&&t.addIssue({code:"custom",message:"Agent-layer steps cannot have a parent environment correlation.",path:["parentReceiptHash"]}),e.layer==="environment"&&e.parentReceiptHash===null&&t.addIssue({code:"custom",message:"Environment steps must correlate to an Agent receipt.",path:["parentReceiptHash"]})}),Ac=g.object({schemaVersion:g.literal(Op),sourceRevisionHash:he,sanitationPolicyVersion:gt,incomplete:g.boolean(),incompleteReasons:g.array(Vp).max(10),droppedEventCount:g.number().int().nonnegative().max(1e6),steps:g.array(Xp).max(1e5)}).strict().superRefine((e,t)=>{e.incomplete!==e.incompleteReasons.length>0&&t.addIssue({code:"custom",message:"incomplete must match the presence of incompleteReasons.",path:["incomplete"]});for(let r=0;r<e.steps.length;r+=1)e.steps[r].sequence!==r&&t.addIssue({code:"custom",message:"Process trace sequences must be contiguous and zero-based.",path:["steps",r,"sequence"]})}),Xo=Ac.safeExtend({contentHash:he}).strict(),zp=g.enum(["policy_failure","validation_failure","model_failure","environment_failure","infrastructure_failure","timeout","cancelled","unknown"]),Zp=g.object({status:g.enum(["completed","failed","cancelled","timeout"]),failureClass:zp.nullable()}).strict().superRefine((e,t)=>{e.status==="completed"&&e.failureClass!==null&&t.addIssue({code:"custom",message:"Completed Work cannot carry a failure class.",path:["failureClass"]}),e.status!=="completed"&&e.failureClass===null&&t.addIssue({code:"custom",message:"Non-completed Work requires a failure class.",path:["failureClass"]}),e.status==="cancelled"&&e.failureClass!=="cancelled"&&t.addIssue({code:"custom",message:"Cancelled Work must use the cancelled failure class.",path:["failureClass"]}),e.status==="timeout"&&e.failureClass!=="timeout"&&t.addIssue({code:"custom",message:"Timed-out Work must use the timeout failure class.",path:["failureClass"]})}),zo=g.object({schemaVersion:g.literal(Ap),id:g.string().regex(/^work-evidence-[a-f0-9]{24}$/),source:g.object({surface:g.enum(["desktop","hosted"]),experience:g.enum(["work","development"]),opaqueRef:Np,revisionHash:he}).strict(),agentSnapshot:Aa.nullable(),model:qa,runtime:g.object({adapterId:gt,adapterVersion:gt,capabilityRef:ie.nullable()}).strict(),inputHash:he,terminal:Zp,trace:g.object({sanitizedRef:ie,traceHash:he,sanitationPolicyVersion:gt,incomplete:g.boolean()}).strict(),outputRefs:g.array(ie).max(1e4),artifactRefs:g.array(ie).max(1e5),validationEvidenceRefs:g.array(ie).max(1e4),interventions:g.object({approvals:g.number().int().nonnegative().max(1e6),questions:g.number().int().nonnegative().max(1e6),steeringEvents:g.number().int().nonnegative().max(1e6),otherUserInterventions:g.number().int().nonnegative().max(1e6)}).strict(),timing:g.object({startedAt:yt,completedAt:yt,latencyMs:g.number().int().nonnegative().max(31536e6)}).strict(),usage:g.object({promptTokens:g.number().int().nonnegative().nullable(),completionTokens:g.number().int().nonnegative().nullable(),totalTokens:g.number().int().nonnegative().nullable()}).strict(),costUsd:g.number().nonnegative().max(1e6).nullable(),provenance:g.object({consentReceiptRef:ie,consentScope:g.literal("work_process_and_artifacts"),consentGrantedAt:yt,policyVersion:gt,projectorVersion:gt,disclosure:g.literal("portable_sanitized"),ownershipScope:g.enum(["personal","workspace"]),workspaceRef:Mp.nullable(),participantPolicy:g.enum(["creator_only","all_participants"]),retention:g.object({policy:g.literal("source_bound"),deleteWithSource:g.literal(!0),expiresAt:yt.nullable()}).strict()}).strict()}).strict().superRefine((e,t)=>{e.trace.traceHash!==e.trace.sanitizedRef.contentHash&&t.addIssue({code:"custom",message:"Sanitized trace reference must bind traceHash.",path:["trace","traceHash"]});let r=Date.parse(e.timing.completedAt)-Date.parse(e.timing.startedAt);(r<0||r!==e.timing.latencyMs)&&t.addIssue({code:"custom",message:"latencyMs must equal completedAt minus startedAt.",path:["timing","latencyMs"]}),e.provenance.ownershipScope==="workspace"&&e.provenance.workspaceRef===null&&t.addIssue({code:"custom",message:"Workspace-owned evidence requires workspaceRef.",path:["provenance","workspaceRef"]}),e.provenance.ownershipScope==="personal"&&e.provenance.workspaceRef!==null&&t.addIssue({code:"custom",message:"Personal evidence cannot carry workspaceRef.",path:["provenance","workspaceRef"]}),Vo(e.outputRefs,["outputRefs"],t),Vo(e.artifactRefs,["artifactRefs"],t),Vo(e.validationEvidenceRefs,["validationEvidenceRefs"],t)}),kn=zo.safeExtend({contentHash:he}).strict(),Yp=g.enum(["accepted","needs_correction","not_useful"]),Qp=g.enum(["correct","complete","high_quality","incorrect","incomplete","wrong_format","unsafe","stale","irrelevant","other"]),Oc=g.object({schemaVersion:g.literal(Pp),id:g.string().regex(/^work-feedback-[a-f0-9]{24}$/),evidenceReceiptRef:ie,outputRevisionRef:ie.nullable(),verdict:Yp,reasonCodes:g.array(Qp).max(16),correctionRef:ie.nullable(),correctedOutputRevisionRef:ie.nullable(),actor:g.literal("user"),createdAt:yt}).strict().superRefine((e,t)=>{new Set(e.reasonCodes).size!==e.reasonCodes.length&&t.addIssue({code:"custom",message:"Feedback reason codes must be unique.",path:["reasonCodes"]}),e.verdict!=="needs_correction"&&(e.correctionRef||e.correctedOutputRevisionRef)&&t.addIssue({code:"custom",message:"Only needs_correction feedback may bind correction artifacts.",path:["verdict"]})}),Zo=Oc.safeExtend({contentHash:he}).strict();function Pc(e){return`urn:openpond:artifact:${e}`}i(Pc,"evidenceArtifactId");function gk(e){return`urn:openpond:work:${y(e)}`}i(gk,"workSourceOpaqueRef");function yk(e){return`urn:openpond:workspace:${y(e)}`}i(yk,"workWorkspaceOpaqueRef");function Gp(e){return ie.parse({id:Pc(e.contentHash),contentHash:e.contentHash,mediaType:e.mediaType??null,sizeBytes:e.sizeBytes??null})}i(Gp,"evidenceArtifactRef");function wk(e){let t=Ac.parse(e);return Xo.parse({...t,contentHash:y(t)})}i(wk,"createWorkProcessTrace");function kk(e){let t=zo.parse(e);return kn.parse({...t,contentHash:y(t)})}i(kk,"createWorkEvidenceReceipt");function Rk(e,t){let r=Oc.parse(e),n=Zo.parse({...r,contentHash:y(r)});return t&&Kp(n,t),n}i(Rk,"createWorkFeedbackReceipt");function Tk(e){return _p(e,kn,zo)}i(Tk,"verifyWorkEvidenceReceipt");function vk(e){return Gp({contentHash:e.contentHash,mediaType:"application/vnd.openpond.work-evidence+json",sizeBytes:null})}i(vk,"workEvidenceReceiptRef");function Kp(e,t){if(e.evidenceReceiptRef.contentHash!==t.contentHash)throw new Error("Feedback targets a different Work evidence receipt.");if(e.outputRevisionRef&&!t.outputRefs.some(r=>r.contentHash===e.outputRevisionRef.contentHash))throw new Error("Feedback targets an output revision not bound by the Work evidence receipt.")}i(Kp,"assertFeedbackTargetsEvidence");function _p(e,t,r){let n=t.safeParse(e);if(!n.success)return!1;let{contentHash:o,...s}=n.data;return y(r.parse(s))===o}i(_p,"verifyHashedValue");function Vo(e,t,r){let n=e.map(o=>o.contentHash);new Set(n).size!==n.length&&r.addIssue({code:"custom",message:"Artifact content hashes must be unique.",path:t})}i(Vo,"addDuplicateHashIssues");import{randomUUID as $p}from"node:crypto";import{promises as Rn}from"node:fs";import Nc from"node:path";function Xt(e){return{binding:i(()=>{let t=gi(e.home,"refiner_bindings","active");return t?Xr.parse(t.value):null},"binding"),releases:i(async()=>{let t=(await Rn.readdir(e.releases)).filter(r=>r.endsWith(".json"));return Promise.all(t.map(async r=>vo.parse(JSON.parse(await Rn.readFile(Nc.join(e.releases,r),"utf8")))))},"releases"),transitions:i(()=>Object.values(yi(e.home,"refiner_transitions")).map(t=>Eo.parse(t.value)),"transitions"),release:i(async t=>{let r=vo.parse(JSON.parse(await Rn.readFile(Nc.join(e.releases,`${t.contentHash}.json`),"utf8")));if(r.id!==t.id||r.contentHash!==t.contentHash)throw new Error("Refiner release reference does not match immutable release content.");return r},"release"),persistRelease:i(async t=>Mc(e.releases+`/${t.contentHash}.json`,Na(t),!0),"persistRelease"),writeSource:i(async t=>Mc(e.source,t),"writeSource"),transition:i(async(t,r)=>{hi(e.home,n=>{n.exec("BEGIN IMMEDIATE");try{let o=n.prepare("SELECT payload FROM refiner_bindings WHERE id = 'active'").get(),s=o?Xr.parse(JSON.parse(o.payload)):null,a=new Date().toISOString(),c={id:t.id,contentHash:t.contentHash},d={schemaVersion:"openpond.refinerTransitionReceipt.v1",id:`refiner-transition-${$p()}`,operation:r.operation,bindingChanged:r.bindingChanged,previousRelease:s?.release??null,nextRelease:c,actor:r.actor,reason:r.reason,authoringSkillHash:r.authoringSkillHash,validation:{valid:!0,messages:[]},createdAt:a},l=Eo.parse({...d,contentHash:y(d)});if(n.prepare("INSERT INTO refiner_transitions VALUES (?, ?, 1)").run(l.contentHash,JSON.stringify(l)),r.bindingChanged){let p=Xr.parse({schemaVersion:"openpond.refinerBinding.v1",channel:"active",revision:(s?.revision??-1)+1,release:c,updatedAt:a});n.prepare("INSERT INTO refiner_bindings VALUES ('active', ?, 1) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload, revision=revision+1").run(JSON.stringify(p))}n.exec("COMMIT")}catch(o){throw n.exec("ROLLBACK"),o}})},"transition")}}i(Xt,"createLocalRefinerProfileRepository");async function Mc(e,t,r=!1){await wt(e,async()=>{if(r){let n=await Rn.readFile(e,"utf8").catch(()=>null);if(n!==null){if(n!==t)throw new Error("Immutable Refiner release bytes changed.");return}}await ui(e,t)})}i(Mc,"atomicWrite");var Dc="OpenPond Refiner Core: evidence admission, privacy, ownership, validation, and immutable activation boundaries.";function gr(e){let t=rt.join(e,"library","refiners");return{home:e,root:t,source:rt.join(t,"source","openpond.review.json"),releases:rt.join(t,"releases")}}i(gr,"refinerProfilePaths");function qk(e){let t=i(()=>ze(e),"inspect"),r=i(s=>em(e,s),"update"),n=i(s=>rm(e,s),"activate"),o=i(s=>om(e,s),"rollback");return{refinerHistoryPayload:t,updateRefinerProfilePayload:r,activateRefinerReleasePayload:n,rollbackRefinerReleasePayload:o,inspectRefiner:t,updateRefiner:r,activateRefiner:n,rollbackRefiner:o}}i(qk,"createRefinerProfileRoutePayloads");async function ze(e){let t=gr(e),r=Xt(t),n=r.binding();if(!n)throw new Error("Active Refiner binding is unavailable.");let o=(await r.releases()).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),s=o.find(c=>c.id===n.release.id&&c.contentHash===n.release.contentHash);if(!s)throw new Error("Active Refiner release is unavailable.");let a=r.transitions().sort((c,d)=>d.createdAt.localeCompare(c.createdAt));return Qi.parse({rootPath:t.root,sourcePath:t.source,binding:n,currentRelease:s,releases:o,transitions:a})}i(ze,"inspectRefinerProfile");async function Hc(e){return(await ze(e)).currentRelease}i(Hc,"loadActiveRefinerRelease");async function em(e,t){return wt(rt.join(ur(e).runtime,"refiner-edit"),()=>tm(e,t))}i(em,"updateRefinerProfile");async function tm(e,t){let r=Gi.parse(t),n=gr(e),o=Xt(n);await Yo(n);let s=Fa.parse(r.profile),a=So({profile:s,coreVersion:xo,corePrompt:Dc}),d=(await o.releases()).find(p=>p.composedPromptHash===a.composedPromptHash&&p.profileHash===a.profileHash)??a;await o.persistRelease(d),await o.writeSource(cr(s));let l=o.binding();if(!l)throw new Error("Active Refiner binding is unavailable.");return r.activate&&l.release.contentHash===d.contentHash||!r.activate&&o.transitions().some(m=>!m.bindingChanged&&m.nextRelease.contentHash===d.contentHash&&m.actor===r.actor&&m.reason===r.reason&&m.authoringSkillHash===r.authoringSkillHash)||await o.transition(d,{operation:"update",bindingChanged:r.activate,actor:r.actor,reason:r.reason,authoringSkillHash:r.authoringSkillHash}),ze(e)}i(tm,"updateRefinerProfileUnlocked");async function rm(e,t){return wt(rt.join(ur(e).runtime,"refiner-edit"),()=>nm(e,t))}i(rm,"activateRefinerRelease");async function nm(e,t){let r=qo.parse(t),n=gr(e),o=Xt(n);await Yo(n);let s=await o.release(r.release),a=o.binding();if(!a)throw new Error("Active Refiner binding is unavailable.");return a.release.contentHash===s.contentHash||(await o.transition(s,{operation:"activate",bindingChanged:!0,actor:r.actor,reason:r.reason,authoringSkillHash:null}),await o.writeSource(cr(s.profile))),ze(e)}i(nm,"activateRefinerReleaseUnlocked");async function om(e,t){return wt(rt.join(ur(e).runtime,"refiner-edit"),()=>sm(e,t))}i(om,"rollbackRefinerRelease");async function sm(e,t){let r=qo.parse(t),n=gr(e),o=Xt(n);await Yo(n);let s=await o.release(r.release),a=o.binding();if(!a)throw new Error("Active Refiner binding is unavailable.");return a.release.contentHash===s.contentHash||(await o.transition(s,{operation:"rollback",bindingChanged:!0,actor:r.actor,reason:r.reason,authoringSkillHash:null}),await o.writeSource(cr(s.profile))),ze(e)}i(sm,"rollbackRefinerReleaseUnlocked");async function am(e){await wt(rt.join(ur(e).runtime,"refiner-initialize"),()=>im(gr(e)))}i(am,"initializeRefinerProfile");async function Yo(e){await am(e.home)}i(Yo,"ensureInitialized");async function im(e){let t=Xt(e);if(await Promise.all([Lc.mkdir(rt.dirname(e.source),{recursive:!0,mode:448}),Lc.mkdir(e.releases,{recursive:!0,mode:448})]),t.binding())return;let r=So({profile:Ua,coreVersion:xo,corePrompt:Dc});await t.persistRelease(r),await t.writeSource(cr(r.profile)),await t.transition(r,{operation:"initialize",bindingChanged:!0,actor:"openpond",reason:"Initialize the default Refiner Review Profile.",authoringSkillHash:null})}i(im,"initialize");import{randomUUID as fm}from"node:crypto";var cm=["prompt_tokens","promptTokens","input_tokens","inputTokens"],dm=["completion_tokens","completionTokens","output_tokens","outputTokens"],lm=["total_tokens","totalTokens"];function Ze(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=Qo(t,cm),n=um(t,r),o=n.promptTokens,s=Qo(t,dm),c=Qo(t,lm)??(o!==null&&s!==null?o+s:null);return{promptTokens:o,cachedPromptTokens:n.cachedPromptTokens,uncachedPromptTokens:n.uncachedPromptTokens,cacheWritePromptTokens:n.cacheWritePromptTokens,cacheTelemetrySource:n.cacheTelemetrySource,completionTokens:s,totalTokens:c}}i(Ze,"normalizeModelUsageTokens");function um(e,t){let r=Tn(e,["cached_input_tokens","cachedInputTokens","cached_prompt_tokens","cachedPromptTokens","prompt_cache_hit_tokens","promptCacheHitTokens"]),n=Tn(e,["prompt_cache_miss_tokens","promptCacheMissTokens"]),o=Tn(e,["cache_read_input_tokens","cacheReadInputTokens"]),s=mm(e,[["prompt_tokens_details","cached_tokens"],["promptTokensDetails","cachedTokens"],["input_tokens_details","cached_tokens"],["inputTokensDetails","cachedTokens"]]),a=Tn(e,["cache_creation_input_tokens","cacheCreationInputTokens","cache_write_input_tokens","cacheWriteInputTokens"]),c=r.value!==null?r:o.value!==null?o:s,d=c.value!==null||n.value!==null||a.value!==null,l=d?pm(e):null;if(!d)return{promptTokens:t,cachedPromptTokens:null,uncachedPromptTokens:null,cacheWritePromptTokens:null,cacheTelemetrySource:null};let p=c.value,u=a.present?a.value:null,m=c===o&&o.value!==null||a.value!==null,f=t??(c.value!==null&&n.value!==null?c.value+n.value:null);if(f===null)return{promptTokens:null,cachedPromptTokens:p,uncachedPromptTokens:n.value,cacheWritePromptTokens:u,cacheTelemetrySource:l};if(m){let w=p??0,k=u??0,x=t??n.value??0;return{promptTokens:x+w+k,cachedPromptTokens:p,uncachedPromptTokens:x+k,cacheWritePromptTokens:u,cacheTelemetrySource:l}}let h=p===null?null:Math.min(f,p),R=n.value===null?h===null?null:f-h:Math.min(f-(h??0),n.value);return{promptTokens:f,cachedPromptTokens:h,uncachedPromptTokens:R,cacheWritePromptTokens:u,cacheTelemetrySource:l}}i(um,"normalizeCacheUsage");function pm(e){return(e.cache_telemetry_source??e.cacheTelemetrySource)==="provider_response_headers"?"provider_response_headers":"provider_usage_body"}i(pm,"cacheTelemetrySourceFromUsage");function Tn(e,t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r))return{present:!0,value:Go(e[r])};return{present:!1,value:null}}i(Tn,"firstPresentTokenCount");function mm(e,t){for(let[r,n]of t){let o=e[r];if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o;if(Object.prototype.hasOwnProperty.call(s,n))return{present:!0,value:Go(s[n])}}return{present:!1,value:null}}i(mm,"firstPresentNestedTokenCount");function Qo(e,t){for(let r of t){let n=Go(e[r]);if(n!==null)return n}return null}i(Qo,"firstTokenCount");function Go(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e);if(typeof e!="string")return null;let t=e.trim();if(!/^\d+$/.test(t))return null;let r=Number(t);return Number.isSafeInteger(r)?r:null}i(Go,"tokenCount");function En(e){let t=vn(vn(vn(e.metadata).billing).pricing);return{version:zt(t.version,"pricing version"),source:zt(t.source,"pricing source"),effectiveAt:zt(t.effectiveAt,"pricing effective date"),inputUsdPerMillionTokens:Zt(t.inputUsdPerMillionTokens,"input token rate"),cachedInputUsdPerMillionTokens:Zt(t.cachedInputUsdPerMillionTokens,"cached input token rate"),outputUsdPerMillionTokens:Zt(t.outputUsdPerMillionTokens,"output token rate")}}i(En,"hostedTokenPricingFromCatalog");function Xk(e){let t=vn(e);try{return{version:zt(t.version,"pricing version"),source:zt(t.source,"pricing source"),effectiveAt:zt(t.effectiveAt,"pricing effective date"),inputUsdPerMillionTokens:Zt(t.inputUsdPerMillionTokens,"input token rate"),cachedInputUsdPerMillionTokens:Zt(t.cachedInputUsdPerMillionTokens,"cached input token rate"),outputUsdPerMillionTokens:Zt(t.outputUsdPerMillionTokens,"output token rate")}}catch{return null}}i(Xk,"hostedTokenPricingFromValue");function nt(e,t){let r=Ze(e);if(r.promptTokens===null&&r.completionTokens===null)return null;let n=r.cachedPromptTokens??0;return((r.uncachedPromptTokens??r.promptTokens??0)*t.inputUsdPerMillionTokens+n*t.cachedInputUsdPerMillionTokens+(r.completionTokens??0)*t.outputUsdPerMillionTokens)/1e6}i(nt,"hostedUsageCostUsd");function vn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}i(vn,"record");function zt(e,t){if(typeof e=="string"&&e.trim())return e.trim();throw new Error(`Hosted model catalog is missing ${t}.`)}i(zt,"requiredString");function Zt(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;throw new Error(`Hosted model catalog is missing ${t}.`)}i(Zt,"requiredRate");function qc(e={}){let t=e.catalog??fn,r=e.stream??hn;return{async prepare(n){if(n.providerId!=="openpond")throw new Error("The selected judge provider is not connected to the hosted judge transport.");if(n.revision!==null)throw new Error("This judge transport cannot enforce a model revision; select a provider with revision support.");let o=await t();if(o.error)throw new Error(`Judge model catalog unavailable: ${o.error}`);let s=o.models.find(u=>u.id===n.modelId);if(!s)throw new Error("The selected judge model is unavailable.");let a=Wc(s.raw),c=En(a),d=jc(a.context_window,"context window"),l=Math.min(4096,jc(a.output_limit,"output limit")),p=(d*Math.max(c.inputUsdPerMillionTokens,c.cachedInputUsdPerMillionTokens)+l*c.outputUsdPerMillionTokens)/1e6;if(!(p>0))throw new Error("The judge model must have a positive known charge ceiling.");return{maximumChargeUsd:p,async dispatch(u){u?.throwIfAborted();let m="",f=null,h=null,R=null,w=!1;for await(let C of r({model:n.modelId,messages:[{role:"system",content:n.system},{role:"user",content:n.data}],requestId:`learning-judge-${fm()}`,maxTokens:l,temperature:n.temperature,signal:u})){let A=Wc(C.raw);if(typeof A.model=="string"){if(f!==null&&A.model!==f)throw new Error("Judge response model identity changed during streaming.");f=A.model}if(typeof A.id=="string"){if(h!==null&&h!==A.id)throw new Error("Judge response identity changed during streaming.");h=A.id}if(C.type==="text_delta"&&(m+=C.text),m.length>1e5)throw new Error("Judge response exceeds the retained response limit.");C.type==="usage"&&(R=C.usage),C.type==="finish"&&(w=!0)}if(!w||!f||!h)throw new Error("Judge response did not include a complete model receipt.");let k=Ze(R),x=k.promptTokens!==null&&k.completionTokens!==null?nt(R,c):null;return{text:m,modelId:f,modelRevision:null,responseId:h,inputTokens:k.promptTokens,outputTokens:k.completionTokens,costUsd:x}}}},async cancel({run:n}){return!n.judgeCalls?.some(o=>o.status==="reserved")}}}i(qc,"createLearningHostedJudgeProvider");function Wc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}i(Wc,"record");function jc(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)throw new Error(`Judge catalog is missing its ${t}.`);return e}i(jc,"positiveInteger");function sR(e,t=qc()){return{execute(r){if(r.definition.execution.environment.entrypoint==="openpond.javascript-environment.v1")throw new Error("Tool Tasksets require grading an owner-recorded environment attempt.");let n=ni({repository:e,scope:r.scope,run:r.run});return Qa({binding:r.binding,rewards:r.rewards,task:Gr(r.evidence,r.definition),evidence:ri(r.evidence,r.run.output),evaluatorContext:r.evidence.submission.evaluatorContext,signal:r.signal,modelJudge:$a({readRubric:i(o=>e.transaction(r.scope,async s=>ue(await Ue(s,"asset",o.id,1),o)),"readRubric"),async executeBudgeted(o,s){let a=await t.prepare(o,{scope:r.scope,run:r.run});return ei({store:n,maximumCharge:i(()=>a.maximumChargeUsd,"maximumCharge"),dispatch:i((d,l)=>a.dispatch(l),"dispatch")})(`grade-${y(o)}`,o,s)}}),customVerifier:i(async({grader:o,task:s,evidence:a})=>{let c=await yr({repository:e,scope:r.scope,grader:o,task:s,evidence:a,evaluatorContext:r.evidence.submission.evaluatorContext,timeoutMs:r.run.timeoutMs,signal:r.signal});return{score:c.score,passed:c.passed,rewardEligible:o.rewardEligible,failureClass:null,feedback:[c.feedback],visibleEvidenceRefs:[],privilegedEvidenceRefs:c.evidenceRefs}},"customVerifier")})},async cancel({scope:r,run:n}){let o=await e.transaction(r,s=>Ue(s,"grade",n.id));return o.judgeCalls?.some(s=>s.status==="reserved")?!1:t.cancel({scope:r,run:o})}}}i(sR,"createLocalTaskGradeExecutor");async function yr(e){let t=await e.repository.transaction(e.scope,async r=>ue(await Ue(r,"asset",e.grader.verifierRef.id,1),e.grader.verifierRef));return Vt({source:t,exportName:e.grader.exportName,runtime:e.grader.runtime,timeoutMs:Math.min(e.grader.timeoutMs,e.timeoutMs??e.grader.timeoutMs),signal:e.signal,value:{task:e.task,attempt:e.evidence,input:e.task.input,output:e.evidence.output,expectedOutput:e.task.expectedOutput,evaluatorContext:e.evaluatorContext,infrastructureError:e.evidence.infrastructureError??null}})}i(yr,"executeLocalLearningVerifier");import hm from"node:path";async function Fc(e,t,r){if(!r)throw new Error("Ordinary tool execution requires its owner's package directory.");let n=$r({taskset:e,adapterId:dn(e)}),o=await wc({root:hm.join(r,"training","tasksets",Me(e)),content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:n.tasksetRelease,environment:n.environmentRelease,verifierSet:n.verifierSetRelease},sources:ec.parse(e.metadata.portableFileInventory)}),s=Ii(o);if(!s)throw new Error("The Taskset does not declare a JavaScript execution graph.");let a=o.taskset.tasks.find(l=>l.id===t.id);if(!a)throw new Error("The selected task is missing from its executable package.");let c=s.assets.find(l=>l.id===s.execution.javascript.module.id),d=s.assets.find(l=>l.id===a.privilegedContextRef);return{execution:s.execution,module:c,initialState:JSON.parse(d.text),definition:Y(o.taskset),instructions:Ci(o),task:a}}i(Fc,"loadOrdinaryToolEnvironment");var ce="openpond.javascript-environment.v1";async function Yt(e,t,r,n){let o=t.tasks.find(s=>s.id===r.id);if(!o||y(o)!==y(r))throw new Error("Tool task differs from the selected immutable Taskset.");return t.metadata.taskDefinition===void 0?Fc(t,r,n):e.learningRepository().transaction(t.profileId,async s=>{let a=await Be(s,"definition",Ee.parse(t.metadata.taskDefinition)),c=a.execution.environment;if(c.entrypoint!==ce||t.environment.entrypoint!==ce||t.environment.kind!=="agent"||t.environment.stateful!==c.stateful||t.environment.defaultTimeoutMs!==c.defaultTimeoutMs||t.environment.networkPolicy!==c.networkPolicy||t.environment.deterministicSeeds!==c.deterministicSeeds||y(t.environment.toolNames)!==y(a.execution.tools.map(T=>T.name))||y(t.environment.metadata.portableTools)!==y(a.execution.tools)||y(t.policy)!==y(a.execution.policy)||y(t.metadata.rewardBinding)!==y(a.rewardBinding))throw new Error("Tool Taskset context differs from its pinned task definition.");let d=await Be(s,"binding",a.rewardBinding),l=await Promise.all(d.sources.map(T=>Be(s,"reward",T.reward))),p=Qr.parse({id:r.id,clusterKey:r.clusterKey,split:r.split,input:r.input,expectedOutput:r.expectedOutput,policyVisibleContext:r.policyVisibleContext,privilegedContextRef:r.privilegedContextRef,artifactRefs:[],tags:r.tags}),u={...a.execution,graders:$e(d,l),tasks:[p]},m=await Ue(s,"asset",Si(u),1),f=vi.parse(JSON.parse(ue(m,m.asset))),h=[f.javascript.module,f.environment.actionSchemaRef,f.environment.observationSchemaRef,f.environment.stateSchemaRef].filter(T=>T!==null),R=[...new Set([...h.map(T=>T.id),r.privilegedContextRef].filter(T=>T!==null))],w=await Promise.all(R.map(T=>Ue(s,"asset",T,1))),k=xi(u,m,w);if(y(t.environment.metadata.portableExecutionResources)!==y({environment:k.environment,verifierSet:k.verifierSet}))throw new Error("Tool Taskset publication differs from its private execution resources.");let x=w.find(T=>T.id===k.javascript.module.id),C=w.find(T=>T.id===r.privilegedContextRef),A=JSON.parse(ue(C,C.asset));return{execution:k,module:x,initialState:A,definition:Y(a),instructions:a.instructions,task:p}})}i(Yt,"loadStarterToolEnvironment");function Uc(e){let t=Mo({text:e.instructions,path:"policy/instructions.txt",mediaType:"text/plain",visibility:"policy"}),r=Mo({text:JSON.stringify({environment:Y(e.execution.environment),verifierSet:Y(e.execution.verifierSet),javascript:Y(e.execution.javascript)}),path:"environment/dependencies.json",mediaType:"application/json",visibility:"host_private"}),n=La({schemaVersion:"openpond.agentSnapshot.v2",id:`starter-agent-${e.definition.contentHash}`,sourceRelease:{id:e.definition.id,contentHash:e.definition.contentHash},instructions:[t.asset],skills:[],agents:[],toolDeclarations:e.execution.javascript.tools,capabilityRequirements:[],dependencyLock:r.asset,portability:{portable:!0,blockers:[],localOnlyAssetRefs:[],hostPrivateAssetRefs:[e.module.id,r.id]},metadata:{execution:ce}}),o=Da({schemaVersion:"openpond.harnessRelease.v2",id:`starter-harness-${n.contentHash}`,agentSnapshot:{id:n.id,contentHash:n.contentHash},program:e.module.asset,tools:e.execution.javascript.tools,lifecycle:{create:!0,reset:!0,step:!0,collect:!0,destroy:!0,resetScope:"attempt"},graderInterface:{visibleEvidence:["output"],privilegedEvidence:["environment_state","private_verifier"],privateVerifierIsolation:!0},files:[t.asset,r.asset,e.module.asset],metadata:{execution:ce}});return{agentSnapshot:n,harnessRelease:o,instructionContext:void 0}}i(Uc,"compileStarterToolHarness");import Sn from"node:path";import{constants as Bc}from"node:fs";import{open as gm,realpath as Jc}from"node:fs/promises";var ym=g.string().regex(/^[a-f0-9]{64}$/),wm=g.object({schemaVersion:g.literal("openpond.starterToolAttempt.v1"),requestId:g.string(),taskset:Ee,taskHash:ym,model:g.unknown(),seed:g.number().int(),attempt:g.number().int(),definition:Ee,policySource:g.enum(["model","fixture"]),environment:Ee,verifierSet:Ee,result:Ti}).strict();async function xn(e){let{store:t,taskset:r,task:n,attempt:o}=e,s=await Yt(t,r,n,e.storeDir),c=(await t.listTaskAttemptArtifacts({attemptId:o.id})).filter(x=>x.kind==="environment_state"&&x.tasksetId===r.id&&x.taskId===n.id&&x.attemptId===o.id&&o.artifactRefs.includes(x.id)&&o.privilegedOutcomeRef===x.id);if(c.length!==1)throw new Error("Tool grading requires exactly one owner-recorded environment artifact.");let d=c[0],l=await Jc(Sn.join(e.storeDir,"training","evaluation-artifacts")),p=await Jc(Sn.dirname(d.path)),u=Sn.relative(l,p);if(!u||u.startsWith("..")||Sn.isAbsolute(u))throw new Error("Tool evidence is outside the execution owner's artifact directory.");let m=await gm(d.path,Bc.O_RDONLY|Bc.O_NOFOLLOW),f;try{let x=await m.stat();if(!x.isFile()||x.size>33554432||x.size!==d.sizeBytes)throw new Error("Tool evidence exceeds its declared byte boundary.");f=await m.readFile()}finally{await m.close()}if(f.byteLength!==d.sizeBytes||ve(f)!==d.sha256)throw new Error("Owner-recorded tool evidence bytes changed.");let h=wm.parse(JSON.parse(f.toString("utf8"))),{contentHash:R,...w}=h.result,k=h.result;if(y(w)!==R||!k.snapshot||!k.environmentCleanupComplete||!["completed","budget_exhausted","policy_failure"].includes(k.status)||y(h.taskset)!==y(Y(r))||h.taskHash!==y(n)||y(h.model)!==y(o.modelRef)||h.seed!==o.seed||h.attempt!==o.attempt||o.tasksetId!==r.id||o.taskId!==n.id||o.split!==n.split||y(h.definition)!==y(s.definition)||y(h.environment)!==y(Y(s.execution.environment))||y(h.verifierSet)!==y(Y(s.execution.verifierSet))||k.taskId!==n.id||k.snapshot.seed!==o.seed||k.snapshot.inputHash!==y(n.input)||y(k.snapshot.definition)!==y(Y(s.execution.javascript))||k.snapshot.finalStateHash!==y(k.snapshot.state)||y(o.output)!==y({text:k.output??""})||o.metadata.environmentAttemptHash!==R)throw new Error("Tool evidence differs from the selected task, model or recorded attempt.");if(o.metadata.policySource!==h.policySource)throw new Error("Tool evidence policy source changed.");return{environment:{status:k.status,collected:k.collected,definition:k.snapshot.definition,initialStateHash:k.snapshot.initialStateHash,finalStateHash:k.snapshot.finalStateHash,finalState:k.snapshot.state,events:k.snapshot.events}}}i(xn,"readStarterToolEvidence");async function ot(e,t){if(t.metadata.learning!==void 0)return qt.parse(t.metadata.learning);if(t.metadata.rewardBinding===void 0)return;let r=Ee.parse(t.metadata.rewardBinding);return e.learningRepository().transaction(t.profileId,async n=>{let o=await Be(n,"binding",r),s=[...new Map(o.sources.map(c=>[`${c.reward.id}:${c.reward.revision}:${c.reward.contentHash}`,c.reward])).values()],a=await Promise.all(s.map(c=>Be(n,"reward",c)));return{binding:o,rewards:a}})}i(ot,"resolveTasksetRewardBinding");async function km(e,t,r){let n=await ot(e,t);if(!n)return{rewardExecution:void 0,verifierAssets:[]};let o=$e(n.binding,n.rewards).flatMap(c=>c.kind==="custom_verifier"?[c.verifierRef]:c.kind==="model_judge"?[c.rubricRef]:[]),s=t.metadata.learning===void 0?void 0:await un(r,t);if(s){let c=[...new Map(o.map(d=>{let l=s.learningResources.assets.find(p=>p.id===d.id);if(!l)throw new Error("Imported batch verifier is missing from its package.");return ue(l,d),[l.id,l]})).values()];return{rewardExecution:n,verifierAssets:c}}let a=await e.learningRepository().transaction(t.profileId,async c=>{let d=new Map;for(let l of o){let p=await Ue(c,"asset",l.id,1);ue(p,l),d.set(p.id,p)}return[...d.values()]});return{rewardExecution:n,verifierAssets:a}}i(km,"resolveTasksetTrainingReward");async function YR(e,t,r){let n=await km(e,t,r.storeDir);if(!n.rewardExecution)return n;let o=$e(n.rewardExecution.binding,n.rewardExecution.rewards);if(!n.rewardExecution.binding.sources.some(s=>s.role==="evaluation"&&s.weight>0))throw new Error("Managed training requires a positively weighted evaluation Reward source for retained validation.");if(o.some(s=>s.kind==="custom_verifier"&&s.runtime==="sandbox_process"))throw new Error("Managed preparation requires a qualified isolated sandbox for process verifiers.");if(r.placement!=="remote"||t.environment.kind==="work"||t.capabilities.requiresState||t.capabilities.requiresTools||o.some(s=>s.kind==="human"||s.kind==="model_judge"&&(!s.model||s.calibrationStatus!=="passed"))||t.tasks.some(s=>s.privilegedContextRef!==null)||!n.rewardExecution.binding.sources.some(s=>s.role==="training"&&s.weight>0)||r.hasLearnedPreferenceReward)throw new Error("This Reward binding requires an additional managed execution adapter.");return n}i(YR,"resolveManagedTasksetReward");async function Vc(e,t,r){let n=await ot(e,t);if(!n)throw new Error("The Taskset has no published Reward binding.");let o=$e(n.binding,n.rewards);return async({grader:s,task:a,attempt:c,signal:d})=>{let l=t.tasks.find(f=>f.id===a.id);if(!l||y(l)!==y(a))throw new Error("Task differs from the selected immutable Taskset.");let p=null;if(t.environment.entrypoint===ce){if(!r)throw new Error("Tool grading requires the execution owner's artifact directory.");p=await xn({store:e,storeDir:r,taskset:t,task:a,attempt:c})}else if(a.privilegedContextRef!==null)throw new Error("This authored Taskset requires a private evaluator-context resolver.");let u=o.find(f=>f.id===s.id);if(u?.kind!=="custom_verifier")throw new Error("The verifier is absent from the published Reward binding.");let m=Qr.parse({id:a.id,clusterKey:a.clusterKey,split:a.split,input:a.input,expectedOutput:a.expectedOutput,policyVisibleContext:a.policyVisibleContext,privilegedContextRef:a.privilegedContextRef,artifactRefs:[],tags:a.tags});return yr({repository:e.learningRepository(),scope:t.profileId,grader:u,task:m,evidence:{output:c.output,artifactRefs:c.artifactRefs,runtimeEventRefs:c.runtimeEventRefs,infrastructureError:c.infrastructureError},evaluatorContext:p,signal:d})}}i(Vc,"createTasksetBindingVerifier");async function Tt(e,t,r){let n=r?Ee.parse(r):null;if(n&&n.id!==t)throw new Error("Taskset execution reference differs from the requested Taskset.");let o=n?await e.getTasksetRevision(n.id,n.revision):await e.getTaskset(t);if(!o||n&&(o.contentHash!==n.contentHash||et(o)!==n.contentHash))throw new Error("Taskset execution revision is unavailable or differs from its immutable hash.");return o}i(Tt,"requireLocalTasksetRevision");async function tT(e,t,r){let n=await e.releaseForTaskset(t);return n||$r({taskset:t,rewardExecution:r?await ot(r,t):void 0,adapterId:dn(t)}).tasksetRelease}i(tT,"requireReleasedTaskset");import{createHash as Rm}from"node:crypto";function Xc(e,t,r){if(t.metadata.importedPackageHash!==e.contentHash)throw new Error("The Work projection differs from the admitted published package.");let n=e.taskset.tasks.find(a=>a.id===r.id);if(!n||n.split!==r.split||y(r.metadata.portableTaskRecord)!==y(n))throw new Error("The Work task differs from its exact released population.");let o=0,s=(r.assets??[]).map(a=>{let c=n.artifactRefs.find(u=>u.id===a.id&&u.contentHash===a.sha256&&u.path===a.artifactRef),d=c&&e.files.find(u=>y(u.asset)===y(c));if(!c||!d||c.visibility!=="policy")throw new Error("The Work task requests an unavailable or private evaluator file.");let l=Buffer.from(bi(d));if(Rm("sha256").update(l).digest("hex")!==a.sha256||l.length!==a.sizeBytes||a.split!==r.split)throw new Error("The published Work input manifest changed.");if(o+=l.length,o>25e7)throw new Error("Published Work inputs exceed the admitted 250 MB ceiling.");return{...a,assetId:a.id,storageName:a.fileName,bytes:l,sizeBytes:l.length}});if(s.length!==n.artifactRefs.length)throw new Error("The exact policy-visible Work asset population is incomplete.");return s}i(Xc,"advancedPublishedWorkAssets");import{AsyncLocalStorage as Tm}from"node:async_hooks";var Zc=new Tm,wr=i(()=>Zc.getStore(),"currentScheduledAdmissionGuard");function lT(e,t){return Zc.run(e,t)}i(lT,"withScheduledAdmission");var Qt=class extends Error{constructor(r,n,o){super("The scheduled request was refused before provider transport.",{cause:o});this.executionId=r;this.requestId=n}executionId;requestId;static{i(this,"ScheduledTransportNotInvokedError")}},zc=class extends Error{constructor(r,n,o){super("The scheduled admission lost its exact owner lease before Run insertion.");this.scheduleId=r;this.operationId=n;this.configurationHash=o}scheduleId;operationId;configurationHash;static{i(this,"ScheduledAdmissionRejectedError")}};function bn(e,t){let r=t.scope==="arguments"?e.action?.arguments:e[t.scope];for(let n of t.path){if(!r||typeof r!="object"||!Object.hasOwn(r,n))throw new Error("environment_service_reference_missing");r=r[n]}return r}i(bn,"resolveValue");async function kr(e,t){if(!e.executionServices?.length)return t.controller(e);if(!Number.isSafeInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>3e4)throw new Error("environment_timeout_invalid");G(e.value,4194304);let r=e.executionServices.map(c=>ci.parse(c));if(r.length>16)throw new Error("environment_service_limit");if(new Set(r.map(c=>c.id)).size!==r.length)throw new Error("environment_service_identity_collision");let n=Date.now(),o=new AbortController,s=e.signal?AbortSignal.any([e.signal,o.signal]):o.signal,a=setTimeout(()=>o.abort(new Error("environment_timeout")),e.timeoutMs);try{let c=Object.create(null);for(let l of r){if(s.throwIfAborted(),l.operation!==e.operation||l.operation==="step"&&l.toolName!==e.value.action?.name)throw new Error("environment_service_operation_mismatch");let p=Math.min(l.timeoutMs,e.timeoutMs-(Date.now()-n));if(p<1)throw new Error("environment_timeout");let u=new AbortController,m=AbortSignal.any([s,u.signal]),f=setTimeout(()=>u.abort(new Error("environment_service_timeout")),p),h=Date.now();try{if(l.kind==="sqlite.v1"){if(!t.sql)throw new Error("environment_sql_executor_required");let R=bn(e.value,l.sql);if(typeof R!="string"||!R.length||new TextEncoder().encode(R).byteLength>65536||R.includes("\0")){c[l.id]={status:"rejected",code:"invalid_submission"};continue}let w=Kr({schemaVersion:"openpond.sqlExecution.v1",snapshot:bn(e.value,l.snapshot),sql:R,maxRows:l.maxRows,maxResultBytes:l.maxResultBytes});c[l.id]=await t.sql({request:w,timeoutMs:e.timeoutMs,signal:m})}else{let R=bn(e.value,l.source),w=bn(e.value,l.cases);if(typeof R!="string"||new TextEncoder().encode(R).byteLength>524288){c[l.id]={status:"rejected",code:"invalid_submission"};continue}if(!Array.isArray(w)||!w.length||w.length>l.maxCases||w.some(x=>!x||typeof x!="object"||!Object.hasOwn(x,"input")))throw new Error("environment_service_cases_invalid");let k=[];for(let x of w){let C=p-(Date.now()-h);if(C<1&&(u.abort(new Error("environment_service_timeout")),m.throwIfAborted()),k.push(await t.candidate({source:R,exportName:l.exportName,value:structuredClone(x.input),timeoutMs:Math.max(1,C),maxResultBytes:l.maxResultBytes,deterministic:!0,errorPrefix:"candidate",signal:m})),new TextEncoder().encode(JSON.stringify({status:"completed",cases:k})).byteLength>l.maxResultBytes)throw new Bo("candidate_result_too_large")}c[l.id]={status:"completed",cases:k}}}catch(R){if(s.throwIfAborted(),u.signal.aborted)c[l.id]={status:"rejected",code:"timeout"};else if(R instanceof Bo)c[l.id]={status:"rejected",code:"execution_failed"};else throw R}finally{clearTimeout(f)}}s.throwIfAborted();let d=e.timeoutMs-(Date.now()-n);if(d<1)throw new Error("environment_timeout");return await t.controller({...e,executionServices:void 0,value:{...e.value,services:c},timeoutMs:d,signal:s})}finally{clearTimeout(a)}}i(kr,"executeEnvironmentWithServices");async function vm(e){let t=lr.parse(e.operation);return kr(e,{candidate:Jo,controller:i(async r=>Ft.parse(await Jo({...r,exportName:t,maxResultBytes:1572864,deterministic:!0,errorPrefix:"environment"})),"controller")})}i(vm,"executeJavaScriptEnvironment");var vt=class extends Error{static{i(this,"JavaScriptEnvironmentActionError")}code;constructor(t){super(`environment_${t}`),this.code=t,this.name="JavaScriptEnvironmentActionError"}};async function Yc(e){let t=li(e.definition),r=ue(e.asset,t.module);if(!Number.isSafeInteger(e.seed))throw new Error("environment_seed_invalid");let n=e.seed;G(e.input,1048576),G(e.initialState,t.maxStateBytes);let o=structuredClone(e.input),s=structuredClone(e.initialState),a=e.execute??vm,c=new AbortController,d=e.signal?AbortSignal.any([e.signal,c.signal]):c.signal,l={},p=0,u=!1,m=!1,f=null,h=[],R=null;async function w(x,C){if(u||m)throw new Error("environment_closed");if(f)throw new Error("environment_operation_in_progress");d.throwIfAborted(),C&&(G(C,262144),C=structuredClone(C));let A=y(l),T=C?t.tools.find(v=>v.name===C.name):null;if(x==="step"){if(p>=t.maxSteps)throw new vt("step_budget_exhausted");p++}let P=i((v,I)=>h.push({sequence:h.length,operation:x,toolName:C?.name??null,arguments:C?structuredClone(C.arguments):null,observation:v,beforeStateHash:A,afterStateHash:y(l),error:I}),"record");try{if(C&&!T)throw new vt("unknown_tool");if(C&&T&&!Ya(T.inputSchema,C.arguments).valid)throw new vt("invalid_arguments");let v=t.executionServices?.filter(E=>E.operation===x&&(x!=="step"||E.toolName===C?.name)),I=a({source:r,operation:x,value:{input:o,initialState:s,seed:n,state:structuredClone(l),sequence:p,action:C?structuredClone(C):null},timeoutMs:Math.min(t.operationTimeoutMs,T?.timeoutMs??t.operationTimeoutMs),signal:d,...v?.length?{executionServices:v}:{}});f=I;let S=Ft.parse(await I);if(d.throwIfAborted(),G(S.state,t.maxStateBytes),G(S.observation,t.maxObservationBytes),(x==="collect"||T?.sideEffect==="read")&&y(S.state)!==A)throw new Error("environment_read_changed_state");l=structuredClone(S.state);let N=structuredClone(S.observation);return P(N,null),{state:structuredClone(l),observation:N}}catch(v){throw P(null,v instanceof Error?v.message:"environment_execution_failed"),v}finally{f=null}}i(w,"invoke");async function k(){return R||(m=!0,c.abort(new Error("environment_destroyed")),R=(async()=>{try{try{await f}catch{}await a({source:r,operation:"destroy",value:{input:o,initialState:s,seed:n,state:structuredClone(l),sequence:p,action:null},timeoutMs:t.operationTimeoutMs})}finally{l={},u=!0}})(),R)}i(k,"destroy");try{await w("create");let x=await w("reset"),C=y(l),A=i(()=>{if(u)throw new Error("environment_closed");return{definition:{id:t.id,revision:t.revision,contentHash:t.contentHash},inputHash:y(o),seed:n,initialStateHash:C,finalStateHash:y(l),state:structuredClone(l),events:structuredClone(h)}},"snapshot");return{definition:structuredClone(t),observation:x.observation,async step(T){return(await w("step",T)).observation},async collect(){let T=await w("collect");return{...A(),observation:T.observation}},snapshot:A,destroy:k}}catch(x){try{await k()}catch{}throw x}}i(Yc,"createJavaScriptEnvironmentSession");var Em=g.string().trim().min(1).max(500),Sm=g.string().regex(/^[a-f0-9]{64}$/),Ko=g.object({kind:g.literal("model"),id:g.string().trim().min(1).max(191),taskId:Em,admissionHash:Sm,model:tc,instructions:g.string().max(262144),harness:Ka.optional(),input:g.record(g.string(),g.unknown()),policyVisibleContext:g.record(g.string(),g.unknown()),timeoutMs:g.number().int().positive().max(36e5),environment:g.discriminatedUnion("kind",[g.object({kind:g.literal("text")}).strict(),g.object({kind:g.literal("javascript"),definition:di,asset:Ga,initialState:g.record(g.string(),g.unknown()),seed:g.number().int().safe()}).strict()])}).strict(),MT=g.discriminatedUnion("kind",[Ko,g.object({kind:g.literal("profile"),request:g.unknown()}).strict()]);var Qc=g.string().trim().min(1).max(200),JT=g.object({receiptId:Qc,taskId:Qc,seed:g.string(),request:Ko}).strict(),M=class extends Error{constructor(r,n,o=409){super(n);this.code=r;this.status=o}code;status;static{i(this,"LocalExperimentError")}};async function _o(e,t=fn,r=!1){if(e.kind==="hosted_harness")return _o({kind:"hosted_chat",modelId:e.modelId,maxOutputTokens:4096,temperature:0,topP:1},t);if(e.kind!=="hosted_chat")throw new M("local_target_not_qualified","Select an explicit model target for local execution.",422);if(e.harness&&!r)throw new M("local_harness_not_qualified","This released Harness requires its native turn executor; it cannot run as a model-only case.",422);let n=await t();if(n.error)throw new M("local_model_catalog_unavailable",n.error,422);let o=n.models.find(m=>m.id===e.modelId);if(!o)throw new M("local_model_unavailable","The selected model is unavailable.",422);let s=Gc(o.raw),a=En(s),c=Gc(s.capabilities).samplingParameters===!0;if(!c&&(e.temperature!==0||e.topP!==1))throw new M("local_sampling_unsupported","This model uses provider-managed sampling. Custom temperature or top P requires an explicit supported capability.",422);let d=Kc(s.context_window),l=Kc(s.output_limit);if(e.maxOutputTokens>l)throw new M("local_model_output_limit","The model cannot accept the configured output limit.",422);let p={providerId:"openpond",modelId:e.modelId,maxOutputTokens:e.maxOutputTokens,...c?{temperature:e.temperature,topP:e.topP}:{},messages:e.messages??[]},u=(d*Math.max(a.inputUsdPerMillionTokens,a.cachedInputUsdPerMillionTokens)+e.maxOutputTokens*a.outputUsdPerMillionTokens)/1e6;if(!(u>0))throw new M("local_model_charge_unknown","The model must publish an enforceable positive request ceiling.",422);return{model:{...p,configurationHash:y({configuration:p,contextWindow:d,outputLimit:l,pricing:a})},pricing:a,maximumChargeUsd:u}}i(_o,"prepareLocalExperimentModel");function $T(e){let t=e.admission.streamFactory?.(e)??e.admission.stream??e.stream??hn;return async function*(r){if(!r.requestId)throw new M("local_request_identity_missing","Every local model dispatch requires a stable request identity.");let n=e.admission.model;if(r.model!==n.modelId||r.maxTokens!==n.maxOutputTokens||r.temperature!==n.temperature||r.topP!==n.topP)throw new M("local_model_configuration_conflict","The native model request changed its admitted model, output limit or sampling configuration.",422);let o=wr();o?.assertExecution(e.executionId);let s={teamId:e.teamId,id:e.executionId,ownerId:e.ownerId,requestId:r.requestId};await e.store.reserveLocalCharge({...s,caseId:e.caseId,maximumUsd:e.admission.maximumChargeUsd}),r.signal?.aborted&&(await e.store.settleLocalCharge({...s,costUsd:null,usage:null,notDispatched:!0}),r.signal.throwIfAborted());try{await e.store.markLocalChargeDispatched(s.teamId,s.id,s.requestId,s.ownerId)}catch(p){throw o&&await e.store.settleLocalCharge({...s,costUsd:null,usage:null,notDispatched:!0}),p}await e.store.appendLocalExperimentEvent({...s,caseId:e.caseId,type:"model.dispatch",payload:{requestId:s.requestId,model:r.model,messages:r.messages}});let a=null,c=!1,d=!1,l;try{for await(let p of t(r)){d=!0,p.type==="usage"&&(a=p.usage),p.type==="finish"&&(c=!0);let u=p.type==="text_delta"?{requestId:s.requestId,text:p.text}:p.type==="tool_call_delta"?{requestId:s.requestId,toolCalls:p.toolCalls}:p.type==="usage"?{requestId:s.requestId,usage:Ze(p.usage)}:p.type==="finish"?{requestId:s.requestId,finishReason:p.finishReason}:null;u&&await e.store.appendLocalExperimentEvent({...s,caseId:e.caseId,type:`model.${p.type}`,payload:u}),yield p}}catch(p){throw!d&&p instanceof Qt&&p.executionId===s.id&&p.requestId===s.requestId&&(l=p),p}finally{let p=Ze(a),u=e.admission.pricing&&c&&p.promptTokens!==null&&p.completionTokens!==null?nt(a,e.admission.pricing):null;await e.store.settleLocalCharge({...s,costUsd:u,confirmedTransportNotInvoked:l,usage:a===null?null:{promptTokens:p.promptTokens,completionTokens:p.completionTokens,cachedPromptTokens:p.cachedPromptTokens,uncachedPromptTokens:p.uncachedPromptTokens}})}}}i($T,"createLocalBudgetedModelStream");function Gc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}i(Gc,"record");function Kc(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)throw new M("local_model_bound_unknown","The model catalog is missing an enforceable context/output bound.",422);return e}i(Kc,"positive");import{AsyncLocalStorage as xm}from"node:async_hooks";import bm from"node:path";var _c=new xm;function $c(){return _c.getStore()}i($c,"currentAdvancedRefinerBoundary");function dv(e){let t=fi(bm.join(e.storeDir,"library","harnesses","advanced-refiner-paid-calls.sqlite"));t.exec(`CREATE TABLE IF NOT EXISTS advanced_refiner_budgets(id TEXT PRIMARY KEY,actor_id TEXT NOT NULL,team_id TEXT NOT NULL,pin_hash TEXT NOT NULL,maximum_spend REAL NOT NULL,maximum_steps INTEGER NOT NULL,expires_at TEXT NOT NULL);
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{V as Bt,Wa as ar,ab as et,ba as _t,bb as tt,db as at,ib as nr,lb as or,mb as sr,q as Ze,v as er,x as tr}from"./chunk-NHJ26KXF.js";import{a as rr}from"./chunk-EMKZVP7Z.js";import{i as Ya}from"./chunk-VOIH2BQA.js";import{a as Ye}from"./chunk-T5LE6R5S.js";import{f as Za,h as He}from"./chunk-QJRXTIOC.js";import{a as We,b as Sa,c as Ha,d as Ea,e as Aa,f as xa,g as Ga,h as _e,ha as Xa,i as Ka,j as Oe,ka as Xe,pa as Qe,qa as se,ra as Qa}from"./chunk-7MXZJQS7.js";import{g as he}from"./chunk-5CMKGD43.js";import{M as Ja,q as Wa}from"./chunk-HA7EFTPF.js";import{b as Va}from"./chunk-L3KS6MOV.js";import{Ib as Na,N as Be,fc as Ua,jc as Ge,lc as F,mc as Ke,od as Mt}from"./chunk-XDMUD4FW.js";import{$ as Ct,W as Da,Y as Se,Z as Je,ga as Fa,ka as $a,ma as za}from"./chunk-IKWDL3RB.js";import{Ca as qa,Dc as La,Qa as Me,Ta as Tt,xa as ja}from"./chunk-QRWPEW3Z.js";import{E as Ia,K as Pa,N as Ta,V as Ca,X as Ma,j as ba,k as Ve,p as ya}from"./chunk-WV2APYWG.js";import{Ma as Ie,Na as Ra,W as ka}from"./chunk-PJM2G7SG.js";import{B as ma,Ca as wa,D as ua,E as pa,Ma as va,S as fa,p as Le,r as ia,s as da,sa as ha,t as ca,ta as ga,u as la}from"./chunk-SDEDAHV6.js";import{Z as Oa}from"./chunk-DALJMSJG.js";import{L as Ba}from"./chunk-TGIB24K4.js";import{h as sa,k as re,l as fe,m as v}from"./chunk-NNF6KCHD.js";import{b as M}from"./chunk-ES2ISFJC.js";import{n as _a}from"./chunk-H7IWJN7L.js";import{a as h}from"./chunk-FTQLQJQV.js";import{execFile as Wr}from"node:child_process";import{readFile as Jr}from"node:fs/promises";import{promisify as Gr}from"node:util";var Kr=5,Xr=20*1024*1024,ir=4e4,jt=Gr(Wr);function Zn(e){return async({grader:t,task:a,attempt:n})=>{let s=[],o=0,i=await Qr({store:e.store,attempt:n}),d=n.modelRef?.providerId===t.judge.providerId&&n.modelRef.modelId===t.judge.modelId?tr(n.metadata.hostedTokenPricing)??void 0:void 0,g=await e.modelText({model:t.judge,hostedTokenPricing:d,signal:new AbortController().signal,requestId:`task-judge:${n.id}:${t.id}`,onUsage:h((m,r)=>{s.push(m),typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o+=r)},"onUsage"),messages:[{role:"system",content:`Apply this rubric and return JSON only with score (0..1), passed, and feedback.
2
+ import{V as Bt,Wa as ar,ab as et,ba as _t,bb as tt,db as at,ib as nr,lb as or,mb as sr,q as Ze,v as er,x as tr}from"./chunk-TBNBCOW7.js";import{a as rr}from"./chunk-EMKZVP7Z.js";import{i as Ya}from"./chunk-OE2VF6KU.js";import{a as Ye}from"./chunk-T5LE6R5S.js";import{f as Za,h as He}from"./chunk-QJRXTIOC.js";import{a as We,b as Sa,c as Ha,d as Ea,e as Aa,f as xa,g as Ga,h as _e,ha as Xa,i as Ka,j as Oe,ka as Xe,pa as Qe,qa as se,ra as Qa}from"./chunk-7MXZJQS7.js";import{g as he}from"./chunk-5CMKGD43.js";import{M as Ja,q as Wa}from"./chunk-HA7EFTPF.js";import{b as Va}from"./chunk-L3KS6MOV.js";import{Ib as Na,N as Be,fc as Ua,jc as Ge,lc as F,mc as Ke,od as Mt}from"./chunk-XDMUD4FW.js";import{$ as Ct,W as Da,Y as Se,Z as Je,ga as Fa,ka as $a,ma as za}from"./chunk-IKWDL3RB.js";import{Ca as qa,Dc as La,Qa as Me,Ta as Tt,xa as ja}from"./chunk-QRWPEW3Z.js";import{E as Ia,K as Pa,N as Ta,V as Ca,X as Ma,j as ba,k as Ve,p as ya}from"./chunk-WV2APYWG.js";import{Ma as Ie,Na as Ra,W as ka}from"./chunk-PJM2G7SG.js";import{B as ma,Ca as wa,D as ua,E as pa,Ma as va,S as fa,p as Le,r as ia,s as da,sa as ha,t as ca,ta as ga,u as la}from"./chunk-SDEDAHV6.js";import{Z as Oa}from"./chunk-DALJMSJG.js";import{L as Ba}from"./chunk-TGIB24K4.js";import{h as sa,k as re,l as fe,m as v}from"./chunk-NNF6KCHD.js";import{b as M}from"./chunk-ES2ISFJC.js";import{n as _a}from"./chunk-H7IWJN7L.js";import{a as h}from"./chunk-FTQLQJQV.js";import{execFile as Wr}from"node:child_process";import{readFile as Jr}from"node:fs/promises";import{promisify as Gr}from"node:util";var Kr=5,Xr=20*1024*1024,ir=4e4,jt=Gr(Wr);function Zn(e){return async({grader:t,task:a,attempt:n})=>{let s=[],o=0,i=await Qr({store:e.store,attempt:n}),d=n.modelRef?.providerId===t.judge.providerId&&n.modelRef.modelId===t.judge.modelId?tr(n.metadata.hostedTokenPricing)??void 0:void 0,g=await e.modelText({model:t.judge,hostedTokenPricing:d,signal:new AbortController().signal,requestId:`task-judge:${n.id}:${t.id}`,onUsage:h((m,r)=>{s.push(m),typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o+=r)},"onUsage"),messages:[{role:"system",content:`Apply this rubric and return JSON only with score (0..1), passed, and feedback.
3
3
 
4
4
  ${t.rubric}`},{role:"user",content:JSON.stringify({input:a.input,expectedOutput:a.expectedOutput,output:n.output,artifactEvidence:i})}]}),f=ar(g);if(!f)throw new Error("Model judge returned invalid structured output.");return{...f,usage:s,...o>0?{costUsd:o}:{}}}}h(Zn,"createTaskAttemptModelJudge");async function Qr(e){let t=(await e.store.listTaskAttemptArtifacts({attemptId:e.attempt.id})).filter(a=>a.kind==="output_artifact").slice(0,Kr);return Promise.all(t.map(async a=>{let n={artifactId:a.id,mediaType:a.mediaType??null,sha256:a.sha256,sizeBytes:a.sizeBytes,requiredOutputPath:typeof a.metadata.requiredOutputPath=="string"?a.metadata.requiredOutputPath:null};if(a.sizeBytes>Xr)return{...n,extraction:"omitted",reason:"artifact exceeds inspection bound"};try{if(a.mediaType==="application/pdf"){let{stdout:s}=await jt("pdftotext",[a.path,"-"],{env:{...process.env,PATH:_t()},maxBuffer:8388608,timeout:15e3});return{...n,extraction:"pdf_text",content:Ot(s)}}if(Zr(a.mediaType)){let s=await en(a.path,a.mediaType);return{...n,extraction:"open_xml_text",content:Ot(s.content),structure:s.structure}}return Yr(a.mediaType)?{...n,extraction:"text",content:Ot(await Jr(a.path,"utf8"))}:{...n,extraction:"metadata_only"}}catch(s){return{...n,extraction:"unavailable",reason:s instanceof Error?s.message.slice(0,500):String(s).slice(0,500)}}}))}h(Qr,"loadTaskAttemptGraderEvidence");function Yr(e){return!!(e?.startsWith("text/")||e==="application/json"||e==="application/javascript"||e==="application/sql"||e==="application/xml"||e==="application/yaml")}h(Yr,"isTextArtifact");function Zr(e){return e==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||e==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"||e==="application/vnd.openxmlformats-officedocument.presentationml.presentation"}h(Zr,"isOpenXmlArtifact");async function en(e,t){let a={env:{...process.env,PATH:_t()},maxBuffer:16777216,timeout:15e3},{stdout:n}=await jt("unzip",["-Z1",e],a),s=n.split(/\r?\n/).filter(Boolean),o=tn(s,t).slice(0,250),i=[];for(let d of o){let{stdout:g}=await jt("unzip",["-p",e,d],a),f=rn(g);f&&i.push(`[${d}]
5
5
  ${f}`)}return{content:i.join(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as H,f as te,h as ae,i as ie}from"./chunk-VOIH2BQA.js";import{g as se}from"./chunk-QJRXTIOC.js";import{F as re,H as oe}from"./chunk-7K72KS5C.js";import{U as X,ba as Y,ca as Z,ga as ee}from"./chunk-7MXZJQS7.js";import{L as K,da as b}from"./chunk-XDMUD4FW.js";import{Ca as g,Ta as U,pc as Q,xa as P}from"./chunk-QRWPEW3Z.js";import{s as G,t as F,u as T}from"./chunk-WV2APYWG.js";import{Qa as L,na as N,oa as y,qa as W,wa as $}from"./chunk-PJM2G7SG.js";import{Fa as _}from"./chunk-SDEDAHV6.js";import{b as R,c as v,d as J,l as S,m as n,o as j,r as q}from"./chunk-NNF6KCHD.js";import{b as h}from"./chunk-ES2ISFJC.js";import{a as d}from"./chunk-FTQLQJQV.js";import{randomUUID as V,createHash as fe}from"node:crypto";import{mkdtemp as ue,mkdir as pe,writeFile as D,rm as me}from"node:fs/promises";import he from"node:os";import E from"node:path";var ne=d(async e=>{let a=g(e.packageValue);if(e.grader.runtime!=="sandbox_process")throw new Error("Select the sandbox process runtime for a local file grader.");if(!a.taskset.graders.some(r=>n(r)===n(e.grader)))throw new Error("The private grader differs from its package.");if(!a.taskset.tasks.some(r=>n(r)===n(e.task)))throw new Error("The private case differs from its package.");await e.authorize(),e.signal?.throwIfAborted();let i=await ue(E.join(he.tmpdir(),"profile-private-grade-")),t=V();try{for(let f of a.files.filter(l=>l.asset.visibility!=="policy")){let l=f.asset.path;if(E.isAbsolute(l)||l.split(/[\\/]/).some(u=>!u||u==="."||u===".."))throw new Error("Private grader asset path invalid.");let m=E.join(i,"package",l);await pe(E.dirname(m),{recursive:!0,mode:448}),await D(m,P(f),{mode:256})}await D(E.join(i,"request.json"),JSON.stringify({task:e.task,attempt:e.evidence,input:e.task.input,output:e.evidence.output,artifacts:"artifacts"in e.evidence?e.evidence.artifacts:[],expectedOutput:e.task.expectedOutput}),{mode:256});let r=`import fs from 'node:fs/promises'; const module=await import(${JSON.stringify("./package/"+e.grader.verifierRef.path)}); const result=await module[${JSON.stringify(e.grader.exportName??"verify")}](JSON.parse(await fs.readFile('request.json','utf8'))); console.log(JSON.stringify(result));`;await D(E.join(i,"runner.mjs"),r,{mode:256});let s=await ie({authorize:d(async()=>(await e.authorize(),e.signal?.throwIfAborted(),{candidateId:t,candidateRevision:1,ownerId:t,sessionId:t,turnId:t,sourceRoot:i,writablePaths:[]}),"authorize")})({candidateId:t,sessionId:t,turnId:t,expectedRevision:1,command:"/runtime/node --max-old-space-size=512 runner.mjs",timeoutMs:e.grader.timeoutMs,maxOutputBytes:7e4,signal:e.signal});if(await e.authorize(),e.signal?.throwIfAborted(),s.code!==0||s.timedOut||s.stdoutTruncated||s.stderrTruncated)throw new Error("Private grading sandbox did not complete.");return H.parse(JSON.parse(s.stdout))}finally{await me(i,{recursive:!0,force:!0})}},"executeLocalProfileVerifier");function Me(e){return async a=>{if(!a.manifest)throw new Error("The hosted grader requires its admitted manifest.");await a.authorize(),a.signal?.throwIfAborted();let i="artifacts"in a.evidence&&Array.isArray(a.evidence.artifacts)?a.evidence.artifacts.map(({reference:l,title:m,contentType:u})=>({reference:l,title:m,contentType:u})):[],t="caseOwner"in a.evidence?a.evidence.caseOwner:null;if(!t?.sessionId||!t.turnId)throw new Error("The private grader has no sealed case owner.");let r=Buffer.from(JSON.stringify({manifest:a.manifest,packageValue:a.packageValue,graderId:a.grader.id,taskId:a.task.id,evidence:{...a.evidence,artifacts:i}}));if(r.length>2e7)throw new Error("The private grading package exceeds its transport limit.");let o={callId:V(),sessionId:t.sessionId,turnId:t.turnId,sha256:fe("sha256").update(r).digest("hex"),sizeBytes:r.length,timeoutMs:a.grader.timeoutMs},s=d((l,m=12e4)=>e.request(oe.parse({contractVersion:re,requestId:V(),operation:"profile-evaluations/grade",params:l}),m),"request");for(let l=0;l<r.length;l+=98304)await a.authorize(),a.signal?.throwIfAborted(),await s({...o,action:"upload",offset:l,contentsBase64:r.subarray(l,l+98304).toString("base64")});let f=await s({...o,action:"execute"},a.grader.timeoutMs+12e4);return await a.authorize(),a.signal?.throwIfAborted(),H.parse(f)}}d(Me,"createHostedProfileVerifier");async function ge(e,a){let i=g(e);for(let r of i.taskset.graders){if(r.kind==="model_judge"&&(!a||r.calibrationStatus!=="passed"))throw new Error("This Profile requires its current calibrated judge and bounded private provider owner.");let o="verifierRef"in r?r.verifierRef:"rubricRef"in r?r.rubricRef:null;o&&A(i,o)}let t=i.taskset.metrics?.customAggregator;if(t){let r=i.files.find(o=>o.asset.path===t.module);if(!r||r.asset.visibility==="policy"||S(P(r))!==t.contentHash)throw new Error("The authored aggregate metric is not its exact private release.");new TextDecoder("utf8",{fatal:!0}).decode(P(r))}}d(ge,"preflightProfilePrivateGrading");function A(e,a){let i=e.files.find(t=>t.asset.id===a.id);if(!i||i.asset.visibility==="policy"||n(i.asset)!==n(a))throw new Error("The exact private grader asset is unavailable.");return new TextDecoder("utf8",{fatal:!0}).decode(P(i))}d(A,"readPrivate");async function $e(e){let a=g(e.packageValue);if(a.contentHash!==e.manifest.packageHash||a.taskset.contentHash!==e.manifest.tasksetRelease.contentHash)throw new Error("The private grading package changed its frozen Run identity.");await e.authorize(),await ge(a,!!e.executeBudgetedJudge),await e.authorize();let i=d(async({grader:o,task:s,evidence:f})=>{let l=e.signal;await e.authorize(),l?.throwIfAborted();let m={manifest:e.manifest,packageValue:a,grader:o,task:s,evidence:f,signal:l,authorize:e.authorize},u=e.executeSandboxVerifier?await e.executeSandboxVerifier(m):o.runtime==="sandbox_process"?await ne(m):await te({source:A(a,o.verifierRef),exportName:o.exportName,runtime:o.runtime,timeoutMs:o.timeoutMs,signal:l,value:{task:s,attempt:f,input:s.input,output:f.output,artifacts:"artifacts"in f?f.artifacts:[],expectedOutput:s.expectedOutput,infrastructureError:f.infrastructureError??null}});return await e.authorize(),l?.throwIfAborted(),{score:u.score,passed:u.passed,rewardEligible:o.rewardEligible,failureClass:null,feedback:[u.feedback],visibleEvidenceRefs:[],privilegedEvidenceRefs:u.evidenceRefs}},"customVerifier"),t=a.taskset.metrics?.customAggregator,r=t?new TextDecoder("utf8",{fatal:!0}).decode(P(a.files.find(o=>o.asset.path===t.module))):void 0;return{authorize:e.authorize,customVerifier:i,...e.executeBudgetedJudge?{modelJudge:L({readRubric:d(async o=>{await e.authorize();let s=A(a,o);return await e.authorize(),s},"readRubric"),executeBudgeted:d(async(o,s)=>{await e.authorize(),s?.throwIfAborted();let f=await e.executeBudgetedJudge(o,s);return await e.authorize(),s?.throwIfAborted(),f},"executeBudgeted")})}:{},...r!==void 0?{metricSource:r,metricExecutor:d(async o=>{await e.authorize(),o.signal?.throwIfAborted();let s=await ae(o);return await e.authorize(),o.signal?.throwIfAborted(),s},"metricExecutor")}:{}}}d($e,"createProfilePrivateGradingOwner");import{promises as ve}from"node:fs";import ke from"node:path";async function at(e){let a=e.definition.tasksetRelease,i=await se(e.store,e.harnessRelease);if(!i)throw new Error("Evaluation Profile Harness release is unavailable.");let t=await Re({...e,runtime:i});if(t)return t;let r=await e.store.listTasksetRevisions(e.profileId);for(let o of r){if(a.id!==o.id&&a.id!==`taskset-release-${o.id}-r${o.revision}`)continue;let s=await we(e.storeDir,o);if(s.taskset.id===a.id&&s.taskset.contentHash===a.contentHash)return s}throw new Error(`Released Taskset ${a.id} is unavailable in Profile ${e.profileId}.`)}d(at,"loadLocalProfileEvaluationTaskset");async function we(e,a){let i=a.metadata.importedPackageHash;if(typeof i=="string"){let o=await Z(e,i);if(o.taskset.id!==a.id||o.taskset.revision!==a.revision)throw new Error("Imported evaluation Taskset differs from its local Profile revision.");return o}if(U(a)!==a.contentHash)throw new Error("Authored evaluation Taskset differs from its immutable revision.");let t=Q({taskset:a,adapterId:X(a)}),r=await ee({storeDir:e,taskset:a,content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:t.tasksetRelease,environment:t.environmentRelease,verifierSet:t.verifierSetRelease}});return await Y(e,r),r}d(we,"loadCandidate");async function Re(e){let a=e.definition.tasksetRelease,i=e.runtime;if(i.release.harnessRelease.id!==e.harnessRelease.id||i.release.harnessRelease.contentHash!==e.harnessRelease.contentHash)throw new Error("Evaluation Taskset runtime differs from its requested release.");let t=`evals/tasksets/${a.contentHash}.json`,r=i.release.harnessRelease.files.find(o=>o.path===t);if(r){if(r.visibility!=="verifier")throw new Error("Evaluation Taskset package is not verifier-private.");let o=await ve.readFile(ke.join(i.release.bundlePath,"source",...t.split("/")));if(S(o)!==r.contentHash)throw new Error("Released evaluation Taskset package bytes differ from their source receipt.");let s=g(JSON.parse(o.toString("utf8")));if(s.taskset.id!==a.id||s.taskset.contentHash!==a.contentHash)throw new Error("Released evaluation Taskset package differs from its definition.");return s}return null}d(Re,"loadReleasedProfileEvaluationTaskset");function C(e){return{id:W(e),label:"Selected Dataset evaluation",description:"Explicit sealed external Dataset evaluation recipe.",target:e.target,tasksetRelease:{id:e.dataset.id,contentHash:e.dataset.contentHash},split:e.split,taskIds:[...new Set(e.population.map(a=>a.taskId))],seeds:[...new Set(e.population.map(a=>a.seed))],criterion:e.criterion}}d(C,"externalProfileEvaluationDefinition");async function lt(e){let a=e.manifest.profileEvaluation,i=a?.externalDatasetBinding?y(a.externalDatasetBinding):null;if(!i)return null;if(!e.resolveExternalDataset)throw new Error("This owner has no authorized external Dataset resolver.");let t=await e.resolveExternalDataset(i,e.selected);await t.authorize();let r=g(t.packageValue),o=await e.loadCatalog({ref:e.selected.profileRef,sourceRevision:e.selected.sourceRevision,harnessRelease:e.selected.harnessRelease});if(n(t.binding)!==n(i)||i.profileId!==e.selected.profileRef.profileId||i.declaredProfileCatalogHash!==o.catalogHash||r.contentHash!==i.packageHash||n(r.taskset)!==n(e.taskset)||i.environmentHash!==n(r.taskset.environment)||i.privateDatasetClosureHash!==n(r.files.filter(l=>l.asset.visibility!=="policy").map(l=>l.asset)))throw new Error("External Dataset admission changed its actual Profile, package or private closure.");let s=C(i),f={schemaVersion:"openpond.profileEvaluations.v1",definitions:[s],suites:[]};if(T(e.manifest,e.taskset,f),!a||a.catalogHash!==n(f)||a.definitionHash!==n(s)||n(a.target)!==n(i.target))throw new Error("External Dataset manifest changed its derived definition.");return await t.authorize(),{...t,packageValue:r,definition:s,catalog:f}}d(lt,"admitProfileExternalDataset");var Pe=h.object({id:R,createdAt:J,definitionId:R,externalDatasetBinding:N.optional(),profileRef:K.optional(),profileSource:h.object({sourceRevision:h.string().min(1).max(500),harnessRelease:h.object({id:R,contentHash:v}).strict()}).strict().optional(),modelRef:q,hostModelConfigurationHash:v.optional(),hostArtifactHash:v.optional(),maximumSpendUsd:h.number().positive().max(1e4).optional(),expectedManifestHash:v.optional(),hostExperiment:h.object({definition:h.object({id:R,revision:h.number().int().positive(),contentHash:v}).strict().nullable(),configurationHash:v,project:h.object({id:R,revision:h.number().int().positive(),contentHash:v,targetId:R.nullable()}).strict().optional()}).strict().optional()}).strict();function vt(e){return async(a,i)=>{let t=Pe.parse(a);if(i?.requireExpectedManifestHash&&!t.expectedManifestHash)throw new Error("Profile evaluation execution requires the reviewed manifest hash.");if(t.profileSource&&!t.profileRef)throw new Error("An exact Profile source requires its accepted Profile reference.");let r=i?.selectedWorkflows??await e.selectedWorkflows(t.profileRef,t.profileSource);if(t.profileRef&&n(t.profileRef)!==n(r.profileRef))throw new Error("Profile preparation did not resolve the explicitly selected Profile.");if(t.profileSource&&(r.sourceRevision!==t.profileSource.sourceRevision||n(r.harnessRelease)!==n(t.profileSource.harnessRelease)))throw new Error("Profile preparation changed its explicitly pinned source.");let o=t.externalDatasetBinding?y(t.externalDatasetBinding):null,s=o?await(e.resolveExternalDataset?e.resolveExternalDataset(o,r):Promise.reject(new Error("This host has not qualified external Dataset Profile execution."))):null;if(s&&(await s.authorize(),n(y(s.binding))!==n(o)))throw new Error("External Dataset admission differs from the actual authorized recipe.");let f=await e.loadCatalog({ref:r.profileRef,sourceRevision:r.sourceRevision,harnessRelease:r.harnessRelease});if(o&&o.declaredProfileCatalogHash!==f.catalogHash)throw new Error("The original Profile verifier catalog changed.");let l=o?C(o):null;if(l&&t.definitionId!==l.id)throw new Error("Use the external recipe's own definition identity.");let m={schemaVersion:"openpond.profileEvaluations.v1",definitions:l?[l]:f.definitions,suites:l?[]:f.suites},u=l??f.definitions.find(c=>c.id===t.definitionId);if(!u)throw new Error(`Evaluation ${t.definitionId} is absent from the selected Profile release.`);let k=u.target,z=k.kind==="workflow"?r.workflows.find(c=>c.binding.workflowId===k.workflowId)?.binding:_.parse({schemaVersion:"openpond.profileComponentBinding.v1",profileId:r.profileRef.profileId,sourceRevision:r.sourceRevision,harnessRelease:r.harnessRelease,target:k});if(!z)throw new Error(`Evaluation workflow ${k.kind==="workflow"?k.workflowId:""} is absent from the selected Profile release.`);let w=g(s?.packageValue??await e.loadTasksetPackage(u,r.profileRef.profileId,r.harnessRelease)),p=w.taskset;if(p.id!==u.tasksetRelease.id||p.contentHash!==u.tasksetRelease.contentHash)throw new Error("Evaluation Taskset package differs from its released definition.");let le=p.environment.kind==="text"&&p.tools.length===0,M=p.environment.kind==="work"&&p.environment.entrypoint==="openpond-work-v1"&&p.tools.every(c=>["work_exec","work_save_output"].includes(c.name));if(!le&&!M)throw new Error("Profile evaluation supports text cases or Work cases with the built-in execution and output tools.");if(t.maximumSpendUsd!==void 0&&M&&!e.boundedWorkComputeAvailable)throw new Error("This host has not admitted budgeted Work compute.");if(p.tasks.some(c=>c.artifactRefs.length>b.maxAttachments||c.artifactRefs.some(x=>x.visibility!=="policy"||x.mediaType!=="application/pdf"||x.sizeBytes>b.maxAttachmentBytes)))throw new Error("Profile evaluation accepts only bounded policy-visible PDF task attachments.");if(!o&&!e.privateGradingPreflight&&(p.graders.some(c=>c.kind==="model_judge"||c.kind==="custom_verifier")||p.metrics?.aggregation==="custom"))throw new Error("Profile evaluation cannot run this Taskset's model judge, custom verifier, or custom metric in the current app-server runtime.");await e.privateGradingPreflight?.(w);let B={adapterId:k.kind==="workflow"?"openpond.profile-workflow":"openpond.profile-component",placement:e.placement,runtimeVersion:"app-server-v1",capabilityReceipt:n({adapterId:k.kind==="workflow"?"openpond.profile-workflow":"openpond.profile-component",packageHash:w.contentHash,connectedAppScopes:p.policy.connectedAppScopes})},ce={...$({catalog:m,definitionId:u.id,profileId:r.profileRef.profileId,sourceRevision:r.sourceRevision,harnessRelease:r.harnessRelease,environmentHash:n({packageHash:w.contentHash,runtimeTarget:B})}),...o?{externalDatasetBinding:o}:{},...e.sourceCandidate?{sourceCandidate:e.sourceCandidate}:{}};if(o&&(o.packageHash!==w.contentHash||o.environmentHash!==n(p.environment)||o.privateDatasetClosureHash!==n(w.files.filter(c=>c.asset.visibility!=="policy").map(c=>c.asset))))throw new Error("External Dataset package/environment/private closure changed.");let de=j.parse({provider:t.modelRef.providerId,model:t.modelRef.modelId,revision:null,artifactHash:t.hostArtifactHash??null,tokenizerRevision:null,chatTemplateHash:null}),O=await e.modelConfigurationHash(t.modelRef,t),I=G({schemaVersion:"openpond.tasksetRunManifest.v1",id:t.id,tasksetRelease:u.tasksetRelease,packageHash:w.contentHash,execution:{kind:"harness",harnessRelease:r.harnessRelease},profileEvaluation:ce,policy:{kind:"model",model:de,configurationHash:O},gradingRole:"evaluation",metricPolicy:F(p),population:o?o.population.map(c=>({...c,receiptId:`evaluation-${n([t.id,c.taskId,c.seed,c.fixtureId]).slice(0,32)}`})):u.taskIds.flatMap(c=>u.seeds.map(x=>({receiptId:`evaluation-${n([t.id,c,x]).slice(0,32)}`,taskId:c,seed:x,fixtureId:null}))),runtimeTarget:B,limits:{maxTurns:128,timeoutMs:p.environment.defaultTimeoutMs,maxOutputBytes:25e7,maximumSpendUsd:t.maximumSpendUsd??null},createdAt:t.createdAt,metadata:{sourceTasksetId:p.metadata.sourceTasksetId??p.id,...r.profileRef.source==="openpond_git"?{profileRepositoryId:r.profileRef.repositoryId}:{},...t.hostExperiment?{experimentDefinition:t.hostExperiment.definition,experimentConfigurationHash:t.hostExperiment.configurationHash,...t.hostExperiment.project?{project:t.hostExperiment.project}:{}}:{}}});if(T(I,p,m),s&&await s.authorize(),t.expectedManifestHash&&I.contentHash!==t.expectedManifestHash)throw new Error("Profile evaluation setup changed since preview; prepare the run again.");return{manifest:I,taskset:p,profileRef:r.profileRef,binding:z,modelRef:t.modelRef,modelConfigurationHash:O}}}d(vt,"createProfileEvaluationRunPreparationService");export{ne as a,Me as b,ge as c,$e as d,at as e,Re as f,lt as g,vt as h};
2
+ import{a as H,f as te,h as ae,i as ie}from"./chunk-OE2VF6KU.js";import{g as se}from"./chunk-QJRXTIOC.js";import{F as re,H as oe}from"./chunk-7K72KS5C.js";import{U as X,ba as Y,ca as Z,ga as ee}from"./chunk-7MXZJQS7.js";import{L as K,da as b}from"./chunk-XDMUD4FW.js";import{Ca as g,Ta as U,pc as Q,xa as P}from"./chunk-QRWPEW3Z.js";import{s as G,t as F,u as T}from"./chunk-WV2APYWG.js";import{Qa as L,na as N,oa as y,qa as W,wa as $}from"./chunk-PJM2G7SG.js";import{Fa as _}from"./chunk-SDEDAHV6.js";import{b as R,c as v,d as J,l as S,m as n,o as j,r as q}from"./chunk-NNF6KCHD.js";import{b as h}from"./chunk-ES2ISFJC.js";import{a as d}from"./chunk-FTQLQJQV.js";import{randomUUID as V,createHash as fe}from"node:crypto";import{mkdtemp as ue,mkdir as pe,writeFile as D,rm as me}from"node:fs/promises";import he from"node:os";import E from"node:path";var ne=d(async e=>{let a=g(e.packageValue);if(e.grader.runtime!=="sandbox_process")throw new Error("Select the sandbox process runtime for a local file grader.");if(!a.taskset.graders.some(r=>n(r)===n(e.grader)))throw new Error("The private grader differs from its package.");if(!a.taskset.tasks.some(r=>n(r)===n(e.task)))throw new Error("The private case differs from its package.");await e.authorize(),e.signal?.throwIfAborted();let i=await ue(E.join(he.tmpdir(),"profile-private-grade-")),t=V();try{for(let f of a.files.filter(l=>l.asset.visibility!=="policy")){let l=f.asset.path;if(E.isAbsolute(l)||l.split(/[\\/]/).some(u=>!u||u==="."||u===".."))throw new Error("Private grader asset path invalid.");let m=E.join(i,"package",l);await pe(E.dirname(m),{recursive:!0,mode:448}),await D(m,P(f),{mode:256})}await D(E.join(i,"request.json"),JSON.stringify({task:e.task,attempt:e.evidence,input:e.task.input,output:e.evidence.output,artifacts:"artifacts"in e.evidence?e.evidence.artifacts:[],expectedOutput:e.task.expectedOutput}),{mode:256});let r=`import fs from 'node:fs/promises'; const module=await import(${JSON.stringify("./package/"+e.grader.verifierRef.path)}); const result=await module[${JSON.stringify(e.grader.exportName??"verify")}](JSON.parse(await fs.readFile('request.json','utf8'))); console.log(JSON.stringify(result));`;await D(E.join(i,"runner.mjs"),r,{mode:256});let s=await ie({authorize:d(async()=>(await e.authorize(),e.signal?.throwIfAborted(),{candidateId:t,candidateRevision:1,ownerId:t,sessionId:t,turnId:t,sourceRoot:i,writablePaths:[]}),"authorize")})({candidateId:t,sessionId:t,turnId:t,expectedRevision:1,command:"/runtime/node --max-old-space-size=512 runner.mjs",timeoutMs:e.grader.timeoutMs,maxOutputBytes:7e4,signal:e.signal});if(await e.authorize(),e.signal?.throwIfAborted(),s.code!==0||s.timedOut||s.stdoutTruncated||s.stderrTruncated)throw new Error("Private grading sandbox did not complete.");return H.parse(JSON.parse(s.stdout))}finally{await me(i,{recursive:!0,force:!0})}},"executeLocalProfileVerifier");function Me(e){return async a=>{if(!a.manifest)throw new Error("The hosted grader requires its admitted manifest.");await a.authorize(),a.signal?.throwIfAborted();let i="artifacts"in a.evidence&&Array.isArray(a.evidence.artifacts)?a.evidence.artifacts.map(({reference:l,title:m,contentType:u})=>({reference:l,title:m,contentType:u})):[],t="caseOwner"in a.evidence?a.evidence.caseOwner:null;if(!t?.sessionId||!t.turnId)throw new Error("The private grader has no sealed case owner.");let r=Buffer.from(JSON.stringify({manifest:a.manifest,packageValue:a.packageValue,graderId:a.grader.id,taskId:a.task.id,evidence:{...a.evidence,artifacts:i}}));if(r.length>2e7)throw new Error("The private grading package exceeds its transport limit.");let o={callId:V(),sessionId:t.sessionId,turnId:t.turnId,sha256:fe("sha256").update(r).digest("hex"),sizeBytes:r.length,timeoutMs:a.grader.timeoutMs},s=d((l,m=12e4)=>e.request(oe.parse({contractVersion:re,requestId:V(),operation:"profile-evaluations/grade",params:l}),m),"request");for(let l=0;l<r.length;l+=98304)await a.authorize(),a.signal?.throwIfAborted(),await s({...o,action:"upload",offset:l,contentsBase64:r.subarray(l,l+98304).toString("base64")});let f=await s({...o,action:"execute"},a.grader.timeoutMs+12e4);return await a.authorize(),a.signal?.throwIfAborted(),H.parse(f)}}d(Me,"createHostedProfileVerifier");async function ge(e,a){let i=g(e);for(let r of i.taskset.graders){if(r.kind==="model_judge"&&(!a||r.calibrationStatus!=="passed"))throw new Error("This Profile requires its current calibrated judge and bounded private provider owner.");let o="verifierRef"in r?r.verifierRef:"rubricRef"in r?r.rubricRef:null;o&&A(i,o)}let t=i.taskset.metrics?.customAggregator;if(t){let r=i.files.find(o=>o.asset.path===t.module);if(!r||r.asset.visibility==="policy"||S(P(r))!==t.contentHash)throw new Error("The authored aggregate metric is not its exact private release.");new TextDecoder("utf8",{fatal:!0}).decode(P(r))}}d(ge,"preflightProfilePrivateGrading");function A(e,a){let i=e.files.find(t=>t.asset.id===a.id);if(!i||i.asset.visibility==="policy"||n(i.asset)!==n(a))throw new Error("The exact private grader asset is unavailable.");return new TextDecoder("utf8",{fatal:!0}).decode(P(i))}d(A,"readPrivate");async function $e(e){let a=g(e.packageValue);if(a.contentHash!==e.manifest.packageHash||a.taskset.contentHash!==e.manifest.tasksetRelease.contentHash)throw new Error("The private grading package changed its frozen Run identity.");await e.authorize(),await ge(a,!!e.executeBudgetedJudge),await e.authorize();let i=d(async({grader:o,task:s,evidence:f})=>{let l=e.signal;await e.authorize(),l?.throwIfAborted();let m={manifest:e.manifest,packageValue:a,grader:o,task:s,evidence:f,signal:l,authorize:e.authorize},u=e.executeSandboxVerifier?await e.executeSandboxVerifier(m):o.runtime==="sandbox_process"?await ne(m):await te({source:A(a,o.verifierRef),exportName:o.exportName,runtime:o.runtime,timeoutMs:o.timeoutMs,signal:l,value:{task:s,attempt:f,input:s.input,output:f.output,artifacts:"artifacts"in f?f.artifacts:[],expectedOutput:s.expectedOutput,infrastructureError:f.infrastructureError??null}});return await e.authorize(),l?.throwIfAborted(),{score:u.score,passed:u.passed,rewardEligible:o.rewardEligible,failureClass:null,feedback:[u.feedback],visibleEvidenceRefs:[],privilegedEvidenceRefs:u.evidenceRefs}},"customVerifier"),t=a.taskset.metrics?.customAggregator,r=t?new TextDecoder("utf8",{fatal:!0}).decode(P(a.files.find(o=>o.asset.path===t.module))):void 0;return{authorize:e.authorize,customVerifier:i,...e.executeBudgetedJudge?{modelJudge:L({readRubric:d(async o=>{await e.authorize();let s=A(a,o);return await e.authorize(),s},"readRubric"),executeBudgeted:d(async(o,s)=>{await e.authorize(),s?.throwIfAborted();let f=await e.executeBudgetedJudge(o,s);return await e.authorize(),s?.throwIfAborted(),f},"executeBudgeted")})}:{},...r!==void 0?{metricSource:r,metricExecutor:d(async o=>{await e.authorize(),o.signal?.throwIfAborted();let s=await ae(o);return await e.authorize(),o.signal?.throwIfAborted(),s},"metricExecutor")}:{}}}d($e,"createProfilePrivateGradingOwner");import{promises as ve}from"node:fs";import ke from"node:path";async function at(e){let a=e.definition.tasksetRelease,i=await se(e.store,e.harnessRelease);if(!i)throw new Error("Evaluation Profile Harness release is unavailable.");let t=await Re({...e,runtime:i});if(t)return t;let r=await e.store.listTasksetRevisions(e.profileId);for(let o of r){if(a.id!==o.id&&a.id!==`taskset-release-${o.id}-r${o.revision}`)continue;let s=await we(e.storeDir,o);if(s.taskset.id===a.id&&s.taskset.contentHash===a.contentHash)return s}throw new Error(`Released Taskset ${a.id} is unavailable in Profile ${e.profileId}.`)}d(at,"loadLocalProfileEvaluationTaskset");async function we(e,a){let i=a.metadata.importedPackageHash;if(typeof i=="string"){let o=await Z(e,i);if(o.taskset.id!==a.id||o.taskset.revision!==a.revision)throw new Error("Imported evaluation Taskset differs from its local Profile revision.");return o}if(U(a)!==a.contentHash)throw new Error("Authored evaluation Taskset differs from its immutable revision.");let t=Q({taskset:a,adapterId:X(a)}),r=await ee({storeDir:e,taskset:a,content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:t.tasksetRelease,environment:t.environmentRelease,verifierSet:t.verifierSetRelease}});return await Y(e,r),r}d(we,"loadCandidate");async function Re(e){let a=e.definition.tasksetRelease,i=e.runtime;if(i.release.harnessRelease.id!==e.harnessRelease.id||i.release.harnessRelease.contentHash!==e.harnessRelease.contentHash)throw new Error("Evaluation Taskset runtime differs from its requested release.");let t=`evals/tasksets/${a.contentHash}.json`,r=i.release.harnessRelease.files.find(o=>o.path===t);if(r){if(r.visibility!=="verifier")throw new Error("Evaluation Taskset package is not verifier-private.");let o=await ve.readFile(ke.join(i.release.bundlePath,"source",...t.split("/")));if(S(o)!==r.contentHash)throw new Error("Released evaluation Taskset package bytes differ from their source receipt.");let s=g(JSON.parse(o.toString("utf8")));if(s.taskset.id!==a.id||s.taskset.contentHash!==a.contentHash)throw new Error("Released evaluation Taskset package differs from its definition.");return s}return null}d(Re,"loadReleasedProfileEvaluationTaskset");function C(e){return{id:W(e),label:"Selected Dataset evaluation",description:"Explicit sealed external Dataset evaluation recipe.",target:e.target,tasksetRelease:{id:e.dataset.id,contentHash:e.dataset.contentHash},split:e.split,taskIds:[...new Set(e.population.map(a=>a.taskId))],seeds:[...new Set(e.population.map(a=>a.seed))],criterion:e.criterion}}d(C,"externalProfileEvaluationDefinition");async function lt(e){let a=e.manifest.profileEvaluation,i=a?.externalDatasetBinding?y(a.externalDatasetBinding):null;if(!i)return null;if(!e.resolveExternalDataset)throw new Error("This owner has no authorized external Dataset resolver.");let t=await e.resolveExternalDataset(i,e.selected);await t.authorize();let r=g(t.packageValue),o=await e.loadCatalog({ref:e.selected.profileRef,sourceRevision:e.selected.sourceRevision,harnessRelease:e.selected.harnessRelease});if(n(t.binding)!==n(i)||i.profileId!==e.selected.profileRef.profileId||i.declaredProfileCatalogHash!==o.catalogHash||r.contentHash!==i.packageHash||n(r.taskset)!==n(e.taskset)||i.environmentHash!==n(r.taskset.environment)||i.privateDatasetClosureHash!==n(r.files.filter(l=>l.asset.visibility!=="policy").map(l=>l.asset)))throw new Error("External Dataset admission changed its actual Profile, package or private closure.");let s=C(i),f={schemaVersion:"openpond.profileEvaluations.v1",definitions:[s],suites:[]};if(T(e.manifest,e.taskset,f),!a||a.catalogHash!==n(f)||a.definitionHash!==n(s)||n(a.target)!==n(i.target))throw new Error("External Dataset manifest changed its derived definition.");return await t.authorize(),{...t,packageValue:r,definition:s,catalog:f}}d(lt,"admitProfileExternalDataset");var Pe=h.object({id:R,createdAt:J,definitionId:R,externalDatasetBinding:N.optional(),profileRef:K.optional(),profileSource:h.object({sourceRevision:h.string().min(1).max(500),harnessRelease:h.object({id:R,contentHash:v}).strict()}).strict().optional(),modelRef:q,hostModelConfigurationHash:v.optional(),hostArtifactHash:v.optional(),maximumSpendUsd:h.number().positive().max(1e4).optional(),expectedManifestHash:v.optional(),hostExperiment:h.object({definition:h.object({id:R,revision:h.number().int().positive(),contentHash:v}).strict().nullable(),configurationHash:v,project:h.object({id:R,revision:h.number().int().positive(),contentHash:v,targetId:R.nullable()}).strict().optional()}).strict().optional()}).strict();function vt(e){return async(a,i)=>{let t=Pe.parse(a);if(i?.requireExpectedManifestHash&&!t.expectedManifestHash)throw new Error("Profile evaluation execution requires the reviewed manifest hash.");if(t.profileSource&&!t.profileRef)throw new Error("An exact Profile source requires its accepted Profile reference.");let r=i?.selectedWorkflows??await e.selectedWorkflows(t.profileRef,t.profileSource);if(t.profileRef&&n(t.profileRef)!==n(r.profileRef))throw new Error("Profile preparation did not resolve the explicitly selected Profile.");if(t.profileSource&&(r.sourceRevision!==t.profileSource.sourceRevision||n(r.harnessRelease)!==n(t.profileSource.harnessRelease)))throw new Error("Profile preparation changed its explicitly pinned source.");let o=t.externalDatasetBinding?y(t.externalDatasetBinding):null,s=o?await(e.resolveExternalDataset?e.resolveExternalDataset(o,r):Promise.reject(new Error("This host has not qualified external Dataset Profile execution."))):null;if(s&&(await s.authorize(),n(y(s.binding))!==n(o)))throw new Error("External Dataset admission differs from the actual authorized recipe.");let f=await e.loadCatalog({ref:r.profileRef,sourceRevision:r.sourceRevision,harnessRelease:r.harnessRelease});if(o&&o.declaredProfileCatalogHash!==f.catalogHash)throw new Error("The original Profile verifier catalog changed.");let l=o?C(o):null;if(l&&t.definitionId!==l.id)throw new Error("Use the external recipe's own definition identity.");let m={schemaVersion:"openpond.profileEvaluations.v1",definitions:l?[l]:f.definitions,suites:l?[]:f.suites},u=l??f.definitions.find(c=>c.id===t.definitionId);if(!u)throw new Error(`Evaluation ${t.definitionId} is absent from the selected Profile release.`);let k=u.target,z=k.kind==="workflow"?r.workflows.find(c=>c.binding.workflowId===k.workflowId)?.binding:_.parse({schemaVersion:"openpond.profileComponentBinding.v1",profileId:r.profileRef.profileId,sourceRevision:r.sourceRevision,harnessRelease:r.harnessRelease,target:k});if(!z)throw new Error(`Evaluation workflow ${k.kind==="workflow"?k.workflowId:""} is absent from the selected Profile release.`);let w=g(s?.packageValue??await e.loadTasksetPackage(u,r.profileRef.profileId,r.harnessRelease)),p=w.taskset;if(p.id!==u.tasksetRelease.id||p.contentHash!==u.tasksetRelease.contentHash)throw new Error("Evaluation Taskset package differs from its released definition.");let le=p.environment.kind==="text"&&p.tools.length===0,M=p.environment.kind==="work"&&p.environment.entrypoint==="openpond-work-v1"&&p.tools.every(c=>["work_exec","work_save_output"].includes(c.name));if(!le&&!M)throw new Error("Profile evaluation supports text cases or Work cases with the built-in execution and output tools.");if(t.maximumSpendUsd!==void 0&&M&&!e.boundedWorkComputeAvailable)throw new Error("This host has not admitted budgeted Work compute.");if(p.tasks.some(c=>c.artifactRefs.length>b.maxAttachments||c.artifactRefs.some(x=>x.visibility!=="policy"||x.mediaType!=="application/pdf"||x.sizeBytes>b.maxAttachmentBytes)))throw new Error("Profile evaluation accepts only bounded policy-visible PDF task attachments.");if(!o&&!e.privateGradingPreflight&&(p.graders.some(c=>c.kind==="model_judge"||c.kind==="custom_verifier")||p.metrics?.aggregation==="custom"))throw new Error("Profile evaluation cannot run this Taskset's model judge, custom verifier, or custom metric in the current app-server runtime.");await e.privateGradingPreflight?.(w);let B={adapterId:k.kind==="workflow"?"openpond.profile-workflow":"openpond.profile-component",placement:e.placement,runtimeVersion:"app-server-v1",capabilityReceipt:n({adapterId:k.kind==="workflow"?"openpond.profile-workflow":"openpond.profile-component",packageHash:w.contentHash,connectedAppScopes:p.policy.connectedAppScopes})},ce={...$({catalog:m,definitionId:u.id,profileId:r.profileRef.profileId,sourceRevision:r.sourceRevision,harnessRelease:r.harnessRelease,environmentHash:n({packageHash:w.contentHash,runtimeTarget:B})}),...o?{externalDatasetBinding:o}:{},...e.sourceCandidate?{sourceCandidate:e.sourceCandidate}:{}};if(o&&(o.packageHash!==w.contentHash||o.environmentHash!==n(p.environment)||o.privateDatasetClosureHash!==n(w.files.filter(c=>c.asset.visibility!=="policy").map(c=>c.asset))))throw new Error("External Dataset package/environment/private closure changed.");let de=j.parse({provider:t.modelRef.providerId,model:t.modelRef.modelId,revision:null,artifactHash:t.hostArtifactHash??null,tokenizerRevision:null,chatTemplateHash:null}),O=await e.modelConfigurationHash(t.modelRef,t),I=G({schemaVersion:"openpond.tasksetRunManifest.v1",id:t.id,tasksetRelease:u.tasksetRelease,packageHash:w.contentHash,execution:{kind:"harness",harnessRelease:r.harnessRelease},profileEvaluation:ce,policy:{kind:"model",model:de,configurationHash:O},gradingRole:"evaluation",metricPolicy:F(p),population:o?o.population.map(c=>({...c,receiptId:`evaluation-${n([t.id,c.taskId,c.seed,c.fixtureId]).slice(0,32)}`})):u.taskIds.flatMap(c=>u.seeds.map(x=>({receiptId:`evaluation-${n([t.id,c,x]).slice(0,32)}`,taskId:c,seed:x,fixtureId:null}))),runtimeTarget:B,limits:{maxTurns:128,timeoutMs:p.environment.defaultTimeoutMs,maxOutputBytes:25e7,maximumSpendUsd:t.maximumSpendUsd??null},createdAt:t.createdAt,metadata:{sourceTasksetId:p.metadata.sourceTasksetId??p.id,...r.profileRef.source==="openpond_git"?{profileRepositoryId:r.profileRef.repositoryId}:{},...t.hostExperiment?{experimentDefinition:t.hostExperiment.definition,experimentConfigurationHash:t.hostExperiment.configurationHash,...t.hostExperiment.project?{project:t.hostExperiment.project}:{}}:{}}});if(T(I,p,m),s&&await s.authorize(),t.expectedManifestHash&&I.contentHash!==t.expectedManifestHash)throw new Error("Profile evaluation setup changed since preview; prepare the run again.");return{manifest:I,taskset:p,profileRef:r.profileRef,binding:z,modelRef:t.modelRef,modelConfigurationHash:O}}}d(vt,"createProfileEvaluationRunPreparationService");export{ne as a,Me as b,ge as c,$e as d,at as e,Re as f,lt as g,vt as h};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as Ie,b as ye,c as Re,d as He,e as Ee,f as Pe,h as B,i as Ae,j as je}from"./chunk-TIUSKRBP.js";import{e as Ce,f as U}from"./chunk-IOQUF34U.js";import{V as be,Va as Se,W as ke,hb as xe,jb as Te,n as we,nb as G,o as ve,ob as De,pb as ze}from"./chunk-NHJ26KXF.js";import"./chunk-EMKZVP7Z.js";import"./chunk-DLZP22WV.js";import{k as ge}from"./chunk-VOIH2BQA.js";import{a as z}from"./chunk-T5LE6R5S.js";import"./chunk-QJRXTIOC.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{h as me,ma as fe,qa as D,ra as he}from"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-2ZJJFBIA.js";import"./chunk-5CMKGD43.js";import{M as W}from"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import{Da as de,Ea as ce,M as C,N as $,a as se,lc as pe}from"./chunk-XDMUD4FW.js";import{aa as le,ga as V,ia as ue}from"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import{Ca as ie,za as ae}from"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import{B as re,C as oe,E as ne}from"./chunk-WV2APYWG.js";import{Ma as M}from"./chunk-PJM2G7SG.js";import{L as Y,P as ee,sa as te}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{l as J,m as R,r as X}from"./chunk-NNF6KCHD.js";import{b as e}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{promises as $e}from"node:fs";import Ue from"node:path";import Le from"node:http";var Q=e.object({socketPath:e.string().min(1).max(1e3),capability:e.string().regex(/^[a-f0-9]{64}$/),jobId:e.string().min(1),pinHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),Ne=e.object({jobId:e.string().min(1),pinHash:e.string().regex(/^[a-f0-9]{64}$/),requestId:e.string().min(1).max(500),model:X,reasoningEffort:e.enum(["off","low","medium","high","xhigh","max","none"]).nullable(),messages:e.array(e.unknown()).min(1).max(1e3),tools:e.array(e.unknown()).max(100),toolChoice:e.unknown(),maxOutputTokens:e.number().int().positive().max(131072),temperature:e.number().finite().optional(),topP:e.number().finite().optional(),seed:e.number().int().optional()}).strict(),Je=e.discriminatedUnion("kind",[e.object({kind:e.literal("chat_completions_reasoning"),reasoningContent:e.string()}).strict(),e.object({kind:e.literal("responses_reasoning_items"),items:e.array(e.record(e.string(),e.unknown()))}).strict()]),Ve=e.object({id:e.string().optional(),type:e.string(),function:e.object({name:e.string().optional(),arguments:e.string().optional()}).passthrough().optional()}).passthrough(),Ge=e.object({text:e.string().optional(),usage:e.unknown().optional(),costUsd:e.number().finite().nonnegative().optional(),continuation:Je.optional(),toolCalls:e.array(Ve).optional()}).strict();function qe(s,r){let t=Q.parse(s);async function n(u,v,I=r){I.throwIfAborted();let x=Buffer.from(JSON.stringify({action:u,jobId:t.jobId,pinHash:t.pinHash,value:v}));if(x.length>8*1024*1024)throw new Error("Hosted advanced request exceeds its private byte limit.");return new Promise((y,h)=>{let l=Le.request({socketPath:t.socketPath,path:"/",method:"POST",headers:{authorization:`Bearer ${t.capability}`,"content-type":"application/json","content-length":x.length},signal:I},H=>{let E=[],P=0;H.on("data",w=>{if(P+=w.length,P>8388608){H.destroy(new Error("Hosted advanced response exceeds its private byte limit."));return}E.push(w)}),H.on("error",h),H.on("end",()=>{try{let w=JSON.parse(Buffer.concat(E).toString("utf8"));if(H.statusCode!==200)throw new Error(typeof w?.error=="string"?w.error:"The actual hosted advanced owner refused this operation.");y(w)}catch(w){h(w)}})});l.on("error",h),l.end(x)})}i(n,"call");let d=i(async function*(u){let v=Ne.parse({jobId:t.jobId,pinHash:t.pinHash,requestId:u.requestId,model:u.model,reasoningEffort:u.reasoningEffort,messages:u.messages,tools:u.tools,toolChoice:u.toolChoice,maxOutputTokens:u.maxOutputTokens??4096,...u.temperature===void 0?{}:{temperature:u.temperature},...u.topP===void 0?{}:{topP:u.topP},...u.seed===void 0?{}:{seed:u.seed}}),I=e.object({deltas:e.array(Ge).max(1e5)}).strict().parse(await n("model",v,AbortSignal.any([r,u.signal])));for(let x of I.deltas)yield x},"stream");return{stream:d,text:i(async u=>{let v="";for await(let I of d({...u,reasoningEffort:u.reasoningEffort??null,tools:[],toolChoice:"none"}))I.text&&(v+=I.text),I.usage!==void 0&&u.onUsage?.(I.usage,I.costUsd);return v},"text"),authorize:i(async()=>{await n("authorize",{})},"authorize"),ceiling:i(async(u,v,I)=>e.object({configurationHash:e.string().regex(/^[a-f0-9]{64}$/),maximumChargeUsd:e.number().finite().positive()}).strict().parse(await n("ceiling",{modelId:u,pricing:v,maximumOutputTokens:I})),"ceiling"),compute:i((u,v=!1)=>n("compute",u,v?AbortSignal.timeout(6e4):r),"compute"),checkpoint:i(u=>n("checkpoint",u),"checkpoint")}}i(qe,"createHostedAdvancedModelBridge");import Qe from"node:path";var Me=e.string().regex(/^[a-f0-9]{64}$/),Ke=e.object({taskId:e.string().min(1),caseHash:Me,session:C,turn:$,events:e.array(se).max(1e4),traceHash:Me,output:e.string().nullable()}).strict(),K=e.object({packageValue:ae,contexts:e.array(Ke).max(1e4)}).strict();async function _e(s){let r=V(s.pin),t=K.parse(s.privateSource),n=ie(t.packageValue),d=M(e.object({manifest:e.unknown(),result:e.unknown()}).parse(s.evidence));async function m(){if(await s.authorize(),r.actorId!==s.actor.actorId||r.teamId!==s.actor.teamId||r.profileRef.source!=="openpond_git"||r.profileRef.repositoryId!==s.source.repositoryId||r.profileRef.profileId!==s.source.profileId||r.sourceRevision!==s.source.sourceRevision)throw new Error("The actual hosted advanced source owner changed.")}if(i(m,"authorize"),await m(),d.manifest.teamId!==r.teamId||d.result.status!=="completed"||d.manifest.id!==r.evidence.id||d.result.contentHash!==r.evidence.contentHash||R(d.manifest.dataset)!==R(r.externalDatasetBinding.dataset))throw new Error("The exact completed hosted advanced evidence changed.");if(n.contentHash!==r.externalDatasetBinding.packageHash||n.contentHash!==r.adaptationDatasetBinding.packageHash||n.environment.contentHash!==r.environmentPolicy.environmentHash||n.environment.contract.networkPolicy!=="none")throw new Error("The hosted advanced environment/package is not the exact reviewed closed-network release.");if(n.taskset.tools.some(l=>l.name==="web_search"||l.name==="web_fetch"))throw new Error("Live external tools require their own qualified frozen-observation and budget owner.");if(n.verifierSet.graders.some(l=>l.kind==="human"||l.kind==="model_judge"&&l.calibrationStatus!=="passed"))throw new Error("Advanced hosted evaluation needs executable, qualified independent graders.");let u=r.adaptationTaskIds.map(l=>n.taskset.tasks.find(H=>H.id===l)),v=r.holdoutTaskIds.map(l=>n.taskset.tasks.find(H=>H.id===l)),I=new Set(u.map(l=>l?.clusterKey));if(u.some(l=>!l||l.split!==r.adaptationSplit)||v.some(l=>!l||l.split!==r.holdoutSplit||I.has(l.clusterKey)))throw new Error("Hosted adaptation/holdout membership or independent families changed.");let x=await s.store.getHarnessReleaseRecord(r.baselineRelease.contentHash);if(!x||x.harnessRelease.id!==r.baselineRelease.id||s.workspace.currentChannel.release?.contentHash!==r.baselineRelease.contentHash)throw new Error("The exact hosted source baseline is unavailable.");let y=await D({workspaceId:typeof x.agentSnapshot.metadata.workspaceId=="string"?x.agentSnapshot.metadata.workspaceId:x.workspaceId,sourceDir:Qe.join(x.bundlePath,"source")});if(z(y).protectedClosureHash!==r.privateClosureHash)throw new Error("The protected hosted Profile closure changed.");let h={packageValue:n,authorize:m};return{read:i(async l=>{if(V(l).contentHash!==r.contentHash)throw new Error("The actual hosted advanced admission changed.");return await m(),h},"read"),evidence:i(async()=>(await m(),d),"evidence"),authorize:i(async()=>m(),"authorize"),reviewContext:i(async(l,H)=>{await m();let E=t.contexts.filter(p=>p.taskId===H),P=d.result.cases.find(p=>p.identity.caseId===H);if(E.length!==1||!P||P.status!=="completed")throw new Error("The actual retained hosted review case is unavailable.");let w=E[0];if(w.caseHash!==R(P)||w.session.cloudTeamId!==r.teamId||w.turn.sessionId!==w.session.id||w.turn.status==="in_progress"||w.events.some(p=>p.sessionId!==w.session.id||p.turnId!==w.turn.id))throw new Error("The actual hosted review session/turn/trace binding changed.");return await m(),{...w,case:{output:w.output}}},"reviewContext")}}i(_e,"createHostedAdvancedRefinerSource");import{randomUUID as Ze}from"node:crypto";function Oe(s){async function r(n){let d=await s.store.getSession(n);if(!d||d.cloudTeamId!==s.teamId||d.metadata?.hostedAdvancedTurnId!==s.hostedTurnId||d.metadata?.parentModelRunId!==s.modelRunId)throw new Error("The actual hosted advanced case owner changed.");return d}i(r,"read");async function t(n,d,m){let u=await r(n),v=e.object({action:e.string()}).passthrough().parse(d).action;return ce.parse(await s.bridge.compute({session:u,payload:d,turnId:m??null},v==="sandbox_stop"||v==="sandbox_receipts"))}return i(t,"tool"),{createSession:i(async n=>{await s.bridge.authorize();let d=C.partial().parse(n),m=new Date().toISOString();if(d.metadata?.parentModelRunId!==s.modelRunId)throw new Error("The foreground case belongs to another actual advanced Run.");let u=C.parse({...d,id:`hosted-advanced-case-${Ze()}`,provider:"openpond",currentProfile:s.profileRef,cloudTeamId:s.teamId,cwd:null,codexThreadId:null,appId:null,appName:null,createdAt:m,updatedAt:m,status:"active",pinned:!1,archived:!1,order:0,hiddenFromDefaultSidebar:!0,title:d.title??"Advanced hosted evaluation case",metadata:{...d.metadata,source:"hosted-advanced-evaluation",hostedAdvancedTurnId:s.hostedTurnId,actorId:s.actorId,workspaceTarget:"hosted",benchmarkRuntime:"hosted_managed_work"}});return await s.store.insertSessionAtFront(u),await s.bridge.authorize(),u},"createSession"),getSession:r,runtimeEventsForSession:i(n=>s.store.runtimeEventsForSession(n),"runtimeEventsForSession"),executeWorkspaceTool:i((n,d,m)=>t(n,d,m?.turnId),"executeWorkspaceTool"),settleCostEvidence:i((n,d)=>t(n,{action:"sandbox_receipts",args:{}},d?.turnId),"settleCostEvidence")}}i(Oe,"createHostedAdvancedWorkRuntime");var Xe=e.string().regex(/^[a-f0-9]{64}$/),Be=e.object({version:e.string().min(1),source:e.string().min(1),effectiveAt:e.string().min(1),inputUsdPerMillionTokens:e.number().finite().nonnegative(),cachedInputUsdPerMillionTokens:e.number().finite().nonnegative(),outputUsdPerMillionTokens:e.number().finite().nonnegative()}).strict(),Z=e.object({operation:e.enum(["prepare_run","start","read","resume","cancel"]),request:ue,configuration:e.object({id:e.string().min(1),profileId:e.string().min(1),etag:Xe}).strict(),refinerRelease:Y,privateSource:K,upstream:e.object({modelId:e.string().min(1),revision:e.string().min(1),pricing:Be}).strict(),judgeModels:e.array(e.object({modelId:e.string().min(1),revision:e.string().min(1),pricing:Be}).strict()).max(50),bridge:Q.optional(),hostedTurnId:e.string().min(1).optional()}).strict();async function Fe(s){let r=Z.parse(s.request),t=r.request.pin;if(r.request.model.providerId!=="openpond"||r.request.model.modelId!==r.upstream.modelId||r.configuration.id!==r.request.modelId||r.configuration.profileId!==t.profileRef.profileId||r.request.profileId!==t.profileRef.profileId||r.refinerRelease.id!==t.refinerRelease.id||r.refinerRelease.contentHash!==t.refinerRelease.contentHash)throw new Error("The actual hosted advanced configuration/model/Refiner admission changed.");let n=`advanced-refiner-${R([t.actorId,t.teamId,t.operationId,t.contentHash,r.request.model,[r.request.seed],1]).slice(0,40)}`;if((r.operation==="start"||r.operation==="resume")&&(!r.bridge||!r.hostedTurnId))throw new Error("The actual hosted advanced execution grant is unavailable.");let m=r.bridge?qe(r.bridge,s.signal):null;if(r.bridge&&(r.bridge.jobId!==n||r.bridge.pinHash!==t.contentHash))throw new Error("The hosted model bridge belongs to another actual Run.");let u=i(async()=>{s.signal.throwIfAborted(),await s.authorize(),m&&await m.authorize()},"authorize"),v=await _e({...s,pin:t,privateSource:r.privateSource,authorize:u}),I=we(ve(s.storeDir));await I.persistRelease(r.refinerRelease),await I.writeSource(ee(r.refinerRelease.profile)),I.binding()?.release.contentHash!==t.refinerRelease.contentHash&&await I.transition(r.refinerRelease,{operation:"activate",bindingChanged:!0,actor:s.actor.actorId,reason:"Pin the actual hosted evaluation fork to its admitted immutable Refiner release.",authoringSkillHash:null});let y=ke({storeDir:s.storeDir,authorize:i(async()=>u(),"authorize"),packageForPin:i(async()=>r.privateSource.packageValue,"packageForPin"),prepareModel:i(async(c,f,k)=>{if(!m)throw new Error("The actual hosted model ceiling owner is unavailable.");return m.ceiling(c,k,f)},"prepareModel")}),h=i(async function*(c){let f=be(),k=[r.upstream,...r.judgeModels].find(q=>q.modelId===c.model.modelId);if(!m||!f||!k)throw new Error("The actual hosted model and durable shared budget are unavailable.");let{signal:T,...j}=c,O=c.maxOutputTokens??4096,L=await f.call(c.requestId,j,k.pricing,O,async()=>{let q=[],F=null;for await(let N of m.stream({...c,signal:AbortSignal.any([T,f.signal])}))q.push(N),N.costUsd!==void 0&&(F=(F??0)+N.costUsd);return{value:q,costUsd:F}});for(let q of L)yield q},"stream"),l=i(async c=>{let f="";for await(let k of h({...c,reasoningEffort:c.reasoningEffort??null,tools:[],toolChoice:"none"}))k.text&&(f+=k.text),k.usage!==void 0&&c.onUsage?.(k.usage,k.costUsd);return f},"text"),H=Ie({store:s.store,storeDir:s.storeDir}),E=await H.projectSelected({profileId:t.profileRef.profileId,package:r.privateSource.packageValue,adaptationSplit:t.adaptationSplit,holdoutSplit:t.holdoutSplit}),P=i(async c=>{let f=C.partial().parse(c),k=new Date().toISOString(),T=C.parse({...f,id:`hosted-review-${R([n,f.metadata]).slice(0,40)}`,cloudTeamId:t.teamId,currentProfile:t.profileRef,appId:null,appName:null,cwd:null,codexThreadId:null,title:f.title??"Hosted Refiner review",provider:"openpond",createdAt:k,updatedAt:k,status:"active",pinned:!1,archived:!1,order:0,metadata:{...f.metadata,hostedAdvancedTurnId:r.hostedTurnId??null,actorId:t.actorId,source:"hosted-advanced-evaluation"}});return await s.store.insertSessionAtFront(T),T},"createSession"),w=m&&r.hostedTurnId?Oe({store:s.store,bridge:m,teamId:t.teamId,actorId:t.actorId,hostedTurnId:r.hostedTurnId,modelRunId:n,profileRef:t.profileRef}):void 0,p=Se({store:s.store,storeDir:s.storeDir,modelJudge:ye({store:s.store,modelText:l}),modelText:l,modelStream:h,workRuntime:w,resolveTasksetRelease:i(c=>H.releaseForTaskset(c),"resolveTasksetRelease")}),a={store:s.store,storeDir:s.storeDir,evaluation:p,benchmarkTasksets:H,loadProfileState:i(async()=>s.profile,"loadProfileState"),resolveEvaluationProject:i(async(c,f)=>{if(await u(),c!==r.configuration.id||f!==r.configuration.profileId)throw new Error("The actual hosted evaluation configuration changed.");return{id:c,profileId:f}},"resolveEvaluationProject"),resolveUpstreamModel:i(async()=>({providerId:"openpond",modelId:r.upstream.modelId,revision:r.upstream.revision,pricing:r.upstream.pricing}),"resolveUpstreamModel"),advancedBoundary:y,refinerStream:i(async function*(c){if(!c.requestId)throw new Error("A hosted Refiner call needs its actual retained ID.");yield*h({model:c.model,reasoningEffort:"low",messages:c.messages,tools:[],toolChoice:"none",requestId:c.requestId,maxOutputTokens:4096,signal:c.signal,hostedTokenPricing:c.pricing})},"refinerStream")},o=Re({...a,reviewQuality:He({source:v,boundary:y,benchmark:a,createSession:P})}),g={advancedEvaluation:t,selectedTaskset:{id:E.id,revision:E.revision,contentHash:E.contentHash},modelId:r.request.modelId,profileId:r.request.profileId,model:r.request.model,reasoningEffort:r.request.reasoningEffort,seeds:[r.request.seed],repetitions:1,maximumSpendUsd:t.maximumCostUsd},b,S=i(()=>{o.cancel(n)},"stop");s.signal.addEventListener("abort",S,{once:!0});try{if(r.operation==="prepare_run")return o.prepare(g);let c=await s.store.getModelRun(n);if(!c||c.evaluation?.benchmarkId!=="harness-refiner"||c.evaluation.advancedEvaluation?.contentHash!==t.contentHash)throw new Error("The original hosted advanced Run is unavailable.");if(r.operation==="read")return c;if(r.operation==="cancel")return o.cancel(n);if(m){let T=!1;b=setInterval(()=>{T||(T=!0,s.store.getModelRun(n).then(j=>j?m.checkpoint(j):void 0).catch(()=>S()).finally(()=>{T=!1}))},2e3)}r.operation==="start"?await o.start(g):await o.resume(n);let f=await o.wait(n);if(!f)throw new Error("The actual hosted advanced engine did not retain its Run.");let k=pe.parse(f);return m&&await m.checkpoint(k),k}finally{b&&clearInterval(b),s.signal.removeEventListener("abort",S),await o.close(),await y.close()}}i(Fe,"runHostedAdvancedRefinerOwner");import{promises as _}from"node:fs";import A from"node:path";var Ye=e.object({actor:e.object({actorId:e.string().min(1),teamId:e.string().min(1)}).strict(),storeDir:e.string().min(1),source:e.object({repoPath:e.string().min(1),repositoryId:e.string().min(1),profileId:e.string().min(1),sourceRevision:e.string().regex(/^[a-f0-9]{40,64}$/),filesHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),evidence:e.object({manifest:e.unknown(),result:e.unknown()}).strict(),operation:e.enum(["advanced","describe","command","queue","cancelQueued","bind","finish","beginTesting","cancelTesting","failTesting","comparison","beginAdoption","export","source","tool","toolCatalog"]),advanced:Z.optional(),command:le.optional(),candidateId:e.string().optional(),revision:e.number().int().positive().optional(),actualSession:C.optional(),actualTurn:$.optional(),recipe:e.unknown().optional(),baseline:e.object({manifest:e.unknown(),result:e.unknown()}).strict().optional(),candidate:e.object({manifest:e.unknown(),result:e.unknown()}).strict().optional(),humanProjection:oe.optional(),humanSelections:re.optional(),adoptionReadback:e.unknown().optional(),failure:e.object({message:e.string().max(2e3),cancelled:e.boolean()}).strict().optional(),tool:e.object({name:e.string(),args:e.record(e.string(),e.unknown()),callId:e.string()}).strict().optional(),agentRuntime:e.object({source:e.string(),cliRelativePath:e.string()}).strict().optional(),queued:e.object({sessionId:e.string(),turnId:e.string(),createdAt:e.string().datetime()}).strict().optional()}).strict();async function We(s,r=new AbortController().signal){r.throwIfAborted();let t=Ye.parse(s),{actor:n,source:d}=t;if(!A.isAbsolute(t.storeDir)||!A.isAbsolute(d.repoPath))throw new Error("Hosted candidate owner requires contained absolute private paths.");let m=M(t.evidence),u=[t.baseline,t.candidate].filter(l=>l!==void 0).map(l=>M(l));if(m.manifest.teamId!==n.teamId)throw new Error("Hosted candidate evidence belongs to another team.");if(await B(d.repoPath)!==d.filesHash)throw new Error("The admitted hosted Profile source bytes changed.");let v=`hosted-improve-source-${R([n,d.repositoryId,d.profileId,d.sourceRevision]).slice(0,40)}`,I=A.join(t.storeDir,"library","profile-experiment-origins",v);if(await _.mkdir(A.dirname(I),{recursive:!0,mode:448}),await _.stat(I).catch(()=>null)||await _.cp(d.repoPath,I,{recursive:!0,errorOnExist:!0,force:!1}),await B(I)!==d.filesHash)throw new Error("The private accepted Profile cache changed.");let x=await W(I,d.profileId);if(x.error||!x.sourcePath)throw new Error("The accepted hosted Profile does not compile.");let y=new xe(t.storeDir),h;try{let l=await y.getHarnessWorkspace(v);l||(l=(await fe({store:y,storeDir:t.storeDir,id:v,ownerId:n.actorId,name:d.profileId,profile:x,sourceRevision:d.sourceRevision,repositoryId:d.repositoryId,selectionEligible:!1,originMetadata:{profileExperimentOrigin:{schemaVersion:"openpond.profileExperimentOrigin.v1",...n,sourceRevision:d.sourceRevision,sourcePath:I,sourceFilesHash:d.filesHash},hostedImprovementOwner:!0}})).workspace);let H={source:"openpond_git",repositoryId:d.repositoryId,profileId:d.profileId},E=i(async()=>{if(r.throwIfAborted(),await B(I)!==d.filesHash||await B(d.repoPath)!==d.filesHash)throw new Error("Accepted source changed during private candidate I/O.")},"authorizer");if(t.operation==="advanced"){if(!t.advanced)throw new Error("Missing actual hosted advanced owner command.");return Fe({store:y,storeDir:t.storeDir,actor:n,profile:x,workspace:l,source:d,evidence:m,request:t.advanced,authorize:E,signal:r})}let P=i(()=>{if(!t.adoptionReadback)throw new Error("Actual hosted Git owner has not returned its sealed adoption receipt.");return e.object({receipt:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),activeRelease:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),testedCandidateRelease:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),executableSourceHash:e.string().regex(/^[a-f0-9]{64}$/),protectedClosureHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(t.adoptionReadback)},"readback");h=Ee({store:y,storeDir:t.storeDir,projectHumanComparison:i(async()=>{if(await E(),!t.humanProjection)throw new Error("The current private Human comparison owner is unavailable.");return ne(t.humanProjection)},"projectHumanComparison"),authorizeOwner:i(async(a,o,g,b,S)=>{if(R(a)!==R(n)||R(g)!==R(H)||o.id!==v)throw new Error("Hosted candidate source owner changed.");if(S.requireCurrentBase&&(o.currentChannel.release?.contentHash!==l.currentChannel.release?.contentHash||d.sourceRevision!==o.metadata.profileExperimentOrigin.sourceRevision))throw new Error("Hosted candidate accepted revision changed.");await E()},"authorizeOwner"),loadEvidence:i(async(a,o)=>{if(R(a)!==R(n))throw new Error("Hosted candidate evidence actor changed.");let g=[m,...u].find(b=>b.manifest.id===o.id&&b.result.contentHash===o.contentHash&&b.manifest.teamId===n.teamId);if(!g)throw new Error("Hosted candidate exact retained evidence changed.");return await E(),g},"loadEvidence"),freezeProfile:i(async(a,o,g)=>{let b=await y.getHarnessReleaseRecord(o.baseRelease.contentHash);if(!b)throw new Error("Hosted source baseline is missing.");let S=await D({workspaceId:typeof b.agentSnapshot.metadata.workspaceId=="string"?b.agentSnapshot.metadata.workspaceId:b.workspaceId,sourceDir:A.join(b.bundlePath,"source")}),c=await D({workspaceId:typeof g.release.agentSnapshot.metadata.workspaceId=="string"?g.release.agentSnapshot.metadata.workspaceId:g.release.workspaceId,sourceDir:A.join(g.release.bundlePath,"source")});return Ae({store:y,storeDir:t.storeDir,state:o},async f=>{await Ce({...f,state:o,base:S,candidate:c});let k=await W(f.root,o.profileRef.profileId),T=await U({storeDir:t.storeDir,state:o,profile:k,sourceRevision:g.profileSourceRevision,base:S}),j=z(T);if(j.protectedClosureHash!==z(S).protectedClosureHash)throw new Error("Hosted source candidate changed protected evaluation closure.");let O=A.join(t.storeDir,"library","profile-candidate-archives",o.id,j.contentHash);await _.mkdir(A.dirname(O),{recursive:!0,mode:448}),await _.stat(O).catch(()=>null)||await _.cp(f.root,O,{recursive:!0,errorOnExist:!0,force:!1});let L=await W(O,o.profileRef.profileId);if((await U({storeDir:t.storeDir,state:o,profile:L,sourceRevision:g.profileSourceRevision,base:S})).harnessRelease.contentHash!==T.harnessRelease.contentHash)throw new Error("Hosted frozen Profile archive readback differs.");let F=await he({storeDir:t.storeDir,workspaceId:g.release.workspaceId,compiled:T,createdAt:g.release.createdAt});return await E(),{...g,release:F,executableIdentity:j}})},"freezeProfile"),adopt:i(async()=>P(),"adopt"),readAdoption:i(async()=>t.adoptionReadback?P():null,"readAdoption"),rollback:i(async()=>P(),"rollback")});let w=Pe({store:y,improvements:h,actorId:i(async()=>n.actorId,"actorId"),teamId:i(async()=>n.teamId,"teamId"),loadProfile:i(async a=>{if(R(a)!==R(H))throw new Error("Candidate requested another source owner.");return x},"loadProfile"),agentRuntime:t.agentRuntime,operationSignal:r,loadAgentRuntime:De({storeDir:t.storeDir,loadArchive:ze({storeDir:t.storeDir})})});if(t.operation==="describe"){await E();let a=l.currentChannel.release,o=a?await y.getHarnessReleaseRecord(a.contentHash):null;if(!a||!o||o.workspaceId!==l.id||o.harnessRelease.id!==a.id||o.harnessRelease.contentHash!==a.contentHash||l.ownerScope.kind!=="personal"||l.ownerScope.id!==n.actorId)throw new Error("Hosted source release is unavailable to its admitted owner.");let g=await D({workspaceId:typeof o.agentSnapshot.metadata.workspaceId=="string"?o.agentSnapshot.metadata.workspaceId:v,sourceDir:A.join(o.bundlePath,"source")});if(g.harnessRelease.contentHash!==o.harnessRelease.contentHash)throw new Error("Hosted source compiler readback changed.");let b=await ge({runtime:{release:o},ref:H,sourceRevision:d.sourceRevision,harnessRelease:a}),S=i(c=>{let f=g.sourceFiles.find(k=>k.path===c)?.bytes;return f?JSON.parse(Buffer.from(f).toString("utf8")):null},"readJson");return await E(),{workspaceId:v,ownerRevision:l.revision,profileRef:H,baseRelease:l.currentChannel.release,profileSourceRevision:d.sourceRevision,manifest:g.manifest,executable:z(g),catalogHash:b.catalogHash,workflows:S("workflows/catalog.json"),actions:S("workflows/actions.json")}}if(t.operation==="command"){let a=t.command;if(!a)throw new Error("Missing canonical Improve command.");if(a.operation==="start")return h.start(n,a.request);if(a.operation==="list")return h.list(n,a.limit,a.cursor);if(!("id"in a))throw new Error("Discover exact hosted source choices through the authenticated host.");let o=await h.read(n,a.id);if(a.operation==="read")return o;if(a.operation==="instructions"){let g=await h.partition(n,o.id),b=await me(g.sourceRoot,o.component.path),S=await _.readFile(b);if(S.length>25e4)throw new Error("Instruction editor size limit exceeded.");let c=S.toString("utf8");if(o.component.kind==="workflow"){let f=JSON.parse(c).workflows?.find(k=>k.id===o.component.workflowId);if(f?.invocation?.kind!=="instructions")throw new Error("Use Work to author this executable Workflow.");c=f.invocation.instructions}return{candidateId:o.id,candidateRevision:o.revision,path:o.component.path,text:c,textHash:J(c),contentHash:J(S)}}if(a.operation==="humanComparisonOptions")throw new Error("Read the actual paired sources through their current hosted Experiment owner.");if(!("revision"in a)||o.revision!==a.revision)throw new Error("Candidate revision changed.");if(a.operation==="edit")return h.edit(n,o.id,o.revision,a.expectedFileHash,a.text);if(a.operation==="mode")return h.setMode(n,o.id,o.revision,a.mode);if(a.operation==="freeze")return h.freeze(n,o.id,o.revision);if(a.operation==="useCandidate")return h.useCandidate(n,o.id,o.revision);if(a.operation==="rollback")return h.rollback(n,o.id,o.revision);if(a.operation==="discard")return h.discard(n,o.id,o.revision);throw new Error("Hosted Work/test lifecycle requires the actual host turn/run admission.")}if(!t.candidateId)throw new Error("Missing actual hosted candidate ID.");let p=await h.read(n,t.candidateId);if(t.operation==="beginAdoption")return h.beginAdoption(n,p.id,t.revision);if(t.operation==="export")return je(y,p,"hosted_execution");if(t.operation==="source"){if(!p.frozen||p.status!=="frozen"&&p.status!=="testing"&&p.status!=="ready_for_review"&&p.status!=="adopting")throw new Error("Only the exact frozen source can enter hosted preparation.");let a=await y.getHarnessReleaseRecord(p.frozen.release.contentHash);if(!a||a.harnessRelease.id!==p.frozen.release.id)throw new Error("Frozen hosted source is unavailable.");let o=await D({workspaceId:typeof a.agentSnapshot.metadata.workspaceId=="string"?a.agentSnapshot.metadata.workspaceId:a.workspaceId,sourceDir:A.join(a.bundlePath,"source")}),g=z(o);if(o.harnessRelease.contentHash!==p.frozen.release.contentHash||g.contentHash!==p.frozen.executableSourceHash||g.protectedClosureHash!==p.frozen.protectedClosureHash)throw new Error("Frozen hosted executable changed.");let b=A.join(t.storeDir,"library","profile-candidate-archives",p.id,g.contentHash),S=await W(b,p.profileRef.profileId);if(S.error||!S.sourcePath)throw new Error("Frozen actual Profile archive is unavailable.");let c=await y.getHarnessReleaseRecord(p.baseRelease.contentHash);if(!c)throw new Error("Frozen baseline is unavailable.");let f=await D({workspaceId:typeof c.agentSnapshot.metadata.workspaceId=="string"?c.agentSnapshot.metadata.workspaceId:c.workspaceId,sourceDir:A.join(c.bundlePath,"source")}),k=await U({storeDir:t.storeDir,state:p,profile:S,sourceRevision:p.frozen.profileSourceRevision,base:f});if(k.harnessRelease.contentHash!==p.frozen.release.contentHash||z(k).contentHash!==g.contentHash)throw new Error("Actual frozen Profile archive differs from its compiled release.");return{state:p,profileSource:{repoPath:b,profileId:p.profileRef.profileId,sourceRevision:p.frozen.profileSourceRevision,repositoryId:p.profileRef.repositoryId,filesHash:await B(b)},sourcePackage:te({agentSnapshot:o.agentSnapshot,harnessRelease:o.harnessRelease,files:new Map(o.sourceFiles.map(T=>[T.path,T.bytes]))})}}if(t.operation==="comparison"){if(!t.baseline||!t.candidate)throw new Error("Missing actual hosted paired evidence.");return h.completeComparison(n,p.id,t.revision,M(t.baseline),M(t.candidate),t.humanSelections)}if(t.operation==="beginTesting")return h.beginTesting(n,p.id,t.revision,t.recipe);if(t.operation==="failTesting"){if(!t.failure)throw new Error("Missing actual hosted test failure.");return h.failTesting(n,p.id,t.revision,t.failure.message,t.failure.cancelled)}if(t.operation==="cancelTesting")return h.cancelTesting(n,p.id,t.revision);if(t.operation==="queue"){if(!t.queued)throw new Error("Missing actual hosted queue admission.");return h.queueAuthoringTurn(n,p.id,t.revision,t.queued.sessionId,t.queued.turnId,t.queued.createdAt)}if(t.operation==="cancelQueued")return h.cancelQueuedAuthoring(n,p.id,t.revision);if(t.operation==="bind"||t.operation==="finish"||t.operation==="tool"||t.operation==="toolCatalog"){if(!t.actualSession||!t.actualTurn||t.actualTurn.sessionId!==t.actualSession.id||t.actualSession.cloudTeamId!==n.teamId||R(t.actualSession.currentProfile)!==R(H))throw new Error("Actual hosted candidate Work binding changed.");let a=t.actualSession,o=t.actualTurn,g=await y.getSession(a.id);if(!g)await y.insertSessionAtFront(a);else if(R({...g,updatedAt:a.updatedAt,status:a.status})!==R(a))throw new Error("Retained hosted candidate session changed.");let b=await y.getTurn(o.id);if(!b)await y.insertTurn(o);else{if(b.sessionId!==o.sessionId||R(b.metadata.refinementCandidate)!==R(o.metadata.refinementCandidate)||b.prompt!==o.prompt)throw new Error("Actual hosted candidate turn identity changed.");await y.updateTurn(o.id,()=>o)}if(t.operation==="bind")return h.bindAuthoringTurn(n,p.id,t.revision,a.id,o.id);if(t.operation==="finish")return h.finishAuthoring(n,p.id,t.revision);if(t.operation==="toolCatalog")return await w.candidateAuthoringForTurn(a.id,o.id),[...G({loadProfileState:i(async()=>x,"loadProfileState"),resolveCandidateProfile:w.resolveCandidateProfile,executeCandidateAgentCommand:w.executeCandidateAgentCommand}),...Te(async()=>{throw new Error("Hosted file tools require a bound private call.")}),{name:"exec_command",description:"Run a bounded command confined to the selected public candidate component.",parameters:{type:"object",additionalProperties:!1,properties:{command:{type:"string",minLength:1,maxLength:2e4},cwd:{type:"string"}},required:["command"]}},{name:"view_image",description:"Inspect an image inside the candidate public source tree.",parameters:{type:"object",additionalProperties:!1,properties:{path:{type:"string"}},required:["path"]}}].map(({name:c,description:f,parameters:k})=>({name:c,description:f,parameters:k}));if(!t.tool)throw new Error("Missing candidate tool call.");await w.authorizeCandidateTool({sessionId:a.id,turnId:o.id,name:t.tool.name});let S={session:a,turnId:o.id,args:t.tool.args,callId:t.tool.callId,signal:r,workspaceDiffBaseline:null,turnPermissions:{approvalPolicy:"never",sandbox:"workspace-write",codexPermissionMode:"default"},provider:a.provider,model:o.modelRef?.modelId??a.modelRef?.modelId??"",mentionedApps:[],userPrompt:o.prompt,turnMetadata:o.metadata};if(t.tool.name==="get_profile"||t.tool.name.startsWith("agent_")||t.tool.name==="ask_user"){let c=G({loadProfileState:i(async()=>x,"loadProfileState"),resolveCandidateProfile:w.resolveCandidateProfile,executeCandidateAgentCommand:w.executeCandidateAgentCommand}).find(f=>f.name===t.tool.name);if(!c)throw new Error("Candidate authoring tool is unavailable.");return c.execute(S)}if(t.tool.name==="view_image")return w.executeCandidateImage(S);if(t.tool.name==="exec_command")return w.executeCandidateCommand(S,{session:a,turnId:o.id,command:e.string().min(1).max(2e4).parse(t.tool.args.command),cwd:typeof t.tool.args.cwd=="string"?t.tool.args.cwd:null,signal:S.signal,source:"model_tool"});if(["list_files","read_files","search_files","workspace_status","write_file","write_files","edit_file","delete_file"].includes(t.tool.name))return w.executeCandidateWorkspaceTool({session:a,turnId:o.id,request:de.parse({action:t.tool.name,args:t.tool.args,source:"chat_action"})});throw new Error("This hosted tool has no confined candidate transport.")}throw new Error("Unknown private hosted Improve operation.")}finally{await h?.close(),await y.close()}}i(We,"runHostedExperimentImprovementOwner");async function wr(s){if(s.length!==1||s[0].length>16e3||!/^[A-Za-z0-9_-]+$/.test(s[0]))throw new Error("Hosted Improve IPC argument is invalid.");let r=e.object({directory:e.string(),file:e.string().regex(/^[A-Za-z0-9_-]+\.json$/)}).strict().parse(JSON.parse(Buffer.from(s[0],"base64url").toString("utf8")));if(!Ue.isAbsolute(r.directory))throw new Error("Hosted Improve IPC requires an absolute private directory.");let t=Ue.join(r.directory,r.file),n=await $e.lstat(t);if(!n.isFile()||n.isSymbolicLink()||n.size>32*1024*1024)throw new Error("Hosted Improve private request exceeds its byte/type limit.");let d=new AbortController,m=i(()=>d.abort(new Error("The actual hosted owner stopped this private operation.")),"stop");process.once("SIGTERM",m),process.once("SIGINT",m);try{let u=await We(JSON.parse(await $e.readFile(t,"utf8")),d.signal),v=Buffer.from(JSON.stringify(u));if(v.length>32*1024*1024)throw new Error("Hosted Improve private response exceeds its byte limit.");process.stdout.write(`${v.toString("utf8")}
2
+ import{a as Ie,b as ye,c as Re,d as He,e as Ee,f as Pe,h as B,i as Ae,j as je}from"./chunk-UBFRWC6I.js";import{e as Ce,f as U}from"./chunk-IOQUF34U.js";import{V as be,Va as Se,W as ke,hb as xe,jb as Te,n as we,nb as G,o as ve,ob as De,pb as ze}from"./chunk-TBNBCOW7.js";import"./chunk-EMKZVP7Z.js";import"./chunk-DLZP22WV.js";import{k as ge}from"./chunk-OE2VF6KU.js";import{a as z}from"./chunk-T5LE6R5S.js";import"./chunk-QJRXTIOC.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{h as me,ma as fe,qa as D,ra as he}from"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-2ZJJFBIA.js";import"./chunk-5CMKGD43.js";import{M as W}from"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import{Da as de,Ea as ce,M as C,N as $,a as se,lc as pe}from"./chunk-XDMUD4FW.js";import{aa as le,ga as V,ia as ue}from"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import{Ca as ie,za as ae}from"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import{B as re,C as oe,E as ne}from"./chunk-WV2APYWG.js";import{Ma as M}from"./chunk-PJM2G7SG.js";import{L as Y,P as ee,sa as te}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{l as J,m as R,r as X}from"./chunk-NNF6KCHD.js";import{b as e}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{promises as $e}from"node:fs";import Ue from"node:path";import Le from"node:http";var Q=e.object({socketPath:e.string().min(1).max(1e3),capability:e.string().regex(/^[a-f0-9]{64}$/),jobId:e.string().min(1),pinHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),Ne=e.object({jobId:e.string().min(1),pinHash:e.string().regex(/^[a-f0-9]{64}$/),requestId:e.string().min(1).max(500),model:X,reasoningEffort:e.enum(["off","low","medium","high","xhigh","max","none"]).nullable(),messages:e.array(e.unknown()).min(1).max(1e3),tools:e.array(e.unknown()).max(100),toolChoice:e.unknown(),maxOutputTokens:e.number().int().positive().max(131072),temperature:e.number().finite().optional(),topP:e.number().finite().optional(),seed:e.number().int().optional()}).strict(),Je=e.discriminatedUnion("kind",[e.object({kind:e.literal("chat_completions_reasoning"),reasoningContent:e.string()}).strict(),e.object({kind:e.literal("responses_reasoning_items"),items:e.array(e.record(e.string(),e.unknown()))}).strict()]),Ve=e.object({id:e.string().optional(),type:e.string(),function:e.object({name:e.string().optional(),arguments:e.string().optional()}).passthrough().optional()}).passthrough(),Ge=e.object({text:e.string().optional(),usage:e.unknown().optional(),costUsd:e.number().finite().nonnegative().optional(),continuation:Je.optional(),toolCalls:e.array(Ve).optional()}).strict();function qe(s,r){let t=Q.parse(s);async function n(u,v,I=r){I.throwIfAborted();let x=Buffer.from(JSON.stringify({action:u,jobId:t.jobId,pinHash:t.pinHash,value:v}));if(x.length>8*1024*1024)throw new Error("Hosted advanced request exceeds its private byte limit.");return new Promise((y,h)=>{let l=Le.request({socketPath:t.socketPath,path:"/",method:"POST",headers:{authorization:`Bearer ${t.capability}`,"content-type":"application/json","content-length":x.length},signal:I},H=>{let E=[],P=0;H.on("data",w=>{if(P+=w.length,P>8388608){H.destroy(new Error("Hosted advanced response exceeds its private byte limit."));return}E.push(w)}),H.on("error",h),H.on("end",()=>{try{let w=JSON.parse(Buffer.concat(E).toString("utf8"));if(H.statusCode!==200)throw new Error(typeof w?.error=="string"?w.error:"The actual hosted advanced owner refused this operation.");y(w)}catch(w){h(w)}})});l.on("error",h),l.end(x)})}i(n,"call");let d=i(async function*(u){let v=Ne.parse({jobId:t.jobId,pinHash:t.pinHash,requestId:u.requestId,model:u.model,reasoningEffort:u.reasoningEffort,messages:u.messages,tools:u.tools,toolChoice:u.toolChoice,maxOutputTokens:u.maxOutputTokens??4096,...u.temperature===void 0?{}:{temperature:u.temperature},...u.topP===void 0?{}:{topP:u.topP},...u.seed===void 0?{}:{seed:u.seed}}),I=e.object({deltas:e.array(Ge).max(1e5)}).strict().parse(await n("model",v,AbortSignal.any([r,u.signal])));for(let x of I.deltas)yield x},"stream");return{stream:d,text:i(async u=>{let v="";for await(let I of d({...u,reasoningEffort:u.reasoningEffort??null,tools:[],toolChoice:"none"}))I.text&&(v+=I.text),I.usage!==void 0&&u.onUsage?.(I.usage,I.costUsd);return v},"text"),authorize:i(async()=>{await n("authorize",{})},"authorize"),ceiling:i(async(u,v,I)=>e.object({configurationHash:e.string().regex(/^[a-f0-9]{64}$/),maximumChargeUsd:e.number().finite().positive()}).strict().parse(await n("ceiling",{modelId:u,pricing:v,maximumOutputTokens:I})),"ceiling"),compute:i((u,v=!1)=>n("compute",u,v?AbortSignal.timeout(6e4):r),"compute"),checkpoint:i(u=>n("checkpoint",u),"checkpoint")}}i(qe,"createHostedAdvancedModelBridge");import Qe from"node:path";var Me=e.string().regex(/^[a-f0-9]{64}$/),Ke=e.object({taskId:e.string().min(1),caseHash:Me,session:C,turn:$,events:e.array(se).max(1e4),traceHash:Me,output:e.string().nullable()}).strict(),K=e.object({packageValue:ae,contexts:e.array(Ke).max(1e4)}).strict();async function _e(s){let r=V(s.pin),t=K.parse(s.privateSource),n=ie(t.packageValue),d=M(e.object({manifest:e.unknown(),result:e.unknown()}).parse(s.evidence));async function m(){if(await s.authorize(),r.actorId!==s.actor.actorId||r.teamId!==s.actor.teamId||r.profileRef.source!=="openpond_git"||r.profileRef.repositoryId!==s.source.repositoryId||r.profileRef.profileId!==s.source.profileId||r.sourceRevision!==s.source.sourceRevision)throw new Error("The actual hosted advanced source owner changed.")}if(i(m,"authorize"),await m(),d.manifest.teamId!==r.teamId||d.result.status!=="completed"||d.manifest.id!==r.evidence.id||d.result.contentHash!==r.evidence.contentHash||R(d.manifest.dataset)!==R(r.externalDatasetBinding.dataset))throw new Error("The exact completed hosted advanced evidence changed.");if(n.contentHash!==r.externalDatasetBinding.packageHash||n.contentHash!==r.adaptationDatasetBinding.packageHash||n.environment.contentHash!==r.environmentPolicy.environmentHash||n.environment.contract.networkPolicy!=="none")throw new Error("The hosted advanced environment/package is not the exact reviewed closed-network release.");if(n.taskset.tools.some(l=>l.name==="web_search"||l.name==="web_fetch"))throw new Error("Live external tools require their own qualified frozen-observation and budget owner.");if(n.verifierSet.graders.some(l=>l.kind==="human"||l.kind==="model_judge"&&l.calibrationStatus!=="passed"))throw new Error("Advanced hosted evaluation needs executable, qualified independent graders.");let u=r.adaptationTaskIds.map(l=>n.taskset.tasks.find(H=>H.id===l)),v=r.holdoutTaskIds.map(l=>n.taskset.tasks.find(H=>H.id===l)),I=new Set(u.map(l=>l?.clusterKey));if(u.some(l=>!l||l.split!==r.adaptationSplit)||v.some(l=>!l||l.split!==r.holdoutSplit||I.has(l.clusterKey)))throw new Error("Hosted adaptation/holdout membership or independent families changed.");let x=await s.store.getHarnessReleaseRecord(r.baselineRelease.contentHash);if(!x||x.harnessRelease.id!==r.baselineRelease.id||s.workspace.currentChannel.release?.contentHash!==r.baselineRelease.contentHash)throw new Error("The exact hosted source baseline is unavailable.");let y=await D({workspaceId:typeof x.agentSnapshot.metadata.workspaceId=="string"?x.agentSnapshot.metadata.workspaceId:x.workspaceId,sourceDir:Qe.join(x.bundlePath,"source")});if(z(y).protectedClosureHash!==r.privateClosureHash)throw new Error("The protected hosted Profile closure changed.");let h={packageValue:n,authorize:m};return{read:i(async l=>{if(V(l).contentHash!==r.contentHash)throw new Error("The actual hosted advanced admission changed.");return await m(),h},"read"),evidence:i(async()=>(await m(),d),"evidence"),authorize:i(async()=>m(),"authorize"),reviewContext:i(async(l,H)=>{await m();let E=t.contexts.filter(p=>p.taskId===H),P=d.result.cases.find(p=>p.identity.caseId===H);if(E.length!==1||!P||P.status!=="completed")throw new Error("The actual retained hosted review case is unavailable.");let w=E[0];if(w.caseHash!==R(P)||w.session.cloudTeamId!==r.teamId||w.turn.sessionId!==w.session.id||w.turn.status==="in_progress"||w.events.some(p=>p.sessionId!==w.session.id||p.turnId!==w.turn.id))throw new Error("The actual hosted review session/turn/trace binding changed.");return await m(),{...w,case:{output:w.output}}},"reviewContext")}}i(_e,"createHostedAdvancedRefinerSource");import{randomUUID as Ze}from"node:crypto";function Oe(s){async function r(n){let d=await s.store.getSession(n);if(!d||d.cloudTeamId!==s.teamId||d.metadata?.hostedAdvancedTurnId!==s.hostedTurnId||d.metadata?.parentModelRunId!==s.modelRunId)throw new Error("The actual hosted advanced case owner changed.");return d}i(r,"read");async function t(n,d,m){let u=await r(n),v=e.object({action:e.string()}).passthrough().parse(d).action;return ce.parse(await s.bridge.compute({session:u,payload:d,turnId:m??null},v==="sandbox_stop"||v==="sandbox_receipts"))}return i(t,"tool"),{createSession:i(async n=>{await s.bridge.authorize();let d=C.partial().parse(n),m=new Date().toISOString();if(d.metadata?.parentModelRunId!==s.modelRunId)throw new Error("The foreground case belongs to another actual advanced Run.");let u=C.parse({...d,id:`hosted-advanced-case-${Ze()}`,provider:"openpond",currentProfile:s.profileRef,cloudTeamId:s.teamId,cwd:null,codexThreadId:null,appId:null,appName:null,createdAt:m,updatedAt:m,status:"active",pinned:!1,archived:!1,order:0,hiddenFromDefaultSidebar:!0,title:d.title??"Advanced hosted evaluation case",metadata:{...d.metadata,source:"hosted-advanced-evaluation",hostedAdvancedTurnId:s.hostedTurnId,actorId:s.actorId,workspaceTarget:"hosted",benchmarkRuntime:"hosted_managed_work"}});return await s.store.insertSessionAtFront(u),await s.bridge.authorize(),u},"createSession"),getSession:r,runtimeEventsForSession:i(n=>s.store.runtimeEventsForSession(n),"runtimeEventsForSession"),executeWorkspaceTool:i((n,d,m)=>t(n,d,m?.turnId),"executeWorkspaceTool"),settleCostEvidence:i((n,d)=>t(n,{action:"sandbox_receipts",args:{}},d?.turnId),"settleCostEvidence")}}i(Oe,"createHostedAdvancedWorkRuntime");var Xe=e.string().regex(/^[a-f0-9]{64}$/),Be=e.object({version:e.string().min(1),source:e.string().min(1),effectiveAt:e.string().min(1),inputUsdPerMillionTokens:e.number().finite().nonnegative(),cachedInputUsdPerMillionTokens:e.number().finite().nonnegative(),outputUsdPerMillionTokens:e.number().finite().nonnegative()}).strict(),Z=e.object({operation:e.enum(["prepare_run","start","read","resume","cancel"]),request:ue,configuration:e.object({id:e.string().min(1),profileId:e.string().min(1),etag:Xe}).strict(),refinerRelease:Y,privateSource:K,upstream:e.object({modelId:e.string().min(1),revision:e.string().min(1),pricing:Be}).strict(),judgeModels:e.array(e.object({modelId:e.string().min(1),revision:e.string().min(1),pricing:Be}).strict()).max(50),bridge:Q.optional(),hostedTurnId:e.string().min(1).optional()}).strict();async function Fe(s){let r=Z.parse(s.request),t=r.request.pin;if(r.request.model.providerId!=="openpond"||r.request.model.modelId!==r.upstream.modelId||r.configuration.id!==r.request.modelId||r.configuration.profileId!==t.profileRef.profileId||r.request.profileId!==t.profileRef.profileId||r.refinerRelease.id!==t.refinerRelease.id||r.refinerRelease.contentHash!==t.refinerRelease.contentHash)throw new Error("The actual hosted advanced configuration/model/Refiner admission changed.");let n=`advanced-refiner-${R([t.actorId,t.teamId,t.operationId,t.contentHash,r.request.model,[r.request.seed],1]).slice(0,40)}`;if((r.operation==="start"||r.operation==="resume")&&(!r.bridge||!r.hostedTurnId))throw new Error("The actual hosted advanced execution grant is unavailable.");let m=r.bridge?qe(r.bridge,s.signal):null;if(r.bridge&&(r.bridge.jobId!==n||r.bridge.pinHash!==t.contentHash))throw new Error("The hosted model bridge belongs to another actual Run.");let u=i(async()=>{s.signal.throwIfAborted(),await s.authorize(),m&&await m.authorize()},"authorize"),v=await _e({...s,pin:t,privateSource:r.privateSource,authorize:u}),I=we(ve(s.storeDir));await I.persistRelease(r.refinerRelease),await I.writeSource(ee(r.refinerRelease.profile)),I.binding()?.release.contentHash!==t.refinerRelease.contentHash&&await I.transition(r.refinerRelease,{operation:"activate",bindingChanged:!0,actor:s.actor.actorId,reason:"Pin the actual hosted evaluation fork to its admitted immutable Refiner release.",authoringSkillHash:null});let y=ke({storeDir:s.storeDir,authorize:i(async()=>u(),"authorize"),packageForPin:i(async()=>r.privateSource.packageValue,"packageForPin"),prepareModel:i(async(c,f,k)=>{if(!m)throw new Error("The actual hosted model ceiling owner is unavailable.");return m.ceiling(c,k,f)},"prepareModel")}),h=i(async function*(c){let f=be(),k=[r.upstream,...r.judgeModels].find(q=>q.modelId===c.model.modelId);if(!m||!f||!k)throw new Error("The actual hosted model and durable shared budget are unavailable.");let{signal:T,...j}=c,O=c.maxOutputTokens??4096,L=await f.call(c.requestId,j,k.pricing,O,async()=>{let q=[],F=null;for await(let N of m.stream({...c,signal:AbortSignal.any([T,f.signal])}))q.push(N),N.costUsd!==void 0&&(F=(F??0)+N.costUsd);return{value:q,costUsd:F}});for(let q of L)yield q},"stream"),l=i(async c=>{let f="";for await(let k of h({...c,reasoningEffort:c.reasoningEffort??null,tools:[],toolChoice:"none"}))k.text&&(f+=k.text),k.usage!==void 0&&c.onUsage?.(k.usage,k.costUsd);return f},"text"),H=Ie({store:s.store,storeDir:s.storeDir}),E=await H.projectSelected({profileId:t.profileRef.profileId,package:r.privateSource.packageValue,adaptationSplit:t.adaptationSplit,holdoutSplit:t.holdoutSplit}),P=i(async c=>{let f=C.partial().parse(c),k=new Date().toISOString(),T=C.parse({...f,id:`hosted-review-${R([n,f.metadata]).slice(0,40)}`,cloudTeamId:t.teamId,currentProfile:t.profileRef,appId:null,appName:null,cwd:null,codexThreadId:null,title:f.title??"Hosted Refiner review",provider:"openpond",createdAt:k,updatedAt:k,status:"active",pinned:!1,archived:!1,order:0,metadata:{...f.metadata,hostedAdvancedTurnId:r.hostedTurnId??null,actorId:t.actorId,source:"hosted-advanced-evaluation"}});return await s.store.insertSessionAtFront(T),T},"createSession"),w=m&&r.hostedTurnId?Oe({store:s.store,bridge:m,teamId:t.teamId,actorId:t.actorId,hostedTurnId:r.hostedTurnId,modelRunId:n,profileRef:t.profileRef}):void 0,p=Se({store:s.store,storeDir:s.storeDir,modelJudge:ye({store:s.store,modelText:l}),modelText:l,modelStream:h,workRuntime:w,resolveTasksetRelease:i(c=>H.releaseForTaskset(c),"resolveTasksetRelease")}),a={store:s.store,storeDir:s.storeDir,evaluation:p,benchmarkTasksets:H,loadProfileState:i(async()=>s.profile,"loadProfileState"),resolveEvaluationProject:i(async(c,f)=>{if(await u(),c!==r.configuration.id||f!==r.configuration.profileId)throw new Error("The actual hosted evaluation configuration changed.");return{id:c,profileId:f}},"resolveEvaluationProject"),resolveUpstreamModel:i(async()=>({providerId:"openpond",modelId:r.upstream.modelId,revision:r.upstream.revision,pricing:r.upstream.pricing}),"resolveUpstreamModel"),advancedBoundary:y,refinerStream:i(async function*(c){if(!c.requestId)throw new Error("A hosted Refiner call needs its actual retained ID.");yield*h({model:c.model,reasoningEffort:"low",messages:c.messages,tools:[],toolChoice:"none",requestId:c.requestId,maxOutputTokens:4096,signal:c.signal,hostedTokenPricing:c.pricing})},"refinerStream")},o=Re({...a,reviewQuality:He({source:v,boundary:y,benchmark:a,createSession:P})}),g={advancedEvaluation:t,selectedTaskset:{id:E.id,revision:E.revision,contentHash:E.contentHash},modelId:r.request.modelId,profileId:r.request.profileId,model:r.request.model,reasoningEffort:r.request.reasoningEffort,seeds:[r.request.seed],repetitions:1,maximumSpendUsd:t.maximumCostUsd},b,S=i(()=>{o.cancel(n)},"stop");s.signal.addEventListener("abort",S,{once:!0});try{if(r.operation==="prepare_run")return o.prepare(g);let c=await s.store.getModelRun(n);if(!c||c.evaluation?.benchmarkId!=="harness-refiner"||c.evaluation.advancedEvaluation?.contentHash!==t.contentHash)throw new Error("The original hosted advanced Run is unavailable.");if(r.operation==="read")return c;if(r.operation==="cancel")return o.cancel(n);if(m){let T=!1;b=setInterval(()=>{T||(T=!0,s.store.getModelRun(n).then(j=>j?m.checkpoint(j):void 0).catch(()=>S()).finally(()=>{T=!1}))},2e3)}r.operation==="start"?await o.start(g):await o.resume(n);let f=await o.wait(n);if(!f)throw new Error("The actual hosted advanced engine did not retain its Run.");let k=pe.parse(f);return m&&await m.checkpoint(k),k}finally{b&&clearInterval(b),s.signal.removeEventListener("abort",S),await o.close(),await y.close()}}i(Fe,"runHostedAdvancedRefinerOwner");import{promises as _}from"node:fs";import A from"node:path";var Ye=e.object({actor:e.object({actorId:e.string().min(1),teamId:e.string().min(1)}).strict(),storeDir:e.string().min(1),source:e.object({repoPath:e.string().min(1),repositoryId:e.string().min(1),profileId:e.string().min(1),sourceRevision:e.string().regex(/^[a-f0-9]{40,64}$/),filesHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),evidence:e.object({manifest:e.unknown(),result:e.unknown()}).strict(),operation:e.enum(["advanced","describe","command","queue","cancelQueued","bind","finish","beginTesting","cancelTesting","failTesting","comparison","beginAdoption","export","source","tool","toolCatalog"]),advanced:Z.optional(),command:le.optional(),candidateId:e.string().optional(),revision:e.number().int().positive().optional(),actualSession:C.optional(),actualTurn:$.optional(),recipe:e.unknown().optional(),baseline:e.object({manifest:e.unknown(),result:e.unknown()}).strict().optional(),candidate:e.object({manifest:e.unknown(),result:e.unknown()}).strict().optional(),humanProjection:oe.optional(),humanSelections:re.optional(),adoptionReadback:e.unknown().optional(),failure:e.object({message:e.string().max(2e3),cancelled:e.boolean()}).strict().optional(),tool:e.object({name:e.string(),args:e.record(e.string(),e.unknown()),callId:e.string()}).strict().optional(),agentRuntime:e.object({source:e.string(),cliRelativePath:e.string()}).strict().optional(),queued:e.object({sessionId:e.string(),turnId:e.string(),createdAt:e.string().datetime()}).strict().optional()}).strict();async function We(s,r=new AbortController().signal){r.throwIfAborted();let t=Ye.parse(s),{actor:n,source:d}=t;if(!A.isAbsolute(t.storeDir)||!A.isAbsolute(d.repoPath))throw new Error("Hosted candidate owner requires contained absolute private paths.");let m=M(t.evidence),u=[t.baseline,t.candidate].filter(l=>l!==void 0).map(l=>M(l));if(m.manifest.teamId!==n.teamId)throw new Error("Hosted candidate evidence belongs to another team.");if(await B(d.repoPath)!==d.filesHash)throw new Error("The admitted hosted Profile source bytes changed.");let v=`hosted-improve-source-${R([n,d.repositoryId,d.profileId,d.sourceRevision]).slice(0,40)}`,I=A.join(t.storeDir,"library","profile-experiment-origins",v);if(await _.mkdir(A.dirname(I),{recursive:!0,mode:448}),await _.stat(I).catch(()=>null)||await _.cp(d.repoPath,I,{recursive:!0,errorOnExist:!0,force:!1}),await B(I)!==d.filesHash)throw new Error("The private accepted Profile cache changed.");let x=await W(I,d.profileId);if(x.error||!x.sourcePath)throw new Error("The accepted hosted Profile does not compile.");let y=new xe(t.storeDir),h;try{let l=await y.getHarnessWorkspace(v);l||(l=(await fe({store:y,storeDir:t.storeDir,id:v,ownerId:n.actorId,name:d.profileId,profile:x,sourceRevision:d.sourceRevision,repositoryId:d.repositoryId,selectionEligible:!1,originMetadata:{profileExperimentOrigin:{schemaVersion:"openpond.profileExperimentOrigin.v1",...n,sourceRevision:d.sourceRevision,sourcePath:I,sourceFilesHash:d.filesHash},hostedImprovementOwner:!0}})).workspace);let H={source:"openpond_git",repositoryId:d.repositoryId,profileId:d.profileId},E=i(async()=>{if(r.throwIfAborted(),await B(I)!==d.filesHash||await B(d.repoPath)!==d.filesHash)throw new Error("Accepted source changed during private candidate I/O.")},"authorizer");if(t.operation==="advanced"){if(!t.advanced)throw new Error("Missing actual hosted advanced owner command.");return Fe({store:y,storeDir:t.storeDir,actor:n,profile:x,workspace:l,source:d,evidence:m,request:t.advanced,authorize:E,signal:r})}let P=i(()=>{if(!t.adoptionReadback)throw new Error("Actual hosted Git owner has not returned its sealed adoption receipt.");return e.object({receipt:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),activeRelease:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),testedCandidateRelease:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),executableSourceHash:e.string().regex(/^[a-f0-9]{64}$/),protectedClosureHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(t.adoptionReadback)},"readback");h=Ee({store:y,storeDir:t.storeDir,projectHumanComparison:i(async()=>{if(await E(),!t.humanProjection)throw new Error("The current private Human comparison owner is unavailable.");return ne(t.humanProjection)},"projectHumanComparison"),authorizeOwner:i(async(a,o,g,b,S)=>{if(R(a)!==R(n)||R(g)!==R(H)||o.id!==v)throw new Error("Hosted candidate source owner changed.");if(S.requireCurrentBase&&(o.currentChannel.release?.contentHash!==l.currentChannel.release?.contentHash||d.sourceRevision!==o.metadata.profileExperimentOrigin.sourceRevision))throw new Error("Hosted candidate accepted revision changed.");await E()},"authorizeOwner"),loadEvidence:i(async(a,o)=>{if(R(a)!==R(n))throw new Error("Hosted candidate evidence actor changed.");let g=[m,...u].find(b=>b.manifest.id===o.id&&b.result.contentHash===o.contentHash&&b.manifest.teamId===n.teamId);if(!g)throw new Error("Hosted candidate exact retained evidence changed.");return await E(),g},"loadEvidence"),freezeProfile:i(async(a,o,g)=>{let b=await y.getHarnessReleaseRecord(o.baseRelease.contentHash);if(!b)throw new Error("Hosted source baseline is missing.");let S=await D({workspaceId:typeof b.agentSnapshot.metadata.workspaceId=="string"?b.agentSnapshot.metadata.workspaceId:b.workspaceId,sourceDir:A.join(b.bundlePath,"source")}),c=await D({workspaceId:typeof g.release.agentSnapshot.metadata.workspaceId=="string"?g.release.agentSnapshot.metadata.workspaceId:g.release.workspaceId,sourceDir:A.join(g.release.bundlePath,"source")});return Ae({store:y,storeDir:t.storeDir,state:o},async f=>{await Ce({...f,state:o,base:S,candidate:c});let k=await W(f.root,o.profileRef.profileId),T=await U({storeDir:t.storeDir,state:o,profile:k,sourceRevision:g.profileSourceRevision,base:S}),j=z(T);if(j.protectedClosureHash!==z(S).protectedClosureHash)throw new Error("Hosted source candidate changed protected evaluation closure.");let O=A.join(t.storeDir,"library","profile-candidate-archives",o.id,j.contentHash);await _.mkdir(A.dirname(O),{recursive:!0,mode:448}),await _.stat(O).catch(()=>null)||await _.cp(f.root,O,{recursive:!0,errorOnExist:!0,force:!1});let L=await W(O,o.profileRef.profileId);if((await U({storeDir:t.storeDir,state:o,profile:L,sourceRevision:g.profileSourceRevision,base:S})).harnessRelease.contentHash!==T.harnessRelease.contentHash)throw new Error("Hosted frozen Profile archive readback differs.");let F=await he({storeDir:t.storeDir,workspaceId:g.release.workspaceId,compiled:T,createdAt:g.release.createdAt});return await E(),{...g,release:F,executableIdentity:j}})},"freezeProfile"),adopt:i(async()=>P(),"adopt"),readAdoption:i(async()=>t.adoptionReadback?P():null,"readAdoption"),rollback:i(async()=>P(),"rollback")});let w=Pe({store:y,improvements:h,actorId:i(async()=>n.actorId,"actorId"),teamId:i(async()=>n.teamId,"teamId"),loadProfile:i(async a=>{if(R(a)!==R(H))throw new Error("Candidate requested another source owner.");return x},"loadProfile"),agentRuntime:t.agentRuntime,operationSignal:r,loadAgentRuntime:De({storeDir:t.storeDir,loadArchive:ze({storeDir:t.storeDir})})});if(t.operation==="describe"){await E();let a=l.currentChannel.release,o=a?await y.getHarnessReleaseRecord(a.contentHash):null;if(!a||!o||o.workspaceId!==l.id||o.harnessRelease.id!==a.id||o.harnessRelease.contentHash!==a.contentHash||l.ownerScope.kind!=="personal"||l.ownerScope.id!==n.actorId)throw new Error("Hosted source release is unavailable to its admitted owner.");let g=await D({workspaceId:typeof o.agentSnapshot.metadata.workspaceId=="string"?o.agentSnapshot.metadata.workspaceId:v,sourceDir:A.join(o.bundlePath,"source")});if(g.harnessRelease.contentHash!==o.harnessRelease.contentHash)throw new Error("Hosted source compiler readback changed.");let b=await ge({runtime:{release:o},ref:H,sourceRevision:d.sourceRevision,harnessRelease:a}),S=i(c=>{let f=g.sourceFiles.find(k=>k.path===c)?.bytes;return f?JSON.parse(Buffer.from(f).toString("utf8")):null},"readJson");return await E(),{workspaceId:v,ownerRevision:l.revision,profileRef:H,baseRelease:l.currentChannel.release,profileSourceRevision:d.sourceRevision,manifest:g.manifest,executable:z(g),catalogHash:b.catalogHash,workflows:S("workflows/catalog.json"),actions:S("workflows/actions.json")}}if(t.operation==="command"){let a=t.command;if(!a)throw new Error("Missing canonical Improve command.");if(a.operation==="start")return h.start(n,a.request);if(a.operation==="list")return h.list(n,a.limit,a.cursor);if(!("id"in a))throw new Error("Discover exact hosted source choices through the authenticated host.");let o=await h.read(n,a.id);if(a.operation==="read")return o;if(a.operation==="instructions"){let g=await h.partition(n,o.id),b=await me(g.sourceRoot,o.component.path),S=await _.readFile(b);if(S.length>25e4)throw new Error("Instruction editor size limit exceeded.");let c=S.toString("utf8");if(o.component.kind==="workflow"){let f=JSON.parse(c).workflows?.find(k=>k.id===o.component.workflowId);if(f?.invocation?.kind!=="instructions")throw new Error("Use Work to author this executable Workflow.");c=f.invocation.instructions}return{candidateId:o.id,candidateRevision:o.revision,path:o.component.path,text:c,textHash:J(c),contentHash:J(S)}}if(a.operation==="humanComparisonOptions")throw new Error("Read the actual paired sources through their current hosted Experiment owner.");if(!("revision"in a)||o.revision!==a.revision)throw new Error("Candidate revision changed.");if(a.operation==="edit")return h.edit(n,o.id,o.revision,a.expectedFileHash,a.text);if(a.operation==="mode")return h.setMode(n,o.id,o.revision,a.mode);if(a.operation==="freeze")return h.freeze(n,o.id,o.revision);if(a.operation==="useCandidate")return h.useCandidate(n,o.id,o.revision);if(a.operation==="rollback")return h.rollback(n,o.id,o.revision);if(a.operation==="discard")return h.discard(n,o.id,o.revision);throw new Error("Hosted Work/test lifecycle requires the actual host turn/run admission.")}if(!t.candidateId)throw new Error("Missing actual hosted candidate ID.");let p=await h.read(n,t.candidateId);if(t.operation==="beginAdoption")return h.beginAdoption(n,p.id,t.revision);if(t.operation==="export")return je(y,p,"hosted_execution");if(t.operation==="source"){if(!p.frozen||p.status!=="frozen"&&p.status!=="testing"&&p.status!=="ready_for_review"&&p.status!=="adopting")throw new Error("Only the exact frozen source can enter hosted preparation.");let a=await y.getHarnessReleaseRecord(p.frozen.release.contentHash);if(!a||a.harnessRelease.id!==p.frozen.release.id)throw new Error("Frozen hosted source is unavailable.");let o=await D({workspaceId:typeof a.agentSnapshot.metadata.workspaceId=="string"?a.agentSnapshot.metadata.workspaceId:a.workspaceId,sourceDir:A.join(a.bundlePath,"source")}),g=z(o);if(o.harnessRelease.contentHash!==p.frozen.release.contentHash||g.contentHash!==p.frozen.executableSourceHash||g.protectedClosureHash!==p.frozen.protectedClosureHash)throw new Error("Frozen hosted executable changed.");let b=A.join(t.storeDir,"library","profile-candidate-archives",p.id,g.contentHash),S=await W(b,p.profileRef.profileId);if(S.error||!S.sourcePath)throw new Error("Frozen actual Profile archive is unavailable.");let c=await y.getHarnessReleaseRecord(p.baseRelease.contentHash);if(!c)throw new Error("Frozen baseline is unavailable.");let f=await D({workspaceId:typeof c.agentSnapshot.metadata.workspaceId=="string"?c.agentSnapshot.metadata.workspaceId:c.workspaceId,sourceDir:A.join(c.bundlePath,"source")}),k=await U({storeDir:t.storeDir,state:p,profile:S,sourceRevision:p.frozen.profileSourceRevision,base:f});if(k.harnessRelease.contentHash!==p.frozen.release.contentHash||z(k).contentHash!==g.contentHash)throw new Error("Actual frozen Profile archive differs from its compiled release.");return{state:p,profileSource:{repoPath:b,profileId:p.profileRef.profileId,sourceRevision:p.frozen.profileSourceRevision,repositoryId:p.profileRef.repositoryId,filesHash:await B(b)},sourcePackage:te({agentSnapshot:o.agentSnapshot,harnessRelease:o.harnessRelease,files:new Map(o.sourceFiles.map(T=>[T.path,T.bytes]))})}}if(t.operation==="comparison"){if(!t.baseline||!t.candidate)throw new Error("Missing actual hosted paired evidence.");return h.completeComparison(n,p.id,t.revision,M(t.baseline),M(t.candidate),t.humanSelections)}if(t.operation==="beginTesting")return h.beginTesting(n,p.id,t.revision,t.recipe);if(t.operation==="failTesting"){if(!t.failure)throw new Error("Missing actual hosted test failure.");return h.failTesting(n,p.id,t.revision,t.failure.message,t.failure.cancelled)}if(t.operation==="cancelTesting")return h.cancelTesting(n,p.id,t.revision);if(t.operation==="queue"){if(!t.queued)throw new Error("Missing actual hosted queue admission.");return h.queueAuthoringTurn(n,p.id,t.revision,t.queued.sessionId,t.queued.turnId,t.queued.createdAt)}if(t.operation==="cancelQueued")return h.cancelQueuedAuthoring(n,p.id,t.revision);if(t.operation==="bind"||t.operation==="finish"||t.operation==="tool"||t.operation==="toolCatalog"){if(!t.actualSession||!t.actualTurn||t.actualTurn.sessionId!==t.actualSession.id||t.actualSession.cloudTeamId!==n.teamId||R(t.actualSession.currentProfile)!==R(H))throw new Error("Actual hosted candidate Work binding changed.");let a=t.actualSession,o=t.actualTurn,g=await y.getSession(a.id);if(!g)await y.insertSessionAtFront(a);else if(R({...g,updatedAt:a.updatedAt,status:a.status})!==R(a))throw new Error("Retained hosted candidate session changed.");let b=await y.getTurn(o.id);if(!b)await y.insertTurn(o);else{if(b.sessionId!==o.sessionId||R(b.metadata.refinementCandidate)!==R(o.metadata.refinementCandidate)||b.prompt!==o.prompt)throw new Error("Actual hosted candidate turn identity changed.");await y.updateTurn(o.id,()=>o)}if(t.operation==="bind")return h.bindAuthoringTurn(n,p.id,t.revision,a.id,o.id);if(t.operation==="finish")return h.finishAuthoring(n,p.id,t.revision);if(t.operation==="toolCatalog")return await w.candidateAuthoringForTurn(a.id,o.id),[...G({loadProfileState:i(async()=>x,"loadProfileState"),resolveCandidateProfile:w.resolveCandidateProfile,executeCandidateAgentCommand:w.executeCandidateAgentCommand}),...Te(async()=>{throw new Error("Hosted file tools require a bound private call.")}),{name:"exec_command",description:"Run a bounded command confined to the selected public candidate component.",parameters:{type:"object",additionalProperties:!1,properties:{command:{type:"string",minLength:1,maxLength:2e4},cwd:{type:"string"}},required:["command"]}},{name:"view_image",description:"Inspect an image inside the candidate public source tree.",parameters:{type:"object",additionalProperties:!1,properties:{path:{type:"string"}},required:["path"]}}].map(({name:c,description:f,parameters:k})=>({name:c,description:f,parameters:k}));if(!t.tool)throw new Error("Missing candidate tool call.");await w.authorizeCandidateTool({sessionId:a.id,turnId:o.id,name:t.tool.name});let S={session:a,turnId:o.id,args:t.tool.args,callId:t.tool.callId,signal:r,workspaceDiffBaseline:null,turnPermissions:{approvalPolicy:"never",sandbox:"workspace-write",codexPermissionMode:"default"},provider:a.provider,model:o.modelRef?.modelId??a.modelRef?.modelId??"",mentionedApps:[],userPrompt:o.prompt,turnMetadata:o.metadata};if(t.tool.name==="get_profile"||t.tool.name.startsWith("agent_")||t.tool.name==="ask_user"){let c=G({loadProfileState:i(async()=>x,"loadProfileState"),resolveCandidateProfile:w.resolveCandidateProfile,executeCandidateAgentCommand:w.executeCandidateAgentCommand}).find(f=>f.name===t.tool.name);if(!c)throw new Error("Candidate authoring tool is unavailable.");return c.execute(S)}if(t.tool.name==="view_image")return w.executeCandidateImage(S);if(t.tool.name==="exec_command")return w.executeCandidateCommand(S,{session:a,turnId:o.id,command:e.string().min(1).max(2e4).parse(t.tool.args.command),cwd:typeof t.tool.args.cwd=="string"?t.tool.args.cwd:null,signal:S.signal,source:"model_tool"});if(["list_files","read_files","search_files","workspace_status","write_file","write_files","edit_file","delete_file"].includes(t.tool.name))return w.executeCandidateWorkspaceTool({session:a,turnId:o.id,request:de.parse({action:t.tool.name,args:t.tool.args,source:"chat_action"})});throw new Error("This hosted tool has no confined candidate transport.")}throw new Error("Unknown private hosted Improve operation.")}finally{await h?.close(),await y.close()}}i(We,"runHostedExperimentImprovementOwner");async function wr(s){if(s.length!==1||s[0].length>16e3||!/^[A-Za-z0-9_-]+$/.test(s[0]))throw new Error("Hosted Improve IPC argument is invalid.");let r=e.object({directory:e.string(),file:e.string().regex(/^[A-Za-z0-9_-]+\.json$/)}).strict().parse(JSON.parse(Buffer.from(s[0],"base64url").toString("utf8")));if(!Ue.isAbsolute(r.directory))throw new Error("Hosted Improve IPC requires an absolute private directory.");let t=Ue.join(r.directory,r.file),n=await $e.lstat(t);if(!n.isFile()||n.isSymbolicLink()||n.size>32*1024*1024)throw new Error("Hosted Improve private request exceeds its byte/type limit.");let d=new AbortController,m=i(()=>d.abort(new Error("The actual hosted owner stopped this private operation.")),"stop");process.once("SIGTERM",m),process.once("SIGINT",m);try{let u=await We(JSON.parse(await $e.readFile(t,"utf8")),d.signal),v=Buffer.from(JSON.stringify(u));if(v.length>32*1024*1024)throw new Error("Hosted Improve private response exceeds its byte limit.");process.stdout.write(`${v.toString("utf8")}
3
3
  `)}finally{process.removeListener("SIGTERM",m),process.removeListener("SIGINT",m)}}i(wr,"runHostedExperimentImprovementCli");export{wr as runHostedExperimentImprovementCli};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a,b,c,d}from"./chunk-HEPLG5FY.js";import"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as compileHostedProfileRelease,b as runHostedProfileCompilerCli,c as runHostedProfileEvaluationCli,d as runHostedProfileInspectionCli};
2
+ import{a,b,c,d}from"./chunk-OC6UWKBL.js";import"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as compileHostedProfileRelease,b as runHostedProfileCompilerCli,c as runHostedProfileEvaluationCli,d as runHostedProfileInspectionCli};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as V}from"./chunk-HEPLG5FY.js";import{c as I,f as j,h as D}from"./chunk-DFM5JTS2.js";import{k as x}from"./chunk-VOIH2BQA.js";import{a as E}from"./chunk-T5LE6R5S.js";import"./chunk-QJRXTIOC.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-7K72KS5C.js";import{ha as b,qa as C}from"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import{ta as m}from"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import{Ca as S}from"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import{ma as H}from"./chunk-PJM2G7SG.js";import{Ga as y,j as P,m as R}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{m as d}from"./chunk-NNF6KCHD.js";import{b as e}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";import{readFile as h,realpath as z,lstat as T}from"node:fs/promises";import l from"node:path";var B=e.object({compile:e.object({repoPath:e.string(),profileId:e.string(),repositoryId:e.string(),sourceRevision:e.string(),workspaceId:e.string(),outputDir:e.string()}).strict(),externalDatasetPackage:e.string().regex(/^external-dataset-[a-f0-9-]+\.json$/).optional(),sourceCandidate:H.optional(),action:e.enum(["catalog","prepare"]),request:e.unknown().optional()}).strict();async function G(t){let o=await V(t.compile);if(t.sourceCandidate){let a=await C({workspaceId:typeof o.agentSnapshot.metadata.workspaceId=="string"?o.agentSnapshot.metadata.workspaceId:o.workspaceId,sourceDir:l.join(o.bundlePath,"source")});if(d(t.sourceCandidate.harnessRelease)!==d({id:o.harnessRelease.id,contentHash:o.harnessRelease.contentHash})||E(a).protectedClosureHash!==t.sourceCandidate.protectedClosureHash)throw new Error("Private candidate source differs from its actual frozen compiled release.")}let g={release:b.parse({schemaVersion:"openpond.localHarnessReleaseRecord.v1",workspaceId:o.workspaceId,sourceRevision:o.sourceRevision,agentSnapshot:P.parse(o.agentSnapshot),harnessRelease:R.parse(o.harnessRelease),bundlePath:o.bundlePath,createdAt:new Date().toISOString()})},p={source:"openpond_git",profileId:t.compile.profileId,repositoryId:t.compile.repositoryId},f=t.compile.sourceRevision,c={id:o.harnessRelease.id,contentHash:o.harnessRelease.contentHash},w=s(async a=>x({...a,runtime:g}),"loadCatalog"),q=await w({ref:p,sourceRevision:f,harnessRelease:c}),k=l.join(o.bundlePath,"source"),v=o.harnessRelease.files.some(a=>a.path==="workflows/catalog.json")?await(async()=>{let a=y({agentSnapshot:o.agentSnapshot,harnessRelease:o.harnessRelease,catalogBytes:await h(l.join(k,"workflows/catalog.json")),actionBytes:await h(l.join(k,"workflows/actions.json"))});return a.catalog.workflows.map(r=>({workflow:r,binding:{schemaVersion:"openpond.profileWorkflowBinding.v1",profileId:p.profileId,sourceRevision:f,harnessRelease:c,catalogHash:a.catalogHash,workflowId:r.id}}))})():[],A={profileRef:p,sourceRevision:f,harnessRelease:c,workflows:v};if(t.action==="catalog")return{...q,workflows:v};let u=t.externalDatasetPackage?await(async()=>{let a=await z(t.compile.outputDir),r=l.join(a,t.externalDatasetPackage),i=await T(r);if(!i.isFile()||i.isSymbolicLink()||i.size>32*1024*1024||await z(r)!==r)throw new Error("External Dataset cache is outside its bounded verifier storage.");let n=e.object({packageValue:e.unknown(),graders:e.array(e.object({id:e.string(),version:e.string(),contentHash:e.string(),feedbackKey:e.string(),release:e.object({id:e.string(),revision:e.union([e.string(),e.number()]),contentHash:e.string()}).strict().nullable()}).strict()).max(100)}).strict().parse(JSON.parse(await h(r,"utf8")));return{packageValue:S(n.packageValue),graders:n.graders}})():null;return D({privateGradingPreflight:s(a=>I(a,!1),"privateGradingPreflight"),sourceCandidate:t.sourceCandidate,resolveExternalDataset:u?async a=>{let r=m({binding:a,...u}),i=d(o.harnessRelease.files.filter(n=>n.visibility!=="policy").map(n=>({path:n.path,asset:n})));if(a.protectedProfileClosureHash!==i)throw new Error("The selected Profile's protected evaluator closure changed.");return{binding:a,packageValue:r,authorize:s(async()=>{m({binding:a,...u})},"authorize")}}:void 0,loadCatalog:w,selectedWorkflows:s(async()=>A,"selectedWorkflows"),placement:"remote",boundedWorkComputeAvailable:!0,loadTasksetPackage:s(async a=>{let r=await j({runtime:g,definition:a,harnessRelease:c});if(!r)throw new Error("Hosted evaluation Taskset is absent from its published Profile release.");return r},"loadTasksetPackage"),modelConfigurationHash:s(async(a,r)=>{if(a.providerId!=="openpond"||!r.hostModelConfigurationHash)throw new Error("Hosted evaluation preparation requires a trusted model configuration receipt.");return r.hostModelConfigurationHash},"modelConfigurationHash")})(t.request)}s(G,"prepareHostedProfileEvaluation");async function ae(t){if(t.length!==1||t[0].length>48e3||!/^[A-Za-z0-9_-]+$/.test(t[0]))throw new Error("Hosted Profile evaluation preparation argument is invalid.");let o=B.parse(JSON.parse(Buffer.from(t[0],"base64url").toString("utf8")));process.stdout.write(`${JSON.stringify(await G(o))}
2
+ import{a as V}from"./chunk-OC6UWKBL.js";import{c as I,f as j,h as D}from"./chunk-ZCWHVLJ4.js";import{k as x}from"./chunk-OE2VF6KU.js";import{a as E}from"./chunk-T5LE6R5S.js";import"./chunk-QJRXTIOC.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-7K72KS5C.js";import{ha as b,qa as C}from"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import{ta as m}from"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import{Ca as S}from"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import{ma as H}from"./chunk-PJM2G7SG.js";import{Ga as y,j as P,m as R}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{m as d}from"./chunk-NNF6KCHD.js";import{b as e}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";import{readFile as h,realpath as z,lstat as T}from"node:fs/promises";import l from"node:path";var B=e.object({compile:e.object({repoPath:e.string(),profileId:e.string(),repositoryId:e.string(),sourceRevision:e.string(),workspaceId:e.string(),outputDir:e.string()}).strict(),externalDatasetPackage:e.string().regex(/^external-dataset-[a-f0-9-]+\.json$/).optional(),sourceCandidate:H.optional(),action:e.enum(["catalog","prepare"]),request:e.unknown().optional()}).strict();async function G(t){let o=await V(t.compile);if(t.sourceCandidate){let a=await C({workspaceId:typeof o.agentSnapshot.metadata.workspaceId=="string"?o.agentSnapshot.metadata.workspaceId:o.workspaceId,sourceDir:l.join(o.bundlePath,"source")});if(d(t.sourceCandidate.harnessRelease)!==d({id:o.harnessRelease.id,contentHash:o.harnessRelease.contentHash})||E(a).protectedClosureHash!==t.sourceCandidate.protectedClosureHash)throw new Error("Private candidate source differs from its actual frozen compiled release.")}let g={release:b.parse({schemaVersion:"openpond.localHarnessReleaseRecord.v1",workspaceId:o.workspaceId,sourceRevision:o.sourceRevision,agentSnapshot:P.parse(o.agentSnapshot),harnessRelease:R.parse(o.harnessRelease),bundlePath:o.bundlePath,createdAt:new Date().toISOString()})},p={source:"openpond_git",profileId:t.compile.profileId,repositoryId:t.compile.repositoryId},f=t.compile.sourceRevision,c={id:o.harnessRelease.id,contentHash:o.harnessRelease.contentHash},w=s(async a=>x({...a,runtime:g}),"loadCatalog"),q=await w({ref:p,sourceRevision:f,harnessRelease:c}),k=l.join(o.bundlePath,"source"),v=o.harnessRelease.files.some(a=>a.path==="workflows/catalog.json")?await(async()=>{let a=y({agentSnapshot:o.agentSnapshot,harnessRelease:o.harnessRelease,catalogBytes:await h(l.join(k,"workflows/catalog.json")),actionBytes:await h(l.join(k,"workflows/actions.json"))});return a.catalog.workflows.map(r=>({workflow:r,binding:{schemaVersion:"openpond.profileWorkflowBinding.v1",profileId:p.profileId,sourceRevision:f,harnessRelease:c,catalogHash:a.catalogHash,workflowId:r.id}}))})():[],A={profileRef:p,sourceRevision:f,harnessRelease:c,workflows:v};if(t.action==="catalog")return{...q,workflows:v};let u=t.externalDatasetPackage?await(async()=>{let a=await z(t.compile.outputDir),r=l.join(a,t.externalDatasetPackage),i=await T(r);if(!i.isFile()||i.isSymbolicLink()||i.size>32*1024*1024||await z(r)!==r)throw new Error("External Dataset cache is outside its bounded verifier storage.");let n=e.object({packageValue:e.unknown(),graders:e.array(e.object({id:e.string(),version:e.string(),contentHash:e.string(),feedbackKey:e.string(),release:e.object({id:e.string(),revision:e.union([e.string(),e.number()]),contentHash:e.string()}).strict().nullable()}).strict()).max(100)}).strict().parse(JSON.parse(await h(r,"utf8")));return{packageValue:S(n.packageValue),graders:n.graders}})():null;return D({privateGradingPreflight:s(a=>I(a,!1),"privateGradingPreflight"),sourceCandidate:t.sourceCandidate,resolveExternalDataset:u?async a=>{let r=m({binding:a,...u}),i=d(o.harnessRelease.files.filter(n=>n.visibility!=="policy").map(n=>({path:n.path,asset:n})));if(a.protectedProfileClosureHash!==i)throw new Error("The selected Profile's protected evaluator closure changed.");return{binding:a,packageValue:r,authorize:s(async()=>{m({binding:a,...u})},"authorize")}}:void 0,loadCatalog:w,selectedWorkflows:s(async()=>A,"selectedWorkflows"),placement:"remote",boundedWorkComputeAvailable:!0,loadTasksetPackage:s(async a=>{let r=await j({runtime:g,definition:a,harnessRelease:c});if(!r)throw new Error("Hosted evaluation Taskset is absent from its published Profile release.");return r},"loadTasksetPackage"),modelConfigurationHash:s(async(a,r)=>{if(a.providerId!=="openpond"||!r.hostModelConfigurationHash)throw new Error("Hosted evaluation preparation requires a trusted model configuration receipt.");return r.hostModelConfigurationHash},"modelConfigurationHash")})(t.request)}s(G,"prepareHostedProfileEvaluation");async function ae(t){if(t.length!==1||t[0].length>48e3||!/^[A-Za-z0-9_-]+$/.test(t[0]))throw new Error("Hosted Profile evaluation preparation argument is invalid.");let o=B.parse(JSON.parse(Buffer.from(t[0],"base64url").toString("utf8")));process.stdout.write(`${JSON.stringify(await G(o))}
3
3
  `)}s(ae,"runHostedProfileEvaluationCli");export{G as prepareHostedProfileEvaluation,ae as runHostedProfileEvaluationCli};