openpond 0.2.36 → 0.2.37
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.
- package/dist/app-server.d.ts +189 -3
- package/dist/app-server.js +1 -1
- package/dist/chunks/actions-command-GNQREIDD.js +2 -0
- package/dist/chunks/{app-layer-KPPQSL67.js → app-layer-BDAKS3DG.js} +1 -1
- package/dist/chunks/app-server-runtime-D74FFS27.js +2 -0
- package/dist/chunks/apps-2SUP5JZE.js +2 -0
- package/dist/chunks/chunk-2O5UZOYL.js +13 -0
- package/dist/chunks/{chunk-Q2Z27DCK.js → chunk-3I5BMVJI.js} +1 -1
- package/dist/chunks/{chunk-P3DI3ZMK.js → chunk-3LG4G5JR.js} +2 -2
- package/dist/chunks/{chunk-4QX2I2DX.js → chunk-3N4GQL6I.js} +1 -1
- package/dist/chunks/{chunk-DR3XPQRZ.js → chunk-3YA2CD22.js} +1 -1
- package/dist/chunks/{chunk-EFTLCT7C.js → chunk-4R4KM6LL.js} +1 -1
- package/dist/chunks/{chunk-MXLB6MEW.js → chunk-5YUITAUN.js} +1 -1
- package/dist/chunks/{chunk-QPZNN5Q3.js → chunk-6EAQL7YX.js} +1 -1
- package/dist/chunks/{chunk-DJHJIXMW.js → chunk-BLXEK5F7.js} +1 -1
- package/dist/chunks/{chunk-BFHAJTU4.js → chunk-DAOLQUAK.js} +1 -1
- package/dist/chunks/{chunk-ZF6OAPTQ.js → chunk-DG4DIFF4.js} +1 -1
- package/dist/chunks/{chunk-SHWLRMDG.js → chunk-DXOOJFFU.js} +1 -1
- package/dist/chunks/chunk-EIB7GHIQ.js +4 -0
- package/dist/chunks/{chunk-XCTFXXVY.js → chunk-FFEI7IRU.js} +1 -1
- package/dist/chunks/chunk-FOW3LI6G.js +2 -0
- package/dist/chunks/{chunk-VRY5TEEF.js → chunk-FQOVC2GR.js} +78 -78
- package/dist/chunks/chunk-HZP5U2AA.js +3 -0
- package/dist/chunks/chunk-I6DQSOSF.js +12 -0
- package/dist/chunks/chunk-IYROEHYB.js +2 -0
- package/dist/chunks/{chunk-LL3ZAZEU.js → chunk-KCFVJDIV.js} +1 -1
- package/dist/chunks/chunk-L6NNQUAT.js +53 -0
- package/dist/chunks/chunk-OO7JG7KM.js +42 -0
- package/dist/chunks/chunk-PKBU37CH.js +5 -0
- package/dist/chunks/chunk-QUNRWDVO.js +155 -0
- package/dist/chunks/{chunk-34URWDE7.js → chunk-S4RSY6CR.js} +1 -1
- package/dist/chunks/{chunk-5WFHGIQB.js → chunk-SL7XLTIT.js} +199 -199
- package/dist/chunks/{chunk-CL6YPTWP.js → chunk-TZ6N7WFI.js} +1 -1
- package/dist/chunks/{chunk-Z6F6PYF4.js → chunk-UJLZRM2M.js} +1 -1
- package/dist/chunks/chunk-XISNUB62.js +2 -0
- package/dist/chunks/{chunk-FIFGH6W3.js → chunk-XLVFY2BA.js} +1 -1
- package/dist/chunks/{chunk-K6EGNB2A.js → chunk-YQPECTJ2.js} +1 -1
- package/dist/chunks/{chunk-YZ262JZT.js → chunk-Z3RBK6LN.js} +1 -1
- package/dist/chunks/cli-A2P56J7R.js +2 -0
- package/dist/chunks/configuration-command-URDRLDNY.js +2 -0
- package/dist/chunks/core-commands-CMAAUKPQ.js +2 -0
- package/dist/chunks/desktop-test-5PKGG6H6.js +3 -0
- package/dist/chunks/dist-CEKBK32A.js +2 -0
- package/dist/chunks/dist-GKCGK44T.js +2 -0
- package/dist/chunks/{extension-LG3JL5QD.js → extension-DG2XISC6.js} +1 -1
- package/dist/chunks/{help-XP73IYAV.js → help-ZLJV3ZVW.js} +1 -1
- package/dist/chunks/hosted-harness-runtime-ABEMAABI.js +2 -0
- package/dist/chunks/hosted-profile-compiler-CSLJT75T.js +3 -0
- package/dist/chunks/{opchat-5NQ22CPO.js → opchat-IMGIFM4W.js} +1 -1
- package/dist/chunks/organizations-G3UOHURO.js +2 -0
- package/dist/chunks/{profile-O7NIC76F.js → profile-LMRN5QMQ.js} +1 -1
- package/dist/chunks/project-agent-DTAVYEB6.js +2 -0
- package/dist/chunks/sandbox-command-YO6RR5SD.js +2 -0
- package/dist/chunks/{sandbox-template-H5M4NV2F.js → sandbox-template-LN5OQ55F.js} +1 -1
- package/dist/chunks/{src-WN3RDFPF.js → src-A5KEQW52.js} +1 -1
- package/dist/chunks/{src-BITVDQDA.js → src-LRJO4THC.js} +1 -1
- package/dist/chunks/{teams-bot-RPZVD4UD.js → teams-bot-RY5M6AOW.js} +1 -1
- package/dist/chunks/{workspaces-XMU4772P.js → workspaces-KZ6ZJXXY.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/actions-command-U2DMVGDS.js +0 -2
- package/dist/chunks/app-server-runtime-ELR3VCKR.js +0 -2
- package/dist/chunks/apps-NBV45ZGW.js +0 -2
- package/dist/chunks/chunk-IFP6W4OW.js +0 -54
- package/dist/chunks/chunk-JB6FTAMW.js +0 -2
- package/dist/chunks/chunk-L67V63N3.js +0 -2
- package/dist/chunks/chunk-MPNHNWN6.js +0 -15
- package/dist/chunks/chunk-PBRD43CI.js +0 -42
- package/dist/chunks/chunk-RC3JXLP7.js +0 -4
- package/dist/chunks/chunk-VVKE6EYN.js +0 -166
- package/dist/chunks/cli-EG7K37TB.js +0 -2
- package/dist/chunks/configuration-command-MSDFCKOT.js +0 -2
- package/dist/chunks/core-commands-WDHXJPCY.js +0 -2
- package/dist/chunks/desktop-test-SN4BHDV3.js +0 -3
- package/dist/chunks/dist-XCT2G25K.js +0 -2
- package/dist/chunks/hosted-profile-compiler-HQ6T6NDP.js +0 -3
- package/dist/chunks/organizations-AY52SHI4.js +0 -2
- package/dist/chunks/project-agent-UKGWIFFI.js +0 -2
- package/dist/chunks/sandbox-command-WL6DAJTO.js +0 -2
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{b as t}from"./chunk-ES2ISFJC.js";import{a as c}from"./chunk-FTQLQJQV.js";var O=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),v=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function E(n){let a=typeof n=="string"?new TextEncoder().encode(n):n,r=Math.ceil((a.byteLength+9)/64)*64,d=new Uint8Array(r);d.set(a),d[a.byteLength]=128;let b=a.byteLength*8,A=new DataView(d.buffer);A.setUint32(r-8,Math.floor(b/4294967296),!1),A.setUint32(r-4,b>>>0,!1);let e=new Uint32Array(O),f=new Uint32Array(64);for(let u=0;u<r;u+=64){for(let o=0;o<16;o+=1)f[o]=A.getUint32(u+o*4,!1);for(let o=16;o<64;o+=1){let g=f[o-15],S=f[o-2],T=i(g,7)^i(g,18)^g>>>3,w=i(S,17)^i(S,19)^S>>>10;f[o]=f[o-16]+T+f[o-7]+w>>>0}let s=e[0],p=e[1],h=e[2],_=e[3],x=e[4],y=e[5],R=e[6],H=e[7];for(let o=0;o<64;o+=1){let g=x&y^~x&R,S=s&p^s&h^p&h,T=i(s,2)^i(s,13)^i(s,22),w=i(x,6)^i(x,11)^i(x,25),j=H+w+g+v[o]+f[o]>>>0,L=T+S>>>0;H=R,R=y,y=x,x=_+j>>>0,_=h,h=p,p=s,s=j+L>>>0}e[0]=e[0]+s>>>0,e[1]=e[1]+p>>>0,e[2]=e[2]+h>>>0,e[3]=e[3]+_>>>0,e[4]=e[4]+x>>>0,e[5]=e[5]+y>>>0,e[6]=e[6]+R>>>0,e[7]=e[7]+H>>>0}return Array.from(e,u=>u.toString(16).padStart(8,"0")).join("")}c(E,"sha256Hex");function i(n,a){return n>>>a|n<<32-a}c(i,"rotateRight");var z=2e3,U=25e7,l=t.string().trim().min(1).max(240),m=t.string().regex(/^[a-f0-9]{64}$/),Y=t.string().datetime({offset:!0}),q=t.record(t.string(),t.unknown()).default({}),M=t.object({id:l,contentHash:m}).strict(),F=M.extend({revision:t.number().int().positive()}).strict(),W=t.object({id:l,path:t.string().trim().min(1).max(z).refine(N),contentHash:m,sizeBytes:t.number().int().nonnegative().max(U),mediaType:t.string().trim().min(1).max(200),visibility:t.enum(["policy","verifier","host_private"])}).strict(),G=t.object({id:l,contentHash:m,mediaType:t.string().trim().min(1).max(200).nullable().default(null),sizeBytes:t.number().int().nonnegative().max(U).nullable().default(null)}).strict(),K=t.enum(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function B(n){return`${JSON.stringify(I(n),null,2)}
|
|
3
|
+
`}c(B,"canonicalJson");function C(n){return E(n)}c(C,"sha256");function P(n){return C(B(n))}c(P,"contentHash");function Q(n,a){let{contentHash:r,...d}=n,b=P(d);if(r!==b)throw new Error(`${a} contentHash is ${r}; expected ${b}.`)}c(Q,"assertContentHash");function N(n){let a=n.replaceAll("\\","/");return!a||a.startsWith("/")||a.includes("\0")?!1:!a.split("/").some(r=>!r||r==="."||r==="..")}c(N,"safeRelativePath");function I(n){return Array.isArray(n)?n.map(I):!n||typeof n!="object"?n:Object.fromEntries(Object.entries(n).sort(([a],[r])=>a.localeCompare(r)).map(([a,r])=>[a,I(r)]))}c(I,"sortValue");var ae=t.object({provider:l,model:l,revision:t.string().trim().min(1).max(500).nullable().default(null),artifactHash:m.nullable().default(null),tokenizerRevision:t.string().trim().min(1).max(500).nullable().default(null),chatTemplateHash:m.nullable().default(null)}).strict(),$=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],D=t.enum($),oe=t.object({providerId:D,modelId:t.string().trim().min(1).max(300)});export{l as a,m as b,Y as c,q as d,M as e,F as f,W as g,G as h,K as i,B as j,C as k,P as l,Q as m,ae as n,$ as o,D as p,oe as q};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{fa as Y,ia as D,ja as Z,ka as ee,oa as I,pa as re}from"./chunk-FQOVC2GR.js";import{E as x}from"./chunk-PKBU37CH.js";import{ce as X}from"./chunk-BLXEK5F7.js";import{b as W}from"./chunk-L3KS6MOV.js";import{Ba as G,Ca as Q,i as B,l as K,o as J,q as $,r as P,s as U,v as L,x as q}from"./chunk-QUNRWDVO.js";import{k as N,l as _,m as A}from"./chunk-HZP5U2AA.js";import{b as S}from"./chunk-ES2ISFJC.js";import{a as w}from"./chunk-FTQLQJQV.js";import{randomUUID as Re}from"node:crypto";import{readFile as C}from"node:fs/promises";import E from"node:path";import{promises as le}from"node:fs";import y from"node:path";import{randomUUID as O}from"node:crypto";import{promises as h}from"node:fs";import{stripTypeScriptTypes as me}from"node:module";import R from"node:path";async function Oe(s){let e=$.parse(s.overlay),r=P.parse(s.proposal),t=s.validations.map(u=>U.parse(u));if((r.route==="agent"?r.edits.filter(u=>u.target!=="harness.json"&&u.operation!=="delete"):[]).length>0){let u=r.validationPlan.find(a=>a.kind==="component_activation"&&a.required);if(!u)throw new Error("Desktop Work Agent proposals require component-activation validation before review.");if(t.find(a=>a.validationId===u.id)?.status==="passed")throw new Error("Desktop Work cannot accept a passed Agent activation receipt until an Agent source executor exists.")}if(r.overlay.id!==e.id||r.overlay.revision!==e.revision||r.overlay.contentHash!==e.contentHash)throw new Error("Refiner proposal is not bound to the supplied run overlay.");if(e.status!=="frozen")throw new Error("Only a frozen run overlay can advance a Harness workspace.");let o=await s.store.getHarnessWorkspace(r.expectedWorkspace.workspaceId);if(!o)throw new Error(`Harness workspace ${r.expectedWorkspace.workspaceId} does not exist.`);if(o.location!==s.store.harnessStoragePlacement)throw new Error("Refiner workspace does not match the admitted storage placement.");let i=D(s.storeDir,o.id),l=await I({workspaceId:o.id,sourceDir:i.source});if(l.sourceRevision!==o.sourceRevision)throw new Error(`Harness source is ${l.sourceRevision}; workspace expects ${o.sourceRevision}. Record or revert the source change before refinement.`);let d=R.join(i.root,`.source-candidate-${O()}`);await h.cp(i.source,d,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});try{await ae(d,r);let u=await I({workspaceId:o.id,sourceDir:d}),f=(s.now??(()=>new Date().toISOString()))(),a=await re({storeDir:s.storeDir,workspaceId:o.id,compiled:u,createdAt:f});await s.store.saveHarnessReleaseRecord(a),await s.store.saveHarnessImprovementArtifact(o.id,"run_overlay",e),await s.store.saveHarnessImprovementArtifact(o.id,"proposal",r);for(let c of t)await s.store.saveHarnessImprovementArtifact(o.id,"targeted_validation",c);if(!X({workspace:o,proposal:r}).eligible&&!s.reviewAuthority)return s.store.advanceHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:o.id,proposal:r,validations:t,nextRelease:{id:a.harnessRelease.id,contentHash:a.harnessRelease.contentHash},nextSourceRevision:a.sourceRevision,now:f});let m=R.join(i.root,`.source-backup-${O()}`),p=R.join(i.root,"source-swap.json");await ne(p,{schemaVersion:"openpond.localHarnessSourceSwap.v1",workspaceId:o.id,expectedWorkspaceRevision:o.revision,previousSourceRevision:o.sourceRevision,nextSourceRevision:a.sourceRevision,backupSource:m,candidateSource:d,createdAt:f}),await h.rename(i.source,m),await h.rename(d,i.source);try{let c=s.reviewAuthority?await s.store.advanceReviewedHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:o.id,proposal:r,validations:t,nextRelease:{id:a.harnessRelease.id,contentHash:a.harnessRelease.contentHash},nextSourceRevision:a.sourceRevision,reviewer:s.reviewAuthority.reviewer,now:f}):await s.store.advanceHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:o.id,proposal:r,validations:t,nextRelease:{id:a.harnessRelease.id,contentHash:a.harnessRelease.contentHash},nextSourceRevision:a.sourceRevision,now:f});return c.receipt.decision!=="advanced"?await j(i.source,m):await h.rm(m,{recursive:!0,force:!0}),await h.rm(p,{force:!0}),c}catch(c){throw await j(i.source,m).catch(()=>{}),await h.rm(p,{force:!0}).catch(()=>{}),c}}finally{await h.rm(d,{recursive:!0,force:!0}).catch(()=>{})}}w(Oe,"applyLocalHarnessRefinerProposal");async function $e(s){let e=await s.store.getHarnessWorkspace(s.workspaceId);if(!e||e.location!==s.store.harnessStoragePlacement)throw new Error(`Local Harness workspace ${s.workspaceId} does not exist.`);if(e.currentChannel.release?.id!==s.rollbackOf.id||e.currentChannel.release.contentHash!==s.rollbackOf.contentHash)throw new Error("Harness rollback source is no longer the current release.");let r=await s.store.getHarnessReleaseRecord(s.targetRelease.contentHash);if(!r||r.workspaceId!==e.id||r.harnessRelease.id!==s.targetRelease.id)throw new Error("Harness rollback target is unavailable in this workspace.");let t=D(s.storeDir,e.id);if((await I({workspaceId:e.id,sourceDir:t.source})).sourceRevision!==e.sourceRevision)throw new Error("Harness source changed before rollback.");let o=R.join(t.root,`.source-rollback-${O()}`);await h.cp(R.join(r.bundlePath,"source"),o,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});try{if((await I({workspaceId:e.id,sourceDir:o})).sourceRevision!==r.sourceRevision)throw new Error("Harness rollback bundle does not reproduce its registered source revision.");let l=(s.now??(()=>new Date().toISOString()))(),d=R.join(t.root,`.source-backup-${O()}`),u=R.join(t.root,"source-swap.json");await ne(u,{schemaVersion:"openpond.localHarnessSourceSwap.v1",workspaceId:e.id,expectedWorkspaceRevision:e.revision,previousSourceRevision:e.sourceRevision,nextSourceRevision:r.sourceRevision,backupSource:d,candidateSource:o,createdAt:l}),await h.rename(t.source,d),await h.rename(o,t.source);try{let f=await s.store.rollbackHarnessWorkspaceAtomically({receiptId:s.receiptId,workspaceId:e.id,expectedWorkspaceRevision:e.revision,expectedChannelRevision:e.currentChannel.revision,targetRelease:s.targetRelease,targetSourceRevision:r.sourceRevision,rollbackOf:s.rollbackOf,now:l});return f.receipt.decision!=="rolled_back"?await j(t.source,d):await h.rm(d,{recursive:!0,force:!0}),await h.rm(u,{force:!0}),f}catch(f){throw await j(t.source,d).catch(()=>{}),await h.rm(u,{force:!0}).catch(()=>{}),f}}finally{await h.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}w($e,"rollbackLocalHarnessWorkspaceRelease");async function We(s){let e=P.parse(s.proposal);if(e.expectedWorkspace.workspaceId!==s.workspace.id)throw new Error("Refiner proposal targets a different Harness workspace.");if(e.route==="memory")return we({proposal:e,now:s.now});let r=D(s.storeDir,s.workspace.id),t=await I({workspaceId:s.workspace.id,sourceDir:r.source});if(t.sourceRevision!==e.expectedWorkspace.sourceRevision)throw new Error("Refiner proposal source revision no longer matches the Local Harness workspace.");let n=R.join(r.root,`.validation-candidate-${O()}`);await h.cp(r.source,n,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});let o=(s.now??(()=>new Date().toISOString()))();try{await ae(n,e);let i=await I({workspaceId:s.workspace.id,sourceDir:n}),l=new Map(i.manifest.files.map(a=>[a.path,a])),d=new Map(e.edits.map(a=>[a.target,a])),u=se(t),f=se(i);return Promise.all(e.validationPlan.map(async a=>{let v="passed",m="The candidate Harness source compiles and preserves its manifest contract.";try{if(a.kind==="observed_recovery"){let p=e.evidence.filter(c=>c.kind==="recovery");if(p.length===0)throw new Error("Observed-recovery validation requires recorded recovery evidence.");m=`Validated ${p.length} immutable recovery evidence reference(s) before candidate advancement.`}else if(a.kind==="prompt"){let p=e.edits.filter(c=>c.route==="prompt"&&c.target!=="harness.json");if(p.length===0)throw new Error("Prompt validation requires an instruction-file edit.");for(let c of p){let g=l.get(c.target);if(c.operation==="delete"){if(g)throw new Error(`Deleted instruction ${c.target} remains declared.`)}else if(g?.kind!=="instruction")throw new Error(`Instruction ${c.target} is not declared in the candidate Harness.`);if(c.content!==null&&/\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]/i.test(c.content))throw new Error(`Instruction ${c.target} appears to contain credential material.`)}m=`Validated ${p.length} textual instruction edit(s) and compiled candidate ${i.harnessRelease.id}.`}else if(a.kind==="skill"){let p=e.edits.filter(c=>c.route==="skill"&&c.target!=="harness.json");if(p.length===0)throw new Error("Skill validation requires a declared Skill-file edit.");for(let c of p){let g=l.get(c.target);if(c.operation==="delete"){if(g)throw new Error(`Deleted Skill ${c.target} remains declared.`);continue}if(g?.kind!=="skill")throw new Error(`Skill ${c.target} is not declared in the candidate Harness.`);let k=d.get(c.target)?.content;if(!k)throw new Error(`Skill edit ${c.target} has no content.`);let H=W(k);if(!H.name||!H.description||H.messages.length>0)throw new Error(`Skill ${c.target} is invalid: ${H.messages.join(" ")}`)}m=`Validated ${p.length} Skill edit(s), Skill frontmatter, and compiled candidate ${i.harnessRelease.id}.`}else if(a.kind==="dependency"){let p=i.manifest.files.find(c=>c.kind==="dependency_lock");if(!p)throw new Error("Candidate Harness has no dependency lock.");JSON.parse(await h.readFile(oe(n,p.path),"utf8")),m=`Validated dependency lock ${p.path} and compiled candidate ${i.harnessRelease.id}.`}else if(a.kind==="schema")P.parse(e),m=`Validated proposal, manifest, and candidate release schemas for ${i.harnessRelease.id}.`;else if(a.kind==="package"){let p=e.edits.filter(c=>c.route==="agent"&&c.operation!=="delete"&&c.target!=="harness.json");for(let c of p){if(!c.content)throw new Error(`Agent edit ${c.target} has no source.`);me(c.content,{mode:"transform",sourceUrl:c.target,sourceMap:!1})}m=p.length>0?`Syntax-checked ${p.length} Agent source edit(s) and compiled candidate ${i.harnessRelease.id}.`:`Compiled candidate package ${i.harnessRelease.id} and preserved the Harness source manifest contract.`}else if(a.kind==="component_activation"){let p=e.edits.filter(c=>c.target!=="harness.json");if(p.length===0)throw new Error("Component activation requires a concrete Harness component edit.");if(e.route==="agent"){if(p.filter(g=>g.operation!=="delete").length>0)throw new Error("Desktop Work does not compile or execute released Agent source; use an active instruction or standalone Skill, or add an Agent executor before release.");m=`Confirmed ${p.length} deleted Agent component(s) were inactive in Desktop Work.`}else{if(!["prompt","skill"].includes(e.route))throw new Error(`Desktop Work has no activation policy for ${e.route} proposals.`);let c=e.route==="prompt"?"instruction":"skill";for(let g of p){let k=f.components.find(H=>H.path===g.target&&H.kind===c);if(g.operation==="delete"?k:!k)throw new Error(`${c} ${g.target} is not reflected in the candidate Desktop Work runtime surface.`)}if(u.contentHash===f.contentHash)throw new Error("The candidate does not change the effective Desktop Work runtime surface.");m=`Activated ${p.length} ${c} edit(s) in the candidate Desktop Work runtime surface.`}}else a.kind==="business_formula"?(v="blocked",m="Business or financial logic is retained for review until an approved deterministic fixture supplies inputs and expected outputs."):a.kind==="targeted_evaluation"?(v="blocked",m="This sensitive change requires an explicit authority-preserving targeted Evaluation before release."):a.kind==="file_render"?(v="blocked",m="File-render validation requires an exact produced artifact reference; no artifact was attached to this Harness-source proposal."):(v="blocked",m=`Local targeted validation does not yet own ${a.kind}; it requires its dedicated validator.`)}catch(p){v="failed",m=p instanceof Error?p.message:String(p)}return q({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${e.id}-${a.id}`,proposal:{id:e.id,contentHash:e.contentHash},validationId:a.id,kind:a.kind,status:v,summary:m,evidenceRefs:e.evidence,createdAt:o,metadata:{candidateHarnessRelease:{id:i.harnessRelease.id,contentHash:i.harnessRelease.contentHash},sourceRevision:i.sourceRevision,...a.kind==="component_activation"?{targetRuntime:"desktop_work",beforeEffectiveRuntimeHash:u.contentHash,afterEffectiveRuntimeHash:f.contentHash,activatedComponentRefs:f.components,inactiveAgentRefs:f.inactiveAgents}:{}}})}))}catch(i){let l=i instanceof Error?i.message:String(i);return e.validationPlan.map(d=>q({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${e.id}-${d.id}`,proposal:{id:e.id,contentHash:e.contentHash},validationId:d.id,kind:d.kind,status:"failed",summary:l,evidenceRefs:e.evidence,createdAt:o,metadata:{}}))}finally{await h.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}w(We,"validateLocalHarnessRefinerProposal");function se(s){let e=[...s.agentSnapshot.instructions.map(t=>({kind:"instruction",path:t.path,contentHash:t.contentHash})),...s.agentSnapshot.skills.map(t=>({kind:"skill",path:t.path,contentHash:t.contentHash}))].sort((t,n)=>t.path.localeCompare(n.path)),r=s.agentSnapshot.agents.map(t=>({path:t.path,contentHash:t.contentHash})).sort((t,n)=>t.path.localeCompare(n.path));return{contentHash:_({schemaVersion:"openpond.desktopWorkHarnessSurface.v1",components:e}),components:e,inactiveAgents:r}}w(se,"desktopWorkRuntimeSurface");function we(s){let e=(s.now??(()=>new Date().toISOString()))(),r=s.proposal.edits.find(t=>t.route==="memory");return s.proposal.validationPlan.map(t=>{let n="passed",o="Memory candidate is bounded, scoped, and contains no obvious credential material.";try{if(t.kind==="observed_recovery"){if(!s.proposal.evidence.some(i=>i.kind==="recovery"))throw new Error("Observed-recovery validation requires recorded recovery evidence.");o="Memory proposal is grounded in immutable recovery evidence."}else if(t.kind==="memory"){if(!r||!/^memory\/[a-z0-9][a-z0-9-]{0,119}$/.test(r.target))throw new Error("Memory proposal requires one safe memory/<slug> target.");let i=s.proposal.metadata.expectedMemory;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Memory proposal requires an expected revision snapshot.");let l=i;if(l.key!==fe(r.target))throw new Error("Memory proposal expected revision targets a different key.");if(l.revision!==null&&(!Number.isInteger(l.revision)||Number(l.revision)<1))throw new Error("Memory proposal expected revision is invalid.");if(l.contentHash!==null&&typeof l.contentHash!="string")throw new Error("Memory proposal expected content hash is invalid.");if(l.status!==null&&l.status!=="active"&&l.status!=="deleted")throw new Error("Memory proposal expected status is invalid.");if(l.revision===null&&(l.contentHash!==null||l.status!==null))throw new Error("New memory snapshot must not claim existing content or status.");if(l.revision!==null&&(typeof l.contentHash!="string"||l.status===null))throw new Error("Existing memory snapshot requires its content hash and status.");if(r.operation==="delete"&&l.status!=="active")throw new Error("Memory deletion requires an active expected revision.");if(r.operation!=="delete"){if(!r.content?.trim()||r.content.length>24e3)throw new Error("Memory content must contain 1-24,000 characters.");if(/\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]/i.test(r.content))throw new Error("Memory content appears to contain credential material.")}}else n="blocked",o=`Memory validation cannot satisfy ${t.kind}.`}catch(i){n="failed",o=i instanceof Error?i.message:String(i)}return q({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${s.proposal.id}-${t.id}`,proposal:{id:s.proposal.id,contentHash:s.proposal.contentHash},validationId:t.id,kind:t.kind,status:n,summary:o,evidenceRefs:s.proposal.evidence,createdAt:e,metadata:{externalState:"harness_memory"}})})}w(we,"validateMemoryProposal");function fe(s){let e=s.replaceAll("\\","/"),r=/^memory\/([a-z0-9][a-z0-9-]{0,119})$/.exec(e);if(!r)throw new Error(`Invalid Harness memory target: ${s}.`);return r[1]}w(fe,"memoryKeyFromTarget");async function te(s){let e=await s.store.getHarnessWorkspace(s.workspaceId);if(!e)throw new Error(`Harness workspace ${s.workspaceId} does not exist.`);let r=D(s.storeDir,e.id),t=R.join(r.root,"source-swap.json"),n=await h.readFile(t,"utf8").then(JSON.parse).catch(l=>{if(l.code==="ENOENT")return null;throw l});if(!n)return"none";let o=await I({workspaceId:e.id,sourceDir:r.source});if(e.sourceRevision===n.nextSourceRevision&&o.sourceRevision===n.nextSourceRevision)return await h.rm(n.backupSource,{recursive:!0,force:!0}),await h.rm(t,{force:!0}),"completed";let i=await I({workspaceId:e.id,sourceDir:n.backupSource});if(e.sourceRevision===n.previousSourceRevision&&i.sourceRevision===n.previousSourceRevision)return await j(r.source,n.backupSource),await h.rm(t,{force:!0}),"restored";throw new Error("Harness source-swap recovery cannot reconcile filesystem and workspace revisions.")}w(te,"recoverLocalHarnessSourceSwap");async function ae(s,e){for(let r of e.edits){let t=oe(s,r.target);if(r.operation==="delete"){await h.rm(t,{force:!1});continue}if(r.content===null)throw new Error(`Refiner edit ${r.id} has no content.`);if(r.operation==="create")await h.mkdir(R.dirname(t),{recursive:!0}),await h.writeFile(t,r.content,{flag:"wx"});else{let n=await h.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`Refiner update target must be a regular file: ${r.target}`);await h.writeFile(t,r.content,{flag:"w"})}}}w(ae,"applyOverlayEdits");function oe(s,e){let r=R.resolve(s),t=R.resolve(r,...e.replaceAll("\\","/").split("/")),n=R.relative(r,t);if(!n||n.startsWith("..")||R.isAbsolute(n))throw new Error(`Refiner edit target escapes the Harness source: ${e}`);return t}w(oe,"containedPath");async function ne(s,e){let r=`${s}.${O()}.tmp`;await h.writeFile(r,`${JSON.stringify(e,null,2)}
|
|
3
|
+
`,{flag:"wx"}),await h.rename(r,s)}w(ne,"writeSwapJournal");async function j(s,e){await h.rm(s,{recursive:!0,force:!0}),await h.rename(e,s)}w(j,"restoreSource");var b="desktop-personal",ie="personal-default";async function qe(s){let e=await s.store.getSelectedHarnessWorkspace({ownerKind:"personal",ownerId:b});if(e&&e.metadata.selectionEligible!==!1)return await te({store:s.store,storeDir:s.storeDir,workspaceId:e.id}),M(s.store,e.id,e.currentChannel.release?.contentHash??null);let r=(await s.store.listHarnessWorkspaces({ownerKind:"personal",ownerId:b})).find(o=>o.metadata.selectionEligible!==!1);if(r)return await s.store.selectHarnessWorkspace({ownerKind:"personal",ownerId:b,workspaceId:r.id,updatedAt:(s.now??(()=>new Date().toISOString()))()}),M(s.store,r.id,r.currentChannel.release?.contentHash??null);let t=await s.loadProfileState(),n=t.mode==="local"&&t.sourcePath&&!t.error?await ee({store:s.store,storeDir:s.storeDir,id:ie,ownerId:b,name:t.activeProfile?.trim()||"Personal Harness",profile:t,now:s.now}):await Z({store:s.store,storeDir:s.storeDir,id:ie,ownerId:b,name:"Personal Harness",now:s.now});return await s.store.selectHarnessWorkspace({ownerKind:"personal",ownerId:b,workspaceId:n.workspace.id,updatedAt:(s.now??(()=>new Date().toISOString()))()}),n.release}w(qe,"ensureSelectedLocalHarnessWorkspace");async function ce(s){let e=await s.getSelectedHarnessWorkspace({ownerKind:"personal",ownerId:b});return e?M(s,e.id,e.currentChannel.release?.contentHash??null):null}w(ce,"resolveSelectedLocalHarnessRelease");async function M(s,e,r){if(!r)throw new Error(`Selected Harness workspace ${e} has no current release.`);let t=await s.getHarnessReleaseRecord(r);if(!t||t.workspaceId!==e)throw new Error(`Selected Harness workspace ${e} points to a missing release ${r}.`);return A(t.agentSnapshot,"Selected Agent snapshot"),A(t.harnessRelease,"Selected Harness release"),t}w(M,"requireCurrentRelease");async function Ke(s,e){if(e){let n=await s.getHarnessReleaseRecord(e.contentHash);if(!n||n.harnessRelease.id!==e.id)throw new Error("The selected immutable Harness release is unavailable.");let o=await s.getHarnessWorkspace(n.workspaceId);if(!o||o.ownerScope.kind!=="personal"||o.ownerScope.id!==b)throw new Error("The selected Harness release is not available to this local owner.");return A(n.agentSnapshot,"Selected Agent snapshot"),A(n.harnessRelease,"Selected Harness release"),T({workspace:o,release:n})}let r=await ce(s);if(!r)return null;let t=await s.getSelectedHarnessWorkspace({ownerKind:"personal",ownerId:b});if(!t||t.id!==r.workspaceId)throw new Error("Selected Harness workspace changed while its release was being admitted.");return T({workspace:t,release:r})}w(Ke,"loadSelectedLocalHarnessRuntime");async function T(s){let{workspace:e,release:r}=s;if(r.workspaceId!==e.id)throw new Error("Harness release does not belong to the requested workspace.");let t=y.join(r.bundlePath,"source");await Promise.all(r.harnessRelease.files.map(a=>ve(t,a.path,a.contentHash)));let n=await Promise.all(r.agentSnapshot.instructions.map(async a=>({path:a.path,content:await z(t,a.path,a.contentHash)}))),o=[],i=new Map;for(let a of r.agentSnapshot.skills){let v=await z(t,a.path,a.contentHash),m=W(v);if(!m.name||!m.description||m.messages.length>0)throw new Error(`Released Harness Skill ${a.path} is invalid: ${m.messages.join(" ")||"missing name or description"}`);if(i.has(m.name))throw new Error(`Released Harness has duplicate Skill ${m.name}.`);let p=`${y.posix.dirname(a.path)}/`,c=r.harnessRelease.files.filter(k=>k.path.startsWith(p)&&k.path!==a.path).map(k=>k.path.slice(p.length)).sort(),g={name:m.name,description:m.description,path:a.path,scope:"profile",enabled:!0,sourcePath:t,charCount:v.length,sourceHash:a.contentHash,validationStatus:"valid",validationMessages:[],resourceFiles:c};o.push(g),i.set(g.name,async()=>{let k=await z(t,a.path,a.contentHash),H=W(k);if(!H.name||!H.description||H.messages.length>0)throw new Error(`Released Harness Skill ${a.path} failed validation while loading.`);return{name:H.name,description:H.description,body:H.body,path:a.path,sourceHash:a.contentHash,charCount:k.length,packagePath:y.join(t,...y.posix.dirname(a.path).split("/")),resourceFiles:c}})}o.sort((a,v)=>a.name.localeCompare(v.name));let l={profileSourcePath:t,skills:o,readSkill:i.size>0?async a=>{let v=i.get(a);if(!v)throw new Error(`Released Harness Skill not found: ${a}`);return v()}:null},d=n.sort((a,v)=>a.path.localeCompare(v.path)).map(({path:a,content:v})=>[`Active Harness instruction (${a}):`,v.trim()].join(`
|
|
4
|
+
`)).filter(a=>a.trim().length>0),f=[["Harness capability receipt:",JSON.stringify({harnessRelease:{id:r.harnessRelease.id,contentHash:r.harnessRelease.contentHash},agentSnapshot:{id:r.agentSnapshot.id,contentHash:r.agentSnapshot.contentHash},files:r.harnessRelease.files.map(a=>({path:a.path,contentHash:a.contentHash})),skills:r.agentSnapshot.skills.map(a=>a.path),agents:r.agentSnapshot.agents.map(a=>a.path),tools:r.agentSnapshot.toolDeclarations.map(a=>a.name),capabilityRequirements:r.agentSnapshot.capabilityRequirements})].join(`
|
|
5
|
+
`),d.length>0?["Active Harness preflight:","Apply the following released instructions when planning work and immediately before every tool call.","Preflight each call: (1) identify any active instruction that matches the planned operation, (2) inspect the exact tool arguments for a forbidden pattern, and (3) rewrite the call before sending it when a pattern matches. Compliance is required even when the prohibited call might still succeed.",...d].join(`
|
|
6
|
+
|
|
7
|
+
`):null].filter(a=>!!a?.trim()).join(`
|
|
8
|
+
|
|
9
|
+
`);return{workspace:e,release:r,instructionContext:f,skillRuntime:l}}w(T,"loadLocalHarnessRuntimeFromRelease");async function z(s,e,r){let t=y.resolve(s,...e.split("/")),n=y.relative(y.resolve(s),t);if(!n||n.startsWith("..")||y.isAbsolute(n))throw new Error(`Released Harness asset escapes its bundle: ${e}`);let o=await le.readFile(t),i=N(o);if(i!==r)throw new Error(`Released Harness asset ${e} is ${i}; expected ${r}.`);return new TextDecoder("utf-8",{fatal:!0}).decode(o)}w(z,"readVerifiedAsset");async function ve(s,e,r){let t=y.resolve(s,...e.split("/")),n=y.relative(y.resolve(s),t);if(!n||n.startsWith("..")||y.isAbsolute(n))throw new Error(`Released Harness asset escapes its bundle: ${e}`);let o=N(await le.readFile(t));if(o!==r)throw new Error(`Released Harness asset ${e} is ${o}; expected ${r}.`)}w(ve,"verifyAsset");import{randomUUID as ge}from"node:crypto";var F=S.object({revision:S.number().int().nonnegative(),overlay:$}).strict(),He=F.extend({proposal:P}).strict(),V=class{constructor(e){this.client=e}client;static{w(this,"HostedHarnessOverlayStorage")}async getHarnessRunOverlay(e){let r=await this.client.request({contractVersion:x,requestId:ge(),operation:"harness/overlay/get",params:{runId:e}});return r===null?null:F.parse(r).overlay}async putHarnessRunOverlay(e){let r=$.parse(e.overlay);if(!e.requestId.trim()||r.revision!==(e.expectedRevision===null?0:e.expectedRevision+1))throw new Error("Hosted Harness overlay mutation requires a stable request and next revision.");let t=F.parse(await this.client.request({contractVersion:x,requestId:e.requestId,operation:"harness/overlay/put",params:{runId:r.runId,expectedRevision:e.expectedRevision,overlay:r}}));if(t.revision!==r.revision||t.overlay.contentHash!==r.contentHash)throw new Error("Host Harness overlay response changed committed identity.");return t.overlay}async createHarnessRunOverlay(e){if(e.revision!==0||e.status!=="active")throw new Error("A new Harness run overlay must be active at revision 0.");return this.putHarnessRunOverlay({overlay:e,expectedRevision:null,requestId:`harness-overlay:${e.runId}:${e.contentHash}`})}async ensureHarnessRunOverlay(e){let r=await this.getHarnessRunOverlay(e.runId);if(r){if(r.workspace.workspaceId!==e.workspace.id||r.baseHarnessRelease.id!==e.harnessRelease.id||r.baseHarnessRelease.contentHash!==e.harnessRelease.contentHash)throw new Error("The durable Agent run is already bound to another Harness release.");return r}let t=L({schemaVersion:"openpond.harnessRunOverlay.v1",id:`overlay-${_({runId:e.runId,harnessRelease:e.harnessRelease}).slice(0,24)}`,runId:e.runId,baseHarnessRelease:e.harnessRelease,workspace:{workspaceId:e.workspace.id,revision:e.workspace.revision,sourceRevision:e.workspace.sourceRevision,channelRevision:e.workspace.currentChannel.revision},revision:0,status:"active",edits:[],createdAt:e.admittedAt,updatedAt:e.admittedAt,metadata:{}});return this.createHarnessRunOverlay(t)}async appendHarnessRunOverlayEditsAtomically(e){return this.transition(e,"append")}async freezeHarnessRunOverlayAtomically(e){return this.transition({...e,edits:[]},"freeze")}async abandonHarnessRunOverlayAtomically(e){return this.transition({...e,edits:[]},"abandon")}async freezeHarnessRunOverlayWithProposalAtomically(e){let r=await this.getHarnessRunOverlay(e.runId);if(!r||r.revision!==e.expectedRevision||r.status!=="active")throw new Error("Hosted Harness overlay revision or status changed.");let t=new Set(r.edits.map(u=>u.id));for(let u of e.edits){if(t.has(u.id))throw new Error(`Harness overlay edit id already exists: ${u.id}.`);t.add(u.id)}let{contentHash:n,...o}=r,i=L({...o,revision:r.revision+1,status:"frozen",edits:[...r.edits,...e.edits],updatedAt:e.updatedAt}),l=P.parse(e.buildProposal(i)),d=He.parse(await this.client.request({contractVersion:x,requestId:`harness-proposal:${i.runId}:${l.contentHash}`,operation:"harness/overlay/freezeProposal",params:{runId:i.runId,expectedRevision:r.revision,overlay:i,proposal:l}}));if(d.overlay.contentHash!==i.contentHash||d.proposal.contentHash!==l.contentHash)throw new Error("Host Harness proposal response changed committed identity.");return{overlay:d.overlay,proposal:d.proposal}}async transition(e,r){let t=await this.getHarnessRunOverlay(e.runId);if(!t||t.revision!==e.expectedRevision||t.status==="abandoned"||r!=="abandon"&&t.status!=="active")throw new Error("Hosted Harness overlay revision or status changed.");if(r==="append"&&e.edits.length===0)throw new Error("Harness overlay append requires edits.");let n=new Set(t.edits.map(d=>d.id));for(let d of e.edits){if(n.has(d.id))throw new Error(`Harness overlay edit id already exists: ${d.id}.`);n.add(d.id)}let{contentHash:o,...i}=t,l=L({...i,revision:t.revision+1,status:r==="append"?"active":r==="freeze"?"frozen":"abandoned",edits:[...t.edits,...e.edits],updatedAt:e.updatedAt});return this.putHarnessRunOverlay({overlay:l,expectedRevision:t.revision,requestId:`harness-overlay:${l.runId}:${l.contentHash}`})}};var ke=S.object({workspace:J,release:S.object({id:S.string().min(1),contentHash:S.string().regex(/^[a-f0-9]{64}$/),sourceRevision:S.string().min(1),assetsPath:S.string().min(1)}).strict()}).strict();async function he(s,e=null){let r=await s.request({contractVersion:x,requestId:Re(),operation:"harness/get",params:{reference:e}});if(r===null)return null;let t=ke.parse(r);if(!E.isAbsolute(t.release.assetsPath))throw new Error("Hosted Harness assets path must be absolute.");let[n,o]=await Promise.all([C(E.join(t.release.assetsPath,"agent-snapshot.json"),"utf8"),C(E.join(t.release.assetsPath,"harness-release.json"),"utf8")]),i=Y.parse({schemaVersion:"openpond.localHarnessReleaseRecord.v1",workspaceId:t.workspace.id,sourceRevision:t.release.sourceRevision,agentSnapshot:B.parse(JSON.parse(n)),harnessRelease:K.parse(JSON.parse(o)),bundlePath:t.release.assetsPath,createdAt:new Date().toISOString()});if(i.harnessRelease.id!==t.release.id||i.harnessRelease.contentHash!==t.release.contentHash||(e!==null?e.id!==t.release.id||e.contentHash!==t.release.contentHash:t.workspace.currentChannel.release?.contentHash!==t.release.contentHash))throw new Error("Hosted Harness release differs from its bound workspace.");return T({workspace:t.workspace,release:i})}w(he,"loadHostedHarnessRuntime");async function ur(s,e){let r=e.profileComponentBinding,t=e.profileWorkflowBinding;if(r){if(t||e.currentProfile?.profileId!==r.profileId)throw new Error("Profile component binding differs from the session Profile reference.");let o=await de(s,r.harnessRelease);if(pe(o,r.profileId,r.sourceRevision,e.currentProfile?.repositoryId),r.target.kind==="profile")return o;if(r.target.kind==="skill"){let u=r.target.skillPath;if(!o.release.agentSnapshot.skills.some(a=>a.path===u))throw new Error("Bound Profile Skill is unavailable in its released source.");let f=await C(E.join(o.release.bundlePath,"source",u),"utf8");return{...o,instructionContext:[o.instructionContext,`Released Profile Skill (${u}):
|
|
10
|
+
${f}`].join(`
|
|
11
|
+
|
|
12
|
+
`)}}let i=await ue(o),l=r.target.actionId,d=i.actions.find(u=>u.id===l);if(!d)throw new Error("Bound Profile Agent action is unavailable in its released source.");return{...o,workflowAction:d}}if(t){if(e.currentProfile?.profileId!==t.profileId)throw new Error("Profile workflow binding differs from the session Profile reference.");let o=await de(s,t.harnessRelease);pe(o,t.profileId,t.sourceRevision,e.currentProfile?.repositoryId);let i=await ue(o),l=Q({binding:t,harnessRelease:o.release.harnessRelease,catalog:i.catalog,catalogHash:i.catalogHash}),d=l.invocation.kind==="agent_action"?l.invocation.actionId:null,u=d?i.actions.find(f=>f.id===d):void 0;if(d&&!u)throw new Error(`Bound Profile action ${d} is missing from its release.`);return{...o,workflow:l,...u?{workflowAction:u}:{}}}let n=await new V(s).getHarnessRunOverlay(e.id);return he(s,n?.baseHarnessRelease??null)}w(ur,"loadHostedHarnessRuntimeForSession");async function de(s,e){let r=await he(s,e);if(!r)throw new Error("The bound Profile Harness release is unavailable.");return r}w(de,"requireRelease");function pe(s,e,r,t){let n=s.release.harnessRelease.metadata.profile;if(!n||typeof n!="object"||n.id!==e||n.sourceRevision!==r||n.repositoryId!==void 0&&n.repositoryId!==t)throw new Error("Bound Profile source differs from its released Harness source.")}w(pe,"assertProfileProvenance");async function ue(s){let e=E.join(s.release.bundlePath,"source"),[r,t]=await Promise.all([C(E.join(e,"workflows","catalog.json")),C(E.join(e,"workflows","actions.json"))]);return G({agentSnapshot:s.release.agentSnapshot,harnessRelease:s.release.harnessRelease,catalogBytes:r,actionBytes:t})}w(ue,"loadHostedProfileCatalog");export{Oe as a,$e as b,We as c,b as d,qe as e,ce as f,Ke as g,T as h,V as i,he as j,ur as k};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{$ as we,A as te,Aa as Te,B as ne,Ba as N,D as re,Da as De,E as ae,Ea as qe,F as oe,H as se,J as ce,L as de,N as y,O as u,P as me,Q as le,R as ue,S as pe,T as ge,V as he,W as fe,X as be,Z as xe,_ as ve,a as m,aa as Se,b as H,ba as P,ca as Re,da as _e,ea as _,fa as I,ha as ke,ia as Ie,ja as ye,ka as F,qa as Ae,r as X,sa as B,t as Y,ta as Le,va as Ce,w as Z,x as ee,y as V,ya as je,z as ie,za as Ee}from"./chunk-2O5UZOYL.js";import{a,b as E,c as l,e as C,l as k}from"./chunk-HZP5U2AA.js";import{b as e}from"./chunk-ES2ISFJC.js";import{a as c}from"./chunk-FTQLQJQV.js";var M=e.discriminatedUnion("kind",[e.object({kind:e.literal("manual"),identity:a}).strict(),e.object({kind:e.literal("schedule"),scheduledAt:l}).strict(),e.object({kind:e.literal("approved_count"),checkedAt:l}).strict()]),$=e.object({schemaVersion:e.literal("openpond.learningChain.v1"),id:a,revision:e.number().int().positive(),modelProjectId:a,activeIterationId:a.nullable(),acceptedParent:P.nullable().optional(),latestIterationId:a,lastReservedAt:l.nullable(),updatedAt:l}).strict(),K=e.object({eligible:e.number().int().nonnegative(),awaitingReview:e.number().int().nonnegative(),excluded:e.number().int().nonnegative(),consumed:e.number().int().nonnegative()}).strict(),Pe=e.object({schemaVersion:e.literal("openpond.learningConsumption.v1"),id:a,revision:e.literal(1),chainId:a,iterationId:a,evidence:u,decision:u,reservedAt:l}).strict(),Oe=e.object({schemaVersion:e.literal("openpond.learningIterationReservation.v1"),id:a,revision:e.number().int().positive(),chainId:a,iterationId:a,policy:u,trigger:M,requestHash:E,outcome:e.enum(["reserved","waiting_for_data","waiting_for_review"]),counts:K,budget:e.object({maximumSpendUsd:e.number().nonnegative(),reservedSpendUsd:e.number().nonnegative(),settledSpendUsd:e.number().nonnegative(),settledAt:l.nullable()}).strict(),createdAt:l,updatedAt:l}).strict();var v=e.object({operationId:a}),Ye=v.extend({action:e.literal("import_intake"),format:De,files:e.array(qe).min(1).max(100),expectedPreviewHash:e.string().length(64),name:e.string().trim().min(1).max(500),recordIds:e.array(e.string().min(1).max(200)).min(1).max(90)}).strict(),O=v.extend({action:e.literal("publish"),expectedRevision:e.number().int().nonnegative(),finalizeDraft:N.optional()}),He=e.discriminatedUnion("kind",[O.extend({kind:e.literal("asset"),content:Ie}).strict(),O.extend({kind:e.literal("definition"),content:me}).strict(),O.extend({kind:e.literal("reward"),content:ee}).strict(),O.extend({kind:e.literal("binding"),content:ie}).strict(),O.extend({kind:e.literal("source"),content:ue}).strict(),O.extend({kind:e.literal("policy"),content:we}).strict()]),Ze=v.extend({action:e.literal("publish_resources"),finalizeDraft:N.optional(),resources:e.array(e.union(He.options.map(t=>t.omit({operationId:!0,action:!0,finalizeDraft:!0})))).min(1).max(20)}).strict(),ei=v.extend({action:e.literal("submit_example"),example:ge}).strict(),ii=v.extend({action:e.literal("submit_feedback"),feedback:fe}).strict(),ti=v.extend({action:e.literal("apply_correction"),feedbackId:a,evidence:u}).strict(),ni=v.extend({action:e.literal("resolve_feedback"),feedbackId:a,expectedRevision:e.number().int().positive(),disposition:e.enum(["applied","rejected","superseded"]),decision:u.nullable(),note:e.string().max(2e4)}).strict(),ri=v.extend({action:e.literal("queue_grade"),evidence:u,target:e.enum(["observed","proposed_target"]),proposedTarget:y.nullable(),timeoutMs:e.number().int().min(100).max(3e5).default(3e4),maximumSpendUsd:e.number().nonnegative().max(1e3).default(0)}).strict(),ai=v.extend({action:e.literal("review"),evidence:u,expectedRevision:e.number().int().nonnegative(),disposition:e.enum(["approved","rejected","pending"]),targetApproval:e.enum(["approved","rejected","pending","not_required"]),approvedTarget:y.nullable(),observedGradeId:a.nullable(),targetGradeId:a.nullable(),note:e.string().max(2e4)}).strict(),oi=v.extend({action:e.literal("seal_batch"),batchId:a,taskDefinition:u,purpose:e.enum(["supervised_training","reward_training","evaluation"]),evidence:e.array(u).min(1).max(1e4),decisions:e.array(u).min(1).max(1e4)}).strict(),si=v.extend({action:e.literal("cancel_grade"),gradeId:a,expectedRevision:e.number().int().positive()}).strict(),ci=v.extend({action:e.literal("save_draft"),expectedRevision:e.number().int().nonnegative(),draft:Ee}).strict(),di=v.extend({action:e.literal("archive_draft"),draft:u}).strict(),mi=v.extend({action:e.literal("queue_reward_check"),draft:u,timeoutMs:e.number().int().min(100).max(3e5).default(3e4),maximumSpendUsd:e.number().nonnegative().max(1e3).default(0)}).strict(),li=v.extend({action:e.literal("cancel_reward_check"),checkId:a,expectedRevision:e.number().int().positive()}).strict(),ui=v.extend({action:e.literal("publish_checked_reward"),draft:u,checkId:a,checkRevision:e.number().int().positive()}).strict(),pi=v.extend({action:e.literal("reserve_iteration"),policy:u,trigger:M}).strict(),gi=v.extend({action:e.literal("cancel_iteration_reservation"),iterationId:a,expectedRevision:e.number().int().positive()}).strict(),hi=v.extend({action:e.literal("cancel_iteration"),iterationId:a,expectedRevision:e.number().int().positive()}).strict(),fi=v.extend({action:e.literal("retry_iteration_dispatch"),iterationId:a,expectedRevision:e.number().int().positive()}).strict(),Fe=e.union([ui,Ye,hi,fi,gi,pi,mi,li,ci,di,He,Ze,ei,ii,ti,ni,ri,ai,oi,si]);var bi=e.object({provider:a,protocol:a,payload:y}).strict(),Be=e.object({schemaVersion:e.literal("openpond.learningIterationDispatch.v1"),id:a,revision:e.number().int().positive(),iterationId:a,chainId:a,policy:u,batch:u,state:e.enum(["preparing","prepared","submitted","settled","blocked"]),submission:bi.nullable(),submissionHash:e.string().regex(/^[a-f0-9]{64}$/).nullable(),submissionStartedAt:l.nullable(),execution:C.nullable(),terminalReceipt:C.nullable(),cancelRequestedAt:l.nullable(),leaseOwner:a.nullable(),leaseGeneration:e.number().int().nonnegative(),leaseExpiresAt:l.nullable(),consecutiveFailures:e.number().int().nonnegative(),nextAttemptAt:l.nullable(),lastError:e.string().max(2e4).nullable(),createdAt:l,updatedAt:l}).strict().superRefine((t,i)=>{(!!t.submission!=!!t.submissionHash||t.submission&&k(t.submission)!==t.submissionHash)&&i.addIssue({code:"custom",path:["submissionHash"],message:"Dispatch submission identity changed."}),t.submissionStartedAt&&!t.submission&&i.addIssue({code:"custom",path:["submission"],message:"A started dispatch requires its persisted submission."}),t.execution&&!t.submissionStartedAt&&i.addIssue({code:"custom",path:["execution"],message:"An execution requires a started dispatch."}),["prepared","submitted"].includes(t.state)&&!t.submission&&i.addIssue({code:"custom",path:["state"],message:"A prepared dispatch requires its immutable submission."}),t.state==="submitted"&&!t.execution&&i.addIssue({code:"custom",path:["execution"],message:"A submitted dispatch requires an observed execution."}),t.state==="settled"&&t.submissionStartedAt&&!t.terminalReceipt&&i.addIssue({code:"custom",path:["terminalReceipt"],message:"A started dispatch requires terminal receipt evidence before settlement."}),!!t.leaseOwner!=!!t.leaseExpiresAt&&i.addIssue({code:"custom",path:["leaseOwner"],message:"Dispatch lease owner and expiration must be recorded together."})}),Ui=e.object({scope:a,dispatchId:a,submissionHash:e.string().regex(/^[a-f0-9]{64}$/),execution:C.nullable(),status:e.enum(["running","evaluating","succeeded","failed","cancelled"]),spendUsd:e.number().nonnegative(),cleanupComplete:e.boolean(),receipt:C.nullable(),evaluation:C.nullable(),candidate:C.nullable(),failure:e.string().max(2e4).nullable()}).strict().superRefine((t,i)=>{["succeeded","failed","cancelled"].includes(t.status)&&(!t.cleanupComplete||!t.receipt)&&i.addIssue({code:"custom",path:["receipt"],message:"Terminal execution requires an authoritative cleanup receipt."}),t.status!=="cancelled"&&!t.execution&&i.addIssue({code:"custom",path:["execution"],message:"The execution identity is required."}),t.candidate&&(t.status!=="succeeded"||!t.evaluation)&&i.addIssue({code:"custom",path:["candidate"],message:"A candidate requires successful retained evaluation."})});var Ue=e.object({schemaVersion:e.literal("openpond.learningSchedule.v1"),id:a,revision:e.number().int().positive(),policy:u,modelProjectId:a,executionOwner:e.enum(["local","hosted"]),state:e.enum(["scheduled","disabled","blocked"]),intervalSeconds:e.number().int().min(60).max(31536e3).nullable(),calendar:de.nullable().default(null),nextRunAt:l.nullable(),lastFire:u.nullable(),consecutiveFailures:e.number().int().nonnegative(),nextAttemptAt:l.nullable(),lastError:e.string().max(2e4).nullable(),createdAt:l,updatedAt:l}).strict().superRefine((t,i)=>{t.state!=="disabled"&&(!t.intervalSeconds&&!t.calendar||!t.nextRunAt)&&i.addIssue({code:"custom",path:["nextRunAt"],message:"An active timer must retain its cadence and due time."}),t.state==="disabled"&&t.nextRunAt&&i.addIssue({code:"custom",path:["nextRunAt"],message:"A disabled timer cannot have a pending occurrence."}),t.intervalSeconds&&t.calendar&&i.addIssue({code:"custom",path:["calendar"],message:"A timer uses either an interval or a nightly calendar."})}),Ve=e.object({schemaVersion:e.literal("openpond.learningScheduleFire.v1"),id:a,revision:e.literal(1),scheduleId:a,policy:u,scheduledAt:l,coalescedThroughAt:l,coalescedCount:e.number().int().nonnegative(),outcome:e.enum(["reserved","waiting_for_data","waiting_for_review","skipped"]),reason:e.enum(["active_iteration","cooldown","daily_budget"]).nullable(),iteration:e.object({id:a,revision:e.number().int().positive()}).strict().nullable(),createdAt:l,contentHash:E}).strict().superRefine((t,i)=>{(t.outcome==="skipped"!=!!t.reason||t.outcome!=="skipped"!=!!t.iteration)&&i.addIssue({code:"custom",path:["outcome"],message:"A fire retains either its reservation or its explicit skip reason."})});function Je(t){H(t,262144);let i=je.parse(t.fields),n=t.base?V.parse(t.base):null;if(n&&n.id!==t.id)throw new m("reward_authoring_base_mismatch",422);let o=i.fixtures?.length?F({text:JSON.stringify(i.fixtures),path:"reward-fixtures.json",mediaType:"application/json",visibility:"verifier"}):null,r=null,s,d;if(i.kind==="custom_verifier")r=F({text:i.code,path:"verifier.mjs",mediaType:"application/javascript",visibility:"verifier"}),s={kind:i.kind,verifierRef:r.asset,exportName:i.exportName,timeoutMs:T(i.timeout,"Time limit"),networkPolicy:"none",...n?.implementation.kind==="custom_verifier"&&n.implementation.runtime!==void 0?{runtime:n.implementation.runtime}:{}};else if(i.kind==="model_judge"||i.kind==="human"){if(!i.rubric.trim())throw new m("reward_rubric_required",422,"Write the rubric before checking or publishing this Reward.");if(r=F({text:i.rubric,path:"rubric.md",mediaType:"text/markdown",visibility:"verifier"}),i.kind==="human")s={kind:i.kind,rubricRef:r.asset,reviewerRole:i.reviewerRole};else{let h={providerId:i.providerId,modelId:i.modelId,revision:i.modelRevision.trim()||null},x=T(i.temperature,"Temperature"),w=n?.implementation,b=w?.kind==="model_judge"&&w.rubricRef.contentHash===r.asset.contentHash&&w.model?.providerId===h.providerId&&w.model?.modelId===h.modelId&&w.model?.revision===h.revision&&(w.temperature??0)===x&&n?.fixtureSetRef?.contentHash===o?.asset.contentHash;s={kind:i.kind,rubricRef:r.asset,model:h,temperature:x,calibrationStatus:b?w.calibrationStatus:"pending"},b&&(d=n?.calibrationCheckRef)}}else i.kind==="learned_model"?(D(i.inputContract,"Model input contract"),r=F({text:i.inputContract,path:"input-contract.json",mediaType:"application/json",visibility:"verifier"}),s={kind:i.kind,modelVersion:{id:i.learnedId,contentHash:i.learnedHash},inputContract:r.asset}):i.kind==="state"?s={kind:i.kind,config:{fields:$e(i.fields)}}:i.kind==="content"?s={kind:i.kind,config:{outputField:i.outputField,expectedField:i.expectedField,...i.expectedValue?{expectedValue:i.expectedValue}:{}}}:i.kind==="schema"?s={kind:i.kind,config:{jsonSchema:D(i.schema,"Output schema")}}:i.kind==="artifact"?s={kind:i.kind,config:{refIncludes:i.reference}}:s={kind:i.kind,config:{requiredEvents:$e(i.events)}};let g=[...r?[r]:[],...o?[o]:[]];return{reward:re({schemaVersion:"openpond.rewardRelease.v1",id:t.id,revision:(n?.revision??0)+1,name:i.name,description:i.description,feedbackKey:i.feedbackKey??Z({id:t.id}),implementation:s,rawScore:i.kind==="learned_model"?{minimum:T(i.minimum,"Minimum score"),maximum:T(i.maximum,"Maximum score")}:{minimum:0,maximum:1},assets:g.map(h=>h.asset),...o?{fixtureSetRef:o.asset}:{},...d?{calibrationCheckRef:d}:{}}),assets:g}}c(Je,"compileRewardAuthoring");function D(t,i){try{let n=JSON.parse(t);return H(n,131072),y.parse(n)}catch{throw new m("reward_authoring_json_invalid",422,`${i} must be a JSON object.`)}}c(D,"parseRewardAuthoringObject");function T(t,i){let n=Number(t);if(!t.trim()||!Number.isFinite(n))throw new m("reward_authoring_number_invalid",422,`${i} must be a finite number.`);return n}c(T,"authoringNumber");function $e(t){return t.split(",").map(i=>i.trim()).filter(Boolean)}c($e,"split");var ze=e.object({id:a,name:e.string().trim().min(1).max(500),input:y,output:y,expectedOutput:y.nullable(),evaluatorContext:y.nullable(),artifactRefs:e.array(a).max(100),runtimeEventRefs:e.array(a).max(100),infrastructureError:e.string().max(2e4).nullable(),expected:e.discriminatedUnion("status",[e.object({status:e.literal("scored"),minimum:e.number().finite(),maximum:e.number().finite(),passed:e.boolean().nullable()}).strict(),e.object({status:e.enum(["pending","unavailable","failed"])}).strict()])}).strict().superRefine((t,i)=>{t.expected.status==="scored"&&t.expected.minimum>t.expected.maximum&&i.addIssue({code:"custom",path:["expected"],message:"Expected score minimum must not exceed maximum."})}),xi=e.object({id:a,packageVersion:e.string().min(1).max(100),engine:e.string().min(1).max(200)}).strict(),Ne=e.object({fixture:e.object({id:a,contentHash:E}).strict(),result:ne,matchesExpectation:e.boolean()}).strict(),Me=e.object({schemaVersion:e.literal("openpond.rewardCheckRun.v1"),id:a,revision:e.number().int().positive(),draft:u,reward:u,snapshotHash:E,fixtureRefs:e.array(e.object({id:a,contentHash:E}).strict()).min(1).max(50),status:e.enum(["queued","running","completed","failed","cancelling","cancelled"]),runtime:xi.nullable(),results:e.array(Ne).max(50),matchesExpectations:e.boolean().nullable(),failure:e.string().max(2e4).nullable(),timeoutMs:e.number().int().min(100).max(3e5),maximumSpendUsd:e.number().nonnegative().max(1e3),judgeCalls:e.array(ce).max(1e3).optional(),requestedBy:a.optional(),leaseOwner:a.nullable(),leaseExpiresAt:l.nullable(),attemptCount:e.number().int().nonnegative(),createdAt:l,updatedAt:l}).strict();function vi(t){if(!t.length||t.length>50)throw new m("reward_check_fixtures_required",422,"Add between one and 50 fixtures before checking this Reward.");if(new Set(t.map(i=>i.id)).size!==t.length)throw new m("reward_fixture_id_duplicate",422);return t.map(i=>ze.parse({id:i.id,name:i.name,input:D(i.input,`${i.name}: input`),output:D(i.output,`${i.name}: output`),expectedOutput:i.expectedOutput.trim()?D(i.expectedOutput,`${i.name}: expected answer`):null,evaluatorContext:i.evaluatorContext.trim()?D(i.evaluatorContext,`${i.name}: evaluator context`):null,artifactRefs:i.artifactRefs.map(n=>n.trim()).filter(Boolean),runtimeEventRefs:i.runtimeEventRefs.map(n=>n.trim()).filter(Boolean),infrastructureError:i.infrastructureError||null,expected:i.expectedStatus==="scored"?{status:i.expectedStatus,minimum:T(i.minimumScore,`${i.name}: minimum score`),maximum:T(i.maximumScore,`${i.name}: maximum score`),passed:i.expectedPassed==="any"?null:i.expectedPassed==="true"}:{status:i.expectedStatus}}))}c(vi,"compileRewardFixtures");function lt(t,i){let n=Je({id:t.targetId,fields:t.fields,base:i}),o=vi(t.fields.fixtures??[]),r=o.map(s=>({id:s.id,contentHash:k(s)}));return{...n,fixtures:o,fixtureRefs:r,snapshotHash:k({reward:n.reward,fixtures:o})}}c(lt,"compileRewardCheck");async function ut(t){let i=ze.parse(t.fixture),n=X.parse({id:i.id,clusterKey:i.id,split:"validation",input:i.input,expectedOutput:i.expectedOutput,privilegedContextRef:null}),o=ae({schemaVersion:"openpond.rewardBinding.v1",id:`fixture-binding-${k(_(t.reward))}`,revision:1,sources:[{graderId:t.reward.id,reward:_(t.reward),role:"evaluation",normalization:t.reward.rawScore.minimum===0&&t.reward.rawScore.maximum===1?{kind:"identity"}:{kind:"linear",minimum:t.reward.rawScore.minimum,maximum:t.reward.rawScore.maximum,direction:"higher"},weight:1,required:!0,hardGate:!1,privileged:!0,fixtureRefs:[]}],aggregation:"weighted_mean",unscorable:"exclude_optional_require_all_required"},[t.reward]);return(await se({binding:o,rewards:[t.reward],task:n,evidence:{output:i.output,artifactRefs:i.artifactRefs,runtimeEventRefs:i.runtimeEventRefs,infrastructureError:i.infrastructureError},signal:t.signal,customVerifier:t.customVerifier,modelJudge:t.modelJudge,purpose:"fixture_calibration"})).results[0]}c(ut,"executeRewardFixture");function pt(t,i){let n=t.expected,o=i.status===n.status&&(n.status!=="scored"||i.rawScore!==null&&i.rawScore>=n.minimum&&i.rawScore<=n.maximum&&(n.passed===null||n.passed===i.passed));return Ne.parse({fixture:{id:t.id,contentHash:k(t)},result:i,matchesExpectation:o})}c(pt,"matchRewardFixture");var J={draft:Te,reward_check:Me,asset:ye,definition:le,reward:V,binding:te,source:pe,evidence:he,feedback:be,decision:xe,batch:ve,policy:Se,chain:$,consumption:Pe,reservation:Oe,dispatch:Be,schedule:Ue,schedule_fire:Ve,iteration:Re,grade:_e,package:Y},G=e.enum(Object.keys(J)),Ke=class extends m{static{c(this,"LearningConflictError")}kind;id;expectedRevision;currentRevision;constructor(i,n,o,r){super("learning_revision_conflict",409,`Revision conflict for ${i} ${n}: expected ${o}, current ${r}.`),this.kind=i,this.id=n,this.expectedRevision=o,this.currentRevision=r,this.name="LearningConflictError"}};async function L(t,i,n,o){let r=await t.get(i,n,o);if(!r)throw new m("learning_resource_not_found",404,`${i}:${n}`);return J[i].parse(r)}c(L,"requireLearningResource");async function S(t,i,n){let o=await L(t,i,n.id,n.revision);if(!("contentHash"in o)||o.contentHash!==n.contentHash)throw new m("learning_release_hash_mismatch",409,`${i}:${n.id}`);return ke(o),o}c(S,"requireLearningRelease");function Lt(t,i,n){return`evidence-${k([t,i,n])}`}c(Lt,"learningEvidenceId");function Ct(t,i){return k([t,i])}c(Ct,"learningOperationId");async function Ht(t,i,n,o){let{batch:r,release:s,evidence:d,definition:g}=await Q(t,i,n,o);for(let f of d)for(let h of B(f,g))await t.reserveFamilySplit(h.namespace,h.kind,h.key,h.split);return await t.put("batch",r,0,{parentId:g.id}),await t.put("package",s,0,{parentId:r.id}),[Ge("batch",r),Ge("package",s)]}c(Ht,"sealLearningBatch");async function Q(t,i,n,o){let r=await S(t,"definition",i.taskDefinition),s=await S(t,"binding",r.rewardBinding),d=await Promise.all(s.sources.map(b=>S(t,"reward",b.reward)));oe(s,d);let g=await Promise.all(i.evidence.map(b=>wi(t,b))),f=await Promise.all(i.decisions.map(async b=>{let R=await S(t,"decision",b),p=await L(t,"decision",b.id);if(!I(_(p),b))throw new m("task_admission_revision_stale",409);return R})),h=[];for(let b of g)for(let R of B(b,r)){let p=await t.familySplit(R.namespace,R.kind,R.key);p!==null&&h.push({...R,split:p})}let x=Le({id:i.batchId,definition:r,binding:s,rewards:d,purpose:i.purpose,evidence:g,decisions:f,priorSplits:h,actorId:n,now:o}),w=Ce({batch:x,definition:r,binding:s,rewards:d,evidence:g,decisions:f});return{batch:x,release:w,evidence:g,definition:r}}c(Q,"prepareLearningBatch");async function wi(t,i){let n=await S(t,"evidence",i),o=await L(t,"evidence",i.id);if(!I(_(o),i))throw new m("task_evidence_revision_stale",409);return n}c(wi,"requireCurrentLearningEvidence");function Ge(t,i){return{kind:t,id:i.id,revision:i.revision}}c(Ge,"pointer");async function Qe(t,i,n){let o=new Date(n).toISOString().slice(0,10),r=0,s=0,d;do{let g=await t.list("reservation",{parentId:i,limit:100,...d?{afterId:d}:{}});for(let{budget:f}of g.items)r+=f.reservedSpendUsd,f.settledAt&&new Date(f.settledAt).toISOString().slice(0,10)===o&&(s+=f.settledSpendUsd);d=g.nextCursor??void 0}while(d);return{reservedSpendUsd:r,settledSpendUsd:s,committedSpendUsd:r+s}}c(Qe,"readLearningIterationBudget");function W(t){return`chain-${k(t)}`}c(W,"learningChainId");function Si(t,i){return`consumption-${k([t,i.id,i.revision])}`}c(Si,"learningConsumptionId");async function z(t,i,n={}){let o=i.training.method==="sft"?"supervised_training":"reward_training";if(!["sft","grpo","ppo"].includes(i.training.method))throw new m("learning_batch_method_unsupported",422);if(i.admission.mode!=="human")throw new m("learning_automatic_admission_not_available",422);let r=await S(t,"definition",i.taskDefinition);if(!I(r.rewardBinding,i.rewardBinding))throw new m("learning_policy_binding_mismatch",422);let s={eligible:0,awaitingReview:0,excluded:0,consumed:0},d=[],g=[],f=W(i.modelProjectId),h=new Set,x=0;for(let w of i.sources){let b=await S(t,"source",w),R=await L(t,"source",b.id);if(!b.enabled||!R.enabled)throw new m("learning_source_disabled",409);if(!I(b.taskDefinition,i.taskDefinition))throw new m("learning_policy_source_definition_mismatch",422);let p;do{let j=await t.list("evidence",{parentId:b.id,limit:100,...p?{afterId:p}:{}});for(let A of j.items){if(h.has(A.id))continue;if(h.add(A.id),!i.sources.some(U=>I(A.source,U))||!I(A.submission.taskDefinition,i.taskDefinition)||A.submission.split!=="train"){s.excluded+=1;continue}if(await t.get("consumption",Si(f,A))){s.consumed+=1;continue}if(++x>i.limits.maxBacklogExamples)throw new m("learning_backlog_limit_exceeded",409);let q=await t.get("decision",`decision-${A.id}`);if(!q||!I(q.evidence,_(A))||q.taskAdmissibility==="pending"||q.actor.kind!=="human"){s.awaitingReview+=1;continue}try{Ae({decision:q,evidence:A,definition:r,purpose:o})}catch(U){if(!(U instanceof m))throw U;s.excluded+=1;continue}s.eligible+=1,n.collectEligible&&g.push(_(A)),d.length<i.limits.maxBatchExamples&&d.push({evidence:A,decision:q})}p=j.nextCursor??void 0}while(p)}return{counts:s,selected:d,purpose:o,eligibleEvidence:g}}c(z,"inspectIterationEligibility");async function We(t,i,n=!1){let o=null,r;do{let s=await t.list("iteration",{parentId:i,status:"accepted",limit:100,...r?{afterId:r}:{}});for(let d of s.items){if(!d.candidateVersion||!d.candidateDecision||!d.candidateDecisionAt||!d.trainingJob){if(n)throw new m("learning_accepted_parent_evidence_missing",409);continue}let g=P.parse({iterationId:d.id,iterationRevision:d.revision,candidate:d.candidateVersion,decision:d.candidateDecision,decidedAt:d.candidateDecisionAt}),f=[Date.parse(g.decidedAt),g.decision.id,g.decision.revision],h=o?[Date.parse(o.decidedAt),o.decision.id,o.decision.revision]:null;(!h||f[0]>h[0]||f[0]===h[0]&&(f[1]>h[1]||f[1]===h[1]&&f[2]>h[2]))&&(o=g)}r=s.nextCursor??void 0}while(r);return o}c(We,"latestAcceptedLearningParent");async function Xe(t,i,n){if(!n)return{trainingParent:i.trainingParent,trainingParentSelection:null};let o=await L(t,"iteration",n.iterationId,n.iterationRevision),r=await S(t,"policy",o.policy);if(o.status!=="accepted"||!o.candidateVersion||!o.candidateDecision||!o.trainingJob||o.candidateVersion.id!==n.candidate.id||o.candidateVersion.contentHash!==n.candidate.contentHash||!I(o.candidateDecision,n.decision)||o.candidateDecisionAt!==n.decidedAt||r.modelProjectId!==i.modelProjectId||r.executionOwner!==i.executionOwner)throw new m("learning_accepted_parent_evidence_mismatch",409);if(r.trainingParent.id!==i.trainingParent.id||r.trainingParent.contentHash!==i.trainingParent.contentHash||r.training.method!==i.training.method)throw new m("learning_accepted_parent_configuration_mismatch",409,"The accepted checkpoint belongs to a different starting model or training method.");return{trainingParent:n.candidate,trainingParentSelection:n}}c(Xe,"resolveLearningTrainingParent");var Ri=e.object({policy:u,modelProjectId:a,inspectedAt:l,chain:$.nullable(),trainingParent:e.object({reference:C,selection:P.nullable()}).strict().nullable().default(null),counts:K.nullable(),minimumApprovedExamples:e.number().int().positive(),canReserve:e.boolean(),blockers:e.array(e.object({code:e.string().min(1).max(200),message:e.string().min(1).max(2e4)}).strict()).max(20),cooldownUntil:l.nullable(),budget:e.object({reservedSpendUsd:e.number().nonnegative(),settledSpendUsd:e.number().nonnegative(),committedSpendUsd:e.number().nonnegative(),maximumIterationSpendUsd:e.number().nonnegative(),maximumDailySpendUsd:e.number().nonnegative()}).strict()}).strict();async function ln(t,i,n,o){let r=await S(t,"policy",i),s=await L(t,"policy",r.id);if(!I(_(s),i))throw new m("learning_policy_revision_stale",409);let d=W(r.modelProjectId),g=await t.get("chain",d),f=await Qe(t,d,o),h=[],x=c((p,j)=>{h.push({code:p,message:j})},"block");r.enabled||x("learning_policy_paused","Learning is paused."),(r.automation.accept||r.automation.serve)&&x("learning_automatic_acceptance_not_available","Candidates require explicit acceptance and serving selection."),g?.activeIterationId&&x("learning_iteration_active","An iteration is already active.");let w=g?.lastReservedAt&&Date.parse(o)-Date.parse(g.lastReservedAt)<r.limits.cooldownSeconds*1e3?new Date(Date.parse(g.lastReservedAt)+r.limits.cooldownSeconds*1e3).toISOString():null;w&&x("learning_iteration_cooldown","The training cooldown has not elapsed."),f.committedSpendUsd+r.limits.maxIterationSpendUsd>r.limits.maxDailySpendUsd&&x("learning_daily_budget_exhausted","The daily budget cannot cover another iteration's maximum spend.");let b=null;try{let p=await z(t,r);b=p.counts,b.eligible<r.admission.minimumApprovedExamples?b.awaitingReview>0?x("learning_waiting_for_review","More approved tasks are required before training."):x("learning_waiting_for_data","More eligible new tasks are required before training."):await Q(t,{action:"seal_batch",operationId:"policy-inspection",batchId:"policy-inspection",taskDefinition:r.taskDefinition,purpose:p.purpose,evidence:p.selected.map(j=>_(j.evidence)),decisions:p.selected.map(j=>_(j.decision))},n,o)}catch(p){if(!(p instanceof m))throw p;x(p.code,p.message.slice(0,2e4))}let R=null;try{let p=await Xe(t,r,await We(t,d,!0));R={reference:p.trainingParent,selection:p.trainingParentSelection}}catch(p){if(!(p instanceof m))throw p;x(p.code,p.message.slice(0,2e4))}return Ri.parse({policy:_(r),modelProjectId:r.modelProjectId,inspectedAt:o,chain:g,trainingParent:R,counts:b,minimumApprovedExamples:r.admission.minimumApprovedExamples,canReserve:h.length===0,blockers:h,cooldownUntil:w,budget:{...f,maximumIterationSpendUsd:r.limits.maxIterationSpendUsd,maximumDailySpendUsd:r.limits.maxDailySpendUsd}})}c(ln,"inspectLearningPolicy");var _i=e.object({modelProjectId:a.nullable(),inspectedAt:l,pendingTrainingCount:e.number().int().nonnegative().nullable(),issues:e.array(e.object({policyId:a,code:e.string(),message:e.string()}).strict())}).strict();async function wn(t,i,n){let o=new Set,r=[],s;do{let d=await t.list("policy",{limit:100,...i?{parentId:i}:{},...s?{afterId:s}:{}});for(let g of d.items)try{let f=await z(t,g,{collectEligible:!0}),h=await S(t,"definition",g.taskDefinition);for(let x of f.eligibleEvidence){let w=await S(t,"evidence",x),b=!1;for(let R of B(w,h)){let p=await t.familySplit(R.namespace,R.kind,R.key);if(p!==null&&p!=="train"){b=!0;break}}b||o.add(JSON.stringify([x.id,x.revision,x.contentHash]))}}catch(f){if(!(f instanceof m))throw f;r.push({policyId:g.id,code:f.code,message:f.message})}s=d.nextCursor??void 0}while(s);return _i.parse({modelProjectId:i,inspectedAt:n,pendingTrainingCount:r.length?null:o.size,issues:r})}c(wn,"inspectLearningTaskQueue");function jn(t){try{H(t,16777216)}catch(i){throw new m("learning_json_invalid",400,i instanceof Error?i.message:"Expected bounded JSON.")}}c(jn,"assertLearningRequestJson");var En=e.object({scope:a,command:Fe}).strict(),Tn=e.discriminatedUnion("action",[e.object({action:e.literal("inspect_task_queue"),scope:a,modelProjectId:a.nullable()}).strict(),e.object({action:e.literal("inspect_policy"),scope:a,policy:u}).strict(),e.object({action:e.literal("inspect_evidence"),scope:a,evidence:u}).strict(),e.object({action:e.literal("get"),scope:a,kind:G,id:a,revision:e.number().int().positive().optional()}).strict(),e.object({action:e.literal("list"),scope:a,kind:G,parentId:a.optional(),status:e.string().min(1).max(200).optional(),reviewState:e.enum(["inbox","reviewed"]).optional(),afterId:a.optional(),limit:e.number().int().min(1).max(100).default(50)}).strict()]),Dn=e.object({evidence:u,definition:u,inspection:e.object({evidenceValidity:e.enum(["valid","invalid"]),taskReady:e.boolean(),observedOutputValid:e.boolean().nullable(),issues:e.array(e.object({path:e.string(),code:e.string(),message:e.string()}).strict()).max(100)}).strict()}).strict(),qn=e.object({operationId:a,resources:e.array(e.union(Object.values(J))).max(100)}).strict();export{$ as a,Pe as b,Oe as c,Fe as d,Be as e,Ue as f,xi as g,Me as h,lt as i,ut as j,pt as k,J as l,Ke as m,L as n,S as o,Lt as p,Ct as q,Ht as r,wi as s,W as t,Si as u,z as v,Qe as w,We as x,Xe as y,Ri as z,ln as A,_i as B,wn as C,jn as D,En as E,Tn as F,Dn as G,qn as H};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{a as me,b as D,c as G,d as j,e as z,g as ye,i as T,j as we,k as S,l as he,v as B,x as F}from"./chunk-MXLB6MEW.js";import{a as fe,b as L,c as R}from"./chunk-XCTFXXVY.js";import{b as H,c as be,d as ve,f as w,h as P,i as Re}from"./chunk-BSHAIAXY.js";import{M as ce,N as le,R as de,V as pe,h as $,i as ne,l as oe,n as re,o as ie,p as ae,q as se}from"./chunk-Z6F6PYF4.js";import{d as y,e as ue,f as ge,g as C}from"./chunk-QPZNN5Q3.js";import{a as Z,b as ee,c as te}from"./chunk-P3DI3ZMK.js";import{a as M,f as v,k as X}from"./chunk-3M53YXEI.js";import{a as g}from"./chunk-FTQLQJQV.js";import{promises as V,existsSync as W}from"node:fs";import U from"node:path";import{stdin as $e}from"node:process";async function Ge(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=await ie(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(Ge,"runTemplateStatus");async function je(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=await ae(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(je,"runTemplateBranches");async function ze(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=typeof e.env=="string"?e.env:typeof e.environment=="string"?e.environment:void 0,f=X(s),c=await se(n,i,a.id,{environment:f});console.log(JSON.stringify(c,null,2))}g(ze,"runTemplateUpdate");async function He(e){let o=await y(),t=w(o),r=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,n=r?r.trim():await L();if(!n)throw new Error("API key is required");n.startsWith("opk_")||console.log("warning: API keys usually start with opk_."),await C({handle:o.activeProfile?.handle||"default",apiKey:n,baseUrl:t,apiBaseUrl:o.apiBaseUrl,chatApiBaseUrl:o.chatApiBaseUrl,setActive:!0}),console.log("Saved account credentials to the encrypted OpenPond credential store.")}g(He,"runLogin");async function Fe(e,o){let t=o[0]||"list";if(t==="list"){let r=await ue();console.log(JSON.stringify({profiles:r},null,2));return}if(t==="use"){let r=o[1];if(!r)throw new Error("usage: profiles use <name> [--base-url <url>]");let n=await ge(r,{baseUrl:H(e)});console.log(JSON.stringify({profile:n},null,2));return}if(t==="save"){let r=o[1];if(!r)throw new Error("usage: profiles save <name> --api-key <key> [--base-url <url>] [--api-base-url <url>] [--chat-api-base-url <url>]");let n=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,i=n?n.trim():await L(),a=typeof e.environment=="string"?e.environment:typeof e.env=="string"?e.env:void 0,s=await C({handle:r,apiKey:i,baseUrl:H(e),apiBaseUrl:be(e),chatApiBaseUrl:ve(e),environment:a,setActive:!0});console.log(JSON.stringify({profile:s},null,2));return}throw new Error("usage: profiles <list|use|save> [args]")}g(Fe,"runProfiles");async function Ve(){let e=await y(),o=w(e),t=P(e),r=await R(e,o),n=await ce(t,r);console.log(JSON.stringify(n,null,2))}g(Ve,"runAccount");async function We(e){let o=await y(),t=P(o),r=fe(o),n=await le(t,r);console.log(JSON.stringify(n,null,2))}g(We,"runHealth");async function qe(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=typeof e.branch=="string"?String(e.branch):void 0,f=await $(n,i,a.id,{branch:s});if(!f?.id){console.log("no deployments found");return}let c=await ne(n,i,f.id),d=(c&&Array.isArray(c.toolsJson)?c.toolsJson:null)||(c&&typeof c.metadataJson=="object"&&c.metadataJson?c.metadataJson.tools:null),u=Array.isArray(d)?d:[];if(u.length===0){console.log("no tools found");return}for(let l of u){let m=l,h=m.profile||m.function,I=m.name||h?.name||"unknown",p=m.description||h?.description||"";console.log(p?`${I} - ${p}`:I)}}g(qe,"runToolList");async function Ye(e,o,t){let r=await y(),n=w(r),i=P(r),a=await R(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=await $(i,a,s.id,{branch:f});if(!c?.id)throw new Error("no deployments found");let d;if(typeof e.body=="string")try{d=JSON.parse(e.body)}catch{throw new Error("tool body must be valid JSON")}let u=typeof e.method=="string"?String(e.method).toUpperCase():"POST",l=await pe(n,a,{appId:s.id,deploymentId:c.id,toolName:t,method:u,body:d,headers:a?{"openpond-api-key":a}:void 0});if(!l.ok)throw new Error(l.error||`tool failed (${l.status})`);let m=l.data??{ok:!0};console.log(JSON.stringify(m,null,2))}g(Ye,"runToolRun");async function Qe(e,o,t){let r=await y(),n=w(r),i=P(r),a=await R(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,d=c?{id:c}:await $(i,a,s.id,{branch:f});if(!d?.id)throw new Error("no deployments found");let u=typeof e.body=="string"?M(String(e.body),"body"):{};if(!u||typeof u!="object"||Array.isArray(u))throw new Error("body must be a JSON object");let l=typeof e.method=="string"?String(e.method).toUpperCase():"POST",m={...u,appId:s.id,deploymentId:d.id,toolName:t,method:l},h=await de(i,a,m);console.log(JSON.stringify(h,null,2))}g(Qe,"runBacktestRun");async function Xe(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a,handle:s,repo:f}=await T(n,i,o),c=typeof e.branch=="string"?String(e.branch):void 0,d=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,u=d?{id:d}:await $(n,i,a.id,{branch:c});if(!u?.id){console.log("no deployments found");return}await we({baseUrl:n,apiKey:i,deploymentId:u.id,prefix:`[${s}/${f}] `,intervalMs:e.interval?Number(e.interval):void 0,timeoutMs:e.timeout?Number(e.timeout):void 0})}g(Xe,"runDeployWatch");async function Ze(e,o){let r=((typeof e.name=="string"?e.name:null)||o.join(" ")).trim();if(!r)throw new Error("usage: repo create --name <name> [--team-id <id>] [--path <dir>] [--template <owner/repo|url>] [--template-branch <branch>] [--empty|--opentool] [--sandbox] [--token] [--auto-schedule-migration <true|false>]");let n=await y(),i=w(n),a=await R(n,i),s=P(n),f=typeof e.teamId=="string"&&e.teamId.trim()?e.teamId.trim():void 0,c=typeof e.template=="string"?e.template.trim():"";if(c&&(e.empty==="true"||e.opentool==="true"))throw new Error("choose one: --template or --empty/--opentool");if(e.empty==="true"&&e.opentool==="true")throw new Error("choose one: --empty or --opentool");let d=typeof e.description=="string"?e.description.trim():void 0,u=typeof e.templateBranch=="string"&&e.templateBranch.trim().length>0?e.templateBranch.trim():void 0,l=typeof e.env=="string"?M(e.env,"env"):void 0;if(l){if(typeof l!="object"||Array.isArray(l))throw new Error("env must be a JSON object");for(let[b,A]of Object.entries(l))if(typeof A!="string")throw new Error(`env value for ${b} must be a string`)}if(c){e.deployOnPush!==void 0&&console.warn("deploy-on-push is not used for template create (auto deploys)");let b=Re(c,i),k=(await re(s,a,[{name:r,...d?{description:d}:{},templateRepoUrl:b,...u?{templateBranch:u}:{},...l?{envVars:l}:{}}],f)).items?.[0];if(!k||k.status!=="ok"||!k.appId)throw new Error(k?.error||"Template create failed");console.log(`app_id: ${k.appId}`),k.deploymentId&&console.log(`deployment_id: ${k.deploymentId}`),k.conversationId&&console.log(`conversation_id: ${k.conversationId}`);return}let m=process.cwd(),h=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,I=h&&h.trim().length>0?h.trim():$e.isTTY?await he(m):m,p=U.resolve(I);if(W(p)){if(!(await V.stat(p)).isDirectory())throw new Error(`path is not a directory: ${p}`)}else await V.mkdir(p,{recursive:!0});let Pe=(await V.readdir(p)).filter(b=>b!==".git").length===0,x=v(e.yes)||v(e.force);if(!Pe&&!x&&!await S(`Directory is not empty (${p}). Continue?`,!1)){console.log("aborted");return}let ke=U.join(p,".git");if(!W(ke)){if(!(x?!0:await S("Initialize git repository here?",!0))){console.log("aborted");return}let A=await B("git",["init"],{cwd:p});if(A.code!==0)throw new Error(`git init failed: ${A.stderr.trim()||A.stdout.trim()||"unknown error"}`)}let K=await F(p,"origin");if(K&&!x&&!await S(`Remote "origin" already set (${K}). Replace it?`,!1)){console.log("aborted");return}let q=e.opentool==="true"?"opentool":"empty",Te=v(e.sandbox),Be=v(e.deployOnPush),N=e.autoScheduleMigration,Y=typeof N=="string"||typeof N=="boolean",Ee=Y?v(N):void 0,E=await oe(s,a,{name:r,...f?{teamId:f}:{},...d?{description:d}:{},...q?{repoInit:q}:{},...Te?{sandbox:!0}:{},...l?{envVars:l}:{},...Be?{deployOnPush:!0}:{},...Y?{autoScheduleMigration:Ee}:{}}),O=me(E);z(O);let J=v(e.token)||v(e.setRemoteToken),Oe=D(O,a),Q=J?Oe:O,_=await B("git",K?["remote","set-url","origin",Q]:["remote","add","origin",Q],{cwd:p});if(_.code!==0)throw new Error(`git remote failed: ${j(_.stderr.trim()||_.stdout.trim()||"unknown error")}`);let Ae=J?G(O):O;console.log(`app_id: ${E.appId}`),E.gitOwner&&E.gitRepo&&console.log(`repo: ${E.gitOwner}/${E.gitRepo}`),console.log(`remote: ${Ae}`),console.log('next: git add . && git commit -m "init"');let Ie=E.defaultBranch||"master";console.log(`next: openpond repo push --path ${p} --branch ${Ie}`),J||console.log(`token-remote (non-interactive): git -C ${p} remote set-url origin ${G(O)}`);try{await ye({apiBase:s,apiKey:a,forceRefresh:!0})}catch(b){console.warn("cache refresh failed",b)}}g(Ze,"runRepoCreate");async function Se(e){let o=await B("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e});if(o.code!==0)return null;let t=o.stdout.trim();return t.length>0?t:null}g(Se,"resolveGitBranch");async function et(e){let o=await y(),t=w(o),r=await R(o,t),n=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,i=U.resolve(n&&n.trim().length>0?n.trim():"."),a=U.join(i,".git");if(!W(a))throw new Error(`git repo not found at ${i} (missing .git)`);let s=await F(i,"origin");if(!s)throw new Error("origin remote not set; run `openpond repo create` first");z(s);let c=(typeof e.branch=="string"?e.branch.trim():"")||await Se(i);if(!c)throw new Error("unable to resolve git branch; pass --branch");let d;try{d=D(s,r)}catch{throw new Error("origin remote must be https for tokenized pushes")}let u=v(e.keepTokenRemote)||v(e.token)||v(e.setRemoteToken),l=s.includes("x-access-token:"),m=!u&&!l?s:null,h=process.env.GIT_TERMINAL_PROMPT;process.env.GIT_TERMINAL_PROMPT="0";try{if(!l){let p=await B("git",["remote","set-url","origin",d],{cwd:i});if(p.code!==0)throw new Error(`git remote set-url failed: ${j(p.stderr.trim()||p.stdout.trim()||"unknown error")}`)}if((await B("git",["push","-u","origin",c],{cwd:i,inherit:!0})).code!==0)throw new Error("git push failed")}finally{m&&await B("git",["remote","set-url","origin",m],{cwd:i}).catch(()=>null),h===void 0?delete process.env.GIT_TERMINAL_PROMPT:process.env.GIT_TERMINAL_PROMPT=h}}g(et,"runRepoPush");async function tt(e){if(e.length===0)throw new Error("usage: opentool <init|validate|build> [args]");let o=process.platform==="win32"?"npx.cmd":"npx";if((await B(o,["opentool",...e],{inherit:!0})).code!==0)throw new Error("opentool command failed")}g(tt,"runOpentool");async function nt(){let e="openpond",o=Z(),t=await te(e),r=`npm i -g ${e}@${t}`,n=ee(o,t);if(n===0){console.log(`${e} is up to date (${o})`);return}if(n===-1){console.log(`Update available: ${o} -> ${t}`),console.log(`Run: ${r}`);return}if(n===1){console.log(`Installed version (${o}) is newer than npm latest (${t}).`);return}if(o===t){console.log(`${e} is up to date (${o})`);return}console.log(`Installed: ${o}`),console.log(`Latest: ${t}`),console.log(`Run: ${r}`)}g(nt,"runCheckUpdate");export{Ge as a,je as b,ze as c,He as d,Fe as e,Ve as f,We as g,qe as h,Ye as i,Qe as j,Xe as k,Ze as l,Se as m,et as n,tt as o,nt as p};
|
|
2
|
+
import{a as me,b as D,c as G,d as j,e as z,g as ye,i as T,j as we,k as S,l as he,v as B,x as F}from"./chunk-5YUITAUN.js";import{a as fe,b as L,c as R}from"./chunk-FFEI7IRU.js";import{b as H,c as be,d as ve,f as w,h as P,i as Re}from"./chunk-BSHAIAXY.js";import{M as ce,N as le,R as de,V as pe,h as $,i as ne,l as oe,n as re,o as ie,p as ae,q as se}from"./chunk-UJLZRM2M.js";import{d as y,e as ue,f as ge,g as C}from"./chunk-6EAQL7YX.js";import{a as Z,b as ee,c as te}from"./chunk-3LG4G5JR.js";import{a as M,f as v,k as X}from"./chunk-3M53YXEI.js";import{a as g}from"./chunk-FTQLQJQV.js";import{promises as V,existsSync as W}from"node:fs";import U from"node:path";import{stdin as $e}from"node:process";async function Ge(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=await ie(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(Ge,"runTemplateStatus");async function je(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=await ae(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(je,"runTemplateBranches");async function ze(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=typeof e.env=="string"?e.env:typeof e.environment=="string"?e.environment:void 0,f=X(s),c=await se(n,i,a.id,{environment:f});console.log(JSON.stringify(c,null,2))}g(ze,"runTemplateUpdate");async function He(e){let o=await y(),t=w(o),r=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,n=r?r.trim():await L();if(!n)throw new Error("API key is required");n.startsWith("opk_")||console.log("warning: API keys usually start with opk_."),await C({handle:o.activeProfile?.handle||"default",apiKey:n,baseUrl:t,apiBaseUrl:o.apiBaseUrl,chatApiBaseUrl:o.chatApiBaseUrl,setActive:!0}),console.log("Saved account credentials to the encrypted OpenPond credential store.")}g(He,"runLogin");async function Fe(e,o){let t=o[0]||"list";if(t==="list"){let r=await ue();console.log(JSON.stringify({profiles:r},null,2));return}if(t==="use"){let r=o[1];if(!r)throw new Error("usage: profiles use <name> [--base-url <url>]");let n=await ge(r,{baseUrl:H(e)});console.log(JSON.stringify({profile:n},null,2));return}if(t==="save"){let r=o[1];if(!r)throw new Error("usage: profiles save <name> --api-key <key> [--base-url <url>] [--api-base-url <url>] [--chat-api-base-url <url>]");let n=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,i=n?n.trim():await L(),a=typeof e.environment=="string"?e.environment:typeof e.env=="string"?e.env:void 0,s=await C({handle:r,apiKey:i,baseUrl:H(e),apiBaseUrl:be(e),chatApiBaseUrl:ve(e),environment:a,setActive:!0});console.log(JSON.stringify({profile:s},null,2));return}throw new Error("usage: profiles <list|use|save> [args]")}g(Fe,"runProfiles");async function Ve(){let e=await y(),o=w(e),t=P(e),r=await R(e,o),n=await ce(t,r);console.log(JSON.stringify(n,null,2))}g(Ve,"runAccount");async function We(e){let o=await y(),t=P(o),r=fe(o),n=await le(t,r);console.log(JSON.stringify(n,null,2))}g(We,"runHealth");async function qe(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=typeof e.branch=="string"?String(e.branch):void 0,f=await $(n,i,a.id,{branch:s});if(!f?.id){console.log("no deployments found");return}let c=await ne(n,i,f.id),d=(c&&Array.isArray(c.toolsJson)?c.toolsJson:null)||(c&&typeof c.metadataJson=="object"&&c.metadataJson?c.metadataJson.tools:null),u=Array.isArray(d)?d:[];if(u.length===0){console.log("no tools found");return}for(let l of u){let m=l,h=m.profile||m.function,I=m.name||h?.name||"unknown",p=m.description||h?.description||"";console.log(p?`${I} - ${p}`:I)}}g(qe,"runToolList");async function Ye(e,o,t){let r=await y(),n=w(r),i=P(r),a=await R(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=await $(i,a,s.id,{branch:f});if(!c?.id)throw new Error("no deployments found");let d;if(typeof e.body=="string")try{d=JSON.parse(e.body)}catch{throw new Error("tool body must be valid JSON")}let u=typeof e.method=="string"?String(e.method).toUpperCase():"POST",l=await pe(n,a,{appId:s.id,deploymentId:c.id,toolName:t,method:u,body:d,headers:a?{"openpond-api-key":a}:void 0});if(!l.ok)throw new Error(l.error||`tool failed (${l.status})`);let m=l.data??{ok:!0};console.log(JSON.stringify(m,null,2))}g(Ye,"runToolRun");async function Qe(e,o,t){let r=await y(),n=w(r),i=P(r),a=await R(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,d=c?{id:c}:await $(i,a,s.id,{branch:f});if(!d?.id)throw new Error("no deployments found");let u=typeof e.body=="string"?M(String(e.body),"body"):{};if(!u||typeof u!="object"||Array.isArray(u))throw new Error("body must be a JSON object");let l=typeof e.method=="string"?String(e.method).toUpperCase():"POST",m={...u,appId:s.id,deploymentId:d.id,toolName:t,method:l},h=await de(i,a,m);console.log(JSON.stringify(h,null,2))}g(Qe,"runBacktestRun");async function Xe(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a,handle:s,repo:f}=await T(n,i,o),c=typeof e.branch=="string"?String(e.branch):void 0,d=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,u=d?{id:d}:await $(n,i,a.id,{branch:c});if(!u?.id){console.log("no deployments found");return}await we({baseUrl:n,apiKey:i,deploymentId:u.id,prefix:`[${s}/${f}] `,intervalMs:e.interval?Number(e.interval):void 0,timeoutMs:e.timeout?Number(e.timeout):void 0})}g(Xe,"runDeployWatch");async function Ze(e,o){let r=((typeof e.name=="string"?e.name:null)||o.join(" ")).trim();if(!r)throw new Error("usage: repo create --name <name> [--team-id <id>] [--path <dir>] [--template <owner/repo|url>] [--template-branch <branch>] [--empty|--opentool] [--sandbox] [--token] [--auto-schedule-migration <true|false>]");let n=await y(),i=w(n),a=await R(n,i),s=P(n),f=typeof e.teamId=="string"&&e.teamId.trim()?e.teamId.trim():void 0,c=typeof e.template=="string"?e.template.trim():"";if(c&&(e.empty==="true"||e.opentool==="true"))throw new Error("choose one: --template or --empty/--opentool");if(e.empty==="true"&&e.opentool==="true")throw new Error("choose one: --empty or --opentool");let d=typeof e.description=="string"?e.description.trim():void 0,u=typeof e.templateBranch=="string"&&e.templateBranch.trim().length>0?e.templateBranch.trim():void 0,l=typeof e.env=="string"?M(e.env,"env"):void 0;if(l){if(typeof l!="object"||Array.isArray(l))throw new Error("env must be a JSON object");for(let[b,A]of Object.entries(l))if(typeof A!="string")throw new Error(`env value for ${b} must be a string`)}if(c){e.deployOnPush!==void 0&&console.warn("deploy-on-push is not used for template create (auto deploys)");let b=Re(c,i),k=(await re(s,a,[{name:r,...d?{description:d}:{},templateRepoUrl:b,...u?{templateBranch:u}:{},...l?{envVars:l}:{}}],f)).items?.[0];if(!k||k.status!=="ok"||!k.appId)throw new Error(k?.error||"Template create failed");console.log(`app_id: ${k.appId}`),k.deploymentId&&console.log(`deployment_id: ${k.deploymentId}`),k.conversationId&&console.log(`conversation_id: ${k.conversationId}`);return}let m=process.cwd(),h=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,I=h&&h.trim().length>0?h.trim():$e.isTTY?await he(m):m,p=U.resolve(I);if(W(p)){if(!(await V.stat(p)).isDirectory())throw new Error(`path is not a directory: ${p}`)}else await V.mkdir(p,{recursive:!0});let Pe=(await V.readdir(p)).filter(b=>b!==".git").length===0,x=v(e.yes)||v(e.force);if(!Pe&&!x&&!await S(`Directory is not empty (${p}). Continue?`,!1)){console.log("aborted");return}let ke=U.join(p,".git");if(!W(ke)){if(!(x?!0:await S("Initialize git repository here?",!0))){console.log("aborted");return}let A=await B("git",["init"],{cwd:p});if(A.code!==0)throw new Error(`git init failed: ${A.stderr.trim()||A.stdout.trim()||"unknown error"}`)}let K=await F(p,"origin");if(K&&!x&&!await S(`Remote "origin" already set (${K}). Replace it?`,!1)){console.log("aborted");return}let q=e.opentool==="true"?"opentool":"empty",Te=v(e.sandbox),Be=v(e.deployOnPush),N=e.autoScheduleMigration,Y=typeof N=="string"||typeof N=="boolean",Ee=Y?v(N):void 0,E=await oe(s,a,{name:r,...f?{teamId:f}:{},...d?{description:d}:{},...q?{repoInit:q}:{},...Te?{sandbox:!0}:{},...l?{envVars:l}:{},...Be?{deployOnPush:!0}:{},...Y?{autoScheduleMigration:Ee}:{}}),O=me(E);z(O);let J=v(e.token)||v(e.setRemoteToken),Oe=D(O,a),Q=J?Oe:O,_=await B("git",K?["remote","set-url","origin",Q]:["remote","add","origin",Q],{cwd:p});if(_.code!==0)throw new Error(`git remote failed: ${j(_.stderr.trim()||_.stdout.trim()||"unknown error")}`);let Ae=J?G(O):O;console.log(`app_id: ${E.appId}`),E.gitOwner&&E.gitRepo&&console.log(`repo: ${E.gitOwner}/${E.gitRepo}`),console.log(`remote: ${Ae}`),console.log('next: git add . && git commit -m "init"');let Ie=E.defaultBranch||"master";console.log(`next: openpond repo push --path ${p} --branch ${Ie}`),J||console.log(`token-remote (non-interactive): git -C ${p} remote set-url origin ${G(O)}`);try{await ye({apiBase:s,apiKey:a,forceRefresh:!0})}catch(b){console.warn("cache refresh failed",b)}}g(Ze,"runRepoCreate");async function Se(e){let o=await B("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e});if(o.code!==0)return null;let t=o.stdout.trim();return t.length>0?t:null}g(Se,"resolveGitBranch");async function et(e){let o=await y(),t=w(o),r=await R(o,t),n=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,i=U.resolve(n&&n.trim().length>0?n.trim():"."),a=U.join(i,".git");if(!W(a))throw new Error(`git repo not found at ${i} (missing .git)`);let s=await F(i,"origin");if(!s)throw new Error("origin remote not set; run `openpond repo create` first");z(s);let c=(typeof e.branch=="string"?e.branch.trim():"")||await Se(i);if(!c)throw new Error("unable to resolve git branch; pass --branch");let d;try{d=D(s,r)}catch{throw new Error("origin remote must be https for tokenized pushes")}let u=v(e.keepTokenRemote)||v(e.token)||v(e.setRemoteToken),l=s.includes("x-access-token:"),m=!u&&!l?s:null,h=process.env.GIT_TERMINAL_PROMPT;process.env.GIT_TERMINAL_PROMPT="0";try{if(!l){let p=await B("git",["remote","set-url","origin",d],{cwd:i});if(p.code!==0)throw new Error(`git remote set-url failed: ${j(p.stderr.trim()||p.stdout.trim()||"unknown error")}`)}if((await B("git",["push","-u","origin",c],{cwd:i,inherit:!0})).code!==0)throw new Error("git push failed")}finally{m&&await B("git",["remote","set-url","origin",m],{cwd:i}).catch(()=>null),h===void 0?delete process.env.GIT_TERMINAL_PROMPT:process.env.GIT_TERMINAL_PROMPT=h}}g(et,"runRepoPush");async function tt(e){if(e.length===0)throw new Error("usage: opentool <init|validate|build> [args]");let o=process.platform==="win32"?"npx.cmd":"npx";if((await B(o,["opentool",...e],{inherit:!0})).code!==0)throw new Error("opentool command failed")}g(tt,"runOpentool");async function nt(){let e="openpond",o=Z(),t=await te(e),r=`npm i -g ${e}@${t}`,n=ee(o,t);if(n===0){console.log(`${e} is up to date (${o})`);return}if(n===-1){console.log(`Update available: ${o} -> ${t}`),console.log(`Run: ${r}`);return}if(n===1){console.log(`Installed version (${o}) is newer than npm latest (${t}).`);return}if(o===t){console.log(`${e} is up to date (${o})`);return}console.log(`Installed: ${o}`),console.log(`Latest: ${t}`),console.log(`Run: ${r}`)}g(nt,"runCheckUpdate");export{Ge as a,je as b,ze as c,He as d,Fe as e,Ve as f,We as g,qe as h,Ye as i,Qe as j,Xe as k,Ze as l,Se as m,et as n,tt as o,nt as p};
|