openpond 0.2.40 → 0.2.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/app-server.d.ts +5 -1
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/actions-command-JPJLAR44.js +2 -0
  4. package/dist/chunks/{app-layer-W2M7SM2L.js → app-layer-ENO5MMPX.js} +1 -1
  5. package/dist/chunks/app-server-runtime-LACOVSKH.js +2 -0
  6. package/dist/chunks/apps-VFXTNQ25.js +2 -0
  7. package/dist/chunks/{chunk-ALYT2HWV.js → chunk-2Z6H32OC.js} +1 -1
  8. package/dist/chunks/chunk-3FXZW4G7.js +3 -0
  9. package/dist/chunks/{chunk-DWY6YCBI.js → chunk-452UKUIB.js} +200 -201
  10. package/dist/chunks/{chunk-3HQEEZPO.js → chunk-65BW2QXY.js} +1 -1
  11. package/dist/chunks/{chunk-4QURHV3Q.js → chunk-6C5XPL6E.js} +1 -1
  12. package/dist/chunks/{chunk-J4S7AVGF.js → chunk-6UGTLC7Z.js} +1 -1
  13. package/dist/chunks/chunk-ALZRXBEC.js +33 -0
  14. package/dist/chunks/chunk-AO753YWB.js +5 -0
  15. package/dist/chunks/chunk-AT6XYNQ5.js +2 -0
  16. package/dist/chunks/chunk-DLQW5X6F.js +2 -0
  17. package/dist/chunks/chunk-DXAZUJPA.js +2 -0
  18. package/dist/chunks/chunk-ERFHALGF.js +4 -0
  19. package/dist/chunks/chunk-FLWIBAHG.js +2 -0
  20. package/dist/chunks/{chunk-ASRSYRE3.js → chunk-GKP2ZPKM.js} +1 -1
  21. package/dist/chunks/{chunk-H7YH35JO.js → chunk-H7JB25HO.js} +1 -1
  22. package/dist/chunks/{chunk-JIG7KQOX.js → chunk-HLNJKX3S.js} +2 -2
  23. package/dist/chunks/{chunk-YHBIGFFA.js → chunk-JLZ2TEKK.js} +1 -1
  24. package/dist/chunks/chunk-JXD5PNF7.js +9 -0
  25. package/dist/chunks/{chunk-FFTVDR3E.js → chunk-JXGLH7OR.js} +139 -139
  26. package/dist/chunks/chunk-KCENW4ME.js +2 -0
  27. package/dist/chunks/{chunk-T7Y5OYO2.js → chunk-KIGN4FI6.js} +1 -1
  28. package/dist/chunks/{chunk-GTG2ODOV.js → chunk-KRC36KV2.js} +1 -1
  29. package/dist/chunks/{chunk-XRI3HLZ3.js → chunk-KVJF3H4N.js} +2 -2
  30. package/dist/chunks/{chunk-FUFIZ37W.js → chunk-LRGLV6JX.js} +1 -1
  31. package/dist/chunks/chunk-MOMDY22U.js +2 -0
  32. package/dist/chunks/chunk-MTJNKRXL.js +22 -0
  33. package/dist/chunks/{chunk-ELUCM7CG.js → chunk-NVPKY3KE.js} +1 -1
  34. package/dist/chunks/chunk-POWZXZJ2.js +2 -0
  35. package/dist/chunks/{chunk-WWCU4ETR.js → chunk-PU2JM765.js} +1 -1
  36. package/dist/chunks/{chunk-CYZOPDTW.js → chunk-QJX7UASW.js} +1 -1
  37. package/dist/chunks/chunk-R6YJY7F2.js +3 -0
  38. package/dist/chunks/{chunk-3QXPXBVG.js → chunk-RT6YPMWF.js} +1 -1
  39. package/dist/chunks/{chunk-TU5ITNMX.js → chunk-TPOW52DO.js} +3 -3
  40. package/dist/chunks/chunk-V62BHD5G.js +2 -0
  41. package/dist/chunks/{chunk-IYWNO4RB.js → chunk-VB2S5HV4.js} +2 -2
  42. package/dist/chunks/{chunk-3UQU3KOS.js → chunk-VKGVC26K.js} +1 -1
  43. package/dist/chunks/{chunk-ZCFX6HQO.js → chunk-VQG25QBJ.js} +1 -1
  44. package/dist/chunks/{chunk-JARGGWF5.js → chunk-XMXGITQE.js} +1 -1
  45. package/dist/chunks/chunk-Z2BYC6TP.js +2 -0
  46. package/dist/chunks/{chunk-562Q5UVS.js → chunk-ZG7QX66E.js} +1 -1
  47. package/dist/chunks/cli-QW2BELOE.js +2 -0
  48. package/dist/chunks/configuration-command-VXCGFVAP.js +2 -0
  49. package/dist/chunks/core-commands-XEPFY3PQ.js +2 -0
  50. package/dist/chunks/{datasets-W24QTQL7.js → datasets-6PTDCZQ7.js} +1 -1
  51. package/dist/chunks/desktop-test-JGSH4T5Z.js +3 -0
  52. package/dist/chunks/dist-ELWB75PL.js +2 -0
  53. package/dist/chunks/experiments-WKRYHZDK.js +2 -0
  54. package/dist/chunks/{extension-3P3JNRYN.js → extension-S2UIZH46.js} +1 -1
  55. package/dist/chunks/{help-23QDOMG7.js → help-ZVAGMF3C.js} +1 -1
  56. package/dist/chunks/hosted-harness-runtime-F4UPHTTT.js +2 -0
  57. package/dist/chunks/hosted-profile-compiler-4LKIBC75.js +2 -0
  58. package/dist/chunks/hosted-profile-evaluation-control-WPRPL4YW.js +2 -0
  59. package/dist/chunks/hosted-profile-evaluation-inspection-ULRRZDS2.js +3 -0
  60. package/dist/chunks/hosted-profile-evaluation-preparation-NWR4PRHS.js +3 -0
  61. package/dist/chunks/opchat-EOQ4PPE7.js +3 -0
  62. package/dist/chunks/organizations-4IGFWOYA.js +2 -0
  63. package/dist/chunks/{profile-NJMKPS6Z.js → profile-KJS7WQ3F.js} +1 -1
  64. package/dist/chunks/project-agent-6WNHPBXA.js +2 -0
  65. package/dist/chunks/sandbox-command-NCRIL6NH.js +2 -0
  66. package/dist/chunks/{sandbox-template-RCDR2FXX.js → sandbox-template-AAOUNWTL.js} +1 -1
  67. package/dist/chunks/{src-H7VE4J62.js → src-HLLPHEW4.js} +1 -1
  68. package/dist/chunks/{src-JVSP6UKT.js → src-PERIQ7VT.js} +91 -91
  69. package/dist/chunks/{teams-bot-KCKZTM3N.js → teams-bot-LKIOF3B5.js} +1 -1
  70. package/dist/chunks/{workspaces-J5QQUR53.js → workspaces-S3NXR6VJ.js} +1 -1
  71. package/dist/cli.js +3 -3
  72. package/dist/index.js +1 -1
  73. package/package.json +1 -1
  74. package/dist/chunks/actions-command-X2ERGYMA.js +0 -2
  75. package/dist/chunks/app-server-runtime-IO3FDF37.js +0 -2
  76. package/dist/chunks/apps-IBVU56HR.js +0 -2
  77. package/dist/chunks/chunk-5OA57RW4.js +0 -2
  78. package/dist/chunks/chunk-62H5KUOS.js +0 -12
  79. package/dist/chunks/chunk-AOBTILU5.js +0 -2
  80. package/dist/chunks/chunk-DDHUSA3I.js +0 -2
  81. package/dist/chunks/chunk-QCLVO56H.js +0 -4
  82. package/dist/chunks/chunk-QK2GLRCY.js +0 -53
  83. package/dist/chunks/chunk-SHCKK3SU.js +0 -2
  84. package/dist/chunks/chunk-ZCPIVNCS.js +0 -2
  85. package/dist/chunks/cli-QXO6OHZJ.js +0 -2
  86. package/dist/chunks/configuration-command-6VJUXQNZ.js +0 -2
  87. package/dist/chunks/core-commands-J6OY62PE.js +0 -2
  88. package/dist/chunks/desktop-test-SHS2VUYP.js +0 -3
  89. package/dist/chunks/dist-4OUZANXR.js +0 -2
  90. package/dist/chunks/experiments-O7WTSICN.js +0 -2
  91. package/dist/chunks/hosted-harness-runtime-U7JV7Z5T.js +0 -2
  92. package/dist/chunks/hosted-profile-compiler-ZCVMUTFA.js +0 -3
  93. package/dist/chunks/opchat-OI2YFNNY.js +0 -3
  94. package/dist/chunks/organizations-LB5QXKWT.js +0 -2
  95. package/dist/chunks/project-agent-SZLUVG3U.js +0 -2
  96. package/dist/chunks/sandbox-command-FQBOFZGM.js +0 -2
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{Wa as A,v as C}from"./chunk-TPOW52DO.js";import{a as m,b as p,c as R,e as H,h as T,l as h,m as z}from"./chunk-HZP5U2AA.js";import{b as e}from"./chunk-ES2ISFJC.js";import{a as d}from"./chunk-FTQLQJQV.js";var F=e.number().finite().nonnegative(),V=e.discriminatedUnion("kind",[e.object({kind:e.literal("model"),modelId:m,configurationHash:p}).strict(),e.object({kind:e.literal("harness"),source:A,model:e.object({modelId:m,configurationHash:p}).strict()}).strict(),e.object({kind:e.literal("fixture"),configurationHash:p}).strict()]),U=e.object({release:H.extend({revision:e.union([e.number().int().positive(),e.string().trim().min(1).max(200)])}).strict(),feedbackKey:C,configurationHash:p.optional(),output:e.enum(["boolean","score","category"]),categories:e.array(e.string().trim().min(1).max(120)).max(50)}).strict().superRefine((t,n)=>{t.output==="category"!=t.categories.length>0&&n.addIssue({code:"custom",path:["categories"],message:"Only category feedback declares categories."}),new Set(t.categories).size!==t.categories.length&&n.addIssue({code:"custom",path:["categories"],message:"Feedback categories must be unique."})}),M=e.object({caseId:m,seed:e.string().trim().min(1).max(500),fixtureId:m.nullable()}).strict();function K(t){let n=M.parse(t);return JSON.stringify([n.caseId,n.seed,n.fixtureId])}d(K,"experimentCaseKey");var D=e.object({schemaVersion:e.literal("openpond.experimentManifest.v1"),id:m,name:e.string().trim().min(1).max(500),teamId:m,operationId:m,maximumCostUsd:F.nullable(),dataset:H.extend({revision:e.number().int().positive()}).strict(),target:V,execution:e.object({packageHash:p,runtimeTargetHash:p,metricPolicyHash:p}).strict().optional(),lineage:e.object({definition:H.extend({revision:e.number().int().positive()}).strict().nullable(),execution:H,scoringPassId:m.nullable()}).strict().optional(),evaluators:e.array(U).max(100),population:e.array(M).min(1).max(1e4),createdAt:R}).strict().superRefine((t,n)=>{t.lineage&&t.id!==(t.lineage.scoringPassId??t.lineage.execution.id)&&n.addIssue({code:"custom",path:["lineage"],message:"Experiment identity must match its execution or independent scoring pass."}),new Set(t.population.map(K)).size!==t.population.length&&n.addIssue({code:"custom",path:["population"],message:"Experiment cases must be unique."}),new Set(t.evaluators.map(s=>s.feedbackKey)).size!==t.evaluators.length&&n.addIssue({code:"custom",path:["evaluators"],message:"Experiment feedback keys must be unique."})}),q=D.extend({contentHash:p}).strict(),J=e.object({feedbackKey:C,evaluator:U.shape.release,status:e.enum(["scored","unavailable","failed","pending"]),value:e.union([e.boolean(),e.number().finite(),e.string().max(120)]).nullable(),passed:e.boolean().nullable().optional(),reasoning:e.string().max(2e4).nullable(),evidenceRefs:e.array(T).max(1e3)}).strict(),B=e.object({inputTokens:e.number().int().nonnegative().nullable(),outputTokens:e.number().int().nonnegative().nullable(),totalTokens:e.number().int().nonnegative().nullable(),costUsd:F.nullable(),latencyMs:e.number().finite().nonnegative().nullable()}).strict().superRefine((t,n)=>{t.inputTokens!==null&&t.outputTokens!==null&&t.totalTokens!==null&&t.totalTokens<t.inputTokens+t.outputTokens&&n.addIssue({code:"custom",path:["totalTokens"],message:"Total tokens cannot be less than input plus output."})}),G=e.object({identity:M,status:e.enum(["completed","failed","cancelled","unavailable"]),output:e.unknown().nullable(),error:e.object({code:m,message:e.string().max(2e3)}).strict().nullable(),feedback:e.array(J).max(100),usage:B,traceRef:T.nullable(),startedAt:R.nullable(),completedAt:R.nullable()}).strict(),N=e.object({schemaVersion:e.literal("openpond.experimentResult.v1"),manifest:H,status:e.enum(["completed","failed","cancelled"]),cases:e.array(G).min(1).max(1e4),completedAt:R}).strict(),O=N.extend({contentHash:p}).strict();function L(t,n){q.parse(n),z(n,"Experiment manifest");let s=N.parse(t);if(s.manifest.id!==n.id||s.manifest.contentHash!==n.contentHash)throw new Error("Experiment result differs from its manifest.");let v=new Set(n.population.map(K)),l=new Set,w=new Map(n.evaluators.map(g=>[g.feedbackKey,g]));for(let g of s.cases){let S=K(g.identity);if(!v.has(S)||l.has(S))throw new Error("Experiment result has an unexpected or repeated case.");l.add(S);let I=new Set;for(let i of g.feedback){let a=w.get(i.feedbackKey);if(!a||I.has(i.feedbackKey)||i.evaluator.id!==a.release.id||i.evaluator.contentHash!==a.release.contentHash||i.evaluator.revision!==a.release.revision)throw new Error("Experiment feedback differs from its pinned evaluator.");if(I.add(i.feedbackKey),i.status==="scored"){if(i.value===null||typeof i.value!=={boolean:"boolean",score:"number",category:"string"}[a.output]||a.output==="category"&&!a.categories.includes(i.value)||a.output==="score"&&(i.value<0||i.value>1))throw new Error("Experiment feedback value violates its output contract.")}else if(i.value!==null||i.passed!==null&&i.passed!==void 0)throw new Error("Unscored experiment feedback cannot claim a value or pass decision.")}}if(l.size!==v.size)throw new Error("Experiment result omits admitted cases.");return O.parse({...s,contentHash:h(s)})}d(L,"createExperimentResult");function Q(t){let n=q.parse(t.manifest),s=O.parse(t.result),{contentHash:v,...l}=s;if(h(l)!==v)throw new Error("Experiment result integrity failed.");return L(l,n),{manifest:n,result:s}}d(Q,"verifyExperimentEvidence");function $(t,n){for(let a of[t,n])Q(a);let s=[];if(t.manifest.teamId!==n.manifest.teamId&&s.push("different_workspace"),(t.manifest.dataset.id!==n.manifest.dataset.id||t.manifest.dataset.contentHash!==n.manifest.dataset.contentHash||t.manifest.dataset.revision!==n.manifest.dataset.revision)&&s.push("different_dataset_version"),t.manifest.target.kind!==n.manifest.target.kind&&s.push("different_target_kind"),h(t.manifest.execution??null)!==h(n.manifest.execution??null)&&s.push("different_execution_contract"),t.manifest.target.kind==="harness"&&n.manifest.target.kind==="harness"){let a=t.manifest.target.source,r=n.manifest.target.source;(a.profileId!==r.profileId||h(a.target)!==h(r.target))&&s.push("different_component"),a.environmentHash!==r.environmentHash&&s.push("different_environment"),(a.definitionId!==r.definitionId||a.definitionHash!==r.definitionHash)&&s.push("different_evaluation_definition")}let v=d(a=>[...a.evaluators].sort((r,o)=>r.feedbackKey.localeCompare(o.feedbackKey)),"orderedEvaluators");h(v(t.manifest))!==h(v(n.manifest))&&s.push("different_evaluators");let l=new Map(t.result.cases.map(a=>[K(a.identity),a])),w=new Map(n.result.cases.map(a=>[K(a.identity),a])),g=[...new Set([...l.keys(),...w.keys()])].sort();(l.size!==w.size||g.some(a=>!l.has(a)||!w.has(a)))&&s.push("different_population");let S=s.length===0,I=g.map(a=>{let r=l.get(a)??null,o=w.get(a)??null,j=new Map(r?.feedback.map(c=>[c.feedbackKey,c])??[]),_=new Map(o?.feedback.map(c=>[c.feedbackKey,c])??[]);return{identity:(r??o).identity,baseline:r,candidate:o,feedback:t.manifest.evaluators.map(c=>{let y=j.get(c.feedbackKey),x=_.get(c.feedbackKey),f=S?!r||!o?"missing_case":r.status!=="completed"||o.status!=="completed"||r.error||o.error?"case_not_completed":!y||!x||y.status!=="scored"||x.status!=="scored"?"feedback_unavailable":c.output==="category"?"categorical_feedback":null:"incompatible_experiments",u=d(k=>typeof k?.value=="boolean"?Number(k.value):typeof k?.value=="number"?k.value:null,"numeric"),b=f?null:u(y),E=f?null:u(x),P=d(k=>f?null:typeof k?.value=="boolean"?k.value:k?.passed??null,"pass");return{feedbackKey:c.feedbackKey,eligible:f===null,reason:f,baseline:b,candidate:E,delta:b===null||E===null?null:E-b,baselinePassed:P(y),candidatePassed:P(x)}})}}),i=t.manifest.evaluators.map((a,r)=>{let o=I.map(u=>u.feedback[r]).filter(u=>u.eligible),j=d(u=>o.length?o.reduce((b,E)=>b+E[u],0)/o.length:null,"mean"),_=j("baseline"),c=j("candidate"),y=d(u=>o.length&&o.every(b=>b[u]!==null)?o.reduce((b,E)=>b+Number(E[u]),0)/o.length:null,"passRate"),x=y("baselinePassed"),f=y("candidatePassed");return{feedbackKey:a.feedbackKey,eligibleCount:o.length,excludedCount:I.length-o.length,baseline:_,candidate:c,delta:_===null||c===null?null:c-_,baselinePassRate:x,candidatePassRate:f,passRateDelta:x===null||f===null?null:f-x}});return{comparable:S,reasons:s,cases:I,metrics:i}}d($,"compareExperiments");export{Q as a,$ as b};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as fe,c as ge,d as ye,f as Re,g as Ae,i as Ce,j as Oe}from"./chunk-JEVA7YQL.js";import{b as de}from"./chunk-22UARBPW.js";import{A as z,B as J,C as $,D as V,E as Y,F as Q,G as X,H as Z,I as ee,J as te,K as ne,L as oe,M as se,N as re,O as ae,Q as le,V as pe,W as ie,X as ce,Y as ue,Z as me,_ as he,c as E,d as b,e as x,f as L,g as B,h as D,i as I,j as v,l as U,o as M,p as _,q as H,r as N,s as q,u as k,v as K,w as F,x as G,y as j,z as W}from"./chunk-SHCKK3SU.js";import{a as P,b as w}from"./chunk-GLUWATL5.js";import{a as s}from"./chunk-FTQLQJQV.js";function xe(t,e=14){if(t.length<e+1)return null;let r=0,o=0;for(let l=1;l<=e;l+=1){let m=t[l]-t[l-1];m>=0?r+=m:o-=m}let a=r/e,i=o/e;for(let l=e+1;l<t.length;l+=1){let m=t[l]-t[l-1],d=m>0?m:0,n=m<0?-m:0;a=(a*(e-1)+d)/e,i=(i*(e-1)+n)/e}return i===0?100:100-100/(1+a/i)}s(xe,"computeRsi");function T(t,e){if(t.length<e)return[];let r=[],o=0;for(let a=0;a<t.length;a+=1)o+=t[a],a>=e&&(o-=t[a-e]),a>=e-1&&r.push(o/e);return r}s(T,"computeSmaSeries");function Le(t,e){let r=T(t,e);return r.length>0?r[r.length-1]:null}s(Le,"computeSma");function A(t,e){if(t.length<e)return[];let r=2/(e+1),a=t.slice(0,e).reduce((p,l)=>p+l,0)/e,i=[a];for(let p=e;p<t.length;p+=1)a=t[p]*r+a*(1-r),i.push(a);return i}s(A,"computeEmaSeries");function Be(t,e){let r=A(t,e);return r.length>0?r[r.length-1]:null}s(Be,"computeEma");function De(t){let e=A(t,12),r=A(t,26);if(e.length===0||r.length===0)return null;let o=e.length-r.length,a=r.map((m,d)=>e[d+o]-m),i=A(a,9);if(i.length===0)return null;let p=a[a.length-1],l=i[i.length-1];return{macd:p,signalLine:l,histogram:p-l}}s(De,"computeMacd");function Ie(t,e,r,o){if(t.length<o)return null;let a=e==="ema"?A(t,r):T(t,r),i=e==="ema"?A(t,o):T(t,o);if(a.length===0||i.length===0)return null;let p=a.length-i.length;if(p<0)return null;let l=i.length-1,m=a[l+p],d=i[l],n=l-1,c=n>=0?a[n+p]:null,u=n>=0?i[n]:null,h="neutral";return c!=null&&u!=null?c<=u&&m>d?h="bullish-cross":c>=u&&m<d?h="bearish-cross":m>d?h="bullish":m<d&&(h="bearish"):m>d?h="bullish":m<d&&(h="bearish"),{fast:m,slow:d,signal:h}}s(Ie,"computeMaCross");function ve(t,e=20,r=2){if(t.length<e)return null;let o=t.slice(-e),a=o.reduce((l,m)=>l+m,0)/e,i=o.reduce((l,m)=>l+Math.pow(m-a,2),0)/e,p=Math.sqrt(i);return{middle:a,upper:a+r*p,lower:a-r*p}}s(ve,"computeBollinger");function Ue(t,e=24){if(t.length<2)return null;let r=t[t.length-1],o=Math.max(0,t.length-1-e),a=t[o];if(a===0)return null;let i=(r-a)/a*100;return{previous:a,percent:i}}s(Ue,"computePriceChange");function Me(t,e=14){if(t.length<e+1)return null;let r=[];for(let i=1;i<t.length;i+=1){let p=t[i],l=t[i-1],m=p.high-p.low,d=Math.abs(p.high-l.close),n=Math.abs(p.low-l.close);r.push(Math.max(m,d,n))}return r.length<e?null:r.slice(-e).reduce((i,p)=>i+p,0)/e}s(Me,"computeAtr");function Te(t){return t.replace(/\/$/,"")}s(Te,"resolveUrl");function _e(t){let e=process.env.OPENPOND_BASE_URL,r=t.baseUrl||e||P;return Te(r.trim())}s(_e,"resolveBaseUrl");function He(t){let e=process.env.OPENPOND_API_URL,r=t.apiUrl||e||w;return Te(r.trim())}s(He,"resolveApiUrl");function Ne(t,e){return fe({apiBaseUrl:e,opChatApiBaseUrl:t.opChatApiUrl,chatApiBaseUrl:t.chatApiUrl})}s(Ne,"resolveChatApiUrl");function qe(t,e){let r=process.env.OPENPOND_TOOL_URL,o=t.toolUrl||r||e;return Te(o.trim())}s(qe,"resolveToolUrl");function ke(t){let e=t.apiKey?.trim();if(e)return e;let r=process.env.OPENPOND_API_KEY?.trim();if(r)return r;throw new Error("OPENPOND_API_KEY is required")}s(ke,"resolveApiKey");function Ke(t){let e=t.split("/").filter(Boolean);if(e.length!==2)throw new Error("expected <handle>/<repo>");return{handle:e[0],repo:e[1]}}s(Ke,"parseHandleRepo");function Pe(t){return(t||"").trim().toLowerCase()}s(Pe,"normalizeRepoName");function Fe(t){if(!t||typeof t!="object")return{name:"unknown",raw:t};let e=t,r=e.profile||e.function,o=typeof e.name=="string"?e.name:typeof r?.name=="string"?r.name:"unknown",a=typeof e.description=="string"?e.description:typeof r?.description=="string"?r.description:void 0;return{name:o,description:a,raw:t}}s(Fe,"normalizeToolSummary");function Ge(t){if(!t)return[];if(Array.isArray(t.toolsJson))return t.toolsJson;if(t.metadataJson&&typeof t.metadataJson=="object"){let e=t.metadataJson.tools;if(Array.isArray(e))return e}return[]}s(Ge,"extractDeploymentTools");async function O(t){let{handle:e,repo:r}=Ke(t.target),o=await Se({apiBase:t.apiBase,apiKey:t.apiKey,useCache:t.useCache,cacheTtlMs:t.cacheTtlMs,forceRefresh:t.forceRefresh}),a=Pe(r),i=o.find(p=>p.handle&&p.handle!==e?!1:[p.repo,p.gitRepo,p.id].map(Pe).includes(a));if(!i)throw new Error(`app not found for ${e}/${r}`);return{app:i,handle:e,repo:r}}s(O,"resolveAppTarget");async function Se(t){if(t.useCache&&!t.forceRefresh){let r=await ce({apiBase:t.apiBase,apiKey:t.apiKey,ttlMs:t.cacheTtlMs});if(r)return r}let e=await v(t.apiBase,t.apiKey);return t.useCache&&await ue({apiBase:t.apiBase,apiKey:t.apiKey,apps:e}),e}s(Se,"fetchAppsWithCache");async function we(t){if(t.useCache&&!t.forceRefresh){let o=await me({apiBase:t.apiBase,apiKey:t.apiKey,ttlMs:t.cacheTtlMs});if(o)return o}let e=await k(t.apiBase,t.apiKey),r=Array.isArray(e.tools)?e.tools:[];return t.useCache&&await he({apiBase:t.apiBase,apiKey:t.apiKey,tools:r}),r}s(we,"fetchToolsWithCache");function je(t){if(!t)return"POST";let e=t.toUpperCase();switch(e){case"GET":case"POST":case"PUT":case"DELETE":return e;default:throw new Error("method must be GET, POST, PUT, or DELETE")}}s(je,"normalizeMethod");async function We(t,e){let r,o,a;return await de(t,{...e,onConversationId:s(i=>{r=i,e?.onConversationId?.(i)},"onConversationId"),onItems:s(i=>{for(let p of i){let l=p;!o&&typeof l.appId=="string"&&(o=l.appId,e?.onAppId?.(l.appId)),!a&&typeof l.deploymentId=="string"&&(a=l.deploymentId,e?.onDeploymentId?.(l.deploymentId))}e?.onItems?.(i)},"onItems")}),{conversationId:r,appId:o,deploymentId:a}}s(We,"consumeAgentCreateStream");function Pt(t){let e=ke(t),r=_e(t),o=He(t),a=Ne(t,o),i=qe(t,r),p=t.cacheTtlMs??ie,l=t.useCache!==!1,m=s(async()=>{l&&await Promise.all([Se({apiBase:o,apiKey:e,useCache:l,cacheTtlMs:p,forceRefresh:!0}),we({apiBase:o,apiKey:e,useCache:l,cacheTtlMs:p,forceRefresh:!0})])},"refreshCache"),d=s(async(n,c)=>(await D(o,e,n,{branch:c}))?.id??null,"resolveLatestDeploymentId");return{baseUrl:r,apiUrl:o,chatApiUrl:a,toolUrl:i,apiKey:e,account:{get:s(async()=>se(o,e),"get"),health:s(async()=>re(o,e),"health")},chat:{providers:s(async()=>Re({apiBaseUrl:a,token:e}),"providers"),provider:s(async n=>Ae({apiBaseUrl:a,token:e,provider:n}),"provider"),models:s(async()=>ge({apiBaseUrl:a,token:e}),"models"),model:s(async n=>ye({apiBaseUrl:a,token:e,model:n}),"model"),send:s(async n=>Ce({...n,apiBaseUrl:a,token:e}),"send"),stream:s(n=>Oe({...n,apiBaseUrl:a,token:e}),"stream")},tool:{list:s(async(n,c)=>{let{app:u}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:c?.forceRefresh}),h=c?.deploymentId||await d(u.id,c?.branch);if(!h)return{app:u,deploymentId:null,tools:[]};let g=await I(o,e,h),y=Ge(g).map(Fe);return{app:u,deploymentId:h,tools:y}},"list"),run:s(async(n,c,u)=>{let{app:h}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:u?.forceRefresh}),g=u?.deploymentId||await d(h.id,u?.branch);if(!g)throw new Error("no deployments found");let f=je(u?.method);return pe(i,e,{appId:h.id,deploymentId:g,toolName:c,method:f,body:u?.body,headers:u?.headers})},"run")},deploy:{watch:s(async(n,c)=>{let{app:u}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:c?.forceRefresh}),h=c?.deploymentId||await d(u.id,c?.branch);if(!h)throw new Error("no deployments found");let g=c?.intervalMs??5e3,f=c?.timeoutMs??240*1e3,y=[],S=new Set,Ee=Date.now(),R=null;for(;Date.now()-Ee<f;){let be=await L(o,e,h);for(let C of be)S.has(C.id)||(S.add(C.id),y.push(C),c?.onLog?.(C));if(R=(await B(o,e,h)).status??null,c?.onStatus?.(R),R==="failed")return{deploymentId:h,status:R,logs:y};if(R==="running"||R==="deployed")return{deploymentId:h,status:R,logs:y};await new Promise(C=>setTimeout(C,g))}return{deploymentId:h,status:"timeout",logs:y}},"watch")},template:{status:s(async(n,c)=>{let{app:u}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:c?.forceRefresh});return M(o,e,u.id)},"status"),branches:s(async(n,c)=>{let{app:u}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:c?.forceRefresh});return _(o,e,u.id)},"branches"),update:s(async(n,c)=>{let{app:u}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:c?.forceRefresh}),h=c?.environment==="preview"?"preview":"production";return H(o,e,u.id,{environment:h})},"update")},opentool:{recipesList:s(async(n={})=>F(o,e,n),"recipesList"),recipesSearch:s(async n=>G(o,e,n),"recipesSearch"),recipeGet:s(async n=>j(o,e,n),"recipeGet"),rulesGet:s(async n=>W(o,e,n),"rulesGet")},apps:{list:s(async n=>{let c=await Se({apiBase:o,apiKey:e,useCache:l,cacheTtlMs:p,forceRefresh:n?.forceRefresh});return n?.handle?c.filter(u=>u.handle===n.handle):c},"list"),tools:s(async n=>we({apiBase:o,apiKey:e,useCache:l,cacheTtlMs:p,forceRefresh:n?.forceRefresh}),"tools"),performance:s(async n=>ne(o,e,{appId:n?.appId}),"performance"),summary:s(async n=>oe(o,e,n.appId),"summary"),schedules:s(async n=>K(o,e,n.appId),"schedules"),schedulesStart:s(async n=>{let{appId:c,...u}=n;return z(o,e,c,u)},"schedulesStart"),schedulesStop:s(async n=>J(o,e,n.appId),"schedulesStop"),schedulesStopCurrent:s(async()=>$(o,e),"schedulesStopCurrent"),scheduleRunNow:s(async n=>V(o,e,n),"scheduleRunNow"),scheduleDelete:s(async n=>Y(o,e,n.appId,n.scheduleId),"scheduleDelete"),scheduleExecutionLogs:s(async n=>Q(o,e,n.scheduleId,{limit:n.limit}),"scheduleExecutionLogs"),scheduleExecutionLog:s(async n=>Z(o,e,n.runId),"scheduleExecutionLog"),deploymentScheduleExecutionLogs:s(async n=>X(o,e,n.deploymentId,{limit:n.limit}),"deploymentScheduleExecutionLogs"),executionTimeline:s(async n=>ee(o,e,n.appId,{limit:n.limit}),"executionTimeline"),assistantRun:s(async n=>ae(o,e,n),"assistantRun"),agentCreate:s(async(n,c)=>{let{refreshCache:u,...h}=n,g={...h,streamDeployLogs:h.streamDeployLogs??!0},f=await te(o,e,g);if(!f.ok){let S=await f.text().catch(()=>"");throw new Error(`agent create failed: ${f.status} ${S}`)}let y=await We(f,c);if(l&&u!==!1)try{await m()}catch{}return y},"agentCreate"),toolsExecute:s(async n=>le(o,e,n),"toolsExecute"),deploy:s(async n=>E(o,e,n.appId,{environment:n.environment,commitSha:n.commitSha,branch:n.branch}),"deploy"),startApp:s(async n=>{let{appId:c,...u}=n;return x(o,e,c,u)},"startApp"),promotePreview:s(async n=>{let{appId:c,...u}=n;return b(o,e,c,u)},"promotePreview"),envGet:s(async n=>q(o,e,n.appId),"envGet"),envSet:s(async n=>N(o,e,n.appId,{envVars:n.envVars}),"envSet")},repo:{create:s(async n=>{let{refreshCache:c,...u}=n,h=await U(o,e,u);if(l&&c!==!1)try{await m()}catch{}return h},"create")},cache:{refresh:m}}}s(Pt,"createClient");export{xe as a,T as b,Le as c,A as d,Be as e,De as f,Ie as g,ve as h,Ue as i,Me as j,We as k,Pt as l};
2
+ import{a as fe,c as ge,d as ye,f as Re,g as Ae,i as Ce,j as Oe}from"./chunk-JEVA7YQL.js";import{b as de}from"./chunk-22UARBPW.js";import{A as z,B as J,C as $,D as V,E as Y,F as Q,G as X,H as Z,I as ee,J as te,K as ne,L as oe,M as se,N as re,O as ae,Q as le,V as pe,W as ie,X as ce,Y as ue,Z as me,_ as he,c as E,d as b,e as x,f as L,g as B,h as D,i as I,j as v,l as U,o as M,p as _,q as H,r as N,s as q,u as k,v as K,w as F,x as G,y as j,z as W}from"./chunk-Z2BYC6TP.js";import{a as P,b as w}from"./chunk-GLUWATL5.js";import{a as s}from"./chunk-FTQLQJQV.js";function xe(t,e=14){if(t.length<e+1)return null;let r=0,o=0;for(let l=1;l<=e;l+=1){let m=t[l]-t[l-1];m>=0?r+=m:o-=m}let a=r/e,i=o/e;for(let l=e+1;l<t.length;l+=1){let m=t[l]-t[l-1],d=m>0?m:0,n=m<0?-m:0;a=(a*(e-1)+d)/e,i=(i*(e-1)+n)/e}return i===0?100:100-100/(1+a/i)}s(xe,"computeRsi");function T(t,e){if(t.length<e)return[];let r=[],o=0;for(let a=0;a<t.length;a+=1)o+=t[a],a>=e&&(o-=t[a-e]),a>=e-1&&r.push(o/e);return r}s(T,"computeSmaSeries");function Le(t,e){let r=T(t,e);return r.length>0?r[r.length-1]:null}s(Le,"computeSma");function A(t,e){if(t.length<e)return[];let r=2/(e+1),a=t.slice(0,e).reduce((p,l)=>p+l,0)/e,i=[a];for(let p=e;p<t.length;p+=1)a=t[p]*r+a*(1-r),i.push(a);return i}s(A,"computeEmaSeries");function Be(t,e){let r=A(t,e);return r.length>0?r[r.length-1]:null}s(Be,"computeEma");function De(t){let e=A(t,12),r=A(t,26);if(e.length===0||r.length===0)return null;let o=e.length-r.length,a=r.map((m,d)=>e[d+o]-m),i=A(a,9);if(i.length===0)return null;let p=a[a.length-1],l=i[i.length-1];return{macd:p,signalLine:l,histogram:p-l}}s(De,"computeMacd");function Ie(t,e,r,o){if(t.length<o)return null;let a=e==="ema"?A(t,r):T(t,r),i=e==="ema"?A(t,o):T(t,o);if(a.length===0||i.length===0)return null;let p=a.length-i.length;if(p<0)return null;let l=i.length-1,m=a[l+p],d=i[l],n=l-1,c=n>=0?a[n+p]:null,u=n>=0?i[n]:null,h="neutral";return c!=null&&u!=null?c<=u&&m>d?h="bullish-cross":c>=u&&m<d?h="bearish-cross":m>d?h="bullish":m<d&&(h="bearish"):m>d?h="bullish":m<d&&(h="bearish"),{fast:m,slow:d,signal:h}}s(Ie,"computeMaCross");function ve(t,e=20,r=2){if(t.length<e)return null;let o=t.slice(-e),a=o.reduce((l,m)=>l+m,0)/e,i=o.reduce((l,m)=>l+Math.pow(m-a,2),0)/e,p=Math.sqrt(i);return{middle:a,upper:a+r*p,lower:a-r*p}}s(ve,"computeBollinger");function Ue(t,e=24){if(t.length<2)return null;let r=t[t.length-1],o=Math.max(0,t.length-1-e),a=t[o];if(a===0)return null;let i=(r-a)/a*100;return{previous:a,percent:i}}s(Ue,"computePriceChange");function Me(t,e=14){if(t.length<e+1)return null;let r=[];for(let i=1;i<t.length;i+=1){let p=t[i],l=t[i-1],m=p.high-p.low,d=Math.abs(p.high-l.close),n=Math.abs(p.low-l.close);r.push(Math.max(m,d,n))}return r.length<e?null:r.slice(-e).reduce((i,p)=>i+p,0)/e}s(Me,"computeAtr");function Te(t){return t.replace(/\/$/,"")}s(Te,"resolveUrl");function _e(t){let e=process.env.OPENPOND_BASE_URL,r=t.baseUrl||e||P;return Te(r.trim())}s(_e,"resolveBaseUrl");function He(t){let e=process.env.OPENPOND_API_URL,r=t.apiUrl||e||w;return Te(r.trim())}s(He,"resolveApiUrl");function Ne(t,e){return fe({apiBaseUrl:e,opChatApiBaseUrl:t.opChatApiUrl,chatApiBaseUrl:t.chatApiUrl})}s(Ne,"resolveChatApiUrl");function qe(t,e){let r=process.env.OPENPOND_TOOL_URL,o=t.toolUrl||r||e;return Te(o.trim())}s(qe,"resolveToolUrl");function ke(t){let e=t.apiKey?.trim();if(e)return e;let r=process.env.OPENPOND_API_KEY?.trim();if(r)return r;throw new Error("OPENPOND_API_KEY is required")}s(ke,"resolveApiKey");function Ke(t){let e=t.split("/").filter(Boolean);if(e.length!==2)throw new Error("expected <handle>/<repo>");return{handle:e[0],repo:e[1]}}s(Ke,"parseHandleRepo");function Pe(t){return(t||"").trim().toLowerCase()}s(Pe,"normalizeRepoName");function Fe(t){if(!t||typeof t!="object")return{name:"unknown",raw:t};let e=t,r=e.profile||e.function,o=typeof e.name=="string"?e.name:typeof r?.name=="string"?r.name:"unknown",a=typeof e.description=="string"?e.description:typeof r?.description=="string"?r.description:void 0;return{name:o,description:a,raw:t}}s(Fe,"normalizeToolSummary");function Ge(t){if(!t)return[];if(Array.isArray(t.toolsJson))return t.toolsJson;if(t.metadataJson&&typeof t.metadataJson=="object"){let e=t.metadataJson.tools;if(Array.isArray(e))return e}return[]}s(Ge,"extractDeploymentTools");async function O(t){let{handle:e,repo:r}=Ke(t.target),o=await Se({apiBase:t.apiBase,apiKey:t.apiKey,useCache:t.useCache,cacheTtlMs:t.cacheTtlMs,forceRefresh:t.forceRefresh}),a=Pe(r),i=o.find(p=>p.handle&&p.handle!==e?!1:[p.repo,p.gitRepo,p.id].map(Pe).includes(a));if(!i)throw new Error(`app not found for ${e}/${r}`);return{app:i,handle:e,repo:r}}s(O,"resolveAppTarget");async function Se(t){if(t.useCache&&!t.forceRefresh){let r=await ce({apiBase:t.apiBase,apiKey:t.apiKey,ttlMs:t.cacheTtlMs});if(r)return r}let e=await v(t.apiBase,t.apiKey);return t.useCache&&await ue({apiBase:t.apiBase,apiKey:t.apiKey,apps:e}),e}s(Se,"fetchAppsWithCache");async function we(t){if(t.useCache&&!t.forceRefresh){let o=await me({apiBase:t.apiBase,apiKey:t.apiKey,ttlMs:t.cacheTtlMs});if(o)return o}let e=await k(t.apiBase,t.apiKey),r=Array.isArray(e.tools)?e.tools:[];return t.useCache&&await he({apiBase:t.apiBase,apiKey:t.apiKey,tools:r}),r}s(we,"fetchToolsWithCache");function je(t){if(!t)return"POST";let e=t.toUpperCase();switch(e){case"GET":case"POST":case"PUT":case"DELETE":return e;default:throw new Error("method must be GET, POST, PUT, or DELETE")}}s(je,"normalizeMethod");async function We(t,e){let r,o,a;return await de(t,{...e,onConversationId:s(i=>{r=i,e?.onConversationId?.(i)},"onConversationId"),onItems:s(i=>{for(let p of i){let l=p;!o&&typeof l.appId=="string"&&(o=l.appId,e?.onAppId?.(l.appId)),!a&&typeof l.deploymentId=="string"&&(a=l.deploymentId,e?.onDeploymentId?.(l.deploymentId))}e?.onItems?.(i)},"onItems")}),{conversationId:r,appId:o,deploymentId:a}}s(We,"consumeAgentCreateStream");function Pt(t){let e=ke(t),r=_e(t),o=He(t),a=Ne(t,o),i=qe(t,r),p=t.cacheTtlMs??ie,l=t.useCache!==!1,m=s(async()=>{l&&await Promise.all([Se({apiBase:o,apiKey:e,useCache:l,cacheTtlMs:p,forceRefresh:!0}),we({apiBase:o,apiKey:e,useCache:l,cacheTtlMs:p,forceRefresh:!0})])},"refreshCache"),d=s(async(n,c)=>(await D(o,e,n,{branch:c}))?.id??null,"resolveLatestDeploymentId");return{baseUrl:r,apiUrl:o,chatApiUrl:a,toolUrl:i,apiKey:e,account:{get:s(async()=>se(o,e),"get"),health:s(async()=>re(o,e),"health")},chat:{providers:s(async()=>Re({apiBaseUrl:a,token:e}),"providers"),provider:s(async n=>Ae({apiBaseUrl:a,token:e,provider:n}),"provider"),models:s(async()=>ge({apiBaseUrl:a,token:e}),"models"),model:s(async n=>ye({apiBaseUrl:a,token:e,model:n}),"model"),send:s(async n=>Ce({...n,apiBaseUrl:a,token:e}),"send"),stream:s(n=>Oe({...n,apiBaseUrl:a,token:e}),"stream")},tool:{list:s(async(n,c)=>{let{app:u}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:c?.forceRefresh}),h=c?.deploymentId||await d(u.id,c?.branch);if(!h)return{app:u,deploymentId:null,tools:[]};let g=await I(o,e,h),y=Ge(g).map(Fe);return{app:u,deploymentId:h,tools:y}},"list"),run:s(async(n,c,u)=>{let{app:h}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:u?.forceRefresh}),g=u?.deploymentId||await d(h.id,u?.branch);if(!g)throw new Error("no deployments found");let f=je(u?.method);return pe(i,e,{appId:h.id,deploymentId:g,toolName:c,method:f,body:u?.body,headers:u?.headers})},"run")},deploy:{watch:s(async(n,c)=>{let{app:u}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:c?.forceRefresh}),h=c?.deploymentId||await d(u.id,c?.branch);if(!h)throw new Error("no deployments found");let g=c?.intervalMs??5e3,f=c?.timeoutMs??240*1e3,y=[],S=new Set,Ee=Date.now(),R=null;for(;Date.now()-Ee<f;){let be=await L(o,e,h);for(let C of be)S.has(C.id)||(S.add(C.id),y.push(C),c?.onLog?.(C));if(R=(await B(o,e,h)).status??null,c?.onStatus?.(R),R==="failed")return{deploymentId:h,status:R,logs:y};if(R==="running"||R==="deployed")return{deploymentId:h,status:R,logs:y};await new Promise(C=>setTimeout(C,g))}return{deploymentId:h,status:"timeout",logs:y}},"watch")},template:{status:s(async(n,c)=>{let{app:u}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:c?.forceRefresh});return M(o,e,u.id)},"status"),branches:s(async(n,c)=>{let{app:u}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:c?.forceRefresh});return _(o,e,u.id)},"branches"),update:s(async(n,c)=>{let{app:u}=await O({apiBase:o,apiKey:e,target:n,useCache:l,cacheTtlMs:p,forceRefresh:c?.forceRefresh}),h=c?.environment==="preview"?"preview":"production";return H(o,e,u.id,{environment:h})},"update")},opentool:{recipesList:s(async(n={})=>F(o,e,n),"recipesList"),recipesSearch:s(async n=>G(o,e,n),"recipesSearch"),recipeGet:s(async n=>j(o,e,n),"recipeGet"),rulesGet:s(async n=>W(o,e,n),"rulesGet")},apps:{list:s(async n=>{let c=await Se({apiBase:o,apiKey:e,useCache:l,cacheTtlMs:p,forceRefresh:n?.forceRefresh});return n?.handle?c.filter(u=>u.handle===n.handle):c},"list"),tools:s(async n=>we({apiBase:o,apiKey:e,useCache:l,cacheTtlMs:p,forceRefresh:n?.forceRefresh}),"tools"),performance:s(async n=>ne(o,e,{appId:n?.appId}),"performance"),summary:s(async n=>oe(o,e,n.appId),"summary"),schedules:s(async n=>K(o,e,n.appId),"schedules"),schedulesStart:s(async n=>{let{appId:c,...u}=n;return z(o,e,c,u)},"schedulesStart"),schedulesStop:s(async n=>J(o,e,n.appId),"schedulesStop"),schedulesStopCurrent:s(async()=>$(o,e),"schedulesStopCurrent"),scheduleRunNow:s(async n=>V(o,e,n),"scheduleRunNow"),scheduleDelete:s(async n=>Y(o,e,n.appId,n.scheduleId),"scheduleDelete"),scheduleExecutionLogs:s(async n=>Q(o,e,n.scheduleId,{limit:n.limit}),"scheduleExecutionLogs"),scheduleExecutionLog:s(async n=>Z(o,e,n.runId),"scheduleExecutionLog"),deploymentScheduleExecutionLogs:s(async n=>X(o,e,n.deploymentId,{limit:n.limit}),"deploymentScheduleExecutionLogs"),executionTimeline:s(async n=>ee(o,e,n.appId,{limit:n.limit}),"executionTimeline"),assistantRun:s(async n=>ae(o,e,n),"assistantRun"),agentCreate:s(async(n,c)=>{let{refreshCache:u,...h}=n,g={...h,streamDeployLogs:h.streamDeployLogs??!0},f=await te(o,e,g);if(!f.ok){let S=await f.text().catch(()=>"");throw new Error(`agent create failed: ${f.status} ${S}`)}let y=await We(f,c);if(l&&u!==!1)try{await m()}catch{}return y},"agentCreate"),toolsExecute:s(async n=>le(o,e,n),"toolsExecute"),deploy:s(async n=>E(o,e,n.appId,{environment:n.environment,commitSha:n.commitSha,branch:n.branch}),"deploy"),startApp:s(async n=>{let{appId:c,...u}=n;return x(o,e,c,u)},"startApp"),promotePreview:s(async n=>{let{appId:c,...u}=n;return b(o,e,c,u)},"promotePreview"),envGet:s(async n=>q(o,e,n.appId),"envGet"),envSet:s(async n=>N(o,e,n.appId,{envVars:n.envVars}),"envSet")},repo:{create:s(async n=>{let{refreshCache:c,...u}=n,h=await U(o,e,u);if(l&&c!==!1)try{await m()}catch{}return h},"create")},cache:{refresh:m}}}s(Pt,"createClient");export{xe as a,T as b,Le as c,A as d,Be as e,De as f,Ie as g,ve as h,Ue as i,Me as j,We as k,Pt as l};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as he,b as Qe}from"./chunk-ZCPIVNCS.js";import{B as Ke,D as Fe,E as Je,F as A,G as Ge,H as Ve,l as fe,z as Ne}from"./chunk-ALYT2HWV.js";import{a as te,b as O,c as v,h as et,i as ye,j as xe}from"./chunk-MJC26GOX.js";import{$a as ee,D as Be,M as De,Ma as Ye,P as ue,Wa as Xe,_a as Ze,b as me,ga as ge,h as Z,k as Ue,m as We,v as $e,z as ze}from"./chunk-TU5ITNMX.js";import{a as h,e as Le,i as He,l,m as pe}from"./chunk-HZP5U2AA.js";import{b as t}from"./chunk-ES2ISFJC.js";import{a as c}from"./chunk-FTQLQJQV.js";var C=t.object({id:t.string().trim().min(1).max(240),revision:t.number().int().positive(),contentHash:t.string().regex(/^[a-f0-9]{64}$/),targetId:t.string().trim().min(1).max(240).nullable()}).strict(),be=t.array(t.object({role:t.enum(["system","user","assistant"]),content:t.string().max(1e5)}).strict()).max(100).superRefine((o,e)=>{o.reduce((n,r)=>n+r.content.length,0)>1e5&&e.addIssue({code:"custom",message:"Evaluation prompt exceeds 100,000 characters."})});var we=De.extend({mode:t.enum(["nightly","approved_count"]),minimumTasks:t.number().int().min(1).max(1e4),maximumSpendUsd:t.number().positive().max(1e5),maximumDailySpendUsd:t.number().positive().max(1e6)}).strict().superRefine((o,e)=>{o.maximumDailySpendUsd<o.maximumSpendUsd&&e.addIssue({code:"custom",path:["maximumDailySpendUsd"],message:"The daily budget must cover one update."})});var j=class extends Error{static{c(this,"OpenPondProtocolError")}code;constructor(e,n){super(n),this.name="OpenPondProtocolError",this.code=e}};function f(o){return JSON.stringify(Se(o))}c(f,"canonicalJson");async function ne(o){let e=new TextEncoder().encode(f(o)),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}c(ne,"canonicalSha256");function Se(o){if(o===null||typeof o=="string"||typeof o=="boolean")return o;if(typeof o=="number"){if(!Number.isFinite(o))throw new j("non_json_value","Canonical JSON cannot contain a non-finite number.");return Object.is(o,-0)?0:o}if(Array.isArray(o))return o.map(e=>Se(e));if(typeof o=="object"){let e=Object.getPrototypeOf(o);if(e!==Object.prototype&&e!==null)throw new j("non_json_value","Canonical JSON accepts only plain objects.");let n={};for(let r of Object.keys(o).sort()){let s=o[r];if(s===void 0||typeof s=="function"||typeof s=="symbol")throw new j("non_json_value",`Canonical JSON cannot contain ${typeof s} at ${r}.`);n[r]=Se(s)}return n}throw new j("non_json_value",`Canonical JSON cannot contain ${typeof o}.`)}c(Se,"normalizeCanonicalJson");var p=t.string().trim().min(1).max(500),E=t.string().regex(/^[a-f0-9]{64}$/),k=t.string().datetime({offset:!0}),_=t.object({id:p,contentHash:E}).strict(),R=_.extend({revision:t.number().int().positive()}).strict(),L=t.object({schemaVersion:t.literal("openpond.baseModelPreference.v1"),modelId:p,revision:t.string().trim().min(1).max(256).nullable(),tokenizerRevision:t.string().trim().min(1).max(256).nullable(),chatTemplateHash:t.string().trim().min(8).max(256).nullable(),modelAssetId:p.nullable(),source:t.enum(["managed","local","builtin"])}).strict(),tt=t.enum(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),$t=t.object({schemaVersion:t.string().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:tt,parameterization:t.enum(["lora","full"])}).catchall(t.unknown()),zt=t.object({profileProjectId:p,sourceRevision:t.string().regex(/^[a-f0-9]{40,64}$/),harnessRelease:_}).strict(),Bt=t.object({profileProjectId:p,sourceRevision:t.string().regex(/^[a-f0-9]{40,64}$/),catalogHash:E,definitionId:p,harnessRelease:_,tasksetRelease:_}).strict(),nt=t.object({tasksetRef:R.nullable().default(null),evaluationTasksetRef:R.nullable().optional(),profileSource:zt.nullable().optional(),profileEvaluation:Bt.nullable().optional(),rewardBindingRef:R.nullable().optional(),tasksetRelease:_.nullable().default(null),harnessRelease:_.nullable().default(null),baseModel:L.nullable().default(null),method:tt.nullable().default(null),destinationId:p.nullable().default(null),managedRolloutPlacement:t.enum(["local","remote"]).default("remote"),managedGpuPlacementObjective:t.enum(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:t.enum(["any","h100_hbm3"]).default("any"),runPreset:t.enum(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:$t.nullable().default(null),preferredMaximumSpendUsd:t.number().nonnegative().nullable().default(null),preferredRetentionDays:t.number().int().nonnegative().nullable().default(null)}).strict(),rt=nt.omit({managedGpuRequirement:!0}),Dt=t.object({schemaVersion:t.literal("openpond.hostedModelProjectLink.v1"),apiOrigin:t.string().url().refine(o=>new URL(o).origin===o,"Use a canonical API origin.").nullable().default(null),teamId:p,projectId:p,portableProjectId:p,revision:t.number().int().positive(),etag:E,syncedSourceRevision:t.number().int().positive(),syncedAt:k,tasksets:t.array(t.object({localTasksetId:p,localTasksetHash:E.nullable().default(null),releaseId:p,releaseRevision:t.number().int().positive(),releaseHash:E,packageHash:E.nullable().default(null),hostedTasksetId:p,syncedAt:k}).strict()).max(1e4).default([])}).strict(),Nt=t.object({localTasksetId:p,releaseId:p,releaseRevision:t.number().int().positive(),releaseHash:E,state:t.enum(["syncing","synced","sync_failed"]),hostedTasksetId:p.nullable().default(null),lastAttemptAt:k,syncedAt:k.nullable().default(null),lastError:t.string().trim().min(1).max(5e3).nullable().default(null)}).strict(),Kt=t.object({schemaVersion:t.literal("openpond.modelProject.v2"),id:p,profileId:p,revision:t.number().int().positive().default(1),name:t.string().trim().min(1).max(200),objective:t.string().trim().max(5e3).nullable(),defaultBaseModel:L.nullable(),defaultDestinationId:p.nullable(),trainingSetup:nt,hosted:Dt.nullable().default(null),tasksetSyncs:t.array(Nt).max(1e4).default([]),createdAt:k,updatedAt:k}).strict(),Ft=Kt.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),Ln=t.object({schemaVersion:t.literal("openpond.modelProjectSave.v1"),operationId:p,expectedRevision:t.number().int().nonnegative(),project:Ft,learning:we.optional()}).strict().superRefine((o,e)=>{o.learning&&o.expectedRevision!==0&&e.addIssue({code:"custom",path:["learning"],message:"Use learning settings to edit an existing Model's policy."})}),Hn=t.object({schemaVersion:t.literal("openpond.modelProjectConfigurationCheck.v1"),configurationHash:E,projectId:p,expectedRevision:t.number().int().nonnegative(),checkedAt:k,canSave:t.boolean(),deferred:t.array(t.enum(["base_model","taskset"])).max(2),findings:t.array(t.object({code:p,severity:t.enum(["error","warning"]),message:t.string().min(1).max(5e3),field:t.string().min(1).max(500).nullable()}).strict()).max(100)}).strict(),Un=t.object({id:p,name:t.string().min(1).max(500),available:t.boolean(),preference:L}).strict();var Wn=t.object({schemaVersion:t.literal("openpond.hostedModelProjectSync.v2"),portableProjectId:p,name:t.string().trim().min(1).max(200),objective:t.string().trim().max(5e3).nullable(),defaultBaseModel:L.nullable(),defaultDestinationId:p.nullable(),trainingSetup:rt,sourceRevision:t.number().int().positive(),sourceUpdatedAt:k,expectedEtag:E.nullable().default(null)}).strict(),Jt=t.object({id:p,teamId:p,portableProjectId:p,name:t.string().trim().min(1).max(200),objective:t.string().trim().max(5e3).nullable(),defaultBaseModel:L.nullable(),defaultDestinationId:p.nullable(),trainingSetup:rt,sourceRevision:t.number().int().positive(),sourceUpdatedAt:k,revision:t.number().int().positive(),etag:E,createdAt:k,updatedAt:k}).strict(),Gt=t.object({kind:t.enum(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:_,role:t.string().trim().min(1).max(200).nullable().default(null),updatedAt:k}).strict(),$n=t.object({project:Jt,resources:t.array(Gt).max(1e4),jobCount:t.number().int().nonnegative(),latestJobIds:t.array(p).max(100)}).strict(),zn=t.object({schemaVersion:t.literal("openpond.modelProjectApiError.v2"),code:t.string().trim().min(1).max(200),message:t.string().trim().min(1).max(5e3),retryable:t.boolean().default(!1),requestId:t.string().trim().min(1).max(500).nullable().default(null),details:t.record(t.string(),t.unknown()).default({})}).strict();var ot=t.object({schemaVersion:t.literal("openpond.experimentAttemptGrade.v1"),selectionHash:t.string().regex(/^[a-f0-9]{64}$/),grades:t.array(Z).min(1).max(100),score:t.number().min(0).max(1).nullable(),passed:t.boolean(),rewardEligible:t.boolean(),gradingStatus:t.enum(["scored","unscorable","not_configured"]),failureClass:He.nullable(),contentHash:t.string().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((o,e)=>{let{contentHash:n,...r}=o;l(r)!==n&&e.addIssue({code:"custom",message:"Experiment grading integrity failed."});let s=o.grades.flatMap(i=>i.components);(s.length!==o.grades.length||new Set(s.map(i=>i.graderId)).size!==s.length)&&e.addIssue({code:"custom",message:"Each selected criterion requires exactly one distinct grader result."});for(let i of o.grades){let{contentHash:a,...d}=i;l(d)!==a&&e.addIssue({code:"custom",message:"A retained criterion changed."});for(let x of i.components){let{contentHash:b,...g}=x;l(g)!==b&&e.addIssue({code:"custom",message:"A retained grader result changed."})}}});var m=t.string().trim().min(1).max(200),H=t.string().regex(/^[a-f0-9]{64}$/),Pe=t.discriminatedUnion("kind",[t.object({kind:t.literal("hosted_chat"),modelId:m,messages:be.optional(),maxOutputTokens:t.number().int().min(1).max(4096).default(1024),temperature:t.number().min(0).max(2).default(0),topP:t.number().gt(0).max(1).default(1)}).strict(),t.object({kind:t.literal("fixture"),fixtureId:m}).strict()]),Vt=t.object({schemaVersion:t.literal("openpond.modelStarterAttemptRequest.v1"),operationId:m,teamId:m,modelProjectId:m.nullable(),project:C.optional(),taskset:R,taskId:m,environmentSeed:t.number().int().min(0).max(2147483647).default(0),policy:Pe}).strict(),rr=t.object({modelProjectId:m.nullable(),taskset:R,afterTaskId:m.optional(),limit:t.number().int().min(1).max(100).default(25)}).strict(),or=t.object({modelProjectId:m.nullable(),taskset:R,available:t.boolean(),unavailableReason:t.string().max(1e3).nullable(),models:t.array(t.object({id:m,name:t.string().max(500)}).strict()).max(200),tasks:t.array(t.object({id:m,split:t.enum(["train","validation","frozen_eval"]),inputPreview:t.string().max(500),fixtures:t.array(t.object({id:m,label:t.string().max(200)}).strict()).max(1e3)}).strict()).max(100),nextCursor:m.nullable()}).strict(),re=t.object({schemaVersion:t.literal("openpond.modelStarterAttemptSummary.v1"),id:m,revision:t.number().int().positive(),request:Vt,status:t.enum(["queued","running","cancelling","completed","failed","cancelled"]),policySnapshot:t.object({modelId:m,provider:m,upstreamModelId:t.string().min(1).max(500),configurationHash:H}).strict().nullable(),createdAt:t.iso.datetime(),startedAt:t.iso.datetime().nullable(),completedAt:t.iso.datetime().nullable(),cleanupComplete:t.boolean(),resultAvailable:t.boolean(),score:t.number().min(0).max(1).nullable(),gradingStatus:t.enum(["not_started","scored","unscorable","not_configured"]).default("not_started"),passed:t.boolean().nullable(),outputPreview:t.string().max(500).nullable(),error:t.object({code:m,message:t.string().max(2e3)}).strict().nullable()}).strict().superRefine((o,e)=>{o.request.policy.kind==="fixture"!=(o.policySnapshot===null)&&e.addIssue({code:"custom",path:["policySnapshot"],message:"Fixture execution must not claim a model identity."}),o.status==="completed"&&(!o.cleanupComplete||!o.resultAvailable||!o.completedAt)&&e.addIssue({code:"custom",message:"Completed attempts require retained results and confirmed cleanup."})}),sr=t.object({modelProjectId:m,afterId:m.optional(),limit:t.number().int().min(1).max(100).default(25)}).strict(),ir=t.object({items:t.array(re).max(100),nextCursor:m.nullable()}).strict(),ar=t.object({schemaVersion:t.literal("openpond.modelStarterAttemptResult.v1"),attempt:re,output:t.string().max(1048576).nullable(),messages:t.array(t.record(t.string(),t.unknown())).max(4002),composition:Be.nullable(),grade:Z.nullable().optional(),experimentGrade:ot.nullable().optional(),environment:t.object({status:t.enum(["completed","budget_exhausted","cancelled","timed_out","policy_failure","environment_failure"]),collected:t.boolean(),definition:R,initialStateHash:H.nullable(),finalStateHash:H.nullable(),attemptHash:H}).strict(),providerRequestIds:t.array(m).max(1001),contentHash:H}).strict().superRefine((o,e)=>{o.experimentGrade&&((o.grade||o.composition)&&e.addIssue({code:"custom",message:"Selected Experiment grading cannot claim another grade population."}),(!["completed","failed"].includes(o.attempt.status)||!o.attempt.resultAvailable||o.attempt.score!==o.experimentGrade.score||o.attempt.gradingStatus!==o.experimentGrade.gradingStatus||o.attempt.passed!==(o.experimentGrade.score===null?null:o.experimentGrade.passed))&&e.addIssue({code:"custom",message:"Experiment grading differs from its retained attempt summary."})),o.grade&&(o.composition&&e.addIssue({code:"custom",path:["grade"],message:"An ordinary grade cannot also claim a Reward composition."}),(!["completed","failed"].includes(o.attempt.status)||!o.attempt.resultAvailable||o.attempt.score!==o.grade.score||o.attempt.gradingStatus!==o.grade.gradingStatus||o.attempt.passed!==(o.grade.score===null?null:o.grade.passed))&&e.addIssue({code:"custom",path:["grade"],message:"Ordinary grade differs from its terminal attempt summary."}))});var st=t.string().trim().min(1).max(240),it=t.string().regex(/^[a-f0-9]{64}$/),ke=t.object({kind:t.literal("hosted_harness"),modelId:st,reasoningEffort:t.enum(["off","low","medium","high","xhigh","max"]).optional(),profileRepositoryId:st,source:Xe,modelConfigurationHash:it,packageHash:it}).strict();var I=t.string().trim().min(1).max(200),at=t.string().regex(/^[a-f0-9]{64}$/),Yt=t.discriminatedUnion("kind",[Pe.options[0],t.object({kind:t.literal("fixture")}).strict(),ke]),U=t.object({schemaVersion:t.literal("openpond.modelTasksetRunRequest.v1"),operationId:I,teamId:I,modelProjectId:I.nullable(),name:t.string().trim().min(1).max(200).optional(),project:C.optional(),taskset:R,policy:Yt,population:t.array(Ze).min(1).max(1e4)}).strict().superRefine((o,e)=>{new Set(o.population.map(n=>n.receiptId)).size!==o.population.length&&e.addIssue({code:"custom",path:["population"],message:"Run receipt identities must be unique."}),o.population.some(n=>n.fixtureId!==null!=(o.policy.kind==="fixture"))&&e.addIssue({code:"custom",path:["population"],message:"Only fixture runs require a fixture identity for every member."}),o.population.some(n=>!/^(0|[1-9][0-9]*)$/.test(n.seed)||Number(n.seed)>2147483647)&&e.addIssue({code:"custom",path:["population"],message:"Hosted environment seeds must be integers from 0 to 2147483647."}),o.policy.kind==="hosted_harness"&&o.modelProjectId!==null&&e.addIssue({code:"custom",path:["modelProjectId"],message:"A Harness target retains its released Profile binding separately from Model artifacts."}),o.policy.kind==="hosted_harness"&&new Set(o.population.map(n=>f([n.taskId,n.seed]))).size!==o.population.length&&e.addIssue({code:"custom",path:["population"],message:"Harness case identities must be unique for each task and seed."})}),ct=t.object({schemaVersion:t.literal("openpond.modelTasksetRunSummary.v1"),id:I,revision:t.number().int().positive(),teamId:I,modelProjectId:I.nullable(),name:t.string().trim().min(1).max(200).optional(),project:C.optional(),operationId:I,taskset:R,policyKind:t.enum(["hosted_chat","fixture","hosted_harness"]),manifestHash:at,status:t.enum(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:t.number().int().min(1).max(1e4),counts:t.object({pending:t.number().int().nonnegative(),running:t.number().int().nonnegative(),completed:t.number().int().nonnegative(),failed:t.number().int().nonnegative(),cancelled:t.number().int().nonnegative()}).strict(),createdAt:t.iso.datetime(),startedAt:t.iso.datetime().nullable(),completedAt:t.iso.datetime().nullable(),cleanupComplete:t.boolean(),resultAvailable:t.boolean(),score:t.number().min(0).max(1).nullable(),metricName:t.string().min(1).max(240),error:t.object({code:I,message:t.string().max(2e3)}).strict().nullable()}).strict().superRefine((o,e)=>{Object.values(o.counts).reduce((n,r)=>n+r,0)!==o.totalCount&&e.addIssue({code:"custom",path:["counts"],message:"Run counts must account for the complete population."}),o.status!=="completed"&&o.score!==null&&e.addIssue({code:"custom",path:["score"],message:"Only completed evaluations publish a metric value."}),["completed","failed","cancelled"].includes(o.status)&&(!o.completedAt||o.counts.pending||o.counts.running)&&e.addIssue({code:"custom",message:"Terminal runs require complete population accounting."}),o.status==="cancelled"&&!o.cleanupComplete&&e.addIssue({code:"custom",message:"Cancelled runs require confirmed cleanup."}),o.resultAvailable&&!["completed","failed","cancelled"].includes(o.status)&&e.addIssue({code:"custom",message:"Run results require terminal population accounting."}),o.status==="completed"&&(!o.cleanupComplete||!o.resultAvailable)&&e.addIssue({code:"custom",message:"Completed evaluations require retained results and confirmed cleanup."})}),dt=t.object({summary:ct,request:U,manifest:ee,policySnapshot:re.shape.policySnapshot}).strict(),Ir=t.object({modelProjectId:I.optional(),projectId:C.shape.id.optional(),afterId:I.optional(),limit:t.number().int().min(1).max(100).default(25)}).strict(),Or=t.object({items:t.array(ct).max(100),nextCursor:I.nullable()}).strict(),vr=t.object({schemaVersion:t.literal("openpond.modelTasksetRunResult.v1"),run:dt,receipts:t.array(Ye).min(1).max(1e4),metric:Ue.nullable(),contentHash:at}).strict();function Re(o,e){pe(e,"Taskset run manifest");let n=o.policy;if(n.kind!=="hosted_harness"||e.execution.kind!=="harness"||f(e.profileEvaluation)!==f(n.source)||f(e.execution.harnessRelease)!==f(n.source.harnessRelease)||e.metadata.profileRepositoryId!==n.profileRepositoryId||e.packageHash!==n.packageHash||e.policy.kind!=="model"||e.policy.model.provider!=="openpond"||e.policy.model.model!==n.modelId||e.policy.model.revision!==null||e.policy.model.artifactHash!==null||e.policy.model.tokenizerRevision!==null||e.policy.model.chatTemplateHash!==null||e.policy.configurationHash!==n.modelConfigurationHash||e.tasksetRelease.id!==o.taskset.id||e.tasksetRelease.contentHash!==o.taskset.contentHash||f(e.population)!==f(o.population)||e.population.some(r=>r.receiptId!==`evaluation-${l([e.id,r.taskId,r.seed]).slice(0,32)}`))throw new Error("Harness evaluation differs from its admitted source, package or model configuration.")}c(Re,"verifyHarnessExperimentManifest");async function oe(o){let e=dt.parse(o),{summary:n,request:r,manifest:s,policySnapshot:i}=e;if(pe(s,"Taskset run manifest"),s.contentHash!==n.manifestHash||s.id!==n.id||s.createdAt!==n.createdAt||n.teamId!==r.teamId||n.modelProjectId!==r.modelProjectId||f(n.project??null)!==f(r.project??null)||f(s.metadata.project??null)!==f(r.project??null)||(n.name??null)!==(r.name??null)||n.operationId!==r.operationId||n.policyKind!==r.policy.kind||n.totalCount!==r.population.length||n.metricName!==s.metricPolicy.primaryMetric||f(n.taskset)!==f(r.taskset)||s.tasksetRelease.id!==r.taskset.id||s.tasksetRelease.contentHash!==r.taskset.contentHash||f(s.population)!==f(r.population))throw new Error("Evaluation run differs from its admitted request or manifest.");if(r.policy.kind==="fixture"){if(s.policy.kind!=="fixture"||i!==null)throw new Error("Fixture checks cannot claim a model identity.")}else if(r.policy.kind==="hosted_harness"){if(Re(r,s),i!==null)throw new Error("Harness evaluations retain the native host model configuration.")}else if(s.policy.kind!=="model"||!i||i.modelId!==r.policy.modelId||s.policy.model.provider!==i.provider||s.policy.model.model!==i.upstreamModelId||s.policy.model.revision!==null||s.policy.model.artifactHash!==null||s.policy.model.tokenizerRevision!==null||s.policy.model.chatTemplateHash!==null||s.policy.configurationHash!==await ne({policy:r.policy,snapshot:i}))throw new Error("Evaluation model differs from its admitted policy.");return e}c(oe,"verifyModelTasksetRunDetails");var mt=t.string().min(1).max(200).refine(o=>!["__proto__","prototype","constructor"].includes(o),"Use an ordinary field name."),Xt=t.array(mt).min(1).max(20),lt=t.enum(["input","output","expectedOutput","evaluatorContext"]),Qt=t.object({destination:lt,path:Xt,source:lt,sourcePath:t.array(mt).max(20)}).strict(),W=t.array(Qt).max(100).superRefine((o,e)=>{for(let[n,r]of o.entries())o.slice(0,n).some(s=>s.destination===r.destination&&(pt(s.path,r.path)||pt(r.path,s.path)))&&e.addIssue({code:"custom",path:[n,"path"],message:"Mapped destination paths must not overlap."})});function pt(o,e){return o.length<=e.length&&o.every((n,r)=>n===e[r])}c(pt,"prefix");var S=t.string().trim().min(1).max(200),$=t.string().regex(/^[a-f0-9]{64}$/),T=t.object({id:S,revision:t.number().int().positive(),contentHash:$}).strict(),z=t.object({id:S,version:t.string().min(1).max(200),contentHash:$,feedbackKey:$e,release:T.nullable(),mappings:W.optional()}).strict(),Zt=t.object({id:S,version:t.string().min(1).max(200),contentHash:$,mappings:W}).strict(),ut=t.object({operationId:S,id:S.optional(),expectedRevision:t.number().int().nonnegative(),request:U,maximumCostUsd:t.number().finite().positive().max(1e4),graders:t.array(Zt).min(1).max(100).optional()}).strict().superRefine((o,e)=>{o.request.name||e.addIssue({code:"custom",path:["request","name"],message:"Name this Experiment before saving it."}),!!o.id!=o.expectedRevision>0&&e.addIssue({code:"custom",path:["expectedRevision"],message:"An update requires its saved definition revision."}),Math.round(o.maximumCostUsd*1e6)<1&&e.addIssue({code:"custom",path:["maximumCostUsd"],message:"The budget must be at least $0.000001."}),o.graders&&new Set(o.graders.map(n=>n.id)).size!==o.graders.length&&e.addIssue({code:"custom",path:["graders"],message:"Select each grader once."})}),en=t.object({schemaVersion:t.literal("openpond.experimentDefinition.v1"),id:S,teamId:S,revision:t.number().int().positive(),request:U,maximumCostUsd:t.number().finite().positive().max(1e4),graders:t.array(z).min(1).max(100),createdAt:t.iso.datetime(),updatedAt:t.iso.datetime()}).strict(),tn=en.extend({contentHash:$}),gt=t.object({operationId:S,definition:T}).strict(),ft=t.object({projectId:S.optional(),datasetHash:$.optional(),search:t.string().trim().max(200).optional(),afterId:S.optional(),limit:t.number().int().min(1).max(100).default(30)}).strict(),$r=t.object({definition:T,maximumCostUsd:t.number().finite().positive().max(1e4),graders:t.array(z).min(1).max(100)}).strict(),ht=t.object({operationId:S,profileRepositoryId:S,definitionId:S,modelId:S,reasoningEffort:t.enum(["off","low","medium","high","xhigh","max"]).optional(),maximumCostUsd:t.number().finite().positive().max(1e4)}).strict(),yt=t.object({request:U,manifest:ee,maximumCostUsd:t.number().finite().positive().max(1e4),graders:t.array(z).min(1).max(100)}).strict();function xt(o){let e=tn.parse(o),{contentHash:n,...r}=e;if(n!==l(r)||e.request.teamId!==e.teamId||!e.request.name)throw new Error("Experiment definition differs from its immutable content.");if(new Set(e.graders.map(s=>s.feedbackKey)).size!==e.graders.length)throw new Error("Experiment feedback keys must be distinct.");return e}c(xt,"verifyExperimentDefinition");var Ie=c(o=>({id:o.id,revision:o.revision,contentHash:o.contentHash}),"experimentDefinitionRef");var B=t.string().trim().min(1).max(200),Oe=t.object({operationId:B,execution:Le,graders:t.array(ze).min(1).max(100),maximumCostUsd:t.number().finite().min(1e-6).max(1e4),mappings:t.array(t.object({graderId:B,fields:W}).strict()).max(100).optional()}).strict().superRefine((o,e)=>{new Set(o.graders.map(n=>n.id)).size!==o.graders.length&&e.addIssue({code:"custom",path:["graders"],message:"Select each grader once."}),o.mappings&&(new Set(o.mappings.map(n=>n.graderId)).size!==o.mappings.length||o.mappings.some(n=>!o.graders.some(r=>r.id===n.graderId)))&&e.addIssue({code:"custom",path:["mappings"],message:"Map each selected grader at most once."})}),nn=t.object({schemaVersion:t.literal("openpond.experimentScoringPass.v1"),id:B,teamId:B,revision:t.number().int().positive(),request:Oe,graders:t.array(z).min(1).max(100),status:t.enum(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:t.number().int().min(1).max(1e4),counts:t.object({pending:t.number().int().nonnegative(),running:t.number().int().nonnegative(),scored:t.number().int().nonnegative(),unavailable:t.number().int().nonnegative(),failed:t.number().int().nonnegative(),cancelled:t.number().int().nonnegative()}).strict(),resultAvailable:t.boolean(),createdAt:t.iso.datetime(),startedAt:t.iso.datetime().nullable(),completedAt:t.iso.datetime().nullable(),error:t.object({code:B,message:t.string().max(2e3)}).strict().nullable()}).strict(),rn=nn.extend({contentHash:t.string().regex(/^[a-f0-9]{64}$/)});function bt(o){let e=rn.parse(o),{contentHash:n,...r}=e;if(l(r)!==n||Object.values(e.counts).reduce((i,a)=>i+a,0)!==e.totalCount)throw new Error("Scoring pass integrity or population accounting failed.");let s=["completed","failed","cancelled"].includes(e.status);if(s&&(!e.completedAt||e.counts.pending||e.counts.running)||!s&&(e.completedAt!==null||e.resultAvailable)||e.status==="completed"&&!e.resultAvailable)throw new Error("Scoring pass lifecycle differs from its retained result.");if(e.graders.length!==e.request.graders.length||new Set(e.graders.map(i=>i.feedbackKey)).size!==e.graders.length||e.graders.some((i,a)=>l(i.release)!==l(e.request.graders[a])||l(i.mappings??[])!==l(e.request.mappings?.find(d=>d.graderId===i.release?.id)?.fields??[])))throw new Error("Scoring pass graders differ from their exact admission.");return e}c(bt,"verifyExperimentScoringPass");var u=t.string().trim().min(1).max(200),ve=class extends Error{constructor(n,r,s){super(s);this.status=n;this.code=r;this.name="OpenPondExperimentError"}status;code;static{c(this,"OpenPondExperimentError")}},se=class{constructor(e){this.options=e;let n=new URL(e.baseUrl);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||n.search||n.hash||!e.apiKey.trim()||!e.teamId.trim())throw new Error("A clean API origin and workspace credentials are required.");this.baseUrl=n.toString().replace(/\/+$/,"")}options;static{c(this,"OpenPondExperimentsClient")}baseUrl;async prepareHarness(e,n){let r=ht.parse(e),s=yt.parse(await this.request("/harness-setup","POST",r,n));Re(s.request,s.manifest);let i=s.request.policy;if(s.request.teamId!==this.options.teamId||s.request.operationId!==r.operationId||i.kind!=="hosted_harness"||i.profileRepositoryId!==r.profileRepositoryId||i.source.definitionId!==r.definitionId||i.modelId!==r.modelId||i.reasoningEffort!==r.reasoningEffort||s.maximumCostUsd!==r.maximumCostUsd||s.manifest.limits.maximumSpendUsd!==r.maximumCostUsd)throw new Error("Harness preparation differs from its requested scope or configuration.");return s}async save(e,n){let r=ut.parse(e);if(r.request.teamId!==this.options.teamId)throw new Error("Experiment workspace mismatch.");let s=this.definition(await this.request("","POST",r,n),r.id);if(s.revision!==r.expectedRevision+1||l(s.request)!==l(r.request)||s.maximumCostUsd!==r.maximumCostUsd)throw new Error("Experiment save receipt differs from its submitted configuration.");if(r.graders&&l(r.graders)!==l(s.graders.map(i=>({id:i.id,version:i.version,contentHash:i.contentHash,mappings:i.mappings??[]}))))throw new Error("Experiment save receipt differs from its selected graders or mappings.");return s}async get(e,n={}){let r=n.reference?T.parse(n.reference):void 0;if(r&&r.id!==e)throw new Error("Experiment reference identity mismatch.");let s=r?`?${new URLSearchParams({revision:String(r.revision),contentHash:r.contentHash})}`:"",i=this.definition(await this.request(`/${encodeURIComponent(u.parse(e))}${s}`,"GET",void 0,n.signal),e);if(n.reference&&l(Ie(i))!==l(n.reference))throw new Error("Experiment revision mismatch.");return i}async list(e={},n){let r=ft.parse(e),s=new URLSearchParams(Object.entries(r).map(([d,x])=>[d,String(x)])),i=t.object({items:t.array(t.unknown()).max(100),nextCursor:u.nullable()}).strict().parse(await this.request(`?${s}`,"GET",void 0,n)),a=i.items.map(d=>this.definition(d));if(a.length>r.limit||new Set(a.map(d=>d.id)).size!==a.length||a.some(d=>r.projectId&&d.request.project?.id!==r.projectId||r.datasetHash&&d.request.taskset.contentHash!==r.datasetHash))throw new Error("Experiment page differs from its selected scope.");return{items:a,nextCursor:i.nextCursor}}async start(e,n){let r=gt.parse(e),s=t.object({definition:t.unknown(),run:t.unknown()}).strict().parse(await this.request(`/${encodeURIComponent(r.definition.id)}/start`,"POST",r,n)),i=this.definition(s.definition,r.definition.id);if(l(Ie(i))!==l(r.definition))throw new Error("Experiment Start revision mismatch.");let a=await oe(s.run);if(a.summary.teamId!==this.options.teamId||a.request.operationId!==r.operationId||l(wt(a.request))!==l(wt({...i.request,operationId:r.operationId}))||l(a.manifest.metadata.experimentDefinition)!==l(r.definition)||a.manifest.metadata.experimentConfigurationHash!==l({definition:r.definition,maximumCostUsd:i.maximumCostUsd,graders:i.graders}))throw new Error("Experiment execution differs from its saved configuration.");return a}async result(e,n){let r=t.object({executionId:u,passId:u.nullable(),manifest:t.unknown(),result:t.unknown()}).strict().parse(await this.request(`/executions/${encodeURIComponent(u.parse(e))}/result`,"GET",void 0,n)),s=he(r);if(r.executionId!==e||s.manifest.teamId!==this.options.teamId||s.manifest.lineage?.execution.id!==e||s.manifest.lineage.scoringPassId!==r.passId)throw new Error("Experiment result identity mismatch.");return{...s,executionId:e,passId:r.passId}}async executions(e,n={}){let r=new URLSearchParams(n.afterId?{afterId:u.parse(n.afterId)}:{}),s=t.object({items:t.array(t.unknown()).max(30),nextCursor:u.nullable()}).strict().parse(await this.request(`/${encodeURIComponent(u.parse(e))}/executions?${r}`,"GET",void 0,n.signal)),i=await Promise.all(s.items.map(a=>oe(a)));if(i.some(a=>a.summary.teamId!==this.options.teamId||T.parse(a.manifest.metadata.experimentDefinition).id!==e)||new Set(i.map(a=>a.summary.id)).size!==i.length)throw new Error("Experiment execution page has invalid ownership or repeated identities.");return{items:i,nextCursor:s.nextCursor}}async execution(e,n){return this.executionDetails(await this.request(`/executions/${encodeURIComponent(u.parse(e))}`,"GET",void 0,n),e)}async cancel(e,n){return this.executionDetails(await this.request(`/executions/${encodeURIComponent(u.parse(e))}/cancel`,"POST",{},n),e)}async retry(e,n,r){let s=await this.executionDetails(await this.request(`/executions/${encodeURIComponent(u.parse(e))}/retry`,"POST",{operationId:u.parse(n)},r));if(s.request.operationId!==n)throw new Error("Experiment retry operation mismatch.");return s}async score(e,n){let r=Oe.parse(e),s=this.pass(await this.request(`/executions/${encodeURIComponent(r.execution.id)}/scoring-passes`,"POST",r,n));if(l(s.request)!==l(r))throw new Error("Scoring admission differs from its submitted inputs.");return s}async scoringPass(e,n){return this.pass(await this.request(`/scoring-passes/${encodeURIComponent(u.parse(e))}`,"GET",void 0,n),e)}async scoringPasses(e,n={}){let r=new URLSearchParams(n.afterId?{afterId:u.parse(n.afterId)}:{}),s=t.object({items:t.array(t.unknown()).max(30),nextCursor:u.nullable()}).strict().parse(await this.request(`/executions/${encodeURIComponent(u.parse(e))}/scoring-passes?${r}`,"GET",void 0,n.signal)),i=s.items.map(a=>this.pass(a));if(i.some(a=>a.request.execution.id!==e)||new Set(i.map(a=>a.id)).size!==i.length)throw new Error("Scoring pass page differs from its execution ownership.");return{items:i,nextCursor:s.nextCursor}}async cancelScoringPass(e,n){return this.pass(await this.request(`/scoring-passes/${encodeURIComponent(u.parse(e))}/cancel`,"POST",{},n),e)}async scoringResult(e,n){let r=t.object({executionId:u,passId:u,manifest:t.unknown(),result:t.unknown()}).strict().parse(await this.request(`/scoring-passes/${encodeURIComponent(u.parse(e))}/result`,"GET",void 0,n)),s=he(r);if(r.passId!==e||s.manifest.teamId!==this.options.teamId||s.manifest.id!==e||s.manifest.lineage?.execution.id!==r.executionId||s.manifest.lineage.scoringPassId!==e)throw new Error("Scoring result identity mismatch.");return{...s,executionId:r.executionId,passId:e}}async compare(e,n,r){let s=c(d=>d.startsWith("score_")?this.scoringResult(d,r):this.result(d,r),"read"),[i,a]=await Promise.all([s(e),s(n)]);return{baseline:i,candidate:a,comparison:Qe(i,a)}}definition(e,n){let r=xt(e);if(r.teamId!==this.options.teamId||n&&r.id!==n)throw new Error("Experiment identity mismatch.");return r}async executionDetails(e,n){let r=await oe(e);if(r.summary.teamId!==this.options.teamId||n&&r.summary.id!==n)throw new Error("Experiment execution identity mismatch.");return r}pass(e,n){let r=bt(e);if(r.teamId!==this.options.teamId||n&&r.id!==n)throw new Error("Scoring pass identity mismatch.");return r}async request(e,n,r,s){let i=await(this.options.fetch??fetch)(`${this.baseUrl}/v1/experiments${e}`,{method:n,signal:s,redirect:"error",headers:{Authorization:`Bearer ${this.options.apiKey}`,"X-OpenPond-Team-Id":this.options.teamId,"Content-Type":"application/json",Accept:"application/json"},...r===void 0?{}:{body:JSON.stringify(r)}}),a=await i.json();if(!i.ok){let d=t.object({code:t.string(),message:t.string()}).safeParse(a);throw new ve(i.status,d.success?d.data.code:"experiment_request_failed",d.success?d.data.message:"Experiment request failed.")}return a}};function wt(o){return o.policy.kind==="hosted_harness"?{...o,population:o.population.map(({receiptId:e,...n})=>n)}:o}c(wt,"savedRequestPopulation");function St(o,e){return{supportsResume:!e,get:c((...n)=>o.get(...n),"get"),start:e?async()=>{throw new Error("This runtime does not support resuming a stopped guest; start fresh Work with saved outputs")}:(...n)=>o.start(...n),exec:c((n,r)=>o.exec(n,e?{...r,timeoutSeconds:Math.min(r.timeoutSeconds??30,60)}:r),"exec"),mkdir:c((...n)=>o.mkdir(...n),"mkdir"),uploadFile:c((...n)=>o.uploadFile(...n),"uploadFile"),uploadFileBase64:c((...n)=>o.uploadFileBase64(...n),"uploadFileBase64"),listFiles:c((...n)=>o.listFiles(...n),"listFiles"),downloadFileResponse:c((...n)=>o.downloadFileResponse(...n),"downloadFileResponse"),stop:c((...n)=>o.stop(...n),"stop"),delete:c((...n)=>o.delete(...n),"delete"),createWork:c(({requestId:n,repo:r,budgetUsd:s,metadata:i})=>{if(e){if(r?.trim())throw new Error("This runtime does not support repository provisioning; provide Work inputs instead");if(s!==void 0)throw new Error("Hosted spending budgets are not supported by this runtime");let d={resources:e.resources??{cpu:1,memoryGb:2,diskGb:10},...n?{requestId:n}:{}};return o.create(d)}let a=s?.trim()||"1.00";return o.create({...r?.trim()?{repo:r.trim()}:{},runtimeProfileId:"openpond-work-v1",resources:{cpu:2,memoryGb:4,diskGb:16},budget:{maxUsd:a},quotas:{maxSpendUsd:a,maxDurationSeconds:3600,idleTimeoutSeconds:900,maxCommands:200,maxOpenPorts:4},metadata:{source:"openpond-sdk-work",...i,...n?{workRequestId:n}:{}}},{async:!0})},"createWork")}}c(St,"workSandbox");function Ee(o,e){let n=new URL(o);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||n.search||n.hash)throw new Error(`${e} must be an HTTP(S) endpoint without embedded credentials, query or fragment`);return n.toString().replace(/\/$/,"")}c(Ee,"configuredEndpoint");function ie(o,e){if(!o?.trim())throw new Error(`${e} is required`);return o.trim()}c(ie,"configuredKey");var on=t.object({choices:t.array(t.object({message:t.object({content:t.string().nullable().optional(),tool_calls:t.array(t.object({id:t.string().min(1),type:t.literal("function"),function:t.object({name:t.string().min(1),arguments:t.string()})})).optional()})})).min(1)});async function Pt(o,e){if(!e)return xe(o);let n=await fetch(`${o.apiBaseUrl}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${o.token}`,"content-type":"application/json"},body:JSON.stringify({model:o.model,messages:o.messages,tools:o.tools,tool_choice:"auto",stream:!1}),signal:o.signal,redirect:"error"});if(!n.ok)throw new Error(`Configured model request failed (${n.status})`);return on.parse(await n.json())}c(Pt,"workModelTurn");var sn="openpond-chat",an=24,cn=4e4,Ce=2e4,je="outputs",_e="inputs/previous-outputs",vt="inputs/.openpond-context.json",dn=100,kt=100,Rt=100*1024*1024,N=class{static{c(this,"OpenPondWorkClient")}#e;#n;#t;#r;#o;#s;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl,this.#t=e.chatApiBaseUrl,this.#r=St(e.sandboxes,e.sandboxConfig),this.#o=e.defaultModel??sn,this.#s=e.customModel??!1}async run(e){let n=e.prompt.trim();if(!n)throw new Error("Work prompt is required");e.signal?.throwIfAborted();let r=c(async w=>e.onEvent?.(w),"emit"),s=e.cleanup??"keep",i=mn(s),a=null,d=null,x=!1,b=Ot(e.maxSteps,1,100,an),g="";try{await r({type:"status",message:"Preparing sandbox"}),a=await this.#g(e),await r({type:"sandbox",sandboxId:a.id,state:a.state}),await this.#m(a.id,e.inputs??[]),d=await this.#u(a.id);let w=[{role:"system",content:pn(a.id,(e.inputs?.length??0)>0)},...(e.history??[]).map(P=>({...P})),{role:"user",content:n}];for(let P=1;P<=b;P+=1){e.signal?.throwIfAborted(),await r({type:"status",message:`Thinking \xB7 step ${P}`});let qe=(await Pt({apiBaseUrl:this.#t,token:this.#e,model:e.model?.trim()||this.#o,messages:w,tools:ln,toolChoice:"auto",signal:e.signal,metadata:{source:"openpond-sdk-work",sandboxId:a.id,apiBaseUrl:this.#n,...e.metadata}},this.#s)).choices?.[0],Y=qe?.message?.content?.trim()??"",X=qe?.message?.tool_calls??[];if(w.push({role:"assistant",content:Y||null,...X.length>0?{tool_calls:X}:{}}),Y&&(g=Y,await r({type:"assistant",text:Y})),X.length===0){let q=await this.#d(a.id,d);for(let le of q)await r({type:"output",output:le});x=!0,await this.#i(a.id,q,e,i,r);let Q={sandboxId:a.id,text:g,steps:P,outputs:q,lifecycle:i};return await r({type:"done",...Q}),Q}for(let[q,Q]of X.entries()){e.signal?.throwIfAborted();let le=await this.#f(a.id,Q,q,e.timeoutSeconds,r);w.push(le)}}throw new Error(`Work did not finish within ${b} steps`)}catch(w){if(a&&d&&!x)try{let P=await this.#d(a.id,d);for(let Me of P)await r({type:"output",output:Me});await this.#i(a.id,P,e,i,r)}catch(P){It(w,i,P)}throw It(w,i),w}}async deleteSandbox(e){try{if((await this.#r.get(e)).state==="deleted")return;await this.#r.delete(e)}catch(n){if(n instanceof te&&n.status===404)return;throw n}}async#m(e,n){if(n.length===0)return;if(n.length>kt)throw new Error(`Work inputs exceed the ${kt} file limit`);if(n.reduce((a,d)=>a+Buffer.byteLength(d.contentsBase64,"base64"),0)>Rt)throw new Error(`Work inputs exceed the ${Rt} byte limit`);await this.#r.mkdir(e,{path:_e,recursive:!0});let s=new Set,i=[];for(let[a,d]of n.entries()){let x=gn(d,a,s),b=`${_e}/${x}`;await this.#r.uploadFileBase64(e,b,d.contentsBase64),i.push({id:d.id,path:b,name:d.name,mimeType:d.mimeType??null,checksumSha256:d.checksumSha256??null,revision:d.revision??null,metadata:d.metadata??{}})}await this.#r.uploadFile(e,vt,JSON.stringify({version:1,files:i},null,2))}async#i(e,n,r,s,i){if(s.persistence.outputCount=n.length,n.length===0)s.persistence.status="not_needed";else if(r.persistOutput){s.persistence.status="running";for(let a of n){await i({type:"persistence",output:a,status:"started"});try{let d=un(this.#r,e,a);await r.persistOutput({output:a,download:d}),s.persistence.persistedCount+=1,await i({type:"persistence",output:a,status:"succeeded"})}catch(d){let x=D(d);throw s.persistence.status="failed",s.persistence.error=x,await i({type:"persistence",output:a,status:"failed",error:x}),(r.cleanup??"keep")!=="keep"&&await this.#a(e,s,i),d}}s.persistence.status="complete"}else{if((r.cleanup??"keep")==="delete"&&!r.discardOutputs)throw s.persistence.status="failed",s.persistence.error="Deleting a Work sandbox with outputs requires persistOutput or discardOutputs: true",await this.#a(e,s,i),new Error(s.persistence.error);s.persistence.status="not_requested"}await this.#c(e,r.cleanup??"keep",s,i)}async#a(e,n,r){if(this.#r.supportsResume){await this.#c(e,"stop",n,r);return}n.cleanup.status="pending",n.cleanup.finalSandboxState="running",n.cleanup.error="Output persistence must be retried before guest deletion",await r({type:"cleanup",policy:n.cleanupPolicy,status:"pending",sandboxState:"running",error:n.cleanup.error})}async#c(e,n,r,s){if(n!=="keep"){r.cleanup.status="running",await s({type:"cleanup",policy:n,status:"started"});try{let i=n==="delete"?await this.#r.delete(e):(await this.#r.stop(e)).sandbox;r.cleanup.finalSandboxState=i.state,r.cleanup.status=n==="delete"&&i.state==="deleted"||n==="stop"&&i.state==="stopped"?"complete":"pending",await s({type:"cleanup",policy:n,status:r.cleanup.status,sandboxState:i.state})}catch(i){let a=D(i);throw r.cleanup.status="failed",r.cleanup.error=a,await s({type:"cleanup",policy:n,status:"failed",error:a}),i}}}downloadOutput(e,n){return this.#r.downloadFileResponse(e,typeof n=="string"?n:n.path)}async#u(e){return await this.#r.mkdir(e,{path:je,recursive:!0}),fn(await this.#l(e))}async#d(e,n){return(await this.#l(e)).filter(s=>n.get(s.path)!==Et(s)).sort((s,i)=>s.path.localeCompare(i.path)).slice(0,dn).map(hn)}async#l(e){return(await this.#r.listFiles(e,{path:je,recursive:!0,maxEntries:500})).files.filter(r=>r.type==="file"&&!Ct(r.path).includes("/.openpond-"))}async#g(e){if(e.sandboxId){let r=await this.#r.get(e.sandboxId);if(r.state==="stopped")await this.#r.start(r.id,{async:!0});else if(r.state==="deleted"||r.state==="error")throw new Error(`Cannot resume sandbox ${r.id} in state ${r.state}`);return await this.#p(r.id,e.signal)}let n=await this.#r.createWork(e);return this.#p(n.id,e.signal)}async#p(e,n){let r=Date.now()+72e4,s=await this.#r.get(e);for(;Date.now()<r;){if(n?.throwIfAborted(),s.state==="running")return s;if(s.state==="error"||s.state==="deleted")throw new Error(`Sandbox ${s.id} entered ${s.state}${s.logs.length?`: ${s.logs.join(`
2
+ import{a as he,b as Qe}from"./chunk-KCENW4ME.js";import{B as Ke,D as Fe,E as Je,F as A,G as Ge,H as Ve,l as fe,z as Ne}from"./chunk-2Z6H32OC.js";import{a as te,b as O,c as v,h as et,i as ye,j as xe}from"./chunk-MJC26GOX.js";import{$a as ee,D as Be,M as De,Ma as Ye,P as ue,Wa as Xe,_a as Ze,b as me,ga as ge,h as Z,k as Ue,m as We,v as $e,z as ze}from"./chunk-TPOW52DO.js";import{a as h,e as Le,i as He,l,m as pe}from"./chunk-HZP5U2AA.js";import{b as t}from"./chunk-ES2ISFJC.js";import{a as c}from"./chunk-FTQLQJQV.js";var C=t.object({id:t.string().trim().min(1).max(240),revision:t.number().int().positive(),contentHash:t.string().regex(/^[a-f0-9]{64}$/),targetId:t.string().trim().min(1).max(240).nullable()}).strict(),be=t.array(t.object({role:t.enum(["system","user","assistant"]),content:t.string().max(1e5)}).strict()).max(100).superRefine((o,e)=>{o.reduce((n,r)=>n+r.content.length,0)>1e5&&e.addIssue({code:"custom",message:"Evaluation prompt exceeds 100,000 characters."})});var we=De.extend({mode:t.enum(["nightly","approved_count"]),minimumTasks:t.number().int().min(1).max(1e4),maximumSpendUsd:t.number().positive().max(1e5),maximumDailySpendUsd:t.number().positive().max(1e6)}).strict().superRefine((o,e)=>{o.maximumDailySpendUsd<o.maximumSpendUsd&&e.addIssue({code:"custom",path:["maximumDailySpendUsd"],message:"The daily budget must cover one update."})});var j=class extends Error{static{c(this,"OpenPondProtocolError")}code;constructor(e,n){super(n),this.name="OpenPondProtocolError",this.code=e}};function f(o){return JSON.stringify(Se(o))}c(f,"canonicalJson");async function ne(o){let e=new TextEncoder().encode(f(o)),n=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}c(ne,"canonicalSha256");function Se(o){if(o===null||typeof o=="string"||typeof o=="boolean")return o;if(typeof o=="number"){if(!Number.isFinite(o))throw new j("non_json_value","Canonical JSON cannot contain a non-finite number.");return Object.is(o,-0)?0:o}if(Array.isArray(o))return o.map(e=>Se(e));if(typeof o=="object"){let e=Object.getPrototypeOf(o);if(e!==Object.prototype&&e!==null)throw new j("non_json_value","Canonical JSON accepts only plain objects.");let n={};for(let r of Object.keys(o).sort()){let s=o[r];if(s===void 0||typeof s=="function"||typeof s=="symbol")throw new j("non_json_value",`Canonical JSON cannot contain ${typeof s} at ${r}.`);n[r]=Se(s)}return n}throw new j("non_json_value",`Canonical JSON cannot contain ${typeof o}.`)}c(Se,"normalizeCanonicalJson");var p=t.string().trim().min(1).max(500),E=t.string().regex(/^[a-f0-9]{64}$/),k=t.string().datetime({offset:!0}),_=t.object({id:p,contentHash:E}).strict(),R=_.extend({revision:t.number().int().positive()}).strict(),L=t.object({schemaVersion:t.literal("openpond.baseModelPreference.v1"),modelId:p,revision:t.string().trim().min(1).max(256).nullable(),tokenizerRevision:t.string().trim().min(1).max(256).nullable(),chatTemplateHash:t.string().trim().min(8).max(256).nullable(),modelAssetId:p.nullable(),source:t.enum(["managed","local","builtin"])}).strict(),tt=t.enum(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),$t=t.object({schemaVersion:t.string().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:tt,parameterization:t.enum(["lora","full"])}).catchall(t.unknown()),zt=t.object({profileProjectId:p,sourceRevision:t.string().regex(/^[a-f0-9]{40,64}$/),harnessRelease:_}).strict(),Bt=t.object({profileProjectId:p,sourceRevision:t.string().regex(/^[a-f0-9]{40,64}$/),catalogHash:E,definitionId:p,harnessRelease:_,tasksetRelease:_}).strict(),nt=t.object({tasksetRef:R.nullable().default(null),evaluationTasksetRef:R.nullable().optional(),profileSource:zt.nullable().optional(),profileEvaluation:Bt.nullable().optional(),rewardBindingRef:R.nullable().optional(),tasksetRelease:_.nullable().default(null),harnessRelease:_.nullable().default(null),baseModel:L.nullable().default(null),method:tt.nullable().default(null),destinationId:p.nullable().default(null),managedRolloutPlacement:t.enum(["local","remote"]).default("remote"),managedGpuPlacementObjective:t.enum(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:t.enum(["any","h100_hbm3"]).default("any"),runPreset:t.enum(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:$t.nullable().default(null),preferredMaximumSpendUsd:t.number().nonnegative().nullable().default(null),preferredRetentionDays:t.number().int().nonnegative().nullable().default(null)}).strict(),rt=nt.omit({managedGpuRequirement:!0}),Dt=t.object({schemaVersion:t.literal("openpond.hostedModelProjectLink.v1"),apiOrigin:t.string().url().refine(o=>new URL(o).origin===o,"Use a canonical API origin.").nullable().default(null),teamId:p,projectId:p,portableProjectId:p,revision:t.number().int().positive(),etag:E,syncedSourceRevision:t.number().int().positive(),syncedAt:k,tasksets:t.array(t.object({localTasksetId:p,localTasksetHash:E.nullable().default(null),releaseId:p,releaseRevision:t.number().int().positive(),releaseHash:E,packageHash:E.nullable().default(null),hostedTasksetId:p,syncedAt:k}).strict()).max(1e4).default([])}).strict(),Nt=t.object({localTasksetId:p,releaseId:p,releaseRevision:t.number().int().positive(),releaseHash:E,state:t.enum(["syncing","synced","sync_failed"]),hostedTasksetId:p.nullable().default(null),lastAttemptAt:k,syncedAt:k.nullable().default(null),lastError:t.string().trim().min(1).max(5e3).nullable().default(null)}).strict(),Kt=t.object({schemaVersion:t.literal("openpond.modelProject.v2"),id:p,profileId:p,revision:t.number().int().positive().default(1),name:t.string().trim().min(1).max(200),objective:t.string().trim().max(5e3).nullable(),defaultBaseModel:L.nullable(),defaultDestinationId:p.nullable(),trainingSetup:nt,hosted:Dt.nullable().default(null),tasksetSyncs:t.array(Nt).max(1e4).default([]),createdAt:k,updatedAt:k}).strict(),Ft=Kt.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),Ln=t.object({schemaVersion:t.literal("openpond.modelProjectSave.v1"),operationId:p,expectedRevision:t.number().int().nonnegative(),project:Ft,learning:we.optional()}).strict().superRefine((o,e)=>{o.learning&&o.expectedRevision!==0&&e.addIssue({code:"custom",path:["learning"],message:"Use learning settings to edit an existing Model's policy."})}),Hn=t.object({schemaVersion:t.literal("openpond.modelProjectConfigurationCheck.v1"),configurationHash:E,projectId:p,expectedRevision:t.number().int().nonnegative(),checkedAt:k,canSave:t.boolean(),deferred:t.array(t.enum(["base_model","taskset"])).max(2),findings:t.array(t.object({code:p,severity:t.enum(["error","warning"]),message:t.string().min(1).max(5e3),field:t.string().min(1).max(500).nullable()}).strict()).max(100)}).strict(),Un=t.object({id:p,name:t.string().min(1).max(500),available:t.boolean(),preference:L}).strict();var Wn=t.object({schemaVersion:t.literal("openpond.hostedModelProjectSync.v2"),portableProjectId:p,name:t.string().trim().min(1).max(200),objective:t.string().trim().max(5e3).nullable(),defaultBaseModel:L.nullable(),defaultDestinationId:p.nullable(),trainingSetup:rt,sourceRevision:t.number().int().positive(),sourceUpdatedAt:k,expectedEtag:E.nullable().default(null)}).strict(),Jt=t.object({id:p,teamId:p,portableProjectId:p,name:t.string().trim().min(1).max(200),objective:t.string().trim().max(5e3).nullable(),defaultBaseModel:L.nullable(),defaultDestinationId:p.nullable(),trainingSetup:rt,sourceRevision:t.number().int().positive(),sourceUpdatedAt:k,revision:t.number().int().positive(),etag:E,createdAt:k,updatedAt:k}).strict(),Gt=t.object({kind:t.enum(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:_,role:t.string().trim().min(1).max(200).nullable().default(null),updatedAt:k}).strict(),$n=t.object({project:Jt,resources:t.array(Gt).max(1e4),jobCount:t.number().int().nonnegative(),latestJobIds:t.array(p).max(100)}).strict(),zn=t.object({schemaVersion:t.literal("openpond.modelProjectApiError.v2"),code:t.string().trim().min(1).max(200),message:t.string().trim().min(1).max(5e3),retryable:t.boolean().default(!1),requestId:t.string().trim().min(1).max(500).nullable().default(null),details:t.record(t.string(),t.unknown()).default({})}).strict();var ot=t.object({schemaVersion:t.literal("openpond.experimentAttemptGrade.v1"),selectionHash:t.string().regex(/^[a-f0-9]{64}$/),grades:t.array(Z).min(1).max(100),score:t.number().min(0).max(1).nullable(),passed:t.boolean(),rewardEligible:t.boolean(),gradingStatus:t.enum(["scored","unscorable","not_configured"]),failureClass:He.nullable(),contentHash:t.string().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((o,e)=>{let{contentHash:n,...r}=o;l(r)!==n&&e.addIssue({code:"custom",message:"Experiment grading integrity failed."});let s=o.grades.flatMap(i=>i.components);(s.length!==o.grades.length||new Set(s.map(i=>i.graderId)).size!==s.length)&&e.addIssue({code:"custom",message:"Each selected criterion requires exactly one distinct grader result."});for(let i of o.grades){let{contentHash:a,...d}=i;l(d)!==a&&e.addIssue({code:"custom",message:"A retained criterion changed."});for(let x of i.components){let{contentHash:b,...g}=x;l(g)!==b&&e.addIssue({code:"custom",message:"A retained grader result changed."})}}});var m=t.string().trim().min(1).max(200),H=t.string().regex(/^[a-f0-9]{64}$/),Pe=t.discriminatedUnion("kind",[t.object({kind:t.literal("hosted_chat"),modelId:m,messages:be.optional(),maxOutputTokens:t.number().int().min(1).max(4096).default(1024),temperature:t.number().min(0).max(2).default(0),topP:t.number().gt(0).max(1).default(1)}).strict(),t.object({kind:t.literal("fixture"),fixtureId:m}).strict()]),Vt=t.object({schemaVersion:t.literal("openpond.modelStarterAttemptRequest.v1"),operationId:m,teamId:m,modelProjectId:m.nullable(),project:C.optional(),taskset:R,taskId:m,environmentSeed:t.number().int().min(0).max(2147483647).default(0),policy:Pe}).strict(),rr=t.object({modelProjectId:m.nullable(),taskset:R,afterTaskId:m.optional(),limit:t.number().int().min(1).max(100).default(25)}).strict(),or=t.object({modelProjectId:m.nullable(),taskset:R,available:t.boolean(),unavailableReason:t.string().max(1e3).nullable(),models:t.array(t.object({id:m,name:t.string().max(500)}).strict()).max(200),tasks:t.array(t.object({id:m,split:t.enum(["train","validation","frozen_eval"]),inputPreview:t.string().max(500),fixtures:t.array(t.object({id:m,label:t.string().max(200)}).strict()).max(1e3)}).strict()).max(100),nextCursor:m.nullable()}).strict(),re=t.object({schemaVersion:t.literal("openpond.modelStarterAttemptSummary.v1"),id:m,revision:t.number().int().positive(),request:Vt,status:t.enum(["queued","running","cancelling","completed","failed","cancelled"]),policySnapshot:t.object({modelId:m,provider:m,upstreamModelId:t.string().min(1).max(500),configurationHash:H}).strict().nullable(),createdAt:t.iso.datetime(),startedAt:t.iso.datetime().nullable(),completedAt:t.iso.datetime().nullable(),cleanupComplete:t.boolean(),resultAvailable:t.boolean(),score:t.number().min(0).max(1).nullable(),gradingStatus:t.enum(["not_started","scored","unscorable","not_configured"]).default("not_started"),passed:t.boolean().nullable(),outputPreview:t.string().max(500).nullable(),error:t.object({code:m,message:t.string().max(2e3)}).strict().nullable()}).strict().superRefine((o,e)=>{o.request.policy.kind==="fixture"!=(o.policySnapshot===null)&&e.addIssue({code:"custom",path:["policySnapshot"],message:"Fixture execution must not claim a model identity."}),o.status==="completed"&&(!o.cleanupComplete||!o.resultAvailable||!o.completedAt)&&e.addIssue({code:"custom",message:"Completed attempts require retained results and confirmed cleanup."})}),sr=t.object({modelProjectId:m,afterId:m.optional(),limit:t.number().int().min(1).max(100).default(25)}).strict(),ir=t.object({items:t.array(re).max(100),nextCursor:m.nullable()}).strict(),ar=t.object({schemaVersion:t.literal("openpond.modelStarterAttemptResult.v1"),attempt:re,output:t.string().max(1048576).nullable(),messages:t.array(t.record(t.string(),t.unknown())).max(4002),composition:Be.nullable(),grade:Z.nullable().optional(),experimentGrade:ot.nullable().optional(),environment:t.object({status:t.enum(["completed","budget_exhausted","cancelled","timed_out","policy_failure","environment_failure"]),collected:t.boolean(),definition:R,initialStateHash:H.nullable(),finalStateHash:H.nullable(),attemptHash:H}).strict(),providerRequestIds:t.array(m).max(1001),contentHash:H}).strict().superRefine((o,e)=>{o.experimentGrade&&((o.grade||o.composition)&&e.addIssue({code:"custom",message:"Selected Experiment grading cannot claim another grade population."}),(!["completed","failed"].includes(o.attempt.status)||!o.attempt.resultAvailable||o.attempt.score!==o.experimentGrade.score||o.attempt.gradingStatus!==o.experimentGrade.gradingStatus||o.attempt.passed!==(o.experimentGrade.score===null?null:o.experimentGrade.passed))&&e.addIssue({code:"custom",message:"Experiment grading differs from its retained attempt summary."})),o.grade&&(o.composition&&e.addIssue({code:"custom",path:["grade"],message:"An ordinary grade cannot also claim a Reward composition."}),(!["completed","failed"].includes(o.attempt.status)||!o.attempt.resultAvailable||o.attempt.score!==o.grade.score||o.attempt.gradingStatus!==o.grade.gradingStatus||o.attempt.passed!==(o.grade.score===null?null:o.grade.passed))&&e.addIssue({code:"custom",path:["grade"],message:"Ordinary grade differs from its terminal attempt summary."}))});var st=t.string().trim().min(1).max(240),it=t.string().regex(/^[a-f0-9]{64}$/),ke=t.object({kind:t.literal("hosted_harness"),modelId:st,reasoningEffort:t.enum(["off","low","medium","high","xhigh","max"]).optional(),profileRepositoryId:st,source:Xe,modelConfigurationHash:it,packageHash:it}).strict();var I=t.string().trim().min(1).max(200),at=t.string().regex(/^[a-f0-9]{64}$/),Yt=t.discriminatedUnion("kind",[Pe.options[0],t.object({kind:t.literal("fixture")}).strict(),ke]),U=t.object({schemaVersion:t.literal("openpond.modelTasksetRunRequest.v1"),operationId:I,teamId:I,modelProjectId:I.nullable(),name:t.string().trim().min(1).max(200).optional(),project:C.optional(),taskset:R,policy:Yt,population:t.array(Ze).min(1).max(1e4)}).strict().superRefine((o,e)=>{new Set(o.population.map(n=>n.receiptId)).size!==o.population.length&&e.addIssue({code:"custom",path:["population"],message:"Run receipt identities must be unique."}),o.population.some(n=>n.fixtureId!==null!=(o.policy.kind==="fixture"))&&e.addIssue({code:"custom",path:["population"],message:"Only fixture runs require a fixture identity for every member."}),o.population.some(n=>!/^(0|[1-9][0-9]*)$/.test(n.seed)||Number(n.seed)>2147483647)&&e.addIssue({code:"custom",path:["population"],message:"Hosted environment seeds must be integers from 0 to 2147483647."}),o.policy.kind==="hosted_harness"&&o.modelProjectId!==null&&e.addIssue({code:"custom",path:["modelProjectId"],message:"A Harness target retains its released Profile binding separately from Model artifacts."}),o.policy.kind==="hosted_harness"&&new Set(o.population.map(n=>f([n.taskId,n.seed]))).size!==o.population.length&&e.addIssue({code:"custom",path:["population"],message:"Harness case identities must be unique for each task and seed."})}),ct=t.object({schemaVersion:t.literal("openpond.modelTasksetRunSummary.v1"),id:I,revision:t.number().int().positive(),teamId:I,modelProjectId:I.nullable(),name:t.string().trim().min(1).max(200).optional(),project:C.optional(),operationId:I,taskset:R,policyKind:t.enum(["hosted_chat","fixture","hosted_harness"]),manifestHash:at,status:t.enum(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:t.number().int().min(1).max(1e4),counts:t.object({pending:t.number().int().nonnegative(),running:t.number().int().nonnegative(),completed:t.number().int().nonnegative(),failed:t.number().int().nonnegative(),cancelled:t.number().int().nonnegative()}).strict(),createdAt:t.iso.datetime(),startedAt:t.iso.datetime().nullable(),completedAt:t.iso.datetime().nullable(),cleanupComplete:t.boolean(),resultAvailable:t.boolean(),score:t.number().min(0).max(1).nullable(),metricName:t.string().min(1).max(240),error:t.object({code:I,message:t.string().max(2e3)}).strict().nullable()}).strict().superRefine((o,e)=>{Object.values(o.counts).reduce((n,r)=>n+r,0)!==o.totalCount&&e.addIssue({code:"custom",path:["counts"],message:"Run counts must account for the complete population."}),o.status!=="completed"&&o.score!==null&&e.addIssue({code:"custom",path:["score"],message:"Only completed evaluations publish a metric value."}),["completed","failed","cancelled"].includes(o.status)&&(!o.completedAt||o.counts.pending||o.counts.running)&&e.addIssue({code:"custom",message:"Terminal runs require complete population accounting."}),o.status==="cancelled"&&!o.cleanupComplete&&e.addIssue({code:"custom",message:"Cancelled runs require confirmed cleanup."}),o.resultAvailable&&!["completed","failed","cancelled"].includes(o.status)&&e.addIssue({code:"custom",message:"Run results require terminal population accounting."}),o.status==="completed"&&(!o.cleanupComplete||!o.resultAvailable)&&e.addIssue({code:"custom",message:"Completed evaluations require retained results and confirmed cleanup."})}),dt=t.object({summary:ct,request:U,manifest:ee,policySnapshot:re.shape.policySnapshot}).strict(),Ir=t.object({modelProjectId:I.optional(),projectId:C.shape.id.optional(),afterId:I.optional(),limit:t.number().int().min(1).max(100).default(25)}).strict(),Or=t.object({items:t.array(ct).max(100),nextCursor:I.nullable()}).strict(),vr=t.object({schemaVersion:t.literal("openpond.modelTasksetRunResult.v1"),run:dt,receipts:t.array(Ye).min(1).max(1e4),metric:Ue.nullable(),contentHash:at}).strict();function Re(o,e){pe(e,"Taskset run manifest");let n=o.policy;if(n.kind!=="hosted_harness"||e.execution.kind!=="harness"||f(e.profileEvaluation)!==f(n.source)||f(e.execution.harnessRelease)!==f(n.source.harnessRelease)||e.metadata.profileRepositoryId!==n.profileRepositoryId||e.packageHash!==n.packageHash||e.policy.kind!=="model"||e.policy.model.provider!=="openpond"||e.policy.model.model!==n.modelId||e.policy.model.revision!==null||e.policy.model.artifactHash!==null||e.policy.model.tokenizerRevision!==null||e.policy.model.chatTemplateHash!==null||e.policy.configurationHash!==n.modelConfigurationHash||e.tasksetRelease.id!==o.taskset.id||e.tasksetRelease.contentHash!==o.taskset.contentHash||f(e.population)!==f(o.population)||e.population.some(r=>r.receiptId!==`evaluation-${l([e.id,r.taskId,r.seed]).slice(0,32)}`))throw new Error("Harness evaluation differs from its admitted source, package or model configuration.")}c(Re,"verifyHarnessExperimentManifest");async function oe(o){let e=dt.parse(o),{summary:n,request:r,manifest:s,policySnapshot:i}=e;if(pe(s,"Taskset run manifest"),s.contentHash!==n.manifestHash||s.id!==n.id||s.createdAt!==n.createdAt||n.teamId!==r.teamId||n.modelProjectId!==r.modelProjectId||f(n.project??null)!==f(r.project??null)||f(s.metadata.project??null)!==f(r.project??null)||(n.name??null)!==(r.name??null)||n.operationId!==r.operationId||n.policyKind!==r.policy.kind||n.totalCount!==r.population.length||n.metricName!==s.metricPolicy.primaryMetric||f(n.taskset)!==f(r.taskset)||s.tasksetRelease.id!==r.taskset.id||s.tasksetRelease.contentHash!==r.taskset.contentHash||f(s.population)!==f(r.population))throw new Error("Evaluation run differs from its admitted request or manifest.");if(r.policy.kind==="fixture"){if(s.policy.kind!=="fixture"||i!==null)throw new Error("Fixture checks cannot claim a model identity.")}else if(r.policy.kind==="hosted_harness"){if(Re(r,s),i!==null)throw new Error("Harness evaluations retain the native host model configuration.")}else if(s.policy.kind!=="model"||!i||i.modelId!==r.policy.modelId||s.policy.model.provider!==i.provider||s.policy.model.model!==i.upstreamModelId||s.policy.model.revision!==null||s.policy.model.artifactHash!==null||s.policy.model.tokenizerRevision!==null||s.policy.model.chatTemplateHash!==null||s.policy.configurationHash!==await ne({policy:r.policy,snapshot:i}))throw new Error("Evaluation model differs from its admitted policy.");return e}c(oe,"verifyModelTasksetRunDetails");var mt=t.string().min(1).max(200).refine(o=>!["__proto__","prototype","constructor"].includes(o),"Use an ordinary field name."),Xt=t.array(mt).min(1).max(20),lt=t.enum(["input","output","expectedOutput","evaluatorContext"]),Qt=t.object({destination:lt,path:Xt,source:lt,sourcePath:t.array(mt).max(20)}).strict(),W=t.array(Qt).max(100).superRefine((o,e)=>{for(let[n,r]of o.entries())o.slice(0,n).some(s=>s.destination===r.destination&&(pt(s.path,r.path)||pt(r.path,s.path)))&&e.addIssue({code:"custom",path:[n,"path"],message:"Mapped destination paths must not overlap."})});function pt(o,e){return o.length<=e.length&&o.every((n,r)=>n===e[r])}c(pt,"prefix");var S=t.string().trim().min(1).max(200),$=t.string().regex(/^[a-f0-9]{64}$/),T=t.object({id:S,revision:t.number().int().positive(),contentHash:$}).strict(),z=t.object({id:S,version:t.string().min(1).max(200),contentHash:$,feedbackKey:$e,release:T.nullable(),mappings:W.optional()}).strict(),Zt=t.object({id:S,version:t.string().min(1).max(200),contentHash:$,mappings:W}).strict(),ut=t.object({operationId:S,id:S.optional(),expectedRevision:t.number().int().nonnegative(),request:U,maximumCostUsd:t.number().finite().positive().max(1e4),graders:t.array(Zt).min(1).max(100).optional()}).strict().superRefine((o,e)=>{o.request.name||e.addIssue({code:"custom",path:["request","name"],message:"Name this Experiment before saving it."}),!!o.id!=o.expectedRevision>0&&e.addIssue({code:"custom",path:["expectedRevision"],message:"An update requires its saved definition revision."}),Math.round(o.maximumCostUsd*1e6)<1&&e.addIssue({code:"custom",path:["maximumCostUsd"],message:"The budget must be at least $0.000001."}),o.graders&&new Set(o.graders.map(n=>n.id)).size!==o.graders.length&&e.addIssue({code:"custom",path:["graders"],message:"Select each grader once."})}),en=t.object({schemaVersion:t.literal("openpond.experimentDefinition.v1"),id:S,teamId:S,revision:t.number().int().positive(),request:U,maximumCostUsd:t.number().finite().positive().max(1e4),graders:t.array(z).min(1).max(100),createdAt:t.iso.datetime(),updatedAt:t.iso.datetime()}).strict(),tn=en.extend({contentHash:$}),gt=t.object({operationId:S,definition:T}).strict(),ft=t.object({projectId:S.optional(),datasetHash:$.optional(),search:t.string().trim().max(200).optional(),afterId:S.optional(),limit:t.number().int().min(1).max(100).default(30)}).strict(),$r=t.object({definition:T,maximumCostUsd:t.number().finite().positive().max(1e4),graders:t.array(z).min(1).max(100)}).strict(),ht=t.object({operationId:S,profileRepositoryId:S,definitionId:S,modelId:S,reasoningEffort:t.enum(["off","low","medium","high","xhigh","max"]).optional(),maximumCostUsd:t.number().finite().positive().max(1e4)}).strict(),yt=t.object({request:U,manifest:ee,maximumCostUsd:t.number().finite().positive().max(1e4),graders:t.array(z).min(1).max(100)}).strict();function xt(o){let e=tn.parse(o),{contentHash:n,...r}=e;if(n!==l(r)||e.request.teamId!==e.teamId||!e.request.name)throw new Error("Experiment definition differs from its immutable content.");if(new Set(e.graders.map(s=>s.feedbackKey)).size!==e.graders.length)throw new Error("Experiment feedback keys must be distinct.");return e}c(xt,"verifyExperimentDefinition");var Ie=c(o=>({id:o.id,revision:o.revision,contentHash:o.contentHash}),"experimentDefinitionRef");var B=t.string().trim().min(1).max(200),Oe=t.object({operationId:B,execution:Le,graders:t.array(ze).min(1).max(100),maximumCostUsd:t.number().finite().min(1e-6).max(1e4),mappings:t.array(t.object({graderId:B,fields:W}).strict()).max(100).optional()}).strict().superRefine((o,e)=>{new Set(o.graders.map(n=>n.id)).size!==o.graders.length&&e.addIssue({code:"custom",path:["graders"],message:"Select each grader once."}),o.mappings&&(new Set(o.mappings.map(n=>n.graderId)).size!==o.mappings.length||o.mappings.some(n=>!o.graders.some(r=>r.id===n.graderId)))&&e.addIssue({code:"custom",path:["mappings"],message:"Map each selected grader at most once."})}),nn=t.object({schemaVersion:t.literal("openpond.experimentScoringPass.v1"),id:B,teamId:B,revision:t.number().int().positive(),request:Oe,graders:t.array(z).min(1).max(100),status:t.enum(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:t.number().int().min(1).max(1e4),counts:t.object({pending:t.number().int().nonnegative(),running:t.number().int().nonnegative(),scored:t.number().int().nonnegative(),unavailable:t.number().int().nonnegative(),failed:t.number().int().nonnegative(),cancelled:t.number().int().nonnegative()}).strict(),resultAvailable:t.boolean(),createdAt:t.iso.datetime(),startedAt:t.iso.datetime().nullable(),completedAt:t.iso.datetime().nullable(),error:t.object({code:B,message:t.string().max(2e3)}).strict().nullable()}).strict(),rn=nn.extend({contentHash:t.string().regex(/^[a-f0-9]{64}$/)});function bt(o){let e=rn.parse(o),{contentHash:n,...r}=e;if(l(r)!==n||Object.values(e.counts).reduce((i,a)=>i+a,0)!==e.totalCount)throw new Error("Scoring pass integrity or population accounting failed.");let s=["completed","failed","cancelled"].includes(e.status);if(s&&(!e.completedAt||e.counts.pending||e.counts.running)||!s&&(e.completedAt!==null||e.resultAvailable)||e.status==="completed"&&!e.resultAvailable)throw new Error("Scoring pass lifecycle differs from its retained result.");if(e.graders.length!==e.request.graders.length||new Set(e.graders.map(i=>i.feedbackKey)).size!==e.graders.length||e.graders.some((i,a)=>l(i.release)!==l(e.request.graders[a])||l(i.mappings??[])!==l(e.request.mappings?.find(d=>d.graderId===i.release?.id)?.fields??[])))throw new Error("Scoring pass graders differ from their exact admission.");return e}c(bt,"verifyExperimentScoringPass");var u=t.string().trim().min(1).max(200),ve=class extends Error{constructor(n,r,s){super(s);this.status=n;this.code=r;this.name="OpenPondExperimentError"}status;code;static{c(this,"OpenPondExperimentError")}},se=class{constructor(e){this.options=e;let n=new URL(e.baseUrl);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||n.search||n.hash||!e.apiKey.trim()||!e.teamId.trim())throw new Error("A clean API origin and workspace credentials are required.");this.baseUrl=n.toString().replace(/\/+$/,"")}options;static{c(this,"OpenPondExperimentsClient")}baseUrl;async prepareHarness(e,n){let r=ht.parse(e),s=yt.parse(await this.request("/harness-setup","POST",r,n));Re(s.request,s.manifest);let i=s.request.policy;if(s.request.teamId!==this.options.teamId||s.request.operationId!==r.operationId||i.kind!=="hosted_harness"||i.profileRepositoryId!==r.profileRepositoryId||i.source.definitionId!==r.definitionId||i.modelId!==r.modelId||i.reasoningEffort!==r.reasoningEffort||s.maximumCostUsd!==r.maximumCostUsd||s.manifest.limits.maximumSpendUsd!==r.maximumCostUsd)throw new Error("Harness preparation differs from its requested scope or configuration.");return s}async save(e,n){let r=ut.parse(e);if(r.request.teamId!==this.options.teamId)throw new Error("Experiment workspace mismatch.");let s=this.definition(await this.request("","POST",r,n),r.id);if(s.revision!==r.expectedRevision+1||l(s.request)!==l(r.request)||s.maximumCostUsd!==r.maximumCostUsd)throw new Error("Experiment save receipt differs from its submitted configuration.");if(r.graders&&l(r.graders)!==l(s.graders.map(i=>({id:i.id,version:i.version,contentHash:i.contentHash,mappings:i.mappings??[]}))))throw new Error("Experiment save receipt differs from its selected graders or mappings.");return s}async get(e,n={}){let r=n.reference?T.parse(n.reference):void 0;if(r&&r.id!==e)throw new Error("Experiment reference identity mismatch.");let s=r?`?${new URLSearchParams({revision:String(r.revision),contentHash:r.contentHash})}`:"",i=this.definition(await this.request(`/${encodeURIComponent(u.parse(e))}${s}`,"GET",void 0,n.signal),e);if(n.reference&&l(Ie(i))!==l(n.reference))throw new Error("Experiment revision mismatch.");return i}async list(e={},n){let r=ft.parse(e),s=new URLSearchParams(Object.entries(r).map(([d,x])=>[d,String(x)])),i=t.object({items:t.array(t.unknown()).max(100),nextCursor:u.nullable()}).strict().parse(await this.request(`?${s}`,"GET",void 0,n)),a=i.items.map(d=>this.definition(d));if(a.length>r.limit||new Set(a.map(d=>d.id)).size!==a.length||a.some(d=>r.projectId&&d.request.project?.id!==r.projectId||r.datasetHash&&d.request.taskset.contentHash!==r.datasetHash))throw new Error("Experiment page differs from its selected scope.");return{items:a,nextCursor:i.nextCursor}}async start(e,n){let r=gt.parse(e),s=t.object({definition:t.unknown(),run:t.unknown()}).strict().parse(await this.request(`/${encodeURIComponent(r.definition.id)}/start`,"POST",r,n)),i=this.definition(s.definition,r.definition.id);if(l(Ie(i))!==l(r.definition))throw new Error("Experiment Start revision mismatch.");let a=await oe(s.run);if(a.summary.teamId!==this.options.teamId||a.request.operationId!==r.operationId||l(wt(a.request))!==l(wt({...i.request,operationId:r.operationId}))||l(a.manifest.metadata.experimentDefinition)!==l(r.definition)||a.manifest.metadata.experimentConfigurationHash!==l({definition:r.definition,maximumCostUsd:i.maximumCostUsd,graders:i.graders}))throw new Error("Experiment execution differs from its saved configuration.");return a}async result(e,n){let r=t.object({executionId:u,passId:u.nullable(),manifest:t.unknown(),result:t.unknown()}).strict().parse(await this.request(`/executions/${encodeURIComponent(u.parse(e))}/result`,"GET",void 0,n)),s=he(r);if(r.executionId!==e||s.manifest.teamId!==this.options.teamId||s.manifest.lineage?.execution.id!==e||s.manifest.lineage.scoringPassId!==r.passId)throw new Error("Experiment result identity mismatch.");return{...s,executionId:e,passId:r.passId}}async executions(e,n={}){let r=new URLSearchParams(n.afterId?{afterId:u.parse(n.afterId)}:{}),s=t.object({items:t.array(t.unknown()).max(30),nextCursor:u.nullable()}).strict().parse(await this.request(`/${encodeURIComponent(u.parse(e))}/executions?${r}`,"GET",void 0,n.signal)),i=await Promise.all(s.items.map(a=>oe(a)));if(i.some(a=>a.summary.teamId!==this.options.teamId||T.parse(a.manifest.metadata.experimentDefinition).id!==e)||new Set(i.map(a=>a.summary.id)).size!==i.length)throw new Error("Experiment execution page has invalid ownership or repeated identities.");return{items:i,nextCursor:s.nextCursor}}async execution(e,n){return this.executionDetails(await this.request(`/executions/${encodeURIComponent(u.parse(e))}`,"GET",void 0,n),e)}async cancel(e,n){return this.executionDetails(await this.request(`/executions/${encodeURIComponent(u.parse(e))}/cancel`,"POST",{},n),e)}async retry(e,n,r){let s=await this.executionDetails(await this.request(`/executions/${encodeURIComponent(u.parse(e))}/retry`,"POST",{operationId:u.parse(n)},r));if(s.request.operationId!==n)throw new Error("Experiment retry operation mismatch.");return s}async score(e,n){let r=Oe.parse(e),s=this.pass(await this.request(`/executions/${encodeURIComponent(r.execution.id)}/scoring-passes`,"POST",r,n));if(l(s.request)!==l(r))throw new Error("Scoring admission differs from its submitted inputs.");return s}async scoringPass(e,n){return this.pass(await this.request(`/scoring-passes/${encodeURIComponent(u.parse(e))}`,"GET",void 0,n),e)}async scoringPasses(e,n={}){let r=new URLSearchParams(n.afterId?{afterId:u.parse(n.afterId)}:{}),s=t.object({items:t.array(t.unknown()).max(30),nextCursor:u.nullable()}).strict().parse(await this.request(`/executions/${encodeURIComponent(u.parse(e))}/scoring-passes?${r}`,"GET",void 0,n.signal)),i=s.items.map(a=>this.pass(a));if(i.some(a=>a.request.execution.id!==e)||new Set(i.map(a=>a.id)).size!==i.length)throw new Error("Scoring pass page differs from its execution ownership.");return{items:i,nextCursor:s.nextCursor}}async cancelScoringPass(e,n){return this.pass(await this.request(`/scoring-passes/${encodeURIComponent(u.parse(e))}/cancel`,"POST",{},n),e)}async scoringResult(e,n){let r=t.object({executionId:u,passId:u,manifest:t.unknown(),result:t.unknown()}).strict().parse(await this.request(`/scoring-passes/${encodeURIComponent(u.parse(e))}/result`,"GET",void 0,n)),s=he(r);if(r.passId!==e||s.manifest.teamId!==this.options.teamId||s.manifest.id!==e||s.manifest.lineage?.execution.id!==r.executionId||s.manifest.lineage.scoringPassId!==e)throw new Error("Scoring result identity mismatch.");return{...s,executionId:r.executionId,passId:e}}async compare(e,n,r){let s=c(d=>d.startsWith("score_")?this.scoringResult(d,r):this.result(d,r),"read"),[i,a]=await Promise.all([s(e),s(n)]);return{baseline:i,candidate:a,comparison:Qe(i,a)}}definition(e,n){let r=xt(e);if(r.teamId!==this.options.teamId||n&&r.id!==n)throw new Error("Experiment identity mismatch.");return r}async executionDetails(e,n){let r=await oe(e);if(r.summary.teamId!==this.options.teamId||n&&r.summary.id!==n)throw new Error("Experiment execution identity mismatch.");return r}pass(e,n){let r=bt(e);if(r.teamId!==this.options.teamId||n&&r.id!==n)throw new Error("Scoring pass identity mismatch.");return r}async request(e,n,r,s){let i=await(this.options.fetch??fetch)(`${this.baseUrl}/v1/experiments${e}`,{method:n,signal:s,redirect:"error",headers:{Authorization:`Bearer ${this.options.apiKey}`,"X-OpenPond-Team-Id":this.options.teamId,"Content-Type":"application/json",Accept:"application/json"},...r===void 0?{}:{body:JSON.stringify(r)}}),a=await i.json();if(!i.ok){let d=t.object({code:t.string(),message:t.string()}).safeParse(a);throw new ve(i.status,d.success?d.data.code:"experiment_request_failed",d.success?d.data.message:"Experiment request failed.")}return a}};function wt(o){return o.policy.kind==="hosted_harness"?{...o,population:o.population.map(({receiptId:e,...n})=>n)}:o}c(wt,"savedRequestPopulation");function St(o,e){return{supportsResume:!e,get:c((...n)=>o.get(...n),"get"),start:e?async()=>{throw new Error("This runtime does not support resuming a stopped guest; start fresh Work with saved outputs")}:(...n)=>o.start(...n),exec:c((n,r)=>o.exec(n,e?{...r,timeoutSeconds:Math.min(r.timeoutSeconds??30,60)}:r),"exec"),mkdir:c((...n)=>o.mkdir(...n),"mkdir"),uploadFile:c((...n)=>o.uploadFile(...n),"uploadFile"),uploadFileBase64:c((...n)=>o.uploadFileBase64(...n),"uploadFileBase64"),listFiles:c((...n)=>o.listFiles(...n),"listFiles"),downloadFileResponse:c((...n)=>o.downloadFileResponse(...n),"downloadFileResponse"),stop:c((...n)=>o.stop(...n),"stop"),delete:c((...n)=>o.delete(...n),"delete"),createWork:c(({requestId:n,repo:r,budgetUsd:s,metadata:i})=>{if(e){if(r?.trim())throw new Error("This runtime does not support repository provisioning; provide Work inputs instead");if(s!==void 0)throw new Error("Hosted spending budgets are not supported by this runtime");let d={resources:e.resources??{cpu:1,memoryGb:2,diskGb:10},...n?{requestId:n}:{}};return o.create(d)}let a=s?.trim()||"1.00";return o.create({...r?.trim()?{repo:r.trim()}:{},runtimeProfileId:"openpond-work-v1",resources:{cpu:2,memoryGb:4,diskGb:16},budget:{maxUsd:a},quotas:{maxSpendUsd:a,maxDurationSeconds:3600,idleTimeoutSeconds:900,maxCommands:200,maxOpenPorts:4},metadata:{source:"openpond-sdk-work",...i,...n?{workRequestId:n}:{}}},{async:!0})},"createWork")}}c(St,"workSandbox");function Ee(o,e){let n=new URL(o);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||n.search||n.hash)throw new Error(`${e} must be an HTTP(S) endpoint without embedded credentials, query or fragment`);return n.toString().replace(/\/$/,"")}c(Ee,"configuredEndpoint");function ie(o,e){if(!o?.trim())throw new Error(`${e} is required`);return o.trim()}c(ie,"configuredKey");var on=t.object({choices:t.array(t.object({message:t.object({content:t.string().nullable().optional(),tool_calls:t.array(t.object({id:t.string().min(1),type:t.literal("function"),function:t.object({name:t.string().min(1),arguments:t.string()})})).optional()})})).min(1)});async function Pt(o,e){if(!e)return xe(o);let n=await fetch(`${o.apiBaseUrl}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${o.token}`,"content-type":"application/json"},body:JSON.stringify({model:o.model,messages:o.messages,tools:o.tools,tool_choice:"auto",stream:!1}),signal:o.signal,redirect:"error"});if(!n.ok)throw new Error(`Configured model request failed (${n.status})`);return on.parse(await n.json())}c(Pt,"workModelTurn");var sn="openpond-chat",an=24,cn=4e4,Ce=2e4,je="outputs",_e="inputs/previous-outputs",vt="inputs/.openpond-context.json",dn=100,kt=100,Rt=100*1024*1024,N=class{static{c(this,"OpenPondWorkClient")}#e;#n;#t;#r;#o;#s;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl,this.#t=e.chatApiBaseUrl,this.#r=St(e.sandboxes,e.sandboxConfig),this.#o=e.defaultModel??sn,this.#s=e.customModel??!1}async run(e){let n=e.prompt.trim();if(!n)throw new Error("Work prompt is required");e.signal?.throwIfAborted();let r=c(async w=>e.onEvent?.(w),"emit"),s=e.cleanup??"keep",i=mn(s),a=null,d=null,x=!1,b=Ot(e.maxSteps,1,100,an),g="";try{await r({type:"status",message:"Preparing sandbox"}),a=await this.#g(e),await r({type:"sandbox",sandboxId:a.id,state:a.state}),await this.#m(a.id,e.inputs??[]),d=await this.#u(a.id);let w=[{role:"system",content:pn(a.id,(e.inputs?.length??0)>0)},...(e.history??[]).map(P=>({...P})),{role:"user",content:n}];for(let P=1;P<=b;P+=1){e.signal?.throwIfAborted(),await r({type:"status",message:`Thinking \xB7 step ${P}`});let qe=(await Pt({apiBaseUrl:this.#t,token:this.#e,model:e.model?.trim()||this.#o,messages:w,tools:ln,toolChoice:"auto",signal:e.signal,metadata:{source:"openpond-sdk-work",sandboxId:a.id,apiBaseUrl:this.#n,...e.metadata}},this.#s)).choices?.[0],Y=qe?.message?.content?.trim()??"",X=qe?.message?.tool_calls??[];if(w.push({role:"assistant",content:Y||null,...X.length>0?{tool_calls:X}:{}}),Y&&(g=Y,await r({type:"assistant",text:Y})),X.length===0){let q=await this.#d(a.id,d);for(let le of q)await r({type:"output",output:le});x=!0,await this.#i(a.id,q,e,i,r);let Q={sandboxId:a.id,text:g,steps:P,outputs:q,lifecycle:i};return await r({type:"done",...Q}),Q}for(let[q,Q]of X.entries()){e.signal?.throwIfAborted();let le=await this.#f(a.id,Q,q,e.timeoutSeconds,r);w.push(le)}}throw new Error(`Work did not finish within ${b} steps`)}catch(w){if(a&&d&&!x)try{let P=await this.#d(a.id,d);for(let Me of P)await r({type:"output",output:Me});await this.#i(a.id,P,e,i,r)}catch(P){It(w,i,P)}throw It(w,i),w}}async deleteSandbox(e){try{if((await this.#r.get(e)).state==="deleted")return;await this.#r.delete(e)}catch(n){if(n instanceof te&&n.status===404)return;throw n}}async#m(e,n){if(n.length===0)return;if(n.length>kt)throw new Error(`Work inputs exceed the ${kt} file limit`);if(n.reduce((a,d)=>a+Buffer.byteLength(d.contentsBase64,"base64"),0)>Rt)throw new Error(`Work inputs exceed the ${Rt} byte limit`);await this.#r.mkdir(e,{path:_e,recursive:!0});let s=new Set,i=[];for(let[a,d]of n.entries()){let x=gn(d,a,s),b=`${_e}/${x}`;await this.#r.uploadFileBase64(e,b,d.contentsBase64),i.push({id:d.id,path:b,name:d.name,mimeType:d.mimeType??null,checksumSha256:d.checksumSha256??null,revision:d.revision??null,metadata:d.metadata??{}})}await this.#r.uploadFile(e,vt,JSON.stringify({version:1,files:i},null,2))}async#i(e,n,r,s,i){if(s.persistence.outputCount=n.length,n.length===0)s.persistence.status="not_needed";else if(r.persistOutput){s.persistence.status="running";for(let a of n){await i({type:"persistence",output:a,status:"started"});try{let d=un(this.#r,e,a);await r.persistOutput({output:a,download:d}),s.persistence.persistedCount+=1,await i({type:"persistence",output:a,status:"succeeded"})}catch(d){let x=D(d);throw s.persistence.status="failed",s.persistence.error=x,await i({type:"persistence",output:a,status:"failed",error:x}),(r.cleanup??"keep")!=="keep"&&await this.#a(e,s,i),d}}s.persistence.status="complete"}else{if((r.cleanup??"keep")==="delete"&&!r.discardOutputs)throw s.persistence.status="failed",s.persistence.error="Deleting a Work sandbox with outputs requires persistOutput or discardOutputs: true",await this.#a(e,s,i),new Error(s.persistence.error);s.persistence.status="not_requested"}await this.#c(e,r.cleanup??"keep",s,i)}async#a(e,n,r){if(this.#r.supportsResume){await this.#c(e,"stop",n,r);return}n.cleanup.status="pending",n.cleanup.finalSandboxState="running",n.cleanup.error="Output persistence must be retried before guest deletion",await r({type:"cleanup",policy:n.cleanupPolicy,status:"pending",sandboxState:"running",error:n.cleanup.error})}async#c(e,n,r,s){if(n!=="keep"){r.cleanup.status="running",await s({type:"cleanup",policy:n,status:"started"});try{let i=n==="delete"?await this.#r.delete(e):(await this.#r.stop(e)).sandbox;r.cleanup.finalSandboxState=i.state,r.cleanup.status=n==="delete"&&i.state==="deleted"||n==="stop"&&i.state==="stopped"?"complete":"pending",await s({type:"cleanup",policy:n,status:r.cleanup.status,sandboxState:i.state})}catch(i){let a=D(i);throw r.cleanup.status="failed",r.cleanup.error=a,await s({type:"cleanup",policy:n,status:"failed",error:a}),i}}}downloadOutput(e,n){return this.#r.downloadFileResponse(e,typeof n=="string"?n:n.path)}async#u(e){return await this.#r.mkdir(e,{path:je,recursive:!0}),fn(await this.#l(e))}async#d(e,n){return(await this.#l(e)).filter(s=>n.get(s.path)!==Et(s)).sort((s,i)=>s.path.localeCompare(i.path)).slice(0,dn).map(hn)}async#l(e){return(await this.#r.listFiles(e,{path:je,recursive:!0,maxEntries:500})).files.filter(r=>r.type==="file"&&!Ct(r.path).includes("/.openpond-"))}async#g(e){if(e.sandboxId){let r=await this.#r.get(e.sandboxId);if(r.state==="stopped")await this.#r.start(r.id,{async:!0});else if(r.state==="deleted"||r.state==="error")throw new Error(`Cannot resume sandbox ${r.id} in state ${r.state}`);return await this.#p(r.id,e.signal)}let n=await this.#r.createWork(e);return this.#p(n.id,e.signal)}async#p(e,n){let r=Date.now()+72e4,s=await this.#r.get(e);for(;Date.now()<r;){if(n?.throwIfAborted(),s.state==="running")return s;if(s.state==="error"||s.state==="deleted")throw new Error(`Sandbox ${s.id} entered ${s.state}${s.logs.length?`: ${s.logs.join(`
3
3
  `)}`:""}`);await wn(2e3,n),s=await this.#r.get(e)}throw new Error(`Sandbox ${e} did not become ready before timeout`)}async#f(e,n,r,s,i){let a=n.id||`work_tool_${r}`,d=n.function?.name;if(d!=="run_command")return M(a,{error:`Unknown tool: ${d??"missing"}`});let x;try{x=JSON.parse(n.function?.arguments||"{}")}catch(g){return M(a,{error:`Invalid tool arguments: ${D(g)}`})}let b=typeof x.command=="string"?x.command.trim():"";if(!b)return M(a,{error:"command is required"});if(b.length>Ce){let g=`command exceeds the ${Ce} character limit`;return await i({type:"tool",toolCallId:a,command:b,status:"failed",output:g}),M(a,{status:"failed",error:g})}await i({type:"tool",toolCallId:a,command:b,status:"started"});try{let g=await this.#r.exec(e,{command:b,timeoutSeconds:Ot(s,1,900,180)}),w=bn(g.command.output,cn),P=g.command.status==="succeeded"?"succeeded":"failed";return await i({type:"tool",toolCallId:a,command:b,status:P,output:w,exitCode:g.command.exitCode}),M(a,{status:g.command.status,exitCode:g.command.exitCode,output:w})}catch(g){if(g instanceof te)throw g;let w=D(g);return await i({type:"tool",toolCallId:a,command:b,status:"failed",output:w}),M(a,{status:"failed",error:w})}}},ln=[{type:"function",function:{name:"run_command",description:"Run a shell command inside the persistent OpenPond sandbox. Use standard shell tools to inspect, edit, build, and test files. Commands start in the repository workspace.",parameters:{type:"object",additionalProperties:!1,properties:{command:{type:"string",minLength:1,maxLength:Ce,description:"Shell command to execute."}},required:["command"]}}}];function pn(o,e){return["You are OpenPond Work, a careful coding agent operating in an isolated Linux sandbox.",`The active sandbox is ${o}.`,...e?[`The authoritative saved files for this turn are staged under /workspace/${_e}; their manifest is /workspace/${vt}.`,"Before revising a previous output, read its staged file and manifest. Copy the staged input into the output directory before editing it; previous output paths may not exist in this sandbox.","Preserve the actual file bytes. Never reconstruct a saved file from the conversation or claim to have preserved it without reading the staged input."]:[],"Use run_command to inspect the workspace, edit files, and validate your work.",`Place completed user-facing files in ${je}. The runtime collects new and revised files there automatically when the turn completes.`,"Do the requested work completely. Preserve existing user changes and avoid destructive commands.","Keep the user informed with concise prose, but call tools whenever verification or file changes are needed.","Before finishing, run relevant tests and summarize the concrete result."].join(`
4
4
  `)}c(pn,"systemPrompt");function mn(o){return{cleanupPolicy:o,persistence:{status:"not_requested",outputCount:0,persistedCount:0},cleanup:{status:"not_requested"}}}c(mn,"initialLifecycle");function un(o,e,n){let r=null;return()=>(r??=o.downloadFileResponse(e,{path:n.path,maxBytes:Math.max(1,n.sizeBytes)}).then(s=>{let i=Buffer.byteLength(s.file.contentsBase64,"base64");if(s.file.truncated||s.file.returnedBytes!==s.file.totalSizeBytes||i!==n.sizeBytes)throw new Error(`Output download was incomplete for ${n.name}`);return s}),r)}c(un,"lazyOutputDownload");function gn(o,e,n){let r=o.id.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,80)||`input-${e+1}`,s=o.name.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(-120)||"file",i=`${r}-${s}`,a=i,d=1;for(;n.has(a);)d+=1,a=`${i}-${d}`;return n.add(a),a}c(gn,"uniqueInputName");function It(o,e,n){!o||typeof o!="object"||Object.assign(o,{workLifecycle:e,...n?{workFinalizationError:D(n)}:{}})}c(It,"attachWorkFailure");function fn(o){return new Map(o.map(e=>[e.path,Et(e)]))}c(fn,"outputSignatures");function Et(o){return`${o.sizeBytes}:${o.updatedAt}`}c(Et,"outputSignature");function hn(o){let e=Ct(o.path).split("/").at(-1)||o.path,n=yn(e);return{path:o.path,name:e,mimeType:n,sizeBytes:o.sizeBytes,updatedAt:o.updatedAt,isBinary:o.isBinary??null,previewable:o.previewable??(n.startsWith("image/")||n==="application/pdf"||n.startsWith("text/"))}}c(hn,"workOutputFromFile");function Ct(o){return o.replaceAll("\\","/")}c(Ct,"normalizedOutputPath");function yn(o){let e=o.toLowerCase().match(/\.[^.]+$/)?.[0]??"";return xn[e]??"application/octet-stream"}c(yn,"workOutputMimeType");var xn=Object.freeze({".avif":"image/avif",".csv":"text/csv",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".gif":"image/gif",".html":"text/html",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".m4a":"audio/mp4",".md":"text/markdown",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".pdf":"application/pdf",".png":"image/png",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".svg":"image/svg+xml",".tsv":"text/tab-separated-values",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".webp":"image/webp",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});function M(o,e){return{role:"tool",tool_call_id:o,content:JSON.stringify(e)}}c(M,"toolMessage");function Ot(o,e,n,r){return Number.isFinite(o)?Math.min(n,Math.max(e,Math.floor(o))):r}c(Ot,"boundedInteger");function bn(o,e){return o.length<=e?o:`${o.slice(0,e)}
5
5
  \u2026 output truncated by openpond-sdk`}c(bn,"truncate");function D(o){return o instanceof Error?o.message:String(o)}c(D,"errorMessage");function wn(o,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason);return}let s=setTimeout(n,o);s.unref?.(),e?.addEventListener("abort",()=>{clearTimeout(s),r(e.reason)},{once:!0})})}c(wn,"sleep");import{promises as jt}from"node:fs";var K=class{static{c(this,"OpenPondProjectActionsClient")}#e;#n;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl.replace(/\/+$/,"")}async list(e){let n=await O(this.#n,this.#e,ae(e.projectId,"releases",e.teamId));return(await v(n,"List Project Action releases")).releases}async catalog(e){let n=await O(this.#n,this.#e,ae(e.projectId,"catalog",e.teamId));return(await v(n,"Get Project Action catalog")).catalog}async publish(e){let[n,r]=await Promise.all([jt.readFile(e.build.bundlePath),jt.readFile(e.build.runnerPath)]),s=await O(this.#n,this.#e,ae(e.projectId,"releases",e.teamId),{method:"POST",body:JSON.stringify({sourceRef:e.sourceRef,sourceCommitSha:e.sourceCommitSha,bundleBase64:n.toString("base64"),runnerBase64:r.toString("base64"),registry:e.build.registry,manifest:e.build.manifest,metadata:e.metadata})});return(await v(s,"Publish Project Actions")).release}async run(e){let n=await O(this.#n,this.#e,ae(e.projectId,`actions/${encodeURIComponent(e.actionId)}`,e.teamId),{method:"POST",body:JSON.stringify({input:e.value??{},releaseId:e.releaseId,idempotencyKey:e.idempotencyKey,callerType:e.callerType??"sdk",callerId:e.callerId}),signal:e.signal,timeoutMs:9e5});return(await v(n,"Run Project Action")).invocation}};function ae(o,e,n){return`/v1/project-actions/${encodeURIComponent(o)}/${e}?teamId=${encodeURIComponent(n)}`}c(ae,"projectActionPath");var J=class{static{c(this,"OpenPondProfileActionsClient")}#e;#n;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl.replace(/\/+$/,"")}async catalog(e){let n=F(e.teamId,"teamId"),r=new URLSearchParams({teamId:n});e.profileId?.trim()&&r.set("profileId",e.profileId.trim()),e.profileName?.trim()&&r.set("profileName",e.profileName.trim());let s=await O(this.#n,this.#e,`/v1/profile/actions?${r.toString()}`);return(await v(s,"Get Profile Action catalog")).catalog}async run(e){let n=F(e.teamId,"teamId"),r=F(e.actionKey,"actionKey"),s=F(e.idempotencyKey,"idempotencyKey"),i=F(e.catalogVersion,"catalogVersion"),a=await O(this.#n,this.#e,`/v1/profile/actions/run?${new URLSearchParams({teamId:n}).toString()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e.profileId?.trim()?{profileId:e.profileId.trim()}:{},...e.profileName?.trim()?{profileName:e.profileName.trim()}:{},actionKey:r,value:e.value??{},conversationId:e.conversationId??null,createConversation:e.createConversation,conversationTitle:e.conversationTitle??null,idempotencyKey:s,catalogVersion:i,externalCapabilityLeases:e.externalCapabilityLeases})});return v(a,"Run Profile Action")}};function F(o,e){let n=o.trim();if(!n)throw new Error(`${e} is required`);return n}c(F,"requiredValue");import{randomUUID as _t}from"node:crypto";var G=class{static{c(this,"OpenPondWorkflowsClient")}#e;#n;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl.replace(/\/+$/,"")}async list(e={}){return this.#t("","List Workflows",{signal:e.signal})}async create(e,n={}){return this.#t("","Create Workflow",{method:"POST",body:JSON.stringify({...e,clientRequestId:e.clientRequestId?.trim()||_t()}),signal:n.signal})}async update(e,n,r={}){return this.#t(`/schedules/${encodeURIComponent(Ae(e,"scheduleId"))}`,"Update Workflow",{method:"PATCH",body:JSON.stringify(n),signal:r.signal})}async delete(e,n={}){return this.#t(`/schedules/${encodeURIComponent(Ae(e,"scheduleId"))}`,"Delete Workflow",{method:"DELETE",signal:n.signal})}async runNow(e,n={},r={}){return this.#t(`/schedules/${encodeURIComponent(Ae(e,"scheduleId"))}/run`,"Run Workflow",{method:"POST",body:JSON.stringify({clientRequestId:n.clientRequestId?.trim()||_t()}),signal:r.signal})}async#t(e,n,r={}){let s=await O(this.#n,this.#e,`/v1/saved-work${e}`,r);return v(s,n)}};function Ae(o,e){let n=o.trim();if(!n)throw new Error(`${e} is required`);return n}c(Ae,"requiredId");var ce=t.object({id:h,scope:h,sourceId:h,name:t.string().trim().min(1).max(100),keyPrefix:t.string().min(1).max(100),createdAt:t.iso.datetime(),expiresAt:t.iso.datetime(),revokedAt:t.iso.datetime().nullable()}).strict(),At=t.string().regex(/^opk_key_[A-Za-z0-9]{16}_[A-Za-z0-9]{48}$/),de=t.discriminatedUnion("action",[t.object({action:t.literal("create"),scope:h,sourceId:h,name:t.string().trim().min(1).max(100),expiresAt:t.iso.datetime(),operationId:h,apiKey:At}).strict(),t.object({action:t.literal("list"),scope:h,sourceId:h,afterId:h.optional(),limit:t.number().int().min(1).max(100).default(30)}).strict(),t.object({action:t.literal("revoke"),scope:h,sourceId:h,id:h}).strict()]),Tt=t.object({credential:ce,apiKey:At}).strict(),Mt=t.object({items:t.array(ce).max(100),nextCursor:h.nullable()}).strict(),qt=t.object({scope:h,sourceId:h}).strict(),Lt=t.object({scope:h,source:ue,taskDefinition:ue,enabled:t.boolean(),allowedSplits:t.array(We).min(1).max(4)}).strict();var Sn=t.object({batchId:t.string().trim().min(1).max(500),modelProjectId:t.string().trim().min(1).max(500)}).strict(),Pn=t.object({batchId:t.string().min(1),projectId:t.string().min(1),tasksetId:t.string().min(1),releaseId:t.string().min(1),revision:t.number().int().positive(),contentHash:t.string().regex(/^[a-f0-9]{64}$/)}).strict(),y=class extends Error{constructor(n,r,s,i){super(s);this.status=n;this.code=r;this.details=i;this.name="OpenPondLearningError"}status;code;details;static{c(this,"OpenPondLearningError")}},V=class{static{c(this,"OpenPondLearningClient")}#e;constructor(e){if(!e.apiKey.trim()||!e.scope.trim())throw new Error("Learning API key and scope are required.");let n=new URL(e.baseUrl);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||n.search||n.hash)throw new Error("Learning base URL must be an HTTP(S) endpoint without credentials, query, or fragment.");this.#e={...e,baseUrl:n.toString().replace(/\/+$/,"")}}async command(e,n={}){Fe(e);let r=Je.parse({scope:this.#e.scope,command:e}),s=Ve.parse(await this.#t("commands",r,n));if(s.operationId!==e.operationId)throw new y(502,"operation_identity_mismatch","Learning response did not match the submitted operation.",null);return s}submitExample(e,n={}){return this.command({action:"submit_example",operationId:e.idempotencyKey,example:e},n)}submitFeedback(e,n={}){return this.command({action:"submit_feedback",operationId:e.idempotencyKey,feedback:e},n)}async get(e,n,r,s={}){let i=A.parse({action:"get",scope:this.#e.scope,kind:e,id:n,...r===void 0?{}:{revision:r}});return fe[e].parse(await this.#t("read",i,s))}async inspectEvidence(e,n={}){let r=A.parse({action:"inspect_evidence",scope:this.#e.scope,evidence:e}),s=Ge.parse(await this.#t("read",r,n));if(!ge(s.evidence,e))throw new y(502,"evidence_identity_mismatch","Inspection did not match the requested evidence release.",null);return s}async inspectTaskQueue(e=null,n={}){let r=A.parse({action:"inspect_task_queue",scope:this.#e.scope,modelProjectId:e}),s=Ke.parse(await this.#t("read",r,n));if(s.modelProjectId!==e)throw new y(502,"model_identity_mismatch","Task queue did not match the requested Model.",null);return s}async inspectPolicy(e,n={}){let r=A.parse({action:"inspect_policy",scope:this.#e.scope,policy:e}),s=Ne.parse(await this.#t("read",r,n));if(!ge(s.policy,e))throw new y(502,"policy_identity_mismatch","Inspection did not match the requested policy release.",null);return s}async createSourceCredential(e,n={}){let r=de.parse({...e,action:"create",scope:this.#e.scope}),s=Tt.parse(await this.#t("credentials",r,n));if(this.#n(s.credential,e.sourceId),s.apiKey!==e.apiKey||!e.apiKey.startsWith(`${s.credential.keyPrefix}_`))throw new y(502,"credential_identity_mismatch","Credential response did not match the prepared credential.",null);return s}async listSourceCredentials(e,n={},r={}){let s=de.parse({...n,action:"list",scope:this.#e.scope,sourceId:e}),i=Mt.parse(await this.#t("credentials",s,r));if(i.items.length>(n.limit??30))throw new y(502,"credential_page_invalid","Credential response exceeded the requested page size.",null);for(let a of i.items)this.#n(a,e);return i}async revokeSourceCredential(e,n,r={}){let s=de.parse({action:"revoke",scope:this.#e.scope,sourceId:e,id:n}),i=ce.parse(await this.#t("credentials",s,r));if(this.#n(i,e),i.id!==n||i.revokedAt===null)throw new y(502,"credential_revocation_mismatch","Credential revocation did not match the requested credential.",null);return i}async sourceConfiguration(e,n={}){let r=qt.parse({scope:this.#e.scope,sourceId:e}),s=Lt.parse(await this.#t("source-config",r,n));if(s.scope!==this.#e.scope||s.source.id!==e)throw new y(502,"source_identity_mismatch","Source configuration did not match the requested source.",null);return s}#n(e,n){if(e.scope!==this.#e.scope||e.sourceId!==n)throw new y(502,"credential_scope_mismatch","Credential response did not match the requested source.",null)}async list(e,n={},r={}){let s=A.parse({action:"list",scope:this.#e.scope,kind:e,...n});return t.object({items:t.array(fe[e]).max(100),nextCursor:t.string().nullable()}).strict().parse(await this.#t("read",s,r))}async publishBatch(e,n={}){let r=Sn.parse(e),s=Pn.parse(await this.#t("publish-batch",{...r,scope:this.#e.scope},n));if(s.batchId!==r.batchId)throw new y(502,"batch_identity_mismatch","Published batch response did not match the requested batch.",null);return s}async#t(e,n,r){me(n,16777216);let s=await(this.#e.fetch??globalThis.fetch)(`${this.#e.baseUrl}/v1/learning/${e}`,{method:"POST",headers:{Authorization:`Bearer ${this.#e.apiKey}`,"Content-Type":"application/json",Accept:"application/json","X-OpenPond-Team-Id":this.#e.scope},body:JSON.stringify(n),signal:r.signal,redirect:"error"}),i=await kn(s);if(!s.ok){let a=t.object({code:t.string().optional(),error:t.string().optional()}).passthrough().safeParse(i);throw new y(s.status,a.success?a.data.code??"learning_request_failed":"learning_request_failed",a.success?a.data.error??`Learning request failed (${s.status}).`:`Learning request failed (${s.status}).`,i)}return i}};async function kn(o){let n=o.body?.getReader();if(!n)throw new y(o.status,"empty_response","Learning response was empty.",null);let r=new TextDecoder,s=0,i="";try{for(;;){let d=await n.read();if(d.done)break;if(s+=d.value.byteLength,s>16777216)throw new y(o.status,"response_too_large","Learning response exceeded 16 MiB; request a smaller page.",null);i+=r.decode(d.value,{stream:!0})}i+=r.decode();let a=JSON.parse(i);return me(a,16777216),a}finally{await n.cancel(),n.releaseLock()}}c(kn,"readBoundedLearningResponse");var Te=class{static{c(this,"OpenPondClient")}sandboxes;work;workflows;actions;profileActions;learning;experiments;constructor(e){let n=e.apiKey?.trim()??"";if(!n&&(!e.sandbox||!e.model))throw new Error("OpenPond API key is required when using a default sandbox or model");let r=e.sandbox?{...e.sandbox,endpoint:Ee(e.sandbox.endpoint,"Sandbox endpoint"),apiKey:ie(e.sandbox.apiKey,"Sandbox API key")}:void 0,s=e.model?{endpoint:Ee(e.model.endpoint,"Model endpoint"),apiKey:ie(e.model.apiKey,"Model API key"),model:ie(e.model.model,"Model ID")}:void 0,i=e.baseUrl?.trim()||"https://api.openpond.ai";this.learning=a=>new V({apiKey:n,baseUrl:i,scope:a}),this.experiments=a=>new se({apiKey:n,baseUrl:i,teamId:a}),this.sandboxes=et({apiKey:r?.apiKey??n,baseUrl:i,sandboxApiUrl:r?.endpoint??e.sandboxApiUrl,customEndpoint:!!r}),this.work=new N({apiKey:s?.apiKey??n,apiBaseUrl:i,chatApiBaseUrl:s?.endpoint||e.chatApiUrl?.trim()||ye({apiBaseUrl:i,env:{}}),sandboxes:this.sandboxes,sandboxConfig:r,defaultModel:s?.model,customModel:!!s}),this.workflows=new G({apiKey:n,apiBaseUrl:i}),this.actions=new K({apiKey:n,apiBaseUrl:i}),this.profileActions=new J({apiKey:n,apiBaseUrl:i})}};function us(o){return new Te(o)}c(us,"createOpenPondClient");export{f as a,_ as b,R as c,L as d,$t as e,ut as f,gt as g,ht as h,Ie as i,Oe as j,se as k,us as l};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{b as Re,c as Ie,e as X,j as Ee,k as ke,l as Oe,m as Ae}from"./chunk-5OA57RW4.js";import{i as Pe,o as xe,q as Ce}from"./chunk-ASRSYRE3.js";import{E as v,I as Te}from"./chunk-PKBU37CH.js";import{a as K,b as Se,h as ye}from"./chunk-H7YH35JO.js";import{Cd as O,Fd as j,Gd as re,I as k,J as te,M as N,N as H,a as F}from"./chunk-JIG7KQOX.js";import{$a as L,Ra as me,Sa as ge,Ua as Y,X as oe,Xa as he,Y as ie,_a as fe,db as ve,fb as we,gb as be,ja as ae,la as ue,ma as le,na as ce,oa as pe,qa as de,v as _}from"./chunk-QK2GLRCY.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as ne,d as q,f as se,h as M}from"./chunk-H7IWJN7L.js";import{a as u}from"./chunk-FTQLQJQV.js";import{promises as Q}from"node:fs";import it from"node:os";import at from"node:path";import{createServer as ut}from"node:http";import{randomBytes as lt}from"node:crypto";var Qe=o.discriminatedUnion("op",[o.strictObject({op:o.literal("set"),path:o.array(o.string().min(1)).min(1),value:o.unknown()}),o.strictObject({op:o.literal("unset"),path:o.array(o.string().min(1)).min(1)})]),et=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(Qe).max(100)}),o.strictObject({action:o.literal("replace"),expectedRevision:o.string(),text:o.string().max(1048576)}),o.strictObject({action:o.literal("validate"),text:o.string().max(1048576)}),o.strictObject({action:o.literal("restore"),expectedRevision:o.string(),revision:o.string()}),o.strictObject({action:o.literal("trust"),root:o.string(),accountId:o.string(),trusted:o.boolean()}),o.strictObject({action:o.literal("client-state"),owner:o.string(),patch:ve,importOnly:o.boolean().optional()})]);function _e(n){let e=null;async function t(s,i){let a=M(n).config,l=null,c=null,p=null;try{l=await ie(a),p=await L(n,{projectRoot:s,accountId:i}),s||(e=p)}catch(b){c=q(b,a)}let h=p??(s?null:e);return{path:a,text:l,rawRevision:oe(l),issue:c,effective:h,usingLastValid:!p&&!!h,applies:"next_turn",recoverableRevisions:await ue(n),clientState:c?null:await we(n)}}u(t,"status");async function r(s){let i=et.parse(s);return i.action==="validate"?{valid:!0,document:ae(i.text,M(n).config)}:(i.action==="patch"&&await de(n,i.expectedRevision,i.operations),i.action==="replace"&&await le(n,i.expectedRevision,i.text),i.action==="restore"&&await ce(n,i.revision,i.expectedRevision),i.action==="trust"&&await fe(n,i.root,i.accountId,i.trusted),i.action==="client-state"?be(n,i.owner,i.patch,i.importOnly):t())}return u(r,"mutate"),{status:t,mutate:r,schema:pe}}u(_e,"createConfigurationPayloads");import{Buffer as He}from"node:buffer";var V={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},tt=25*1024*1024,B=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{u(this,"HttpBodyError")}};function Ue(n,e,t={}){for(let[s,i]of Object.entries(V))e.setHeader(s,i);let r=qe(n.headers.origin);return r?(e.setHeader("Vary",ot(e.getHeader("Vary"))),rt(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}u(Ue,"applyCorsHeaders");function rt(n,e={}){if(n==="null")return!0;let t=Me(n);return t?st(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Me(s):null).filter(s=>!!s)).has(t):!1}u(rt,"isAllowedCorsOrigin");function I(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...V}),n.end(JSON.stringify(t))}u(I,"sendJson");function Ft(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...V}),n.end(t)}u(Ft,"sendText");function jt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...V}),n.end(t)}u(jt,"sendBinary");async function Z(n,e={}){let t=e.maxBytes??tt,r=qe(n.headers["content-type"]),s=[],i=0;for await(let l of n){let c=He.from(l);if(i+=c.byteLength,i>t)throw new B(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(c)}let a=He.concat(s).toString("utf8").trim();if(!a)return{};if(!nt(r))throw new B(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(a)}catch{throw new B(400,"invalid_json","Request body is not valid JSON.")}}u(Z,"readJson");function Ne(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}u(Ne,"hasAuth");function qe(n){return Array.isArray(n)?n[0]??null:n??null}u(qe,"headerValue");function nt(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}u(nt,"isJsonContentType");function Me(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}u(Me,"normalizeOrigin");function st(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}u(st,"isLoopbackOrigin");function ot(n){let t=(Array.isArray(n)?n.join(", "):n?String(n):"").split(",").map(r=>r.trim()).filter(Boolean);return t.some(r=>r.toLowerCase()==="origin")||t.push("Origin"),t.join(", ")}u(ot,"appendVaryOrigin");function Be(n){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
2
+ import{b as Re,c as Ie,e as X,j as Ee,k as ke,n as Oe,o as Ae}from"./chunk-DLQW5X6F.js";import{E as v,I as Te}from"./chunk-PKBU37CH.js";import{i as Pe,o as xe,q as Ce}from"./chunk-GKP2ZPKM.js";import{a as K,b as Se,h as ye}from"./chunk-H7JB25HO.js";import{Cd as O,Fd as j,Gd as re,I as k,J as te,M as N,N as H,a as F}from"./chunk-HLNJKX3S.js";import{X as me,Y as ge,_ as Y,b as oe,ba as he,c as ie,ea as fe,fa as L,ja as ve,la as we,ma as be,p as ae,r as ue,s as le,t as ce,u as pe,w as de}from"./chunk-ALZRXBEC.js";import{y as _}from"./chunk-MTJNKRXL.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as ne,d as q,f as se,h as M}from"./chunk-H7IWJN7L.js";import{a as u}from"./chunk-FTQLQJQV.js";import{promises as Q}from"node:fs";import it from"node:os";import at from"node:path";import{createServer as ut}from"node:http";import{randomBytes as lt}from"node:crypto";var Qe=o.discriminatedUnion("op",[o.strictObject({op:o.literal("set"),path:o.array(o.string().min(1)).min(1),value:o.unknown()}),o.strictObject({op:o.literal("unset"),path:o.array(o.string().min(1)).min(1)})]),et=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(Qe).max(100)}),o.strictObject({action:o.literal("replace"),expectedRevision:o.string(),text:o.string().max(1048576)}),o.strictObject({action:o.literal("validate"),text:o.string().max(1048576)}),o.strictObject({action:o.literal("restore"),expectedRevision:o.string(),revision:o.string()}),o.strictObject({action:o.literal("trust"),root:o.string(),accountId:o.string(),trusted:o.boolean()}),o.strictObject({action:o.literal("client-state"),owner:o.string(),patch:ve,importOnly:o.boolean().optional()})]);function _e(n){let e=null;async function t(s,i){let a=M(n).config,l=null,c=null,p=null;try{l=await ie(a),p=await L(n,{projectRoot:s,accountId:i}),s||(e=p)}catch(b){c=q(b,a)}let h=p??(s?null:e);return{path:a,text:l,rawRevision:oe(l),issue:c,effective:h,usingLastValid:!p&&!!h,applies:"next_turn",recoverableRevisions:await ue(n),clientState:c?null:await we(n)}}u(t,"status");async function r(s){let i=et.parse(s);return i.action==="validate"?{valid:!0,document:ae(i.text,M(n).config)}:(i.action==="patch"&&await de(n,i.expectedRevision,i.operations),i.action==="replace"&&await le(n,i.expectedRevision,i.text),i.action==="restore"&&await ce(n,i.revision,i.expectedRevision),i.action==="trust"&&await fe(n,i.root,i.accountId,i.trusted),i.action==="client-state"?be(n,i.owner,i.patch,i.importOnly):t())}return u(r,"mutate"),{status:t,mutate:r,schema:pe}}u(_e,"createConfigurationPayloads");import{Buffer as He}from"node:buffer";var V={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},tt=25*1024*1024,B=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{u(this,"HttpBodyError")}};function Ue(n,e,t={}){for(let[s,i]of Object.entries(V))e.setHeader(s,i);let r=qe(n.headers.origin);return r?(e.setHeader("Vary",ot(e.getHeader("Vary"))),rt(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}u(Ue,"applyCorsHeaders");function rt(n,e={}){if(n==="null")return!0;let t=Me(n);return t?st(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Me(s):null).filter(s=>!!s)).has(t):!1}u(rt,"isAllowedCorsOrigin");function I(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...V}),n.end(JSON.stringify(t))}u(I,"sendJson");function Ft(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...V}),n.end(t)}u(Ft,"sendText");function jt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...V}),n.end(t)}u(jt,"sendBinary");async function Z(n,e={}){let t=e.maxBytes??tt,r=qe(n.headers["content-type"]),s=[],i=0;for await(let l of n){let c=He.from(l);if(i+=c.byteLength,i>t)throw new B(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(c)}let a=He.concat(s).toString("utf8").trim();if(!a)return{};if(!nt(r))throw new B(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(a)}catch{throw new B(400,"invalid_json","Request body is not valid JSON.")}}u(Z,"readJson");function Ne(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}u(Ne,"hasAuth");function qe(n){return Array.isArray(n)?n[0]??null:n??null}u(qe,"headerValue");function nt(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}u(nt,"isJsonContentType");function Me(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}u(Me,"normalizeOrigin");function st(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}u(st,"isLoopbackOrigin");function ot(n){let t=(Array.isArray(n)?n.join(", "):n?String(n):"").split(",").map(r=>r.trim()).filter(Boolean);return t.some(r=>r.toLowerCase()==="origin")||t.push("Origin"),t.join(", ")}u(ot,"appendVaryOrigin");function Be(n){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
3
3
  <style nonce="${n}">body{font:16px system-ui;background:#171819;color:#eee;max-width:850px;margin:6vh auto;padding:24px}textarea{box-sizing:border-box;width:100%;min-height:280px;background:#222;color:#eee;padding:14px;border:1px solid #777;border-radius:8px;font:14px monospace}button,input,select{font:inherit;margin:6px;padding:8px}pre{white-space:pre-wrap}code{overflow-wrap:anywhere}button{cursor:pointer}p{line-height:1.5}</style>
4
4
  <h1>OpenPond needs a storage repair</h1><p id="issue" role="alert">Loading recovery details\u2026</p><p><code id="file"></code></p>
5
5
  <p id="action"></p><p>Migration backups and the source installation remain available. Execution services are stopped while recovery is open.</p>
@@ -20,7 +20,7 @@ for(const [id,action] of [['preview','preview'],['migrate','migrate'],['restart'
20
20
  el('diagnostics').onclick=()=>{if(!state)return;const blob=new Blob([JSON.stringify({issue:state.issue,migration:state.migration,config:{path:state.config.path,rawRevision:state.config.rawRevision,issue:state.config.issue}},null,2)],{type:'application/json'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='openpond-recovery-diagnostics.json';a.click();URL.revokeObjectURL(a.href)};
21
21
  el('retry').onclick=async()=>{try{await request('/v1/recovery',{action:'retry'});message('Starting OpenPond\u2026');const timer=setInterval(async()=>{try{const h=await(await fetch('/health')).json();if(!h.recovery){clearInterval(timer);const next=new URLSearchParams(location.hash.slice(1)).get('returnTo');if(next){const u=new URL(next);if(['localhost','127.0.0.1','[::1]'].includes(u.hostname)){location.replace(u.toString());return}}location.reload();}}catch{}},500)}catch(e){message(e)}};
22
22
  (async()=>{const params=new URLSearchParams(location.hash.slice(1));token=params.get('openpondToken')||'';if(!token&&window.openpond?.getConnection)token=(await window.openpond.getConnection()).token;if(!token){message('Open the authenticated recovery URL from the launcher.');return}await load()})().catch(message);
23
- </script></html>`}u(Be,"startupRecoveryPage");var ct=o.strictObject({action:o.enum(["preview","migrate","restart","retry"]),sourceAppHome:o.string().optional(),sourceConfig:o.string().optional(),resolutions:me.optional()});function De(n){return n instanceof ne&&/^(PRIVATE_STORAGE_|UNSAFE_STORAGE_|INVALID_CONFIG|CONFIG_|MIGRATION_|SOURCE_CHANGED_|CREDENTIAL_|UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|INVALID_ACCOUNT_|MISSING_INSTRUCTION_|INVALID_PROFILE_|DATABASE_RECOVERY_)/.test(n.issue.code)}u(De,"isRecoverableStartupError");async function Fe(n,e,t){let r=/^(UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|UNSAFE_STORAGE_|PRIVATE_STORAGE_)/.test(t.issue.code),s=r?await Q.mkdtemp(at.join(it.tmpdir(),"openpond-recovery-")):n;return Re(s,async()=>{let{token:i,tokenFile:a}=await Ee(s),l=_e(n),c=t.issue,p,h=new Promise(f=>{p=f}),b=ut((f,g)=>{(async()=>{let S=new URL(f.url??"/","http://127.0.0.1");if(!Ue(f,g).allowed){I(g,403,{error:"Origin not allowed"});return}if(f.method==="OPTIONS"){I(g,204,{});return}if(f.method==="GET"&&S.pathname==="/health"){I(g,200,{ok:!0,server:"openpond-app-server",version:Se,recovery:!0});return}if(f.method==="GET"&&S.pathname==="/"){let w=lt(18).toString("base64");g.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${w}'; style-src 'nonce-${w}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`}),g.end(Be(w));return}if(!Ne(f,S,i)){I(g,401,{error:"Unauthorized"});return}let P=!r;if(f.method==="GET"&&S.pathname==="/v1/recovery"){I(g,200,{issue:c,configEditable:P,config:r?{path:M(n).config,text:null,rawRevision:"unavailable",issue:c,recoverableRevisions:[]}:await l.status(),migration:await ge(n).catch(w=>({issue:q(w,n)}))});return}if(f.method==="POST"&&S.pathname==="/v1/configuration"&&P){I(g,200,await l.mutate(await Z(f)));return}if(f.method==="POST"&&S.pathname==="/v1/recovery"){let w=ct.parse(await Z(f));if(r&&w.action!=="retry"&&w.action!=="preview")throw t;if(w.action==="restart"){I(g,200,await he(n));return}if(w.action==="preview"||w.action==="migrate"){I(g,200,await Y(n,{sourceAppHome:w.sourceAppHome,sourceConfig:w.sourceConfig,resolutions:w.resolutions,dryRun:w.action==="preview"}));return}await Y(n),await L(n),I(g,200,{ready:!0}),p();return}I(g,503,{error:`${c.message} ${c.action}`,issue:c,recovery:!0})})().catch(S=>{c=q(S,n),I(g,422,{error:`${c.message} ${c.action}`,issue:c})})});await new Promise((f,g)=>{b.once("error",g),b.listen(e,"127.0.0.1",()=>{b.off("error",g),f()})});let x=b.address().port,A=`http://127.0.0.1:${x}`;return await Ie(s,A,"startup-recovery"),{url:A,port:x,token:i,tokenFile:a,storePath:M(n).database,repaired:h,close:u(async()=>{b.closeIdleConnections(),await new Promise((f,g)=>b.close(S=>S?g(S):f())),r&&await Q.rm(s,{recursive:!0,force:!0})},"close")}}).catch(async i=>{throw r&&await Q.rm(s,{recursive:!0,force:!0}),i})}u(Fe,"startRecoveryServer");import{createHash as Ct}from"node:crypto";import{createHash as pt,randomUUID as je}from"node:crypto";var dt=o.object({updatedAt:o.string(),id:o.string().min(1)}).strict(),mt=o.object({entries:o.array(k).max(200),nextBefore:dt.nullable()}).strict(),gt=o.object({run:k,replayed:o.boolean()}).strict(),$=class{constructor(e){this.client=e}client;static{u(this,"HostedCreateImproveStorage")}async getCreateImproveRun(e){let t=await this.client.request({contractVersion:v,requestId:je(),operation:"create-improve/execute",params:{action:"get",runId:e}});return t===null?null:k.parse(t)}async listCreateImproveRuns(e={}){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250))),r=Array.isArray(e.state)?[...e.state]:e.state?[e.state]:[],s=[],i=null;for(;s.length<t;){let a=mt.parse(await this.client.request({contractVersion:v,requestId:je(),operation:"create-improve/execute",params:{action:"page",query:{profileId:e.profileId??null,targetKind:e.targetKind??null,targetId:e.targetId??null,state:r},before:i,limit:Math.min(50,t-s.length)}}));if(e.conversationId&&a.entries.some(l=>l.scope.conversationId!==e.conversationId))throw new Error("Hosted Create/Improve page crossed its conversation scope.");if(s.push(...a.entries),!a.nextBefore)break;if(a.entries.length===0||i&&(a.nextBefore.updatedAt>i.updatedAt||a.nextBefore.updatedAt===i.updatedAt&&a.nextBefore.id>=i.id))throw new Error("Hosted Create/Improve cursor did not advance.");i=a.nextBefore}return s}async upsertCreateImproveRun(e){let t=k.parse(e),r=`create-improve:${pt("sha256").update(JSON.stringify(t)).digest("hex")}`,s=await this.client.request({contractVersion:v,requestId:r,operation:"create-improve/execute",params:{action:"put",run:t}});return k.parse(o.object({run:o.unknown()}).strict().parse(s).run)}async mutateCreateImproveRun(e,t){let r=te.parse(e),s=await this.getCreateImproveRun(r.runId);if(!s)throw new Error(`Create/Improve run not found: ${r.runId}`);if(s.appliedActionIds.includes(r.actionId))return{run:s,replayed:!0};if(s.revision!==r.expectedRevision)throw new Error(`Create/Improve run changed from revision ${r.expectedRevision} to ${s.revision}. Refresh and try again.`);let i=k.parse(t(s));if(i.id!==s.id||i.revision!==s.revision+1||!i.appliedActionIds.includes(r.actionId))throw new Error("Create/Improve mutation must preserve identity, advance one revision and record its action.");return gt.parse(await this.client.request({contractVersion:v,requestId:r.actionId,operation:"create-improve/execute",params:{action:"mutate",mutation:r,next:i}}))}};import{randomUUID as ft}from"node:crypto";async function D(n,e){let t=n;for(;;)try{return await e(t)}catch(r){if(!ht(r)||t<=1)throw r;t=Math.max(1,Math.floor(t/2))}}u(D,"hostedBoundedPage");function ht(n){return n instanceof Error?n.message==="Host storage response is too large."||n.message==="Host storage request failed: host_storage_response_too_large":!1}u(ht,"isOversizeResponse");var vt=o.object({entries:o.array(o.object({sequence:o.number().int().positive(),event:F})).max(200),totalMatchingEvents:o.number().int().nonnegative(),remainingMatchingEvents:o.number().int().nonnegative()}).strict(),W=class{constructor(e){this.client=e}client;static{u(this,"HostedRuntimeEventStorage")}async runtimeEventsForSession(e,t={}){let r=t.limit==null?1e4:Math.max(0,Math.trunc(t.limit));if(r===0)return[];let s=Math.min(r,1e4),i=[],a=Math.max(0,t.afterSequence??0),l=0,c=t.names?new Set(t.names):null;for(;i.length<=s;){let p=await this.runtimeEventPageRows({sessionId:e,afterSequence:a,beforeSequence:null,limit:Math.min(200,s+1-i.length),excludeReasoningDeltas:t.excludeReasoningDeltas});for(let h of p.entries){if(h.sequence<=a)throw new Error("Host event cursor did not advance.");if(a=h.sequence,l+=1,l>1e4)throw new Error("Hosted runtime event scan exceeds 10,000 rows; use a narrower query.");(!c||c.has(h.event.name))&&i.push(h.event)}if(p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break}if(i.length>s||t.limit==null&&r===1e4&&i.length===s)throw new Error("Hosted runtime event read exceeds 10,000 rows; use a bounded cursor query.");return i}async persistedRuntimeEventsForSession(e,t={}){return this.runtimeEventsForSession(e,t)}async appendRuntimeEvent(e){let t=F.parse(e),r=await this.client.request({contractVersion:v,requestId:t.id,operation:"event/append",params:{event:t}});return o.object({event:F}).strict().parse(r).event}async runtimeEventPageRows(e){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit))),r=Math.max(0,Math.trunc(e.afterSequence)),s=e.beforeSequence,i=[],a=0,l=0;for(;i.length<t;){let c=Math.min(200,t-i.length),p=await D(c,async h=>vt.parse(await this.client.request({contractVersion:v,requestId:`event-page:${ft()}`,operation:"events/page",params:{sessionId:e.sessionId,afterSequence:r,beforeSequence:s,limit:h,...e.excludeReasoningDeltas?{excludeReasoningDeltas:!0}:{}}})));if(i.length===0&&(a=p.totalMatchingEvents,l=p.remainingMatchingEvents),i=s===null?[...i,...p.entries]:[...p.entries,...i],p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break;if(s===null){let h=p.entries.at(-1).sequence;if(h<=r)throw new Error("Host event cursor did not advance.");r=h}else{let h=p.entries[0].sequence;if(h>=s)throw new Error("Host event cursor did not advance.");s=h}}return{entries:i,totalMatchingEvents:a,remainingMatchingEvents:l}}};import{randomUUID as y}from"node:crypto";var Le=o.object({revision:o.number().int().min(1),session:N}).strict(),Ve=o.object({revision:o.number().int().min(1),turn:H}).strict(),wt=o.object({sessions:o.array(N).max(200),nextAfterId:o.string().min(1).nullable()}).strict(),bt=o.object({turns:o.array(H).max(200),nextBeforeSortIndex:o.number().int().nonnegative().nullable()}).strict(),G=class{constructor(e){this.client=e}client;static{u(this,"HostedSessionStorage")}async count(){let e=await this.client.request({contractVersion:v,requestId:y(),operation:"session/count",params:{}});return o.object({count:o.number().int().nonnegative()}).strict().parse(e).count}async get(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"session/get",params:{sessionId:e}});return t===null?null:Le.parse(t)}async sessionCount(){return this.count()}async sessionShells(){let e=[],t=null;do{let r=await D(Math.min(10,1001-e.length),async s=>wt.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"session/page",params:{afterId:t,limit:s}})));if(e.push(...r.sessions),e.length>1e3)throw new Error("Hosted session list exceeds 1,000 rows; use a scoped page query.");if(r.nextAfterId!==null&&(r.sessions.length===0||t!==null&&r.nextAfterId<=t))throw new Error("Host session cursor did not advance.");t=r.nextAfterId}while(t!==null);return e}async getSession(e){return(await this.get(e))?.session??null}async insertSessionAtFront(e){await this.put({session:e,expectedRevision:null,requestId:y()})}async updateSession(e,t){let r=await this.get(e);if(!r)return null;let s=N.parse(t(r.session));if(s.id!==e)throw new Error("A session update cannot change its identity.");return(await this.put({session:s,expectedRevision:r.revision,requestId:y()})).session}async put(e){let t=N.parse(e.session);return Le.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"session/put",params:{sessionId:t.id,expectedRevision:e.expectedRevision,session:t}}))}async readTurn(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/get",params:{turnId:e}});return t===null?null:Ve.parse(t)}async getTurn(e){return(await this.readTurn(e))?.turn??null}async turnsForSession(e,t=50){let r=Math.max(1,Math.min(1e3,Math.trunc(t))),s=[],i=null;for(;s.length<r;){let a=await D(Math.min(200,r-s.length),async l=>bt.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"turn/page",params:{sessionId:e,beforeSortIndex:i,limit:l}})));if(s.push(...a.turns),a.nextBeforeSortIndex===null)break;if(i!==null&&a.nextBeforeSortIndex>=i)throw new Error("Host turn cursor did not advance.");i=a.nextBeforeSortIndex}return s}async countTurnsForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/count",params:{sessionId:e}});return o.object({count:o.number().int().nonnegative()}).strict().parse(t).count}async hasSubagentParentWakeTurn(e,t){return await this.wakeCount(e,"messageId",t)>0}async countSubagentParentWakeTurns(e,t){return this.wakeCount(e,"fromRunId",t)}async latestAssistantTextForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"events/latestAssistantText",params:{sessionId:e}});return o.object({text:o.string().nullable()}).strict().parse(t).text}async wakeCount(e,t,r){let s=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/wakeCount",params:{sessionId:e,key:t,value:r}});return o.object({count:o.number().int().nonnegative()}).strict().parse(s).count}async latestTurnForSession(e,t){let r=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/latest",params:{sessionId:e,status:t??null}});return r===null?null:H.parse(r)}async latestPersistedTurnForSession(e,t){return this.latestTurnForSession(e,t)}async insertTurn(e){await this.putTurn({turn:e,expectedRevision:null,requestId:y()})}async updateTurn(e,t){let r=await this.readTurn(e);if(!r)return null;let s=H.parse(t(r.turn));if(s.id!==e||s.sessionId!==r.turn.sessionId)throw new Error("A turn update cannot change its identity.");return(await this.putTurn({turn:s,expectedRevision:r.revision,requestId:y()})).turn}async putTurn(e){let t=H.parse(e.turn);return Ve.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"turn/put",params:{sessionId:t.sessionId,turnId:t.id,expectedRevision:e.expectedRevision,turn:t}}))}};import{createHash as St,randomUUID as yt}from"node:crypto";var C=o.object({ok:o.literal(!0)}).strict(),J=o.array(O),Rt=o.array(o.string()),It=o.object({turnId:o.string(),run:_}).strict(),Tt=o.object({inputs:o.array(O).max(10),hasMore:o.boolean()}).strict(),Pt=o.object({items:o.array(j).max(10),hasMore:o.boolean()}).strict(),xt=o.object({items:o.array(o.string()).max(200),hasMore:o.boolean()}).strict();function z(n,e){return`inbox:${n}:${St("sha256").update(JSON.stringify(e)).digest("hex")}`}u(z,"retryKey");var U=class{constructor(e){this.client=e}client;static{u(this,"HostedTaskInboxStorage")}async call(e,t,r=yt()){let s=await this.client.request({contractVersion:v,requestId:r,operation:"task-inbox/execute",params:e});return t.parse(s)}async inputPages(e,t=Number.MAX_SAFE_INTEGER){let r=[],s=0;for(;r.length<t;){let i=await this.call(e(s),Tt);for(let a of i.inputs){if(a.sequence<=s)throw new Error("Host task input cursor did not advance.");if(s=a.sequence,r.push(a),r.length>=t)break}if(!i.hasMore)return r;if(i.inputs.length===0)throw new Error("Host task input page made no progress.")}return r}async recoverTaskInboxOwners(e){return this.call({action:"recoverTaskInboxOwners",ownerId:e},o.array(o.object({sessionId:o.string(),turnId:o.string()}).strict()))}async hasTaskCompletion(e){return this.call({action:"hasTaskCompletion",turnId:e},o.boolean())}async taskInboxSnapshot(e){let t=await this.call({action:"taskInboxSnapshot",sessionId:e},re),[r,s]=await Promise.all([this.inputPages(i=>({action:"taskInboxSnapshotInputs",sessionId:e,afterSequence:i})),this.taskWaitsForSession(e)]);return{...t,inputs:r,waits:s}}async declareTaskWork(e,t,r,s){await this.call({action:"declareTaskWork",sessionId:e,turnId:t,ownerId:r,areas:s},C)}async taskWorkAreas(e){return this.call({action:"taskWorkAreas",sessionId:e},Rt)}async admitTaskInput(e){return this.call({action:"admitTaskInput",input:e},O)}async admitTaskInputs(e){return this.call({action:"admitTaskInputs",inputs:e},J)}async rejectTaskInput(e,t){await this.call({action:"rejectTaskInput",id:e,error:t},C)}async getTaskInput(e){return this.call({action:"getTaskInput",id:e},O.nullable())}async taskInputsForSession(e,t={}){let r=Math.max(1,Math.min(500,t.limit??128)),s=[],i=t.afterSequence??0;for(;s.length<r;){let a=Math.min(10,r-s.length),l=await this.call({action:"taskInputsForSession",sessionId:e,query:{afterSequence:i,pendingOnly:t.pendingOnly,limit:a}},J);if(!l.length)break;for(let c of l){if(c.sequence<=i)throw new Error("Host task input cursor did not advance.");i=c.sequence,s.push(c)}if(l.length<a)break}return s}async mutateTaskInput(e,t,r){return this.call({action:"mutateTaskInput",sessionId:e,inputId:t,change:r},O,z("mutate",{sessionId:e,inputId:t,change:r}))}async openTaskInboxTurn(e,t,r){await this.call({action:"openTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C,z("open",{sessionId:e,turnId:t,ownerId:r}))}async renewTaskInboxTurn(e,t,r){await this.call({action:"renewTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async pendingTaskInputs(e,t){return this.inputPages(r=>({action:"pendingTaskInputs",sessionId:e,turnId:t,afterSequence:r}))}async taskAssignmentInputs(e){return this.inputPages(t=>({action:"taskAssignmentInputs",turnId:e,afterSequence:t}))}async pauseTaskInboxTurn(e,t,r){await this.call({action:"pauseTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async includeTaskInputs(e,t,r,s){return this.call({action:"includeTaskInputs",sessionId:e,turnId:t,ownerId:r,requestId:s},J,z("include",{sessionId:e,turnId:t,ownerId:r,requestId:s}))}async settleTaskInputRequest(e,t){await this.call({action:"settleTaskInputRequest",requestId:e,outcome:t},C)}async sealTaskInboxTurn(e,t,r){return this.call({action:"sealTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},o.boolean())}async sealNativeTaskInboxTurn(e,t,r){return this.call({action:"sealNativeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},J)}async closeTaskInboxTurn(e,t,r,s){await this.call({action:"closeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r,outcome:s},C)}async taskInboxPaused(e){return this.call({action:"taskInboxPaused",sessionId:e},o.boolean())}async reserveTaskFollowup(e,t,r){return this.call({action:"reserveTaskFollowup",sessionId:e,turnId:t,ownerId:r},O.nullable(),z("reserve",{sessionId:e,turnId:t,ownerId:r}))}async taskInboxWakeTargets(){let e=[],t="";for(;;){let r=await this.call({action:"taskInboxWakeTargets",afterSessionId:t},xt);for(let s of r.items){if(s<=t)throw new Error("Host task wake cursor did not advance.");t=s,e.push(s)}if(!r.hasMore)return e;if(!r.items.length)throw new Error("Host task wake page made no progress.")}}async createTaskWait(e){return this.call({action:"createTaskWait",value:e},j)}async settleTaskWait(e,t){return this.call({action:"settleTaskWait",id:e,state:t},j)}async taskWaitsForSession(e){let t=[],r="";for(;;){let s=await this.call({action:"taskWaitsForSession",sessionId:e,afterId:r},Pt);for(let i of s.items){if(i.id<=r)throw new Error("Host task wait cursor did not advance.");r=i.id,t.push(i)}if(!s.hasMore)return t;if(!s.items.length)throw new Error("Host task wait page made no progress.")}}async commitSubagentCompletion(e,t){await this.call({action:"commitSubagentCompletion",value:e,turnId:t},C)}async pendingTaskCompletions(e=""){let t=[],r=e;for(;t.length<100;){let s=await this.call({action:"pendingTaskCompletions",afterTurnId:r},o.array(It).max(10));for(let i of s){if(i.turnId<=r)throw new Error("Host task completion cursor did not advance.");r=i.turnId,t.push(i)}if(s.length<10)break}return t}async settleTaskCompletion(e,t){await this.call({action:"settleTaskCompletion",turnId:e,inputId:t},C)}async upsertSubagentRun(e){return this.call({action:"upsertSubagentRun",value:_.parse(e)},_)}async getSubagentRun(e){return this.call({action:"getSubagentRun",id:e},_.nullable())}async listSubagentRuns(e={}){let r=[],s="",i=e.status?Array.isArray(e.status)?[...e.status]:[e.status]:null;for(;;){let a=await this.call({action:"listSubagentRuns",query:{parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,status:i,afterId:s,limit:10}},o.array(_).max(10));for(let l of a){if(l.id<=s)throw new Error("Host subagent run cursor did not advance.");if(s=l.id,r.push(l),r.length>1e3)throw new Error("Hosted subagent run list exceeds 1,000 rows; use a narrower session or status query.")}if(a.length<10)break}return r.sort((a,l)=>(l.updatedAt??l.createdAt).localeCompare(a.updatedAt??a.createdAt)),e.limit===void 0?r:r.slice(0,Math.max(1,Math.min(1e3,e.limit)))}async listActiveSubagentRuns(e={}){return this.listSubagentRuns({...e,status:e.status??["queued","running","needs_resume"]})}};var ee=class extends U{static{u(this,"HostedTurnRepository")}sessions;events;approvals;usage;createImprove;constructor(e){super(e),this.sessions=new G(e),this.events=new W(e),this.approvals=new ke(e),this.usage=new Oe(e),this.createImprove=new $(e)}sessionShells(){return this.sessions.sessionShells()}sessionCount(){return this.sessions.sessionCount()}getSession(e){return this.sessions.getSession(e)}insertSessionAtFront(e){return this.sessions.insertSessionAtFront(e)}updateSession(e,t){return this.sessions.updateSession(e,t)}getTurn(e){return this.sessions.getTurn(e)}insertTurn(e){return this.sessions.insertTurn(e)}updateTurn(e,t){return this.sessions.updateTurn(e,t)}latestTurnForSession(e,t){return this.sessions.latestTurnForSession(e,t)}latestPersistedTurnForSession(e,t){return this.sessions.latestPersistedTurnForSession(e,t)}turnsForSession(e,t){return this.sessions.turnsForSession(e,t)}countTurnsForSession(e){return this.sessions.countTurnsForSession(e)}hasSubagentParentWakeTurn(e,t){return this.sessions.hasSubagentParentWakeTurn(e,t)}countSubagentParentWakeTurns(e,t){return this.sessions.countSubagentParentWakeTurns(e,t)}latestAssistantTextForSession(e){return this.sessions.latestAssistantTextForSession(e)}appendRuntimeEvent(e){return this.events.appendRuntimeEvent(e)}runtimeEventsForSession(e,t){return this.events.runtimeEventsForSession(e,t)}persistedRuntimeEventsForSession(e,t){return this.events.persistedRuntimeEventsForSession(e,t)}runtimeEventPageRows(e){return this.events.runtimeEventPageRows(e)}getApproval(e){return this.approvals.getApproval(e)}async upsertApproval(e){let t=await this.approvals.readApproval(e.id);t&&JSON.stringify(t.approval)===JSON.stringify(e)||await this.approvals.putApproval({approval:e,expectedRevision:t?.revision??null,requestId:`approval:${Ct("sha256").update(JSON.stringify({approval:e,revision:t?.revision??null})).digest("hex")}`})}upsertModelUsageRecord(e){return this.usage.upsertModelUsageRecord(e)}listModelUsageRecords(e){return this.usage.listModelUsageRecords(e)}getCreateImproveRun(e){return this.createImprove.getCreateImproveRun(e)}listCreateImproveRuns(e){return this.createImprove.listCreateImproveRuns(e)}upsertCreateImproveRun(e){return this.createImprove.upsertCreateImproveRun(e)}mutateCreateImproveRun(e,t){return this.createImprove.mutateCreateImproveRun(e,t)}};function $e(n){return new ee(n)}u($e,"createHostedRuntimeCoreStorage");function We(n=process.env){let e=n.OPENPOND_API_KEY?.trim(),t=n.OPENPOND_OPCHAT_API_URL?.trim(),r=n.OPENPOND_HOSTED_MODEL_ID?.trim();if(!e||!t||!r)throw new Error("Hosted model stream requires a host credential, API URL, and admitted model.");let s=new URL(t);if(s.protocol!=="https:"||s.username||s.password||s.search||s.hash)throw new Error("Hosted model stream API URL is invalid.");return u(async function*(a){if(a.model!==r)throw new Error("Hosted model selection changed outside host admission.");yield*Pe({...a,apiBaseUrl:s.toString(),token:e,model:r})},"streamHostedModel")}u(We,"createHostedModelStreamFromEnvironment");import{existsSync as Et}from"node:fs";import T from"node:path";import{fileURLToPath as kt}from"node:url";var Ge=T.dirname(kt(import.meta.url));function R(n,e,t){let r=n[e+1];if(!r||r.startsWith("--"))throw new Error(`${t} requires a value.`);return r}u(R,"requireValue");function Je(n,e){let t=Number.parseInt(n,10);if(!Number.isFinite(t)||t<0||t>65535)throw new Error(`${e} must be a port from 0 to 65535.`);return t}u(Je,"parsePort");function Ke(n){let e="serve",t=K,r=17874,s=null,i=!1,a=!1,l=null,c,p,h=null,b=null,x=null,A=null,f,g="sqlite_bundle",S=0,P=n[0];if(P&&!P.startsWith("-")){if(P==="serve"||P==="server")e="serve";else if(P==="app-server")e="app-server";else if(P==="web")e="web";else{if(P==="help")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,help:!0};throw new Error(`Unknown command: ${P}`)}S=1}for(let m=S;m<n.length;m+=1){let d=n[m];if(d==="--help"||d==="-h")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,help:!0};if(d==="--listen"){let E=ye(R(n,m,d));t=E.host,r=Je(String(E.port),d),m+=1}else if(d==="--hostname"||d==="--host")t=R(n,m,d),m+=1;else if(d==="--port")r=Je(R(n,m,d),d),m+=1;else if(d==="--web-root")s=T.resolve(R(n,m,d)),m+=1;else if(d==="--source-browser-state")p=T.resolve(R(n,m,d)),m+=1;else{if(d==="--store-dir")throw new Error("--store-dir has been replaced by --home. Use --home <directory> or OPENPOND_HOME.");if(d==="--home")l=T.resolve(R(n,m,d)),m+=1;else if(d==="--hosted-cache-home")c=T.resolve(R(n,m,d)),m+=1;else if(d==="--runtime-storage"){if(R(n,m,d)!=="hosted-postgres")throw new Error("Unsupported app-server runtime storage.");g="hosted_postgres",m+=1}else if(d==="--profile-source-root")h=T.resolve(R(n,m,d)),m+=1;else if(d==="--profile-repository-id")b=R(n,m,d),m+=1;else if(d==="--profile-id")x=R(n,m,d),m+=1;else if(d==="--profile-revision")A=R(n,m,d),m+=1;else if(d==="--hosted-profile-release"){if(f)throw new Error("Duplicate hosted Profile release descriptor.");let E=R(n,m,d);if(E.length>16e3||!/^[A-Za-z0-9_-]+$/.test(E))throw new Error("Invalid hosted Profile release descriptor.");try{f=Ae.parse(JSON.parse(Buffer.from(E,"base64url").toString("utf8")))}catch{throw new Error("Invalid hosted Profile release descriptor.")}m+=1}else if(d==="--open-browser")i=!0;else if(d==="--print-access-url")a=!0;else throw new Error(`Unknown option: ${d}`)}}if(i&&a)throw new Error("--open-browser and --print-access-url cannot be used together.");if(e!=="web"&&(i||a))throw new Error("Browser options are only available in web mode.");let w=[h,b,x,A].filter(Boolean).length;if(w&&(w!==4||e!=="app-server"))throw new Error("Profile source flags require app-server mode and --profile-source-root, --profile-repository-id, --profile-id, and --profile-revision together.");if(g==="hosted_postgres"&&(e!=="app-server"||l||w))throw new Error("Hosted Postgres app-server cannot use --home or local Profile source flags.");if(f&&g!=="hosted_postgres")throw new Error("Hosted Profile release requires hosted Postgres app-server mode.");if(c&&g!=="hosted_postgres")throw new Error("Hosted cache home requires hosted Postgres mode.");return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,sourceBrowserState:p,...w?{profileSource:{repoPath:h,repositoryId:b,profileId:x,sourceRevision:A}}:{},...f?{admittedProfileRelease:f}:{},...c?{hostedCacheHome:c}:{},help:!1}}u(Ke,"parseCliArgs");function Ot(){return[process.env.OPENPOND_WEB_ROOT,T.resolve(process.cwd(),"apps/web/dist"),T.resolve(Ge,"../../web/dist"),T.resolve(process.cwd(),"web"),T.resolve(Ge,"../web")].filter(n=>!!n)}u(Ot,"defaultWebRootCandidates");function At(n){let e=n?[n]:Ot();for(let t of e){let r=T.resolve(t);if(Et(T.join(r,"index.html")))return r}return null}u(At,"resolveWebRoot");function _t(n){let e=n==="0.0.0.0"||n==="::"?"127.0.0.1":n;return e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}u(_t,"formatHostForUrl");function Ht(n){return`http://${_t(n.status.host)}:${n.status.port}`}u(Ht,"browserBaseUrl");function Mt(n,e){let t=new URL(n),r=new URLSearchParams;return r.set("openpondServerUrl",n),r.set("openpondToken",e),t.hash=r.toString(),t.toString()}u(Mt,"tokenizedWebUrl");async function ze(n,e=Ce){let t=Mt(n.baseUrl,n.token);if(n.printAccessUrl)return{stdout:[`OpenPond access URL: ${t}`],stderr:[]};if(!n.openBrowser)return{stdout:[`OpenPond web UI: ${n.baseUrl}`],stderr:[]};let r=await e(t);return r.opened?{stdout:[`Opened OpenPond in your browser: ${n.baseUrl}`],stderr:[]}:{stdout:[`OpenPond access URL: ${t}`],stderr:[`Could not open the system browser: ${r.error}`]}}u(ze,"resolveWebLaunchMessages");function Xe(){console.log(`Usage:
23
+ </script></html>`}u(Be,"startupRecoveryPage");var ct=o.strictObject({action:o.enum(["preview","migrate","restart","retry"]),sourceAppHome:o.string().optional(),sourceConfig:o.string().optional(),resolutions:me.optional()});function De(n){return n instanceof ne&&/^(PRIVATE_STORAGE_|UNSAFE_STORAGE_|INVALID_CONFIG|CONFIG_|MIGRATION_|SOURCE_CHANGED_|CREDENTIAL_|UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|INVALID_ACCOUNT_|MISSING_INSTRUCTION_|INVALID_PROFILE_|DATABASE_RECOVERY_)/.test(n.issue.code)}u(De,"isRecoverableStartupError");async function Fe(n,e,t){let r=/^(UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|UNSAFE_STORAGE_|PRIVATE_STORAGE_)/.test(t.issue.code),s=r?await Q.mkdtemp(at.join(it.tmpdir(),"openpond-recovery-")):n;return Re(s,async()=>{let{token:i,tokenFile:a}=await Ee(s),l=_e(n),c=t.issue,p,h=new Promise(f=>{p=f}),b=ut((f,g)=>{(async()=>{let S=new URL(f.url??"/","http://127.0.0.1");if(!Ue(f,g).allowed){I(g,403,{error:"Origin not allowed"});return}if(f.method==="OPTIONS"){I(g,204,{});return}if(f.method==="GET"&&S.pathname==="/health"){I(g,200,{ok:!0,server:"openpond-app-server",version:Se,recovery:!0});return}if(f.method==="GET"&&S.pathname==="/"){let w=lt(18).toString("base64");g.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${w}'; style-src 'nonce-${w}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`}),g.end(Be(w));return}if(!Ne(f,S,i)){I(g,401,{error:"Unauthorized"});return}let P=!r;if(f.method==="GET"&&S.pathname==="/v1/recovery"){I(g,200,{issue:c,configEditable:P,config:r?{path:M(n).config,text:null,rawRevision:"unavailable",issue:c,recoverableRevisions:[]}:await l.status(),migration:await ge(n).catch(w=>({issue:q(w,n)}))});return}if(f.method==="POST"&&S.pathname==="/v1/configuration"&&P){I(g,200,await l.mutate(await Z(f)));return}if(f.method==="POST"&&S.pathname==="/v1/recovery"){let w=ct.parse(await Z(f));if(r&&w.action!=="retry"&&w.action!=="preview")throw t;if(w.action==="restart"){I(g,200,await he(n));return}if(w.action==="preview"||w.action==="migrate"){I(g,200,await Y(n,{sourceAppHome:w.sourceAppHome,sourceConfig:w.sourceConfig,resolutions:w.resolutions,dryRun:w.action==="preview"}));return}await Y(n),await L(n),I(g,200,{ready:!0}),p();return}I(g,503,{error:`${c.message} ${c.action}`,issue:c,recovery:!0})})().catch(S=>{c=q(S,n),I(g,422,{error:`${c.message} ${c.action}`,issue:c})})});await new Promise((f,g)=>{b.once("error",g),b.listen(e,"127.0.0.1",()=>{b.off("error",g),f()})});let x=b.address().port,A=`http://127.0.0.1:${x}`;return await Ie(s,A,"startup-recovery"),{url:A,port:x,token:i,tokenFile:a,storePath:M(n).database,repaired:h,close:u(async()=>{b.closeIdleConnections(),await new Promise((f,g)=>b.close(S=>S?g(S):f())),r&&await Q.rm(s,{recursive:!0,force:!0})},"close")}}).catch(async i=>{throw r&&await Q.rm(s,{recursive:!0,force:!0}),i})}u(Fe,"startRecoveryServer");import{createHash as Ct}from"node:crypto";import{createHash as pt,randomUUID as je}from"node:crypto";var dt=o.object({updatedAt:o.string(),id:o.string().min(1)}).strict(),mt=o.object({entries:o.array(k).max(200),nextBefore:dt.nullable()}).strict(),gt=o.object({run:k,replayed:o.boolean()}).strict(),$=class{constructor(e){this.client=e}client;static{u(this,"HostedCreateImproveStorage")}async getCreateImproveRun(e){let t=await this.client.request({contractVersion:v,requestId:je(),operation:"create-improve/execute",params:{action:"get",runId:e}});return t===null?null:k.parse(t)}async listCreateImproveRuns(e={}){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250))),r=Array.isArray(e.state)?[...e.state]:e.state?[e.state]:[],s=[],i=null;for(;s.length<t;){let a=mt.parse(await this.client.request({contractVersion:v,requestId:je(),operation:"create-improve/execute",params:{action:"page",query:{profileId:e.profileId??null,targetKind:e.targetKind??null,targetId:e.targetId??null,state:r},before:i,limit:Math.min(50,t-s.length)}}));if(e.conversationId&&a.entries.some(l=>l.scope.conversationId!==e.conversationId))throw new Error("Hosted Create/Improve page crossed its conversation scope.");if(s.push(...a.entries),!a.nextBefore)break;if(a.entries.length===0||i&&(a.nextBefore.updatedAt>i.updatedAt||a.nextBefore.updatedAt===i.updatedAt&&a.nextBefore.id>=i.id))throw new Error("Hosted Create/Improve cursor did not advance.");i=a.nextBefore}return s}async upsertCreateImproveRun(e){let t=k.parse(e),r=`create-improve:${pt("sha256").update(JSON.stringify(t)).digest("hex")}`,s=await this.client.request({contractVersion:v,requestId:r,operation:"create-improve/execute",params:{action:"put",run:t}});return k.parse(o.object({run:o.unknown()}).strict().parse(s).run)}async mutateCreateImproveRun(e,t){let r=te.parse(e),s=await this.getCreateImproveRun(r.runId);if(!s)throw new Error(`Create/Improve run not found: ${r.runId}`);if(s.appliedActionIds.includes(r.actionId))return{run:s,replayed:!0};if(s.revision!==r.expectedRevision)throw new Error(`Create/Improve run changed from revision ${r.expectedRevision} to ${s.revision}. Refresh and try again.`);let i=k.parse(t(s));if(i.id!==s.id||i.revision!==s.revision+1||!i.appliedActionIds.includes(r.actionId))throw new Error("Create/Improve mutation must preserve identity, advance one revision and record its action.");return gt.parse(await this.client.request({contractVersion:v,requestId:r.actionId,operation:"create-improve/execute",params:{action:"mutate",mutation:r,next:i}}))}};import{randomUUID as ft}from"node:crypto";async function D(n,e){let t=n;for(;;)try{return await e(t)}catch(r){if(!ht(r)||t<=1)throw r;t=Math.max(1,Math.floor(t/2))}}u(D,"hostedBoundedPage");function ht(n){return n instanceof Error?n.message==="Host storage response is too large."||n.message==="Host storage request failed: host_storage_response_too_large":!1}u(ht,"isOversizeResponse");var vt=o.object({entries:o.array(o.object({sequence:o.number().int().positive(),event:F})).max(200),totalMatchingEvents:o.number().int().nonnegative(),remainingMatchingEvents:o.number().int().nonnegative()}).strict(),W=class{constructor(e){this.client=e}client;static{u(this,"HostedRuntimeEventStorage")}async runtimeEventsForSession(e,t={}){let r=t.limit==null?1e4:Math.max(0,Math.trunc(t.limit));if(r===0)return[];let s=Math.min(r,1e4),i=[],a=Math.max(0,t.afterSequence??0),l=0,c=t.names?new Set(t.names):null;for(;i.length<=s;){let p=await this.runtimeEventPageRows({sessionId:e,afterSequence:a,beforeSequence:null,limit:Math.min(200,s+1-i.length),excludeReasoningDeltas:t.excludeReasoningDeltas});for(let h of p.entries){if(h.sequence<=a)throw new Error("Host event cursor did not advance.");if(a=h.sequence,l+=1,l>1e4)throw new Error("Hosted runtime event scan exceeds 10,000 rows; use a narrower query.");(!c||c.has(h.event.name))&&i.push(h.event)}if(p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break}if(i.length>s||t.limit==null&&r===1e4&&i.length===s)throw new Error("Hosted runtime event read exceeds 10,000 rows; use a bounded cursor query.");return i}async persistedRuntimeEventsForSession(e,t={}){return this.runtimeEventsForSession(e,t)}async appendRuntimeEvent(e){let t=F.parse(e),r=await this.client.request({contractVersion:v,requestId:t.id,operation:"event/append",params:{event:t}});return o.object({event:F}).strict().parse(r).event}async runtimeEventPageRows(e){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit))),r=Math.max(0,Math.trunc(e.afterSequence)),s=e.beforeSequence,i=[],a=0,l=0;for(;i.length<t;){let c=Math.min(200,t-i.length),p=await D(c,async h=>vt.parse(await this.client.request({contractVersion:v,requestId:`event-page:${ft()}`,operation:"events/page",params:{sessionId:e.sessionId,afterSequence:r,beforeSequence:s,limit:h,...e.excludeReasoningDeltas?{excludeReasoningDeltas:!0}:{}}})));if(i.length===0&&(a=p.totalMatchingEvents,l=p.remainingMatchingEvents),i=s===null?[...i,...p.entries]:[...p.entries,...i],p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break;if(s===null){let h=p.entries.at(-1).sequence;if(h<=r)throw new Error("Host event cursor did not advance.");r=h}else{let h=p.entries[0].sequence;if(h>=s)throw new Error("Host event cursor did not advance.");s=h}}return{entries:i,totalMatchingEvents:a,remainingMatchingEvents:l}}};import{randomUUID as y}from"node:crypto";var Le=o.object({revision:o.number().int().min(1),session:N}).strict(),Ve=o.object({revision:o.number().int().min(1),turn:H}).strict(),wt=o.object({sessions:o.array(N).max(200),nextAfterId:o.string().min(1).nullable()}).strict(),bt=o.object({turns:o.array(H).max(200),nextBeforeSortIndex:o.number().int().nonnegative().nullable()}).strict(),G=class{constructor(e){this.client=e}client;static{u(this,"HostedSessionStorage")}async count(){let e=await this.client.request({contractVersion:v,requestId:y(),operation:"session/count",params:{}});return o.object({count:o.number().int().nonnegative()}).strict().parse(e).count}async get(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"session/get",params:{sessionId:e}});return t===null?null:Le.parse(t)}async sessionCount(){return this.count()}async sessionShells(){let e=[],t=null;do{let r=await D(Math.min(10,1001-e.length),async s=>wt.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"session/page",params:{afterId:t,limit:s}})));if(e.push(...r.sessions),e.length>1e3)throw new Error("Hosted session list exceeds 1,000 rows; use a scoped page query.");if(r.nextAfterId!==null&&(r.sessions.length===0||t!==null&&r.nextAfterId<=t))throw new Error("Host session cursor did not advance.");t=r.nextAfterId}while(t!==null);return e}async getSession(e){return(await this.get(e))?.session??null}async insertSessionAtFront(e){await this.put({session:e,expectedRevision:null,requestId:y()})}async updateSession(e,t){let r=await this.get(e);if(!r)return null;let s=N.parse(t(r.session));if(s.id!==e)throw new Error("A session update cannot change its identity.");return(await this.put({session:s,expectedRevision:r.revision,requestId:y()})).session}async put(e){let t=N.parse(e.session);return Le.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"session/put",params:{sessionId:t.id,expectedRevision:e.expectedRevision,session:t}}))}async readTurn(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/get",params:{turnId:e}});return t===null?null:Ve.parse(t)}async getTurn(e){return(await this.readTurn(e))?.turn??null}async turnsForSession(e,t=50){let r=Math.max(1,Math.min(1e3,Math.trunc(t))),s=[],i=null;for(;s.length<r;){let a=await D(Math.min(200,r-s.length),async l=>bt.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"turn/page",params:{sessionId:e,beforeSortIndex:i,limit:l}})));if(s.push(...a.turns),a.nextBeforeSortIndex===null)break;if(i!==null&&a.nextBeforeSortIndex>=i)throw new Error("Host turn cursor did not advance.");i=a.nextBeforeSortIndex}return s}async countTurnsForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/count",params:{sessionId:e}});return o.object({count:o.number().int().nonnegative()}).strict().parse(t).count}async hasSubagentParentWakeTurn(e,t){return await this.wakeCount(e,"messageId",t)>0}async countSubagentParentWakeTurns(e,t){return this.wakeCount(e,"fromRunId",t)}async latestAssistantTextForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"events/latestAssistantText",params:{sessionId:e}});return o.object({text:o.string().nullable()}).strict().parse(t).text}async wakeCount(e,t,r){let s=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/wakeCount",params:{sessionId:e,key:t,value:r}});return o.object({count:o.number().int().nonnegative()}).strict().parse(s).count}async latestTurnForSession(e,t){let r=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/latest",params:{sessionId:e,status:t??null}});return r===null?null:H.parse(r)}async latestPersistedTurnForSession(e,t){return this.latestTurnForSession(e,t)}async insertTurn(e){await this.putTurn({turn:e,expectedRevision:null,requestId:y()})}async updateTurn(e,t){let r=await this.readTurn(e);if(!r)return null;let s=H.parse(t(r.turn));if(s.id!==e||s.sessionId!==r.turn.sessionId)throw new Error("A turn update cannot change its identity.");return(await this.putTurn({turn:s,expectedRevision:r.revision,requestId:y()})).turn}async putTurn(e){let t=H.parse(e.turn);return Ve.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"turn/put",params:{sessionId:t.sessionId,turnId:t.id,expectedRevision:e.expectedRevision,turn:t}}))}};import{createHash as St,randomUUID as yt}from"node:crypto";var C=o.object({ok:o.literal(!0)}).strict(),J=o.array(O),Rt=o.array(o.string()),It=o.object({turnId:o.string(),run:_}).strict(),Tt=o.object({inputs:o.array(O).max(10),hasMore:o.boolean()}).strict(),Pt=o.object({items:o.array(j).max(10),hasMore:o.boolean()}).strict(),xt=o.object({items:o.array(o.string()).max(200),hasMore:o.boolean()}).strict();function z(n,e){return`inbox:${n}:${St("sha256").update(JSON.stringify(e)).digest("hex")}`}u(z,"retryKey");var U=class{constructor(e){this.client=e}client;static{u(this,"HostedTaskInboxStorage")}async call(e,t,r=yt()){let s=await this.client.request({contractVersion:v,requestId:r,operation:"task-inbox/execute",params:e});return t.parse(s)}async inputPages(e,t=Number.MAX_SAFE_INTEGER){let r=[],s=0;for(;r.length<t;){let i=await this.call(e(s),Tt);for(let a of i.inputs){if(a.sequence<=s)throw new Error("Host task input cursor did not advance.");if(s=a.sequence,r.push(a),r.length>=t)break}if(!i.hasMore)return r;if(i.inputs.length===0)throw new Error("Host task input page made no progress.")}return r}async recoverTaskInboxOwners(e){return this.call({action:"recoverTaskInboxOwners",ownerId:e},o.array(o.object({sessionId:o.string(),turnId:o.string()}).strict()))}async hasTaskCompletion(e){return this.call({action:"hasTaskCompletion",turnId:e},o.boolean())}async taskInboxSnapshot(e){let t=await this.call({action:"taskInboxSnapshot",sessionId:e},re),[r,s]=await Promise.all([this.inputPages(i=>({action:"taskInboxSnapshotInputs",sessionId:e,afterSequence:i})),this.taskWaitsForSession(e)]);return{...t,inputs:r,waits:s}}async declareTaskWork(e,t,r,s){await this.call({action:"declareTaskWork",sessionId:e,turnId:t,ownerId:r,areas:s},C)}async taskWorkAreas(e){return this.call({action:"taskWorkAreas",sessionId:e},Rt)}async admitTaskInput(e){return this.call({action:"admitTaskInput",input:e},O)}async admitTaskInputs(e){return this.call({action:"admitTaskInputs",inputs:e},J)}async rejectTaskInput(e,t){await this.call({action:"rejectTaskInput",id:e,error:t},C)}async getTaskInput(e){return this.call({action:"getTaskInput",id:e},O.nullable())}async taskInputsForSession(e,t={}){let r=Math.max(1,Math.min(500,t.limit??128)),s=[],i=t.afterSequence??0;for(;s.length<r;){let a=Math.min(10,r-s.length),l=await this.call({action:"taskInputsForSession",sessionId:e,query:{afterSequence:i,pendingOnly:t.pendingOnly,limit:a}},J);if(!l.length)break;for(let c of l){if(c.sequence<=i)throw new Error("Host task input cursor did not advance.");i=c.sequence,s.push(c)}if(l.length<a)break}return s}async mutateTaskInput(e,t,r){return this.call({action:"mutateTaskInput",sessionId:e,inputId:t,change:r},O,z("mutate",{sessionId:e,inputId:t,change:r}))}async openTaskInboxTurn(e,t,r){await this.call({action:"openTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C,z("open",{sessionId:e,turnId:t,ownerId:r}))}async renewTaskInboxTurn(e,t,r){await this.call({action:"renewTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async pendingTaskInputs(e,t){return this.inputPages(r=>({action:"pendingTaskInputs",sessionId:e,turnId:t,afterSequence:r}))}async taskAssignmentInputs(e){return this.inputPages(t=>({action:"taskAssignmentInputs",turnId:e,afterSequence:t}))}async pauseTaskInboxTurn(e,t,r){await this.call({action:"pauseTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async includeTaskInputs(e,t,r,s){return this.call({action:"includeTaskInputs",sessionId:e,turnId:t,ownerId:r,requestId:s},J,z("include",{sessionId:e,turnId:t,ownerId:r,requestId:s}))}async settleTaskInputRequest(e,t){await this.call({action:"settleTaskInputRequest",requestId:e,outcome:t},C)}async sealTaskInboxTurn(e,t,r){return this.call({action:"sealTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},o.boolean())}async sealNativeTaskInboxTurn(e,t,r){return this.call({action:"sealNativeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},J)}async closeTaskInboxTurn(e,t,r,s){await this.call({action:"closeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r,outcome:s},C)}async taskInboxPaused(e){return this.call({action:"taskInboxPaused",sessionId:e},o.boolean())}async reserveTaskFollowup(e,t,r){return this.call({action:"reserveTaskFollowup",sessionId:e,turnId:t,ownerId:r},O.nullable(),z("reserve",{sessionId:e,turnId:t,ownerId:r}))}async taskInboxWakeTargets(){let e=[],t="";for(;;){let r=await this.call({action:"taskInboxWakeTargets",afterSessionId:t},xt);for(let s of r.items){if(s<=t)throw new Error("Host task wake cursor did not advance.");t=s,e.push(s)}if(!r.hasMore)return e;if(!r.items.length)throw new Error("Host task wake page made no progress.")}}async createTaskWait(e){return this.call({action:"createTaskWait",value:e},j)}async settleTaskWait(e,t){return this.call({action:"settleTaskWait",id:e,state:t},j)}async taskWaitsForSession(e){let t=[],r="";for(;;){let s=await this.call({action:"taskWaitsForSession",sessionId:e,afterId:r},Pt);for(let i of s.items){if(i.id<=r)throw new Error("Host task wait cursor did not advance.");r=i.id,t.push(i)}if(!s.hasMore)return t;if(!s.items.length)throw new Error("Host task wait page made no progress.")}}async commitSubagentCompletion(e,t){await this.call({action:"commitSubagentCompletion",value:e,turnId:t},C)}async pendingTaskCompletions(e=""){let t=[],r=e;for(;t.length<100;){let s=await this.call({action:"pendingTaskCompletions",afterTurnId:r},o.array(It).max(10));for(let i of s){if(i.turnId<=r)throw new Error("Host task completion cursor did not advance.");r=i.turnId,t.push(i)}if(s.length<10)break}return t}async settleTaskCompletion(e,t){await this.call({action:"settleTaskCompletion",turnId:e,inputId:t},C)}async upsertSubagentRun(e){return this.call({action:"upsertSubagentRun",value:_.parse(e)},_)}async getSubagentRun(e){return this.call({action:"getSubagentRun",id:e},_.nullable())}async listSubagentRuns(e={}){let r=[],s="",i=e.status?Array.isArray(e.status)?[...e.status]:[e.status]:null;for(;;){let a=await this.call({action:"listSubagentRuns",query:{parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,status:i,afterId:s,limit:10}},o.array(_).max(10));for(let l of a){if(l.id<=s)throw new Error("Host subagent run cursor did not advance.");if(s=l.id,r.push(l),r.length>1e3)throw new Error("Hosted subagent run list exceeds 1,000 rows; use a narrower session or status query.")}if(a.length<10)break}return r.sort((a,l)=>(l.updatedAt??l.createdAt).localeCompare(a.updatedAt??a.createdAt)),e.limit===void 0?r:r.slice(0,Math.max(1,Math.min(1e3,e.limit)))}async listActiveSubagentRuns(e={}){return this.listSubagentRuns({...e,status:e.status??["queued","running","needs_resume"]})}};var ee=class extends U{static{u(this,"HostedTurnRepository")}sessions;events;approvals;usage;createImprove;constructor(e){super(e),this.sessions=new G(e),this.events=new W(e),this.approvals=new Oe(e),this.usage=new Ae(e),this.createImprove=new $(e)}sessionShells(){return this.sessions.sessionShells()}sessionCount(){return this.sessions.sessionCount()}getSession(e){return this.sessions.getSession(e)}insertSessionAtFront(e){return this.sessions.insertSessionAtFront(e)}updateSession(e,t){return this.sessions.updateSession(e,t)}getTurn(e){return this.sessions.getTurn(e)}insertTurn(e){return this.sessions.insertTurn(e)}updateTurn(e,t){return this.sessions.updateTurn(e,t)}latestTurnForSession(e,t){return this.sessions.latestTurnForSession(e,t)}latestPersistedTurnForSession(e,t){return this.sessions.latestPersistedTurnForSession(e,t)}turnsForSession(e,t){return this.sessions.turnsForSession(e,t)}countTurnsForSession(e){return this.sessions.countTurnsForSession(e)}hasSubagentParentWakeTurn(e,t){return this.sessions.hasSubagentParentWakeTurn(e,t)}countSubagentParentWakeTurns(e,t){return this.sessions.countSubagentParentWakeTurns(e,t)}latestAssistantTextForSession(e){return this.sessions.latestAssistantTextForSession(e)}appendRuntimeEvent(e){return this.events.appendRuntimeEvent(e)}runtimeEventsForSession(e,t){return this.events.runtimeEventsForSession(e,t)}persistedRuntimeEventsForSession(e,t){return this.events.persistedRuntimeEventsForSession(e,t)}async runtimeEventsForTurn(e,t){let r=await this.getTurn(e);if(!r)return[];let s=(await this.events.runtimeEventsForSession(r.sessionId)).filter(i=>i.turnId===e&&(!t?.names||t.names.includes(i.name)));return t?.limit==null?s:s.slice(0,Math.max(0,t.limit))}runtimeEventPageRows(e){return this.events.runtimeEventPageRows(e)}getApproval(e){return this.approvals.getApproval(e)}async upsertApproval(e){let t=await this.approvals.readApproval(e.id);t&&JSON.stringify(t.approval)===JSON.stringify(e)||await this.approvals.putApproval({approval:e,expectedRevision:t?.revision??null,requestId:`approval:${Ct("sha256").update(JSON.stringify({approval:e,revision:t?.revision??null})).digest("hex")}`})}upsertModelUsageRecord(e){return this.usage.upsertModelUsageRecord(e)}listModelUsageRecords(e){return this.usage.listModelUsageRecords(e)}getCreateImproveRun(e){return this.createImprove.getCreateImproveRun(e)}listCreateImproveRuns(e){return this.createImprove.listCreateImproveRuns(e)}upsertCreateImproveRun(e){return this.createImprove.upsertCreateImproveRun(e)}mutateCreateImproveRun(e,t){return this.createImprove.mutateCreateImproveRun(e,t)}};function $e(n){return new ee(n)}u($e,"createHostedRuntimeCoreStorage");function We(n=process.env){let e=n.OPENPOND_API_KEY?.trim(),t=n.OPENPOND_OPCHAT_API_URL?.trim(),r=n.OPENPOND_HOSTED_MODEL_ID?.trim();if(!e||!t||!r)throw new Error("Hosted model stream requires a host credential, API URL, and admitted model.");let s=new URL(t);if(s.protocol!=="https:"||s.username||s.password||s.search||s.hash)throw new Error("Hosted model stream API URL is invalid.");return u(async function*(a){if(a.model!==r)throw new Error("Hosted model selection changed outside host admission.");yield*Pe({...a,apiBaseUrl:s.toString(),token:e,model:r})},"streamHostedModel")}u(We,"createHostedModelStreamFromEnvironment");import{existsSync as Et}from"node:fs";import T from"node:path";import{fileURLToPath as kt}from"node:url";var Ge=T.dirname(kt(import.meta.url));function R(n,e,t){let r=n[e+1];if(!r||r.startsWith("--"))throw new Error(`${t} requires a value.`);return r}u(R,"requireValue");function Je(n,e){let t=Number.parseInt(n,10);if(!Number.isFinite(t)||t<0||t>65535)throw new Error(`${e} must be a port from 0 to 65535.`);return t}u(Je,"parsePort");function Ke(n){let e="serve",t=K,r=17874,s=null,i=!1,a=!1,l=null,c,p,h=null,b=null,x=null,A=null,f,g="sqlite_bundle",S=0,P=n[0];if(P&&!P.startsWith("-")){if(P==="serve"||P==="server")e="serve";else if(P==="app-server")e="app-server";else if(P==="web")e="web";else{if(P==="help")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,help:!0};throw new Error(`Unknown command: ${P}`)}S=1}for(let m=S;m<n.length;m+=1){let d=n[m];if(d==="--help"||d==="-h")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,help:!0};if(d==="--listen"){let E=ye(R(n,m,d));t=E.host,r=Je(String(E.port),d),m+=1}else if(d==="--hostname"||d==="--host")t=R(n,m,d),m+=1;else if(d==="--port")r=Je(R(n,m,d),d),m+=1;else if(d==="--web-root")s=T.resolve(R(n,m,d)),m+=1;else if(d==="--source-browser-state")p=T.resolve(R(n,m,d)),m+=1;else{if(d==="--store-dir")throw new Error("--store-dir has been replaced by --home. Use --home <directory> or OPENPOND_HOME.");if(d==="--home")l=T.resolve(R(n,m,d)),m+=1;else if(d==="--hosted-cache-home")c=T.resolve(R(n,m,d)),m+=1;else if(d==="--runtime-storage"){if(R(n,m,d)!=="hosted-postgres")throw new Error("Unsupported app-server runtime storage.");g="hosted_postgres",m+=1}else if(d==="--profile-source-root")h=T.resolve(R(n,m,d)),m+=1;else if(d==="--profile-repository-id")b=R(n,m,d),m+=1;else if(d==="--profile-id")x=R(n,m,d),m+=1;else if(d==="--profile-revision")A=R(n,m,d),m+=1;else if(d==="--hosted-profile-release"){if(f)throw new Error("Duplicate hosted Profile release descriptor.");let E=R(n,m,d);if(E.length>16e3||!/^[A-Za-z0-9_-]+$/.test(E))throw new Error("Invalid hosted Profile release descriptor.");try{f=ke.parse(JSON.parse(Buffer.from(E,"base64url").toString("utf8")))}catch{throw new Error("Invalid hosted Profile release descriptor.")}m+=1}else if(d==="--open-browser")i=!0;else if(d==="--print-access-url")a=!0;else throw new Error(`Unknown option: ${d}`)}}if(i&&a)throw new Error("--open-browser and --print-access-url cannot be used together.");if(e!=="web"&&(i||a))throw new Error("Browser options are only available in web mode.");let w=[h,b,x,A].filter(Boolean).length;if(w&&(w!==4||e!=="app-server"))throw new Error("Profile source flags require app-server mode and --profile-source-root, --profile-repository-id, --profile-id, and --profile-revision together.");if(g==="hosted_postgres"&&(e!=="app-server"||l||w))throw new Error("Hosted Postgres app-server cannot use --home or local Profile source flags.");if(f&&g!=="hosted_postgres")throw new Error("Hosted Profile release requires hosted Postgres app-server mode.");if(c&&g!=="hosted_postgres")throw new Error("Hosted cache home requires hosted Postgres mode.");return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,sourceBrowserState:p,...w?{profileSource:{repoPath:h,repositoryId:b,profileId:x,sourceRevision:A}}:{},...f?{admittedProfileRelease:f}:{},...c?{hostedCacheHome:c}:{},help:!1}}u(Ke,"parseCliArgs");function Ot(){return[process.env.OPENPOND_WEB_ROOT,T.resolve(process.cwd(),"apps/web/dist"),T.resolve(Ge,"../../web/dist"),T.resolve(process.cwd(),"web"),T.resolve(Ge,"../web")].filter(n=>!!n)}u(Ot,"defaultWebRootCandidates");function At(n){let e=n?[n]:Ot();for(let t of e){let r=T.resolve(t);if(Et(T.join(r,"index.html")))return r}return null}u(At,"resolveWebRoot");function _t(n){let e=n==="0.0.0.0"||n==="::"?"127.0.0.1":n;return e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}u(_t,"formatHostForUrl");function Ht(n){return`http://${_t(n.status.host)}:${n.status.port}`}u(Ht,"browserBaseUrl");function Mt(n,e){let t=new URL(n),r=new URLSearchParams;return r.set("openpondServerUrl",n),r.set("openpondToken",e),t.hash=r.toString(),t.toString()}u(Mt,"tokenizedWebUrl");async function ze(n,e=Ce){let t=Mt(n.baseUrl,n.token);if(n.printAccessUrl)return{stdout:[`OpenPond access URL: ${t}`],stderr:[]};if(!n.openBrowser)return{stdout:[`OpenPond web UI: ${n.baseUrl}`],stderr:[]};let r=await e(t);return r.opened?{stdout:[`Opened OpenPond in your browser: ${n.baseUrl}`],stderr:[]}:{stdout:[`OpenPond access URL: ${t}`],stderr:[`Could not open the system browser: ${r.error}`]}}u(ze,"resolveWebLaunchMessages");function Xe(){console.log(`Usage:
24
24
  openpond-app-server serve [--hostname HOST] [--port PORT]
25
25
  openpond-app-server app-server [--home DIR]
26
26
  openpond-app-server web [--hostname HOST] [--port PORT] [--web-root DIR]