openpond 0.2.56 → 0.2.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/app-server.d.ts +1 -0
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/{app-server-evaluations-GJPFWIDA.js → app-server-evaluations-K52NAQLP.js} +1 -1
  4. package/dist/chunks/{app-server-harness-services-IH4G6POY.js → app-server-harness-services-QMUOEYOA.js} +1 -1
  5. package/dist/chunks/{app-server-runtime-DVKOZ5B6.js → app-server-runtime-ISGGLQHU.js} +1 -1
  6. package/dist/chunks/{chunk-XTFPDQMH.js → chunk-4EQA2M7K.js} +1 -1
  7. package/dist/chunks/chunk-5IPFI25K.js +2 -0
  8. package/dist/chunks/{chunk-3K4VVB7S.js → chunk-65PL62KH.js} +1 -1
  9. package/dist/chunks/{chunk-OGDADQGH.js → chunk-6UDGARFC.js} +1 -1
  10. package/dist/chunks/{chunk-2QUCCP6Z.js → chunk-7SC46OFC.js} +1 -1
  11. package/dist/chunks/{chunk-L6K7ERG5.js → chunk-APB4O67E.js} +1 -1
  12. package/dist/chunks/{chunk-S5ESN275.js → chunk-H4QHIHMK.js} +1 -1
  13. package/dist/chunks/{chunk-PPAPVGJP.js → chunk-HDGTHRY7.js} +1 -1
  14. package/dist/chunks/{chunk-XXYGGNVM.js → chunk-HPBQ4VTW.js} +1 -1
  15. package/dist/chunks/{chunk-FY5KHLMW.js → chunk-I3HZKJB3.js} +1 -1
  16. package/dist/chunks/{chunk-QHWGQ3A4.js → chunk-I3VVWNUW.js} +1 -1
  17. package/dist/chunks/{chunk-KUERKVEU.js → chunk-IIZ4CWBX.js} +1 -1
  18. package/dist/chunks/{chunk-SH5CBAFC.js → chunk-JAJ46T5X.js} +1 -1
  19. package/dist/chunks/{chunk-QEFHOJFE.js → chunk-JE7RJZOA.js} +1 -1
  20. package/dist/chunks/{chunk-GWCHDF2C.js → chunk-JUHZ5S3R.js} +1 -1
  21. package/dist/chunks/{chunk-PUZQU66L.js → chunk-L3KCP52O.js} +1 -1
  22. package/dist/chunks/{chunk-EQFGBL3O.js → chunk-NC27T4AB.js} +1 -1
  23. package/dist/chunks/{chunk-7HPDGZOR.js → chunk-NH6UUX5S.js} +1 -1
  24. package/dist/chunks/{chunk-QOTVNQDI.js → chunk-QL4OIPEZ.js} +1 -1
  25. package/dist/chunks/{chunk-ZFSHBFG5.js → chunk-RNQF63ZR.js} +1 -1
  26. package/dist/chunks/chunk-ROGF26KV.js +2 -0
  27. package/dist/chunks/{chunk-HDL5YSAA.js → chunk-RWWE5OXU.js} +1 -1
  28. package/dist/chunks/{chunk-YOBN7KTF.js → chunk-TJ6GVTYB.js} +1 -1
  29. package/dist/chunks/{chunk-3RCRSMWZ.js → chunk-TTVS6JMC.js} +1 -1
  30. package/dist/chunks/{chunk-WMKYHXVM.js → chunk-VVCKLCF3.js} +1 -1
  31. package/dist/chunks/{chunk-OIUTWU6K.js → chunk-X2HIHF2I.js} +1 -1
  32. package/dist/chunks/{chunk-J2TWKFML.js → chunk-XX6SMFDY.js} +4 -4
  33. package/dist/chunks/{chunk-GZ7M5XBP.js → chunk-YNH3NMPF.js} +1 -1
  34. package/dist/chunks/{chunk-YCJO3YVD.js → chunk-ZTNHW2K7.js} +3 -3
  35. package/dist/chunks/{cli-X25RSO2X.js → cli-XZENDZ7Z.js} +1 -1
  36. package/dist/chunks/{connected-app-executor-IVLGQP65.js → connected-app-executor-LQNIU5NR.js} +1 -1
  37. package/dist/chunks/host-profile-evaluation-tools-JOFBL5OF.js +2 -0
  38. package/dist/chunks/{hosted-app-server-composition-BCOO5ANF.js → hosted-app-server-composition-T5IWGOTA.js} +1 -1
  39. package/dist/chunks/{hosted-experiment-improvement-NFSVS5TU.js → hosted-experiment-improvement-HVMDGS75.js} +1 -1
  40. package/dist/chunks/{hosted-harness-runtime-723S5ZSH.js → hosted-harness-runtime-YCKB6NBI.js} +1 -1
  41. package/dist/chunks/{hosted-profile-candidate-2S5LFUWD.js → hosted-profile-candidate-EXNN6MVN.js} +1 -1
  42. package/dist/chunks/{hosted-profile-compiler-2DQIFSXW.js → hosted-profile-compiler-IYLLHCRY.js} +1 -1
  43. package/dist/chunks/{hosted-profile-evaluation-control-76BTRTYD.js → hosted-profile-evaluation-control-TJVER3NW.js} +1 -1
  44. package/dist/chunks/{hosted-profile-evaluation-inspection-V6Z3A5XJ.js → hosted-profile-evaluation-inspection-ZUANDYZ6.js} +1 -1
  45. package/dist/chunks/{hosted-profile-evaluation-preparation-IDJYREW3.js → hosted-profile-evaluation-preparation-ORVZ6MBD.js} +1 -1
  46. package/dist/chunks/{local-harness-improvement-runtime-JIQ6ZVDW.js → local-harness-improvement-runtime-QRFGPFRM.js} +1 -1
  47. package/dist/chunks/{local-harness-taskset-review-XVYTGAGK.js → local-harness-taskset-review-HR7KLY4B.js} +1 -1
  48. package/dist/chunks/{project-action-payload-7VGL7OER.js → project-action-payload-JDS6OQAW.js} +1 -1
  49. package/dist/chunks/{published-experiment-source-DZFENAQA.js → published-experiment-source-HVP5IGRH.js} +1 -1
  50. package/dist/chunks/{refiner-profile-service-UUIWFJVT.js → refiner-profile-service-FDTQKY33.js} +1 -1
  51. package/dist/chunks/{saved-work-6BMBFP43.js → saved-work-SHEEDZ6Z.js} +1 -1
  52. package/dist/chunks/{src-LMC3K6LH.js → src-DZL5T2MT.js} +1 -1
  53. package/dist/chunks/{src-CJM6HY5Y.js → src-R36AGJY7.js} +103 -103
  54. package/dist/chunks/{store-continual-support-reviews-HHA6NX7K.js → store-continual-support-reviews-LJPNG4SP.js} +1 -1
  55. package/dist/chunks/{store-create-improve-QV54XIZW.js → store-create-improve-SW5FTBTL.js} +1 -1
  56. package/dist/chunks/{store-datasets-RXJ33SUN.js → store-datasets-WMA7AJKN.js} +1 -1
  57. package/dist/chunks/{store-evaluation-results-3F3P527G.js → store-evaluation-results-ZO6R653G.js} +1 -1
  58. package/dist/chunks/{store-human-review-RAH7WMIP.js → store-human-review-7QQ7ZQ6P.js} +1 -1
  59. package/dist/chunks/{store-learned-preference-migration-validation-4CI2IRUF.js → store-learned-preference-migration-validation-NADPXOTG.js} +1 -1
  60. package/dist/chunks/{store-local-experiments-5LUJR7GI.js → store-local-experiments-SAULQSBN.js} +1 -1
  61. package/dist/chunks/{store-model-batch-review-YEGX327M.js → store-model-batch-review-VKLDYGH3.js} +1 -1
  62. package/dist/chunks/{store-model-configuration-5ZURQATB.js → store-model-configuration-BYRJUR3C.js} +1 -1
  63. package/dist/chunks/{store-task-inbox-JJTBW76C.js → store-task-inbox-QPE44OSS.js} +11 -11
  64. package/dist/chunks/{store-task-inventory-OB3F2APC.js → store-task-inventory-I3RDRI52.js} +1 -1
  65. package/dist/chunks/{store-taskset-drafts-EKQWWFYQ.js → store-taskset-drafts-2IULRV2W.js} +1 -1
  66. package/dist/chunks/{store-training-G6YLFSIR.js → store-training-B2TW2MLA.js} +1 -1
  67. package/dist/chunks/{store-training-jobs-RC46YBF6.js → store-training-jobs-VBNG23RL.js} +1 -1
  68. package/dist/chunks/{store-training-models-6BA43IPP.js → store-training-models-OMV5FIC4.js} +1 -1
  69. package/dist/cli.js +1 -1
  70. package/package.json +1 -1
  71. package/dist/chunks/chunk-UHFZHBGW.js +0 -2
  72. package/dist/chunks/chunk-YY7LEQGP.js +0 -2
  73. package/dist/chunks/host-profile-evaluation-tools-JJQWJUBT.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-W45RKGM6.js";import{a as we}from"./chunk-EIEZHFIW.js";import{e as Te,f as ge}from"./chunk-SDXFLO7J.js";import"./chunk-GLDYJM7O.js";import{h as x,j as L}from"./chunk-HCYX6RHP.js";import{d as F,f as me,g as ke,i as N,j as D,k as ue}from"./chunk-O72BSKSO.js";import{a as H,b as g,c as $}from"./chunk-DBK66CJP.js";import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as he}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import{d as de,e as ce,f as q,n as fe,p as le,q as pe}from"./chunk-XDQMGUWL.js";import{C as ne,k as y,l as se,m as re,o as ie,p as oe}from"./chunk-FTEOCCPB.js";import{Ib as A,U as ae,b as Y,c as X,ca as O,e as B,i as Z,ua as T,xa as _}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import{n as ee,x as S,y as te}from"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import{e as J,f as K}from"./chunk-I7AQMAQI.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import{N as j,O as M}from"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m}from"./chunk-KGNCKIFP.js";import{b as u}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as h}from"./chunk-FTQLQJQV.js";import{randomUUID as Ze}from"node:crypto";import{cp as et,mkdir as tt,readdir as at,rename as Q,rm as Ae,stat as st}from"node:fs/promises";import I from"node:path";function Ee(o,t,e,a){let s=t.modelScope;if(!s)return;let i=o.get("SELECT payload FROM model_projects WHERE id = ? AND profile_id = ?",[s.modelId,t.profileId]);if(!i)throw new Error("Taskset draft Model was not found in this Profile.");let r=S.parse(JSON.parse(i.payload)),n={id:e.id,revision:e.revision,contentHash:e.contentHash};return Te(o,{schemaVersion:"openpond.modelProjectSave.v1",operationId:`draft-publication:${m({draftId:t.id,revision:t.revision,scope:s,tasksetRef:n})}`,expectedRevision:s.expectedModelRevision,project:te.strip().parse({...r,trainingSetup:{...r.trainingSetup,tasksetRef:n,rewardBindingRef:e.metadata.rewardBinding===void 0?null:ee.parse(e.metadata.rewardBinding),tasksetRelease:null,recipe:null,...r.trainingSetup.evaluationTasksetRef&&r.trainingSetup.tasksetRef&&M(r.trainingSetup.evaluationTasksetRef,r.trainingSetup.tasksetRef)?{evaluationTasksetRef:n}:{}}})},null,a?.modelResources?{...a.modelResources,taskset:a.taskset,executionResources:{environment:a.environment,verifierSet:a.verifierSet}}:a??void 0)}h(Ee,"selectTasksetDraftModel");import{createHash as We,randomUUID as je}from"node:crypto";import{lstat as ve,mkdir as ye,readdir as Je,readFile as Be,rename as $e,rm as qe,writeFile as Ue}from"node:fs/promises";import R from"node:path";var b=le.extend({workspaceHash:u.string().regex(/^[a-f0-9]{64}$/).nullable()}).strict();async function Pe(o){let{db:t,profileId:e}=o,a=X.parse(o.request),s=h(()=>{let w=t.get("SELECT payload FROM model_projects WHERE id = ? AND profile_id = ?",[a.modelId,e]);if(!w)throw new Error("Taskset draft Model was not found in this Profile.");return S.parse(JSON.parse(w.payload))},"requireModel"),i=s(),r=m(a),n=t.get("SELECT request_hash, state, payload FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[e,a.operationId]);if(n){if(n.request_hash!==r)throw new Error("Taskset draft operation was reused with different input.");if(n.state==="deleted")throw new Error("This Taskset draft was deleted.");return b.parse(JSON.parse(n.payload))}if(!o.source)return null;if(i.revision!==a.expectedModelRevision)throw new Error("Model changed before draft initialization. Refresh before editing.");let f=i.trainingSetup.tasksetRef,p=f?t.get("SELECT payload FROM taskset_revisions WHERE taskset_id = ? AND revision = ? AND profile_id = ?",[f.id,f.revision,e]):null,d=p?T.parse(JSON.parse(p.payload)):null;if(!d||!f||d.contentHash!==f.contentHash)throw new Error("The selected source Taskset is unavailable.");let l=o.source,c=i.hosted?.apiOrigin?i.hosted.tasksets.find(w=>w.localTasksetId===d.id&&w.localTasksetHash===d.contentHash&&w.packageHash===l.contentHash&&w.releaseId===l.taskset.id&&w.releaseRevision===l.taskset.revision&&w.releaseHash===l.taskset.contentHash):null,k=typeof d.metadata.importedPackageHash=="string"?d.metadata.importedPackageHash:c?.packageHash;if(k?k!==l.contentHash:!M(j(A({taskset:d,adapterId:F(d)}).tasksetRelease),j(l.taskset)))throw new Error("Taskset draft package differs from its selected source.");let v=l.modelResources?ae.safeParse(l.taskset.metadata.modelTasksetDerivation):Y.safeParse(l.taskset.metadata.modelTasksetAuthoring),xe=c&&v.success&&v.data.owner.modelId===i.id?v.data.owner:{scopeId:e,modelId:i.id},Le=de({request:a,owner:xe,source:l}),Ce=pe({sourceDraft:ne(d),source:l,preparation:Le,expectedModelRevision:a.expectedModelRevision});await N(o.home,l);let G=b.parse({...Ce,workspaceHash:null}),ze=G.draft;t.exec("BEGIN IMMEDIATE");try{let w=t.get("SELECT request_hash FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[e,a.operationId]);if(w&&w.request_hash!==r)throw new Error("Taskset draft operation was reused with different input.");if(!w&&s().revision!==a.expectedModelRevision)throw new Error("Model changed during draft initialization. Refresh before editing.");t.run("INSERT INTO model_taskset_draft_operations (profile_id, operation_id, request_hash, draft_id, state, payload) VALUES (?, ?, ?, ?, 'prepared', ?) ON CONFLICT(profile_id, operation_id) DO NOTHING",[e,a.operationId,r,ze.id,JSON.stringify(G)]),t.exec("COMMIT")}catch(w){throw t.exec("ROLLBACK"),w}let W=t.get("SELECT request_hash, payload FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[e,a.operationId]);if(!W||W.request_hash!==r)throw new Error("Taskset draft operation was reused with different input.");return b.parse(JSON.parse(W.payload))}h(Pe,"prepareDraftInitialization");async function Se(o){let{initialized:t,workspacePath:e}=o;if(o.completed())return;if(t.workspaceHash)try{if(await ve(e),o.completed())return;if(await U(e),await g(e)!==t.workspaceHash)throw new Error("Prepared Taskset draft files changed before initialization completed.");return}catch(s){if(s.code!=="ENOENT")throw s}let a=`${e}.initializing-${je()}`;await ye(R.dirname(e),{recursive:!0});try{let s=t.draft.modelScope?.source;if(!s)throw new Error("Taskset draft lost its source preparation.");let i=await D(o.home,s.sourcePackageHash),r=new Map;for(let f of t.filePaths){let p=i.files.find(d=>d.asset.id===f.assetId);if(!p)throw new Error("Taskset draft source asset is missing.");for(let d of f.paths){if(d.includes("\\")||R.posix.isAbsolute(d)||d.split("/").some(k=>!k||k==="."||k===".."||k.startsWith(".env")))throw new Error("Taskset draft source path is invalid.");let l=r.get(d);if(l&&l!==p.asset.contentHash)throw new Error("Taskset draft source paths conflict.");if(l)continue;let c=R.join(a,d);await ye(R.dirname(c),{recursive:!0}),await Ue(c,O(p),{flag:"wx"}),r.set(d,p.asset.contentHash)}}await H(t.draft,a);for(let[f,p]of r)if(We("sha256").update(await Be(R.join(a,f))).digest("hex")!==p)throw new Error(`Taskset draft source asset conflicts with authoring file ${f}.`);let n=await g(a);if(o.retainHash({...t,workspaceHash:n}),o.completed())return;try{await $e(a,e)}catch(f){if(!["EEXIST","ENOTEMPTY"].includes(f.code??""))throw f;if(o.completed())return;if(await U(e),await g(e)!==n)throw new Error("Prepared Taskset draft files changed before initialization completed.")}}finally{await qe(a,{recursive:!0,force:!0})}}h(Se,"materializeDraftInitialization");async function U(o){let t=await ve(o);if(!t.isDirectory()||t.isSymbolicLink())throw new Error("Taskset draft source must be a regular directory.");for(let e of await Je(o,{withFileTypes:!0})){if(e.name.startsWith(".env")||e.isSymbolicLink())throw new Error("Taskset draft source contains a prohibited file.");if(e.isDirectory())await U(R.join(o,e.name));else if(!e.isFile())throw new Error("Taskset draft source must contain regular files.")}}h(U,"assertRegularTree");import Ve from"node:path";async function De(o){let t=A({taskset:o.taskset,adapterId:F(o.taskset)}),e=await me({root:o.directory,content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:t.tasksetRelease,environment:t.environmentRelease,verifierSet:t.verifierSetRelease},sources:q.parse(o.taskset.metadata.portableFileInventory??[])}),a=o.preparation.authoringGraph==="bound"?await D(o.home,o.preparation.sourcePackageHash):void 0,s=ce({preparation:o.preparation,edited:e,source:a});if(s.modelResources){let c=fe({package:s,profileId:o.taskset.profileId,name:o.taskset.name,createdAt:o.taskset.createdAt}),k=T.parse({...c.taskset,authoringProvenance:o.taskset.authoringProvenance,metadata:{...c.taskset.metadata,sourcePackageHash:o.taskset.metadata.sourcePackageHash}}),v=T.parse({...k,contentHash:_(k)});return await ue({home:o.home,...c,taskset:v}),{taskset:v,directory:Ve.join(o.home,"training","tasksets",String(v.environment.metadata.runtimeSourceTasksetId))}}let i=q.parse(o.taskset.metadata.portableFileInventory??[]),r=s.files.map(c=>({asset:c.asset,sourcePath:i.find(k=>k.asset.id===c.asset.id)?.sourcePath??c.asset.path})),n=s.taskset.environment.entrypoint==="openpond.javascript-environment.v1"?s.files.find(c=>c.asset.path==="environment/execution.json"):void 0,f=`model-draft-${m({packageHash:s.contentHash,taskset:o.taskset})}`,p=T.parse({...o.taskset,id:s.taskset.id,revision:s.taskset.revision,metadata:{...o.taskset.metadata,portableFileInventory:r,importedPackageHash:s.contentHash,derivedPortableMetadata:s.taskset.metadata},environment:{...o.taskset.environment,metadata:{...o.taskset.environment.metadata,runtimeSourceTasksetId:f,portableExecutionResources:{environment:s.environment,verifierSet:s.verifierSet}}}}),d=T.parse({...p,contentHash:_(p)}),l=await x(o.home,{taskset:d,generatedFiles:n?[{path:n.asset.path,role:"environment",content:new TextDecoder("utf-8",{fatal:!0}).decode(O(n))}]:[]},f,{source:{directory:o.directory,packageHash:await g(o.directory)},verify:h(c=>L(c,d),"verify")});return await N(o.home,s),{directory:l,taskset:d}}h(De,"materializeModelTasksetDraftPublication");import{constants as V}from"node:fs";import{createHash as Qe}from"node:crypto";import{lstat as be,mkdir as Ge,open as Ke,readdir as Ye,rm as Re}from"node:fs/promises";import C from"node:path";var P=h((o,t)=>K(C.join(o,"state","taskset-draft-writes"),t),"withTasksetDraftLock"),_e=re,Xe=h(o=>Qe("sha256").update(o).digest("hex"),"digest");async function z(o,t,e=!1){B.parse(t);let a=o;for(let s of["",...t.split("/").slice(0,-1)]){s&&(a=C.join(a,s)),e&&await Ge(a,{recursive:!1}).catch(r=>{if(r.code!=="EEXIST")throw r});let i=await be(a);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Taskset draft paths must use regular directories.")}return C.join(o,t)}h(z,"regularPath");async function He(o,t){let e=await z(o,t),a=await Ke(e,V.O_RDONLY|V.O_NOFOLLOW|V.O_NONBLOCK);try{let s=await a.stat();if(!s.isFile()||s.size>se)throw new Error("Taskset draft file must be a regular file within the 6 MB editing limit.");let i=Buffer.alloc(s.size),r=0;for(;r<i.length;){let n=await a.read(i,r,i.length-r,r);if(!n.bytesRead)throw new Error("Taskset draft file changed during reading.");r+=n.bytesRead}if((await a.read(Buffer.alloc(1),0,1,r)).bytesRead)throw new Error("Taskset draft file changed during reading.");return i}finally{await a.close()}}h(He,"readBytes");async function Ie(o,t){let e=await He(o,t);return ie(t,e)}h(Ie,"readTasksetDraftFile");async function Me(o){let t=[];async function e(a=""){for(let s of await Ye(C.join(o,a),{withFileTypes:!0})){let i=a?`${a}/${s.name}`:s.name;if(B.parse(i),s.isSymbolicLink())throw new Error("Taskset draft files cannot contain symbolic links.");if(s.isDirectory()){await e(i);continue}if(!s.isFile())throw new Error("Taskset draft files must be regular files.");if(t.length>=1e4)throw new Error("Taskset draft file inventory exceeds its limit.");let r=await be(await z(o,i));if(!r.isFile()||r.isSymbolicLink())throw new Error("Taskset draft files must be regular files.");t.push({path:i,sizeBytes:r.size,writable:_e(i)})}}return h(e,"visit"),await z(o,"taskset.json"),await e(),t.sort((a,s)=>a.path.localeCompare(s.path))}h(Me,"listTasksetDraftFiles");async function Oe(o,t,e){if(!_e(t.path))throw new Error("This file is managed by the Taskset forms or retained source history.");let a=null;try{a=await He(o,t.path)}catch(r){if(r.code!=="ENOENT")throw r}if((a?Xe(a):null)!==t.expectedFileHash)throw new Error("Taskset draft file changed. Reload it before saving.");if(!a&&t.content===null)throw new Error("Taskset draft file does not exist.");let s=t.content?oe(t.content):null,i=await z(o,t.path,!0);s?await J(i,s):await Re(i);try{return await e()}catch(r){throw a?await J(i,a):await Re(i,{force:!0}),r}}h(Oe,"mutateTasksetDraftFile");var E=u.object({schemaVersion:u.literal("openpond.tasksetDraftPointer.v1"),id:u.string().trim().min(1),profileId:u.string().trim().min(1),modelScope:y.shape.modelScope,status:u.enum(["draft","validating","needs_review","published"]),revision:u.number().int().positive(),workspacePath:u.string().trim().min(1),packageHash:u.string().regex(/^[a-f0-9]{64}$/),publishedTasksetRef:u.object({id:u.string().trim().min(1),revision:u.number().int().positive(),contentHash:u.string().trim().min(8)}).nullable(),createdAt:u.string().trim().min(1),updatedAt:u.string().trim().min(1)}),Fe=class extends he{static{h(this,"SqliteTasksetDraftStore")}async initializeModelTasksetDraft(t,e,a){await this.ready;let s=this.writeQueue.then(()=>P(this.home,async()=>{let i=this.database,r=await Pe({db:i,home:this.home,profileId:t,request:e,source:a});if(!r)return null;let n=h(()=>{let d=i.get("SELECT state FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[t,e.operationId]);if(d?.state==="deleted")throw new Error("This Taskset draft was deleted.");let l=i.get("SELECT payload FROM taskset_drafts WHERE id = ?",[r.draft.id]);if(!l){if(d?.state==="ready")throw new Error("The initialized Taskset draft is unavailable.");return!1}let c=E.parse(JSON.parse(l.payload));if(c.profileId!==t||c.modelScope?.source?.requestHash!==r.draft.modelScope?.source?.requestHash)throw new Error("Taskset draft identity conflicts with its initialization.");return!0},"completed"),f=this.workspacePath(r.draft.id);await Se({home:this.home,initialized:r,workspacePath:f,completed:n,retainHash:h(d=>{let l=i.get("SELECT payload FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[t,e.operationId]),c=b.parse(JSON.parse(l.payload));if(c.workspaceHash&&c.workspaceHash!==d.workspaceHash)throw new Error("Taskset draft initialization produced different files on retry.");i.run("UPDATE model_taskset_draft_operations SET payload = ? WHERE profile_id = ? AND operation_id = ? AND state = 'prepared'",[JSON.stringify(d),t,e.operationId])},"retainHash")}),i.exec("BEGIN IMMEDIATE");try{if(!n()){let d=i.get("SELECT payload FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[t,e.operationId]),l=b.parse(JSON.parse(d.payload)),c=l.draft,k=E.parse({schemaVersion:"openpond.tasksetDraftPointer.v1",id:c.id,profileId:t,modelScope:c.modelScope,status:c.status,revision:c.revision,workspacePath:f,packageHash:l.workspaceHash,publishedTasksetRef:c.publishedTasksetRef,createdAt:c.createdAt,updatedAt:c.updatedAt});i.run("INSERT INTO taskset_drafts (id, profile_id, status, revision, payload, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[c.id,t,c.status,c.revision,JSON.stringify(k),c.createdAt,c.updatedAt]),i.run("UPDATE model_taskset_draft_operations SET state = 'ready' WHERE profile_id = ? AND operation_id = ?",[t,e.operationId])}i.exec("COMMIT")}catch(d){throw i.exec("ROLLBACK"),d}let p=i.get("SELECT payload FROM taskset_drafts WHERE id = ?",[r.draft.id]);return this.draftFromStoredPayload(JSON.parse(p.payload))}));return this.writeQueue=s.then(()=>{},()=>{}),s}async saveTasksetDraft(t,e,a={}){let s=y.parse(t);await this.ready;let i=this.writeQueue.then(()=>P(this.home,async()=>{let r=this.database.get("SELECT payload FROM taskset_drafts WHERE id = ?",[s.id]),n=r?E.safeParse(JSON.parse(r.payload)):null;if(n?.success){if(n.data.profileId!==s.profileId)throw new Error("Taskset draft profile cannot change.");if(m(n.data.modelScope?{...n.data.modelScope,expectedModelRevision:0}:null)!==m(s.modelScope?{...s.modelScope,expectedModelRevision:0}:null)||!a.refreshModelRevision&&m(n.data.modelScope)!==m(s.modelScope))throw new Error("Taskset draft Model ownership cannot change.");if(n.data.status==="published")throw new Error("Published Taskset drafts are immutable. Initialize a new draft to revise the Taskset.");if(s.revision<n.data.revision||e!==void 0&&n.data.revision!==e)throw new Error("Taskset draft changed before saving. Refresh before saving.")}else if(e!==void 0)throw new Error("Taskset draft is unavailable for saving.");if((!n?.success||a.refreshModelRevision)&&s.modelScope){let c=this.database.get("SELECT payload FROM model_projects WHERE id = ? AND profile_id = ?",[s.modelScope.modelId,s.profileId]);if(!c)throw new Error("Taskset draft Model was not found in this Profile.");if(S.parse(JSON.parse(c.payload)).revision!==s.modelScope.expectedModelRevision)throw new Error("Taskset draft Model changed. Refresh before editing.")}let f=this.workspacePath(s.id),d=(await H(s,f)).draft,l=E.parse({schemaVersion:"openpond.tasksetDraftPointer.v1",id:d.id,profileId:d.profileId,modelScope:d.modelScope,status:d.status,revision:d.revision,workspacePath:f,packageHash:await g(f),publishedTasksetRef:d.publishedTasksetRef,createdAt:d.createdAt,updatedAt:d.updatedAt});return await this.savePointer(l,!0),d}));return this.writeQueue=i.then(()=>{},()=>{}),i}async importTasksetDraftPackage(t){let e=I.resolve(t.packagePath),s=(await st(e)).isDirectory()?e:I.dirname(e);await Ne(s);let i=await g(s),r=await $(s),n=await this.getTasksetDraft(r.id);if(n){let c=n.metadata.importedTasksetPackage;if(c&&typeof c=="object"&&!Array.isArray(c)&&c.packageHash===i&&n.profileId===t.profileId)return n;throw new Error(`Taskset draft ${r.id} already exists. Import a package with a distinct Taskset id.`)}let f=y.parse({...r,profileId:t.profileId,modelScope:null,status:"draft",revision:1,publishedTasksetRef:null,metadata:{...r.metadata,importedTasksetPackage:{packageHash:i,importedAt:new Date().toISOString()}},updatedAt:new Date().toISOString()}),p=this.workspacePath(f.id),d=`${p}.import-${process.pid}-${Date.now()}`;await tt(I.dirname(p),{recursive:!0});try{await et(s,d,{recursive:!0,errorOnExist:!0,force:!1,preserveTimestamps:!0}),await H(f,d),await Q(d,p)}catch(c){throw await Ae(d,{recursive:!0,force:!0}),c}let l=E.parse({schemaVersion:"openpond.tasksetDraftPointer.v1",id:f.id,profileId:f.profileId,status:f.status,revision:f.revision,workspacePath:p,packageHash:await g(p),publishedTasksetRef:f.publishedTasksetRef,createdAt:f.createdAt,updatedAt:f.updatedAt});return await this.savePointer(l),this.draftFromStoredPayload(l)}async materializePublishedTasksetPackage(t){let e=await this.getTasksetDraftWorkspace(t.draftId);if(!e)throw new Error(`Taskset draft ${t.draftId} workspace was not found.`);if(t.taskset.metadata.sourcePackageHash!==void 0&&t.taskset.metadata.sourcePackageHash!==e.packageHash)throw new Error("Taskset draft files changed before publication. Refresh before publishing.");let a=`draft-${m({taskset:t.taskset,packageHash:e.packageHash})}`,s=await ke(t.taskset,e.workspacePath),i=T.parse({...s.taskset,metadata:{...s.taskset.metadata,sourcePackageHash:e.packageHash},environment:{...s.taskset.environment,metadata:{...s.taskset.environment.metadata,runtimeSourceTasksetId:a}}}),r=T.parse({...i,contentHash:_(i)}),n=await x(this.home,{taskset:r,generatedFiles:s.generatedFiles},a,{source:{directory:e.workspacePath,packageHash:e.packageHash},verify:h(p=>L(p,r),"verify")}),f=await this.getTasksetDraft(t.draftId);return f?.modelScope?.source?De({home:this.home,directory:n,taskset:r,preparation:f.modelScope.source}):{directory:n,taskset:r}}async finalizeTasksetDraftPublication(t){await this.ready;let e=y.parse(t.draft),a=T.parse(t.taskset),s=e.modelScope?.source?.authoringGraph==="bound"&&typeof a.metadata.importedPackageHash=="string"?await D(this.home,a.metadata.importedPackageHash):null,i=this.writeQueue.then(()=>P(this.home,async()=>{let r=this.database.get("SELECT payload FROM taskset_drafts WHERE id = ?",[e.id]);if(!r)throw new Error("Taskset draft was deleted before publication.");let n=E.parse(JSON.parse(r.payload));if(n.profileId!==e.profileId||a.profileId!==e.profileId)throw new Error("Taskset publication belongs to another Profile.");if(m(n.modelScope)!==m(e.modelScope))throw new Error("Taskset draft Model ownership cannot change.");if(n.status==="published"&&n.publishedTasksetRef){let c=n.publishedTasksetRef,k=this.database.get("SELECT payload FROM taskset_revisions WHERE taskset_id = ? AND revision = ? AND content_hash = ?",[c.id,c.revision,c.contentHash]);if(!k)throw new Error("Published draft lost its immutable Taskset revision.");return{draft:y.parse({...e,status:n.status,revision:n.revision,publishedTasksetRef:c,updatedAt:n.updatedAt}),taskset:T.parse(JSON.parse(k.payload))}}if(n.revision!==e.revision||a.metadata.sourcePackageHash!==t.packageHash)throw new Error("Taskset draft changed before publication. Refresh before publishing.");let f=n.modelScope?.source,p=f?.authoringGraph==="bound"&&a.metadata.modelTasksetDerivation&&typeof a.metadata.modelTasksetDerivation=="object"?{...a.metadata.modelTasksetDerivation,schemaVersion:f.lineage.schemaVersion}:a.metadata.modelTasksetAuthoring;if(f&&(a.id!==f.tasksetId||a.revision!==f.tasksetRevision||m(p)!==m(f.lineage)))throw new Error("Taskset publication differs from its retained source preparation.");let d=y.parse({...e,status:"published",revision:e.revision+1,publishedTasksetRef:{id:a.id,revision:a.revision,contentHash:a.contentHash},updatedAt:new Date().toISOString()}),l=E.parse({...n,status:d.status,revision:d.revision,publishedTasksetRef:d.publishedTasksetRef,updatedAt:d.updatedAt});return we(this.database,a,()=>{if(s&&ge(this.database,{package:s,taskset:a,generatedFiles:[]}),Ee(this.database,e,a,s),this.database.get("SELECT revision FROM taskset_drafts WHERE id = ?",[e.id])?.revision!==e.revision)throw new Error("Taskset draft changed during publication.");this.database.run("UPDATE taskset_drafts SET status = ?, revision = ?, payload = ?, updated_at = ? WHERE id = ?",[l.status,l.revision,JSON.stringify(l),l.updatedAt,e.id])}),{draft:d,taskset:a}}));return this.writeQueue=i.then(()=>{},()=>{}),i}async getTasksetDraft(t){let e=await this.getParsedPayload("SELECT payload FROM taskset_drafts WHERE id = ?",[t],a=>a);return e===null?null:this.draftFromStoredPayload(e)}async listTasksetDrafts(t){await this.ready,await this.writeQueue;let e=await this.all(t?"SELECT payload FROM taskset_drafts WHERE profile_id = ? ORDER BY updated_at DESC":"SELECT payload FROM taskset_drafts ORDER BY updated_at DESC",t?[t]:[]);return Promise.all(e.map(a=>this.draftFromStoredPayload(JSON.parse(a.payload))))}async readHumanPublishedTasksetDraft(t,e){let a=(await this.listTasksetDrafts(t)).filter(r=>r.status==="published"&&r.modelScope===null&&m(r.publishedTasksetRef)===m(e));if(a.length!==1)return null;let s=a[0],i=await this.getTasksetDraftWorkspace(s.id);return i?{draft:s,workspace:i}:null}async getTasksetDraftWorkspace(t){let e=await this.getParsedPayload("SELECT payload FROM taskset_drafts WHERE id = ?",[t],s=>s);if(e===null)return null;let a=await this.pointerFromStoredPayload(e);return{draftId:a.id,workspacePath:a.workspacePath,packageHash:await g(a.workspacePath)}}async deleteTasksetDraft(t){await this.ready;let e=this.writeQueue.then(()=>P(this.home,async()=>{let a=this.workspacePath(t),s=`${a}.delete-${Ze()}`,i=!1;try{await Q(a,s),i=!0}catch(r){if(r.code!=="ENOENT")throw r}try{this.database.exec("BEGIN IMMEDIATE");try{this.database.run("DELETE FROM taskset_drafts WHERE id = ?",[t]),this.database.run("UPDATE model_taskset_draft_operations SET state = 'deleted' WHERE draft_id = ?",[t]),this.database.exec("COMMIT")}catch(r){throw this.database.exec("ROLLBACK"),r}}catch(r){throw i&&await Q(s,a).catch(()=>{}),r}i&&await Ae(s,{recursive:!0,force:!0})}));this.writeQueue=e.catch(()=>{}),await e}async tasksetDraftFiles(t,e,a){return await this.ready,P(this.home,async()=>{let s=this.database.get("SELECT payload FROM taskset_drafts WHERE id = ? AND profile_id = ?",[e,t]);if(!s)throw new Error("Taskset draft was not found in this Profile.");let i=E.parse(JSON.parse(s.payload));if(a!==void 0){let n=await Ie(i.workspacePath,a);return{draftRevision:i.revision,file:{...n,writable:n.writable&&i.status!=="published"}}}let r=await Me(i.workspacePath);return{draftRevision:i.revision,files:r.map(n=>({...n,writable:n.writable&&i.status!=="published"}))}})}async saveTasksetDraftFile(t,e){let a=Z.parse(e);await this.ready;let s=this.writeQueue.then(()=>P(this.home,async()=>{let i=this.database.get("SELECT payload FROM taskset_drafts WHERE id = ? AND profile_id = ?",[a.draftId,t]);if(!i)throw new Error("Taskset draft was not found in this Profile.");let r=E.parse(JSON.parse(i.payload));if(r.status==="published")throw new Error("Published Taskset drafts are immutable.");if(r.revision!==a.expectedDraftRevision)throw new Error("Taskset draft changed. Reload before saving a file.");return Oe(r.workspacePath,a,async()=>{let n=E.parse({...r,revision:r.revision+1,packageHash:await g(r.workspacePath),updatedAt:new Date().toISOString()}),f=await this.draftFromStoredPayload(n);this.database.exec("BEGIN IMMEDIATE");try{if(this.database.get("SELECT revision FROM taskset_drafts WHERE id = ? AND profile_id = ?",[a.draftId,t])?.revision!==r.revision)throw new Error("Taskset draft changed during file saving.");this.database.run("UPDATE taskset_drafts SET revision = ?, payload = ?, updated_at = ? WHERE id = ?",[n.revision,JSON.stringify(n),n.updatedAt,n.id]),this.database.exec("COMMIT")}catch(p){throw this.database.exec("ROLLBACK"),p}return f})}));return this.writeQueue=s.then(()=>{},()=>{}),s}workspacePath(t){let e=m(t).slice(0,24);return I.join(this.home,"workspaces","tasksets",`taskset-${e}`)}async draftFromStoredPayload(t){let e=await this.pointerFromStoredPayload(t),a=await $(e.workspacePath);return y.parse({...a,id:e.id,profileId:e.profileId,modelScope:e.modelScope,status:e.status,revision:e.revision,publishedTasksetRef:e.publishedTasksetRef,createdAt:e.createdAt,updatedAt:e.updatedAt})}async pointerFromStoredPayload(t){let e=E.safeParse(t);if(e.success)return e.data;let a=y.parse(t);await this.saveTasksetDraft(a);let s=await this.getParsedPayload("SELECT payload FROM taskset_drafts WHERE id = ?",[a.id],E.parse);if(!s)throw new Error(`Taskset draft ${a.id} migration failed.`);return s}async savePointer(t,e=!1){await(e?this.run.bind(this):this.upsertPayload.bind(this))(`INSERT INTO taskset_drafts (id, profile_id, status, revision, payload, created_at, updated_at)
2
+ import"./chunk-W45RKGM6.js";import{a as we}from"./chunk-EIEZHFIW.js";import{e as Te,f as ge}from"./chunk-SDXFLO7J.js";import"./chunk-GLDYJM7O.js";import{h as x,j as L}from"./chunk-HCYX6RHP.js";import{d as F,f as me,g as ke,i as N,j as D,k as ue}from"./chunk-O72BSKSO.js";import{a as H,b as g,c as $}from"./chunk-DBK66CJP.js";import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as he}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import{d as de,e as ce,f as q,n as fe,p as le,q as pe}from"./chunk-XDQMGUWL.js";import{C as ne,k as y,l as se,m as re,o as ie,p as oe}from"./chunk-FTEOCCPB.js";import{Ib as A,U as ae,b as Y,c as X,ca as O,e as B,i as Z,ua as T,xa as _}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import{n as ee,x as S,y as te}from"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import{e as J,f as K}from"./chunk-I7AQMAQI.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import{N as j,O as M}from"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import{m}from"./chunk-KGNCKIFP.js";import{b as u}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as h}from"./chunk-FTQLQJQV.js";import{randomUUID as Ze}from"node:crypto";import{cp as et,mkdir as tt,readdir as at,rename as Q,rm as Ae,stat as st}from"node:fs/promises";import I from"node:path";function Ee(o,t,e,a){let s=t.modelScope;if(!s)return;let i=o.get("SELECT payload FROM model_projects WHERE id = ? AND profile_id = ?",[s.modelId,t.profileId]);if(!i)throw new Error("Taskset draft Model was not found in this Profile.");let r=S.parse(JSON.parse(i.payload)),n={id:e.id,revision:e.revision,contentHash:e.contentHash};return Te(o,{schemaVersion:"openpond.modelProjectSave.v1",operationId:`draft-publication:${m({draftId:t.id,revision:t.revision,scope:s,tasksetRef:n})}`,expectedRevision:s.expectedModelRevision,project:te.strip().parse({...r,trainingSetup:{...r.trainingSetup,tasksetRef:n,rewardBindingRef:e.metadata.rewardBinding===void 0?null:ee.parse(e.metadata.rewardBinding),tasksetRelease:null,recipe:null,...r.trainingSetup.evaluationTasksetRef&&r.trainingSetup.tasksetRef&&M(r.trainingSetup.evaluationTasksetRef,r.trainingSetup.tasksetRef)?{evaluationTasksetRef:n}:{}}})},null,a?.modelResources?{...a.modelResources,taskset:a.taskset,executionResources:{environment:a.environment,verifierSet:a.verifierSet}}:a??void 0)}h(Ee,"selectTasksetDraftModel");import{createHash as We,randomUUID as je}from"node:crypto";import{lstat as ve,mkdir as ye,readdir as Je,readFile as Be,rename as $e,rm as qe,writeFile as Ue}from"node:fs/promises";import R from"node:path";var b=le.extend({workspaceHash:u.string().regex(/^[a-f0-9]{64}$/).nullable()}).strict();async function Pe(o){let{db:t,profileId:e}=o,a=X.parse(o.request),s=h(()=>{let w=t.get("SELECT payload FROM model_projects WHERE id = ? AND profile_id = ?",[a.modelId,e]);if(!w)throw new Error("Taskset draft Model was not found in this Profile.");return S.parse(JSON.parse(w.payload))},"requireModel"),i=s(),r=m(a),n=t.get("SELECT request_hash, state, payload FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[e,a.operationId]);if(n){if(n.request_hash!==r)throw new Error("Taskset draft operation was reused with different input.");if(n.state==="deleted")throw new Error("This Taskset draft was deleted.");return b.parse(JSON.parse(n.payload))}if(!o.source)return null;if(i.revision!==a.expectedModelRevision)throw new Error("Model changed before draft initialization. Refresh before editing.");let f=i.trainingSetup.tasksetRef,p=f?t.get("SELECT payload FROM taskset_revisions WHERE taskset_id = ? AND revision = ? AND profile_id = ?",[f.id,f.revision,e]):null,d=p?T.parse(JSON.parse(p.payload)):null;if(!d||!f||d.contentHash!==f.contentHash)throw new Error("The selected source Taskset is unavailable.");let l=o.source,c=i.hosted?.apiOrigin?i.hosted.tasksets.find(w=>w.localTasksetId===d.id&&w.localTasksetHash===d.contentHash&&w.packageHash===l.contentHash&&w.releaseId===l.taskset.id&&w.releaseRevision===l.taskset.revision&&w.releaseHash===l.taskset.contentHash):null,k=typeof d.metadata.importedPackageHash=="string"?d.metadata.importedPackageHash:c?.packageHash;if(k?k!==l.contentHash:!M(j(A({taskset:d,adapterId:F(d)}).tasksetRelease),j(l.taskset)))throw new Error("Taskset draft package differs from its selected source.");let v=l.modelResources?ae.safeParse(l.taskset.metadata.modelTasksetDerivation):Y.safeParse(l.taskset.metadata.modelTasksetAuthoring),xe=c&&v.success&&v.data.owner.modelId===i.id?v.data.owner:{scopeId:e,modelId:i.id},Le=de({request:a,owner:xe,source:l}),Ce=pe({sourceDraft:ne(d),source:l,preparation:Le,expectedModelRevision:a.expectedModelRevision});await N(o.home,l);let G=b.parse({...Ce,workspaceHash:null}),ze=G.draft;t.exec("BEGIN IMMEDIATE");try{let w=t.get("SELECT request_hash FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[e,a.operationId]);if(w&&w.request_hash!==r)throw new Error("Taskset draft operation was reused with different input.");if(!w&&s().revision!==a.expectedModelRevision)throw new Error("Model changed during draft initialization. Refresh before editing.");t.run("INSERT INTO model_taskset_draft_operations (profile_id, operation_id, request_hash, draft_id, state, payload) VALUES (?, ?, ?, ?, 'prepared', ?) ON CONFLICT(profile_id, operation_id) DO NOTHING",[e,a.operationId,r,ze.id,JSON.stringify(G)]),t.exec("COMMIT")}catch(w){throw t.exec("ROLLBACK"),w}let W=t.get("SELECT request_hash, payload FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[e,a.operationId]);if(!W||W.request_hash!==r)throw new Error("Taskset draft operation was reused with different input.");return b.parse(JSON.parse(W.payload))}h(Pe,"prepareDraftInitialization");async function Se(o){let{initialized:t,workspacePath:e}=o;if(o.completed())return;if(t.workspaceHash)try{if(await ve(e),o.completed())return;if(await U(e),await g(e)!==t.workspaceHash)throw new Error("Prepared Taskset draft files changed before initialization completed.");return}catch(s){if(s.code!=="ENOENT")throw s}let a=`${e}.initializing-${je()}`;await ye(R.dirname(e),{recursive:!0});try{let s=t.draft.modelScope?.source;if(!s)throw new Error("Taskset draft lost its source preparation.");let i=await D(o.home,s.sourcePackageHash),r=new Map;for(let f of t.filePaths){let p=i.files.find(d=>d.asset.id===f.assetId);if(!p)throw new Error("Taskset draft source asset is missing.");for(let d of f.paths){if(d.includes("\\")||R.posix.isAbsolute(d)||d.split("/").some(k=>!k||k==="."||k===".."||k.startsWith(".env")))throw new Error("Taskset draft source path is invalid.");let l=r.get(d);if(l&&l!==p.asset.contentHash)throw new Error("Taskset draft source paths conflict.");if(l)continue;let c=R.join(a,d);await ye(R.dirname(c),{recursive:!0}),await Ue(c,O(p),{flag:"wx"}),r.set(d,p.asset.contentHash)}}await H(t.draft,a);for(let[f,p]of r)if(We("sha256").update(await Be(R.join(a,f))).digest("hex")!==p)throw new Error(`Taskset draft source asset conflicts with authoring file ${f}.`);let n=await g(a);if(o.retainHash({...t,workspaceHash:n}),o.completed())return;try{await $e(a,e)}catch(f){if(!["EEXIST","ENOTEMPTY"].includes(f.code??""))throw f;if(o.completed())return;if(await U(e),await g(e)!==n)throw new Error("Prepared Taskset draft files changed before initialization completed.")}}finally{await qe(a,{recursive:!0,force:!0})}}h(Se,"materializeDraftInitialization");async function U(o){let t=await ve(o);if(!t.isDirectory()||t.isSymbolicLink())throw new Error("Taskset draft source must be a regular directory.");for(let e of await Je(o,{withFileTypes:!0})){if(e.name.startsWith(".env")||e.isSymbolicLink())throw new Error("Taskset draft source contains a prohibited file.");if(e.isDirectory())await U(R.join(o,e.name));else if(!e.isFile())throw new Error("Taskset draft source must contain regular files.")}}h(U,"assertRegularTree");import Ve from"node:path";async function De(o){let t=A({taskset:o.taskset,adapterId:F(o.taskset)}),e=await me({root:o.directory,content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:t.tasksetRelease,environment:t.environmentRelease,verifierSet:t.verifierSetRelease},sources:q.parse(o.taskset.metadata.portableFileInventory??[])}),a=o.preparation.authoringGraph==="bound"?await D(o.home,o.preparation.sourcePackageHash):void 0,s=ce({preparation:o.preparation,edited:e,source:a});if(s.modelResources){let c=fe({package:s,profileId:o.taskset.profileId,name:o.taskset.name,createdAt:o.taskset.createdAt}),k=T.parse({...c.taskset,authoringProvenance:o.taskset.authoringProvenance,metadata:{...c.taskset.metadata,sourcePackageHash:o.taskset.metadata.sourcePackageHash}}),v=T.parse({...k,contentHash:_(k)});return await ue({home:o.home,...c,taskset:v}),{taskset:v,directory:Ve.join(o.home,"training","tasksets",String(v.environment.metadata.runtimeSourceTasksetId))}}let i=q.parse(o.taskset.metadata.portableFileInventory??[]),r=s.files.map(c=>({asset:c.asset,sourcePath:i.find(k=>k.asset.id===c.asset.id)?.sourcePath??c.asset.path})),n=s.taskset.environment.entrypoint==="openpond.javascript-environment.v1"?s.files.find(c=>c.asset.path==="environment/execution.json"):void 0,f=`model-draft-${m({packageHash:s.contentHash,taskset:o.taskset})}`,p=T.parse({...o.taskset,id:s.taskset.id,revision:s.taskset.revision,metadata:{...o.taskset.metadata,portableFileInventory:r,importedPackageHash:s.contentHash,derivedPortableMetadata:s.taskset.metadata},environment:{...o.taskset.environment,metadata:{...o.taskset.environment.metadata,runtimeSourceTasksetId:f,portableExecutionResources:{environment:s.environment,verifierSet:s.verifierSet}}}}),d=T.parse({...p,contentHash:_(p)}),l=await x(o.home,{taskset:d,generatedFiles:n?[{path:n.asset.path,role:"environment",content:new TextDecoder("utf-8",{fatal:!0}).decode(O(n))}]:[]},f,{source:{directory:o.directory,packageHash:await g(o.directory)},verify:h(c=>L(c,d),"verify")});return await N(o.home,s),{directory:l,taskset:d}}h(De,"materializeModelTasksetDraftPublication");import{constants as V}from"node:fs";import{createHash as Qe}from"node:crypto";import{lstat as be,mkdir as Ge,open as Ke,readdir as Ye,rm as Re}from"node:fs/promises";import C from"node:path";var P=h((o,t)=>K(C.join(o,"state","taskset-draft-writes"),t),"withTasksetDraftLock"),_e=re,Xe=h(o=>Qe("sha256").update(o).digest("hex"),"digest");async function z(o,t,e=!1){B.parse(t);let a=o;for(let s of["",...t.split("/").slice(0,-1)]){s&&(a=C.join(a,s)),e&&await Ge(a,{recursive:!1}).catch(r=>{if(r.code!=="EEXIST")throw r});let i=await be(a);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Taskset draft paths must use regular directories.")}return C.join(o,t)}h(z,"regularPath");async function He(o,t){let e=await z(o,t),a=await Ke(e,V.O_RDONLY|V.O_NOFOLLOW|V.O_NONBLOCK);try{let s=await a.stat();if(!s.isFile()||s.size>se)throw new Error("Taskset draft file must be a regular file within the 6 MB editing limit.");let i=Buffer.alloc(s.size),r=0;for(;r<i.length;){let n=await a.read(i,r,i.length-r,r);if(!n.bytesRead)throw new Error("Taskset draft file changed during reading.");r+=n.bytesRead}if((await a.read(Buffer.alloc(1),0,1,r)).bytesRead)throw new Error("Taskset draft file changed during reading.");return i}finally{await a.close()}}h(He,"readBytes");async function Ie(o,t){let e=await He(o,t);return ie(t,e)}h(Ie,"readTasksetDraftFile");async function Me(o){let t=[];async function e(a=""){for(let s of await Ye(C.join(o,a),{withFileTypes:!0})){let i=a?`${a}/${s.name}`:s.name;if(B.parse(i),s.isSymbolicLink())throw new Error("Taskset draft files cannot contain symbolic links.");if(s.isDirectory()){await e(i);continue}if(!s.isFile())throw new Error("Taskset draft files must be regular files.");if(t.length>=1e4)throw new Error("Taskset draft file inventory exceeds its limit.");let r=await be(await z(o,i));if(!r.isFile()||r.isSymbolicLink())throw new Error("Taskset draft files must be regular files.");t.push({path:i,sizeBytes:r.size,writable:_e(i)})}}return h(e,"visit"),await z(o,"taskset.json"),await e(),t.sort((a,s)=>a.path.localeCompare(s.path))}h(Me,"listTasksetDraftFiles");async function Oe(o,t,e){if(!_e(t.path))throw new Error("This file is managed by the Taskset forms or retained source history.");let a=null;try{a=await He(o,t.path)}catch(r){if(r.code!=="ENOENT")throw r}if((a?Xe(a):null)!==t.expectedFileHash)throw new Error("Taskset draft file changed. Reload it before saving.");if(!a&&t.content===null)throw new Error("Taskset draft file does not exist.");let s=t.content?oe(t.content):null,i=await z(o,t.path,!0);s?await J(i,s):await Re(i);try{return await e()}catch(r){throw a?await J(i,a):await Re(i,{force:!0}),r}}h(Oe,"mutateTasksetDraftFile");var E=u.object({schemaVersion:u.literal("openpond.tasksetDraftPointer.v1"),id:u.string().trim().min(1),profileId:u.string().trim().min(1),modelScope:y.shape.modelScope,status:u.enum(["draft","validating","needs_review","published"]),revision:u.number().int().positive(),workspacePath:u.string().trim().min(1),packageHash:u.string().regex(/^[a-f0-9]{64}$/),publishedTasksetRef:u.object({id:u.string().trim().min(1),revision:u.number().int().positive(),contentHash:u.string().trim().min(8)}).nullable(),createdAt:u.string().trim().min(1),updatedAt:u.string().trim().min(1)}),Fe=class extends he{static{h(this,"SqliteTasksetDraftStore")}async initializeModelTasksetDraft(t,e,a){await this.ready;let s=this.writeQueue.then(()=>P(this.home,async()=>{let i=this.database,r=await Pe({db:i,home:this.home,profileId:t,request:e,source:a});if(!r)return null;let n=h(()=>{let d=i.get("SELECT state FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[t,e.operationId]);if(d?.state==="deleted")throw new Error("This Taskset draft was deleted.");let l=i.get("SELECT payload FROM taskset_drafts WHERE id = ?",[r.draft.id]);if(!l){if(d?.state==="ready")throw new Error("The initialized Taskset draft is unavailable.");return!1}let c=E.parse(JSON.parse(l.payload));if(c.profileId!==t||c.modelScope?.source?.requestHash!==r.draft.modelScope?.source?.requestHash)throw new Error("Taskset draft identity conflicts with its initialization.");return!0},"completed"),f=this.workspacePath(r.draft.id);await Se({home:this.home,initialized:r,workspacePath:f,completed:n,retainHash:h(d=>{let l=i.get("SELECT payload FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[t,e.operationId]),c=b.parse(JSON.parse(l.payload));if(c.workspaceHash&&c.workspaceHash!==d.workspaceHash)throw new Error("Taskset draft initialization produced different files on retry.");i.run("UPDATE model_taskset_draft_operations SET payload = ? WHERE profile_id = ? AND operation_id = ? AND state = 'prepared'",[JSON.stringify(d),t,e.operationId])},"retainHash")}),i.exec("BEGIN IMMEDIATE");try{if(!n()){let d=i.get("SELECT payload FROM model_taskset_draft_operations WHERE profile_id = ? AND operation_id = ?",[t,e.operationId]),l=b.parse(JSON.parse(d.payload)),c=l.draft,k=E.parse({schemaVersion:"openpond.tasksetDraftPointer.v1",id:c.id,profileId:t,modelScope:c.modelScope,status:c.status,revision:c.revision,workspacePath:f,packageHash:l.workspaceHash,publishedTasksetRef:c.publishedTasksetRef,createdAt:c.createdAt,updatedAt:c.updatedAt});i.run("INSERT INTO taskset_drafts (id, profile_id, status, revision, payload, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[c.id,t,c.status,c.revision,JSON.stringify(k),c.createdAt,c.updatedAt]),i.run("UPDATE model_taskset_draft_operations SET state = 'ready' WHERE profile_id = ? AND operation_id = ?",[t,e.operationId])}i.exec("COMMIT")}catch(d){throw i.exec("ROLLBACK"),d}let p=i.get("SELECT payload FROM taskset_drafts WHERE id = ?",[r.draft.id]);return this.draftFromStoredPayload(JSON.parse(p.payload))}));return this.writeQueue=s.then(()=>{},()=>{}),s}async saveTasksetDraft(t,e,a={}){let s=y.parse(t);await this.ready;let i=this.writeQueue.then(()=>P(this.home,async()=>{let r=this.database.get("SELECT payload FROM taskset_drafts WHERE id = ?",[s.id]),n=r?E.safeParse(JSON.parse(r.payload)):null;if(n?.success){if(n.data.profileId!==s.profileId)throw new Error("Taskset draft profile cannot change.");if(m(n.data.modelScope?{...n.data.modelScope,expectedModelRevision:0}:null)!==m(s.modelScope?{...s.modelScope,expectedModelRevision:0}:null)||!a.refreshModelRevision&&m(n.data.modelScope)!==m(s.modelScope))throw new Error("Taskset draft Model ownership cannot change.");if(n.data.status==="published")throw new Error("Published Taskset drafts are immutable. Initialize a new draft to revise the Taskset.");if(s.revision<n.data.revision||e!==void 0&&n.data.revision!==e)throw new Error("Taskset draft changed before saving. Refresh before saving.")}else if(e!==void 0)throw new Error("Taskset draft is unavailable for saving.");if((!n?.success||a.refreshModelRevision)&&s.modelScope){let c=this.database.get("SELECT payload FROM model_projects WHERE id = ? AND profile_id = ?",[s.modelScope.modelId,s.profileId]);if(!c)throw new Error("Taskset draft Model was not found in this Profile.");if(S.parse(JSON.parse(c.payload)).revision!==s.modelScope.expectedModelRevision)throw new Error("Taskset draft Model changed. Refresh before editing.")}let f=this.workspacePath(s.id),d=(await H(s,f)).draft,l=E.parse({schemaVersion:"openpond.tasksetDraftPointer.v1",id:d.id,profileId:d.profileId,modelScope:d.modelScope,status:d.status,revision:d.revision,workspacePath:f,packageHash:await g(f),publishedTasksetRef:d.publishedTasksetRef,createdAt:d.createdAt,updatedAt:d.updatedAt});return await this.savePointer(l,!0),d}));return this.writeQueue=i.then(()=>{},()=>{}),i}async importTasksetDraftPackage(t){let e=I.resolve(t.packagePath),s=(await st(e)).isDirectory()?e:I.dirname(e);await Ne(s);let i=await g(s),r=await $(s),n=await this.getTasksetDraft(r.id);if(n){let c=n.metadata.importedTasksetPackage;if(c&&typeof c=="object"&&!Array.isArray(c)&&c.packageHash===i&&n.profileId===t.profileId)return n;throw new Error(`Taskset draft ${r.id} already exists. Import a package with a distinct Taskset id.`)}let f=y.parse({...r,profileId:t.profileId,modelScope:null,status:"draft",revision:1,publishedTasksetRef:null,metadata:{...r.metadata,importedTasksetPackage:{packageHash:i,importedAt:new Date().toISOString()}},updatedAt:new Date().toISOString()}),p=this.workspacePath(f.id),d=`${p}.import-${process.pid}-${Date.now()}`;await tt(I.dirname(p),{recursive:!0});try{await et(s,d,{recursive:!0,errorOnExist:!0,force:!1,preserveTimestamps:!0}),await H(f,d),await Q(d,p)}catch(c){throw await Ae(d,{recursive:!0,force:!0}),c}let l=E.parse({schemaVersion:"openpond.tasksetDraftPointer.v1",id:f.id,profileId:f.profileId,status:f.status,revision:f.revision,workspacePath:p,packageHash:await g(p),publishedTasksetRef:f.publishedTasksetRef,createdAt:f.createdAt,updatedAt:f.updatedAt});return await this.savePointer(l),this.draftFromStoredPayload(l)}async materializePublishedTasksetPackage(t){let e=await this.getTasksetDraftWorkspace(t.draftId);if(!e)throw new Error(`Taskset draft ${t.draftId} workspace was not found.`);if(t.taskset.metadata.sourcePackageHash!==void 0&&t.taskset.metadata.sourcePackageHash!==e.packageHash)throw new Error("Taskset draft files changed before publication. Refresh before publishing.");let a=`draft-${m({taskset:t.taskset,packageHash:e.packageHash})}`,s=await ke(t.taskset,e.workspacePath),i=T.parse({...s.taskset,metadata:{...s.taskset.metadata,sourcePackageHash:e.packageHash},environment:{...s.taskset.environment,metadata:{...s.taskset.environment.metadata,runtimeSourceTasksetId:a}}}),r=T.parse({...i,contentHash:_(i)}),n=await x(this.home,{taskset:r,generatedFiles:s.generatedFiles},a,{source:{directory:e.workspacePath,packageHash:e.packageHash},verify:h(p=>L(p,r),"verify")}),f=await this.getTasksetDraft(t.draftId);return f?.modelScope?.source?De({home:this.home,directory:n,taskset:r,preparation:f.modelScope.source}):{directory:n,taskset:r}}async finalizeTasksetDraftPublication(t){await this.ready;let e=y.parse(t.draft),a=T.parse(t.taskset),s=e.modelScope?.source?.authoringGraph==="bound"&&typeof a.metadata.importedPackageHash=="string"?await D(this.home,a.metadata.importedPackageHash):null,i=this.writeQueue.then(()=>P(this.home,async()=>{let r=this.database.get("SELECT payload FROM taskset_drafts WHERE id = ?",[e.id]);if(!r)throw new Error("Taskset draft was deleted before publication.");let n=E.parse(JSON.parse(r.payload));if(n.profileId!==e.profileId||a.profileId!==e.profileId)throw new Error("Taskset publication belongs to another Profile.");if(m(n.modelScope)!==m(e.modelScope))throw new Error("Taskset draft Model ownership cannot change.");if(n.status==="published"&&n.publishedTasksetRef){let c=n.publishedTasksetRef,k=this.database.get("SELECT payload FROM taskset_revisions WHERE taskset_id = ? AND revision = ? AND content_hash = ?",[c.id,c.revision,c.contentHash]);if(!k)throw new Error("Published draft lost its immutable Taskset revision.");return{draft:y.parse({...e,status:n.status,revision:n.revision,publishedTasksetRef:c,updatedAt:n.updatedAt}),taskset:T.parse(JSON.parse(k.payload))}}if(n.revision!==e.revision||a.metadata.sourcePackageHash!==t.packageHash)throw new Error("Taskset draft changed before publication. Refresh before publishing.");let f=n.modelScope?.source,p=f?.authoringGraph==="bound"&&a.metadata.modelTasksetDerivation&&typeof a.metadata.modelTasksetDerivation=="object"?{...a.metadata.modelTasksetDerivation,schemaVersion:f.lineage.schemaVersion}:a.metadata.modelTasksetAuthoring;if(f&&(a.id!==f.tasksetId||a.revision!==f.tasksetRevision||m(p)!==m(f.lineage)))throw new Error("Taskset publication differs from its retained source preparation.");let d=y.parse({...e,status:"published",revision:e.revision+1,publishedTasksetRef:{id:a.id,revision:a.revision,contentHash:a.contentHash},updatedAt:new Date().toISOString()}),l=E.parse({...n,status:d.status,revision:d.revision,publishedTasksetRef:d.publishedTasksetRef,updatedAt:d.updatedAt});return we(this.database,a,()=>{if(s&&ge(this.database,{package:s,taskset:a,generatedFiles:[]}),Ee(this.database,e,a,s),this.database.get("SELECT revision FROM taskset_drafts WHERE id = ?",[e.id])?.revision!==e.revision)throw new Error("Taskset draft changed during publication.");this.database.run("UPDATE taskset_drafts SET status = ?, revision = ?, payload = ?, updated_at = ? WHERE id = ?",[l.status,l.revision,JSON.stringify(l),l.updatedAt,e.id])}),{draft:d,taskset:a}}));return this.writeQueue=i.then(()=>{},()=>{}),i}async getTasksetDraft(t){let e=await this.getParsedPayload("SELECT payload FROM taskset_drafts WHERE id = ?",[t],a=>a);return e===null?null:this.draftFromStoredPayload(e)}async listTasksetDrafts(t){await this.ready,await this.writeQueue;let e=await this.all(t?"SELECT payload FROM taskset_drafts WHERE profile_id = ? ORDER BY updated_at DESC":"SELECT payload FROM taskset_drafts ORDER BY updated_at DESC",t?[t]:[]);return Promise.all(e.map(a=>this.draftFromStoredPayload(JSON.parse(a.payload))))}async readHumanPublishedTasksetDraft(t,e){let a=(await this.listTasksetDrafts(t)).filter(r=>r.status==="published"&&r.modelScope===null&&m(r.publishedTasksetRef)===m(e));if(a.length!==1)return null;let s=a[0],i=await this.getTasksetDraftWorkspace(s.id);return i?{draft:s,workspace:i}:null}async getTasksetDraftWorkspace(t){let e=await this.getParsedPayload("SELECT payload FROM taskset_drafts WHERE id = ?",[t],s=>s);if(e===null)return null;let a=await this.pointerFromStoredPayload(e);return{draftId:a.id,workspacePath:a.workspacePath,packageHash:await g(a.workspacePath)}}async deleteTasksetDraft(t){await this.ready;let e=this.writeQueue.then(()=>P(this.home,async()=>{let a=this.workspacePath(t),s=`${a}.delete-${Ze()}`,i=!1;try{await Q(a,s),i=!0}catch(r){if(r.code!=="ENOENT")throw r}try{this.database.exec("BEGIN IMMEDIATE");try{this.database.run("DELETE FROM taskset_drafts WHERE id = ?",[t]),this.database.run("UPDATE model_taskset_draft_operations SET state = 'deleted' WHERE draft_id = ?",[t]),this.database.exec("COMMIT")}catch(r){throw this.database.exec("ROLLBACK"),r}}catch(r){throw i&&await Q(s,a).catch(()=>{}),r}i&&await Ae(s,{recursive:!0,force:!0})}));this.writeQueue=e.catch(()=>{}),await e}async tasksetDraftFiles(t,e,a){return await this.ready,P(this.home,async()=>{let s=this.database.get("SELECT payload FROM taskset_drafts WHERE id = ? AND profile_id = ?",[e,t]);if(!s)throw new Error("Taskset draft was not found in this Profile.");let i=E.parse(JSON.parse(s.payload));if(a!==void 0){let n=await Ie(i.workspacePath,a);return{draftRevision:i.revision,file:{...n,writable:n.writable&&i.status!=="published"}}}let r=await Me(i.workspacePath);return{draftRevision:i.revision,files:r.map(n=>({...n,writable:n.writable&&i.status!=="published"}))}})}async saveTasksetDraftFile(t,e){let a=Z.parse(e);await this.ready;let s=this.writeQueue.then(()=>P(this.home,async()=>{let i=this.database.get("SELECT payload FROM taskset_drafts WHERE id = ? AND profile_id = ?",[a.draftId,t]);if(!i)throw new Error("Taskset draft was not found in this Profile.");let r=E.parse(JSON.parse(i.payload));if(r.status==="published")throw new Error("Published Taskset drafts are immutable.");if(r.revision!==a.expectedDraftRevision)throw new Error("Taskset draft changed. Reload before saving a file.");return Oe(r.workspacePath,a,async()=>{let n=E.parse({...r,revision:r.revision+1,packageHash:await g(r.workspacePath),updatedAt:new Date().toISOString()}),f=await this.draftFromStoredPayload(n);this.database.exec("BEGIN IMMEDIATE");try{if(this.database.get("SELECT revision FROM taskset_drafts WHERE id = ? AND profile_id = ?",[a.draftId,t])?.revision!==r.revision)throw new Error("Taskset draft changed during file saving.");this.database.run("UPDATE taskset_drafts SET revision = ?, payload = ?, updated_at = ? WHERE id = ?",[n.revision,JSON.stringify(n),n.updatedAt,n.id]),this.database.exec("COMMIT")}catch(p){throw this.database.exec("ROLLBACK"),p}return f})}));return this.writeQueue=s.then(()=>{},()=>{}),s}workspacePath(t){let e=m(t).slice(0,24);return I.join(this.home,"workspaces","tasksets",`taskset-${e}`)}async draftFromStoredPayload(t){let e=await this.pointerFromStoredPayload(t),a=await $(e.workspacePath);return y.parse({...a,id:e.id,profileId:e.profileId,modelScope:e.modelScope,status:e.status,revision:e.revision,publishedTasksetRef:e.publishedTasksetRef,createdAt:e.createdAt,updatedAt:e.updatedAt})}async pointerFromStoredPayload(t){let e=E.safeParse(t);if(e.success)return e.data;let a=y.parse(t);await this.saveTasksetDraft(a);let s=await this.getParsedPayload("SELECT payload FROM taskset_drafts WHERE id = ?",[a.id],E.parse);if(!s)throw new Error(`Taskset draft ${a.id} migration failed.`);return s}async savePointer(t,e=!1){await(e?this.run.bind(this):this.upsertPayload.bind(this))(`INSERT INTO taskset_drafts (id, profile_id, status, revision, payload, created_at, updated_at)
3
3
  VALUES (?, ?, ?, ?, ?, ?, ?)
4
4
  ON CONFLICT(id) DO UPDATE SET
5
5
  profile_id = excluded.profile_id,
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as A}from"./chunk-EIEZHFIW.js";import{a as M}from"./chunk-OLLLZVHF.js";import{d as N}from"./chunk-KG325WTN.js";import"./chunk-DMFUEUAZ.js";import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as L}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import{A as g,B as C,h as l,i as k,l as _,r as O,s as T,t as w,u as f,v as I}from"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import{B as p,sa as S,ua as m}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as o}from"./chunk-FTQLQJQV.js";function h(s,t,a,e,n,r,d){return{schemaVersion:"openpond.trainingChatSearchResult.v1",query:s,offset:t,limit:a,total:e,hasMore:t+n.length<e,indexedChats:r,totalChats:d,indexing:r<d,entries:n.map(i=>({sessionId:i.session_id,title:i.title,updatedAt:i.updated_at,snippet:i.snippet?.trim()||null}))}}o(h,"trainingChatSearchResult");function P(s){let t=s.normalize("NFKC").match(/[\p{L}\p{N}_]+/gu)?.slice(0,24)??[];return t.length?t.map(a=>`"${a.replaceAll('"','""')}"*`).join(" AND "):null}o(P,"trainingChatFtsQuery");function D(s,t,a){let e=s.get(t)??[];e.push(a),s.set(t,e)}o(D,"appendTrainingChatSearchText");var F=class extends L{static{o(this,"SqliteTrainingStore")}async trainingChatSearchSignatures(t){await this.ready,await this.writeQueue;let a=await this.all("SELECT session_id, signature FROM training_chat_search_documents WHERE source = ?",[t]);return new Map(a.map(e=>[e.session_id,e.signature]))}async openPondTrainingChatSearchEvidence(t){await this.ready,await this.writeQueue;let a=[...new Set(t)].slice(0,500);if(!a.length)return[];let e=a.map(()=>"?").join(", "),[n,r,d]=await Promise.all([this.all(`SELECT payload FROM projection_session_shells WHERE id IN (${e})`,a),this.all(`SELECT session_id, payload FROM turns WHERE session_id IN (${e}) ORDER BY sort_index ASC`,a),this.all(`SELECT session_id, payload FROM events
2
+ import{a as A}from"./chunk-EIEZHFIW.js";import{a as M}from"./chunk-OLLLZVHF.js";import{d as N}from"./chunk-KG325WTN.js";import"./chunk-DMFUEUAZ.js";import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as L}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import{A as g,B as C,h as l,i as k,l as _,r as O,s as T,t as w,u as f,v as I}from"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import{B as p,sa as S,ua as m}from"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as o}from"./chunk-FTQLQJQV.js";function h(s,t,a,e,n,r,d){return{schemaVersion:"openpond.trainingChatSearchResult.v1",query:s,offset:t,limit:a,total:e,hasMore:t+n.length<e,indexedChats:r,totalChats:d,indexing:r<d,entries:n.map(i=>({sessionId:i.session_id,title:i.title,updatedAt:i.updated_at,snippet:i.snippet?.trim()||null}))}}o(h,"trainingChatSearchResult");function P(s){let t=s.normalize("NFKC").match(/[\p{L}\p{N}_]+/gu)?.slice(0,24)??[];return t.length?t.map(a=>`"${a.replaceAll('"','""')}"*`).join(" AND "):null}o(P,"trainingChatFtsQuery");function D(s,t,a){let e=s.get(t)??[];e.push(a),s.set(t,e)}o(D,"appendTrainingChatSearchText");var F=class extends L{static{o(this,"SqliteTrainingStore")}async trainingChatSearchSignatures(t){await this.ready,await this.writeQueue;let a=await this.all("SELECT session_id, signature FROM training_chat_search_documents WHERE source = ?",[t]);return new Map(a.map(e=>[e.session_id,e.signature]))}async openPondTrainingChatSearchEvidence(t){await this.ready,await this.writeQueue;let a=[...new Set(t)].slice(0,500);if(!a.length)return[];let e=a.map(()=>"?").join(", "),[n,r,d]=await Promise.all([this.all(`SELECT payload FROM projection_session_shells WHERE id IN (${e})`,a),this.all(`SELECT session_id, payload FROM turns WHERE session_id IN (${e}) ORDER BY sort_index ASC`,a),this.all(`SELECT session_id, payload FROM events
3
3
  WHERE name = 'assistant.delta' AND session_id IN (${e})
4
4
  ORDER BY sequence ASC`,a)]),i=new Map;for(let u of r){let c=JSON.parse(u.payload);c.prompt.trim()&&D(i,u.session_id,c.prompt)}for(let u of d){let c=JSON.parse(u.payload);c.output?.trim()&&D(i,u.session_id,c.output)}return n.map(u=>{let c=M(JSON.parse(u.payload));return{session:c,body:i.get(c.id)?.join(`
5
5
  `)??""}})}async syncTrainingChatSearchDocuments(t,a){await this.ready;let e=this.writeQueue.then(async()=>{let n=await this.all("SELECT session_id, signature FROM training_chat_search_documents WHERE source = ?",[t]),r=new Map(n.map(i=>[i.session_id,i.signature])),d=new Set(a.map(i=>i.sessionId));await this.exec("BEGIN IMMEDIATE");try{for(let i of r.keys())d.has(i)||(await this.run("DELETE FROM training_chat_search_fts WHERE session_id = ?",[i]),await this.run("DELETE FROM training_chat_search_documents WHERE session_id = ?",[i]));for(let i of a)r.get(i.sessionId)!==i.signature&&(await this.run("DELETE FROM training_chat_search_fts WHERE session_id = ?",[i.sessionId]),await this.run(`INSERT INTO training_chat_search_documents (session_id, source, signature, title, updated_at, eligible, body_indexed)
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as u}from"./chunk-OUVIWDL2.js";import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{$ as E,D as S,aa as c,ba as o,ea as _,ga as s,ha as T,na as p,oa as g}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as f}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as d}from"./chunk-FTQLQJQV.js";var l="('openpond_managed')",P=class extends f{static{d(this,"SqliteTrainingJobsStore")}async saveModelProject(t){let a=E.parse(t);return await this.upsertPayload(`INSERT INTO model_projects (id, profile_id, payload, created_at, updated_at) VALUES (?, ?, ?, ?, ?)
2
+ import{a as u}from"./chunk-OUVIWDL2.js";import"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{$ as E,D as S,aa as c,ba as o,ea as _,ga as s,ha as T,na as p,oa as g}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as f}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as d}from"./chunk-FTQLQJQV.js";var l="('openpond_managed')",P=class extends f{static{d(this,"SqliteTrainingJobsStore")}async saveModelProject(t){let a=E.parse(t);return await this.upsertPayload(`INSERT INTO model_projects (id, profile_id, payload, created_at, updated_at) VALUES (?, ?, ?, ?, ?)
3
3
  ON CONFLICT(id) DO UPDATE SET profile_id = excluded.profile_id, payload = excluded.payload, updated_at = excluded.updated_at`,[a.id,a.profileId,JSON.stringify(a),a.createdAt,a.updatedAt]),a}async getModelProject(t){return this.getParsedPayload("SELECT payload FROM model_projects WHERE id = ?",[t],h)}async listModelProjects(t){return this.listParsedPayloads(t?"SELECT payload FROM model_projects WHERE profile_id = ? ORDER BY updated_at DESC":"SELECT payload FROM model_projects ORDER BY updated_at DESC",t?[t]:[],h)}async saveTrainingPlan(t){let a=c.parse(t),e=await this.getTrainingPlan(a.id);if(e&&e.contentHash!==a.contentHash)throw new Error(`Training Plan ${a.id} is immutable and already has different content.`);return await this.upsertPayload(`INSERT INTO training_plans (id, taskset_id, destination_id, payload, created_at) VALUES (?, ?, ?, ?, ?)
4
4
  ON CONFLICT(id) DO UPDATE SET taskset_id = excluded.taskset_id, destination_id = excluded.destination_id, payload = excluded.payload`,[a.id,a.tasksetId,a.destinationId,JSON.stringify(a),a.createdAt]),a}async listTrainingPlans(t){return this.listParsedPayloads(t?`SELECT payload FROM training_plans WHERE taskset_id = ? AND destination_id IN ${l} ORDER BY created_at DESC`:`SELECT payload FROM training_plans WHERE destination_id IN ${l} ORDER BY created_at DESC`,t?[t]:[],c.parse)}async getTrainingPlan(t){return this.getParsedPayload(`SELECT payload FROM training_plans WHERE id = ? AND destination_id IN ${l}`,[t],c.parse)}async saveTrainingBundle(t){let a=o.parse(t);return await this.upsertPayload(`INSERT INTO training_bundles (id, plan_id, content_hash, payload, created_at) VALUES (?, ?, ?, ?, ?)
5
5
  ON CONFLICT(id) DO UPDATE SET plan_id = excluded.plan_id, content_hash = excluded.content_hash, payload = excluded.payload`,[a.id,a.planId,a.contentHash,JSON.stringify(a),a.createdAt]),a}async getTrainingBundle(t){return this.getParsedPayload("SELECT payload FROM training_bundles WHERE id = ?",[t],o.parse)}async listTrainingBundles(t){return this.listParsedPayloads(t?"SELECT payload FROM training_bundles WHERE plan_id = ? ORDER BY created_at DESC":"SELECT payload FROM training_bundles ORDER BY created_at DESC",t?[t]:[],o.parse)}async findTrainingBundleByPlanAndHash(t,a){return this.getParsedPayload("SELECT payload FROM training_bundles WHERE plan_id = ? AND content_hash = ?",[t,a],o.parse)}async saveTrainingJob(t){let a=s.parse(t),e=await this.getTrainingJob(a.id),n=e?.metadata.activityAuthority,r=a.metadata.activityAuthority;if(n!==void 0){let A=u.parse(n);if(r!==void 0&&JSON.stringify(u.parse(r))!==JSON.stringify(A))throw new Error("Training activity ownership cannot change during reconciliation.");a={...a,metadata:{...a.metadata,activityAuthority:A}}}else if(r!==void 0){if(e)throw new Error("Historical training activity cannot be assigned a guessed owner.");a={...a,metadata:{...a.metadata,activityAuthority:u.parse(r)}}}await this.upsertPayload(`INSERT INTO training_jobs (id, plan_id, destination_id, status, payload, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as O}from"./chunk-YOQRYNLP.js";import{Na as P}from"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{U as S,ga as C,h as c,m as p,o as E,p as y,qa as u,r as R,u as m,w as _}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as M}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as l}from"./chunk-FTQLQJQV.js";function w(r,t,e){let a=P.safeParse(e.metadata.portableExecutionRef);return r.kind!=="training"||r.status!=="failed"||r.receipt!==null||t.status!=="succeeded"||t.receipt?.schemaVersion!=="openpond.modelRunReceipt.v1"||t.failure!==null||e.status!=="failed"||e.metadata.phase!=="artifact_collection_failed"||e.metadata.modelRunId!==r.id||!a.success||t.receipt.providerRunId!==(a.data.providerJobId??a.data.runId)||t.receipt.assignmentHash!==e.metadata.harnessRunManifestHash?!1:JSON.stringify({...r,status:t.status,receipt:t.receipt,adapterArtifactLineageId:t.adapterArtifactLineageId,failure:null,completedAt:t.completedAt,updatedAt:t.updatedAt})===JSON.stringify(t)}l(w,"isArtifactCollectionRecoveryTransition");function g(r,t){if(r.kind!=="evaluation"||!["failed","cancelled"].includes(r.status)||t.status!=="running"||t.receipt!==null||t.failure!==null||t.completedAt!==null||!r.evaluation)return!1;let e=r.evaluation.attemptPlan.filter(d=>d.stage==="baseline"||d.stage==="adaptation").reduce((d,n)=>d+n.attemptCount,0),a=r.evaluation.attemptPlan.reduce((d,n)=>d+n.attemptCount,0),i=r.evaluation.attemptPlan.find(d=>d.stage==="candidate_adaptation"),o=e+(i?.attemptCount??0);return!(r.evaluationProgress?.stage==="refiner"&&r.evaluationProgress.completedAttempts===e||r.evaluationProgress?.stage==="candidate_adaptation"&&r.evaluationProgress.completedAttempts>=e&&r.evaluationProgress.completedAttempts<=o||["candidate_adaptation","candidate","comparison"].includes(r.evaluationProgress?.stage??"")&&r.evaluationProgress?.completedAttempts===a)||!r.evaluationProgress?.accounting?!1:JSON.stringify({...r,status:"running",receipt:null,failure:null,completedAt:null,updatedAt:t.updatedAt})===JSON.stringify(t)}l(g,"isCheckpointResumeTransition");var T=class extends M{static{l(this,"SqliteTrainingModelStore")}async saveModelCurrencySnapshot(t){let e=_.parse(t),a=await this.getModelCurrencySnapshot(e.id);if(a){if(a.contentHash===e.contentHash&&JSON.stringify(a)===JSON.stringify(e))return a;throw new Error("An immutable Model Currency Snapshot cannot be replaced.")}return await this.upsertPayload(`INSERT INTO model_currency_snapshots
2
+ import{a as O}from"./chunk-YOQRYNLP.js";import{Na as P}from"./chunk-QL4OIPEZ.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import{U as S,ga as C,h as c,m as p,o as E,p as y,qa as u,r as R,u as m,w as _}from"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import{a as M}from"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import{a as l}from"./chunk-FTQLQJQV.js";function w(r,t,e){let a=P.safeParse(e.metadata.portableExecutionRef);return r.kind!=="training"||r.status!=="failed"||r.receipt!==null||t.status!=="succeeded"||t.receipt?.schemaVersion!=="openpond.modelRunReceipt.v1"||t.failure!==null||e.status!=="failed"||e.metadata.phase!=="artifact_collection_failed"||e.metadata.modelRunId!==r.id||!a.success||t.receipt.providerRunId!==(a.data.providerJobId??a.data.runId)||t.receipt.assignmentHash!==e.metadata.harnessRunManifestHash?!1:JSON.stringify({...r,status:t.status,receipt:t.receipt,adapterArtifactLineageId:t.adapterArtifactLineageId,failure:null,completedAt:t.completedAt,updatedAt:t.updatedAt})===JSON.stringify(t)}l(w,"isArtifactCollectionRecoveryTransition");function g(r,t){if(r.kind!=="evaluation"||!["failed","cancelled"].includes(r.status)||t.status!=="running"||t.receipt!==null||t.failure!==null||t.completedAt!==null||!r.evaluation)return!1;let e=r.evaluation.attemptPlan.filter(d=>d.stage==="baseline"||d.stage==="adaptation").reduce((d,n)=>d+n.attemptCount,0),a=r.evaluation.attemptPlan.reduce((d,n)=>d+n.attemptCount,0),i=r.evaluation.attemptPlan.find(d=>d.stage==="candidate_adaptation"),o=e+(i?.attemptCount??0);return!(r.evaluationProgress?.stage==="refiner"&&r.evaluationProgress.completedAttempts===e||r.evaluationProgress?.stage==="candidate_adaptation"&&r.evaluationProgress.completedAttempts>=e&&r.evaluationProgress.completedAttempts<=o||["candidate_adaptation","candidate","comparison"].includes(r.evaluationProgress?.stage??"")&&r.evaluationProgress?.completedAttempts===a)||!r.evaluationProgress?.accounting?!1:JSON.stringify({...r,status:"running",receipt:null,failure:null,completedAt:null,updatedAt:t.updatedAt})===JSON.stringify(t)}l(g,"isCheckpointResumeTransition");var T=class extends M{static{l(this,"SqliteTrainingModelStore")}async saveModelCurrencySnapshot(t){let e=_.parse(t),a=await this.getModelCurrencySnapshot(e.id);if(a){if(a.contentHash===e.contentHash&&JSON.stringify(a)===JSON.stringify(e))return a;throw new Error("An immutable Model Currency Snapshot cannot be replaced.")}return await this.upsertPayload(`INSERT INTO model_currency_snapshots
3
3
  (id, series_id, entry_id, evidence_state, content_hash, payload, created_at)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?)`,[e.id,e.seriesId,e.entryId,e.evidenceState,e.contentHash,JSON.stringify(e),e.projectedAt]),e}async getModelCurrencySnapshot(t){return this.getParsedPayload("SELECT payload FROM model_currency_snapshots WHERE id = ?",[t],_.parse)}async listModelCurrencySnapshots(t={}){return t.entryId?this.listParsedPayloads("SELECT payload FROM model_currency_snapshots WHERE entry_id = ? ORDER BY created_at DESC",[t.entryId],_.parse):t.seriesId?this.listParsedPayloads("SELECT payload FROM model_currency_snapshots WHERE series_id = ? ORDER BY created_at DESC",[t.seriesId],_.parse):this.listParsedPayloads("SELECT payload FROM model_currency_snapshots ORDER BY created_at DESC",[],_.parse)}async saveModelComparisonSeries(t){let e=c.parse(t),a=await this.getModelComparisonSeries(e.id);if(a&&(a.profileId!==e.profileId||a.modelProjectId!==e.modelProjectId||a.createdAt!==e.createdAt))throw new Error("A Model Comparison Series cannot change its immutable ownership.");if(a&&e.revision!==a.revision+1){if(JSON.stringify(a)===JSON.stringify(e))return a;throw new Error("A Model Comparison Series update requires the next revision.")}if(a?.scheduleSealedAt&&!v(a,e))throw new Error("A sealed Model Comparison Series definition is immutable.");return await this.upsertPayload(`INSERT INTO model_comparison_series
5
5
  (id, profile_id, model_project_id, status, payload, created_at, updated_at)
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
3
- import{b as u}from"./chunks/chunk-M4JWQSV7.js";import{a as c,j as d}from"./chunks/chunk-FV2R5RUN.js";import{a as m,b as l}from"./chunks/chunk-BSHAIAXY.js";import"./chunks/chunk-XWPC3AN4.js";import{f as s}from"./chunks/chunk-3M53YXEI.js";import"./chunks/chunk-GLUWATL5.js";import{a as n}from"./chunks/chunk-FTQLQJQV.js";function f(e){return!e.command&&s(e.options.version)?"version":s(e.options.checkUpdate)?"check-update":!e.command&&s(e.options.help)?"help":!e.command&&s(e.options.tui)?"tui":e.command?"command":"ui"}n(f,"resolveCliTopLevelAction");async function C(e=process.argv.slice(2)){if(await w(e))return;let{command:t,options:o,rest:r}=u(e);typeof o.home=="string"&&(process.env.OPENPOND_HOME=(await import("./chunks/dist-VYC5VMQB.js")).resolveOpenPondHome({home:o.home}));let i=f({command:t,options:o});if(i==="version"){console.log(c());return}if(i==="check-update"){await(await import("./chunks/core-commands-A2DGGIPS.js")).runCheckUpdate();return}if(i==="help"){(await import("./chunks/help-S7THC6IE.js")).printHelp();return}let a=m(o),p=l(o);if(a&&(process.env.OPENPOND_ACCOUNT=a),p&&(process.env.OPENPOND_BASE_URL=p),i==="tui"){await(await import("./chunks/app-layer-NSTE5HIT.js")).runOpenPondTerminalCommand(o,r);return}if(i==="ui"){await(await import("./chunks/app-layer-NSTE5HIT.js")).runOpenPondServerCommand("web",o,r);return}await d({command:t,options:o,rest:r})||((await import("./chunks/help-S7THC6IE.js")).printHelp(),process.exit(1))}n(C,"runOpenPondCli");async function w(e){if(e[0]==="__inspect-hosted-profile-evaluation")return await(await import("./chunks/hosted-profile-compiler-2DQIFSXW.js")).runHostedProfileInspectionCli(e.slice(1)),!0;if(e[0]==="__prepare-hosted-profile-evaluation")return await(await import("./chunks/hosted-profile-compiler-2DQIFSXW.js")).runHostedProfileEvaluationCli(e.slice(1)),!0;if(e[0]==="__hosted-experiment-improvement")return await(await import("./chunks/hosted-experiment-improvement-NFSVS5TU.js")).runHostedExperimentImprovementCli(e.slice(1)),!0;if(e[0]==="__compile-hosted-profile-candidate")return await(await import("./chunks/hosted-profile-candidate-2S5LFUWD.js")).runHostedProfileCandidateCli(e.slice(1)),!0;if(e[0]==="__compile-hosted-profile")return await(await import("./chunks/hosted-profile-compiler-2DQIFSXW.js")).runHostedProfileCompilerCli(e.slice(1)),!0;if(e[0]==="__app-server"){process.argv=[process.execPath,"openpond-app-server",...e.slice(1)];let[{createOpenPondAppServer:t},{runOpenPondAppServerCli:o}]=await Promise.all([import("./chunks/app-server-runtime-DVKOZ5B6.js"),import("./chunks/cli-X25RSO2X.js")]);return await o(t),!0}if(e[0]==="__server"){process.argv=[process.execPath,"openpond-server",...e.slice(1)];let[{createOpenPondServer:t},{runOpenPondServerCli:o}]=await Promise.all([import("./chunks/src-CJM6HY5Y.js"),import("./chunks/cli-X25RSO2X.js")]),{createOpenPondAppServer:r}=await import("./chunks/app-server-runtime-DVKOZ5B6.js");return await o({createOpenPondServer:t,createOpenPondAppServer:r}),!0}return e[0]==="__terminal"?(await(await import("./chunks/src-LMC3K6LH.js")).runOpenPondTerminalCli(e.slice(1)),!0):!1}n(w,"runEmbeddedCompanion");C().catch(e=>{let t=e instanceof Error?e.message:String(e),o=e.issue;if(process.argv.includes("--json")&&!(e instanceof Error&&e.name==="OpenPondChildProcessExitError"))console.log(JSON.stringify({error:o??{code:"CLI_ERROR",message:t}}));else if(o&&typeof o=="object"){let i=o;console.error(`${i.code}: ${i.message}
3
+ import{b as u}from"./chunks/chunk-M4JWQSV7.js";import{a as c,j as d}from"./chunks/chunk-FV2R5RUN.js";import{a as m,b as l}from"./chunks/chunk-BSHAIAXY.js";import"./chunks/chunk-XWPC3AN4.js";import{f as s}from"./chunks/chunk-3M53YXEI.js";import"./chunks/chunk-GLUWATL5.js";import{a as n}from"./chunks/chunk-FTQLQJQV.js";function f(e){return!e.command&&s(e.options.version)?"version":s(e.options.checkUpdate)?"check-update":!e.command&&s(e.options.help)?"help":!e.command&&s(e.options.tui)?"tui":e.command?"command":"ui"}n(f,"resolveCliTopLevelAction");async function C(e=process.argv.slice(2)){if(await w(e))return;let{command:t,options:o,rest:r}=u(e);typeof o.home=="string"&&(process.env.OPENPOND_HOME=(await import("./chunks/dist-VYC5VMQB.js")).resolveOpenPondHome({home:o.home}));let i=f({command:t,options:o});if(i==="version"){console.log(c());return}if(i==="check-update"){await(await import("./chunks/core-commands-A2DGGIPS.js")).runCheckUpdate();return}if(i==="help"){(await import("./chunks/help-S7THC6IE.js")).printHelp();return}let a=m(o),p=l(o);if(a&&(process.env.OPENPOND_ACCOUNT=a),p&&(process.env.OPENPOND_BASE_URL=p),i==="tui"){await(await import("./chunks/app-layer-NSTE5HIT.js")).runOpenPondTerminalCommand(o,r);return}if(i==="ui"){await(await import("./chunks/app-layer-NSTE5HIT.js")).runOpenPondServerCommand("web",o,r);return}await d({command:t,options:o,rest:r})||((await import("./chunks/help-S7THC6IE.js")).printHelp(),process.exit(1))}n(C,"runOpenPondCli");async function w(e){if(e[0]==="__inspect-hosted-profile-evaluation")return await(await import("./chunks/hosted-profile-compiler-IYLLHCRY.js")).runHostedProfileInspectionCli(e.slice(1)),!0;if(e[0]==="__prepare-hosted-profile-evaluation")return await(await import("./chunks/hosted-profile-compiler-IYLLHCRY.js")).runHostedProfileEvaluationCli(e.slice(1)),!0;if(e[0]==="__hosted-experiment-improvement")return await(await import("./chunks/hosted-experiment-improvement-HVMDGS75.js")).runHostedExperimentImprovementCli(e.slice(1)),!0;if(e[0]==="__compile-hosted-profile-candidate")return await(await import("./chunks/hosted-profile-candidate-EXNN6MVN.js")).runHostedProfileCandidateCli(e.slice(1)),!0;if(e[0]==="__compile-hosted-profile")return await(await import("./chunks/hosted-profile-compiler-IYLLHCRY.js")).runHostedProfileCompilerCli(e.slice(1)),!0;if(e[0]==="__app-server"){process.argv=[process.execPath,"openpond-app-server",...e.slice(1)];let[{createOpenPondAppServer:t},{runOpenPondAppServerCli:o}]=await Promise.all([import("./chunks/app-server-runtime-ISGGLQHU.js"),import("./chunks/cli-XZENDZ7Z.js")]);return await o(t),!0}if(e[0]==="__server"){process.argv=[process.execPath,"openpond-server",...e.slice(1)];let[{createOpenPondServer:t},{runOpenPondServerCli:o}]=await Promise.all([import("./chunks/src-R36AGJY7.js"),import("./chunks/cli-XZENDZ7Z.js")]),{createOpenPondAppServer:r}=await import("./chunks/app-server-runtime-ISGGLQHU.js");return await o({createOpenPondServer:t,createOpenPondAppServer:r}),!0}return e[0]==="__terminal"?(await(await import("./chunks/src-DZL5T2MT.js")).runOpenPondTerminalCli(e.slice(1)),!0):!1}n(w,"runEmbeddedCompanion");C().catch(e=>{let t=e instanceof Error?e.message:String(e),o=e.issue;if(process.argv.includes("--json")&&!(e instanceof Error&&e.name==="OpenPondChildProcessExitError"))console.log(JSON.stringify({error:o??{code:"CLI_ERROR",message:t}}));else if(o&&typeof o=="object"){let i=o;console.error(`${i.code}: ${i.message}
4
4
  ${i.path}
5
5
  ${i.action}`)}else console.error(t);let r=typeof e.exitCode=="number"?e.exitCode:1;process.exit(r)});export{C as runOpenPondCli};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openpond",
3
- "version": "0.2.56",
3
+ "version": "0.2.58",
4
4
  "license": "MIT",
5
5
  "description": "OpenPond CLI and local harness",
6
6
  "main": "dist/index.js",
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as z,b as B,c as x}from"./chunk-PF5R6CMP.js";import{a as M}from"./chunk-FEAKTSRS.js";import{x as N}from"./chunk-QOTVNQDI.js";import{n as _}from"./chunk-ACYFMLWG.js";import{l as A,m as S}from"./chunk-KGNCKIFP.js";import{b as I}from"./chunk-ES2ISFJC.js";import{a as u}from"./chunk-FTQLQJQV.js";import{createHash as U}from"node:crypto";function W(n){let p=n.replace(/^\/workspace\/outputs\//,"").replace(/^\/workspace\/work\/outputs\//,"").replace(/^outputs\//,"");if(!p||p.startsWith("/")||p.includes("\0")||p.split(/[\\/]/).some(y=>!y||y==="."||y===".."))throw new Error("Select one file inside this case's writable outputs.");return p}u(W,"confinedProfileOutputPath");var J=u(n=>`'${n.replaceAll("'","'\\''")}'`,"quote");async function D(n){let p=W(n.path),y="const f=require('fs'),p=require('path'),c=require('crypto'),a=JSON.parse(process.argv[1]),r=f.realpathSync('/workspace/work/outputs'),q=f.realpathSync(p.join(r,a.path));if(!q.startsWith(r+'/'))throw Error('Output path escapes the case');const s=f.statSync(q);if(!s.isFile()||s.size>10000000)throw Error('Output exceeds its bound');if(a.offset===undefined){const b=f.readFileSync(q);process.stdout.write(JSON.stringify({size:b.length,hash:c.createHash('sha256').update(b).digest('hex')}))}else{const h=f.openSync(q,'r'),b=Buffer.alloc(Math.min(524288,s.size-a.offset));try{const n=f.readSync(h,b,0,b.length,a.offset);process.stdout.write(b.subarray(0,n).toString('base64'))}finally{f.closeSync(h)}}";async function b(m){let h=await n.command(`/runtime/node -e ${J(y)} ${J(JSON.stringify({path:p,...m!==void 0?{offset:m}:{}}))}`);if(h.code!==0)throw new Error("The confined output could not be read.");return h.stdout}u(b,"read");let v=I.object({size:I.number().int().min(1).max(N),hash:I.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(JSON.parse(await b())),H=[];for(let m=0;m<v.size;m+=524288){let h=await b(m);if(!/^[A-Za-z0-9+/]*={0,2}$/.test(h)||h.length>7e5)throw new Error("Output chunk exceeded its boundary.");let $=Buffer.from(h,"base64");if($.length!==Math.min(524288,v.size-m))throw new Error("The output changed during readback.");H.push($)}let T=Buffer.concat(H),k=U("sha256").update(T).digest("hex"),P=I.object({size:I.number(),hash:I.string()}).strict().parse(JSON.parse(await b()));if(k!==v.hash||P.hash!==k||P.size!==T.length)throw new Error("The output changed before immutable readback.");return{bytes:T,title:p.split("/").at(-1)}}u(D,"readConfinedProfileOutput");import f from"node:path";import{promises as w}from"node:fs";var E=u(n=>`'${n.replaceAll("'","'\\''")}'`,"quote");function le(n){let p=new Map,y=new AbortController,b=n.release,v=n.runtimeNode??"/runtime/node",H=n.runtimeAgentRoot??"/runtime/agent",T=new Set(b.harnessRelease.files.filter(e=>e.visibility!=="policy").map(e=>e.contentHash)),k,P=B({storeDir:n.storeDir,loadArchive:x({storeDir:n.storeDir})});async function m(e){y.signal.throwIfAborted(),await n.authorize({bindingHash:e.manifest.profileEvaluation.externalDatasetBinding?.contentHash??S(e.manifest.profileEvaluation),manifestHash:e.manifest.contentHash,taskId:e.taskId,seed:e.seed}),y.signal.throwIfAborted()}u(m,"fence");async function h(e,t){let i=p.get(e.id),l=i?.manifest.profileEvaluation;if(!i||!l||t.sessionId!==e.id||t.status!=="in_progress"||S(e.metadata?.profileEvaluationRun)!==S({id:i.manifest.id,contentHash:i.manifest.contentHash})||e.currentProfile?.profileId!==l.profileId||t.profileSnapshot?.sourceHash!==l.harnessRelease.contentHash||t.profileSnapshot.revision!==l.sourceRevision)throw new Error("The target tool has no actual admitted source/case/turn authority.");if(i.turnId&&i.turnId!==t.id)throw new Error("The target case already belongs to another turn.");i.turnId=t.id;let s=await n.getTurn(t.id);if(!s||s.sessionId!==e.id||s.status!=="in_progress"||S(s.profileSnapshot)!==S(t.profileSnapshot))throw new Error("The actual target turn is no longer admitted.");return await m(i),i}u(h,"authority");let $=M({authorize:u(async e=>{let t=p.get(e.sessionId);if(!t||t.turnId!==e.turnId||e.candidateId!==t.manifest.id||e.expectedRevision!==1)throw new Error("Target command changed its original admitted source.");return await h(await n.getSession(e.sessionId),await n.getTurn(e.turnId)),{candidateId:t.manifest.id,candidateRevision:1,ownerId:"host-profile-evaluation",sessionId:e.sessionId,turnId:e.turnId,sourceRoot:t.root,layout:"profile_case",writablePaths:["outputs"],...k?{runtimeMounts:[{source:k.source,destination:"/runtime/agent"},{source:f.join(k.source,"node_modules"),destination:"/workspace/node_modules"}]}:{}}},"authorize")});async function O(e,t,i,l,s,a){await m(e);let r=n.executeCommand?await n.executeCommand({sessionId:e.sessionId,turnId:t,sourceRoot:e.root,publicHashes:e.publicHashes,...k?{runtimeRoot:k.source}:{},command:i,cwd:s,stdin:a,timeoutMs:Math.min(e.manifest.limits.timeoutMs,18e4),signal:AbortSignal.any([l,y.signal])}):await $({candidateId:e.manifest.id,expectedRevision:1,sessionId:e.sessionId,turnId:t,command:i,cwd:s,stdin:a,signal:AbortSignal.any([l,y.signal]),maxOutputBytes:75e4,timeoutMs:Math.min(e.manifest.limits.timeoutMs,18e4)});if(await m(e),r.timedOut||r.stdoutTruncated||r.stderrTruncated)throw new Error("The target command exceeded its bounded execution or output.");return r}u(O,"command");async function L(e,t,i,l,s=[]){let a=t.profileEvaluation;if(!a||a.harnessRelease.contentHash!==b.harnessRelease.contentHash||t.population.filter(c=>c.taskId===i&&c.seed===l).length!==1||S(e.metadata?.profileEvaluationRun)!==S({id:t.id,contentHash:t.contentHash}))throw new Error("The target Session differs from its actual sealed source/case admission.");let r=f.join(n.storeDir,"evaluation-policy-cases",S([t.id,e.id])),o={},g={manifest:t,root:r,sessionId:e.id,taskId:i,seed:l,publicHashes:o};await m(g),await w.mkdir(r,{recursive:!0,mode:448});for(let c of b.harnessRelease.files){if(c.visibility!=="policy"||T.has(c.contentHash))continue;let d=f.join(b.bundlePath,"source",c.path),R=await w.realpath(d),K=await w.realpath(f.join(b.bundlePath,"source"));if(!R.startsWith(`${K}${f.sep}`)||(await w.lstat(d)).isSymbolicLink())throw new Error("Released policy source escaped its immutable closure.");let j=await w.readFile(R);if(j.length!==c.sizeBytes||A(j)!==c.contentHash)throw new Error("Released policy source changed before target admission.");let C=f.join(r,c.path);await w.mkdir(f.dirname(C),{recursive:!0,mode:448}),await w.writeFile(C,j,{flag:"wx",mode:256}),o[c.path]=c.contentHash}for(let c of new Set(Object.keys(o).filter(d=>d.startsWith("agents/")).map(d=>d.split("/")[1]))){let d=`agents/${c}`;o[`${d}/agent.ts`]&&!o[`${d}/openpond.yaml`]&&!o[`${d}/agent/agent.ts`]&&(await w.mkdir(f.join(r,d,"agent"),{recursive:!0,mode:448}),await w.rename(f.join(r,d,"agent.ts"),f.join(r,d,"agent","agent.ts")),o[`${d}/agent/agent.ts`]=o[`${d}/agent.ts`],delete o[`${d}/agent.ts`])}for(let c of s){if(c.mediaType!=="application/pdf"||!c.contentsBase64||c.name!==f.basename(c.name))throw new Error("The isolated case has an unsupported input attachment.");let d=Buffer.from(c.contentsBase64,"base64"),R=`inputs/${c.name}`;if(d.length!==c.sizeBytes||d.length>1e7||o[R])throw new Error("The isolated case input identity is invalid.");await w.mkdir(f.join(r,"inputs"),{recursive:!0,mode:448}),await w.writeFile(f.join(r,R),d,{flag:"wx",mode:256}),o[R]=A(d)}await w.mkdir(f.join(r,"outputs"),{mode:448}),await m(g),p.set(e.id,g)}u(L,"admitSession");let F=u(async e=>{let t=await h(e.session,e.turn),i=[],l=u((s,a,r,o)=>i.push({name:s,description:a,parameters:{type:"object",properties:r,additionalProperties:!1},execute:u(async g=>{if(await h(g.session,e.turn)!==t||g.turnId!==e.turn.id)throw new Error("Target tool changed its admitted case.");let d=await o(g.args,g.signal);return await h(g.session,e.turn),{toolCallId:g.callId,name:s,ok:!0,contentText:JSON.stringify(d),data:d}},"execute")}),"define");l("harness_inspect","Inspect this released policy source.",{},async()=>({release:{id:b.harnessRelease.id,contentHash:b.harnessRelease.contentHash},files:Object.entries(t.publicHashes).map(([s,a])=>({path:s,contentHash:a}))}));for(let s of["profile_skill_read","skill_inspect","context_read"])l(s,"Read an exact file from this policy source.",{name:{type:"string"},path:{type:"string"}},async a=>{let r=typeof a.path=="string"?a.path:typeof a.name=="string"?`skills/${a.name}/SKILL.md`:"";if(!t.publicHashes[r])throw new Error("This source file is outside the public policy closure.");let o=await O(t,e.turn.id,`${v} -e ${E("const f=require('fs'),p=process.argv[1],b=f.readFileSync(p);if(b.length>250000)throw Error('Policy source exceeds read bound');process.stdout.write(JSON.stringify({path:p,text:b.toString('utf8')}))")} ${E(`/workspace/work/${r}`)}`,e.signal);if(o.code!==0)throw new Error("The public target file could not be read.");return JSON.parse(o.stdout)});for(let s of["exec_command","work_exec"])l(s,"Run a command inside the policy source namespace and writable outputs.",{command:{type:"string"},cwd:{type:"string"}},async(a,r)=>{if(typeof a.command!="string")throw new Error("Select a target command.");let o=typeof a.cwd=="string"?a.cwd:t.root,g=o.startsWith("/workspace/work/")?f.join(t.root,o.slice(16)):o==="/workspace/work"?t.root:o;return O(t,e.turn.id,a.command,r,g)});l("work_save_output","Save a completed file from this case's outputs into durable output storage.",{path:{type:"string"},suggestedName:{type:"string"}},async(s,a)=>{if(typeof s.path!="string")throw new Error("Select a completed case output.");let r=n.readOutput?await n.readOutput({sessionId:e.session.id,turnId:e.turn.id,path:s.path,signal:a}):await D({path:s.path,command:u(g=>O(t,e.turn.id,g,a),"command")});await h(e.session,e.turn);let o=await n.saveOutput({session:e.session,sourceTurnId:e.turn.id,suggestedName:typeof s.suggestedName=="string"?s.suggestedName:r.title,bytes:r.bytes,validation:[],validationPolicy:"preserve"});return await h(e.session,e.turn),await n.recordOutput(e.session.id,e.turn.id,o),await h(e.session,e.turn),o});for(let s of["list_files","read_files","search_files"])l(s,"Inspect files within the public policy namespace.",{paths:{type:"array",items:{type:"string"}},path:{type:"string"},query:{type:"string"}},async(a,r)=>{let o=await O(t,e.turn.id,`${v} -e ${E(z)}`,r,void 0,JSON.stringify({action:s,args:a,writablePaths:["outputs"]}));if(o.code!==0)throw new Error("The confined target file operation failed.");return JSON.parse(o.stdout)});return i},"resolveTools");async function q(e){let t=await h(e.session,e.turn),i=e.action;if(!_(i.inputSchema,e.value).valid)throw new Error("The actual released Agent action input changed.");if(!Object.keys(t.publicHashes).some(o=>o.startsWith(`agents/${i.agentId}/`)))throw new Error("The Agent action has no public policy source closure.");await m(t),k??=await P(),await m(t);let l=f.join(t.root,"agents",i.agentId),s=`/workspace/work/outputs/${e.turn.id}`,a=["run",i.sourceActionId,"--cwd",`/workspace/work/agents/${i.agentId}`,"--input",JSON.stringify(e.value),"--out-dir",s],r=await O(t,e.turn.id,`${v} ${E(`${H}/${k.cliRelativePath}`)} ${a.map(E).join(" ")}`,e.signal,l);if(r.code!==0)throw new Error(`The confined released Agent action failed: ${r.stderr.slice(0,1e3)}`);return{output:r.stdout,agentSourcePath:`/workspace/work/agents/${i.agentId}`,runPath:s}}return u(q,"executeAction"),{admitSession:L,resolveTools:F,executeAction:q,ownsSession:u(e=>p.has(e),"ownsSession"),settleSession:u(async e=>{let t=p.get(e);try{t?.turnId&&await n.settleRemote?.(e,t.turnId)}finally{p.delete(e)}},"settleSession"),close:u(()=>{y.abort(new Error("Profile evaluation owner closed.")),p.clear()},"close")}}u(le,"createHostProfileEvaluationTools");export{W as a,le as b};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{e as k}from"./chunk-3RCRSMWZ.js";import{a as h,c as v}from"./chunk-PSGGOZFM.js";import{Da as g,G as _,b as w,sb as j,ya as p}from"./chunk-QOTVNQDI.js";import{v as y}from"./chunk-WJ43MJ3F.js";import{m as S}from"./chunk-3QIB5FXI.js";import{b as s}from"./chunk-ES2ISFJC.js";import{q as P}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";function M(e){if(e.kind==="command"||e.kind==="file_change")return!0;if(e.kind!=="permissions")return!1;try{let t=JSON.parse(e.detail);return!t.questions&&Array.isArray(t.options)&&t.options.some(r=>r.kind==="allow_once")&&t.options.some(r=>r.kind==="reject_once")}catch{return!1}}a(M,"remoteApprovalSupported");import{createHash as D}from"node:crypto";import{realpath as x,stat as O}from"node:fs/promises";var E=a(e=>D("sha256").update(w("POST","/local/ponder-project",e)).digest("hex"),"hash"),f=s.object({projectId:s.string().min(1).max(200),name:s.string().min(1).max(300),cwd:s.string().min(1).max(8192),sourceFolders:s.array(s.object({path:s.string().min(1).max(8192),realpath:s.string().min(1).max(8192)}).strict()).min(1).max(1e3),configurationHash:s.string().regex(/^[a-f0-9]{64}$/),revision:s.string().regex(/^[a-f0-9]{64}$/)}).strict();function G(e){let t=Object.values(P(e,"saved_local_projects"));if(t.length>p)throw new Error("ponder_desktop_project_sharing_limit_exceeded");return t.map(r=>S.parse(r.value))}a(G,"readPonderLocalProjects");async function U(e){if(e.hiddenFromDefaultSidebar)throw new Error("ponder_desktop_project_unavailable");let t=[...new Set([...e.sourceFolders??[e.path],e.path,...e.repoPath?[e.repoPath]:[]])];if(!t.length||t.length>1e3)throw new Error("ponder_desktop_project_folder_limit_exceeded");let r=await x(e.workspacePath);if(!(await O(r)).isDirectory())throw new Error("ponder_desktop_project_unavailable");let o=[];for(let c of t){let i=await x(c);if(!(await O(i)).isDirectory())throw new Error("ponder_desktop_project_unavailable");o.push({path:c,realpath:i})}let n={projectId:e.id,name:e.name,cwd:r,sourceFolders:o,configurationHash:E({id:e.id,name:e.name,path:e.path,workspacePath:e.workspacePath,repoPath:e.repoPath,sourceFolders:e.sourceFolders??null,hiddenFromDefaultSidebar:e.hiddenFromDefaultSidebar??!1})};return f.parse({...n,revision:E(n)})}a(U,"capturePonderProjectSnapshot");import{createHash as C}from"node:crypto";var R=j,m=s.object({revision:s.number().int().positive(),owner:h,authority:R,project:f,shared:s.boolean(),updatedAt:s.string().datetime()}).strict(),b=m.omit({revision:!0}),u=a(e=>C("sha256").update(JSON.stringify(h.parse(e))).digest("hex"),"ownerKey");function N(e,t,r){let o=h.parse(t),n=R.parse(r),c=e.get("SELECT payload FROM ponder_desktop_authority WHERE id = 1"),i=c?g.parse(JSON.parse(c.payload)):null;if(!i||i.state!=="attached"||Date.parse(i.leaseExpiresAt)<=Date.now()||i.authorizationRevision!==n.authorizationRevision||!Object.entries(n.scope).every(([d,l])=>i.scope[d]===l)||i.scope.installationId!==o.installationId||i.scope.profileId!==o.profileId||i.scope.ownerUserId!==o.ownerUserId||i.scope.teamId!==o.teamId)throw new Error("ponder_desktop_project_authority_changed")}a(N,"assertAuthority");function re(e,t){let r=b.parse(t);N(e,r.owner,r.authority);let o=u(r.owner),n=e.get("SELECT payload FROM ponder_project_sharing WHERE owner_key = ? AND project_id = ?",[o,r.project.projectId]);if(!n&&(e.get("SELECT count(*) AS count FROM ponder_project_sharing WHERE owner_key = ?",[o])?.count??0)>=p)throw new Error("ponder_desktop_project_sharing_limit_exceeded");let c=n?m.parse(JSON.parse(n.payload)):null,i=c&&c.shared===r.shared&&c.project.revision===r.project.revision&&c.authority.authorizationRevision===r.authority.authorizationRevision&&Object.entries(r.authority.scope).every(([l,L])=>c.authority.scope[l]===L),d=m.parse({...r,revision:c?c.revision+(i?0:1):1});return e.run("INSERT INTO ponder_project_sharing (owner_key, project_id, payload) VALUES (?, ?, ?) ON CONFLICT(owner_key, project_id) DO UPDATE SET payload = excluded.payload",[o,r.project.projectId,JSON.stringify(d)]),d}a(re,"setPonderProjectSharing");function te(e,t){let r=e.all("SELECT payload FROM ponder_project_sharing WHERE owner_key = ? ORDER BY project_id LIMIT ?",[u(t),p+1]);if(r.length>p)throw new Error("ponder_desktop_project_sharing_limit_exceeded");return r.map(o=>{let n=m.parse(JSON.parse(o.payload));if(u(n.owner)!==u(t))throw new Error("ponder_desktop_project_owner_changed");return n})}a(te,"readPonderProjectSharing");function ne(e,t){return e.shared&&e.authority.authorizationRevision===t.authorizationRevision&&Object.entries(t.scope).every(([r,o])=>e.authority.scope[r]===o)}a(ne,"projectSharingMatchesAuthority");import{createHash as T}from"node:crypto";function I(e){return y.parse({provider:e.provider,cwd:e.cwd,localProjectId:e.localProjectId,workspaceId:e.workspaceId,workspaceKind:e.workspaceKind,workspaceName:e.workspaceName,...e.modelRef?{modelRef:e.modelRef}:{},currentProfile:e.currentProfile,experience:e.experience,profileWorkflowBinding:e.profileWorkflowBinding,profileComponentBinding:e.profileComponentBinding,openPondCommandAccessMode:e.openPondCommandAccessMode})}a(I,"remoteStarterPayload");function F(e){return Number.parseInt(T("sha256").update(_({payload:I(e),owner:e.metadata?.ponderLocalOwner})).digest("hex").slice(0,13),16)}a(F,"remoteStarterRevision");function z(e,t){let r=new Map;for(let o of e){if(!v(o,t)||!o.localProjectId||!o.cwd||o.archived||o.status==="closed"||o.systemKind||o.hiddenFromDefaultSidebar||o.metadata?.nativeHistoryProjection||!k(o.provider)||["sandbox","sandbox_template","sandbox_app"].includes(o.workspaceKind??""))continue;try{I(o)}catch{continue}let n=`starter:${o.id}`;r.set(n,{source:o,target:{id:n,projectId:o.localProjectId,projectLabel:o.workspaceName??"Local project",title:`New ${o.provider} task in ${o.workspaceName??"local project"}`,revision:F(o)}})}return r}a(z,"captureRemoteStarters");function le(e){return async t=>{let r=await e.current();if(!r)throw new Error("remote_account_unavailable");let o=[];for(let c of await e.store.sessionShells()){let i=await e.store.getSession(c.id);i&&o.push(i)}let n=z(o,r.owner).get(t.localStarterId);if(!n||n.target.revision!==t.expectedRevision||n.target.projectId!==t.payload.projectId||n.target.revision!==t.payload.starterRevision)throw new Error("remote_starter_changed");return n.source}}a(le,"createRemoteStarterResolver");var A=class extends Error{constructor(r,o=409){super(r);this.status=o;this.name="LocalManagedMessageError"}status;static{a(this,"LocalManagedMessageError")}};export{I as a,F as b,z as c,le as d,M as e,A as f,G as g,U as h,re as i,te as j,ne as k};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{b as a}from"./chunk-UHFZHBGW.js";import"./chunk-PF5R6CMP.js";import"./chunk-FEAKTSRS.js";import"./chunk-QOTVNQDI.js";import"./chunk-OQPJ7FJF.js";import"./chunk-WJ43MJ3F.js";import"./chunk-Q4TBTRIG.js";import"./chunk-T5AACNJI.js";import"./chunk-QOGJAQDO.js";import"./chunk-EYPCBBMS.js";import"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import"./chunk-3VUATFZD.js";import"./chunk-4EPSHPZL.js";import"./chunk-MQULU465.js";import"./chunk-PRGBLQVH.js";import"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import"./chunk-XDQMGUWL.js";import"./chunk-FTEOCCPB.js";import"./chunk-25MBPJVY.js";import"./chunk-WN3V6KDN.js";import"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-YBT2NB32.js";import"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import"./chunk-Z4Z5UOZM.js";import"./chunk-6FA3GG5B.js";import"./chunk-Y4OWBBDD.js";import"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import"./chunk-FFRFSDBM.js";import"./chunk-VYLGI3IH.js";import"./chunk-ACYFMLWG.js";import"./chunk-TVQAPBLZ.js";import"./chunk-KGNCKIFP.js";import"./chunk-ES2ISFJC.js";import"./chunk-FTQLQJQV.js";export{a as createHostProfileEvaluationTools};