openpond 0.2.39 → 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 (99) 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-JZTMHORT.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-GIPSOLAY.js → chunk-2Z6H32OC.js} +1 -1
  8. package/dist/chunks/chunk-3FXZW4G7.js +3 -0
  9. package/dist/chunks/{chunk-RJACNWYJ.js → chunk-452UKUIB.js} +202 -203
  10. package/dist/chunks/{chunk-3HQEEZPO.js → chunk-65BW2QXY.js} +1 -1
  11. package/dist/chunks/{chunk-XHJUP7M4.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-25OT6IYM.js → chunk-GKP2ZPKM.js} +1 -1
  21. package/dist/chunks/{chunk-6GLGOIMQ.js → chunk-H7JB25HO.js} +1 -1
  22. package/dist/chunks/{chunk-SBBXUZWL.js → chunk-HLNJKX3S.js} +2 -2
  23. package/dist/chunks/{chunk-7BGT6Q2D.js → chunk-JLZ2TEKK.js} +1 -1
  24. package/dist/chunks/chunk-JXD5PNF7.js +9 -0
  25. package/dist/chunks/{chunk-L6ELXODL.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-KRC36KV2.js +5 -0
  29. package/dist/chunks/{chunk-ZO7DTED5.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-WCZRDULE.js → chunk-NVPKY3KE.js} +1 -1
  34. package/dist/chunks/chunk-POWZXZJ2.js +2 -0
  35. package/dist/chunks/{chunk-ZPGTGQJT.js → chunk-PU2JM765.js} +1 -1
  36. package/dist/chunks/{chunk-SHCRE7B2.js → chunk-QJX7UASW.js} +1 -1
  37. package/dist/chunks/chunk-R6YJY7F2.js +3 -0
  38. package/dist/chunks/{chunk-MRGA6BKG.js → chunk-RT6YPMWF.js} +1 -1
  39. package/dist/chunks/{chunk-JUX77H6K.js → chunk-TPOW52DO.js} +3 -3
  40. package/dist/chunks/chunk-V62BHD5G.js +2 -0
  41. package/dist/chunks/chunk-VB2S5HV4.js +3 -0
  42. package/dist/chunks/{chunk-FKVP26MC.js → chunk-VKGVC26K.js} +1 -1
  43. package/dist/chunks/{chunk-ZCFX6HQO.js → chunk-VQG25QBJ.js} +1 -1
  44. package/dist/chunks/{chunk-DHP75QSG.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-V7E4I5N3.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-OQ7CFD4Q.js → extension-S2UIZH46.js} +1 -1
  55. package/dist/chunks/{help-4BB2A5JC.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-LZYR4CMX.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-6RLQYNTY.js → sandbox-template-AAOUNWTL.js} +1 -1
  67. package/dist/chunks/{src-PASASTIA.js → src-HLLPHEW4.js} +1 -1
  68. package/dist/chunks/{src-J7NT5WEH.js → src-PERIQ7VT.js} +112 -112
  69. package/dist/chunks/{teams-bot-UQB636V3.js → teams-bot-LKIOF3B5.js} +1 -1
  70. package/dist/chunks/{workspaces-RFQ4QB5A.js → workspaces-S3NXR6VJ.js} +1 -1
  71. package/dist/cli.js +3 -3
  72. package/dist/index.js +1 -1
  73. package/docs/command-reference.md +1 -1
  74. package/package.json +1 -1
  75. package/dist/chunks/actions-command-MHWHPQ66.js +0 -2
  76. package/dist/chunks/app-server-runtime-72NRJAB5.js +0 -2
  77. package/dist/chunks/apps-U5GIOD6W.js +0 -2
  78. package/dist/chunks/chunk-AOBTILU5.js +0 -2
  79. package/dist/chunks/chunk-DDHUSA3I.js +0 -2
  80. package/dist/chunks/chunk-FVALIUVY.js +0 -2
  81. package/dist/chunks/chunk-P5CFBE6Z.js +0 -3
  82. package/dist/chunks/chunk-Q3X5WOVH.js +0 -4
  83. package/dist/chunks/chunk-QK2GLRCY.js +0 -53
  84. package/dist/chunks/chunk-R6DWG5A4.js +0 -12
  85. package/dist/chunks/chunk-RELOOVWW.js +0 -2
  86. package/dist/chunks/chunk-SHCKK3SU.js +0 -2
  87. package/dist/chunks/chunk-TZNKOKQJ.js +0 -5
  88. package/dist/chunks/cli-ETZV6JZI.js +0 -2
  89. package/dist/chunks/configuration-command-RPNYWBKK.js +0 -2
  90. package/dist/chunks/core-commands-WFTASSGL.js +0 -2
  91. package/dist/chunks/desktop-test-NZAZVXLK.js +0 -3
  92. package/dist/chunks/dist-4OUZANXR.js +0 -2
  93. package/dist/chunks/experiments-7UBJCQAQ.js +0 -2
  94. package/dist/chunks/hosted-harness-runtime-2YI2FLU2.js +0 -2
  95. package/dist/chunks/hosted-profile-compiler-35BQPVJ6.js +0 -3
  96. package/dist/chunks/opchat-QVB4UIZR.js +0 -3
  97. package/dist/chunks/organizations-MUKXB6MX.js +0 -2
  98. package/dist/chunks/project-agent-FHNWIH2D.js +0 -2
  99. package/dist/chunks/sandbox-command-GJN3HSJQ.js +0 -2
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as v,b as I}from"./chunk-GLUWATL5.js";import{ya as L,za as E}from"./chunk-QK2GLRCY.js";import{f as w}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";var T=class extends Error{constructor(t,e){super(`API request timed out after ${t}ms: ${e}`);this.timeoutMs=t;this.requestUrl=e;this.name="ApiTimeoutError"}timeoutMs;requestUrl;static{a(this,"ApiTimeoutError")}code="OPENPOND_API_TIMEOUT"},S=class extends Error{constructor(t,e){super(`API response exceeded ${t} bytes: ${e}`);this.maximumBytes=t;this.requestUrl=e;this.name="ApiResponseTooLargeError"}maximumBytes;requestUrl;static{a(this,"ApiResponseTooLargeError")}code="OPENPOND_API_RESPONSE_TOO_LARGE"},O=class extends Error{constructor(t,e,s,r=null){let c=r||e;super(`${s} failed: ${t}${c?` ${c}`:""}`);this.status=t;this.apiMessage=r;this.name="OpenPondApiError",this.code=e||"OPENPOND_API_ERROR"}status;apiMessage;static{a(this,"OpenPondApiError")}code};async function i(o,n,t,e={}){let{timeoutMs:s=3e4,maxResponseBytes:r=8388608,explicitBearerAuth:c=!1,...p}=e,d=`${o}${t}`,m=new Headers(p.headers);m.set("Content-Type","application/json");let g=c?void 0:process.env.OPENPOND_API_KEY,h=n?.trim()||"",u=!c&&h.startsWith("opk_"),x=g||(u?h:null);x&&!m.has("openpond-api-key")&&m.set("openpond-api-key",x),n?m.set("Authorization",u?`ApiKey ${h}`:`Bearer ${n}`):g&&!m.has("Authorization")&&m.set("Authorization",`ApiKey ${g}`);let y=new AbortController,f=new T(s,d),R=s>0?setTimeout(()=>y.abort(f),s):null;R?.unref?.();let P=U(p.signal,y.signal,s),k=a(()=>{R&&clearTimeout(R)},"cleanup");try{let A=await fetch(d,{...p,headers:m,signal:P});return C(A,{cleanup:k,maximumBytes:r,requestUrl:d,timeoutController:y,timeoutError:f})}catch(A){throw k(),y.signal.aborted?f:A}}a(i,"apiFetch");async function l(o,n){let t;try{let e=await o.text();t=e?JSON.parse(e):{}}catch(e){if(e instanceof T||e instanceof S)throw e;t={}}if(!o.ok){let e=typeof t.error=="string"?t.error:null,s=typeof t.message=="string"?t.message:null;throw new O(o.status,e,n,s)}return t}a(l,"readApiJson");function C(o,n){if(!o.body)return n.cleanup(),o;let t=Number(o.headers.get("content-length"));if(n.maximumBytes>0&&Number.isFinite(t)&&t>n.maximumBytes)throw n.cleanup(),o.body.cancel(),new S(n.maximumBytes,n.requestUrl);let e=o.body.getReader(),s=0,r=new ReadableStream({async pull(c){try{let p=await e.read();if(p.done){n.cleanup(),c.close();return}if(s+=p.value.byteLength,n.maximumBytes>0&&s>n.maximumBytes){n.cleanup(),await e.cancel(),c.error(new S(n.maximumBytes,n.requestUrl));return}c.enqueue(p.value)}catch(p){n.cleanup(),c.error(n.timeoutController.signal.aborted?n.timeoutError:p)}},async cancel(c){n.cleanup(),await e.cancel(c)}});return new Response(r,{headers:o.headers,status:o.status,statusText:o.statusText})}a(C,"boundedResponse");function U(o,n,t){return t<=0?o??void 0:o?AbortSignal.any([o,n]):n}a(U,"composedSignal");async function _(o,n,t,e,s){let r=await i(o,n,`/v4/apps/${t}/commits`,{method:"POST",body:JSON.stringify({files:e,message:s})});if(!r.ok){let c=await r.text().catch(()=>"");throw new Error(`Commit failed: ${r.status} ${c}`)}return await r.json()}a(_,"commitFiles");async function j(o,n,t,e){let s=e?.environment??"production",r=await i(o,n,`/v4/apps/${t}/deployments`,{method:"POST",body:JSON.stringify({environment:s,...e?.commitSha?{commitSha:e.commitSha}:{},...e?.branch?{branch:e.branch}:{}})});if(!r.ok){let c=await r.text().catch(()=>"");throw new Error(`Deploy failed: ${r.status} ${c}`)}return await r.json()}a(j,"deployApp");async function B(o,n,t,e){let s=await i(o,n,`/v4/apps/${encodeURIComponent(t)}/deployments/promote-preview`,{method:"POST",body:JSON.stringify(e)});return l(s,"Preview promotion")}a(B,"promotePreviewToProduction");async function G(o,n,t,e){let s=await i(o,n,`/v1/apps/${encodeURIComponent(t)}/lifecycle/start`,{method:"POST",body:JSON.stringify(e)});return l(s,"App lifecycle start")}a(G,"startAppLifecycle");async function J(o,n,t){let e=await i(o,n,`/apps/deployments/${t}/logs`,{method:"GET"});if(!e.ok){let c=await e.text().catch(()=>"");throw new Error(`Deployment logs failed: ${e.status} ${c}`)}let s=await e.json().catch(()=>({}));return(Array.isArray(s.logs)?s.logs:[]).map(c=>{let p=typeof c.createdAt=="string"?c.createdAt:c.createdAt instanceof Date?c.createdAt.toISOString():new Date().toISOString();return{id:typeof c.id=="string"?c.id:`${Math.random()}`,type:typeof c.type=="string"?c.type:void 0,message:typeof c.message=="string"?c.message:"",createdAt:p}})}a(J,"getDeploymentLogs");async function M(o,n,t){let e=await i(o,n,`/apps/deployments/${t}/status`,{method:"GET"});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`Deployment status failed: ${e.status} ${r}`)}return{status:(await e.json().catch(()=>({}))).deployment?.status}}a(M,"getDeploymentStatus");async function F(o,n,t,e){let s=new URLSearchParams;e?.status&&e.status.length>0&&s.set("status",e.status.join(",")),e?.createdAfter&&s.set("createdAfter",e.createdAfter),e?.branch&&s.set("branch",e.branch);let r=s.toString(),c=await i(o,n,`/apps/${t}/deployments/latest${r?`?${r}`:""}`,{method:"GET"});if(!c.ok){let d=await c.text().catch(()=>"");throw new Error(`Latest deployment lookup failed: ${c.status} ${d}`)}let p=await c.json().catch(()=>({}));return p.deployment?{id:p.deployment.id,status:p.deployment.status}:null}a(F,"getLatestDeploymentForApp");async function H(o,n,t){let e=await i(o,n,`/apps/deployments/${t}`,{method:"GET"});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`Deployment fetch failed: ${e.status} ${r}`)}return(await e.json().catch(()=>({}))).deployment??null}a(H,"getDeploymentDetail");var V=new URL(I).hostname,D=new URL(v).hostname;async function ae(o,n,t){let e=new URLSearchParams;t?.handle&&e.set("handle",t.handle),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&e.set("limit",String(Math.max(1,Math.floor(t.limit)))),typeof t?.offset=="number"&&Number.isFinite(t.offset)&&e.set("offset",String(Math.max(0,Math.floor(t.offset)))),typeof t?.includeScheduled=="boolean"&&e.set("includeScheduled",t.includeScheduled?"true":"false");let s=e.toString(),r=await i(o,n,`/apps/list${s?`?${s}`:""}`,{method:"GET"});if(!r.ok){let p=await r.text().catch(()=>"");throw new Error(`Apps list failed: ${r.status} ${p}`)}let c=await r.json().catch(()=>({}));return Array.isArray(c.apps)?c.apps:[]}a(ae,"listApps");async function ie(o,n,t){let e=await i(o,n,"/api/projects/local",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Create project failed: ${e.status} ${s}`)}return await e.json()}a(ie,"createLocalProject");async function ce(o,n,t){let e=await i(o,n,"/apps/repo/create",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Repo create failed: ${e.status} ${s}`)}return await e.json()}a(ce,"createRepo");async function pe(o,n,t,e){let s=await i(o,n,`/apps/${encodeURIComponent(t)}/code-visibility`,{method:"PATCH",body:JSON.stringify({codeVisibility:e})});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Code visibility update failed: ${s.status} ${r}`)}return await s.json()}a(pe,"updateAppCodeVisibility");async function ue(o,n,t,e){let s=await i(o,n,"/v4/apps/headless",{method:"POST",body:JSON.stringify({items:t,...e?{teamId:e}:{}})});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Headless create failed: ${s.status} ${r}`)}return await s.json()}a(ue,"createHeadlessApps");async function le(o,n,t){let e=await i(o,n,`/v4/apps/${t}/template/status`,{method:"GET"});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Template status failed: ${e.status} ${s}`)}return await e.json()}a(le,"getTemplateStatus");async function de(o,n,t){let e=await i(o,n,`/v4/apps/${t}/template/branches`,{method:"GET"});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Template branches failed: ${e.status} ${s}`)}return await e.json()}a(de,"listTemplateBranches");async function me(o,n,t,e){let s=await i(o,n,`/v4/apps/${t}/template/deploy-latest`,{method:"POST",body:JSON.stringify(e)});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Template deploy failed: ${s.status} ${r}`)}return await s.json()}a(me,"deployLatestTemplate");async function ge(o,n,t,e){let s=await i(o,n,`/v4/apps/${t}/environment`,{method:"POST",body:JSON.stringify(e)});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Environment update failed: ${s.status} ${r}`)}return await s.json()}a(ge,"updateAppEnvironment");async function he(o,n,t){let e=await i(o,n,`/v4/apps/${t}/environment`,{method:"GET"});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Environment get failed: ${e.status} ${s}`)}return await e.json()}a(he,"getAppEnvironment");async function ye(o,n){let t=await i(o,n,"/api/tools/manifest",{method:"GET"});if(!t.ok){let e=await t.text().catch(()=>"");throw new Error(`Manifest fetch failed: ${t.status} ${e}`)}return await t.json()}a(ye,"fetchToolManifest");async function fe(o,n){let t=await i(o,n,"/apps/tools",{method:"GET"});if(!t.ok){let e=await t.text().catch(()=>"");throw new Error(`Tools lookup failed: ${t.status} ${e}`)}return await t.json()}a(fe,"listUserTools");async function Re(o,n,t){let e=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules`,{method:"GET"});if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`Schedules lookup failed: ${e.status} ${r}`)}let s=await e.json().catch(()=>({}));return{schedules:Array.isArray(s.schedules)?s.schedules:[]}}a(Re,"listAppSchedules");async function we(o,n,t={}){let e=new URLSearchParams;t.domain&&e.set("domain",t.domain),t.opentoolVersion&&e.set("opentoolVersion",t.opentoolVersion),typeof t.limit=="number"&&e.set("limit",String(t.limit));for(let c of t.tags??[])e.append("tag",c);let s=e.toString(),r=await i(o,n,`/v1/opentool/recipes${s?`?${s}`:""}`,{method:"GET"});return l(r,"OpenTool recipe list")}a(we,"listOpenToolRecipes");async function Se(o,n,t){let e=await i(o,n,"/v1/opentool/recipes/search",{method:"POST",body:JSON.stringify(t)});return l(e,"OpenTool recipe search")}a(Se,"searchOpenToolRecipes");async function xe(o,n,t){let e=new URLSearchParams;typeof t.includeExamples=="boolean"&&e.set("includeExamples",String(t.includeExamples)),typeof t.includeTests=="boolean"&&e.set("includeTests",String(t.includeTests)),t.opentoolVersion&&e.set("opentoolVersion",t.opentoolVersion);let s=e.toString(),r=await i(o,n,`/v1/opentool/recipes/${encodeURIComponent(t.id)}${s?`?${s}`:""}`,{method:"GET"});return l(r,"OpenTool recipe get")}a(xe,"getOpenToolRecipe");async function Te(o,n,t){let e=await i(o,n,"/v1/opentool/rules",{method:"POST",body:JSON.stringify(t)});return l(e,"OpenTool rules get")}a(Te,"getOpenToolRules");function b(o){let n=new URLSearchParams;typeof o=="number"&&Number.isFinite(o)&&n.set("limit",String(Math.max(1,Math.floor(o))));let t=n.toString();return t?`?${t}`:""}a(b,"buildLimitQuery");function N(o){if(Array.isArray(o))return o;if(!o||typeof o!="object")return[];let n=o;return Array.isArray(n.logs)?n.logs:Array.isArray(n.runs)?n.runs:Array.isArray(n.scheduleRuns)?n.scheduleRuns:Array.isArray(n.items)?n.items:[]}a(N,"normalizeScheduleExecutionLogs");async function Pe(o,n,t,e){let s={...e?.preferredScheduleId?{preferredScheduleId:e.preferredScheduleId}:{},...e?.scheduleId?{scheduleId:e.scheduleId}:{},...e?.startAt?{startAt:e.startAt}:{},...e&&"endAt"in e?{endAt:e.endAt??null}:{}},r=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules/start`,{method:"POST",body:JSON.stringify(s)});return l(r,"Schedule start")}a(Pe,"startAppSchedules");async function Ae(o,n,t){let e=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules/stop`,{method:"POST",body:JSON.stringify({})});return l(e,"Schedule stop")}a(Ae,"stopAppSchedules");async function Ee(o,n){let t=await i(o,n,"/apps/schedules/current/stop",{method:"POST",body:JSON.stringify({})});return l(t,"Current schedule stop")}a(Ee,"stopCurrentAppSchedules");async function Oe(o,n,t){let e=await i(o,n,"/v1/schedules/run",{method:"POST",body:JSON.stringify({scheduleId:t.scheduleId})});return l(e,"Schedule run")}a(Oe,"runScheduleNow");async function be(o,n,t,e){let s=await i(o,n,`/apps/${encodeURIComponent(t)}/schedules/${encodeURIComponent(e)}`,{method:"DELETE"});return l(s,"Schedule delete")}a(be,"deleteOrArchiveSchedule");async function $e(o,n,t,e){let s=await i(o,n,`/v1/schedules/${encodeURIComponent(t)}/execution-logs${b(e?.limit)}`,{method:"GET"}),r=await l(s,"Schedule execution logs");return{logs:N(r)}}a($e,"listScheduleExecutionLogs");async function ke(o,n,t,e){let s=await i(o,n,`/v1/deployments/${encodeURIComponent(t)}/schedule-execution-logs${b(e?.limit)}`,{method:"GET"}),r=await l(s,"Deployment schedule execution logs");return{logs:N(r)}}a(ke,"listDeploymentScheduleExecutionLogs");async function Le(o,n,t){let e=await i(o,n,`/v1/schedule-execution-logs/${encodeURIComponent(t)}`,{method:"GET"});return l(e,"Schedule execution log")}a(Le,"getScheduleExecutionLog");async function ve(o,n,t,e){let s=await i(o,n,`/v1/apps/${encodeURIComponent(t)}/execution-timeline${b(e?.limit)}`,{method:"GET"});return l(s,"App execution timeline")}a(ve,"getAppExecutionTimeline");async function Ie(o,n,t){return i(o,n,"/apps/agent/create",{method:"POST",body:JSON.stringify(t)})}a(Ie,"createAgentFromPrompt");async function De(o,n,t){let e=new URLSearchParams;t?.appId&&e.set("appId",t.appId);let s=e.toString(),r=await i(o,n,`/apps/performance${s?`?${s}`:""}`,{method:"GET"});if(!r.ok){let c=await r.text().catch(()=>"");throw new Error(`Performance lookup failed: ${r.status} ${c}`)}return await r.json()}a(De,"getUserPerformance");async function Ne(o,n,t){let e=new URLSearchParams({appId:t}),s=await i(o,n,`/apps/summary?${e.toString()}`,{method:"GET"});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Summary lookup failed: ${s.status} ${r}`)}return await s.json()}a(Ne,"getAppRuntimeSummary");async function z(o,n){let t=await i(o,n,"/v1/account",{method:"GET"});if(!t.ok){let e=await t.text().catch(()=>"");throw new Error(`Account lookup failed: ${t.status} ${e}`)}return await t.json()}a(z,"getOpenPondAccount");async function qe(o,n){let t=new Date().toISOString(),e=Date.now(),s=o.replace(/\/$/,"");try{let r=await i(s,null,"/health",{method:"GET",headers:{Accept:"application/json"}}),c=Date.now()-e,p=await r.json().catch(()=>({})),d=null,m=null;if(n?.trim())try{let g=await z(s,n);d=!0,m=g.account}catch{d=!1}return{reachable:r.ok,authenticated:d,apiBase:s,latencyMs:c,status:r.status,service:typeof p.service=="string"?p.service:null,checkedAt:t,account:m,...r.ok?{}:{error:r.statusText||`HTTP ${r.status}`}}}catch(r){return{reachable:!1,authenticated:n?.trim()?!1:null,apiBase:s,latencyMs:Date.now()-e,status:null,service:null,checkedAt:t,error:r instanceof Error?r.message:String(r)}}}a(qe,"checkOpenPondApiHealth");async function Ce(o,n,t){let e=await i(o,n,"/apps/assistant/run",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Assistant run failed: ${e.status} ${s}`)}return await e.json()}a(Ce,"runAssistantMode");async function Ue(o,n,t){let e=await i(o,n,"/apps/agent/digest",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Agent digest failed: ${e.status} ${s}`)}return await e.json()}a(Ue,"postAgentDigest");async function _e(o,n,t){let e=await i(o,n,"/apps/tools/execute",{method:"POST",body:JSON.stringify(t)}),s=await e.text().catch(()=>""),r=null;try{r=s?JSON.parse(s):null}catch{r=s}return e.ok?{ok:!0,status:e.status,data:r}:{ok:!1,status:e.status,error:r&&typeof r=="object"&&"error"in r?String(r.error):s||e.statusText}}a(_e,"executeUserTool");async function je(o,n,t){let e=await i(o,n,"/apps/backtests/run",{method:"POST",body:JSON.stringify(t)});if(!e.ok){let s=await e.text().catch(()=>"");throw new Error(`Backtest run failed: ${e.status} ${s}`)}return await e.json()}a(je,"submitBacktestRun");async function Be(o,n,t){let e=t.query&&Object.keys(t.query).length>0?`?${new URLSearchParams(t.query).toString()}`:"",s=await i(o,n,`/apps/backtests/tx${e}`,{method:t.method,body:t.method==="POST"&&t.body!==void 0?JSON.stringify(t.body):void 0});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Backtests request failed: ${s.status} ${r}`)}return await s.json()}a(Be,"submitBacktestTx");async function Ge(o,n,t){let e=new URLSearchParams(t).toString(),s=await i(o,n,`/apps/backtests/detail?${e}`,{method:"GET"});if(!s.ok){let r=await s.text().catch(()=>"");throw new Error(`Backtest detail failed: ${s.status} ${r}`)}return await s.json()}a(Ge,"submitBacktestDetail");function K(o){let n=o.trim().replace(/^\/+/,"");return encodeURIComponent(n||"tool")}a(K,"normalizeToolPathSegment");function W(o){let n=o.replace(/\/$/,""),t=process.env.OPENPOND_TOOL_URL;if(t)return t.replace(/\/$/,"");try{let e=new URL(n),s=e.hostname.toLowerCase(),r=s==="apps.openpond.live"?null:s===V||s===D||s===`www.${D}`||s==="openpond.live"||s==="www.openpond.live"?"https://apps.openpond.live":null;if(r)return r;let c=s==="localhost"||s==="127.0.0.1",p=e.port||(e.protocol==="https:"?"443":"80");if(c&&p==="3000")return n}catch{}return n}a(W,"resolveWorkerBaseUrl");async function Je(o,n,t){let e=W(o),s=K(t.toolName),c=`${t.deploymentId?`/${t.appId}/deployments/${t.deploymentId}`:`/${t.appId}`}/${s}`,p=new Headers(t.headers||{}),d=t.method??"POST",m=t.body===void 0||d==="GET"?void 0:JSON.stringify(t.body),g=await i(e,n,c,{method:d,body:m,headers:p}),h=await g.text().catch(()=>""),u=null;try{u=h?JSON.parse(h):null}catch{u=h}let x=u&&typeof u=="object"&&"ok"in u?!!u.ok:!0,y=g.ok&&x,f=u&&typeof u=="object"&&"status"in u&&Number(u.status)||g.status,R=u&&typeof u=="object"&&"error"in u?String(u.error):g.ok?void 0:h||g.statusText,P=u&&typeof u=="object"&&"data"in u?u.data:u;return{ok:y,status:f,data:P,error:R}}a(Je,"executeHostedTool");import{createHash as Y}from"node:crypto";var X=3600*1e3;function $(o){return Y("sha256").update(JSON.stringify([o.apiBase.replace(/\/$/,""),o.apiKey.trim()])).digest("hex")}a($,"buildCacheKey");async function q(o,n){let t=await L(w(),o,$(n),{allowStale:!0});return!t||Date.now()-Date.parse(t.updatedAt)>=(n.ttlMs??X)?null:t.payload}a(q,"cached");async function ot(o){return q("cloud.apps",o)}a(ot,"getCachedApps");async function st(o){await E(w(),"cloud.apps",$(o),o.apps)}a(st,"setCachedApps");async function rt(o){return q("cloud.tools",o)}a(rt,"getCachedTools");async function at(o){await E(w(),"cloud.tools",$(o),o.tools)}a(at,"setCachedTools");var pt=["openpond-generic-v1","openpond-work-v1","openpond-coding-core-v1","openpond-agent-harness-v1"];export{i as a,_ as b,j as c,B as d,G as e,J as f,M as g,F as h,H as i,ae as j,ie as k,ce as l,pe as m,ue as n,le as o,de as p,me as q,ge as r,he as s,ye as t,fe as u,Re as v,we as w,Se as x,xe as y,Te as z,Pe as A,Ae as B,Ee as C,Oe as D,be as E,$e as F,ke as G,Le as H,ve as I,Ie as J,De as K,Ne as L,z as M,qe as N,Ce as O,Ue as P,_e as Q,je as R,Be as S,Ge as T,W as U,Je as V,X as W,ot as X,st as Y,rt as Z,at as _,pt as $};
@@ -1,5 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as ge,b as Ge}from"./chunk-RELOOVWW.js";import{B as De,D as ze,E as Ne,F as A,G as Ke,H as Fe,l as ue,z as Be}from"./chunk-GIPSOLAY.js";import{a as Q,b as I,c as O,h as Xe,i as fe,j as he}from"./chunk-MJC26GOX.js";import{$a as Ye,D as He,M as $e,Ma as Je,P as pe,_a as Ve,b as le,ga as me,h as X,k as qe,m as Le,v as We,z as Ue}from"./chunk-JUX77H6K.js";import{a as f,e as Ae,i as Te,l as p,m as Me}from"./chunk-HZP5U2AA.js";import{b as t}from"./chunk-ES2ISFJC.js";import{a as c}from"./chunk-FTQLQJQV.js";var j=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(),ye=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 xe=$e.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 E=class extends Error{static{c(this,"OpenPondProtocolError")}code;constructor(e,n){super(n),this.name="OpenPondProtocolError",this.code=e}};function P(o){return JSON.stringify(be(o))}c(P,"canonicalJson");async function Z(o){let e=new TextEncoder().encode(P(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(Z,"canonicalSha256");function be(o){if(o===null||typeof o=="string"||typeof o=="boolean")return o;if(typeof o=="number"){if(!Number.isFinite(o))throw new E("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=>be(e));if(typeof o=="object"){let e=Object.getPrototypeOf(o);if(e!==Object.prototype&&e!==null)throw new E("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 E("non_json_value",`Canonical JSON cannot contain ${typeof s} at ${r}.`);n[r]=be(s)}return n}throw new E("non_json_value",`Canonical JSON cannot contain ${typeof o}.`)}c(be,"normalizeCanonicalJson");var l=t.string().trim().min(1).max(500),v=t.string().regex(/^[a-f0-9]{64}$/),S=t.string().datetime({offset:!0}),_=t.object({id:l,contentHash:v}).strict(),k=_.extend({revision:t.number().int().positive()}).strict(),L=t.object({schemaVersion:t.literal("openpond.baseModelPreference.v1"),modelId:l,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:l.nullable(),source:t.enum(["managed","local","builtin"])}).strict(),Qe=t.enum(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),At=t.object({schemaVersion:t.string().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:Qe,parameterization:t.enum(["lora","full"])}).catchall(t.unknown()),Tt=t.object({profileProjectId:l,sourceRevision:t.string().regex(/^[a-f0-9]{40,64}$/),harnessRelease:_}).strict(),Mt=t.object({profileProjectId:l,sourceRevision:t.string().regex(/^[a-f0-9]{40,64}$/),catalogHash:v,definitionId:l,harnessRelease:_,tasksetRelease:_}).strict(),Ze=t.object({tasksetRef:k.nullable().default(null),evaluationTasksetRef:k.nullable().optional(),profileSource:Tt.nullable().optional(),profileEvaluation:Mt.nullable().optional(),rewardBindingRef:k.nullable().optional(),tasksetRelease:_.nullable().default(null),harnessRelease:_.nullable().default(null),baseModel:L.nullable().default(null),method:Qe.nullable().default(null),destinationId:l.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:At.nullable().default(null),preferredMaximumSpendUsd:t.number().nonnegative().nullable().default(null),preferredRetentionDays:t.number().int().nonnegative().nullable().default(null)}).strict(),et=Ze.omit({managedGpuRequirement:!0}),qt=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:l,projectId:l,portableProjectId:l,revision:t.number().int().positive(),etag:v,syncedSourceRevision:t.number().int().positive(),syncedAt:S,tasksets:t.array(t.object({localTasksetId:l,localTasksetHash:v.nullable().default(null),releaseId:l,releaseRevision:t.number().int().positive(),releaseHash:v,packageHash:v.nullable().default(null),hostedTasksetId:l,syncedAt:S}).strict()).max(1e4).default([])}).strict(),Lt=t.object({localTasksetId:l,releaseId:l,releaseRevision:t.number().int().positive(),releaseHash:v,state:t.enum(["syncing","synced","sync_failed"]),hostedTasksetId:l.nullable().default(null),lastAttemptAt:S,syncedAt:S.nullable().default(null),lastError:t.string().trim().min(1).max(5e3).nullable().default(null)}).strict(),Wt=t.object({schemaVersion:t.literal("openpond.modelProject.v2"),id:l,profileId:l,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:l.nullable(),trainingSetup:Ze,hosted:qt.nullable().default(null),tasksetSyncs:t.array(Lt).max(1e4).default([]),createdAt:S,updatedAt:S}).strict(),Ut=Wt.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),Cn=t.object({schemaVersion:t.literal("openpond.modelProjectSave.v1"),operationId:l,expectedRevision:t.number().int().nonnegative(),project:Ut,learning:xe.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."})}),jn=t.object({schemaVersion:t.literal("openpond.modelProjectConfigurationCheck.v1"),configurationHash:v,projectId:l,expectedRevision:t.number().int().nonnegative(),checkedAt:S,canSave:t.boolean(),deferred:t.array(t.enum(["base_model","taskset"])).max(2),findings:t.array(t.object({code:l,severity:t.enum(["error","warning"]),message:t.string().min(1).max(5e3),field:t.string().min(1).max(500).nullable()}).strict()).max(100)}).strict(),En=t.object({id:l,name:t.string().min(1).max(500),available:t.boolean(),preference:L}).strict();var _n=t.object({schemaVersion:t.literal("openpond.hostedModelProjectSync.v2"),portableProjectId:l,name:t.string().trim().min(1).max(200),objective:t.string().trim().max(5e3).nullable(),defaultBaseModel:L.nullable(),defaultDestinationId:l.nullable(),trainingSetup:et,sourceRevision:t.number().int().positive(),sourceUpdatedAt:S,expectedEtag:v.nullable().default(null)}).strict(),Ht=t.object({id:l,teamId:l,portableProjectId:l,name:t.string().trim().min(1).max(200),objective:t.string().trim().max(5e3).nullable(),defaultBaseModel:L.nullable(),defaultDestinationId:l.nullable(),trainingSetup:et,sourceRevision:t.number().int().positive(),sourceUpdatedAt:S,revision:t.number().int().positive(),etag:v,createdAt:S,updatedAt:S}).strict(),$t=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:S}).strict(),An=t.object({project:Ht,resources:t.array($t).max(1e4),jobCount:t.number().int().nonnegative(),latestJobIds:t.array(l).max(100)}).strict(),Tn=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 tt=t.object({schemaVersion:t.literal("openpond.experimentAttemptGrade.v1"),selectionHash:t.string().regex(/^[a-f0-9]{64}$/),grades:t.array(X).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:Te.nullable(),contentHash:t.string().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((o,e)=>{let{contentHash:n,...r}=o;p(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;p(d)!==a&&e.addIssue({code:"custom",message:"A retained criterion changed."});for(let y of i.components){let{contentHash:x,...g}=y;p(g)!==x&&e.addIssue({code:"custom",message:"A retained grader result changed."})}}});var m=t.string().trim().min(1).max(200),W=t.string().regex(/^[a-f0-9]{64}$/),we=t.discriminatedUnion("kind",[t.object({kind:t.literal("hosted_chat"),modelId:m,messages:ye.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()]),Bt=t.object({schemaVersion:t.literal("openpond.modelStarterAttemptRequest.v1"),operationId:m,teamId:m,modelProjectId:m.nullable(),project:j.optional(),taskset:k,taskId:m,environmentSeed:t.number().int().min(0).max(2147483647).default(0),policy:we}).strict(),Vn=t.object({modelProjectId:m.nullable(),taskset:k,afterTaskId:m.optional(),limit:t.number().int().min(1).max(100).default(25)}).strict(),Yn=t.object({modelProjectId:m.nullable(),taskset:k,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(),ee=t.object({schemaVersion:t.literal("openpond.modelStarterAttemptSummary.v1"),id:m,revision:t.number().int().positive(),request:Bt,status:t.enum(["queued","running","cancelling","completed","failed","cancelled"]),policySnapshot:t.object({modelId:m,provider:m,upstreamModelId:t.string().min(1).max(500),configurationHash:W}).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."})}),Xn=t.object({modelProjectId:m,afterId:m.optional(),limit:t.number().int().min(1).max(100).default(25)}).strict(),Qn=t.object({items:t.array(ee).max(100),nextCursor:m.nullable()}).strict(),Zn=t.object({schemaVersion:t.literal("openpond.modelStarterAttemptResult.v1"),attempt:ee,output:t.string().max(1048576).nullable(),messages:t.array(t.record(t.string(),t.unknown())).max(4002),composition:He.nullable(),grade:X.nullable().optional(),experimentGrade:tt.nullable().optional(),environment:t.object({status:t.enum(["completed","budget_exhausted","cancelled","timed_out","policy_failure","environment_failure"]),collected:t.boolean(),definition:k,initialStateHash:W.nullable(),finalStateHash:W.nullable(),attemptHash:W}).strict(),providerRequestIds:t.array(m).max(1001),contentHash:W}).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 R=t.string().trim().min(1).max(200),nt=t.string().regex(/^[a-f0-9]{64}$/),Dt=t.discriminatedUnion("kind",[we.options[0],t.object({kind:t.literal("fixture")}).strict()]),te=t.object({schemaVersion:t.literal("openpond.modelTasksetRunRequest.v1"),operationId:R,teamId:R,modelProjectId:R.nullable(),name:t.string().trim().min(1).max(200).optional(),project:j.optional(),taskset:k,policy:Dt,population:t.array(Ve).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."})}),rt=t.object({schemaVersion:t.literal("openpond.modelTasksetRunSummary.v1"),id:R,revision:t.number().int().positive(),teamId:R,modelProjectId:R.nullable(),name:t.string().trim().min(1).max(200).optional(),project:j.optional(),operationId:R,taskset:k,policyKind:t.enum(["hosted_chat","fixture"]),manifestHash:nt,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:R,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."})}),ot=t.object({summary:rt,request:te,manifest:Ye,policySnapshot:ee.shape.policySnapshot}).strict(),ur=t.object({modelProjectId:R.optional(),projectId:j.shape.id.optional(),afterId:R.optional(),limit:t.number().int().min(1).max(100).default(25)}).strict(),gr=t.object({items:t.array(rt).max(100),nextCursor:R.nullable()}).strict(),fr=t.object({schemaVersion:t.literal("openpond.modelTasksetRunResult.v1"),run:ot,receipts:t.array(Je).min(1).max(1e4),metric:qe.nullable(),contentHash:nt}).strict();async function ne(o){let e=ot.parse(o),{summary:n,request:r,manifest:s,policySnapshot:i}=e;if(Me(s,"Taskset run manifest"),s.contentHash!==n.manifestHash||s.id!==n.id||s.createdAt!==n.createdAt||n.teamId!==r.teamId||n.modelProjectId!==r.modelProjectId||P(n.project??null)!==P(r.project??null)||P(s.metadata.project??null)!==P(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||P(n.taskset)!==P(r.taskset)||s.tasksetRelease.id!==r.taskset.id||s.tasksetRelease.contentHash!==r.taskset.contentHash||P(s.population)!==P(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(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 Z({policy:r.policy,snapshot:i}))throw new Error("Evaluation model differs from its admitted policy.");return e}c(ne,"verifyModelTasksetRunDetails");var at=t.string().min(1).max(200).refine(o=>!["__proto__","prototype","constructor"].includes(o),"Use an ordinary field name."),zt=t.array(at).min(1).max(20),st=t.enum(["input","output","expectedOutput","evaluatorContext"]),Nt=t.object({destination:st,path:zt,source:st,sourcePath:t.array(at).max(20)}).strict(),U=t.array(Nt).max(100).superRefine((o,e)=>{for(let[n,r]of o.entries())o.slice(0,n).some(s=>s.destination===r.destination&&(it(s.path,r.path)||it(r.path,s.path)))&&e.addIssue({code:"custom",path:[n,"path"],message:"Mapped destination paths must not overlap."})});function it(o,e){return o.length<=e.length&&o.every((n,r)=>n===e[r])}c(it,"prefix");var C=t.string().trim().min(1).max(200),H=t.string().regex(/^[a-f0-9]{64}$/),T=t.object({id:C,revision:t.number().int().positive(),contentHash:H}).strict(),re=t.object({id:C,version:t.string().min(1).max(200),contentHash:H,feedbackKey:We,release:T.nullable(),mappings:U.optional()}).strict(),Kt=t.object({id:C,version:t.string().min(1).max(200),contentHash:H,mappings:U}).strict(),ct=t.object({operationId:C,id:C.optional(),expectedRevision:t.number().int().nonnegative(),request:te,maximumCostUsd:t.number().finite().positive().max(1e4),graders:t.array(Kt).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."})}),Ft=t.object({schemaVersion:t.literal("openpond.experimentDefinition.v1"),id:C,teamId:C,revision:t.number().int().positive(),request:te,maximumCostUsd:t.number().finite().positive().max(1e4),graders:t.array(re).min(1).max(100),createdAt:t.iso.datetime(),updatedAt:t.iso.datetime()}).strict(),Jt=Ft.extend({contentHash:H}),dt=t.object({operationId:C,definition:T}).strict(),lt=t.object({projectId:C.optional(),datasetHash:H.optional(),search:t.string().trim().max(200).optional(),afterId:C.optional(),limit:t.number().int().min(1).max(100).default(30)}).strict(),Or=t.object({definition:T,maximumCostUsd:t.number().finite().positive().max(1e4),graders:t.array(re).min(1).max(100)}).strict();function pt(o){let e=Jt.parse(o),{contentHash:n,...r}=e;if(n!==p(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(pt,"verifyExperimentDefinition");var Se=c(o=>({id:o.id,revision:o.revision,contentHash:o.contentHash}),"experimentDefinitionRef");var $=t.string().trim().min(1).max(200),Pe=t.object({operationId:$,execution:Ae,graders:t.array(Ue).min(1).max(100),maximumCostUsd:t.number().finite().min(1e-6).max(1e4),mappings:t.array(t.object({graderId:$,fields:U}).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."})}),Gt=t.object({schemaVersion:t.literal("openpond.experimentScoringPass.v1"),id:$,teamId:$,revision:t.number().int().positive(),request:Pe,graders:t.array(re).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:$,message:t.string().max(2e3)}).strict().nullable()}).strict(),Vt=Gt.extend({contentHash:t.string().regex(/^[a-f0-9]{64}$/)});function mt(o){let e=Vt.parse(o),{contentHash:n,...r}=e;if(p(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)=>p(i.release)!==p(e.request.graders[a])||p(i.mappings??[])!==p(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(mt,"verifyExperimentScoringPass");var u=t.string().trim().min(1).max(200),ke=class extends Error{constructor(n,r,s){super(s);this.status=n;this.code=r;this.name="OpenPondExperimentError"}status;code;static{c(this,"OpenPondExperimentError")}},oe=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 save(e,n){let r=ct.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||p(s.request)!==p(r.request)||s.maximumCostUsd!==r.maximumCostUsd)throw new Error("Experiment save receipt differs from its submitted configuration.");if(r.graders&&p(r.graders)!==p(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&&p(Se(i))!==p(n.reference))throw new Error("Experiment revision mismatch.");return i}async list(e={},n){let r=lt.parse(e),s=new URLSearchParams(Object.entries(r).map(([d,y])=>[d,String(y)])),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=dt.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(p(Se(i))!==p(r.definition))throw new Error("Experiment Start revision mismatch.");let a=await ne(s.run);if(a.summary.teamId!==this.options.teamId||a.request.operationId!==r.operationId||p(a.request)!==p({...i.request,operationId:r.operationId})||p(a.manifest.metadata.experimentDefinition)!==p(r.definition)||a.manifest.metadata.experimentConfigurationHash!==p({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=ge(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=>ne(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=Pe.parse(e),s=this.pass(await this.request(`/executions/${encodeURIComponent(r.execution.id)}/scoring-passes`,"POST",r,n));if(p(s.request)!==p(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=ge(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:Ge(i,a)}}definition(e,n){let r=pt(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 ne(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=mt(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 ke(i.status,d.success?d.data.code:"experiment_request_failed",d.success?d.data.message:"Experiment request failed.")}return a}};function ut(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(ut,"workSandbox");function Re(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(Re,"configuredEndpoint");function se(o,e){if(!o?.trim())throw new Error(`${e} is required`);return o.trim()}c(se,"configuredKey");var Yt=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 gt(o,e){if(!e)return he(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 Yt.parse(await n.json())}c(gt,"workModelTurn");var Xt="openpond-chat",Qt=24,Zt=4e4,Ie=2e4,Oe="outputs",ve="inputs/previous-outputs",bt="inputs/.openpond-context.json",en=100,ft=100,ht=100*1024*1024,D=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=ut(e.sandboxes,e.sandboxConfig),this.#o=e.defaultModel??Xt,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 b=>e.onEvent?.(b),"emit"),s=e.cleanup??"keep",i=rn(s),a=null,d=null,y=!1,x=xt(e.maxSteps,1,100,Qt),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 b=[{role:"system",content:nn(a.id,(e.inputs?.length??0)>0)},...(e.history??[]).map(w=>({...w})),{role:"user",content:n}];for(let w=1;w<=x;w+=1){e.signal?.throwIfAborted(),await r({type:"status",message:`Thinking \xB7 step ${w}`});let _e=(await gt({apiBaseUrl:this.#t,token:this.#e,model:e.model?.trim()||this.#o,messages:b,tools:tn,toolChoice:"auto",signal:e.signal,metadata:{source:"openpond-sdk-work",sandboxId:a.id,apiBaseUrl:this.#n,...e.metadata}},this.#s)).choices?.[0],G=_e?.message?.content?.trim()??"",V=_e?.message?.tool_calls??[];if(b.push({role:"assistant",content:G||null,...V.length>0?{tool_calls:V}:{}}),G&&(g=G,await r({type:"assistant",text:G})),V.length===0){let q=await this.#d(a.id,d);for(let de of q)await r({type:"output",output:de});y=!0,await this.#i(a.id,q,e,i,r);let Y={sandboxId:a.id,text:g,steps:w,outputs:q,lifecycle:i};return await r({type:"done",...Y}),Y}for(let[q,Y]of V.entries()){e.signal?.throwIfAborted();let de=await this.#f(a.id,Y,q,e.timeoutSeconds,r);b.push(de)}}throw new Error(`Work did not finish within ${x} steps`)}catch(b){if(a&&d&&!y)try{let w=await this.#d(a.id,d);for(let Ee of w)await r({type:"output",output:Ee});await this.#i(a.id,w,e,i,r)}catch(w){yt(b,i,w)}throw yt(b,i),b}}async deleteSandbox(e){try{if((await this.#r.get(e)).state==="deleted")return;await this.#r.delete(e)}catch(n){if(n instanceof Q&&n.status===404)return;throw n}}async#m(e,n){if(n.length===0)return;if(n.length>ft)throw new Error(`Work inputs exceed the ${ft} file limit`);if(n.reduce((a,d)=>a+Buffer.byteLength(d.contentsBase64,"base64"),0)>ht)throw new Error(`Work inputs exceed the ${ht} byte limit`);await this.#r.mkdir(e,{path:ve,recursive:!0});let s=new Set,i=[];for(let[a,d]of n.entries()){let y=sn(d,a,s),x=`${ve}/${y}`;await this.#r.uploadFileBase64(e,x,d.contentsBase64),i.push({id:d.id,path:x,name:d.name,mimeType:d.mimeType??null,checksumSha256:d.checksumSha256??null,revision:d.revision??null,metadata:d.metadata??{}})}await this.#r.uploadFile(e,bt,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=on(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 y=B(d);throw s.persistence.status="failed",s.persistence.error=y,await i({type:"persistence",output:a,status:"failed",error:y}),(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=B(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:Oe,recursive:!0}),an(await this.#l(e))}async#d(e,n){return(await this.#l(e)).filter(s=>n.get(s.path)!==wt(s)).sort((s,i)=>s.path.localeCompare(i.path)).slice(0,en).map(cn)}async#l(e){return(await this.#r.listFiles(e,{path:Oe,recursive:!0,maxEntries:500})).files.filter(r=>r.type==="file"&&!St(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
- `)}`:""}`);await mn(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 y;try{y=JSON.parse(n.function?.arguments||"{}")}catch(g){return M(a,{error:`Invalid tool arguments: ${B(g)}`})}let x=typeof y.command=="string"?y.command.trim():"";if(!x)return M(a,{error:"command is required"});if(x.length>Ie){let g=`command exceeds the ${Ie} character limit`;return await i({type:"tool",toolCallId:a,command:x,status:"failed",output:g}),M(a,{status:"failed",error:g})}await i({type:"tool",toolCallId:a,command:x,status:"started"});try{let g=await this.#r.exec(e,{command:x,timeoutSeconds:xt(s,1,900,180)}),b=pn(g.command.output,Zt),w=g.command.status==="succeeded"?"succeeded":"failed";return await i({type:"tool",toolCallId:a,command:x,status:w,output:b,exitCode:g.command.exitCode}),M(a,{status:g.command.status,exitCode:g.command.exitCode,output:b})}catch(g){if(g instanceof Q)throw g;let b=B(g);return await i({type:"tool",toolCallId:a,command:x,status:"failed",output:b}),M(a,{status:"failed",error:b})}}},tn=[{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:Ie,description:"Shell command to execute."}},required:["command"]}}}];function nn(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/${ve}; their manifest is /workspace/${bt}.`,"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 ${Oe}. 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
- `)}c(nn,"systemPrompt");function rn(o){return{cleanupPolicy:o,persistence:{status:"not_requested",outputCount:0,persistedCount:0},cleanup:{status:"not_requested"}}}c(rn,"initialLifecycle");function on(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(on,"lazyOutputDownload");function sn(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(sn,"uniqueInputName");function yt(o,e,n){!o||typeof o!="object"||Object.assign(o,{workLifecycle:e,...n?{workFinalizationError:B(n)}:{}})}c(yt,"attachWorkFailure");function an(o){return new Map(o.map(e=>[e.path,wt(e)]))}c(an,"outputSignatures");function wt(o){return`${o.sizeBytes}:${o.updatedAt}`}c(wt,"outputSignature");function cn(o){let e=St(o.path).split("/").at(-1)||o.path,n=dn(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(cn,"workOutputFromFile");function St(o){return o.replaceAll("\\","/")}c(St,"normalizedOutputPath");function dn(o){let e=o.toLowerCase().match(/\.[^.]+$/)?.[0]??"";return ln[e]??"application/octet-stream"}c(dn,"workOutputMimeType");var ln=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 xt(o,e,n,r){return Number.isFinite(o)?Math.min(n,Math.max(e,Math.floor(o))):r}c(xt,"boundedInteger");function pn(o,e){return o.length<=e?o:`${o.slice(0,e)}
5
- \u2026 output truncated by openpond-sdk`}c(pn,"truncate");function B(o){return o instanceof Error?o.message:String(o)}c(B,"errorMessage");function mn(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(mn,"sleep");import{promises as Pt}from"node:fs";var z=class{static{c(this,"OpenPondProjectActionsClient")}#e;#n;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl.replace(/\/+$/,"")}async list(e){let n=await I(this.#n,this.#e,ie(e.projectId,"releases",e.teamId));return(await O(n,"List Project Action releases")).releases}async catalog(e){let n=await I(this.#n,this.#e,ie(e.projectId,"catalog",e.teamId));return(await O(n,"Get Project Action catalog")).catalog}async publish(e){let[n,r]=await Promise.all([Pt.readFile(e.build.bundlePath),Pt.readFile(e.build.runnerPath)]),s=await I(this.#n,this.#e,ie(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 O(s,"Publish Project Actions")).release}async run(e){let n=await I(this.#n,this.#e,ie(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 O(n,"Run Project Action")).invocation}};function ie(o,e,n){return`/v1/project-actions/${encodeURIComponent(o)}/${e}?teamId=${encodeURIComponent(n)}`}c(ie,"projectActionPath");var K=class{static{c(this,"OpenPondProfileActionsClient")}#e;#n;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl.replace(/\/+$/,"")}async catalog(e){let n=N(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 I(this.#n,this.#e,`/v1/profile/actions?${r.toString()}`);return(await O(s,"Get Profile Action catalog")).catalog}async run(e){let n=N(e.teamId,"teamId"),r=N(e.actionKey,"actionKey"),s=N(e.idempotencyKey,"idempotencyKey"),i=N(e.catalogVersion,"catalogVersion"),a=await I(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 O(a,"Run Profile Action")}};function N(o,e){let n=o.trim();if(!n)throw new Error(`${e} is required`);return n}c(N,"requiredValue");import{randomUUID as kt}from"node:crypto";var F=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()||kt()}),signal:n.signal})}async update(e,n,r={}){return this.#t(`/schedules/${encodeURIComponent(Ce(e,"scheduleId"))}`,"Update Workflow",{method:"PATCH",body:JSON.stringify(n),signal:r.signal})}async delete(e,n={}){return this.#t(`/schedules/${encodeURIComponent(Ce(e,"scheduleId"))}`,"Delete Workflow",{method:"DELETE",signal:n.signal})}async runNow(e,n={},r={}){return this.#t(`/schedules/${encodeURIComponent(Ce(e,"scheduleId"))}/run`,"Run Workflow",{method:"POST",body:JSON.stringify({clientRequestId:n.clientRequestId?.trim()||kt()}),signal:r.signal})}async#t(e,n,r={}){let s=await I(this.#n,this.#e,`/v1/saved-work${e}`,r);return O(s,n)}};function Ce(o,e){let n=o.trim();if(!n)throw new Error(`${e} is required`);return n}c(Ce,"requiredId");var ae=t.object({id:f,scope:f,sourceId:f,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(),Rt=t.string().regex(/^opk_key_[A-Za-z0-9]{16}_[A-Za-z0-9]{48}$/),ce=t.discriminatedUnion("action",[t.object({action:t.literal("create"),scope:f,sourceId:f,name:t.string().trim().min(1).max(100),expiresAt:t.iso.datetime(),operationId:f,apiKey:Rt}).strict(),t.object({action:t.literal("list"),scope:f,sourceId:f,afterId:f.optional(),limit:t.number().int().min(1).max(100).default(30)}).strict(),t.object({action:t.literal("revoke"),scope:f,sourceId:f,id:f}).strict()]),It=t.object({credential:ae,apiKey:Rt}).strict(),Ot=t.object({items:t.array(ae).max(100),nextCursor:f.nullable()}).strict(),vt=t.object({scope:f,sourceId:f}).strict(),Ct=t.object({scope:f,source:pe,taskDefinition:pe,enabled:t.boolean(),allowedSplits:t.array(Le).min(1).max(4)}).strict();var un=t.object({batchId:t.string().trim().min(1).max(500),modelProjectId:t.string().trim().min(1).max(500)}).strict(),gn=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(),h=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")}},J=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={}){ze(e);let r=Ne.parse({scope:this.#e.scope,command:e}),s=Fe.parse(await this.#t("commands",r,n));if(s.operationId!==e.operationId)throw new h(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 ue[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=Ke.parse(await this.#t("read",r,n));if(!me(s.evidence,e))throw new h(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=De.parse(await this.#t("read",r,n));if(s.modelProjectId!==e)throw new h(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=Be.parse(await this.#t("read",r,n));if(!me(s.policy,e))throw new h(502,"policy_identity_mismatch","Inspection did not match the requested policy release.",null);return s}async createSourceCredential(e,n={}){let r=ce.parse({...e,action:"create",scope:this.#e.scope}),s=It.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 h(502,"credential_identity_mismatch","Credential response did not match the prepared credential.",null);return s}async listSourceCredentials(e,n={},r={}){let s=ce.parse({...n,action:"list",scope:this.#e.scope,sourceId:e}),i=Ot.parse(await this.#t("credentials",s,r));if(i.items.length>(n.limit??30))throw new h(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=ce.parse({action:"revoke",scope:this.#e.scope,sourceId:e,id:n}),i=ae.parse(await this.#t("credentials",s,r));if(this.#n(i,e),i.id!==n||i.revokedAt===null)throw new h(502,"credential_revocation_mismatch","Credential revocation did not match the requested credential.",null);return i}async sourceConfiguration(e,n={}){let r=vt.parse({scope:this.#e.scope,sourceId:e}),s=Ct.parse(await this.#t("source-config",r,n));if(s.scope!==this.#e.scope||s.source.id!==e)throw new h(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 h(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(ue[e]).max(100),nextCursor:t.string().nullable()}).strict().parse(await this.#t("read",s,r))}async publishBatch(e,n={}){let r=un.parse(e),s=gn.parse(await this.#t("publish-batch",{...r,scope:this.#e.scope},n));if(s.batchId!==r.batchId)throw new h(502,"batch_identity_mismatch","Published batch response did not match the requested batch.",null);return s}async#t(e,n,r){le(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 fn(s);if(!s.ok){let a=t.object({code:t.string().optional(),error:t.string().optional()}).passthrough().safeParse(i);throw new h(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 fn(o){let n=o.body?.getReader();if(!n)throw new h(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 h(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 le(a,16777216),a}finally{await n.cancel(),n.releaseLock()}}c(fn,"readBoundedLearningResponse");var je=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:Re(e.sandbox.endpoint,"Sandbox endpoint"),apiKey:se(e.sandbox.apiKey,"Sandbox API key")}:void 0,s=e.model?{endpoint:Re(e.model.endpoint,"Model endpoint"),apiKey:se(e.model.apiKey,"Model API key"),model:se(e.model.model,"Model ID")}:void 0,i=e.baseUrl?.trim()||"https://api.openpond.ai";this.learning=a=>new J({apiKey:n,baseUrl:i,scope:a}),this.experiments=a=>new oe({apiKey:n,baseUrl:i,teamId:a}),this.sandboxes=Xe({apiKey:r?.apiKey??n,baseUrl:i,sandboxApiUrl:r?.endpoint??e.sandboxApiUrl,customEndpoint:!!r}),this.work=new D({apiKey:s?.apiKey??n,apiBaseUrl:i,chatApiBaseUrl:s?.endpoint||e.chatApiUrl?.trim()||fe({apiBaseUrl:i,env:{}}),sandboxes:this.sandboxes,sandboxConfig:r,defaultModel:s?.model,customModel:!!s}),this.workflows=new F({apiKey:n,apiBaseUrl:i}),this.actions=new z({apiKey:n,apiBaseUrl:i}),this.profileActions=new K({apiKey:n,apiBaseUrl:i})}};function Qo(o){return new je(o)}c(Qo,"createOpenPondClient");export{P as a,_ as b,k as c,L as d,At as e,ct as f,dt as g,Se as h,Pe as i,oe as j,Qo as k};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{i as a,j as b,k as c}from"./chunk-ZO7DTED5.js";import"./chunk-FVALIUVY.js";import"./chunk-25OT6IYM.js";import"./chunk-R6DWG5A4.js";import"./chunk-L6ELXODL.js";import"./chunk-PKBU37CH.js";import"./chunk-6GLGOIMQ.js";import"./chunk-XHJUP7M4.js";import"./chunk-7BGT6Q2D.js";import"./chunk-SBBXUZWL.js";import"./chunk-L3KS6MOV.js";import"./chunk-SHCRE7B2.js";import"./chunk-MRGA6BKG.js";import"./chunk-6MI4KKWF.js";import"./chunk-WCZRDULE.js";import"./chunk-GIPSOLAY.js";import"./chunk-MJC26GOX.js";import"./chunk-JUX77H6K.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as resolveWebLaunchMessages,c as runOpenPondAppServerCli,b as runOpenPondServerCli};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as f}from"./chunk-FKVP26MC.js";import"./chunk-P5CFBE6Z.js";import"./chunk-3M53YXEI.js";import{$a as I,Ba as J,Qa as N,Ra as q,Ua as k,Wa as A,X as d,Xa as B,Y as w,_ as b,_a as H,hb as E,ib as M,ja as C,jb as T,la as m,ma as j,na as x,oa as F,pa as v,qa as P}from"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import{d as O,f as S,h as g}from"./chunk-H7IWJN7L.js";import{a as l}from"./chunk-FTQLQJQV.js";import R from"node:path";import{readFile as p}from"node:fs/promises";var n=l((t,s)=>typeof t[s]=="string"?t[s]:void 0,"stringOption");function a(t){console.log(JSON.stringify(t,null,2))}l(a,"print");function U(t,s){let i=n(t,"keyPath");if(i){let r=JSON.parse(i);if(Array.isArray(r)&&r.length&&r.every(c=>typeof c=="string"&&c.length))return r;throw new f("--key-path must be a JSON array of key segments.")}if(!s)throw new f("Specify a setting key, or --key-path for keys containing dots.");return s.split(".")}l(U,"keyPath");async function G(t,s){let i=S({home:n(t,"home")}),r=s[0]??"get",c=g(i).config;if(r==="path"){console.log(c);return}if(r==="export"){let e=await T(i),o=n(t,"file");o?(await b(R.resolve(o),JSON.stringify(e,null,2),{privateParent:!1}),a({path:R.resolve(o),requiresRebinding:e.requiresRebinding})):a(e);return}if(r==="backup"||r==="restore"){let e=n(t,"file"),o=n(t,"keyFile");if(!e||!o)throw new f(`config ${r} requires --file <encrypted-backup> and --key-file <separate-32-byte-key-file>.`);let u=await p(o),y=u.length===32?u:Buffer.from(u.toString("utf8").trim(),"base64");try{a(r==="backup"?await E(i,e,y):await M(e,i,y))}finally{y.fill(0),u.fill(0)}return}if(r==="collect-orphans"){a(await N(i));return}if(r==="schema"){a(F());return}if(r==="migrate"){let e=n(t,"resolutionFile"),o=e?q.parse(JSON.parse(await p(e,"utf8"))):void 0;a(await k(i,{resolutions:o,sourceAppHome:n(t,"sourceAppHome"),sourceConfig:n(t,"sourceConfig"),sourceBrowserState:n(t,"sourceBrowserState"),dryRun:t.dryRun===!0||t.dryRun==="true"}));return}if(r==="recover"){let e=n(t,"revision");a(e?await x(i,e,n(t,"expectedRevision")??d(await w(c))):await A(i));return}if(r==="restart-migration"){a(await B(i));return}if(r==="effective"){a(await I(i,{projectRoot:n(t,"projectRoot"),accountId:n(t,"accountId")}));return}if(r==="trust"||r==="untrust"){let e=n(t,"projectRoot")??s[1];if(!e)throw new f("Specify the canonical project root with --project-root.");await H(i,e,n(t,"accountId")??"local",r==="trust"),a({root:e,trusted:r==="trust"});return}if(r==="revisions"){a(await m(i));return}if(r==="validate"){let e=n(t,"file")??c;C(await p(e,"utf8"),e,t.project===!0||t.project==="true"?"project":"user"),a({valid:!0,path:e});return}if(r==="replace"){let e=n(t,"file");if(!e)throw new f("config replace requires --file <validated-toml-file>.");a(await j(i,n(t,"expectedRevision")??d(await w(c)),await p(e,"utf8")));return}if(r==="doctor"){let e=await w(c),o=null;try{await v(i)}catch(u){o=O(u,c)}a({home:i,path:c,rawRevision:d(e),issue:o,recoverableRevisions:await m(i),migration:await w(R.join(g(i).runtime,"migration.json"))!==null}),o&&(process.exitCode=1);return}if(await k(i),r==="clear-cache"){await J(i),a({cleared:!0,path:g(i).cache});return}let h=await v(i);if(r==="get"){if(!s[1]&&!t.keyPath){a(h);return}let e=h.document;for(let o of U(t,s[1]))e=e&&typeof e=="object"?e[o]:void 0;a(e??null);return}if(r==="set"||r==="unset"){let e=U(t,s[1]),o;if(r==="set"){let u=n(t,"value")??s[2];if(u===void 0)throw new f("config set requires a value. Use JSON for arrays, tables, numbers and booleans.");try{o=JSON.parse(u)}catch{o=u}}a(await P(i,n(t,"expectedRevision")??h.rawRevision,[r==="set"?{op:"set",path:e,value:o}:{op:"unset",path:e}]));return}throw new f(`Unknown config command: ${r}`)}l(G,"runConfigurationCommand");export{G as runConfigurationCommand};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-ZPGTGQJT.js";import"./chunk-FUFIZ37W.js";import"./chunk-3HQEEZPO.js";import"./chunk-BSHAIAXY.js";import"./chunk-FKVP26MC.js";import"./chunk-P5CFBE6Z.js";import"./chunk-XWPC3AN4.js";import"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-TZNKOKQJ.js";import"./chunk-SHCKK3SU.js";import"./chunk-AOBTILU5.js";import"./chunk-GLUWATL5.js";import"./chunk-RELOOVWW.js";import"./chunk-GIPSOLAY.js";import"./chunk-MJC26GOX.js";import"./chunk-JUX77H6K.js";import"./chunk-QUNRWDVO.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{m as resolveGitBranch,f as runAccount,j as runBacktestRun,p as runCheckUpdate,k as runDeployWatch,g as runHealth,d as runLogin,o as runOpentool,e as runProfiles,l as runRepoCreate,n as runRepoPush,b as runTemplateBranches,a as runTemplateStatus,c as runTemplateUpdate,h as runToolList,i as runToolRun};
@@ -1,3 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{u as f}from"./chunk-FUFIZ37W.js";import"./chunk-3HQEEZPO.js";import"./chunk-BSHAIAXY.js";import{a as c}from"./chunk-FKVP26MC.js";import"./chunk-P5CFBE6Z.js";import"./chunk-XWPC3AN4.js";import{c as p,f as u}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-TZNKOKQJ.js";import"./chunk-SHCKK3SU.js";import"./chunk-AOBTILU5.js";import"./chunk-GLUWATL5.js";import"./chunk-RELOOVWW.js";import"./chunk-GIPSOLAY.js";import"./chunk-MJC26GOX.js";import"./chunk-JUX77H6K.js";import"./chunk-QUNRWDVO.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as r}from"./chunk-FTQLQJQV.js";import d from"node:path";import{access as v}from"node:fs/promises";import{constants as C}from"node:fs";import{createRequire as P}from"node:module";var l=d.join("scripts","desktop-harness.ts");async function $(n,t){let o=await j({options:n,rest:t}),e=await f(o.command,o.args,{cwd:o.cwd,inherit:!0,timeoutMs:0});if(e.code!==0)throw new m(e.code)}r($,"runDesktopTestCommand");async function j(n){let t=n.options,o=n.rest,e=o[0];if(e!=="run"&&e!=="attach")throw new c(D());let a=o.slice(1);if(a.length===0)throw new c("usage: openpond desktop-test run <scenario...> [options]");let g=p(t,"cwd")||n.cwd||process.cwd(),w=await O(g),k=(n.env??process.env).OPENPOND_NODE_BINARY?.trim()||process.execPath,s=[P(import.meta.url).resolve("tsx/cli"),l,"run",...a],h=x(t,e);return h&&s.push(`--${h}`),i(s,"--app",t,"app"),i(s,"--server",t,"server"),i(s,"--token",t,"token"),i(s,"--token-file",t,"tokenFile"),i(s,"--devtools-port",t,"devtoolsPort"),i(s,"--artifacts-dir",t,"artifactsDir"),H(s,t),i(s,"--grep",t,"grep"),i(s,"--timeout-ms",t,"timeoutMs"),u(t.keepHome)&&s.push("--keep-home"),{command:k,args:s,cwd:w}}r(j,"buildDesktopHarnessInvocation");async function O(n){let t=d.resolve(n);for(;;){let o=d.join(t,l);if(await R(o))return t;let e=d.dirname(t);if(e===t)throw new c(`Could not find ${l}. Run this command from the OpenPond source checkout or pass --cwd <repo>.`);t=e}}r(O,"resolveDesktopHarnessRepoRoot");function x(n,t){let o=t==="attach"?"attach":null;for(let e of["isolated","attach","packaged","none"])if(u(n[e])){if(o&&o!==e)throw new c("Choose only one desktop harness launch mode: --isolated, --attach, --packaged, or --none.");o=e}return o}r(x,"resolveLaunchMode");function i(n,t,o,e){let a=p(o,e);a&&n.push(t,a)}r(i,"appendStringFlag");function H(n,t){let o=p(t,"json"),e=p(t,"jsonPath");if(o&&y(o))throw new c("harness --json requires a report path. Use --json <path> or --json-path <path>.");if(o&&e&&o!==e)throw new c("Use only one JSON report path: --json <path> or --json-path <path>.");let a=o||e;a&&n.push("--json",a)}r(H,"appendJsonFlag");function y(n){return/^(true|false|1|0|yes|no)$/i.test(n)}r(y,"isBooleanLiteral");async function R(n){try{return await v(n,C.R_OK),!0}catch{return!1}}r(R,"fileExists");function D(){return["usage: openpond desktop-test run <scenario...> [options]"," openpond desktop-test attach <scenario...> [options]","","Options include --isolated, --attach, --packaged, --none, --app <path>,","--server <url>, --token <token>, --token-file <path>, --devtools-port <port>, --artifacts-dir <path>,","--json <path>, --json-path <path>, --grep <pattern>, --timeout-ms <ms>,","--keep-home, and --cwd <repo>."].join(`
3
- `)}r(D,"desktopHarnessCliUsage");var m=class extends Error{static{r(this,"HarnessCommandFailedError")}exitCode;constructor(t){let o=typeof t=="number"&&t>0?t:1;super(`desktop harness failed with exit code ${o}`),this.name="HarnessCommandFailedError",this.exitCode=o}};export{j as buildDesktopHarnessInvocation,O as resolveDesktopHarnessRepoRoot,$ as runDesktopTestCommand};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{$ as q,$a as xa,Aa as Y,Ba as Z,Ca as _,Da as $,Ea as aa,Fa as ba,Ga as ca,Ha as da,Ia as ea,Ja as fa,Ka as ga,La as ha,Ma as ia,Na as ja,Oa as ka,Pa as la,Qa as ma,Ra as na,Sa as oa,Ta as pa,Ua as qa,Va as ra,W as l,Wa as sa,X as m,Xa as ta,Y as n,Ya as ua,Z as o,Za as va,_ as p,_a as wa,aa as r,ab as ya,ba as s,bb as za,ca as t,cb as Aa,da as u,db as Ba,ea as v,eb as Ca,fa as w,fb as Da,ga as x,gb as Ea,ha as y,hb as Fa,ia as z,ib as Ga,ja as A,jb as Ha,ka as B,kb as Ia,la as C,ma as D,na as E,oa as F,pa as G,qa as H,ra as I,sa as J,ta as K,ua as L,va as M,wa as N,xa as O,ya as W,za as X}from"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import{a,b,c,d,e,f,g,h,i,k as j,l as k,m as P,n as Q,o as R,p as S,q as T,r as U,s as V}from"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{Ca as CLIENT_CHOICE_KEYS,Ba as ClientChoicesSchema,w as ConfigSchema,v as CredentialReferenceSchema,L as LAYOUT_PREFERENCE_KEYS,l as MISSING_REVISION,na as MigrationResolutionsSchema,P as PERSISTENCE_TABLES_SQL,c as PersistenceError,ea as accountId,r as acquireFileLock,ja as artifactReference,za as assertConfigRunCurrent,Ia as assertHomeCompatible,k as assertStorageAncestors,p as atomicWriteFile,b as bindHomeCallbacks,ya as captureConfigRun,Z as clearCache,ma as collectArtifactOrphans,F as configEditorSchema,C as configRecoveryRevisions,N as configToPreferences,da as credentialVersions,ba as deleteCredential,V as deleteLocalRecord,y as diffConfig,Aa as effectivePreferences,g as expandHome,Fa as exportRecoveryBackup,Ha as exportSettings,m as fileRevision,S as getLocalRecord,qa as initializeHome,e as isMissing,O as layoutPreferences,Y as listCache,T as listLocalRecords,J as mergeConfig,ca as newCredentialId,Q as openStorageDatabase,H as patchConfig,d as persistenceIssue,M as preferencesToConfig,o as privateDirectory,s as processIsDead,j as protectPrivateDirectory,ia as publishManagedArtifact,U as putLocalRecord,fa as readAccountConfiguration,W as readCache,Da as readClientChoices,G as readConfig,_ as readCredential,$ as readCredentials,t as readJsonFile,oa as readMigrationJournal,n as readOptionalFile,ua as readPreferences,sa as recoverMigration,la as releaseArtifactReference,B as rememberValidConfig,D as replaceConfigText,i as resolveConfigPath,xa as resolveEffectiveConfig,f as resolveOpenPondHome,pa as resolveStoredPath,ta as restartMigration,E as restoreConfigRevision,Ga as restoreRecoveryBackup,z as serializeConfig,wa as setProjectTrust,h as storagePaths,ga as updateAccountConfiguration,Ea as updateClientChoices,I as updateConfig,u as updateJsonFile,va as updatePreferences,x as validateConfigDocument,A as validateConfigText,ha as validateManagedArtifacts,ra as validateMigratedHome,K as watchConfig,q as withFileLock,R as withLocalDatabase,ka as withManagedArtifact,a as withOpenPondHome,X as writeCache,aa as writeCredential};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-FUFIZ37W.js";import{c as w}from"./chunk-3HQEEZPO.js";import{c as S,f as I}from"./chunk-BSHAIAXY.js";import"./chunk-FKVP26MC.js";import"./chunk-P5CFBE6Z.js";import"./chunk-XWPC3AN4.js";import{c as s}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import{f as m,g as x,h,i as g,j as E}from"./chunk-TZNKOKQJ.js";import"./chunk-SHCKK3SU.js";import{d as p}from"./chunk-AOBTILU5.js";import{b as u}from"./chunk-GLUWATL5.js";import"./chunk-RELOOVWW.js";import"./chunk-GIPSOLAY.js";import"./chunk-MJC26GOX.js";import"./chunk-JUX77H6K.js";import"./chunk-QUNRWDVO.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as d}from"./chunk-FTQLQJQV.js";import{readFile as q,stat as y}from"node:fs/promises";async function D(n,o){let[e,i]=o,l=s(n,"team");if(!l||!e||o.length>(e==="compare"?3:2))throw new Error("usage: experiments <save|read|list|executions|start|status|cancel|retry|score|passes|pass|cancel-pass|pass-result|result|compare> [id] [candidate-id] --team <id> [--input-file <path>] [--operation-id <id>]");let f=await p(),_={teamId:l,apiKey:await w(f,I(f)),baseUrl:S(n)??f.apiBaseUrl??u},r=new E(_),t;if(e==="save"){let a=s(n,"inputFile");if(!a||i)throw new Error("Saving requires --input-file with the complete configuration and stable operationId.");if((await y(a)).size>1048576)throw new Error("Experiment input exceeds one MiB.");t=await r.save(m.parse(JSON.parse(await q(a,"utf8"))))}else if(e==="list"){if(i)throw new Error("List does not accept an Experiment id.");let a=s(n,"limit");t=await r.list({projectId:s(n,"project")||void 0,datasetHash:s(n,"datasetHash")||void 0,search:s(n,"search")||void 0,afterId:s(n,"afterId")||void 0,...a?{limit:Number(a)}:{}})}else{if(!i)throw new Error(`${e} requires an id.`);if(e==="read")t=await r.get(i);else if(e==="start"){let a=s(n,"operationId");if(!a)throw new Error("Start requires --operation-id. Reuse it after a transport failure; use a new id for another execution.");let c=await r.get(i);t=await r.start(x.parse({operationId:a,definition:h(c)}))}else if(e==="executions")t=await r.executions(i,{afterId:s(n,"afterId")||void 0});else if(e==="status")t=await r.execution(i);else if(e==="cancel")t=await r.cancel(i);else if(e==="retry"){let a=s(n,"operationId");if(!a)throw new Error("Retry requires a stable --operation-id for the new execution.");t=await r.retry(i,a)}else if(e==="score"){let a=s(n,"inputFile");if(!a||(await y(a)).size>1048576)throw new Error("Score requires --input-file containing an exact execution reference, grader releases and explicit ceiling, within one MiB.");let c=g.parse(JSON.parse(await q(a,"utf8")));if(c.execution.id!==i)throw new Error("Scoring input belongs to a different execution.");t=await r.score(c)}else if(e==="passes")t=await r.scoringPasses(i,{afterId:s(n,"afterId")||void 0});else if(e==="pass")t=await r.scoringPass(i);else if(e==="cancel-pass")t=await r.cancelScoringPass(i);else if(e==="pass-result")t=await r.scoringResult(i);else if(e==="result")t=await r.result(i);else if(e==="compare"){if(!o[2])throw new Error("Compare requires a baseline and candidate execution id.");t=await r.compare(i,o[2])}else throw new Error(`Unknown Experiment action: ${e}`)}console.log(JSON.stringify(t,null,2))}d(D,"runExperimentsCommand");export{D as runExperimentsCommand};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{j as a,k as b}from"./chunk-R6DWG5A4.js";import"./chunk-L6ELXODL.js";import"./chunk-PKBU37CH.js";import"./chunk-6GLGOIMQ.js";import"./chunk-XHJUP7M4.js";import"./chunk-7BGT6Q2D.js";import"./chunk-SBBXUZWL.js";import"./chunk-L3KS6MOV.js";import"./chunk-SHCRE7B2.js";import"./chunk-MRGA6BKG.js";import"./chunk-6MI4KKWF.js";import"./chunk-WCZRDULE.js";import"./chunk-GIPSOLAY.js";import"./chunk-MJC26GOX.js";import"./chunk-JUX77H6K.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as loadHostedHarnessRuntime,b as loadHostedHarnessRuntimeForSession};
@@ -1,3 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{ia as l,ma as c}from"./chunk-L6ELXODL.js";import"./chunk-6GLGOIMQ.js";import{M as n}from"./chunk-XHJUP7M4.js";import"./chunk-7BGT6Q2D.js";import"./chunk-SBBXUZWL.js";import"./chunk-L3KS6MOV.js";import"./chunk-SHCRE7B2.js";import"./chunk-MRGA6BKG.js";import"./chunk-6MI4KKWF.js";import"./chunk-WCZRDULE.js";import"./chunk-GIPSOLAY.js";import"./chunk-MJC26GOX.js";import"./chunk-JUX77H6K.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as t}from"./chunk-FTQLQJQV.js";import{mkdir as f}from"node:fs/promises";import p from"node:path";import a from"node:path";function d(e,o){let s=a.resolve(e),r=a.resolve(o);return r===s||r.startsWith(`${s}${a.sep}`)}t(d,"isHostedProfileSourceWithinRepo");async function m(e){if(!p.isAbsolute(e.repoPath)||!p.isAbsolute(e.outputDir)||!/^[a-f0-9]{40,64}$/.test(e.sourceRevision)||!e.workspaceId.trim()||!e.repositoryId.trim()||!e.profileId.trim())throw new Error("Hosted Profile compile request is invalid.");let o=await n({repoPath:e.repoPath,profileId:e.profileId});if(o.error||o.mode!=="local"||o.activeProfile!==e.profileId||!o.sourcePath||!d(e.repoPath,o.sourcePath))throw new Error("Hosted Profile source is unavailable.");await f(e.outputDir,{recursive:!0});let s=await l({storeDir:e.outputDir,workspaceId:e.workspaceId,name:e.profileId,profile:o,sourceRevision:e.sourceRevision,repositoryId:e.repositoryId}),r=s.harnessRelease.metadata.profile;if(!r||typeof r!="object"||r.id!==e.profileId||r.sourceRevision!==e.sourceRevision||r.repositoryId!==e.repositoryId)throw new Error("Hosted Profile release provenance is invalid.");let i=await c({storeDir:e.outputDir,workspaceId:e.workspaceId,compiled:s,createdAt:new Date().toISOString()});return{workspaceId:e.workspaceId,sourceRevision:i.sourceRevision,harnessRelease:i.harnessRelease,agentSnapshot:i.agentSnapshot,bundlePath:i.bundlePath}}t(m,"compileHostedProfileRelease");async function H(e){if(e.length!==1||e[0].length>16e3||!/^[A-Za-z0-9_-]+$/.test(e[0]))throw new Error("Hosted Profile compile argument is invalid.");let o=JSON.parse(Buffer.from(e[0],"base64url").toString("utf8")),s=await m(o);process.stdout.write(`${JSON.stringify(s)}
3
- `)}t(H,"runHostedProfileCompilerCli");export{m as compileHostedProfileRelease,H as runHostedProfileCompilerCli};
@@ -1,3 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-FUFIZ37W.js";import{c as B}from"./chunk-3HQEEZPO.js";import"./chunk-Q3X5WOVH.js";import{c as U,d as C,f as O}from"./chunk-BSHAIAXY.js";import"./chunk-FKVP26MC.js";import"./chunk-P5CFBE6Z.js";import"./chunk-XWPC3AN4.js";import{f as m}from"./chunk-3M53YXEI.js";import"./chunk-MRGA6BKG.js";import"./chunk-6MI4KKWF.js";import"./chunk-WCZRDULE.js";import"./chunk-OGPHXXCD.js";import"./chunk-TZNKOKQJ.js";import{a as u,c as A,d as x,i as v,j as S,k as R}from"./chunk-JEVA7YQL.js";import"./chunk-SHCKK3SU.js";import{d as k}from"./chunk-AOBTILU5.js";import"./chunk-GLUWATL5.js";import"./chunk-RELOOVWW.js";import"./chunk-GIPSOLAY.js";import"./chunk-MJC26GOX.js";import"./chunk-JUX77H6K.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{H as y}from"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{randomUUID as b}from"node:crypto";async function G(r,t){let e=t[0]||"smoke",n=await k(),l=await B(n,O(n)),c=P(n,r);if(e==="provider-catalog"||e==="providers-catalog"||e==="catalog"){let a=await E({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="models"||e==="model-list"){let a=await A({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="model"||e==="model-get"){let a=t[1]||o(r,"model");if(!a)throw new Error("usage: opchat model <model>");let p=await x({apiBaseUrl:c,token:l,model:a});console.log(JSON.stringify(p,null,2));return}if(e==="chat"){let a=o(r,"model")||"openpond-chat",p=o(r,"effort"),f=p?y.parse(p):void 0,d=o(r,"message")||o(r,"prompt")||"Reply with a short confirmation from OpChat.";if(!m(r.stream)){let s=await v({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]});console.log(JSON.stringify(s,null,2));return}let g="",h=null,w=null;for await(let s of S({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]}))s.type==="text_delta"?(g+=s.text,process.stdout.write(s.text)):s.type==="finish"?h=s.finishReason:s.type==="usage"&&(w=s.usage);process.stdout.write(`
3
- `),console.log(JSON.stringify({finishReason:h,usage:w,text:g},null,2));return}if(e==="smoke"){let a=await R({apiBaseUrl:c,token:l,defaultModel:o(r,"model")||void 0,compatibilityModel:o(r,"compatibilityModel")||o(r,"compatModel")||void 0,skipStream:m(r.skipStream),skipTool:m(r.skipTool),log:i(p=>console.log(p),"log")});m(r.json)&&console.log(JSON.stringify(a,null,2));return}throw new Error("usage: opchat <provider-catalog|models|model|chat|smoke> [--opchat-api-base-url <url>] [chat --model <id> --effort <off|low|medium|high|xhigh|max>]")}i(G,"runOpChatCommand");async function E(r){let t=r.apiBaseUrl.trim().replace(/\/+$/,"");if(!t)throw new Error("OpChat API base URL is required.");let e=r.token.trim();if(!e)throw new Error("OpenPond API key is required.");let n=await fetch(`${t}/provider-catalog`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json","Content-Type":"application/json","x-openpond-client":"openpond-cli","x-openpond-request-id":b()}});if(!n.ok)throw new Error(`Hosted provider catalog failed: ${n.status} ${await T(n)}`);return n.json()}i(E,"getOpChatProviderCatalog");async function T(r){let t=await r.text().catch(()=>"");if(!t)return r.statusText||`HTTP ${r.status}`;try{let e=JSON.parse(t);if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(e.error&&typeof e.error=="object"&&!Array.isArray(e.error)){let n=e.error;return[n.code,n.message].filter(Boolean).join(": ")||t}return t}catch{return t}}i(T,"readResponseError");function P(r,t){let e=o(t,"opchatApiBaseUrl")||o(t,"opchatApiBaseurl")||o(t,"opChatApiBaseUrl")||o(t,"opChatApiBaseurl")||o(t,"opchatApiUrl")||o(t,"opChatApiUrl");return e?u({opChatApiBaseUrl:e}):u({apiBaseUrl:U(t)||r.apiBaseUrl,chatApiBaseUrl:C(t)||r.chatApiBaseUrl})}i(P,"resolveOpChatCliBaseUrl");function o(r,t){let e=r[t];return typeof e=="string"?e.trim():""}i(o,"optionString");export{G as runOpChatCommand};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{m as B}from"./chunk-FUFIZ37W.js";import"./chunk-3HQEEZPO.js";import"./chunk-BSHAIAXY.js";import"./chunk-FKVP26MC.js";import"./chunk-P5CFBE6Z.js";import"./chunk-XWPC3AN4.js";import{a as E,f as b,h as k,i as _}from"./chunk-3M53YXEI.js";import"./chunk-XHJUP7M4.js";import"./chunk-SBBXUZWL.js";import"./chunk-L3KS6MOV.js";import"./chunk-MRGA6BKG.js";import"./chunk-6MI4KKWF.js";import"./chunk-WCZRDULE.js";import"./chunk-OGPHXXCD.js";import"./chunk-TZNKOKQJ.js";import"./chunk-SHCKK3SU.js";import"./chunk-AOBTILU5.js";import"./chunk-GLUWATL5.js";import"./chunk-RELOOVWW.js";import"./chunk-GIPSOLAY.js";import{d as x,e as C}from"./chunk-MJC26GOX.js";import"./chunk-JUX77H6K.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as o}from"./chunk-FTQLQJQV.js";import{createHash as ie,randomBytes as ae}from"node:crypto";import{createServer as le}from"node:http";var Se=new URL(C).hostname,Ee=new URL(x).hostname,_e=`${C}/opchat/v1`;import{spawn as se}from"node:child_process";function M(e,t=process.platform){return t==="darwin"?{command:"open",args:[e]}:t==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:{command:"xdg-open",args:[e]}}o(M,"resolveSystemBrowserCommand");async function S(e,t={}){let n=t.command??M(e),s=t.handoffTimeoutMs??1500;return new Promise(u=>{let r=!1,i=null,c=o(a=>{r||(r=!0,i&&clearTimeout(i),u(a))},"finish"),p=se(n.command,n.args,{detached:!1,shell:!1,stdio:"ignore",windowsHide:!0});p.once("error",a=>{let l=a.code;c({opened:!1,error:l?`browser launcher ${n.command} failed (${l})`:`browser launcher ${n.command} failed`})}),p.once("close",(a,l)=>{if(a===0){c({opened:!0});return}let d=l?`signal ${l}`:`code ${a??"unknown"}`;c({opened:!1,error:`browser launcher ${n.command} exited with ${d}`})}),i=setTimeout(()=>{p.unref(),c({opened:!0})},s),i.unref()})}o(S,"openUrlWithSystemBrowser");function ce(e){return[e.slug,`team=${e.teamId}`,`role=${e.role}`,`status=${e.status}`,e.displayName].join(" ")}o(ce,"formatOrganizationLine");function ue(e){return[e.email??e.userId,`user=${e.userId}`,`role=${e.role}`,e.createdAt].join(" ")}o(ue,"formatOrganizationMemberLine");function de(e){return e?[e.slug,`team=${e.teamId}`,`status=${e.status}`,`tools=${e.toolset.join(",")||"-"}`,e.resourceUrl].join(" "):"no mcp server configured"}o(de,"formatOrganizationMcpServerLine");var pe=["estimate.read","estimate.write","estimate.execute","artifacts.read","artifacts.write"];function O(e){let t=e.trim().replace(/\/$/,"");if(!t)throw new Error("MCP resource URL must be non-empty");return new URL(t).toString().replace(/\/$/,"")}o(O,"normalizeMcpResourceUrl");function N(e,t){let n=typeof t.resourceUrl=="string"&&t.resourceUrl.trim()?t.resourceUrl.trim():typeof t.url=="string"&&t.url.trim()?t.url.trim():"";if(n)return O(n);if(!e?.resourceUrl)throw new Error("organization does not have an MCP server; run organizations mcp-generate first");return O(e.resourceUrl)}o(N,"resolveMcpProbeResourceUrl");function D(e,t){let n=typeof t.origin=="string"&&t.origin.trim()?t.origin.trim():"";return n?O(n):new URL(e).origin}o(D,"resolveMcpProbeOrigin");function $(e=32){return ae(e).toString("base64url")}o($,"randomOauthToken");function me(e){return ie("sha256").update(e).digest("base64url")}o(me,"buildMcpOauthPkceChallenge");function fe(e){let t=typeof e.scope=="string"&&e.scope.trim()?e.scope:typeof e.scopes=="string"&&e.scopes.trim()?e.scopes:"";if(!t)return[...pe];let n=t.split(/[,\s]+/g).map(s=>s.trim()).filter(Boolean);if(n.length===0)throw new Error("scope must include at least one OAuth scope");return n}o(fe,"parseMcpOAuthScopes");function ge(e){let t=typeof e.clientId=="string"&&e.clientId.trim()?e.clientId.trim():"openpond-code-mcp-proof";if(t==="true")throw new Error("client-id must be a non-empty value");return t}o(ge,"resolveMcpOAuthClientId");function he(e){let t=k(e.timeoutSeconds,"timeout-seconds")??k(e.timeout,"timeout")??180;if(t<=0)throw new Error("timeout must be greater than zero");return t*1e3}o(he,"resolveMcpOAuthTimeoutMs");function ye(e){let t=k(e.callbackPort,"callback-port")??0;if(t<0||t>65535)throw new Error("callback-port must be between 0 and 65535");return t}o(ye,"resolveMcpOAuthCallbackPort");function j(e){return new Promise((t,n)=>{e.close(s=>{s?n(s):t()})})}o(j,"closeServer");async function Pe(e){let t=!1,n=null,s=null,u=null,r=new Promise((a,l)=>{s=a,u=l}),i=o((a,l,d,m,f)=>{if(t){a.writeHead(204).end();return}t=!0,a.writeHead(l,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),a.end(d),n&&clearTimeout(n),m?s?.(m):u?.(f??new Error("oauth_callback_failed"))},"settle"),c=le((a,l)=>{let d=a.headers.host??"127.0.0.1",m=new URL(a.url??"/",`http://${d}`);if(m.pathname!=="/callback"){l.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),l.end("Not found");return}let f=m.searchParams.get("state")??"",g=m.searchParams.get("error")??"",P=m.searchParams.get("code")??"";if(f!==e.expectedState){i(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>State mismatch. Return to the terminal and retry.</p>",void 0,new Error("oauth_state_mismatch"));return}if(g){i(l,400,"<!doctype html><title>OpenPond OAuth denied</title><p>Authorization was not completed. Return to the terminal.</p>",void 0,new Error(`oauth_authorization_failed:${g}`));return}if(!P){i(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>Missing authorization code. Return to the terminal and retry.</p>",void 0,new Error("oauth_code_missing"));return}i(l,200,"<!doctype html><title>OpenPond OAuth complete</title><p>Authorization complete. You can return to the terminal.</p>",{code:P,state:f})});await new Promise((a,l)=>{let d=o(f=>{c.off("listening",m),l(f)},"onError"),m=o(()=>{c.off("error",d),a()},"onListening");c.once("error",d),c.once("listening",m),c.listen(e.port,"127.0.0.1")});let p=c.address();if(!p||typeof p.port!="number")throw await j(c),new Error("oauth_callback_listener_failed");return n=setTimeout(()=>{t||(t=!0,u?.(new Error("oauth_callback_timeout")))},e.timeoutMs),{close:o(async()=>{n&&clearTimeout(n),await j(c).catch(()=>{})},"close"),redirectUri:`http://127.0.0.1:${p.port}/callback`,waitForCallback:o(()=>r,"waitForCallback")}}o(Pe,"startMcpOAuthCallbackListener");function we(e){S(e)}o(we,"openUrlWithSystemBrowser");function Ae(e){let t=new URL(e.authorizationEndpoint);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",e.clientId),t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("resource",e.resourceUrl),t.searchParams.set("scope",e.scopes.join(" ")),t.searchParams.set("state",e.state),t.toString()}o(Ae,"buildMcpOAuthAuthorizeUrl");async function Oe(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("client_id",e.clientId),t.set("redirect_uri",e.redirectUri),t.set("code",e.code),t.set("code_verifier",e.codeVerifier);let n=await fetch(`${e.origin}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t}),s=await q(n);if(!n.ok)throw new Error(`oauth_token_exchange_failed:${n.status}:${JSON.stringify(s)}`);if(!s||typeof s!="object"||Array.isArray(s))throw new Error("oauth_token_exchange_invalid_response");let u=s;if(typeof u.access_token!="string"||!u.access_token.trim())throw new Error("oauth_token_exchange_missing_access_token");return{access_token:u.access_token,...typeof u.expires_in=="number"?{expires_in:u.expires_in}:{},...typeof u.refresh_token=="string"?{refresh_token:u.refresh_token}:{},...typeof u.scope=="string"?{scope:u.scope}:{},...typeof u.token_type=="string"?{token_type:u.token_type}:{}}}o(Oe,"exchangeMcpOAuthAuthorizationCode");async function q(e){let t=await e.text().catch(()=>"");if(!t)return null;let n=t.trim();if((e.headers.get("content-type")??"").toLowerCase().includes("application/json")||n.startsWith("{")||n.startsWith("["))try{return JSON.parse(n)}catch{return t}return t}o(q,"readMcpProbeBody");async function U(e,t={}){let n=await fetch(e,t);return{url:e,status:n.status,ok:n.ok,headers:{contentType:n.headers.get("content-type"),location:n.headers.get("location"),wwwAuthenticate:n.headers.get("www-authenticate")},body:await q(n)}}o(U,"fetchMcpProbe");function be(e,t,n){return n?{jsonrpc:"2.0",id:e,method:t,params:n}:{jsonrpc:"2.0",id:e,method:t}}o(be,"buildMcpJsonRpcRequest");function F(e){let t=typeof e.arguments=="string"&&e.arguments.trim()?e.arguments:typeof e.args=="string"&&e.args.trim()?e.args:"";if(!t)return{};let n=E(t,"arguments");if(!n||typeof n!="object"||Array.isArray(n))throw new Error("arguments must be a JSON object");return n}o(F,"parseMcpToolArguments");async function R(e){let t={"content-type":"application/json"};return e.accessToken&&(t.authorization=`Bearer ${e.accessToken}`),U(e.resourceUrl,{method:"POST",headers:t,body:JSON.stringify(be(e.id,e.method,e.params))})}o(R,"postMcpJsonRpcProbe");async function J(e){let t=O(e.resourceUrl),n=O(e.origin),s=`${t}/.well-known/oauth-protected-resource`,u=`${n}/.well-known/oauth-authorization-server`,[r,i,c,p,a,l,d]=await Promise.all([U(s),U(u),U(t),R({resourceUrl:t,id:1,method:"initialize"}),R({resourceUrl:t,id:2,method:"tools/list"}),R({resourceUrl:t,id:3,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments}}),e.accessToken?R({resourceUrl:t,id:4,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments},accessToken:e.accessToken}):Promise.resolve(null)]);return{resourceUrl:t,origin:n,protectedResource:r,authorizationServer:i,directGetChallenge:c,initialize:p,toolsList:a,unauthenticatedToolCall:l,...d?{authenticatedToolCall:d}:{}}}o(J,"probeOrganizationMcp");function ke(e){let t=typeof e=="string"?e.trim():"";if(t==="owner"||t==="admin"||t==="member")return t;throw new Error("role must be owner, admin, or member")}o(ke,"parseOrganizationRole");function xe(e){let t=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(!t)throw new Error("usage: organizations create --name <name> [--slug <slug>]");return{displayName:t,...typeof e.slug=="string"&&e.slug.trim()?{slug:e.slug.trim()}:{},...typeof e.primaryContactEmail=="string"&&e.primaryContactEmail.trim()?{primaryContactEmail:e.primaryContactEmail.trim()}:{},...typeof e.customDomain=="string"&&e.customDomain.trim()?{customDomain:e.customDomain.trim()}:{}}}o(xe,"buildOrganizationCreateInput");function Ce(e){let t={},n=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(n&&(t.displayName=n),typeof e.slug=="string"&&e.slug.trim()&&(t.slug=e.slug.trim()),typeof e.primaryContactEmail=="string"&&(t.primaryContactEmail=e.primaryContactEmail.trim()||null),typeof e.customDomain=="string"&&(t.customDomain=e.customDomain.trim()||null),typeof e.status=="string"&&e.status.trim()){let s=e.status.trim();if(s!=="active"&&s!=="disabled"&&s!=="archived")throw new Error("status must be active, disabled, or archived");t.status=s}if(Object.keys(t).length===0)throw new Error("organizations update requires at least one changed field");return t}o(Ce,"buildOrganizationUpdateInput");function Re(e){let t=typeof e.email=="string"?e.email.trim():"";if(!t)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");return{email:t,role:ke(e.role)}}o(Re,"buildOrganizationMemberInput");function Ue(e){return{...typeof e.origin=="string"&&e.origin.trim()?{origin:e.origin.trim()}:{},...typeof e.toolset=="string"&&e.toolset.trim()?{toolset:_(e.toolset)}:{}}}o(Ue,"buildOrganizationMcpGenerateInput");async function yo(e,t){let n=t[0]||"list",s=await B(e),u=b(e.json);if(n==="list"){let r=await s.listOrganizations();if(u){console.log(JSON.stringify({organizations:r},null,2));return}if(r.length===0){console.log("no organizations found");return}for(let i of r)console.log(ce(i));return}if(n==="create"){let r=await s.createOrganization(xe(e));console.log(JSON.stringify({organization:r},null,2));return}if(n==="get"){let r=t[1];if(!r)throw new Error("usage: organizations get <slug>");let i=await s.getOrganization(r);console.log(JSON.stringify({organization:i},null,2));return}if(n==="update"){let r=t[1];if(!r)throw new Error("usage: organizations update <slug> [--name <name>]");let i=await s.updateOrganization(r,Ce(e));console.log(JSON.stringify({organization:i},null,2));return}if(n==="members"||n==="member-list"){let r=t[1];if(!r)throw new Error("usage: organizations members <slug>");let i=await s.listOrganizationMembers(r);if(u){console.log(JSON.stringify({members:i},null,2));return}if(i.length===0){console.log("no organization members found");return}for(let c of i)console.log(ue(c));return}if(n==="member-upsert"||n==="member-add"){let r=t[1];if(!r)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");let i=await s.upsertOrganizationMember(r,Re(e));console.log(JSON.stringify({member:i},null,2));return}if(n==="mcp-get"||n==="mcp-server"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-get <slug>");let i=await s.getOrganizationMcpServer(r);if(u){console.log(JSON.stringify({mcpServer:i},null,2));return}console.log(de(i));return}if(n==="mcp-generate"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-generate <slug> [--origin <url>]");let i=await s.generateOrganizationMcpServer(r,Ue(e));console.log(JSON.stringify({mcpServer:i},null,2));return}if(n==="mcp-probe"||n==="mcp-inspect"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-probe <slug> [--origin <url>] [--tool <name>] [--arguments <json>] [--access-token <token>]");let i=await s.getOrganizationMcpServer(r),c=N(i,e),p=D(c,e),a=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",l=F(e),d=typeof e.accessToken=="string"&&e.accessToken.trim()?e.accessToken.trim():"",m=await J({resourceUrl:c,origin:p,toolName:a,toolArguments:l,...d?{accessToken:d}:{}});console.log(JSON.stringify({mcpServer:i,probe:m},null,2));return}if(n==="mcp-authorize"||n==="mcp-oauth"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-authorize <slug> [--origin <url>] [--scope <csv|space>] [--tool <name>] [--arguments <json>] [--open]");let i=await s.getOrganizationMcpServer(r),c=N(i,e),p=D(c,e),a=ge(e),l=fe(e),d=$(18),m=$(48),f=me(m),g=await Pe({expectedState:d,port:ye(e),timeoutMs:he(e)}),P=Ae({authorizationEndpoint:`${p}/oauth/authorize`,clientId:a,codeChallenge:f,redirectUri:g.redirectUri,resourceUrl:c,scopes:l,state:d});if(console.error("Open this URL to authorize the organization MCP connection:"),console.error(P),console.error(`Waiting for OAuth callback on ${g.redirectUri}`),b(e.open))try{we(P)}catch(w){console.error(`Unable to open a browser automatically: ${w instanceof Error?w.message:String(w)}`)}try{let w=await g.waitForCallback(),h=await Oe({clientId:a,code:w.code,codeVerifier:m,origin:p,redirectUri:g.redirectUri}),K=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",G=F(e),W=await J({accessToken:h.access_token,origin:p,resourceUrl:c,toolArguments:G,toolName:K}),V=b(e.printToken);console.log(JSON.stringify({mcpServer:i,oauth:{accessTokenReceived:!0,clientId:a,expiresIn:h.expires_in??null,refreshTokenReceived:!!h.refresh_token,scope:h.scope??l.join(" "),tokenType:h.token_type??"Bearer",...V?{accessToken:h.access_token,refreshToken:h.refresh_token??null}:{}},probe:W},null,2))}finally{await g.close()}return}if(n==="mcp-rotate"||n==="mcp-disable"||n==="mcp-enable"){let r=t[1];if(!r)throw new Error(`usage: organizations ${n} <slug>`);let i=n==="mcp-rotate"?await s.rotateOrganizationMcpServer(r):n==="mcp-disable"?await s.disableOrganizationMcpServer(r):await s.enableOrganizationMcpServer(r);console.log(JSON.stringify({mcpServer:i},null,2));return}throw new Error("usage: organizations <list|create|get|update|members|member-upsert|mcp-get|mcp-generate|mcp-probe|mcp-authorize|mcp-rotate|mcp-disable|mcp-enable> [args]")}o(yo,"runOrganizationsCommand");export{pe as DEFAULT_MCP_AUTHORIZE_SCOPES,be as buildMcpJsonRpcRequest,Ae as buildMcpOAuthAuthorizeUrl,me as buildMcpOauthPkceChallenge,xe as buildOrganizationCreateInput,Ue as buildOrganizationMcpGenerateInput,Re as buildOrganizationMemberInput,Ce as buildOrganizationUpdateInput,j as closeServer,Oe as exchangeMcpOAuthAuthorizationCode,U as fetchMcpProbe,ce as formatOrganizationLine,de as formatOrganizationMcpServerLine,ue as formatOrganizationMemberLine,O as normalizeMcpResourceUrl,we as openUrlWithSystemBrowser,fe as parseMcpOAuthScopes,F as parseMcpToolArguments,ke as parseOrganizationRole,R as postMcpJsonRpcProbe,J as probeOrganizationMcp,$ as randomOauthToken,q as readMcpProbeBody,ye as resolveMcpOAuthCallbackPort,ge as resolveMcpOAuthClientId,he as resolveMcpOAuthTimeoutMs,D as resolveMcpProbeOrigin,N as resolveMcpProbeResourceUrl,yo as runOrganizationsCommand,Pe as startMcpOAuthCallbackListener};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as b,b as Y,c as F,d as H,e as W,f as z,g as X,h as E,i as y,j as v,k as C,l as Z,m as ee,n as A,o as te,p as _,q as j,r as re,s as ne,t as x,u as M,v as R,w as J,x as N,y as U,z as T}from"./chunk-J4S7AVGF.js";import{m as h,n as I,v as P}from"./chunk-FUFIZ37W.js";import"./chunk-3HQEEZPO.js";import"./chunk-BSHAIAXY.js";import"./chunk-FKVP26MC.js";import"./chunk-P5CFBE6Z.js";import"./chunk-XWPC3AN4.js";import{c as u,d,e as w,f as S}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-TZNKOKQJ.js";import"./chunk-DDHUSA3I.js";import"./chunk-SHCKK3SU.js";import"./chunk-AOBTILU5.js";import"./chunk-GLUWATL5.js";import"./chunk-RELOOVWW.js";import"./chunk-GIPSOLAY.js";import"./chunk-MJC26GOX.js";import"./chunk-JUX77H6K.js";import"./chunk-QUNRWDVO.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as g}from"./chunk-FTQLQJQV.js";function k(e){let o=e.gitRepo?`${e.gitOwner??"_"}/${e.gitRepo}`:e.internalRepoPath??e.templateRepoUrl??e.normalizedSourceIdentity;return[e.id,e.status,e.sourceType,e.name,o].join(" ")}g(k,"formatProjectLine");function L(e){let o=e.selectedEntrypoint.name?`${e.selectedEntrypoint.scope}:${e.selectedEntrypoint.name}`:e.selectedEntrypoint.scope,i=e.runtimeSource?[e.runtimeSource.mode,e.runtimeSource.publishedSnapshotName??e.runtimeSource.publishedSnapshotId??e.runtimeSource.sourceRef].filter(a=>!!a).join(":"):"latest_source";return[e.id,e.status,e.triggerType,e.defaultWorkflowMode,i,o,e.name].join(" ")}g(L,"formatAgentLine");async function B(e,o,i){let a=i[1]?.trim(),t=i[2]?.trim(),n="usage: agent source <deploy-plan|checks|manifest-snapshots|setup|publish> <agent-id> --team-id <id>",r=d(o,n);if(!a||!t)throw new Error(n);if(a==="deploy-plan"){let s=await e.agents.sourceDeployPlan(t,{teamId:r});console.log(JSON.stringify({deployPlan:s},null,2));return}if(a==="manifest-snapshots"){let s=await e.agents.manifestSnapshots(t,{teamId:r,limit:x(o.limit)});console.log(JSON.stringify({manifestSnapshots:s},null,2));return}if(a==="checks"){let s=await e.agents.requestSourceChecks(t,M(r,o));console.log(JSON.stringify(s,null,2));return}if(a==="setup"){let s=typeof o.provider=="string"?o.provider.trim():"",l=typeof o.allowedActions=="string"?o.allowedActions.split(",").map(c=>c.trim()).filter(Boolean):[];if(!s||l.length===0)throw new Error(`${n}; setup requires --provider and --allowed-actions`);let p=await e.agents.configureSourceSetup(t,{teamId:r,integrationBindings:[{provider:s,mode:"connected",connectionMode:"member_connection",grantPolicy:"read_only",allowedActions:l,enabled:!0}]});console.log(JSON.stringify(p,null,2));return}if(a==="publish"){let s=await e.agents.publishSource(t,R(r,o));console.log(JSON.stringify(s,null,2));return}throw new Error(n)}g(B,"runAgentSourceWorkflow");import G from"node:path";var Q=new Set(["inspect","build","validate","eval","traces"]);function $(e,o){return Q.has(e)?!0:e==="run"&&!u(o,"teamId")}g($,"shouldDelegateLocalAgentSdkCommand");async function q(e,o){let i=o[0]||"inspect",a=G.resolve(u(e,"cwd")||u(e,"path")||"."),t=[i,...o.slice(1),"--cwd",a];S(e.json)&&t.push("--json"),D(t,e,"input","input"),D(t,e,"inputFile","input-file");let n=b(a),r=await P(n.command,[...n.args,...t],{cwd:a,inherit:!0});r.code!==0&&(process.exitCode=r.code??1)}g(q,"runLocalAgentSdkCommand");function D(e,o,i,a){let t=u(o,i);t&&e.push(`--${a}`,t)}g(D,"appendForwardedOption");async function Oe(e,o){let i=o[0]||"list";if($(i,e)){await q(e,o);return}let a=await h(e);if(i==="list"){let t=d(e,"usage: agent list"),n=await a.agents.list({teamId:t});if(S(e.json)){console.log(JSON.stringify({agents:n},null,2));return}if(n.length===0){console.log("no sandbox agents found");return}for(let r of n)console.log(L(r));return}if(i==="create"||i==="upsert"){let t=await a.agents.upsert(U(e));console.log(JSON.stringify({agent:t},null,2));return}if(i==="get"){let t=o[1]?.trim(),n=d(e,"usage: agent get <agentId>");if(!t)throw new Error("usage: agent get <agentId> --team-id <id>");let r=await a.agents.get(t,{teamId:n});console.log(JSON.stringify({agent:r},null,2));return}if(i==="run"){let t=o[1]?.trim(),n=d(e,"usage: agent run <agentId>");if(!t)throw new Error("usage: agent run <agentId> --team-id <id>");let r=u(e,"idempotencyKey"),s=u(e,"conversationId"),l=u(e,"targetProjectId"),p=A(e.triggerType),c=I(e.workflowMode),m=w(e,"input","input"),f=w(e,"metadata","metadata"),O=j(e),K=await a.agents.run(t,{teamId:n,...s?{conversationId:s}:{},...r?{idempotencyKey:r}:{},...l?{targetProjectId:l}:{},...l?{targetProject:{id:l}}:{},...p?{triggerType:p}:{},...c?{workflowMode:c}:{},...m?{input:m}:{},...f?{metadata:f}:{},...O?{runtimeSourcePolicy:O}:{}});console.log(JSON.stringify(K,null,2));return}if(i==="bind-runtime-source"||i==="bind-source"){let t=o[1]?.trim(),n=d(e,"usage: agent bind-source <agentId>");if(!t)throw new Error("usage: agent bind-source <agentId> --team-id <id> --source-mode latest_source|published_snapshot|auto");let r=_(e);if(!r?.mode)throw new Error("usage: agent bind-source <agentId> --team-id <id> --source-mode latest_source|published_snapshot|auto");let s=await a.agents.update(t,{teamId:n,runtimeSource:r});console.log(JSON.stringify({agent:s,agentSource:s.runtimeSource},null,2));return}if(i==="run-test"){let t=o[1]?.trim(),n=d(e,"usage: agent run-test <agentId>");if(!t)throw new Error("usage: agent run-test <agentId> --team-id <id>");let r=u(e,"idempotencyKey"),s=u(e,"conversationId"),l=u(e,"targetProjectId"),p=w(e,"input","input"),c=w(e,"metadata","metadata"),m=I(e.workflowMode),f=await a.agents.run(t,{teamId:n,...s?{conversationId:s}:{},...r?{idempotencyKey:r}:{},...l?{targetProjectId:l}:{},...l?{targetProject:{id:l}}:{},...m?{workflowMode:m}:{},...p?{input:p}:{},metadata:{...c??{},source:"agent_run_test"},runtimeSourcePolicy:j(e,"diagnostic")});console.log(JSON.stringify({resolvedRuntimeSource:f.run.runtimeSource,agent:f.agent,run:f.run,sandbox:f.sandbox??null},null,2));return}if(i==="source"){await B(a,e,o);return}if(i==="update"){let t=o[1]?.trim(),n=d(e,"usage: agent update <agentId>");if(!t)throw new Error("usage: agent update <agentId> --team-id <id>");let r=await a.agents.update(t,T(n,e));console.log(JSON.stringify({agent:r},null,2));return}if(i==="archive"){let t=o[1]?.trim(),n=d(e,"usage: agent archive <agentId>");if(!t)throw new Error("usage: agent archive <agentId> --team-id <id>");let r=await a.agents.archive(t,{teamId:n});console.log(JSON.stringify({agent:r},null,2));return}throw new Error("usage: agent <inspect|build|validate|eval|traces|list|create|upsert|get|update|run|run-test|bind-source|source|edit|archive> [--team-id <id>] [--project-id <id>] [--name <name>]")}g(Oe,"runAgentCommand");import V from"node:path";async function xe(e,o){let i=o[0]||"list",a=await h(e);if(i==="list"){let t=d(e,"usage: project list"),n=await a.projects.list({teamId:t});if(S(e.json)){console.log(JSON.stringify({projects:n},null,2));return}if(n.length===0){console.log("no sandbox projects found");return}for(let r of n)console.log(k(r));return}if(i==="create"||i==="upsert"){let t=await a.projects.upsert(J(e));console.log(JSON.stringify({project:t},null,2));return}if(i==="get"){let t=o[1]?.trim(),n=d(e,"usage: project get <projectId>");if(!t)throw new Error("usage: project get <projectId> --team-id <id>");let r=await a.projects.get(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}if(i==="update"){let t=o[1]?.trim(),n=d(e,"usage: project update <projectId>");if(!t)throw new Error("usage: project update <projectId> --team-id <id>");let r=await a.projects.update(t,N(n,e));console.log(JSON.stringify({project:r},null,2));return}if(i==="sync"){let t=o[1]?.trim(),n=d(e,"usage: project sync <projectId>");if(!t)throw new Error("usage: project sync <projectId> --team-id <id>");let r=await a.projects.sync(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}if(i==="source-upload"||i==="upload-source"){let t=o[1]?.trim(),n=d(e,"usage: project source-upload <projectId>");if(!t)throw new Error("usage: project source-upload <projectId> --team-id <id> [--path <dir>]");let r=V.resolve(u(e,"path")||"."),s=await E(r,e),l=u(e,"commitMessage")||u(e,"commit-message")||"Upload OpenPond project source",p=await y(r),c=await v(r,p.entries),m=C(p,c.entries),f=await a.projects.uploadSource(t,{teamId:n,entries:m.entries,...s?{branch:s}:{},commitMessage:l});console.log(JSON.stringify({project:f,uploaded:{path:r,branch:s,fileCount:m.fileCount,totalBytes:m.totalBytes,limits:m.limits,transport:m.transport,...c.generatedManifestPath?{agentSdk:{generatedManifestPath:c.generatedManifestPath,generatedEntryCount:c.entries.length,synthesizedOpenPondYaml:c.synthesizedOpenPondYaml,uploadMetadataPath:c.uploadMetadataPath,uploadMetadataHash:c.uploadMetadataHash,commands:c.uploadMetadata?.commands,dependencySetup:c.uploadMetadata?.dependencySetup,packageManager:c.uploadMetadata?.packageManager,sourceTreeMode:c.uploadMetadata?.sourceTreeMode,artifactHashes:c.uploadMetadata?.artifactHashes}}:{}}},null,2));return}if(i==="archive"){let t=o[1]?.trim(),n=d(e,"usage: project archive <projectId>");if(!t)throw new Error("usage: project archive <projectId> --team-id <id>");let r=await a.projects.archive(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}throw new Error("usage: project <list|create|upsert|get|update|sync|source-upload|archive> [--team-id <id>] [--name <name>]")}g(xe,"runProjectCommand");export{W as PROJECT_SOURCE_UPLOAD_CONCURRENCY,z as PROJECT_SOURCE_UPLOAD_LIMITS,H as PROJECT_SOURCE_UPLOAD_MAX_BYTES,Y as PROJECT_SOURCE_UPLOAD_MAX_FILES,F as PROJECT_SOURCE_UPLOAD_MAX_FILE_BYTES,X as PROJECT_SOURCE_UPLOAD_TRANSPORT,M as buildAgentSourceChecksInput,_ as buildAgentSourceConfig,j as buildAgentSourcePolicy,R as buildAgentSourcePublishInput,T as buildAgentUpdateInput,U as buildAgentUpsertInput,N as buildProjectUpdateInput,J as buildProjectUpsertInput,y as collectProjectSourceUploadEntries,L as formatAgentLine,k as formatProjectLine,ee as parseAgentEntrypointScope,ne as parseAgentSourceCheckDispatch,re as parseAgentSourceCheckKind,te as parseAgentSourceMode,A as parseAgentTriggerType,x as parsePositiveLimit,Z as parseProjectSourceType,b as resolveLocalAgentSdkCommand,Oe as runAgentCommand,B as runAgentSourceWorkflow,xe as runProjectCommand};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as N,b as E,c as P,d as J,e as j,f as S,g as O,h as C,i as R,j as k,k as B,l as q,m as U,n as L,o as l}from"./chunk-ZCFX6HQO.js";import{m as v,s as w,t as y}from"./chunk-FUFIZ37W.js";import"./chunk-3HQEEZPO.js";import"./chunk-BSHAIAXY.js";import"./chunk-FKVP26MC.js";import"./chunk-P5CFBE6Z.js";import"./chunk-XWPC3AN4.js";import{b as I,f,g as h,h as p}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-TZNKOKQJ.js";import"./chunk-SHCKK3SU.js";import"./chunk-AOBTILU5.js";import"./chunk-GLUWATL5.js";import"./chunk-RELOOVWW.js";import"./chunk-GIPSOLAY.js";import"./chunk-MJC26GOX.js";import"./chunk-JUX77H6K.js";import"./chunk-QUNRWDVO.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as b}from"./chunk-FTQLQJQV.js";async function M(r,o,e,i){if(o==="list-files"){let t=i[1];if(!t)throw new Error("usage: sandbox list-files <sandboxId> [--path <path>]");let n=typeof e.path=="string"?e.path.trim():void 0,s=h(e.maxEntries,"max-entries"),a=e.recursive!==void 0?f(e.recursive):void 0,d=await r.listFiles(t,{...n?{path:n}:{},...a!==void 0?{recursive:a}:{},...s!==void 0?{maxEntries:s}:{}});return console.log(JSON.stringify({sandbox:l(d.sandbox),files:d.files},null,2)),!0}if(o==="upload-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"",s=typeof e.contents=="string"?e.contents:typeof e.content=="string"?e.content:"",a=typeof e.contentsBase64=="string"?e.contentsBase64.trim():typeof e.contentBase64=="string"?e.contentBase64.trim():"";if(!t||!n)throw new Error('usage: sandbox upload-file <sandboxId> --path <path> --contents "text"');if(!s&&!a)throw new Error('usage: sandbox upload-file <sandboxId> --path <path> --contents "text"');let d=a?await r.uploadFileBase64(t,n,a):await r.uploadFile(t,n,s);return console.log(JSON.stringify({sandbox:l(d.sandbox),file:d.file},null,2)),!0}if(o==="download-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"",s=Number(e["offset-bytes"]),a=Number(e["max-bytes"]);if(!t||!n)throw new Error("usage: sandbox download-file <sandboxId> --path <path>");let d=await r.downloadFileResponse(t,{path:n,...Number.isFinite(s)?{offsetBytes:s}:{},...Number.isFinite(a)?{maxBytes:a}:{}});return console.log(JSON.stringify({sandbox:l(d.sandbox),file:d.file,contents:Buffer.from(d.file.contentsBase64,"base64").toString("utf-8")},null,2)),!0}if(o==="search-files"){let t=i[1],n=typeof e.query=="string"?e.query.trim():"";if(!t||!n)throw new Error("usage: sandbox search-files <sandboxId> --query <text> [--path <path>]");let s=typeof e.path=="string"?e.path.trim():void 0,a=h(e.maxResults,"max-results"),d=await r.searchFiles(t,{query:n,...s?{path:s}:{},...a!==void 0?{maxResults:a}:{}});return console.log(JSON.stringify({sandbox:l(d.sandbox),matches:d.matches},null,2)),!0}if(o==="delete-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"";if(!t||!n)throw new Error("usage: sandbox delete-file <sandboxId> --path <path> [--recursive]");let s=await r.deleteFile(t,n,{recursive:f(e.recursive)});return console.log(JSON.stringify({sandbox:l(s.sandbox),deleted:s.deleted},null,2)),!0}if(o==="stat-file"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"";if(!t||!n)throw new Error("usage: sandbox stat-file <sandboxId> --path <path>");let s=await r.statFile(t,n);return console.log(JSON.stringify({sandbox:l(s.sandbox),file:s.file},null,2)),!0}if(o==="mkdir"){let t=i[1],n=typeof e.path=="string"?e.path.trim():"";if(!t||!n)throw new Error("usage: sandbox mkdir <sandboxId> --path <path> [--recursive false]");let s=await r.mkdir(t,{path:n,recursive:e.recursive!==void 0?f(e.recursive):void 0});return console.log(JSON.stringify({sandbox:l(s.sandbox),directory:s.directory},null,2)),!0}if(o==="move-file"){let t=i[1],n=typeof e.fromPath=="string"?e.fromPath.trim():"",s=typeof e.toPath=="string"?e.toPath.trim():"";if(!t||!n||!s)throw new Error("usage: sandbox move-file <sandboxId> --from-path <path> --to-path <path> [--overwrite]");let a=await r.moveFile(t,{fromPath:n,toPath:s,overwrite:f(e.overwrite)});return console.log(JSON.stringify({sandbox:l(a.sandbox),moved:a.moved,file:a.file},null,2)),!0}return!1}b(M,"handleSandboxFilesCommand");async function T(r,o,e,i){if(o==="git-status"){let t=i[1];if(!t)throw new Error("usage: sandbox git-status <sandboxId>");let n=await r.gitStatus(t);return console.log(JSON.stringify({sandbox:l(n.sandbox),status:n.status},null,2)),!0}if(o==="git-diff"){let t=i[1];if(!t)throw new Error("usage: sandbox git-diff <sandboxId> [--base-ref <ref>]");let n=typeof e.baseRef=="string"&&e.baseRef.trim()?e.baseRef.trim():void 0,s=await r.gitDiff(t,{...n?{baseRef:n}:{}});return console.log(JSON.stringify({sandbox:l(s.sandbox),diff:s.diff},null,2)),!0}if(o==="git-export-patch"){let t=i[1];if(!t)throw new Error("usage: sandbox git-export-patch <sandboxId> [--base-ref <ref>]");let n=typeof e.baseRef=="string"&&e.baseRef.trim()?e.baseRef.trim():void 0,s=await r.gitExportPatch(t,{...n?{baseRef:n}:{}});return console.log(JSON.stringify({sandbox:l(s.sandbox),patch:s.patch},null,2)),!0}if(o==="git-branch"){let t=i[1],n=typeof e.branch=="string"?e.branch.trim():"",s=typeof e.startPoint=="string"&&e.startPoint.trim()?e.startPoint.trim():void 0;if(!t||!n)throw new Error("usage: sandbox git-branch <sandboxId> --branch <name> [--create] [--start-point <ref>]");let a=await r.gitBranch(t,{branch:n,create:f(e.create),...s?{startPoint:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),branch:a.branch},null,2)),!0}if(o==="git-commit"){let t=i[1],n=typeof e.message=="string"?e.message.trim():"",s=f(e.all),d=(typeof e.paths=="string"?e.paths:typeof e.path=="string"?e.path:"").split(",").map(g=>g.trim()).filter(Boolean);if(!t||!n||!s&&d.length===0)throw new Error('usage: sandbox git-commit <sandboxId> --message "..." [--all|--paths <csv>]');let c=await r.gitCommit(t,{message:n,...s?{all:!0}:{paths:d}});return console.log(JSON.stringify({sandbox:l(c.sandbox),commit:c.commit},null,2)),!0}if(o==="git-pull"){let t=i[1];if(!t)throw new Error("usage: sandbox git-pull <sandboxId> [--remote origin] [--branch main] [--rebase|--ff-only false]");let n=typeof e.remote=="string"&&e.remote.trim()?e.remote.trim():void 0,s=typeof e.branch=="string"&&e.branch.trim()?e.branch.trim():void 0,a=await r.gitPull(t,{...n?{remote:n}:{},...s?{branch:s}:{},...e.rebase!==void 0?{rebase:f(e.rebase)}:{},...e.ffOnly!==void 0?{ffOnly:f(e.ffOnly)}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),pull:a.pull},null,2)),!0}if(o==="git-push"){let t=i[1];if(!t)throw new Error("usage: sandbox git-push <sandboxId> [--remote origin] [--branch main] [--set-upstream] [--force-with-lease]");let n=typeof e.remote=="string"&&e.remote.trim()?e.remote.trim():void 0,s=typeof e.branch=="string"&&e.branch.trim()?e.branch.trim():void 0,a=await r.gitPush(t,{...n?{remote:n}:{},...s?{branch:s}:{},...e.setUpstream!==void 0?{setUpstream:f(e.setUpstream)}:{},...e.forceWithLease!==void 0?{forceWithLease:f(e.forceWithLease)}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),push:a.push},null,2)),!0}return!1}b(T,"handleSandboxGitCommand");async function F(r,o,e,i){if(o==="process-start"){let t=i[1],n=(typeof e.command=="string"?e.command:null)||i.slice(2).join(" ");if(!t||!n.trim())throw new Error("usage: sandbox process-start <sandboxId> --command <command>");let s=p(e.timeoutSeconds,"timeout-seconds"),a=await r.startProcess(t,{command:n.trim(),...s!==void 0?{timeoutSeconds:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),process:a.process},null,2)),!0}if(o==="process-list"){let t=i[1];if(!t)throw new Error("usage: sandbox process-list <sandboxId>");let n=await r.listProcesses(t);return console.log(JSON.stringify({sandbox:l(n.sandbox),processes:n.processes},null,2)),!0}if(o==="process-get"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox process-get <sandboxId> <processId> [--since <cursor>]");let s=p(e.since,"since"),a=await r.getProcess(t,n,{...s!==void 0?{since:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),process:a.process,output:a.output,cursor:a.cursor,completed:a.completed},null,2)),!0}if(o==="process-stop"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox process-stop <sandboxId> <processId>");let s=await r.stopProcess(t,n);return console.log(JSON.stringify({sandbox:l(s.sandbox),process:s.process},null,2)),!0}if(o==="process-stream"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox process-stream <sandboxId> <processId> [--since <cursor>]");let s=p(e.since,"since");return await r.streamProcessOutput(t,n,{...s!==void 0?{since:s}:{}}),!0}if(o==="pty-start"){let t=i[1];if(!t)throw new Error("usage: sandbox pty-start <sandboxId> [--command <command>]");let n=(typeof e.command=="string"?e.command:null)||i.slice(2).join(" "),s=p(e.timeoutSeconds,"timeout-seconds"),a=p(e.rows,"rows"),d=p(e.cols,"cols"),c=await r.startPty(t,{...n.trim()?{command:n.trim()}:{},...s!==void 0?{timeoutSeconds:s}:{},...a!==void 0?{rows:a}:{},...d!==void 0?{cols:d}:{}});return console.log(JSON.stringify({sandbox:l(c.sandbox),pty:c.pty},null,2)),!0}if(o==="pty-list"){let t=i[1];if(!t)throw new Error("usage: sandbox pty-list <sandboxId>");let n=await r.listPtys(t);return console.log(JSON.stringify({sandbox:l(n.sandbox),ptys:n.ptys},null,2)),!0}if(o==="pty-get"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox pty-get <sandboxId> <ptyId> [--since <cursor>]");let s=p(e.since,"since"),a=await r.getPty(t,n,{...s!==void 0?{since:s}:{}});return console.log(JSON.stringify({sandbox:l(a.sandbox),pty:a.pty,output:a.output,cursor:a.cursor,completed:a.completed},null,2)),!0}if(o==="pty-write"){let t=i[1],n=i[2],s=typeof e.inputBase64=="string"?e.inputBase64.trim():"",a=(typeof e.input=="string"?e.input:null)||i.slice(3).join(" ");if(!t||!n||!s&&!a)throw new Error("usage: sandbox pty-write <sandboxId> <ptyId> --input <text>");let d=await r.writePtyInput(t,n,s?{dataBase64:s}:a);return console.log(JSON.stringify({sandbox:l(d.sandbox),pty:d.pty},null,2)),!0}if(o==="pty-stop"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox pty-stop <sandboxId> <ptyId>");let s=await r.stopPty(t,n);return console.log(JSON.stringify({sandbox:l(s.sandbox),pty:s.pty},null,2)),!0}if(o==="pty-stream"){let t=i[1],n=i[2];if(!t||!n)throw new Error("usage: sandbox pty-stream <sandboxId> <ptyId> [--since <cursor>]");let s=p(e.since,"since");return await r.streamPtyOutput(t,n,{...s!==void 0?{since:s}:{}}),!0}return!1}b(F,"handleSandboxProcessCommand");async function A(r,o,e,i){if(o==="replays"||o==="replay-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=typeof e.projectId=="string"?e.projectId.trim():"",s=await r.listReplays({...t?{teamId:t}:{},...n?{projectId:n}:{}});if(f(e.json))return console.log(JSON.stringify(s,null,2)),!0;if(s.replays.length===0)return console.log("no sandbox replays found"),!0;for(let a of s.replays)console.log(O(a));return!0}if(o==="replay-start"||o==="start-replay"){let t=await r.startReplay(k(e));return console.log(JSON.stringify(t,null,2)),!0}if(o==="replay-get"||o==="get-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-get <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.getReplay(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});return console.log(JSON.stringify(a,null,2)),!0}if(o==="replay-logs"||o==="logs-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-logs <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.getReplayLogs(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});for(let d of a.logs)console.log(d);return!0}if(o==="replay-artifacts"||o==="artifacts-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-artifacts <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.getReplayArtifacts(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});return console.log(JSON.stringify({replayId:a.replayId,artifacts:a.artifacts.map(C)},null,2)),!0}if(o==="replay-cancel"||o==="cancel-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-cancel <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=await r.cancelReplay(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});return console.log(JSON.stringify(a,null,2)),!0}if(o==="replay-watch"||o==="watch-replay"){let t=i[1];if(!t)throw new Error("usage: sandbox replay-watch <replayId> [--team-id <id>]");let n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.projectId=="string"?e.projectId.trim():"",a=p(e.intervalMs,"interval-ms")??5e3,d=p(e.timeoutMs,"timeout-ms")??900*1e3,c=Date.now(),g=new Set;for(;Date.now()-c<=d;){let u=await r.getReplay(t,{...n?{teamId:n}:{},...s?{projectId:s}:{}});for(let m of u.replay.logs)g.has(m)||(g.add(m),console.log(m));if(u.replay.state==="succeeded"||u.replay.state==="failed"||u.replay.state==="canceled"){if(console.log(O(u.replay)),u.replay.state!=="succeeded")throw new Error(`sandbox replay ${u.replay.state}: ${u.replay.error??"no error"}`);return!0}await new Promise(m=>setTimeout(m,a))}throw new Error(`sandbox replay did not finish within ${d}ms`)}return!1}b(A,"handleSandboxReplayCommand");async function V(r,o,e,i){if(o==="runtime-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=typeof e.projectId=="string"?e.projectId.trim():"",s=typeof e.agentId=="string"?e.agentId.trim():"",a=await r.listSandboxRuntimes({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{}});return console.log(JSON.stringify({runtimes:a},null,2)),!0}if(o==="runtime-get"){let t=i[1]?.trim();if(!t)throw new Error("usage: sandbox runtime-get <runtimeId>");let n=await r.getSandboxRuntime(t);return console.log(JSON.stringify({runtime:n},null,2)),!0}if(o==="runtime-events"){let t=i[1]?.trim();if(!t)throw new Error("usage: sandbox runtime-events <runtimeId>");return console.log(JSON.stringify(await r.listSandboxRuntimeEvents(t),null,2)),!0}if(o==="runtime-status"){let t=i[1]?.trim(),n=typeof e.status=="string"&&e.status.trim()?e.status.trim():"",s=Number(e.expectedVersion),a=typeof e.summary=="string"&&e.summary.trim()?e.summary.trim():void 0;if(!t||!n||!Number.isInteger(s))throw new Error("usage: sandbox runtime-status <runtimeId> --status <status> --expected-version <n>");let d=await r.updateSandboxRuntimeStatus(t,{status:n,expectedVersion:s,...a?{summary:a}:{}});return console.log(JSON.stringify({runtime:d},null,2)),!0}if(o==="runtime-event"){let t=i[1]?.trim(),n=typeof e.type=="string"&&e.type.trim()?e.type.trim():"",s=typeof e.summary=="string"&&e.summary.trim()?e.summary.trim():void 0,a=typeof e.payload=="string"&&e.payload.trim()?I(e.payload,"payload"):void 0,d=typeof e.lifecycleHint=="string"&&e.lifecycleHint.trim()?I(e.lifecycleHint,"lifecycle-hint"):void 0;if(!t||!n)throw new Error("usage: sandbox runtime-event <runtimeId> --type <eventType> [--summary <text>] [--payload <json>] [--lifecycle-hint <json>]");return console.log(JSON.stringify(await r.emitSandboxRuntimeEvent(t,{type:n,...s?{summary:s}:{},...a?{payload:a}:{},...d?{lifecycleHint:d}:{}}),null,2)),!0}if(o==="runtime-preserve-source"||o==="runtime-preserve"){let t=i[1]?.trim(),n=typeof e.teamId=="string"&&e.teamId.trim()?e.teamId.trim():"",s=typeof e.sandboxId=="string"&&e.sandboxId.trim()?e.sandboxId.trim():"",a=typeof e.message=="string"&&e.message.trim()?e.message.trim():"";if(!t)throw new Error("usage: sandbox runtime-preserve-source <runtimeId> [--team-id <id>] [--sandbox-id <id>] [--message <text>]");return console.log(JSON.stringify(await r.runtimes.preserveSource(t,{...s?{sandboxId:s}:{},...a?{message:a}:{}},{...n?{teamId:n}:{}}),null,2)),!0}return!1}b(V,"handleSandboxRuntimeCommand");async function $(r,o,e,i){if(o==="secrets"||o==="secret-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=await r.listSecrets({...t?{teamId:t}:{}});if(f(e.json))return console.log(JSON.stringify({secrets:n.map(y)},null,2)),!0;if(n.length===0)return console.log("no sandbox secrets found"),!0;for(let s of n)console.log(`${s.name} ${s.status} v${s.currentVersion??"current"} ${s.secretRef}`);return!0}if(o==="secret-create"){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=typeof e.name=="string"?e.name.trim():"",s=typeof e.description=="string"&&e.description.trim()?e.description.trim():void 0,a=e.scope==="project"||e.scope==="template"||e.scope==="team"?e.scope:void 0;if(!n)throw new Error("usage: sandbox secret-create --name <ENV_NAME> [--team-id <id>] [--stdin]");let d=await w(e,`Value for ${n}`),c=await r.createSecret({...t?{teamId:t}:{},name:n,value:d,...s?{description:s}:{},...a?{scope:a}:{}});return console.log(JSON.stringify({secret:y(c)},null,2)),!0}if(o==="secret-rotate"){let t=i[1],n=typeof e.teamId=="string"?e.teamId.trim():"";if(!t)throw new Error("usage: sandbox secret-rotate <secretId> [--team-id <id>] [--stdin]");let s=await w(e,"New secret value"),a=await r.rotateSecret(t,{...n?{teamId:n}:{},value:s});return console.log(JSON.stringify({secret:y(a)},null,2)),!0}if(o==="secret-attach"){let t=i[1],n=typeof e.teamId=="string"?e.teamId.trim():"",s=typeof e.envName=="string"?e.envName.trim():"",a=e.targetType==="sandbox"||e.targetType==="template"||e.targetType==="project"||e.targetType==="agent"||e.targetType==="replay"?e.targetType:void 0,d=typeof e.targetId=="string"?e.targetId.trim():"";if(!t||!s||!a||!d)throw new Error("usage: sandbox secret-attach <secretId> --env-name <ENV_NAME> --target-type sandbox|project|agent|template|replay --target-id <id>");let c=await r.attachSecret(t,{...n?{teamId:n}:{},envName:s,targetType:a,targetId:d});return console.log(JSON.stringify({secret:y(c)},null,2)),!0}if(o==="secret-revoke"||o==="secret-delete"){let t=i[1],n=typeof e.teamId=="string"?e.teamId.trim():"";if(!t)throw new Error(`usage: sandbox ${o} <secretId> [--team-id <id>]`);let s=o==="secret-revoke"?await r.revokeSecret(t,{...n?{teamId:n}:{}}):await r.deleteSecret(t,{...n?{teamId:n}:{}});return console.log(JSON.stringify({secret:y(s)},null,2)),!0}return!1}b($,"handleSandboxSecretsCommand");async function H(r,o,e,i){if(o==="published-snapshot-builds"||o==="published-snapshot-build-list"||o==="template-builds"||o==="template-build-list"){let t=typeof e.teamId=="string"?e.teamId.trim():"";if(!t)throw new Error("usage: sandbox published-snapshot-builds --team-id <id>");let n=await r.listPublishedSnapshotBuilds({teamId:t});if(f(e.json))return console.log(JSON.stringify({builds:n},null,2)),!0;if(n.length===0)return console.log("no published snapshot builds found"),!0;for(let s of n)console.log(S(s));return!0}if(o==="published-snapshot-build-create"||o==="create-published-snapshot-build"||o==="template-build-create"||o==="create-template-build"){let t=await r.createPublishedSnapshotBuild(U(e));return console.log(JSON.stringify({build:t},null,2)),!0}if(o==="published-snapshot-build-get"||o==="get-published-snapshot-build"||o==="template-build-get"||o==="get-template-build"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-get <buildId>");let n=await r.getPublishedSnapshotBuild(t);return console.log(JSON.stringify({build:n},null,2)),!0}if(o==="published-snapshot-build-logs"||o==="published-snapshot-build-log"||o==="template-build-logs"||o==="template-build-log"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-logs <buildId>");let n=await r.getPublishedSnapshotBuildLogs(t);if(f(e.json))return console.log(JSON.stringify(n,null,2)),!0;for(let s of n.logs)console.log(s);return!0}if(o==="published-snapshot-build-cancel"||o==="cancel-published-snapshot-build"||o==="template-build-cancel"||o==="cancel-template-build"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-cancel <buildId>");let n=await r.cancelPublishedSnapshotBuild(t);return console.log(JSON.stringify({build:n},null,2)),!0}if(o==="published-snapshot-build-watch"||o==="watch-published-snapshot-build"||o==="template-build-watch"||o==="watch-template-build"){let t=i[1];if(!t)throw new Error("usage: sandbox published-snapshot-build-watch <buildId>");let n=p(e.intervalMs,"interval-ms")??5e3,s=p(e.timeoutMs,"timeout-ms")??900*1e3,a=Date.now(),d=new Set;for(;Date.now()-a<=s;){let[c,g]=await Promise.all([r.getPublishedSnapshotBuild(t),r.getPublishedSnapshotBuildLogs(t)]);for(let u of g.logs)d.has(u)||(d.add(u),console.log(u));if(c.status==="succeeded"||c.status==="failed"||c.status==="cancelled"){if(console.log(S(c)),c.status!=="succeeded")throw new Error(`published snapshot build ${c.status}: ${c.error??"no error"}`);return!0}await new Promise(u=>setTimeout(u,n))}throw new Error(`published snapshot build did not finish within ${s}ms`)}return!1}b(H,"handleSandboxTemplateBuildsCommand");function G(r){return f(r.async)||f(r.respondAsync)}b(G,"parseSandboxAsyncOption");async function Pe(r,o){let e=o[0]||"list",i=await v(r);if(e==="list"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=await i.list({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{}});if(a.length===0){console.log("no sandboxes found");return}for(let d of a)console.log(P(d));return}if(e==="mcp-config"||e==="mcp-url"){let t=i.mcpServerConfig();console.log(JSON.stringify({...t,headers:{"openpond-api-key":"set OPENPOND_API_KEY or use your saved openpond profile"}},null,2));return}if(!await V(i,e,r,o)){if(e==="pricing"){let t=await i.pricing();console.log(JSON.stringify(t,null,2));return}if(e==="costs"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=await i.costs({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{}});if(f(r.summary)){console.log(JSON.stringify({costs:{teamId:a.costs.teamId,ownerUserId:a.costs.ownerUserId,generatedAt:a.costs.generatedAt,summary:a.costs.summary,lineItems:a.costs.lineItems,tiers:a.costs.pricing.tiers.map(d=>({key:d.key,resources:d.resources,keepRunningEstimate:d.keepRunningEstimate}))}},null,2));return}console.log(JSON.stringify(a,null,2));return}if(!await $(i,e,r,o)){if(e==="snapshots"||e==="snapshot-catalog"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=typeof r.query=="string"&&r.query.trim()?r.query.trim():typeof r.q=="string"&&r.q.trim()?r.q.trim():"",d=typeof r.tag=="string"?r.tag.trim():"",c=typeof r.useCase=="string"?r.useCase.trim():"",g=typeof r.replayState=="string"?r.replayState.trim():"",u=await i.snapshotCatalog({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{},...a?{q:a}:{},...d?{tag:d}:{},...c?{useCase:c}:{},...g==="draft"||g==="validated"||g==="published"?{replayState:g}:{}});if(u.snapshots.length===0){console.log("no sandbox snapshots found");return}for(let m of u.snapshots)console.log(J(m));return}if(e==="published-snapshots"||e==="published-snapshot-catalog"||e==="templates"||e==="template-catalog"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.query=="string"&&r.query.trim()?r.query.trim():typeof r.q=="string"&&r.q.trim()?r.q.trim():"",a=typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.templateName=="string"&&r.templateName.trim()?r.templateName.trim():"",d=typeof r.version=="string"?r.version.trim():"",c=typeof r.tag=="string"?r.tag.trim():"",g=typeof r.useCase=="string"?r.useCase.trim():"",u=await i.publishedSnapshots({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{q:s}:{},...a?{name:a}:{},...d?{version:d}:{},...c?{tag:c}:{},...g?{useCase:g}:{}});if(u.publishedSnapshots.length===0){console.log("no published snapshots found");return}for(let m of u.publishedSnapshots)console.log(j(m));return}if(!(await H(i,e,r,o)||await A(i,e,r,o))){if(e==="run-published-snapshot"||e==="published-snapshot-run"||e==="template-launch"||e==="launch-template"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.snapshotId=="string"&&r.snapshotId.trim()?r.snapshotId.trim():typeof r.snapshot=="string"&&r.snapshot.trim()?r.snapshot.trim():"",a=typeof r.templateName=="string"&&r.templateName.trim()?r.templateName.trim():typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof o[1]=="string"&&o[1].trim()?o[1].trim():"",d=typeof r.version=="string"?r.version.trim():"",c=typeof r.useCase=="string"?r.useCase.trim():"";if(!s&&!a&&!c)throw new Error("usage: sandbox run-published-snapshot [--snapshot-id <id>|--name <name>|--use-case <id>] [--version <v>]");let g=typeof r.budgetUsd=="string"&&r.budgetUsd.trim()?r.budgetUsd.trim():typeof r.budget=="string"&&r.budget.trim()?r.budget.trim():"",u=await i.runPublishedSnapshot({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{snapshotId:s}:{},...a?{templateName:a}:{},...d?{version:d}:{},...c?{useCase:c}:{},...g?{budget:{maxUsd:g}}:{},metadata:{source:"openpond-code-published-snapshot-run"}});console.log(JSON.stringify(u,null,2));return}if(e==="snapshot-fork"||e==="fork-snapshot"){let t=o[1];if(!t)throw new Error("snapshot-fork requires <snapshotId>");let n=typeof r.teamId=="string"?r.teamId.trim():"",s=typeof r.projectId=="string"?r.projectId.trim():"",a=typeof r.budgetUsd=="string"&&r.budgetUsd.trim()?r.budgetUsd.trim():typeof r.budget=="string"&&r.budget.trim()?r.budget.trim():"",d=await i.forkSnapshot(t,{...n?{teamId:n}:{},...s?{projectId:s}:{},...a?{budget:{maxUsd:a}}:{},metadata:{source:"openpond-code-snapshot-fork",templateSnapshotId:t}});console.log(JSON.stringify(d,null,2));return}if(e==="snapshot-create"||e==="create-snapshot"){let t=o[1];if(!t)throw new Error("usage: sandbox snapshot-create <sandboxId> --name <name>");let n=await i.createSnapshot(t,L(r));console.log(JSON.stringify(n,null,2));return}if(e==="snapshot-validate"||e==="validate-snapshot"){let t=o[1],n=o[2];if(!t||!n)throw new Error("snapshot-validate requires <sandboxId> <snapshotId>");let s=R(r.cleanup),a=await i.validateSnapshot(t,n,{...s?{cleanup:s}:{}});console.log(JSON.stringify(a,null,2));return}if(e==="snapshot-publish"||e==="publish-snapshot"){let t=o[1],n=o[2];if(!t||!n)throw new Error("snapshot-publish requires <sandboxId> <snapshotId>");let s=await i.publishSnapshot(t,n);console.log(JSON.stringify(s,null,2));return}if(e==="integration-connections"){let t=typeof r.teamId=="string"?r.teamId.trim():"",n=typeof r.projectId=="string"?r.projectId.trim():"",s=typeof r.agentId=="string"?r.agentId.trim():"",a=r.status==="active"||r.status==="revoked"||r.status==="error"||r.status==="all"?r.status:void 0,d=await i.integrationConnections({...t?{teamId:t}:{},...n?{projectId:n}:{},...s?{agentId:s}:{},...a?{status:a}:{}});console.log(JSON.stringify(d,null,2));return}if(e==="create"){let t=await N(i,B(r));console.log(JSON.stringify({sandbox:l(t.sandbox),...t.runtime?{runtime:t.runtime}:{}},null,2));return}if(e==="exec"){let t=o[1],n=(typeof r.command=="string"?r.command:null)||o.slice(2).join(" ");if(!t||!n.trim())throw new Error("usage: sandbox exec <sandboxId> --command <command>");let s=p(r.timeoutSeconds,"timeout-seconds"),a=await i.exec(t,{command:n.trim(),...s!==void 0?{timeoutSeconds:s}:{}});console.log(JSON.stringify({sandbox:l(a.sandbox),command:a.command},null,2));return}if(e==="port"||e==="preview"){let t=o[1],n=p(r.port,"port");if(!t||n===void 0)throw new Error("usage: sandbox port <sandboxId> --port <port>");let s=typeof r.label=="string"?r.label:void 0,a=typeof r.access=="string"?r.access.trim():"";if(a&&a!=="private"&&a!=="public")throw new Error("sandbox port --access must be private or public");let d=a==="public"?"public":"private",c=typeof r.domain=="string"?r.domain.trim():"",g=typeof r.authToken=="string"?r.authToken:"",u=typeof r.authHeader=="string"?r.authHeader.trim():"",m=typeof r.authHeaderValue=="string"?r.authHeaderValue:"";if(g&&(u||m))throw new Error("sandbox port auth options must use either --auth-token or --auth-header with --auth-header-value");if(u&&!m||!u&&m)throw new Error("sandbox port custom header auth requires both --auth-header and --auth-header-value");let x=await i.openPort(t,{port:n,...s?{label:s}:{},access:d,...r["auto-start"]||r.autoStart?{autoStart:!0}:{},...c?{customDomain:c}:{},...g?{authPolicy:{mode:"bearer",token:g}}:{},...u&&m?{authPolicy:{mode:"header",headerName:u,headerValue:m}}:{}});console.log(JSON.stringify(x.preview,null,2));return}if(e==="stop"){let t=o[1];if(!t)throw new Error("usage: sandbox stop <sandboxId> [--fail-on-unpreserved-changes] [--async]");let n=await i.stop(t,{failOnUnpreservedChanges:f(r.failOnUnpreservedChanges),async:G(r)});console.log(JSON.stringify({sandbox:l(n.sandbox),receipt:n.receipt},null,2));return}if(e==="start"){let t=o[1];if(!t)throw new Error("usage: sandbox start <sandboxId>");let n=await i.start(t);console.log(JSON.stringify({sandbox:await E(i,n.sandbox),receipt:n.receipt},null,2));return}if(e==="delete"){let t=o[1];if(!t)throw new Error("usage: sandbox delete <sandboxId> [--fail-on-unpreserved-changes] [--async]");let n=await i.delete(t,{failOnUnpreservedChanges:f(r.failOnUnpreservedChanges),async:G(r)});console.log(JSON.stringify({sandbox:l(n)},null,2));return}if(e==="receipts"){let t=o[1];if(!t)throw new Error("usage: sandbox receipts <sandboxId>");let n=await i.receipts(t);console.log(JSON.stringify({receipts:n},null,2));return}if(e==="logs"){let t=o[1];if(!t)throw new Error("usage: sandbox logs <sandboxId>");let n=await i.logs(t);for(let s of n)console.log(s);return}if(!(await F(i,e,r,o)||await M(i,e,r,o)||await T(i,e,r,o))){if(e==="billing"){let t=o[1];if(!t)throw new Error("usage: sandbox billing <sandboxId>");let n=await i.billing(t);console.log(JSON.stringify({sandbox:l(n.sandbox),billing:n.billing},null,2));return}if(e==="integration-leases"){let t=o[1];if(!t)throw new Error("usage: sandbox integration-leases <sandboxId>");let n=await i.integrationLeases(t);console.log(JSON.stringify({sandbox:l(n.sandbox),integrationLeases:n.integrationLeases},null,2));return}if(e==="integration-attach"){let t=o[1];if(!t)throw new Error("usage: sandbox integration-attach <sandboxId> --integration-connection <id> --integration-capabilities <csv>");let n=await i.attachIntegrationConnection(t,q(r));console.log(JSON.stringify({sandbox:l(n.sandbox),integrationLeases:n.integrationLeases},null,2));return}if(e==="integration-remove"){let t=o[1],n=typeof r.leaseId=="string"?r.leaseId.trim():"";if(!t||!n)throw new Error("usage: sandbox integration-remove <sandboxId> --lease-id <id>");let s=await i.removeIntegrationLease(t,n);console.log(JSON.stringify({sandbox:l(s.sandbox),integrationLeases:s.integrationLeases},null,2));return}if(e==="smoke"){let t=typeof r.repo=="string"?r.repo.trim():void 0,n=typeof r.budgetUsd=="string"?r.budgetUsd.trim():typeof r.budget=="string"?r.budget.trim():void 0,s=f(r.keep),a=r.preview!==void 0?f(r.preview):!f(r.noPreview),d=f(r.snapshot),c=f(r.fork),g={...t?{repo:t}:{},...n?{budgetUsd:n}:{},keep:s,preview:a,snapshot:d,fork:c};typeof r.expectedMppMode=="string"&&r.expectedMppMode.trim()&&(g.expectedMppMode=r.expectedMppMode.trim());let u=h(r.cpu,"cpu"),m=h(r.memoryGb,"memory-gb"),x=h(r.diskGb,"disk-gb");u!==void 0&&(g.cpu=u),m!==void 0&&(g.memoryGb=m),x!==void 0&&(g.diskGb=x);let z=await i.smoke(g);console.log(JSON.stringify(z,null,2));return}throw new Error("usage: sandbox <list|mcp-config|runtime-list|runtime-get|runtime-events|runtime-status|runtime-event|runtime-preserve-source|pricing|costs|secrets|secret-create|secret-rotate|secret-attach|secret-revoke|secret-delete|snapshots|published-snapshots|run-published-snapshot|snapshot-fork|snapshot-validate|snapshot-publish|create|exec|port|preview|stop|start|delete|receipts|logs|billing|process-start|process-list|process-get|process-stop|process-stream|pty-start|pty-list|pty-get|pty-write|pty-stop|pty-stream|upload-file|download-file|list-files|search-files|delete-file|stat-file|mkdir|move-file|git-status|git-diff|git-export-patch|git-branch|git-commit|git-pull|git-push|smoke> [args]")}}}}}b(Pe,"runSandboxCommand");export{Pe as runSandboxCommand};