openpond 0.2.35 → 0.2.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-server.d.ts +197 -4
- package/dist/app-server.js +1 -1
- package/dist/chunks/actions-command-GNQREIDD.js +2 -0
- package/dist/chunks/{app-layer-HK2GTSRX.js → app-layer-BDAKS3DG.js} +1 -1
- package/dist/chunks/app-server-runtime-D74FFS27.js +2 -0
- package/dist/chunks/apps-2SUP5JZE.js +2 -0
- package/dist/chunks/chunk-2O5UZOYL.js +13 -0
- package/dist/chunks/{chunk-BRJKTOMI.js → chunk-3I5BMVJI.js} +1 -1
- package/dist/chunks/{chunk-E4U7LXSW.js → chunk-3LG4G5JR.js} +2 -2
- package/dist/chunks/{chunk-4QX2I2DX.js → chunk-3N4GQL6I.js} +1 -1
- package/dist/chunks/{chunk-DR3XPQRZ.js → chunk-3YA2CD22.js} +1 -1
- package/dist/chunks/{chunk-EFTLCT7C.js → chunk-4R4KM6LL.js} +1 -1
- package/dist/chunks/{chunk-MXLB6MEW.js → chunk-5YUITAUN.js} +1 -1
- package/dist/chunks/{chunk-QPZNN5Q3.js → chunk-6EAQL7YX.js} +1 -1
- package/dist/chunks/{chunk-77BXXOHW.js → chunk-BLXEK5F7.js} +1 -1
- package/dist/chunks/{chunk-QWENRTVW.js → chunk-DAOLQUAK.js} +1 -1
- package/dist/chunks/{chunk-JFSDNQHW.js → chunk-DG4DIFF4.js} +3 -3
- package/dist/chunks/{chunk-SRQVXHSM.js → chunk-DXOOJFFU.js} +1 -1
- package/dist/chunks/chunk-EIB7GHIQ.js +4 -0
- package/dist/chunks/{chunk-XCTFXXVY.js → chunk-FFEI7IRU.js} +1 -1
- package/dist/chunks/chunk-FOW3LI6G.js +2 -0
- package/dist/chunks/{chunk-JLWAK5PS.js → chunk-FQOVC2GR.js} +78 -78
- package/dist/chunks/chunk-HZP5U2AA.js +3 -0
- package/dist/chunks/chunk-I6DQSOSF.js +12 -0
- package/dist/chunks/chunk-IYROEHYB.js +2 -0
- package/dist/chunks/{chunk-BOQBDCVU.js → chunk-KCFVJDIV.js} +1 -1
- package/dist/chunks/chunk-L6NNQUAT.js +53 -0
- package/dist/chunks/chunk-OO7JG7KM.js +42 -0
- package/dist/chunks/chunk-PKBU37CH.js +5 -0
- package/dist/chunks/chunk-QUNRWDVO.js +155 -0
- package/dist/chunks/{chunk-34URWDE7.js → chunk-S4RSY6CR.js} +1 -1
- package/dist/chunks/{chunk-VL553I5E.js → chunk-SL7XLTIT.js} +199 -199
- package/dist/chunks/{chunk-BAKCGJ5D.js → chunk-TZ6N7WFI.js} +1 -1
- package/dist/chunks/{chunk-Z6F6PYF4.js → chunk-UJLZRM2M.js} +1 -1
- package/dist/chunks/chunk-XISNUB62.js +2 -0
- package/dist/chunks/{chunk-PZ2ZILPN.js → chunk-XLVFY2BA.js} +1 -1
- package/dist/chunks/{chunk-K6EGNB2A.js → chunk-YQPECTJ2.js} +1 -1
- package/dist/chunks/{chunk-PMXE4CAA.js → chunk-Z3RBK6LN.js} +1 -1
- package/dist/chunks/cli-A2P56J7R.js +2 -0
- package/dist/chunks/configuration-command-URDRLDNY.js +2 -0
- package/dist/chunks/core-commands-CMAAUKPQ.js +2 -0
- package/dist/chunks/desktop-test-5PKGG6H6.js +3 -0
- package/dist/chunks/dist-CEKBK32A.js +2 -0
- package/dist/chunks/dist-GKCGK44T.js +2 -0
- package/dist/chunks/{extension-RMJAXEKN.js → extension-DG2XISC6.js} +1 -1
- package/dist/chunks/{help-QDMTLEIL.js → help-ZLJV3ZVW.js} +1 -1
- package/dist/chunks/hosted-harness-runtime-ABEMAABI.js +2 -0
- package/dist/chunks/hosted-profile-compiler-CSLJT75T.js +3 -0
- package/dist/chunks/{opchat-MHH4C5YQ.js → opchat-IMGIFM4W.js} +1 -1
- package/dist/chunks/organizations-G3UOHURO.js +2 -0
- package/dist/chunks/{profile-KVDJTM4D.js → profile-LMRN5QMQ.js} +1 -1
- package/dist/chunks/project-agent-DTAVYEB6.js +2 -0
- package/dist/chunks/sandbox-command-YO6RR5SD.js +2 -0
- package/dist/chunks/{sandbox-template-Q6K5JXA3.js → sandbox-template-LN5OQ55F.js} +1 -1
- package/dist/chunks/{src-42VXY5DZ.js → src-A5KEQW52.js} +1 -1
- package/dist/chunks/{src-ZGGKHNNF.js → src-LRJO4THC.js} +3 -3
- package/dist/chunks/{teams-bot-7TPB34DR.js → teams-bot-RY5M6AOW.js} +1 -1
- package/dist/chunks/{workspaces-XFUQZH5T.js → workspaces-KZ6ZJXXY.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/web/assets/{App-BKY1b22z.js → App-BRZg56AC.js} +32 -32
- package/dist/web/assets/{AppDialog-C64bP66E.js → AppDialog-BR9UjEFe.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-fVkWSvWK.js → AppTerminalPanel-DNXVV6S_.js} +2 -2
- package/dist/web/assets/{AppsView-DHnab11q.js → AppsView-DhaB7uT7.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-C7YeQ9KS.js → BrowserSidebar-zecj1P2T.js} +1 -1
- package/dist/web/assets/{CartesianChart-CYX3IXBM.js → CartesianChart-DRhWC0XA.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-j2oBkesr.js → CollaborationTabs-BzNNwOcD.js} +1 -1
- package/dist/web/assets/{CommandMenu-BN1a4dTn.js → CommandMenu-C7HuXmgN.js} +1 -1
- package/dist/web/assets/{CommunityView-CNoxP71Z.js → CommunityView-C4HfU5ky.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-IoK3lqK8.js → ComposerCreateImproveStrip-CG8YZxWB.js} +1 -1
- package/dist/web/assets/{GetStartedView-QPabIxZC.js → GetStartedView-ZxtcgU5X.js} +1 -1
- package/dist/web/assets/HostedModelLearningReview-BhGIhvoc.js +1 -0
- package/dist/web/assets/{HostedModelLearningSettings-TkSSxw8x.js → HostedModelLearningSettings-BKM_1-LZ.js} +1 -1
- package/dist/web/assets/{LabModelVersionDetailPage-CRFw6V7e.js → LabModelVersionDetailPage-CklKwV_e.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-Dl8KWUe0.js → LabSkillSidebar-Cq_axOXr.js} +1 -1
- package/dist/web/assets/{LabsRoute-BzdL7mUM.js → LabsRoute-BPGkQnKq.js} +6 -6
- package/dist/web/assets/{MainChatThread-C3IdxbN3.js → MainChatThread-DvllW6Ej.js} +2 -2
- package/dist/web/assets/{MainPane-BdR1K59_.js → MainPane-BaUIvio6.js} +4 -4
- package/dist/web/assets/{MarkdownText-CkLxqh2M.js → MarkdownText-DP7Hjp4L.js} +1 -1
- package/dist/web/assets/{NativeSkillSidebar-VkWpZX6S.js → NativeSkillSidebar-BSSKKH-y.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-D_K16Ho-.js → NewExperienceSwitcher-cWw4m_pU.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-B6E1wWOM.js → NewProjectDialog-BMzXEHsC.js} +1 -1
- package/dist/web/assets/{OutputsPage-27MuutGA.js → OutputsPage-CGWtgJ_j.js} +1 -1
- package/dist/web/assets/{ProjectsPage-CokpZHgx.js → ProjectsPage-C00Wt3oR.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-B6JhJdlc.js → RightChatPanelStack-0D_jpeAm.js} +1 -1
- package/dist/web/assets/{RightSidebarHomePanel-nn0dqUF0.js → RightSidebarHomePanel-BgHpI97K.js} +1 -1
- package/dist/web/assets/{ScheduledWorkPage-idJ8AO15.js → ScheduledWorkPage-C-P_Jv04.js} +1 -1
- package/dist/web/assets/{SettingsView-ZH2gDC6E.js → SettingsView-BJDvzvtZ.js} +3 -3
- package/dist/web/assets/{TeamChatView-B5cG9M6w.js → TeamChatView-BdUQNXvx.js} +2 -2
- package/dist/web/assets/{TerminalOverlay-9SPRce9W.js → TerminalOverlay-85H1eqcg.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-2dkxe7py.js → TrainingCreationPanel-Bdx2BJzb.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-oYbOFapi.js → TrainingDraftPanel-TcvqZfYS.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-zWs4Z_9b.js → UsageSettingsSection-Dm8bsNIT.js} +1 -1
- package/dist/web/assets/{WorkSidebarPanel-CiBQztz6.js → WorkSidebarPanel-C9bKi4NH.js} +1 -1
- package/dist/web/assets/{WorkspaceDiffPanel-BPt29A2a.js → WorkspaceDiffPanel-CFzHklbv.js} +3 -3
- package/dist/web/assets/{WorkspaceEnvironmentMenu-pb6fs4-2.js → WorkspaceEnvironmentMenu-_e6IkhGw.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-DHD-L4Vs.js → WorkspaceGitDialogs-BglcR8S9.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-BxtCNaRo.js → WorkspaceMonacoEditor-BuipCT-i.js} +3 -3
- package/dist/web/assets/{arrow-up-right-DcP3EZaY.js → arrow-up-right-jN0p0koy.js} +1 -1
- package/dist/web/assets/{clipboard-BXulVWTJ.js → clipboard-Bat4as9H.js} +1 -1
- package/dist/web/assets/{cloud-upload-B3hP6o0H.js → cloud-upload-CFs0F_2n.js} +1 -1
- package/dist/web/assets/{cssMode-c85YG3Pd.js → cssMode-Cg4Jey3B.js} +1 -1
- package/dist/web/assets/{folder-open-CtOXE4jL.js → folder-open-BqInWH_9.js} +1 -1
- package/dist/web/assets/{folder-plus-KO96VZiR.js → folder-plus-BSA6I7ld.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-Bhtev2bN.js → git-commit-horizontal-CLDqrpDQ.js} +1 -1
- package/dist/web/assets/{htmlMode-BbCawv2y.js → htmlMode-DHHN3vwk.js} +1 -1
- package/dist/web/assets/{index-Hynq87d2.js → index-VtbQYCWA.js} +2 -2
- package/dist/web/assets/{info-Dqf1UVHA.js → info-BSebzpyp.js} +1 -1
- package/dist/web/assets/{jsonMode-CFycP8DE.js → jsonMode-mvqMGlEK.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-CYX4VXe2.js → lspLanguageFeatures-Bw_QMGcP.js} +1 -1
- package/dist/web/assets/{minimize-2-BCmNskf_.js → minimize-2-CaHjbHpF.js} +1 -1
- package/dist/web/assets/{monaco.contribution-CJYgsAyM.js → monaco.contribution-CBkwYqsg.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CPkt_0fd.js → monaco.contribution-CiXEi4Ka.js} +2 -2
- package/dist/web/assets/{monaco.contribution-3ZJbmsu3.js → monaco.contribution-DubQum0F.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DR_TcZx7.js → monaco.contribution-KrPDFXc4.js} +2 -2
- package/dist/web/assets/{monitor-DWlfguJj.js → monitor-DwOfVMY6.js} +1 -1
- package/dist/web/assets/{python-rAXzgbqp.js → python-BPnA89YS.js} +1 -1
- package/dist/web/assets/{refresh-cw-BUPgzu5R.js → refresh-cw-DO-hUyTn.js} +1 -1
- package/dist/web/assets/{save-Mb-ECgFZ.js → save-C7WFI7Mn.js} +1 -1
- package/dist/web/assets/{square-CxNbsHso.js → square-DiLQ59tw.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-DUvtEJ40.js → toggleHighContrast-BWFPIQBM.js} +1 -1
- package/dist/web/assets/{tsMode-IPAavolh.js → tsMode-CWxqU0x6.js} +1 -1
- package/dist/web/assets/{upload-Bn6_UQEa.js → upload-vUnuWYGk.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-DAHspLJg.js → useLocalAgentSchedules-BFbGmflA.js} +1 -1
- package/dist/web/assets/{useSessionTurnCache-CUiJuUjd.js → useSessionTurnCache-C0zgYrCB.js} +1 -1
- package/dist/web/assets/{wifi-off-Bsy0Wjm8.js → wifi-off-DbNO6u3Z.js} +1 -1
- package/dist/web/assets/{workers-35o3qFXU.js → workers-4I09fePv.js} +1 -1
- package/dist/web/assets/{yaml-Ba5fmKgb.js → yaml-DpHYonDY.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunks/actions-command-6LFZFTLA.js +0 -2
- package/dist/chunks/app-server-runtime-CAWXM33C.js +0 -2
- package/dist/chunks/apps-YJRRLX2N.js +0 -2
- package/dist/chunks/chunk-5BFWDFPX.js +0 -166
- package/dist/chunks/chunk-B5LKUQGM.js +0 -2
- package/dist/chunks/chunk-CWW2EK77.js +0 -4
- package/dist/chunks/chunk-IFP6W4OW.js +0 -54
- package/dist/chunks/chunk-OYJ73BSC.js +0 -42
- package/dist/chunks/chunk-TBX3Z7TX.js +0 -2
- package/dist/chunks/chunk-XR6ZLKVW.js +0 -15
- package/dist/chunks/cli-YI6G22CQ.js +0 -2
- package/dist/chunks/configuration-command-CYUWO6CD.js +0 -2
- package/dist/chunks/core-commands-Z5C7S6OH.js +0 -2
- package/dist/chunks/desktop-test-JBZCCTSN.js +0 -3
- package/dist/chunks/dist-XCT2G25K.js +0 -2
- package/dist/chunks/hosted-profile-compiler-7SGXUZB4.js +0 -3
- package/dist/chunks/organizations-5KM2JD32.js +0 -2
- package/dist/chunks/project-agent-SXUMNJLZ.js +0 -2
- package/dist/chunks/sandbox-command-FQGX5MSS.js +0 -2
- package/dist/web/assets/HostedModelLearningReview-CNd3-FrC.js +0 -1
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{I as ee,N as _e,O as He,b as xe,c as Ae,m as g,o as Ce}from"./chunk-XR6ZLKVW.js";import{a as Z,b as Te,h as Pe}from"./chunk-PMXE4CAA.js";import{i as Ee,o as Oe,q as ke}from"./chunk-SRQVXHSM.js";import{Aa as E,Ba as Re,Ea as N,Fa as H,Ga as X,Qa as j,U as F,ue as O,xe as L,ye as Ie}from"./chunk-77BXXOHW.js";import{Aa as ue,Ca as ce,Da as pe,Ea as de,Fa as me,Ha as ge,W as _,b as ae,c as le,gb as he,hb as fe,jb as Q,mb as ve,pb as we,qb as D,ub as be,wb as Se,xb as ye}from"./chunk-IFP6W4OW.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as oe,d as U,f as ie,h as k}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";import{promises as re}from"node:fs";import pt from"node:os";import dt from"node:path";import{createServer as mt}from"node:http";import{randomBytes as gt}from"node:crypto";var st=o.discriminatedUnion("op",[o.strictObject({op:o.literal("set"),path:o.array(o.string().min(1)).min(1),value:o.unknown()}),o.strictObject({op:o.literal("unset"),path:o.array(o.string().min(1)).min(1)})]),ot=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(st).max(100)}),o.strictObject({action:o.literal("replace"),expectedRevision:o.string(),text:o.string().max(1048576)}),o.strictObject({action:o.literal("validate"),text:o.string().max(1048576)}),o.strictObject({action:o.literal("restore"),expectedRevision:o.string(),revision:o.string()}),o.strictObject({action:o.literal("trust"),root:o.string(),accountId:o.string(),trusted:o.boolean()}),o.strictObject({action:o.literal("client-state"),owner:o.string(),patch:be,importOnly:o.boolean().optional()})]);function Me(n){let e=null;async function t(s,i){let l=k(n).config,u=null,d=null,p=null;try{u=await le(l),p=await D(n,{projectRoot:s,accountId:i}),s||(e=p)}catch(b){d=U(b,l)}let h=p??(s?null:e);return{path:l,text:u,rawRevision:ae(u),issue:d,effective:h,usingLastValid:!p&&!!h,applies:"next_turn",recoverableRevisions:await ce(n),clientState:d?null:await Se(n)}}a(t,"status");async function r(s){let i=ot.parse(s);return i.action==="validate"?{valid:!0,document:ue(i.text,k(n).config)}:(i.action==="patch"&&await ge(n,i.expectedRevision,i.operations),i.action==="replace"&&await pe(n,i.expectedRevision,i.text),i.action==="restore"&&await de(n,i.revision,i.expectedRevision),i.action==="trust"&&await we(n,i.root,i.accountId,i.trusted),i.action==="client-state"?ye(n,i.owner,i.patch,i.importOnly):t())}return a(r,"mutate"),{status:t,mutate:r,schema:me}}a(Me,"createConfigurationPayloads");import{Buffer as Ue}from"node:buffer";var V={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},it=25*1024*1024,q=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{a(this,"HttpBodyError")}};function qe(n,e,t={}){for(let[s,i]of Object.entries(V))e.setHeader(s,i);let r=De(n.headers.origin);return r?(e.setHeader("Vary",ct(e.getHeader("Vary"))),at(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}a(qe,"applyCorsHeaders");function at(n,e={}){if(n==="null")return!0;let t=Ne(n);return t?ut(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Ne(s):null).filter(s=>!!s)).has(t):!1}a(at,"isAllowedCorsOrigin");function y(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...V}),n.end(JSON.stringify(t))}a(y,"sendJson");function zt(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...V}),n.end(t)}a(zt,"sendText");function Yt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...V}),n.end(t)}a(Yt,"sendBinary");async function te(n,e={}){let t=e.maxBytes??it,r=De(n.headers["content-type"]),s=[],i=0;for await(let u of n){let d=Ue.from(u);if(i+=d.byteLength,i>t)throw new q(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(d)}let l=Ue.concat(s).toString("utf8").trim();if(!l)return{};if(!lt(r))throw new q(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(l)}catch{throw new q(400,"invalid_json","Request body is not valid JSON.")}}a(te,"readJson");function Be(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}a(Be,"hasAuth");function De(n){return Array.isArray(n)?n[0]??null:n??null}a(De,"headerValue");function lt(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}a(lt,"isJsonContentType");function Ne(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}a(Ne,"normalizeOrigin");function ut(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}a(ut,"isLoopbackOrigin");function ct(n){let t=(Array.isArray(n)?n.join(", "):n?String(n):"").split(",").map(r=>r.trim()).filter(Boolean);return t.some(r=>r.toLowerCase()==="origin")||t.push("Origin"),t.join(", ")}a(ct,"appendVaryOrigin");function Fe(n){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
|
|
3
|
-
<style nonce="${n}">body{font:16px system-ui;background:#171819;color:#eee;max-width:850px;margin:6vh auto;padding:24px}textarea{box-sizing:border-box;width:100%;min-height:280px;background:#222;color:#eee;padding:14px;border:1px solid #777;border-radius:8px;font:14px monospace}button,input,select{font:inherit;margin:6px;padding:8px}pre{white-space:pre-wrap}code{overflow-wrap:anywhere}button{cursor:pointer}p{line-height:1.5}</style>
|
|
4
|
-
<h1>OpenPond needs a storage repair</h1><p id="issue" role="alert">Loading recovery details\u2026</p><p><code id="file"></code></p>
|
|
5
|
-
<p id="action"></p><p>Migration backups and the source installation remain available. Execution services are stopped while recovery is open.</p>
|
|
6
|
-
<details id="editor"><summary>Edit configuration</summary><textarea id="text" aria-label="Configuration TOML" spellcheck="false"></textarea><button id="save">Validate and save</button><button id="reload">Reload file</button><select id="revisions" aria-label="Restore a verified configuration revision"><option value="">Restore a verified revision\u2026</option></select></details>
|
|
7
|
-
<details><summary>Migration sources and diagnostics</summary><pre id="migration"></pre><label>Previous app home <input id="appHome"></label><label>Previous account config <input id="configSource"></label><label>Configuration conflict choices (JSON from the preview) <textarea id="resolutions" aria-label="Migration conflict choices" spellcheck="false" placeholder='[{"path":["chat","steer_active_responses"],"choice":"existing"}]'></textarea></label><button id="preview">Preview migration</button><button id="migrate">Use these sources</button><button id="restart">Restart failed preparation</button><button id="diagnostics">Export diagnostics</button></details>
|
|
8
|
-
<button id="retry">Retry startup</button><p id="message" role="status"></p>
|
|
9
|
-
<script nonce="${n}">
|
|
10
|
-
let token='',state=null,editing=false,revision=null;
|
|
11
|
-
const el=id=>document.getElementById(id);
|
|
12
|
-
async function request(route,body){const r=await fetch(route,{method:body?'POST':'GET',headers:{'Content-Type':'application/json',Authorization:'Bearer '+token},body:body?JSON.stringify(body):undefined});const v=await r.json();if(!r.ok)throw Error(v.error||'Recovery request failed');return v;}
|
|
13
|
-
function message(error){el('message').textContent=error instanceof Error?error.message:String(error);}
|
|
14
|
-
async function load(){state=await request('/v1/recovery');el('issue').textContent=state.issue.message;el('action').textContent=state.issue.action;el('file').textContent=state.issue.path;el('migration').textContent=JSON.stringify(state.migration,null,2);if(!editing){el('text').value=state.config.text||'schema_version = 1\\n';revision=state.config.rawRevision;}el('revisions').replaceChildren(new Option('Restore a verified revision\u2026',''),...state.config.recoverableRevisions.map(r=>new Option(r.createdAt,r.revision)));el('editor').hidden=!state.configEditable;}
|
|
15
|
-
el('text').oninput=()=>{editing=true};
|
|
16
|
-
el('reload').onclick=()=>{editing=false;load().catch(message)};
|
|
17
|
-
el('save').onclick=async()=>{try{await request('/v1/configuration',{action:'replace',text:el('text').value,expectedRevision:revision});editing=false;await load();message('Configuration saved. Retry startup when ready.')}catch(e){message(e)}};
|
|
18
|
-
el('revisions').onchange=async e=>{if(!e.target.value)return;try{await request('/v1/configuration',{action:'restore',revision:e.target.value,expectedRevision:state.config.rawRevision});editing=false;await load();message('Verified revision restored.')}catch(e){message(e)}};
|
|
19
|
-
for(const [id,action] of [['preview','preview'],['migrate','migrate'],['restart','restart']])el(id).onclick=async()=>{try{const result=await request('/v1/recovery',{action,sourceAppHome:el('appHome').value||undefined,sourceConfig:el('configSource').value||undefined,resolutions:el('resolutions').value?JSON.parse(el('resolutions').value):undefined});el('migration').textContent=JSON.stringify(result,null,2);message(action==='preview'?'Review the source paths above.':'Migration operation completed; retry startup.')}catch(e){message(e)}};
|
|
20
|
-
el('diagnostics').onclick=()=>{if(!state)return;const blob=new Blob([JSON.stringify({issue:state.issue,migration:state.migration,config:{path:state.config.path,rawRevision:state.config.rawRevision,issue:state.config.issue}},null,2)],{type:'application/json'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='openpond-recovery-diagnostics.json';a.click();URL.revokeObjectURL(a.href)};
|
|
21
|
-
el('retry').onclick=async()=>{try{await request('/v1/recovery',{action:'retry'});message('Starting OpenPond\u2026');const timer=setInterval(async()=>{try{const h=await(await fetch('/health')).json();if(!h.recovery){clearInterval(timer);const next=new URLSearchParams(location.hash.slice(1)).get('returnTo');if(next){const u=new URL(next);if(['localhost','127.0.0.1','[::1]'].includes(u.hostname)){location.replace(u.toString());return}}location.reload();}}catch{}},500)}catch(e){message(e)}};
|
|
22
|
-
(async()=>{const params=new URLSearchParams(location.hash.slice(1));token=params.get('openpondToken')||'';if(!token&&window.openpond?.getConnection)token=(await window.openpond.getConnection()).token;if(!token){message('Open the authenticated recovery URL from the launcher.');return}await load()})().catch(message);
|
|
23
|
-
</script></html>`}a(Fe,"startupRecoveryPage");var ht=o.strictObject({action:o.enum(["preview","migrate","restart","retry"]),sourceAppHome:o.string().optional(),sourceConfig:o.string().optional(),resolutions:he.optional()});function je(n){return n instanceof oe&&/^(PRIVATE_STORAGE_|UNSAFE_STORAGE_|INVALID_CONFIG|CONFIG_|MIGRATION_|SOURCE_CHANGED_|CREDENTIAL_|UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|INVALID_ACCOUNT_|MISSING_INSTRUCTION_|INVALID_PROFILE_|DATABASE_RECOVERY_)/.test(n.issue.code)}a(je,"isRecoverableStartupError");async function Le(n,e,t){let r=/^(UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|UNSAFE_STORAGE_|PRIVATE_STORAGE_)/.test(t.issue.code),s=r?await re.mkdtemp(dt.join(pt.tmpdir(),"openpond-recovery-")):n;return xe(s,async()=>{let{token:i,tokenFile:l}=await _e(s),u=Me(n),d=t.issue,p,h=new Promise(f=>{p=f}),b=mt((f,v)=>{(async()=>{let w=new URL(f.url??"/","http://127.0.0.1");if(!qe(f,v).allowed){y(v,403,{error:"Origin not allowed"});return}if(f.method==="OPTIONS"){y(v,204,{});return}if(f.method==="GET"&&w.pathname==="/health"){y(v,200,{ok:!0,server:"openpond-app-server",version:Te,recovery:!0});return}if(f.method==="GET"&&w.pathname==="/"){let c=gt(18).toString("base64");v.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${c}'; style-src 'nonce-${c}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`}),v.end(Fe(c));return}if(!Be(f,w,i)){y(v,401,{error:"Unauthorized"});return}let A=!r;if(f.method==="GET"&&w.pathname==="/v1/recovery"){y(v,200,{issue:d,configEditable:A,config:r?{path:k(n).config,text:null,rawRevision:"unavailable",issue:d,recoverableRevisions:[]}:await u.status(),migration:await fe(n).catch(c=>({issue:U(c,n)}))});return}if(f.method==="POST"&&w.pathname==="/v1/configuration"&&A){y(v,200,await u.mutate(await te(f)));return}if(f.method==="POST"&&w.pathname==="/v1/recovery"){let c=ht.parse(await te(f));if(r&&c.action!=="retry"&&c.action!=="preview")throw t;if(c.action==="restart"){y(v,200,await ve(n));return}if(c.action==="preview"||c.action==="migrate"){y(v,200,await Q(n,{sourceAppHome:c.sourceAppHome,sourceConfig:c.sourceConfig,resolutions:c.resolutions,dryRun:c.action==="preview"}));return}await Q(n),await D(n),y(v,200,{ready:!0}),p();return}y(v,503,{error:`${d.message} ${d.action}`,issue:d,recovery:!0})})().catch(w=>{d=U(w,n),y(v,422,{error:`${d.message} ${d.action}`,issue:d})})});await new Promise((f,v)=>{b.once("error",v),b.listen(e,"127.0.0.1",()=>{b.off("error",v),f()})});let T=b.address().port,x=`http://127.0.0.1:${T}`;return await Ae(s,x,"startup-recovery"),{url:x,port:T,token:i,tokenFile:l,storePath:k(n).database,repaired:h,close:a(async()=>{b.closeIdleConnections(),await new Promise((f,v)=>b.close(w=>w?v(w):f())),r&&await re.rm(s,{recursive:!0,force:!0})},"close")}}).catch(async i=>{throw r&&await re.rm(s,{recursive:!0,force:!0}),i})}a(Le,"startRecoveryServer");import{createHash as Ut}from"node:crypto";import{createHash as ft,randomUUID as ne}from"node:crypto";var Ve=o.object({approval:X,revision:o.number().int().positive()}).strict(),$e=o.object({record:j}).strict(),vt=o.object({startedAt:o.string().min(1),requestOrdinal:o.number().int().nonnegative(),id:o.string().min(1)}).strict(),wt=o.object({records:o.array(j).max(200),nextBefore:vt.nullable()}).strict(),We=1e4,$=class{constructor(e){this.client=e}client;static{a(this,"HostedApprovalStorage")}async readApproval(e){let t=await this.client.request({contractVersion:g,requestId:ne(),operation:"approval/get",params:{approvalId:e}});return t===null?null:Ve.parse(t)}async getApproval(e){return(await this.readApproval(e))?.approval??null}async putApproval(e){let t=X.parse(e.approval);if(!e.requestId.trim())throw new Error("Approval mutation requires a stable request ID.");return Ve.parse(await this.client.request({contractVersion:g,requestId:e.requestId,operation:"approval/upsert",params:{approval:t,expectedRevision:e.expectedRevision}}))}},W=class{constructor(e){this.client=e}client;static{a(this,"HostedModelUsageStorage")}async upsertModelUsageRecord(e){let t=j.parse(e),r=ft("sha256").update(JSON.stringify(t)).digest("hex"),s=await this.client.request({contractVersion:g,requestId:`usage:${r}`,operation:"usage/upsert",params:{record:t}}),i=$e.parse(s).record;if(i.requestId!==t.requestId)throw new Error("Host usage upsert changed request identity.");return i}async getModelUsageRecordByRequestId(e){let t=await this.client.request({contractVersion:g,requestId:ne(),operation:"usage/getByRequestId",params:{requestId:e}});return t===null?null:$e.parse(t).record}async listModelUsageRecords(e={}){let t=e.limit===void 0||e.limit>=We,r=e.limit===void 0?We:Math.max(1,Math.min(1e4,Math.trunc(e.limit))),s={...e.sessionId?{sessionId:e.sessionId}:{},...e.turnId?{turnId:e.turnId}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.startedAtFrom?{startedAtFrom:e.startedAtFrom}:{},...e.startedAtTo?{startedAtTo:e.startedAtTo}:{},...e.visibility&&e.visibility!=="all"?{visibility:e.visibility}:{},...e.status&&e.status!=="all"?{status:e.status}:{}},i=[],l=null;for(;i.length<r+(t?1:0);){let u=wt.parse(await this.client.request({contractVersion:g,requestId:ne(),operation:"usage/page",params:{query:s,before:l,limit:Math.min(200,r+(t?1:0)-i.length)}}));if(i.push(...u.records),i.length>r)throw new Error(`Hosted usage query exceeds ${r} rows; narrow its filters or use a streamed aggregation.`);if(u.nextBefore===null)break;if(u.records.length===0||JSON.stringify(u.nextBefore)===JSON.stringify(l))throw new Error("Host usage cursor did not advance.");l=u.nextBefore}return i}async listModelUsageRecordsComplete(e={}){return this.listModelUsageRecords(e)}};import{createHash as bt,randomUUID as Ge}from"node:crypto";var St=o.object({updatedAt:o.string(),id:o.string().min(1)}).strict(),yt=o.object({entries:o.array(E).max(200),nextBefore:St.nullable()}).strict(),Rt=o.object({run:E,replayed:o.boolean()}).strict(),G=class{constructor(e){this.client=e}client;static{a(this,"HostedCreateImproveStorage")}async getCreateImproveRun(e){let t=await this.client.request({contractVersion:g,requestId:Ge(),operation:"create-improve/execute",params:{action:"get",runId:e}});return t===null?null:E.parse(t)}async listCreateImproveRuns(e={}){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250))),r=Array.isArray(e.state)?[...e.state]:e.state?[e.state]:[],s=[],i=null;for(;s.length<t;){let l=yt.parse(await this.client.request({contractVersion:g,requestId:Ge(),operation:"create-improve/execute",params:{action:"page",query:{profileId:e.profileId??null,targetKind:e.targetKind??null,targetId:e.targetId??null,state:r},before:i,limit:Math.min(50,t-s.length)}}));if(e.conversationId&&l.entries.some(u=>u.scope.conversationId!==e.conversationId))throw new Error("Hosted Create/Improve page crossed its conversation scope.");if(s.push(...l.entries),!l.nextBefore)break;if(l.entries.length===0||i&&(l.nextBefore.updatedAt>i.updatedAt||l.nextBefore.updatedAt===i.updatedAt&&l.nextBefore.id>=i.id))throw new Error("Hosted Create/Improve cursor did not advance.");i=l.nextBefore}return s}async upsertCreateImproveRun(e){let t=E.parse(e),r=`create-improve:${bt("sha256").update(JSON.stringify(t)).digest("hex")}`,s=await this.client.request({contractVersion:g,requestId:r,operation:"create-improve/execute",params:{action:"put",run:t}});return E.parse(o.object({run:o.unknown()}).strict().parse(s).run)}async mutateCreateImproveRun(e,t){let r=Re.parse(e),s=await this.getCreateImproveRun(r.runId);if(!s)throw new Error(`Create/Improve run not found: ${r.runId}`);if(s.appliedActionIds.includes(r.actionId))return{run:s,replayed:!0};if(s.revision!==r.expectedRevision)throw new Error(`Create/Improve run changed from revision ${r.expectedRevision} to ${s.revision}. Refresh and try again.`);let i=E.parse(t(s));if(i.id!==s.id||i.revision!==s.revision+1||!i.appliedActionIds.includes(r.actionId))throw new Error("Create/Improve mutation must preserve identity, advance one revision and record its action.");return Rt.parse(await this.client.request({contractVersion:g,requestId:r.actionId,operation:"create-improve/execute",params:{action:"mutate",mutation:r,next:i}}))}};import{randomUUID as Tt}from"node:crypto";async function B(n,e){let t=n;for(;;)try{return await e(t)}catch(r){if(!It(r)||t<=1)throw r;t=Math.max(1,Math.floor(t/2))}}a(B,"hostedBoundedPage");function It(n){return n instanceof Error?n.message==="Host storage response is too large."||n.message==="Host storage request failed: host_storage_response_too_large":!1}a(It,"isOversizeResponse");var Pt=o.object({entries:o.array(o.object({sequence:o.number().int().positive(),event:F})).max(200),totalMatchingEvents:o.number().int().nonnegative(),remainingMatchingEvents:o.number().int().nonnegative()}).strict(),J=class{constructor(e){this.client=e}client;static{a(this,"HostedRuntimeEventStorage")}async runtimeEventsForSession(e,t={}){let r=t.limit==null?1e4:Math.max(0,Math.trunc(t.limit));if(r===0)return[];let s=Math.min(r,1e4),i=[],l=Math.max(0,t.afterSequence??0),u=0,d=t.names?new Set(t.names):null;for(;i.length<=s;){let p=await this.runtimeEventPageRows({sessionId:e,afterSequence:l,beforeSequence:null,limit:Math.min(200,s+1-i.length),excludeReasoningDeltas:t.excludeReasoningDeltas});for(let h of p.entries){if(h.sequence<=l)throw new Error("Host event cursor did not advance.");if(l=h.sequence,u+=1,u>1e4)throw new Error("Hosted runtime event scan exceeds 10,000 rows; use a narrower query.");(!d||d.has(h.event.name))&&i.push(h.event)}if(p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break}if(i.length>s||t.limit==null&&r===1e4&&i.length===s)throw new Error("Hosted runtime event read exceeds 10,000 rows; use a bounded cursor query.");return i}async persistedRuntimeEventsForSession(e,t={}){return this.runtimeEventsForSession(e,t)}async appendRuntimeEvent(e){let t=F.parse(e),r=await this.client.request({contractVersion:g,requestId:t.id,operation:"event/append",params:{event:t}});return o.object({event:F}).strict().parse(r).event}async runtimeEventPageRows(e){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit))),r=Math.max(0,Math.trunc(e.afterSequence)),s=e.beforeSequence,i=[],l=0,u=0;for(;i.length<t;){let d=Math.min(200,t-i.length),p=await B(d,async h=>Pt.parse(await this.client.request({contractVersion:g,requestId:`event-page:${Tt()}`,operation:"events/page",params:{sessionId:e.sessionId,afterSequence:r,beforeSequence:s,limit:h,...e.excludeReasoningDeltas?{excludeReasoningDeltas:!0}:{}}})));if(i.length===0&&(l=p.totalMatchingEvents,u=p.remainingMatchingEvents),i=s===null?[...i,...p.entries]:[...p.entries,...i],p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break;if(s===null){let h=p.entries.at(-1).sequence;if(h<=r)throw new Error("Host event cursor did not advance.");r=h}else{let h=p.entries[0].sequence;if(h>=s)throw new Error("Host event cursor did not advance.");s=h}}return{entries:i,totalMatchingEvents:l,remainingMatchingEvents:u}}};import{randomUUID as S}from"node:crypto";var Je=o.object({revision:o.number().int().min(1),session:N}).strict(),ze=o.object({revision:o.number().int().min(1),turn:H}).strict(),xt=o.object({sessions:o.array(N).max(200),nextAfterId:o.string().min(1).nullable()}).strict(),At=o.object({turns:o.array(H).max(200),nextBeforeSortIndex:o.number().int().nonnegative().nullable()}).strict(),z=class{constructor(e){this.client=e}client;static{a(this,"HostedSessionStorage")}async count(){let e=await this.client.request({contractVersion:g,requestId:S(),operation:"session/count",params:{}});return o.object({count:o.number().int().nonnegative()}).strict().parse(e).count}async get(e){let t=await this.client.request({contractVersion:g,requestId:S(),operation:"session/get",params:{sessionId:e}});return t===null?null:Je.parse(t)}async sessionCount(){return this.count()}async sessionShells(){let e=[],t=null;do{let r=await B(Math.min(10,1001-e.length),async s=>xt.parse(await this.client.request({contractVersion:g,requestId:S(),operation:"session/page",params:{afterId:t,limit:s}})));if(e.push(...r.sessions),e.length>1e3)throw new Error("Hosted session list exceeds 1,000 rows; use a scoped page query.");if(r.nextAfterId!==null&&(r.sessions.length===0||t!==null&&r.nextAfterId<=t))throw new Error("Host session cursor did not advance.");t=r.nextAfterId}while(t!==null);return e}async getSession(e){return(await this.get(e))?.session??null}async insertSessionAtFront(e){await this.put({session:e,expectedRevision:null,requestId:S()})}async updateSession(e,t){let r=await this.get(e);if(!r)return null;let s=N.parse(t(r.session));if(s.id!==e)throw new Error("A session update cannot change its identity.");return(await this.put({session:s,expectedRevision:r.revision,requestId:S()})).session}async put(e){let t=N.parse(e.session);return Je.parse(await this.client.request({contractVersion:g,requestId:e.requestId,operation:"session/put",params:{sessionId:t.id,expectedRevision:e.expectedRevision,session:t}}))}async readTurn(e){let t=await this.client.request({contractVersion:g,requestId:S(),operation:"turn/get",params:{turnId:e}});return t===null?null:ze.parse(t)}async getTurn(e){return(await this.readTurn(e))?.turn??null}async turnsForSession(e,t=50){let r=Math.max(1,Math.min(1e3,Math.trunc(t))),s=[],i=null;for(;s.length<r;){let l=await B(Math.min(200,r-s.length),async u=>At.parse(await this.client.request({contractVersion:g,requestId:S(),operation:"turn/page",params:{sessionId:e,beforeSortIndex:i,limit:u}})));if(s.push(...l.turns),l.nextBeforeSortIndex===null)break;if(i!==null&&l.nextBeforeSortIndex>=i)throw new Error("Host turn cursor did not advance.");i=l.nextBeforeSortIndex}return s}async countTurnsForSession(e){let t=await this.client.request({contractVersion:g,requestId:S(),operation:"turn/count",params:{sessionId:e}});return o.object({count:o.number().int().nonnegative()}).strict().parse(t).count}async hasSubagentParentWakeTurn(e,t){return await this.wakeCount(e,"messageId",t)>0}async countSubagentParentWakeTurns(e,t){return this.wakeCount(e,"fromRunId",t)}async latestAssistantTextForSession(e){let t=await this.client.request({contractVersion:g,requestId:S(),operation:"events/latestAssistantText",params:{sessionId:e}});return o.object({text:o.string().nullable()}).strict().parse(t).text}async wakeCount(e,t,r){let s=await this.client.request({contractVersion:g,requestId:S(),operation:"turn/wakeCount",params:{sessionId:e,key:t,value:r}});return o.object({count:o.number().int().nonnegative()}).strict().parse(s).count}async latestTurnForSession(e,t){let r=await this.client.request({contractVersion:g,requestId:S(),operation:"turn/latest",params:{sessionId:e,status:t??null}});return r===null?null:H.parse(r)}async latestPersistedTurnForSession(e,t){return this.latestTurnForSession(e,t)}async insertTurn(e){await this.putTurn({turn:e,expectedRevision:null,requestId:S()})}async updateTurn(e,t){let r=await this.readTurn(e);if(!r)return null;let s=H.parse(t(r.turn));if(s.id!==e||s.sessionId!==r.turn.sessionId)throw new Error("A turn update cannot change its identity.");return(await this.putTurn({turn:s,expectedRevision:r.revision,requestId:S()})).turn}async putTurn(e){let t=H.parse(e.turn);return ze.parse(await this.client.request({contractVersion:g,requestId:e.requestId,operation:"turn/put",params:{sessionId:t.sessionId,turnId:t.id,expectedRevision:e.expectedRevision,turn:t}}))}};import{createHash as Ct,randomUUID as Et}from"node:crypto";var P=o.object({ok:o.literal(!0)}).strict(),Y=o.array(O),Ot=o.array(o.string()),kt=o.object({turnId:o.string(),run:_}).strict(),_t=o.object({inputs:o.array(O).max(10),hasMore:o.boolean()}).strict(),Ht=o.object({items:o.array(L).max(10),hasMore:o.boolean()}).strict(),Mt=o.object({items:o.array(o.string()).max(200),hasMore:o.boolean()}).strict();function K(n,e){return`inbox:${n}:${Ct("sha256").update(JSON.stringify(e)).digest("hex")}`}a(K,"retryKey");var M=class{constructor(e){this.client=e}client;static{a(this,"HostedTaskInboxStorage")}async call(e,t,r=Et()){let s=await this.client.request({contractVersion:g,requestId:r,operation:"task-inbox/execute",params:e});return t.parse(s)}async inputPages(e,t=Number.MAX_SAFE_INTEGER){let r=[],s=0;for(;r.length<t;){let i=await this.call(e(s),_t);for(let l of i.inputs){if(l.sequence<=s)throw new Error("Host task input cursor did not advance.");if(s=l.sequence,r.push(l),r.length>=t)break}if(!i.hasMore)return r;if(i.inputs.length===0)throw new Error("Host task input page made no progress.")}return r}async recoverTaskInboxOwners(e){return this.call({action:"recoverTaskInboxOwners",ownerId:e},o.array(o.object({sessionId:o.string(),turnId:o.string()}).strict()))}async hasTaskCompletion(e){return this.call({action:"hasTaskCompletion",turnId:e},o.boolean())}async taskInboxSnapshot(e){let t=await this.call({action:"taskInboxSnapshot",sessionId:e},Ie),[r,s]=await Promise.all([this.inputPages(i=>({action:"taskInboxSnapshotInputs",sessionId:e,afterSequence:i})),this.taskWaitsForSession(e)]);return{...t,inputs:r,waits:s}}async declareTaskWork(e,t,r,s){await this.call({action:"declareTaskWork",sessionId:e,turnId:t,ownerId:r,areas:s},P)}async taskWorkAreas(e){return this.call({action:"taskWorkAreas",sessionId:e},Ot)}async admitTaskInput(e){return this.call({action:"admitTaskInput",input:e},O)}async admitTaskInputs(e){return this.call({action:"admitTaskInputs",inputs:e},Y)}async rejectTaskInput(e,t){await this.call({action:"rejectTaskInput",id:e,error:t},P)}async getTaskInput(e){return this.call({action:"getTaskInput",id:e},O.nullable())}async taskInputsForSession(e,t={}){let r=Math.max(1,Math.min(500,t.limit??128)),s=[],i=t.afterSequence??0;for(;s.length<r;){let l=Math.min(10,r-s.length),u=await this.call({action:"taskInputsForSession",sessionId:e,query:{afterSequence:i,pendingOnly:t.pendingOnly,limit:l}},Y);if(!u.length)break;for(let d of u){if(d.sequence<=i)throw new Error("Host task input cursor did not advance.");i=d.sequence,s.push(d)}if(u.length<l)break}return s}async mutateTaskInput(e,t,r){return this.call({action:"mutateTaskInput",sessionId:e,inputId:t,change:r},O,K("mutate",{sessionId:e,inputId:t,change:r}))}async openTaskInboxTurn(e,t,r){await this.call({action:"openTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},P,K("open",{sessionId:e,turnId:t,ownerId:r}))}async renewTaskInboxTurn(e,t,r){await this.call({action:"renewTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},P)}async pendingTaskInputs(e,t){return this.inputPages(r=>({action:"pendingTaskInputs",sessionId:e,turnId:t,afterSequence:r}))}async taskAssignmentInputs(e){return this.inputPages(t=>({action:"taskAssignmentInputs",turnId:e,afterSequence:t}))}async pauseTaskInboxTurn(e,t,r){await this.call({action:"pauseTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},P)}async includeTaskInputs(e,t,r,s){return this.call({action:"includeTaskInputs",sessionId:e,turnId:t,ownerId:r,requestId:s},Y,K("include",{sessionId:e,turnId:t,ownerId:r,requestId:s}))}async settleTaskInputRequest(e,t){await this.call({action:"settleTaskInputRequest",requestId:e,outcome:t},P)}async sealTaskInboxTurn(e,t,r){return this.call({action:"sealTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},o.boolean())}async sealNativeTaskInboxTurn(e,t,r){return this.call({action:"sealNativeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},Y)}async closeTaskInboxTurn(e,t,r,s){await this.call({action:"closeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r,outcome:s},P)}async taskInboxPaused(e){return this.call({action:"taskInboxPaused",sessionId:e},o.boolean())}async reserveTaskFollowup(e,t,r){return this.call({action:"reserveTaskFollowup",sessionId:e,turnId:t,ownerId:r},O.nullable(),K("reserve",{sessionId:e,turnId:t,ownerId:r}))}async taskInboxWakeTargets(){let e=[],t="";for(;;){let r=await this.call({action:"taskInboxWakeTargets",afterSessionId:t},Mt);for(let s of r.items){if(s<=t)throw new Error("Host task wake cursor did not advance.");t=s,e.push(s)}if(!r.hasMore)return e;if(!r.items.length)throw new Error("Host task wake page made no progress.")}}async createTaskWait(e){return this.call({action:"createTaskWait",value:e},L)}async settleTaskWait(e,t){return this.call({action:"settleTaskWait",id:e,state:t},L)}async taskWaitsForSession(e){let t=[],r="";for(;;){let s=await this.call({action:"taskWaitsForSession",sessionId:e,afterId:r},Ht);for(let i of s.items){if(i.id<=r)throw new Error("Host task wait cursor did not advance.");r=i.id,t.push(i)}if(!s.hasMore)return t;if(!s.items.length)throw new Error("Host task wait page made no progress.")}}async commitSubagentCompletion(e,t){await this.call({action:"commitSubagentCompletion",value:e,turnId:t},P)}async pendingTaskCompletions(e=""){let t=[],r=e;for(;t.length<100;){let s=await this.call({action:"pendingTaskCompletions",afterTurnId:r},o.array(kt).max(10));for(let i of s){if(i.turnId<=r)throw new Error("Host task completion cursor did not advance.");r=i.turnId,t.push(i)}if(s.length<10)break}return t}async settleTaskCompletion(e,t){await this.call({action:"settleTaskCompletion",turnId:e,inputId:t},P)}async upsertSubagentRun(e){return this.call({action:"upsertSubagentRun",value:_.parse(e)},_)}async getSubagentRun(e){return this.call({action:"getSubagentRun",id:e},_.nullable())}async listSubagentRuns(e={}){let r=[],s="",i=e.status?Array.isArray(e.status)?[...e.status]:[e.status]:null;for(;;){let l=await this.call({action:"listSubagentRuns",query:{parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,status:i,afterId:s,limit:10}},o.array(_).max(10));for(let u of l){if(u.id<=s)throw new Error("Host subagent run cursor did not advance.");if(s=u.id,r.push(u),r.length>1e3)throw new Error("Hosted subagent run list exceeds 1,000 rows; use a narrower session or status query.")}if(l.length<10)break}return r.sort((l,u)=>(u.updatedAt??u.createdAt).localeCompare(l.updatedAt??l.createdAt)),e.limit===void 0?r:r.slice(0,Math.max(1,Math.min(1e3,e.limit)))}async listActiveSubagentRuns(e={}){return this.listSubagentRuns({...e,status:e.status??["queued","running","needs_resume"]})}};var se=class extends M{static{a(this,"HostedTurnRepository")}sessions;events;approvals;usage;createImprove;constructor(e){super(e),this.sessions=new z(e),this.events=new J(e),this.approvals=new $(e),this.usage=new W(e),this.createImprove=new G(e)}sessionShells(){return this.sessions.sessionShells()}sessionCount(){return this.sessions.sessionCount()}getSession(e){return this.sessions.getSession(e)}insertSessionAtFront(e){return this.sessions.insertSessionAtFront(e)}updateSession(e,t){return this.sessions.updateSession(e,t)}getTurn(e){return this.sessions.getTurn(e)}insertTurn(e){return this.sessions.insertTurn(e)}updateTurn(e,t){return this.sessions.updateTurn(e,t)}latestTurnForSession(e,t){return this.sessions.latestTurnForSession(e,t)}latestPersistedTurnForSession(e,t){return this.sessions.latestPersistedTurnForSession(e,t)}turnsForSession(e,t){return this.sessions.turnsForSession(e,t)}countTurnsForSession(e){return this.sessions.countTurnsForSession(e)}hasSubagentParentWakeTurn(e,t){return this.sessions.hasSubagentParentWakeTurn(e,t)}countSubagentParentWakeTurns(e,t){return this.sessions.countSubagentParentWakeTurns(e,t)}latestAssistantTextForSession(e){return this.sessions.latestAssistantTextForSession(e)}appendRuntimeEvent(e){return this.events.appendRuntimeEvent(e)}runtimeEventsForSession(e,t){return this.events.runtimeEventsForSession(e,t)}persistedRuntimeEventsForSession(e,t){return this.events.persistedRuntimeEventsForSession(e,t)}runtimeEventPageRows(e){return this.events.runtimeEventPageRows(e)}getApproval(e){return this.approvals.getApproval(e)}async upsertApproval(e){let t=await this.approvals.readApproval(e.id);t&&JSON.stringify(t.approval)===JSON.stringify(e)||await this.approvals.putApproval({approval:e,expectedRevision:t?.revision??null,requestId:`approval:${Ut("sha256").update(JSON.stringify({approval:e,revision:t?.revision??null})).digest("hex")}`})}upsertModelUsageRecord(e){return this.usage.upsertModelUsageRecord(e)}listModelUsageRecords(e){return this.usage.listModelUsageRecords(e)}getCreateImproveRun(e){return this.createImprove.getCreateImproveRun(e)}listCreateImproveRuns(e){return this.createImprove.listCreateImproveRuns(e)}upsertCreateImproveRun(e){return this.createImprove.upsertCreateImproveRun(e)}mutateCreateImproveRun(e,t){return this.createImprove.mutateCreateImproveRun(e,t)}};function Ye(n){return new se(n)}a(Ye,"createHostedRuntimeCoreStorage");function Ke(n=process.env){let e=n.OPENPOND_API_KEY?.trim(),t=n.OPENPOND_OPCHAT_API_URL?.trim(),r=n.OPENPOND_HOSTED_MODEL_ID?.trim();if(!e||!t||!r)throw new Error("Hosted model stream requires a host credential, API URL, and admitted model.");let s=new URL(t);if(s.protocol!=="https:"||s.username||s.password||s.search||s.hash)throw new Error("Hosted model stream API URL is invalid.");return a(async function*(l){if(l.model!==r)throw new Error("Hosted model selection changed outside host admission.");yield*Ee({...l,apiBaseUrl:s.toString(),token:e,model:r})},"streamHostedModel")}a(Ke,"createHostedModelStreamFromEnvironment");import{existsSync as Nt}from"node:fs";import I from"node:path";import{fileURLToPath as qt}from"node:url";var Qe=I.dirname(qt(import.meta.url));function R(n,e,t){let r=n[e+1];if(!r||r.startsWith("--"))throw new Error(`${t} requires a value.`);return r}a(R,"requireValue");function Xe(n,e){let t=Number.parseInt(n,10);if(!Number.isFinite(t)||t<0||t>65535)throw new Error(`${e} must be a port from 0 to 65535.`);return t}a(Xe,"parsePort");function tt(n){let e="serve",t=Z,r=17874,s=null,i=!1,l=!1,u=null,d,p=null,h=null,b=null,T=null,x,f="sqlite_bundle",v=0,w=n[0];if(w&&!w.startsWith("-")){if(w==="serve"||w==="server")e="serve";else if(w==="app-server")e="app-server";else if(w==="web")e="web";else{if(w==="help")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:l,storeDir:u,runtimeStorage:f,help:!0};throw new Error(`Unknown command: ${w}`)}v=1}for(let c=v;c<n.length;c+=1){let m=n[c];if(m==="--help"||m==="-h")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:l,storeDir:u,runtimeStorage:f,help:!0};if(m==="--listen"){let C=Pe(R(n,c,m));t=C.host,r=Xe(String(C.port),m),c+=1}else if(m==="--hostname"||m==="--host")t=R(n,c,m),c+=1;else if(m==="--port")r=Xe(R(n,c,m),m),c+=1;else if(m==="--web-root")s=I.resolve(R(n,c,m)),c+=1;else if(m==="--source-browser-state")d=I.resolve(R(n,c,m)),c+=1;else{if(m==="--store-dir")throw new Error("--store-dir has been replaced by --home. Use --home <directory> or OPENPOND_HOME.");if(m==="--home")u=I.resolve(R(n,c,m)),c+=1;else if(m==="--runtime-storage"){if(R(n,c,m)!=="hosted-postgres")throw new Error("Unsupported app-server runtime storage.");f="hosted_postgres",c+=1}else if(m==="--profile-source-root")p=I.resolve(R(n,c,m)),c+=1;else if(m==="--profile-repository-id")h=R(n,c,m),c+=1;else if(m==="--profile-id")b=R(n,c,m),c+=1;else if(m==="--profile-revision")T=R(n,c,m),c+=1;else if(m==="--hosted-profile-release"){if(x)throw new Error("Duplicate hosted Profile release descriptor.");let C=R(n,c,m);if(C.length>16e3||!/^[A-Za-z0-9_-]+$/.test(C))throw new Error("Invalid hosted Profile release descriptor.");try{x=He.parse(JSON.parse(Buffer.from(C,"base64url").toString("utf8")))}catch{throw new Error("Invalid hosted Profile release descriptor.")}c+=1}else if(m==="--open-browser")i=!0;else if(m==="--print-access-url")l=!0;else throw new Error(`Unknown option: ${m}`)}}if(i&&l)throw new Error("--open-browser and --print-access-url cannot be used together.");if(e!=="web"&&(i||l))throw new Error("Browser options are only available in web mode.");let A=[p,h,b,T].filter(Boolean).length;if(A&&(A!==4||e!=="app-server"))throw new Error("Profile source flags require app-server mode and --profile-source-root, --profile-repository-id, --profile-id, and --profile-revision together.");if(f==="hosted_postgres"&&(e!=="app-server"||u||A))throw new Error("Hosted Postgres app-server cannot use --home or local Profile source flags.");if(x&&f!=="hosted_postgres")throw new Error("Hosted Profile release requires hosted Postgres app-server mode.");return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:l,storeDir:u,runtimeStorage:f,sourceBrowserState:d,...A?{profileSource:{repoPath:p,repositoryId:h,profileId:b,sourceRevision:T}}:{},...x?{admittedProfileRelease:x}:{},help:!1}}a(tt,"parseCliArgs");function Bt(){return[process.env.OPENPOND_WEB_ROOT,I.resolve(process.cwd(),"apps/web/dist"),I.resolve(Qe,"../../web/dist"),I.resolve(process.cwd(),"web"),I.resolve(Qe,"../web")].filter(n=>!!n)}a(Bt,"defaultWebRootCandidates");function Dt(n){let e=n?[n]:Bt();for(let t of e){let r=I.resolve(t);if(Nt(I.join(r,"index.html")))return r}return null}a(Dt,"resolveWebRoot");function Ft(n){let e=n==="0.0.0.0"||n==="::"?"127.0.0.1":n;return e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}a(Ft,"formatHostForUrl");function jt(n){return`http://${Ft(n.status.host)}:${n.status.port}`}a(jt,"browserBaseUrl");function Lt(n,e){let t=new URL(n),r=new URLSearchParams;return r.set("openpondServerUrl",n),r.set("openpondToken",e),t.hash=r.toString(),t.toString()}a(Lt,"tokenizedWebUrl");async function Ze(n,e=ke){let t=Lt(n.baseUrl,n.token);if(n.printAccessUrl)return{stdout:[`OpenPond access URL: ${t}`],stderr:[]};if(!n.openBrowser)return{stdout:[`OpenPond web UI: ${n.baseUrl}`],stderr:[]};let r=await e(t);return r.opened?{stdout:[`Opened OpenPond in your browser: ${n.baseUrl}`],stderr:[]}:{stdout:[`OpenPond access URL: ${t}`],stderr:[`Could not open the system browser: ${r.error}`]}}a(Ze,"resolveWebLaunchMessages");function rt(){console.log(`Usage:
|
|
24
|
-
openpond-app-server serve [--hostname HOST] [--port PORT]
|
|
25
|
-
openpond-app-server app-server [--home DIR]
|
|
26
|
-
openpond-app-server web [--hostname HOST] [--port PORT] [--web-root DIR]
|
|
27
|
-
|
|
28
|
-
Options:
|
|
29
|
-
--listen HOST:PORT Set host and port together
|
|
30
|
-
--hostname HOST Bind host (default ${Z})
|
|
31
|
-
--port PORT Bind port, or 0 for any free port (default ${17874})
|
|
32
|
-
--web-root DIR Directory containing the built web UI for web mode
|
|
33
|
-
--home DIR Local app-server state directory
|
|
34
|
-
--runtime-storage hosted-postgres Host-admitted Postgres app-server mode
|
|
35
|
-
--hosted-profile-release BASE64URL Host-admitted immutable Profile release descriptor
|
|
36
|
-
--profile-source-root DIR Authorized Profile repository source for app-server
|
|
37
|
-
--profile-repository-id ID Source repository identity supplied by the host
|
|
38
|
-
--profile-id ID Profile within that source
|
|
39
|
-
--profile-revision REV Accepted immutable source revision
|
|
40
|
-
--open-browser Open the authenticated web URL in the system browser
|
|
41
|
-
--print-access-url Print the authenticated URL instead of opening it
|
|
42
|
-
`)}a(rt,"printHelp");async function yn(n){let e=tt(process.argv.slice(2));if(e.help){rt();return}let t=e.mode==="web"?Dt(e.webRoot):null;if(e.mode==="web"&&!t)throw new Error("Could not find a built OpenPond web UI. Run `pnpm build:web` or pass --web-root.");if(e.mode==="app-server"){await nt(n.createOpenPondAppServer,e.storeDir,e.profileSource,e.runtimeStorage);return}e.storeDir&&(process.env.OPENPOND_HOME=e.storeDir);let r,s=e.port;for(;;)try{r=await n.createOpenPondServer({host:e.host,port:s,webRoot:t,sourceBrowserState:e.sourceBrowserState,...e.storeDir?{storeDir:e.storeDir}:{},httpEnabled:!0});break}catch(d){if(!je(d))throw d;let p=await Le(ie({home:e.storeDir??void 0}),s,d);s=p.port,console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:"recovery",url:p.url,tokenFile:p.tokenFile,storePath:p.storePath})}`),console.error(`${d.issue.code}: ${d.issue.message} ${d.issue.action}`);let h=await Ze({baseUrl:p.url,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:p.token});for(let T of h.stdout)console.log(T);for(let T of h.stderr)console.error(T);let b=a(()=>{p.close().finally(()=>process.exit(0))},"close");process.once("SIGINT",b),process.once("SIGTERM",b);try{await p.repaired}finally{process.off("SIGINT",b),process.off("SIGTERM",b),await p.close()}}let i=e.mode==="web"?jt(r):null;if(console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:e.mode,url:r.url,webUrl:null,webRoot:t,tokenFile:r.tokenFile,storePath:r.storePath,runtime:Oe()})}`),i){let d=await Ze({baseUrl:i,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:r.token});for(let p of d.stderr)console.error(p);for(let p of d.stdout)console.log(p)}else console.log(`OpenPond API server: ${r.url}`);let l=!1,u=a(async()=>{l||(l=!0,await r.close(),process.exit(0))},"shutdown");process.on("SIGINT",()=>{u()}),process.on("SIGTERM",()=>{u()}),await new Promise(()=>{})}a(yn,"runOpenPondServerCli");async function Rn(n){let e=process.argv.slice(2),t=tt(!e[0]||e[0].startsWith("-")?["app-server",...e]:e);if(t.help){rt();return}if(t.mode!=="app-server")throw new Error("The app-server entrypoint only accepts the app-server command.");await nt(n,t.storeDir,t.profileSource,t.runtimeStorage,t.admittedProfileRelease)}a(Rn,"runOpenPondAppServerCli");async function nt(n,e,t,r="sqlite_bundle",s){let i=new Ce;if(r==="hosted_postgres"){if(e||t)throw new Error("Hosted Postgres app-server cannot use local storage sources.");await ee({appServer:a(()=>n({hostStorageClient:i,runtimeStorage:{kind:"hosted_postgres",client:i,core:Ye(i),inbox:new M(i),...s?{admittedProfileRelease:s}:{}},streamOpenPondHostedChatTurn:Ke()}),"appServer"),readable:process.stdin,writable:process.stdout,hostStorageClient:i});return}e&&(process.env.OPENPOND_HOME=e);let l=await n({...e?{storeDir:e}:{},...t?{profileSource:t}:{},hostStorageClient:i});await ee({appServer:l,readable:process.stdin,writable:process.stdout,hostStorageClient:i})}a(nt,"runAgentServer");export{Me as a,q as b,qe as c,y as d,zt as e,Yt as f,te as g,Be as h,Ze as i,yn as j,Rn as k};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{$ as ge,$a as ne,$b as V,Ba as we,Da as N,Ea as p,La as je,Mb as Ge,Pb as Ne,Ra as Ve,Ta as qe,Tb as We,Ya as $e,Z as ke,_a as Le,aa as G,ba as re,cb as Re,cc as U,db as W,dc as Ke,eb as K,ec as Te,fb as oe,fc as Je,gb as Oe,hb as ze,hc as ie,jb as Y,kb as A,kc as ce,lb as Q,p as Ce,pc as Xe,r as Fe,tc as be,uc as Se,wc as xe}from"./chunk-JFSDNQHW.js";import{n as he,o as ve,p as Ae}from"./chunk-B5LKUQGM.js";import{$a as Z,Ab as X,Cb as te,Eb as _e,Lb as v,Mb as j,Nb as H,Ob as Be,Qb as se,Sb as ae,a as B,bc as z,fb as Ie,ib as He,jb as Ee,kb as Me,lb as De,sb as O,tb as J,vb as $,xb as ee}from"./chunk-5BFWDFPX.js";import{b as g}from"./chunk-ES2ISFJC.js";import{a as S}from"./chunk-FTQLQJQV.js";var de=J.shape.id,Ye=g.object({schemaVersion:g.literal("openpond.modelBatchReviewInspection.v1"),packageHash:g.string().regex(/^[a-f0-9]{64}$/),definition:$,binding:Ie,evidence:g.array(X).min(1).max(1e4),decisions:g.array(_e).min(1).max(1e4)}).strict(),Pe=g.object({schemaVersion:g.literal("openpond.modelBatchReviewRequest.v1"),operationId:de,modelId:de,expectedModelRevision:g.number().int().positive(),tasksetRef:J,rewardBindingRef:J.nullable(),definition:g.object({name:g.string().trim().min(1).max(500).optional(),instructions:g.string().trim().min(1).max(2e4).optional(),inputSchema:O.optional(),outputSchema:O.optional(),requiredOutputs:$.shape.requiredOutputs}).strict(),examples:g.array(g.object({evidence:J,input:O.optional(),expected:O.nullable().optional(),evaluatorContext:O.nullable().optional(),proposedTarget:O.nullable().optional()}).strict()).max(1e4)}).strict(),Qe=g.object({schemaVersion:g.literal("openpond.modelBatchReviewReceipt.v1"),operationId:de,modelId:de,source:ee,evidence:g.array(X).min(1).max(1e4),proposals:g.array(te).max(1e4)}).strict();function rt(s){let e=A(s.source),t=A(s.edited),a=s.preparation;if(a.authoringGraph!=="bound"||!e.modelResources||e.learningResources||t.modelResources||t.learningResources)throw new Error("Bound task editing requires its source Reward and an ordinary edited workspace.");if(e.contentHash!==a.sourcePackageHash||!j(v(e.taskset),a.sourceTasksetRef))throw new Error("Bound draft differs from its retained source package.");let i=S(b=>b.taskset.graders.map(F=>F.kind==="custom_verifier"?{...F,exportName:F.exportName??"verify"}:F),"normalizedGraders");if(p(i(e))!==p(i(t)))throw new Error("Edit the saved Reward in Rewards before changing this Taskset's graders.");let m=e.modelResources,u=new Map(m.assets.map(b=>[b.id,b])),k=K(t),x=K(e),R=S(b=>{let{id:F,revision:pe,contentHash:fe,metadata:ue,...st}=b,{javascriptEnvironment:vt,...ye}=ue;return{...st,metadata:{...ye,resources:ye.resources??[]}}},"environmentContent"),n=S(b=>{if(!b)return null;let{id:F,revision:pe,contentHash:fe,...ue}=b.execution.javascript;return ue},"javascriptContent"),w=p(R(e.environment))===p(R(t.environment))&&p(n(x))===p(n(k)),c=w?e.environment:t.environment,l=w?x:k,d=new Set([...m.assets.map(b=>b.id),...t.taskset.tasks.flatMap(b=>b.privilegedContextRef?[b.privilegedContextRef]:[]),...[t.environment.actionSchemaRef,t.environment.observationSchemaRef,t.environment.stateSchemaRef].flatMap(b=>b?[b.id]:[]),...k?.assets.map(b=>b.id)??[]]);for(let b of d){let F=t.files.find(fe=>fe.asset.id===b);if(!F)throw new Error(`Bound Taskset asset is missing: ${b}.`);let pe=new TextDecoder("utf-8",{fatal:!0}).decode(W(F));u.set(b,se.parse(H({schemaVersion:"openpond.learningTextAsset.v1",id:b,revision:1,asset:F.asset,text:pe})))}let I=Y(t),{contentHash:E,...M}=m.taskDefinition,{policy:h,environment:P,environmentRelease:C,tools:q,capabilities:r,verifierSetRelease:f}=t.taskset,T=$.parse(H({...M,instructions:I,execution:{policy:h,environment:P,environmentRelease:C,tools:q,capabilities:r,verifierSetRelease:f}})),{contentHash:D,...o}=t.taskset,y=Z.parse(H({...o,tasks:t.taskset.tasks.map(b=>m.instructionMode==="per_task"?b:{...b,policyVisibleContext:{...b.policyVisibleContext,instructions:I}})})),_=ne({owner:a.lineage.owner,source:{...m,taskset:e.taskset,executionResources:{environment:e.environment,verifierSet:e.verifierSet}},rewardBinding:m.rewardBinding,rewards:m.rewards,assets:[...u.values()],edits:{taskset:y,taskDefinition:T,executionResources:{environment:c,verifierSet:t.verifierSet},...l?{execution:l.execution}:{}}}),L=$e.parse(_.taskset.metadata.modelTasksetDerivation);if(_.taskset.id!==a.tasksetId||_.taskset.revision!==a.tasksetRevision||p({...L,schemaVersion:a.lineage.schemaVersion})!==p(a.lineage))throw new Error("Bound draft differs from its retained ownership lineage.");let{taskset:le,executionResources:et,...tt}=_;return Q({schemaVersion:"openpond.tasksetPackage.v1",taskset:le,...et,modelResources:tt,files:t.files})}S(rt,"publishBoundModelTasksetDraftPackage");function nt(s){let e=ge.parse(s.request),t=ke.parse(s.owner),a=A(s.source);if(a.learningResources)throw new Error("Reviewed Tasksets require their reviewed authoring workflow.");if(a.contentHash!==e.sourcePackageHash)throw new Error("Taskset draft source package changed.");if(a.modelResources){let x=Le({owner:t,source:{...a.modelResources,taskset:a.taskset,executionResources:{environment:a.environment,verifierSet:a.verifierSet}},rewardBinding:a.modelResources.rewardBinding,rewards:a.modelResources.rewards,assets:a.modelResources.assets}),R=x.taskset.metadata.modelTasksetDerivation;return G.parse({schemaVersion:"openpond.modelTasksetDraftPreparation.v1",draftId:`model-taskset-draft-${p({owner:t,operationId:e.operationId})}`,requestHash:p(e),sourcePackageHash:a.contentHash,sourceTasksetRef:v(a.taskset),tasksetId:x.taskset.id,tasksetRevision:x.taskset.revision,lineage:{...R,schemaVersion:"openpond.modelTasksetAuthoring.v1"},authoringGraph:"bound"})}let i=ze(a.taskset),m=i&&p(i.owner)===p(t),u=m?i.root:v(a.taskset),k={schemaVersion:"openpond.modelTasksetAuthoring.v1",owner:t,root:u,parent:v(a.taskset)};return G.parse({schemaVersion:"openpond.modelTasksetDraftPreparation.v1",draftId:`model-taskset-draft-${p({owner:t,operationId:e.operationId})}`,requestHash:p(e),sourcePackageHash:a.contentHash,sourceTasksetRef:v(a.taskset),tasksetId:Oe(k),tasksetRevision:m?a.taskset.revision+1:1,lineage:k})}S(nt,"prepareModelTasksetDraft");function ot(s){let e=G.parse(s.preparation);if(!j(e.sourceTasksetRef,e.lineage.parent))throw new Error("Taskset draft preparation differs from its source lineage.");if(e.authoringGraph==="bound"){if(!s.source)throw new Error("Bound Taskset authoring requires its retained source package.");return rt({preparation:e,source:s.source,edited:s.edited})}let t=it(s.edited),{contentHash:a,...i}=t.verifierSet,m=Fe({...i,id:`${e.tasksetId}-verifiers`,revision:e.tasksetRevision,calibrationReceiptRefs:[],metadata:{sourceVerifierSet:v(t.verifierSet)}}),{contentHash:u,...k}=t.taskset,x=Z.parse(H({...k,id:e.tasksetId,revision:e.tasksetRevision,verifierSetRelease:{id:m.id,contentHash:m.contentHash},metadata:{modelTasksetAuthoring:e.lineage,...t.taskset.metadata.environmentResources===void 0?{}:{environmentResources:t.taskset.metadata.environmentResources},...t.taskset.metadata.ordinaryAuthoring===void 0?{}:{ordinaryAuthoring:t.taskset.metadata.ordinaryAuthoring}}})),R=K(t),n=R?[...t.files.filter(w=>w.asset.id!==qe(t.taskset)),oe({...R.execution,verifierSet:m})]:t.files;return Q({schemaVersion:"openpond.tasksetPackage.v1",taskset:x,environment:t.environment,verifierSet:m,files:n})}S(ot,"publishModelTasksetDraftPackage");function it(s){let e=A(s);if(e.modelResources||e.learningResources)throw new Error("This Taskset requires its bound or reviewed authoring workflow.");return e}S(it,"requireOrdinaryPackage");function ct(s,e,t,a){if(s.environment.entrypoint!=="openpond.javascript-environment.v1")return{taskset:s,inventory:t,generatedFiles:[]};let i="environment/execution.json",m=e.get(i);if(!m||m.length>524288)throw new Error("Authored tool environment requires its bounded private execution declaration.");let u=Ve.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m))),k=S(M=>{if(!M)return null;let h=t.find(P=>P.asset.id===M.id&&P.asset.path===M.path);if(!h)throw new Error(`Authored environment dependency is missing: ${M.id}.`);return h.asset},"repin"),{contentHash:x,...R}=u.javascript,n=je.parse(H({...R,id:`javascript-${s.id}`,revision:s.revision,module:k(u.javascript.module)}));if(p(n.tools)!==p(s.environment.metadata.portableTools)||p(n.tools.map(M=>M.name))!==p(s.environment.toolNames))throw new Error("Authored environment tools differ from the Taskset's declared tools.");let w=Ce({schemaVersion:"openpond.environmentRelease.v1",id:`environment-${s.id}`,revision:s.revision,contract:Se(s),actionSchemaRef:k(u.environment.actionSchemaRef),observationSchemaRef:k(u.environment.observationSchemaRef),stateSchemaRef:k(u.environment.stateSchemaRef),artifactCollection:u.environment.artifactCollection,adapterConformanceHashes:{},metadata:{javascriptEnvironment:v(n),resources:s.environment.resources??[]}}),c=V.parse({...s,environment:{...s.environment,metadata:{...s.environment.metadata,portableExecutionResources:{environment:w}}}}),l=be({taskset:c,adapterId:a}),d=oe({javascript:n,environment:w,verifierSet:l.verifierSetRelease}),I=[...t.filter(M=>M.sourcePath!==i),{asset:d.asset,sourcePath:i}],E=V.parse({...c,metadata:{...c.metadata,portableFileInventory:I}});return{taskset:V.parse({...E,contentHash:U(E)}),inventory:I,generatedFiles:[{path:i,role:"environment",content:new TextDecoder().decode(W(d))}]}}S(ct,"prepareAuthoredToolEnvironment");var me=g.array(g.object({asset:we,sourcePath:g.string().min(1)}).strict()).max(1e4),dt=new Set(["taskset.json","capabilities.json","data/tasks.jsonl","graders/graders.json","fixtures/grader-fixtures.json","environment/taskset.ts"]);function mt(s){return dt.has(s)}S(mt,"isGeneratedTasksetPublicationFilePath");function lt(s,e,t){let a=V.parse(s);if(a.metadata.taskDefinition!==void 0||a.metadata.rewardBinding!==void 0)return{taskset:a,generatedFiles:[]};let i=new Map,m=0;for(let[r,f]of e){if(re.parse(r),m+=f.byteLength,i.size>=1e4||m>Re*3/4)throw new Error("Taskset source exceeds the package byte limit.");i.set(r,f.slice())}let u=a.metrics?.customAggregator,k=u?i.get(u.module):void 0;if(u&&!k)throw new Error("Declared Taskset metric module is missing.");let x=u&&k?{...a.metrics,customAggregator:{...u,contentHash:N(k)}}:a.metrics,R=new Map,n=new Set,w=[],c=S((r,f,T,D)=>{let o=i.get(f);if(!o)throw new Error(`Declared Taskset file is missing: ${f}.`);return{id:r,path:f,contentHash:N(o),sizeBytes:o.byteLength,mediaType:T,visibility:D}},"ref"),l=S((r,f=r.path)=>{let T=R.get(r.id);if(T&&p(T)!==p({asset:r,sourcePath:f}))throw new Error(`Conflicting Taskset file identity: ${r.id}.`);let D=i.get(f);if(!D||D.length!==r.sizeBytes||N(D)!==r.contentHash)throw new Error(`Taskset file differs from its declared bytes: ${r.id}.`);R.set(r.id,{asset:r,sourcePath:f}),n.add(f)},"add");for(let r of a.tasks){let f=xe(r);for(let T of f.artifactRefs)l(T,r.assets?.find(D=>D.id===T.id)?.artifactRef??T.path);for(let T of f.requiredOutputs??[])T.schemaRef&&l(T.schemaRef)}for(let r of a.environment.resources??[])l(c(r.id,r.path,r.mediaType??"application/octet-stream",r.visibility==="policy_visible"?"policy":"host_private"));let d=a.graders.map(r=>{if(r.kind==="custom_verifier"){let f=c(`verifier-${r.id}`,r.module,"application/javascript","host_private"),T=we.safeParse(r.metadata.portableVerifierRef);return T.success&&T.data.contentHash===f.contentHash&&T.data.sizeBytes===f.sizeBytes&&(f=T.data),l(f,r.module),{...r,metadata:{...r.metadata,portableVerifierRef:f}}}if(r.kind==="human"||r.kind==="model_judge"){let f=new TextEncoder().encode(r.rubric),T=`graders/rubric-${N(f)}.md`;i.set(T,f);let D=c(`rubric-${r.id}`,T,"text/markdown","verifier");return l(D),w.push({path:T,role:"verifier",content:r.rubric}),{...r,metadata:{...r.metadata,portableRubricRef:D}}}return r});u&&![...R.values()].some(r=>r.asset.path===u.module&&r.sourcePath===u.module&&r.asset.visibility!=="policy")&&l(c(`metric-${p(u.module)}`,u.module,"application/javascript","host_private"));let I=me.parse(a.metadata.portableFileInventory??[]);for(let r of[...i.keys()].sort())if(!n.has(r)){let f=I.find(T=>T.sourcePath===r&&!R.has(T.asset.id));l(f?{...c(f.asset.id,r,f.asset.mediaType,f.asset.visibility),path:f.asset.path}:c(`taskset-file-${p(r)}`,r,"application/octet-stream","host_private"),r)}let{importedPackageHash:E,derivedPortableMetadata:M,...h}=a.metadata,P={...a.environment.metadata};if(P.portableExecutionResources!==void 0){let r=g.object({environment:g.unknown(),verifierSet:g.unknown().optional()}).parse(P.portableExecutionResources);P.portableExecutionResources={environment:r.environment}}let C=V.parse({...a,graders:d,metrics:x,environment:{...a.environment,metadata:P},metadata:{...h,...E===void 0?{}:{sourceImportedPackageHash:E},portableFileInventory:me.parse([...R.values()].sort((r,f)=>r.asset.id.localeCompare(f.asset.id)))}}),q=ct(C,i,[...R.values()],t);return{taskset:V.parse({...q.taskset,contentHash:U(q.taskset)}),generatedFiles:[...w,...q.generatedFiles]}}S(lt,"prepareAuthoredTasksetSource");function Is(s){let e=A(s.source);if(e.modelResources||e.learningResources)throw new Error("Binding an ordinary Reward requires an ordinary source package.");let t=Y(e);if(!t.trim())throw new Error("Add collection instructions before selecting a saved Reward.");let a=new Map,i=K(e);for(let h of i?.assets??[])a.set(h.id,h);let m=new Set([...e.taskset.tasks.flatMap(h=>h.privilegedContextRef?[h.privilegedContextRef]:[]),...[e.environment.actionSchemaRef,e.environment.observationSchemaRef,e.environment.stateSchemaRef].flatMap(h=>h?[h.id]:[])]);for(let h of m){if(a.has(h))continue;let P=e.files.find(q=>q.asset.id===h);if(!P)throw new Error(`Source Taskset context is missing: ${h}.`);let C=new TextDecoder("utf-8",{fatal:!0}).decode(W(P));a.set(h,se.parse(H({schemaVersion:"openpond.learningTextAsset.v1",id:h,revision:1,asset:P.asset,text:C})))}for(let h of s.assets){let P=e.files.find(C=>C.asset.id===h.id);if(P&&H({asset:P.asset}).contentHash!==H({asset:h.asset}).contentHash)throw new Error(`Selected Reward conflicts with a source asset: ${h.id}.`);a.set(h.id,h)}let{policy:u,environment:k,environmentRelease:x,tools:R,capabilities:n,verifierSetRelease:w}=e.taskset,c=$.parse(H({schemaVersion:"openpond.taskDefinition.v1",id:`${e.taskset.id}-definition`,revision:1,name:e.taskset.id,description:"",instructions:t,category:"custom",familyNamespace:e.taskset.id,inputSchema:{type:"object"},outputSchema:{type:"object"},rewardBinding:v(s.rewardBinding),harness:null,execution:{policy:u,environment:k,environmentRelease:x,tools:R,capabilities:n,verifierSetRelease:w}})),l=ne({...s,assets:[...a.values()],source:{taskset:e.taskset,taskDefinition:c,instructionMode:"per_task",executionResources:{environment:e.environment,verifierSet:e.verifierSet},...i?{execution:i.execution}:{}}}),d=new Map(e.files.map(h=>[h.asset.id,h]));for(let h of l.assets){let P="";for(let C of new TextEncoder().encode(h.text))P+=String.fromCharCode(C);d.set(h.id,{asset:h.asset,base64:btoa(P)})}let{taskset:I,executionResources:E,...M}=l;return Q({schemaVersion:"openpond.tasksetPackage.v1",taskset:I,...E,modelResources:M,files:[...d.values()]})}S(Is,"bindOrdinaryModelTasksetReward");function pt(s){let{request:e,package:t}=s,a=t.learningResources;if(!a)throw new B("model_review_batch_required",422);let i=z(t.taskset),m=`model-review-${p([s.scope,e.modelId,e.operationId])}`,u=new Map(e.examples.map(o=>[p(o.evidence),o])),k=new Set(a.evidence.map(o=>p(v(o)))),x=new Map(a.decisions.map(o=>[p(o.evidence),o]));if(u.size!==e.examples.length||e.examples.some(o=>!k.has(p(o.evidence))))throw new B("model_review_evidence_mismatch",409);for(let o of[s.binding,...s.rewards,...s.assets])Be(o);Me(s.binding,s.rewards);let R=new Map;for(let o of s.binding.sources){let y=s.rewards.find(le=>j(v(le),o.reward)),{contentHash:_,...L}=y;R.set(y.contentHash,He({...L,id:`${m}-reward-${y.contentHash}`,revision:1}))}let n=[...R.values()],{contentHash:w,recipeRef:c,...l}=s.binding,d=Ee({...l,id:`${m}-binding`,revision:1,sources:s.binding.sources.map(o=>({...o,reward:v(R.get(o.reward.contentHash))}))},n),I=n.flatMap(o=>[...o.assets,..."verifierRef"in o.implementation?[o.implementation.verifierRef]:[],..."rubricRef"in o.implementation?[o.implementation.rubricRef]:[],..."inputContract"in o.implementation?[o.implementation.inputContract]:[]]),E=[...new Map(I.map(o=>{let y=s.assets.find(_=>_.id===o.id);if(!y)throw new B("model_review_reward_asset_missing",422);if(ae(y,o),o.visibility==="policy")throw new B("reward_asset_visibility_invalid",422);return[y.id,y]})).values()],{environmentRelease:M,verifierSetRelease:h,...P}=i.definition.execution,{contentHash:C,...q}=i.definition,r=$.parse(H({...q,...e.definition,id:`${m}-definition`,revision:1,rewardBinding:v(d),execution:{...P,policy:{...P.policy,hiddenGraderRefs:De(d,n).filter(o=>o.privileged).map(o=>o.id)}}})),f=ee.parse(H({schemaVersion:"openpond.learningSource.v1",id:m,revision:1,name:`${r.name} review`,kind:"direct",taskDefinition:v(r),enabled:!0,allowedSplits:[...new Set(a.evidence.map(o=>o.submission.split))],mapping:null,adapterVersion:null,reviewOrigin:{modelId:e.modelId,packageHash:t.contentHash,taskset:v(t.taskset),batch:v(a.batch),rewardBinding:v(s.binding)}})),T=a.evidence.map(o=>{let y=u.get(p(v(o))),_=`review-${o.contentHash}`,L=p({instructions:r.instructions,inputSchema:r.inputSchema,outputSchema:r.outputSchema,requiredOutputs:r.requiredOutputs??[],input:y?.input??o.submission.input})!==p({instructions:i.definition.instructions,inputSchema:i.definition.inputSchema,outputSchema:i.definition.outputSchema,requiredOutputs:i.definition.requiredOutputs??[],input:o.submission.input});return X.parse(H({schemaVersion:"openpond.taskEvidence.v1",id:Ae(f.id,o.submission.exampleId,_),revision:1,source:v(f),submission:{...o.submission,sourceId:f.id,taskDefinition:v(r),attemptId:_,observedOutput:L?null:o.submission.observedOutput,idempotencyKey:`${m}-${o.contentHash}`,...y?.input===void 0?{}:{input:y.input},...y?.expected===void 0?{}:{expected:y.expected},...y?.evaluatorContext===void 0?{}:{evaluatorContext:y.evaluatorContext}},supersedes:v(o),correctionFeedbackId:null,receivedAt:s.now}))}),D=T.flatMap(o=>{let y=u.get(p(o.supersedes)),_=x.get(p(o.supersedes)),L=y?.proposedTarget===void 0?_.approvedTarget:y.proposedTarget;return L===null?[]:[te.parse({schemaVersion:"openpond.taskFeedbackRecord.v1",id:`feedback-${p([m,o.id])}`,revision:1,submission:{schemaVersion:"openpond.taskFeedback.v1",sourceId:f.id,idempotencyKey:`${m}-${o.id}`,exampleId:o.submission.exampleId,attemptId:o.submission.attemptId,expectedEvidenceHash:o.contentHash,occurredAt:s.now,kind:"target_correction",value:L,note:"Proposed target for the revised task. Grade and review before admission."},status:"pending_review",evidence:v(o),createdAt:s.now,review:null})]});return{source:f,definition:r,binding:d,rewards:n,assets:E,evidence:T,proposals:D}}S(pt,"prepareModelBatchReview");var Ue=S(s=>`model-batch-review-${p([s.modelId,s.operationId])}`,"operation");function _s(s){let e=A(s);if(!e.learningResources)throw new B("model_review_batch_required",422);let t=z(e.taskset);return Ye.parse({schemaVersion:"openpond.modelBatchReviewInspection.v1",packageHash:e.contentHash,definition:t.definition,binding:t.binding,evidence:e.learningResources.evidence,decisions:e.learningResources.decisions})}S(_s,"inspectModelBatchPackage");async function ft(s,e){let t=Pe.parse(e),a=await s.operation(Ue(t));if(!a)return null;if(a.requestHash!==p(t))throw new B("learning_idempotency_conflict",409);return Ze(s,t,a.resources)}S(ft,"findModelBatchReview");async function Bs(s,e){let t=Pe.parse(e.request),a=await ft(s,t);if(a)return a;let i=A(e.package);if(!i.learningResources)throw new B("model_review_batch_required",422);let m=z(i.taskset),u=t.rewardBindingRef,k=!u||j(u,v(m.binding)),x=k?m.binding:await ve(s,"binding",u),R=k?m.rewards:await Promise.all(x.sources.map(d=>ve(s,"reward",d.reward))),n=new Set(R.flatMap(d=>[...d.assets,..."verifierRef"in d.implementation?[d.implementation.verifierRef]:[],..."rubricRef"in d.implementation?[d.implementation.rubricRef]:[],..."inputContract"in d.implementation?[d.implementation.inputContract]:[]]).map(d=>d.id)),w=k?i.learningResources.assets:await Promise.all([...n].map(d=>he(s,"asset",d,1))),c=pt({...e,request:t,package:i,binding:x,rewards:R,assets:w}),l=[];for(let d of c.assets){let I=await s.get("asset",d.id,1);if(I&&I.contentHash!==d.contentHash)throw new B("model_review_asset_conflict",409);I||await s.put("asset",d,0)}for(let d of c.rewards)await s.put("reward",d,0);await s.put("binding",c.binding,0),await s.put("definition",c.definition,0),await s.put("source",c.source,0,{parentId:t.modelId}),l.push({kind:"source",id:c.source.id,revision:1});for(let d of c.evidence)await s.put("evidence",d,0,{parentId:c.source.id}),l.push({kind:"evidence",id:d.id,revision:1});for(let d of c.proposals)await s.put("feedback",d,0,{parentId:d.evidence.id,status:d.status}),l.push({kind:"feedback",id:d.id,revision:1});return await s.saveOperation(Ue(t),{requestHash:p(t),resources:l}),Ze(s,t,l)}S(Bs,"beginModelBatchReview");async function Ze(s,e,t){let a=await Promise.all(t.map(i=>he(s,i.kind,i.id,i.revision)));return Qe.parse({schemaVersion:"openpond.modelBatchReviewReceipt.v1",operationId:e.operationId,modelId:e.modelId,source:a.find(i=>i.schemaVersion==="openpond.learningSource.v1"),evidence:a.filter(i=>i.schemaVersion==="openpond.taskEvidence.v1"),proposals:a.filter(i=>i.schemaVersion==="openpond.taskFeedbackRecord.v1")})}S(Ze,"readReceipt");function Cs(s){let e=A(s.package),t=e.taskset,a=e.modelResources,i=e.learningResources?z(t):void 0,m=Ge.parse({schemaVersion:"openpond.uploadedFileDatasetSource.v1",kind:"uploaded_file",id:`package-source-${p({profileId:s.profileId,packageHash:e.contentHash})}`,profileId:s.profileId,title:s.name,sourceHash:e.contentHash,occurredAt:s.createdAt,licensingStatus:"pending",secretScanStatus:"pending",piiScanStatus:"pending",originalFileNames:["taskset-package.json"],mediaTypes:["application/json"],sourceFileHashes:[e.contentHash],totalBytes:new TextEncoder().encode(JSON.stringify(e)).byteLength,parserVersion:"openpond.tasksetPackage.v1",metadata:{}}),u=Xe({profileId:s.profileId,id:`${t.id}-import`,name:s.name,now:s.createdAt}),k=[];for(let c of t.graders)if(c.kind==="custom_verifier"){let l=a?.assets.find(E=>E.id===c.verifierRef.id),d=e.files.find(E=>E.asset.id===c.verifierRef.id);if(!d)throw new Error(`Imported verifier source is missing: ${c.id}.`);let I=Je(c.verifierRef.contentHash);k.some(E=>E.path===I)||k.push({path:I,role:"verifier",content:l?ae(l,c.verifierRef):new TextDecoder("utf-8",{fatal:!0}).decode(W(d))})}let x=t.metadata.ordinaryAuthoring??t.metadata.starterAuthoring,R=We.array().max(1e5).parse(x?.graderFixtures??[]),n=t.environment.kind==="text"?"chat":t.environment.kind==="custom_program"?"program":t.environment.kind,w=V.parse({schemaVersion:"openpond.taskset.v1",id:t.id,revision:t.revision,profileId:s.profileId,profileRelease:null,createImproveRunId:null,name:s.name,objective:Y(e),status:"needs_review",sourceRefs:[m],datasetArtifact:null,policy:t.policy,environment:{...u.environment,kind:n,entrypoint:t.environment.entrypoint,resources:Ne.array().max(1e4).parse(t.metadata.environmentResources??[]),stateful:t.environment.stateful,deterministicSeeds:t.environment.deterministicSeeds,toolNames:t.tools.map(c=>c.name),defaultTimeoutMs:t.environment.defaultTimeoutMs,networkPolicy:t.environment.networkPolicy,metadata:{runtimeSourceTasksetId:ut(s.profileId,e.contentHash),portableEnvironment:t.environment,portableTools:t.tools,portableExecutionResources:{environment:e.environment,verifierSet:e.verifierSet}}},capabilities:{...u.capabilities,taskKind:n==="chat"?"chat":n==="program"?"custom_program":"single_agent",compatibleMethods:["none"],requiresTools:t.tools.length>0,requiresState:t.environment.stateful,rewardKinds:[...new Set(t.graders.map(c=>c.kind==="human"?"human":c.kind==="model_judge"?"model_judge":"deterministic"))]},tasks:t.tasks.map(c=>({...c,schemaVersion:"openpond.taskData.v1",sourceRefs:[m.id],assets:c.artifactRefs.map(l=>({id:l.id,sourceRefId:m.id,artifactRef:l.path,fileName:l.path.split("/").at(-1),mediaType:l.mediaType,sha256:l.contentHash,sizeBytes:l.sizeBytes,split:c.split,metadata:{portableAsset:l}})),...c.requiredOutputs?{requiredOutputs:c.requiredOutputs.map(l=>({...l,schemaRef:l.schemaRef?.id??null,maxBytes:l.maxBytes??void 0}))}:{},metadata:{portableTaskRecord:c,exampleOrigin:"imported"}})),graders:a?Te(a.rewardBinding,a.rewards,a.assets):i?Te(i.binding,i.rewards,e.learningResources.assets):Ke(e),graderFixtures:R,learningSignals:u.learningSignals,...t.metrics?{metrics:t.metrics}:{},authoringProvenance:{schemaVersion:"openpond.taskAuthoringProvenance.v1",model:null,modelConfig:{},skillHash:p("openpond-package-import-v1"),promptTemplateVersion:"package-import-v1",buildIntent:"discovery",buildSpecification:null,evidenceHashes:[e.contentHash],tasksetSdkVersion:"package-import-v1",sourceCommit:null,repairHistory:[],createdAt:s.createdAt},readiness:null,contentHash:"00000000",createdAt:s.createdAt,updatedAt:s.createdAt,metadata:{importedPackageHash:e.contentHash,...i?{learning:i}:{},portableFileInventory:e.files.map(c=>({asset:c.asset,sourcePath:c.asset.path})),...a?{taskDefinition:v(a.taskDefinition),rewardBinding:v(a.rewardBinding),rewardExecution:{binding:a.rewardBinding,rewards:a.rewards}}:{},portableCapabilities:t.capabilities,derivedPortableMetadata:t.metadata,...t.metadata.modelTasksetDerivation?{modelTasksetDerivation:t.metadata.modelTasksetDerivation}:{}}});return{package:e,taskset:V.parse({...w,contentHash:U(w)}),generatedFiles:k}}S(Cs,"prepareImportedTasksetPackage");function ut(s,e){return`package-${p({profileId:s,packageHash:e})}`}S(ut,"tasksetPackageSourceId");var ht=g.object({draft:ie,filePaths:g.array(g.object({assetId:g.string().min(1),paths:g.array(re).min(1).max(1e4)}).strict()).max(1e4)}).strict();function Vs(s){let e=A(s.source),t=ie.parse(s.sourceDraft),a=G.parse(s.preparation);if(e.contentHash!==a.sourcePackageHash||!j(v(e.taskset),a.sourceTasksetRef))throw new Error("Taskset draft preparation differs from its source package.");if(e.learningResources)throw new Error("Reviewed Tasksets require their reviewed authoring workflow.");if(!!e.modelResources!=(a.authoringGraph==="bound"))throw new Error("Taskset draft authoring graph differs from its source.");let i=me.parse(t.metadata.portableFileInventory??[]),m=S(n=>ce(n)?`source-artifacts/${e.contentHash}/${p(n)}/${n.split("/").at(-1)}`:n,"sourcePath");if([...t.tasks.flatMap(n=>(n.assets??[]).map(w=>w.artifactRef)),...(t.environment.resources??[]).map(n=>n.path),...e.taskset.tasks.flatMap(n=>(n.requiredOutputs??[]).flatMap(w=>w.schemaRef?[w.schemaRef.path]:[])),...t.metrics.customAggregator?[t.metrics.customAggregator.module]:[],...t.graders.flatMap(n=>n.kind==="custom_verifier"?[n.module]:[])].some(ce))throw new Error("A referenced source asset occupies a reserved Taskset authoring path.");let k=e.files.map(n=>{let w=new Set([n.asset.path]);for(let c of i)c.asset.id===n.asset.id&&w.add(c.sourcePath);for(let c of t.tasks)for(let l of c.assets??[])l.id===n.asset.id&&w.add(l.artifactRef);for(let c of e.taskset.graders)if(c.kind==="custom_verifier"&&c.verifierRef.id===n.asset.id){let l=t.graders.find(d=>d.id===c.id);l?.kind==="custom_verifier"&&w.add(l.module)}return{assetId:n.asset.id,paths:[...w].map(m)}}),x={...t.metadata};if(e.modelResources)for(let n of["taskDefinition","rewardBinding","rewardExecution","derivedPortableMetadata","modelTasksetDerivation","importedPackageHash"])delete x[n];let R=ie.parse({...t,id:a.draftId,revision:1,status:"draft",graders:t.graders.map(n=>({...n,metadata:{...n.metadata,portableGrader:e.taskset.graders.find(w=>w.id===n.id)}})),environment:{...t.environment,metadata:{...t.environment.metadata,portableExecutionResources:{environment:e.environment}}},modelScope:{modelId:a.lineage.owner.modelId,expectedModelRevision:s.expectedModelRevision,source:a},publishedTasksetRef:a.tasksetRevision>1?a.sourceTasksetRef:null,metadata:{...x,modelTasksetAuthoring:a.lineage,portableFileInventory:i.map(n=>({...n,sourcePath:m(n.sourcePath),asset:{...n.asset,id:ce(n.sourcePath)?`source-artifact-${p({packageHash:e.contentHash,assetId:n.asset.id})}`:n.asset.id,path:m(n.asset.path)}}))}});return ht.parse({draft:R,filePaths:k})}S(Vs,"prepareTasksetDraftSource");export{Pe as a,nt as b,ot as c,me as d,mt as e,lt as f,Is as g,_s as h,ft as i,Bs as j,Cs as k,ut as l,ht as m,Vs as n};
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{fa as Te,ha as L,ia as qe,ja as Oe,na as P,oa as Ce}from"./chunk-JLWAK5PS.js";import{Ja as je,Ka as Pe,ce as Ae}from"./chunk-77BXXOHW.js";import{b as N}from"./chunk-L3KS6MOV.js";import{Ba as te,Ca as Ee,j as Ie,m as Se,p as He,r as D,s as C,t as xe,w as Z,y as ee}from"./chunk-5BFWDFPX.js";import{Bb as ye,c as ve,e as Y,f as be,g as ke,i as Re,u as de,v as X,w as V}from"./chunk-IFP6W4OW.js";import{b as e}from"./chunk-ES2ISFJC.js";import{a as Q,c as le,f as ge,h as E}from"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import M from"node:path";import{AsyncLocalStorage as kt}from"node:async_hooks";import{promises as _e}from"node:fs";var $e=new kt;function er(r,t=!1){let n=$e.getStore();n&&(t&&(n.length=0),n.push(r))}i(er,"onStartupFailure");async function tr(r,t){await ye(r);let n;try{n=await ke(M.join(E(r).runtime,"server-owner"),100)}catch(o){if(o instanceof le&&o.issue.code==="STORAGE_BUSY"){let a=await Re(M.join(E(r).runtime,"endpoint.json"),()=>null);throw new le({code:"RUNTIME_ALREADY_RUNNING",path:r,message:"An OpenPond runtime already owns this home.",action:a?.url?`Connect to the existing runtime at ${a.url}, or stop it before starting another.`:"Stop the existing runtime before starting another with this home."})}throw o}let s=[];try{let o=await Q(r,()=>$e.run(s,t)),a=o.close.bind(o);s.length=0;let c;return{...o,close:i(()=>c??=(async()=>{try{await Q(r,a)}finally{await _e.rm(M.join(E(r).runtime,"endpoint.json"),{force:!0}),await n()}})(),"close")}}catch(o){try{for(let a of s.reverse())await Promise.resolve().then(()=>Q(r,a)).catch(()=>{});await _e.rm(M.join(E(r).runtime,"endpoint.json"),{force:!0})}finally{await n()}throw o}}i(tr,"ownHomeRuntime");async function rr(r,t,n){await Y(M.join(E(r).runtime,"endpoint.json"),JSON.stringify({schemaVersion:"openpond.runtimeEndpoint.v1",pid:process.pid,url:t,serverId:n}))}i(rr,"publishRuntimeEndpoint");function or(r){if(!r.maxContextTokens||!r.usableContextTokens)return{shouldCompact:!1,projectedTokens:r.projectedTokens,thresholdTokens:Number.MAX_SAFE_INTEGER,usableContextTokens:0,maxContextTokens:0,tokenSource:"heuristic"};let t=Math.max(.01,Math.min(1,(r.triggerPercent??85)/100)),n=Math.max(1,Math.floor(r.usableContextTokens*t));return{shouldCompact:r.projectedTokens>=n,projectedTokens:r.projectedTokens,thresholdTokens:n,usableContextTokens:r.usableContextTokens,maxContextTokens:r.maxContextTokens,tokenSource:"heuristic"}}i(or,"agentCompactionDecision");async function ar(r){await r.started();try{return await r.compact()}catch(t){throw await r.failed(t),t}}i(ar,"runAgentCompaction");async function ir(r){let t=r.host.projectEvents(r.events),n=r.host.selectEvents(t,r.maxContextTokens),{summaryEvents:s,preservedEvents:o,preservedEventIds:a}=n;if(s.length===0)throw new Error("There is not enough prior context to compact.");let c=r.host.normalizeRecords(s),u=r.host.normalizeRecords(o),h=r.host.buildFileLedger(r.host.normalizeRecords(t)),f=r.host.serializeRecords(c,r.host.inputCharBudget(r.maxContextTokens));if(!f.text.trim())throw new Error("There is not enough prior context to compact.");let b=r.host.buildSummaryMessages({serializedHistory:f.text,fileLedger:h}),d=Date.now(),R=(await r.host.streamSummary({model:r.model,messages:b,signal:r.signal})).trim(),v=Date.now()-d;if(!R)throw new Error("Compaction summary was empty.");let w=r.host.estimateProjection({events:t,preservedEvents:o,summary:R}),p=r.host.createMetrics({sourceEvents:t.length,summarizedEvents:s.length,preservedEvents:o.length,sourceRecords:f.sourceRecordCount,includedRecords:f.includedRecordCount,omittedRecords:f.omittedRecordCount,preservedRecords:u.length,truncatedRecords:f.truncatedRecordCount,summaryInputTruncated:f.inputTruncated,sourceSelectionStrategy:f.selectionStrategy,summaryInputChars:f.inputChars,retainedTailTokens:n.retainedTailTokens,retainedTailBudgetTokens:n.retainedTailBudgetTokens,finalProviderContextTokens:w.inputTokensAfter,durationMs:v,fileLedgerEntries:h.length,splitTurnId:n.splitTurnId});return{summary:R,model:r.model,compactedThroughEventId:t[t.length-1]?.id??null,compactedThroughTurnId:r.host.lastTurnId(t),preservedFromEventId:o[0]?.id??null,preservedEventIds:a,preservedResourceRefs:r.host.durableResourceRefs(r.events),sourceEventCount:s.length,preservedEventCount:o.length,fileLedger:h,inputTokensBefore:w.inputTokensBefore,inputTokensAfter:w.inputTokensAfter,maxContextTokens:r.maxContextTokens,tokenSource:"heuristic",metrics:p}}i(ir,"runAgentCompactionProgram");var re="2026-09-20",ur=["initialize","initialized","runtime/capabilities","thread/start","thread/resume","thread/read","turn/start","turn/steer","task/inbox","task/queue","task/inputUpdate","turn/interrupt","approval/resolve","userInput/resolve","profile/workflows","profile/evaluations","profile/trainingSource","profile/evaluations/prepare","profile/evaluations/run","profile/evaluations/runSuite","profile/evaluations/executeCase","profile/evaluations/executeRun","profile/evaluations/compare","profile/evaluations/report","harness/inspect","harness/proposalReview","harness/review","harness/acceptEvaluationReview","harness/materializeEvaluationTaskset","harness/runEvaluationBaseline","harness/validate","harness/backgroundReview","harness/diff","harness/rollback","refiner/inspect","refiner/update","refiner/activate","refiner/rollback"],ze=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),We=e.object({jsonrpc:e.literal("2.0"),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),ue=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),result:e.unknown()}).strict(),pe=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number(),e.null()]),error:e.object({code:e.number().int(),message:e.string(),data:e.unknown().optional()}).strict()}).strict(),pr=e.union([ze,We,ue,pe]),Rt=e.object({protocolVersion:e.string().trim().min(1),client:e.object({name:e.string().trim().min(1),version:e.string().trim().min(1)}).strict(),capabilities:e.record(e.string(),e.unknown()).default({})}).strict(),ne=class{static{i(this,"AgentJsonRpcDispatcher")}#e;#t=null;#r=!1;constructor(t){this.#e=t}get initialized(){return this.#r}async handle(t){let n=We.safeParse(t);if(n.success&&!("id"in t)){if(n.data.method==="initialized"){if(!this.#t)throw new T(-32002,"initialize must be called first");this.#r=!0}return null}let s=ze.safeParse(t);if(!s.success)return Ve(null,-32600,"Invalid Request",s.error.flatten());let o=s.data;try{let a=await this.#n(o.method,o.params);return{jsonrpc:"2.0",id:o.id,result:a}}catch(a){let c=a instanceof T?a:new T(-32603,a instanceof Error?a.message:String(a));return Ve(o.id,c.code,c.message,c.data)}}async#n(t,n){if(t==="initialize"){let s=Rt.parse(n);if(s.protocolVersion!==re)throw new T(-32001,"Incompatible agent protocol version",{requested:s.protocolVersion,supported:re});return this.#t=s,{protocolVersion:re,server:{name:"openpond-app-server",version:"1"},capabilities:await this.#e.capabilities()}}if(!this.#r)throw new T(-32002,"initialized notification is required");switch(t){case"runtime/capabilities":return this.#e.capabilities(n);case"thread/start":return this.#e.threadStart(n);case"thread/resume":return this.#e.threadResume(n);case"thread/read":return this.#e.threadRead(n);case"turn/start":return this.#e.turnStart(n);case"turn/steer":return this.#e.turnSteer(n);case"task/inbox":return this.#e.taskInbox(n);case"task/queue":return this.#e.taskQueue(n);case"task/inputUpdate":return this.#e.taskInputUpdate(n);case"turn/interrupt":return this.#e.turnInterrupt(n);case"approval/resolve":return this.#e.approvalResolve(n);case"userInput/resolve":return this.#e.userInputResolve(n);case"profile/workflows":return this.#e.profileWorkflows(n);case"profile/evaluations":return this.#e.profileEvaluations(n);case"profile/trainingSource":return this.#e.profileTrainingSource(n);case"profile/evaluations/prepare":return this.#e.profileEvaluationPrepare(n);case"profile/evaluations/run":return this.#e.profileEvaluationRun(n);case"profile/evaluations/runSuite":return this.#e.profileEvaluationRunSuite(n);case"profile/evaluations/executeCase":return this.#e.profileEvaluationExecuteCase(n);case"profile/evaluations/executeRun":return this.#e.profileEvaluationExecuteRun(n);case"profile/evaluations/compare":return this.#e.profileEvaluationCompare(n);case"profile/evaluations/report":return this.#e.profileEvaluationReport(n);case"harness/inspect":return this.#e.harnessInspect(n);case"harness/proposalReview":return this.#e.harnessProposalReview(n);case"harness/review":return this.#e.harnessReview(n);case"harness/acceptEvaluationReview":return this.#e.harnessAcceptEvaluationReview(n);case"harness/materializeEvaluationTaskset":return this.#e.harnessMaterializeEvaluationTaskset(n);case"harness/runEvaluationBaseline":return this.#e.harnessRunEvaluationBaseline(n);case"harness/validate":return this.#e.harnessValidate(n);case"harness/backgroundReview":return this.#e.harnessBackgroundReview(n);case"harness/diff":return this.#e.harnessDiff(n);case"harness/rollback":return this.#e.harnessRollback(n);case"refiner/inspect":return this.#e.refinerInspect(n);case"refiner/update":return this.#e.refinerUpdate(n);case"refiner/activate":return this.#e.refinerActivate(n);case"refiner/rollback":return this.#e.refinerRollback(n);default:throw new T(-32601,`Method not found: ${t}`)}}},T=class extends Error{static{i(this,"JsonRpcDispatchError")}code;data;constructor(t,n,s){super(n),this.code=t,this.data=s}};function Ve(r,t,n,s){return{jsonrpc:"2.0",id:r,error:{code:t,message:n,...s===void 0?{}:{data:s}}}}i(Ve,"jsonRpcError");var m=e.string().trim().min(1).max(200),se=e.string().trim().min(1).max(32e3),B=e.number().int().nonnegative(),De=e.object({id:m,sessionId:m,senderSessionId:m.nullable(),senderKind:e.enum(["user","task","runtime"]),kind:e.enum(["steer","message","followup","queued","result"]),body:se,payload:e.record(e.string(),e.unknown()),idempotencyKey:m,replyTo:m.nullable(),expectedTurnId:m.nullable()}).strict(),yt=e.discriminatedUnion("action",[e.object({action:e.literal("resume"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("cancel"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("edit"),expectedRevision:e.number().int().positive(),body:se}).strict(),e.object({action:e.literal("steer"),expectedRevision:e.number().int().positive(),expectedTurnId:m}).strict()]),Ne=e.object({id:m,sessionId:m,turnId:m,targetSessionId:m.nullable(),targetTurnId:m.nullable(),targetInputId:m.nullable(),afterSequence:B,deadline:e.string(),state:e.enum(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:e.string(),updatedAt:e.string()}).strict(),Le=e.record(e.string(),e.unknown()),It=e.enum(["queued","running","completed","failed","cancelled","needs_resume"]),St=e.object({parentSessionId:m.nullable().optional(),childSessionId:m.nullable().optional(),status:e.array(It).nullable().optional(),afterId:e.string().max(200),limit:e.number().int().min(1).max(10)}).strict(),Me=e.discriminatedUnion("action",[e.object({action:e.literal("recoverTaskInboxOwners"),ownerId:m}).strict(),e.object({action:e.literal("hasTaskCompletion"),turnId:m}).strict(),e.object({action:e.literal("taskInboxSnapshot"),sessionId:m}).strict(),e.object({action:e.literal("taskInboxSnapshotInputs"),sessionId:m,afterSequence:B}).strict(),e.object({action:e.literal("declareTaskWork"),sessionId:m,turnId:m,ownerId:m,areas:e.array(se).max(100)}).strict(),e.object({action:e.literal("taskWorkAreas"),sessionId:m}).strict(),e.object({action:e.literal("admitTaskInput"),input:De}).strict(),e.object({action:e.literal("admitTaskInputs"),inputs:e.array(De).max(50)}).strict(),e.object({action:e.literal("rejectTaskInput"),id:m,error:se}).strict(),e.object({action:e.literal("getTaskInput"),id:m}).strict(),e.object({action:e.literal("taskInputsForSession"),sessionId:m,query:e.object({afterSequence:B.optional(),pendingOnly:e.boolean().optional(),limit:e.number().int().min(1).max(500).optional()}).strict()}).strict(),e.object({action:e.literal("mutateTaskInput"),sessionId:m,inputId:m,change:yt}).strict(),e.object({action:e.literal("openTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("renewTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("pendingTaskInputs"),sessionId:m,turnId:m,afterSequence:B}).strict(),e.object({action:e.literal("taskAssignmentInputs"),turnId:m,afterSequence:B}).strict(),e.object({action:e.literal("pauseTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("includeTaskInputs"),sessionId:m,turnId:m,ownerId:m,requestId:m}).strict(),e.object({action:e.literal("settleTaskInputRequest"),requestId:m,outcome:e.enum(["resolved","failed","replaced"])}).strict(),e.object({action:e.literal("sealTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("sealNativeTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("closeTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m,outcome:e.enum(["completed","failed","interrupted"])}).strict(),e.object({action:e.literal("taskInboxPaused"),sessionId:m}).strict(),e.object({action:e.literal("reserveTaskFollowup"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("taskInboxWakeTargets"),afterSessionId:e.string().max(200)}).strict(),e.object({action:e.literal("createTaskWait"),value:Ne}).strict(),e.object({action:e.literal("settleTaskWait"),id:m,state:Ne.shape.state}).strict(),e.object({action:e.literal("taskWaitsForSession"),sessionId:m,afterId:e.string().max(200)}).strict(),e.object({action:e.literal("commitSubagentCompletion"),value:Le,turnId:m}).strict(),e.object({action:e.literal("pendingTaskCompletions"),afterTurnId:e.string().max(200)}).strict(),e.object({action:e.literal("settleTaskCompletion"),turnId:m,inputId:m}).strict(),e.object({action:e.literal("upsertSubagentRun"),value:Le}).strict(),e.object({action:e.literal("getSubagentRun"),id:m}).strict(),e.object({action:e.literal("listSubagentRuns"),query:St}).strict()]);var oe=e.string().trim().min(1).max(191),Be=e.object({createdAt:e.string().min(1),id:oe}).strict(),Fe=e.enum(["trigger_decision","route_decision","refiner_outcome","proposal","targeted_validation","apply_receipt"]),Ue=e.discriminatedUnion("action",[e.object({action:e.literal("put_artifact"),workspaceId:oe,kind:Fe,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:oe,kind:Fe,before:Be.nullable(),limit:e.number().int().min(1).max(200)}).strict(),e.object({action:e.literal("pending_trigger_page"),workspaceId:oe,before:Be.nullable(),limit:e.number().int().min(1).max(200)}).strict()]);var A=e.string().trim().min(1).max(200),Je=e.string().regex(/^[a-f0-9]{64}$/),Ht=e.object({kind:e.enum(["structural","visual","test","user_review"]),status:e.enum(["passed","failed","not_run"]),label:e.string().trim().min(1).max(240),detail:e.string().trim().max(4e3).nullable().optional(),ref:e.string().trim().max(4096).nullable().optional()}),Ke=e.object({id:A,title:e.string().trim().min(1).max(240),sourceTaskId:A,sourceTurnId:A,revision:e.number().int().positive(),createdAt:e.string().datetime(),contentType:e.string().trim().min(1).max(200),sizeBytes:e.number().int().min(1).max(1e7),sha256:Je,validation:e.array(Ht).max(32)}).strict(),Ge=e.object({sessionId:A,turnId:A,output:Ke}).strict(),Qe=e.object({uploadId:A,index:e.number().int().min(0).max(1024),offset:e.number().int().min(0).max(1e7),sha256:Je,contentsBase64:e.string().min(1).max(131072)}).strict(),Ye=e.object({uploadId:A}).strict(),xt=Ke.pick({id:!0,title:!0,sourceTaskId:!0,sourceTurnId:!0,revision:!0,createdAt:!0,validation:!0}),Xe=e.object({sessionId:A,turnId:A,output:xt,sandboxPath:e.string().trim().min(1).max(4096)}).strict();var F=e.string().trim().min(1).max(200),Et=e.object({type:e.enum(["create","get","start","stop","exec","open_port","list_files","download_file","upload_file","search_files","delete_file","stat_file","mkdir","move_file","process_start","process_get","git_status","git_diff","git_export_patch","git_branch","git_commit","git_pull","git_push"]),sandboxId:F.optional(),payload:e.unknown().optional(),processId:F.optional(),failOnUnpreservedChanges:e.boolean().optional()}).strict().superRefine((r,t)=>{r.type!=="create"&&!r.sandboxId&&t.addIssue({code:"custom",message:"Sandbox identity is required."}),r.type==="create"&&r.sandboxId&&t.addIssue({code:"custom",message:"Create cannot target a sandbox identity."}),r.type==="process_get"&&!r.processId&&t.addIssue({code:"custom",message:"Process identity is required."})}),Ze=e.object({action:Et}).strict(),et=e.object({sessionId:F,turnId:F,name:F}).strict();var g=1,l=e.string().trim().min(1).max(191),q=e.number().int().min(1).max(200),jr=e.object({teamId:l,ownerUserId:l,workspaceId:l,conversationId:l,turnId:l,attempt:e.number().int().min(1),leaseGeneration:e.number().int().min(1)}).strict(),tt=e.discriminatedUnion("operation",[e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("sandbox/request"),params:Ze}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("embedding/authorize"),params:et}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/begin"),params:Ge}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/chunk"),params:Qe}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/complete"),params:Ye}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/saveSandboxFile"),params:Xe}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("settings/get"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/get"),params:e.object({reference:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/overlay/get"),params:e.object({runId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/overlay/put"),params:e.object({runId:l,expectedRevision:e.number().int().min(0).nullable(),overlay:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/overlay/freezeProposal"),params:e.object({runId:l,expectedRevision:e.number().int().min(0),overlay:e.record(e.string(),e.unknown()),proposal:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/get"),params:e.object({workspaceId:l,key:e.string().min(1).max(120)}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/list"),params:e.object({workspaceId:l,includeDeleted:e.boolean(),before:e.object({updatedAt:e.string(),key:e.string()}).strict().nullable(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/search"),params:e.object({workspaceId:l,query:e.string().trim().min(1).max(500),limit:e.number().int().min(1).max(20)}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/write"),params:e.object({input:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/state/read"),params:e.object({workspaceId:l,kind:e.enum(["selection","workspace_settings","evaluation_review_settings","candidates","cross_run_requests"]),afterId:l.nullable(),limit:e.number().int().min(1).max(100)}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/workspace/transition"),params:e.discriminatedUnion("action",[e.object({action:e.literal("advance"),receiptId:l,workspaceId:l,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),now:e.string()}).strict(),e.object({action:e.literal("reviewedAdvance"),receiptId:l,workspaceId:l,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),reviewer:l,now:e.string()}).strict(),e.object({action:e.literal("rollback"),receiptId:l,workspaceId:l,expectedWorkspaceRevision:e.number().int().nonnegative(),expectedChannelRevision:e.number().int().nonnegative(),targetRelease:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),targetSourceRevision:e.string().min(1),rollbackOf:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),now:e.string()}).strict()])}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("task-inbox/execute"),params:Me}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("refiner/execute"),params:e.object({action:Ue}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("create-improve/execute"),params:e.discriminatedUnion("action",[e.object({action:e.literal("get"),runId:l}).strict(),e.object({action:e.literal("page"),query:e.object({profileId:l.nullable(),targetKind:l.nullable(),targetId:l.nullable(),state:e.array(l).max(20)}).strict(),before:e.object({updatedAt:e.string(),id:l}).strict().nullable(),limit:q}).strict(),e.object({action:e.literal("put"),run:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("mutate"),mutation:e.record(e.string(),e.unknown()),next:e.record(e.string(),e.unknown())}).strict()])}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("approval/get"),params:e.object({approvalId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("approval/upsert"),params:e.object({approval:e.record(e.string(),e.unknown()),expectedRevision:e.number().int().min(1).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("usage/getByRequestId"),params:e.object({requestId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("usage/upsert"),params:e.object({record:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("usage/page"),params:e.object({query:e.object({sessionId:l.optional(),turnId:l.optional(),provider:l.optional(),model:l.optional(),startedAtFrom:e.string().optional(),startedAtTo:e.string().optional(),visibility:e.enum(["user_facing","background","system"]).optional(),status:e.enum(["started","completed","failed","interrupted","missing"]).optional()}).strict(),before:e.object({startedAt:e.string(),requestOrdinal:e.number().int().min(0),id:l}).strict().nullable(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("capabilities"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/count"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/get"),params:e.object({sessionId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/page"),params:e.object({afterId:l.nullable(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/put"),params:e.object({sessionId:l,expectedRevision:e.number().int().min(1).nullable(),session:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/count"),params:e.object({sessionId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/wakeCount"),params:e.object({sessionId:l,key:e.enum(["messageId","fromRunId"]),value:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/get"),params:e.object({turnId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/put"),params:e.object({sessionId:l,turnId:l,expectedRevision:e.number().int().min(1).nullable(),turn:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/latest"),params:e.object({sessionId:l,status:e.enum(["in_progress","completed","failed","interrupted"]).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/page"),params:e.object({sessionId:l,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("thread/turnPage"),params:e.object({sessionId:l,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("event/append"),params:e.object({event:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("events/page"),params:e.object({sessionId:l.nullable(),afterSequence:e.number().int().min(0),beforeSequence:e.number().int().min(1).nullable().optional(),limit:q,excludeReasoningDeltas:e.boolean().optional()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("events/latestAssistantText"),params:e.object({sessionId:l}).strict()}).strict()]),Pr=e.object({contractVersion:e.literal(g),operations:e.array(e.enum(["sandbox/request","embedding/authorize","output/begin","output/chunk","output/complete","output/saveSandboxFile","settings/get","harness/get","harness/overlay/get","harness/overlay/put","harness/overlay/freezeProposal","harness/memory/get","harness/memory/list","harness/memory/search","harness/memory/write","harness/state/read","harness/workspace/transition","task-inbox/execute","refiner/execute","create-improve/execute","approval/get","approval/upsert","usage/getByRequestId","usage/upsert","usage/page","session/count","session/get","session/page","session/put","turn/count","turn/wakeCount","turn/get","turn/put","turn/latest","turn/page","thread/turnPage","event/append","events/page","events/latestAssistantText"])).max(40),allowedTools:e.array(l).max(128),maxPageSize:q,maxRequestBytes:e.number().int().min(1).max(1e6),maxInFlight:e.number().int().min(1).max(64)}).strict();var rt=class{static{i(this,"AgentHostStorageClient")}#e=new Map;#t=null;#r=1;bind(t){if(this.#t)throw new Error("Host storage client is already bound.");this.#t=t}async request(t,n=15e3){let s=tt.parse(t);if(!this.#t)throw new Error("Host storage transport is unavailable.");if(this.#e.size>=32)throw new Error("Host storage request limit exceeded.");let o=`host-storage:${this.#r++}`,a={jsonrpc:"2.0",id:o,method:"host/storage",params:s};if(Buffer.byteLength(JSON.stringify(a))>256e3)throw new Error("Host storage request is too large.");let c=new Promise((u,h)=>{let f=s.operation==="sandbox/request"?3e5:6e4,b=setTimeout(()=>{this.#e.delete(o),h(new Error("Host storage request timed out."))},Math.max(1,Math.min(f,n)));this.#e.set(o,{resolve:u,reject:h,timer:b})});try{await this.#t(a)}catch(u){let h=this.#e.get(o);h&&(clearTimeout(h.timer),this.#e.delete(o),h.reject(u instanceof Error?u:new Error(String(u))))}return c}accept(t){let n=ue.safeParse(t),s=n.success?null:pe.safeParse(t),o=n.success?n.data:s?.success?s.data:null;if(!o||typeof o.id!="string"||!o.id.startsWith("host-storage:"))return!1;let a=this.#e.get(o.id);return a?(clearTimeout(a.timer),this.#e.delete(o.id),Buffer.byteLength(JSON.stringify(o))>1e6?(a.reject(new Error("Host storage response is too large.")),!0):("error"in o?a.reject(new Error(`Host storage request failed: ${o.error.message}`)):a.resolve(o.result),!0)):!0}close(){this.#t=null;for(let t of this.#e.values())clearTimeout(t.timer),t.reject(new Error("Host storage transport closed."));this.#e.clear()}};import{createHash as jt}from"node:crypto";function me(r){if(r===null||typeof r=="boolean"||typeof r=="string")return r;if(typeof r=="number"){if(!Number.isFinite(r))throw new Error("Canonical JSON cannot encode a non-finite number.");return r}if(Array.isArray(r))return r.map(me);if(typeof r=="object"){let t={};for(let n of Object.keys(r).sort()){let s=r[n];s!==void 0&&(t[n]=me(s))}return t}throw new Error(`Canonical JSON cannot encode ${typeof r}.`)}i(me,"canonicalJson");function z(r){return jt("sha256").update(JSON.stringify(me(r)),"utf8").digest("hex")}i(z,"canonicalHash");var Pt=e.enum(["thread.started","thread.resumed","turn.started","turn.steered","turn.interrupted","turn.completed","turn.failed","item.started","item.delta","item.completed","assistant.reasoning.delta","assistant.delta","tool.started","tool.completed","approval.requested","approval.resolved","user_input.requested","user_input.resolved","compaction.started","compaction.completed","harness.admitted","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","diagnostic"]),At=e.object({sequence:e.number().int().nonnegative(),name:Pt,source:e.enum(["runtime","provider","tool","host","refiner"]),status:e.string().trim().min(1).nullable().default(null),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1).nullable().default(null),callId:e.string().trim().min(1).nullable().default(null),output:e.string().nullable().default(null),error:e.string().nullable().default(null),data:e.record(e.string(),e.unknown()).default({})}).strict();function Dr(r){return z(At.parse(r))}i(Dr,"canonicalEventHash");import{once as Tt}from"node:events";import{createInterface as qt}from"node:readline";async function nt(r){let t=null,n=Promise.resolve(),s=[],o=i(w=>(n=n.then(async()=>{r.writable.write(`${JSON.stringify(w)}
|
|
3
|
-
`)||await Tt(r.writable,"drain")}),n),"write");r.hostStorageClient?.bind(w=>o(w));let a=i(()=>{if(!(!t?.initialized||s.length===0))for(let w of s.splice(0))o(w)},"flushPendingNotifications"),c,u=new Set,h=qt({input:r.readable,crlfDelay:1/0}),f=[],b=!1,d=null,R=i(async w=>{let p=t;if(!p)throw new Error("Agent runtime dispatcher is unavailable.");let y=(async()=>{let I=await p.handle(w);I&&await o(I),a()})(),S=w&&typeof w=="object"&&"method"in w?w.method:null;if(S==="initialize"||S==="initialized"){await y;return}u.add(y),y.finally(()=>u.delete(y))},"dispatch"),v=(async()=>{let w=typeof r.host=="function"?await r.host():r.host;for(t=new ne(w),c=w.subscribe?.(p=>{if(!t?.initialized){s.push(p);return}o(p)});f.length>0;)await R(f.shift());b=!0})().catch(w=>{d=w,h.close()});try{for await(let w of h){if(!w.trim())continue;if(Buffer.byteLength(w,"utf8")>1e6){await o({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Request exceeds the JSONL size limit"}});continue}let p;try{p=JSON.parse(w)}catch{await o({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}});continue}if(!r.hostStorageClient?.accept(p))if(b)await R(p);else if(f.length>=64){let y=p&&typeof p=="object"&&"id"in p?p.id:null;(typeof y=="string"||typeof y=="number")&&await o({jsonrpc:"2.0",id:y,error:{code:-32e3,message:"Runtime startup request limit exceeded"}})}else f.push(p)}if(await v,d)throw d;await Promise.all(u),await n}finally{r.hostStorageClient?.close(),c?.()}}i(nt,"runAgentJsonlServer");var ae=e.object({threadId:e.string().trim().min(1)}).passthrough(),Ot=ae.extend({includeHistory:e.boolean().optional()}),Ct=e.object({session:e.unknown()}).strict(),U=ae.extend({input:e.unknown()}),_t=U.extend({idempotencyKey:e.string().trim().min(1).max(200)}),$t=U.extend({inputId:e.string().trim().min(1)}),Vt=ae.extend({reason:e.string().trim().min(1).optional()}),zt=e.object({approvalId:e.string().trim().min(1),input:e.unknown()}).strict();function st(r){let t=i(async(s,o,a)=>{let c=performance.now();r.telemetry?.({method:s,phase:"started",threadId:o,durationMs:null,errorClass:null});try{let u=await a();return r.telemetry?.({method:s,phase:"completed",threadId:o,durationMs:performance.now()-c,errorClass:null}),u}catch(u){throw r.telemetry?.({method:s,phase:"failed",threadId:o,durationMs:performance.now()-c,errorClass:u instanceof Error?u.name:"UnknownError"}),u}},"run"),n=i(async(s,o="thread/read")=>{let{threadId:a,includeHistory:c}=Ot.parse(s);return t(o,a,async()=>{if(c===!1)return{thread:await r.readThread(a),turns:[],events:[]};let[u,h,f]=await Promise.all([r.readThread(a),r.listTurns(a),r.listEvents(a)]);return{thread:u,turns:h,events:f}})},"threadRead");return{capabilities:i(s=>t("runtime/capabilities",null,()=>r.capabilities(s)),"capabilities"),threadStart:i(async s=>t("thread/start",null,async()=>({thread:await r.createThread(Ct.parse(s).session)})),"threadStart"),threadResume:i(s=>n(s,"thread/resume"),"threadResume"),threadRead:n,turnStart:i(async s=>{let o=U.parse(s);return t("turn/start",o.threadId,async()=>({turn:await r.startTurn(o.threadId,o.input)}))},"turnStart"),turnSteer:i(async s=>{let o=U.parse(s);return t("turn/steer",o.threadId,async()=>({receipt:await r.steerTurn(o.threadId,o.input)}))},"turnSteer"),taskInbox:i(async s=>{let{threadId:o}=ae.parse(s);return t("task/inbox",o,()=>r.readTaskInbox(o))},"taskInbox"),taskQueue:i(async s=>{let o=_t.parse(s);return t("task/queue",o.threadId,()=>r.queueTaskInput(o.threadId,o.input,o.idempotencyKey))},"taskQueue"),taskInputUpdate:i(async s=>{let o=$t.parse(s);return t("task/inputUpdate",o.threadId,()=>r.updateTaskInput(o.threadId,o.inputId,o.input))},"taskInputUpdate"),turnInterrupt:i(async s=>{let o=Vt.parse(s);return t("turn/interrupt",o.threadId,async()=>({turn:await r.interruptTurn(o.threadId,o.reason)}))},"turnInterrupt"),approvalResolve:i(async s=>{let o=zt.parse(s);return t("approval/resolve",null,async()=>({approval:await r.resolveApproval(o.approvalId,o.input)}))},"approvalResolve"),userInputResolve:i(async s=>{let o=U.parse(s);return t("userInput/resolve",o.threadId,async()=>(r.isTurnActive(o.threadId)&&await r.waitForTurnSettlement(o.threadId),{turn:await r.startTurn(o.threadId,o.input)}))},"userInputResolve"),profileWorkflows:i(()=>t("profile/workflows",null,()=>r.listProfileWorkflows()),"profileWorkflows"),profileEvaluations:i(s=>t("profile/evaluations",null,()=>r.listProfileEvaluations(s)),"profileEvaluations"),profileTrainingSource:i(()=>t("profile/trainingSource",null,()=>r.loadProfileTrainingSource()),"profileTrainingSource"),profileEvaluationPrepare:i(s=>t("profile/evaluations/prepare",null,()=>r.prepareProfileEvaluationRun(s)),"profileEvaluationPrepare"),profileEvaluationRun:i(s=>t("profile/evaluations/run",null,()=>r.runPreparedProfileEvaluation(s)),"profileEvaluationRun"),profileEvaluationRunSuite:i(s=>t("profile/evaluations/runSuite",null,()=>r.runProfileEvaluationSuite(s)),"profileEvaluationRunSuite"),profileEvaluationExecuteCase:i(s=>t("profile/evaluations/executeCase",null,()=>r.executeProfileEvaluationCase(s)),"profileEvaluationExecuteCase"),profileEvaluationExecuteRun:i(s=>t("profile/evaluations/executeRun",null,()=>r.executeProfileEvaluationRun(s)),"profileEvaluationExecuteRun"),profileEvaluationCompare:i(s=>t("profile/evaluations/compare",null,()=>r.compareProfileEvaluationRuns(s)),"profileEvaluationCompare"),profileEvaluationReport:i(s=>t("profile/evaluations/report",null,()=>r.buildProfileEvaluationReport(s)),"profileEvaluationReport"),harnessInspect:i(()=>t("harness/inspect",null,()=>r.inspectHarness()),"harnessInspect"),harnessProposalReview:i(s=>t("harness/proposalReview",null,()=>r.reviewHarnessProposal(s)),"harnessProposalReview"),harnessReview:i(s=>t("harness/review",null,()=>r.reviewHarness(s)),"harnessReview"),harnessAcceptEvaluationReview:i(s=>t("harness/acceptEvaluationReview",null,()=>r.acceptHarnessEvaluationReview(s)),"harnessAcceptEvaluationReview"),harnessMaterializeEvaluationTaskset:i(s=>t("harness/materializeEvaluationTaskset",null,()=>r.materializeHarnessEvaluationTaskset(s)),"harnessMaterializeEvaluationTaskset"),harnessRunEvaluationBaseline:i(s=>t("harness/runEvaluationBaseline",null,()=>r.runHarnessEvaluationBaseline(s)),"harnessRunEvaluationBaseline"),harnessValidate:i(()=>t("harness/validate",null,()=>r.validateHarness()),"harnessValidate"),harnessBackgroundReview:i(s=>t("harness/backgroundReview",null,()=>r.updateHarnessBackgroundReview(s)),"harnessBackgroundReview"),harnessDiff:i(s=>t("harness/diff",null,()=>r.diffHarness(s)),"harnessDiff"),harnessRollback:i(s=>t("harness/rollback",null,()=>r.rollbackHarness(s)),"harnessRollback"),refinerInspect:i(()=>t("refiner/inspect",null,()=>r.inspectRefiner()),"refinerInspect"),refinerUpdate:i(s=>t("refiner/update",null,()=>r.updateRefiner(s)),"refinerUpdate"),refinerActivate:i(s=>t("refiner/activate",null,()=>r.activateRefiner(s)),"refinerActivate"),refinerRollback:i(s=>t("refiner/rollback",null,()=>r.rollbackRefiner(s)),"refinerRollback"),subscribe:r.subscribeEvents&&r.eventNotification?s=>r.subscribeEvents(o=>s(r.eventNotification(o))):void 0}}i(st,"createAgentRuntimeService");var _=e.string().regex(/^[a-f0-9]{64}$/),cn=e.object({harnessReleaseHash:_,instructionsHash:_,skillHashes:e.record(e.string(),_),agentAssetHashes:e.record(e.string(),_),toolCatalogHash:_,memoryRevision:e.number().int().nonnegative().nullable()}).strict(),Wt=e.object({protocolVersion:e.string().trim().min(1),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1),harnessReleaseHash:_,toolCatalogHash:_,context:e.record(e.string(),e.unknown()),pendingInteraction:e.record(e.string(),e.unknown()).nullable(),usage:e.record(e.string(),e.unknown())}).strict();function ln(r){return z(Wt.parse(r))}i(ln,"checkpointHash");function dn(r){return[r.system,...r.harnessInstructions,...r.skillInstructions,...r.hostInstructions??[]].map(t=>t.trim()).filter(Boolean).join(`
|
|
4
|
-
|
|
5
|
-
`)}i(dn,"materializeAgentPrompt");function hn(r){let t=new Set,n=[...r].map(a=>{let c=a.name.trim();if(!c)throw new Error("Agent tool names cannot be empty.");if(t.has(c))throw new Error(`Duplicate agent tool: ${c}.`);if(t.add(c),!a.unavailableReason&&!a.executorAvailable)throw new Error(`Agent tool ${c} is declared as available without an executor.`);return{...a,name:c}}).sort((a,c)=>a.name.localeCompare(c.name)),s=n.filter(a=>!a.unavailableReason).map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema})),o=n.map(a=>({name:a.name,displayLabel:a.displayLabel??a.name,placement:a.placement,available:!a.unavailableReason,unavailableReason:a.unavailableReason??null}));return{byName:new Map(n.map(a=>[a.name,a])),tools:n,modelTools:s,capabilities:o,hash:z({modelTools:s,capabilities:o})}}i(hn,"createAgentToolCatalogProjection");async function fn(r,t){let n=r.byName.get(t.name);if(!n)throw new Error(`Unknown agent tool: ${t.name}.`);if(n.unavailableReason)throw new Error(`Agent tool ${t.name} is unavailable: ${n.unavailableReason}`);if(!n.execute)throw new Error(`Agent tool ${t.name} has no executor.`);let s=n.validateArguments?n.validateArguments(t.arguments):t.arguments;return n.execute(s,t.context)}i(fn,"executeProjectedAgentTool");var ot=class{static{i(this,"TaskSignals")}#e=new Map;notify(t){for(let n of[...this.#e.get(t)??[]])n()}subscribe(t,n){let s=this.#e.get(t);return s||this.#e.set(t,s=new Set),s.add(n),()=>{s.delete(n),s.size===0&&this.#e.delete(t)}}async wait(t){let n=i(()=>{},"wake"),s=0,o=i(()=>{s+=1,n()},"changed"),a=[...new Set(t.taskIds)].map(u=>this.subscribe(u,o)),c=setTimeout(o,Math.max(0,t.deadline-Date.now()));t.signal.addEventListener("abort",o);try{for(;;){t.signal.throwIfAborted();let u=s,h=await t.read();if(h!==null)return h;if(Date.now()>=t.deadline)return null;s===u&&await new Promise(f=>{n=f,(s!==u||t.signal.aborted)&&f()})}}finally{clearTimeout(c),t.signal.removeEventListener("abort",o);for(let u of a)u()}}},at=class{static{i(this,"TaskSerialExecutor")}#e=new Map;async run(t,n){let o=(this.#e.get(t)??Promise.resolve()).then(n),a=o.then(()=>{},()=>{});this.#e.set(t,a);try{return await o}finally{this.#e.get(t)===a&&this.#e.delete(t)}}};import{randomUUID as W}from"node:crypto";import{promises as k}from"node:fs";import{stripTypeScriptTypes as Dt}from"node:module";import H from"node:path";async function Un(r){let t=D.parse(r.overlay),n=C.parse(r.proposal),s=r.validations.map(f=>xe.parse(f));if((n.route==="agent"?n.edits.filter(f=>f.target!=="harness.json"&&f.operation!=="delete"):[]).length>0){let f=n.validationPlan.find(d=>d.kind==="component_activation"&&d.required);if(!f)throw new Error("Desktop Work Agent proposals require component-activation validation before review.");if(s.find(d=>d.validationId===f.id)?.status==="passed")throw new Error("Desktop Work cannot accept a passed Agent activation receipt until an Agent source executor exists.")}if(n.overlay.id!==t.id||n.overlay.revision!==t.revision||n.overlay.contentHash!==t.contentHash)throw new Error("Refiner proposal is not bound to the supplied run overlay.");if(t.status!=="frozen")throw new Error("Only a frozen run overlay can advance a Harness workspace.");let a=await r.store.getHarnessWorkspace(n.expectedWorkspace.workspaceId);if(!a)throw new Error(`Harness workspace ${n.expectedWorkspace.workspaceId} does not exist.`);if(a.location!=="local")throw new Error("The local Refiner can only advance a local Harness workspace.");let c=L(r.storeDir,a.id),u=await P({workspaceId:a.id,sourceDir:c.source});if(u.sourceRevision!==a.sourceRevision)throw new Error(`Harness source is ${u.sourceRevision}; workspace expects ${a.sourceRevision}. Record or revert the source change before refinement.`);let h=H.join(c.root,`.source-candidate-${W()}`);await k.cp(c.source,h,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});try{await lt(h,n);let f=await P({workspaceId:a.id,sourceDir:h}),b=(r.now??(()=>new Date().toISOString()))(),d=await Ce({storeDir:r.storeDir,workspaceId:a.id,compiled:f,createdAt:b});await r.store.saveHarnessReleaseRecord(d),await r.store.saveHarnessImprovementArtifact(a.id,"run_overlay",t),await r.store.saveHarnessImprovementArtifact(a.id,"proposal",n);for(let p of s)await r.store.saveHarnessImprovementArtifact(a.id,"targeted_validation",p);if(!Ae({workspace:a,proposal:n}).eligible&&!r.reviewAuthority)return r.store.advanceHarnessWorkspaceAtomically({receiptId:r.receiptId,workspaceId:a.id,proposal:n,validations:s,nextRelease:{id:d.harnessRelease.id,contentHash:d.harnessRelease.contentHash},nextSourceRevision:d.sourceRevision,now:b});let v=H.join(c.root,`.source-backup-${W()}`),w=H.join(c.root,"source-swap.json");await ut(w,{schemaVersion:"openpond.localHarnessSourceSwap.v1",workspaceId:a.id,expectedWorkspaceRevision:a.revision,previousSourceRevision:a.sourceRevision,nextSourceRevision:d.sourceRevision,backupSource:v,candidateSource:h,createdAt:b}),await k.rename(c.source,v),await k.rename(h,c.source);try{let p=r.reviewAuthority?await r.store.advanceReviewedHarnessWorkspaceAtomically({receiptId:r.receiptId,workspaceId:a.id,proposal:n,validations:s,nextRelease:{id:d.harnessRelease.id,contentHash:d.harnessRelease.contentHash},nextSourceRevision:d.sourceRevision,reviewer:r.reviewAuthority.reviewer,now:b}):await r.store.advanceHarnessWorkspaceAtomically({receiptId:r.receiptId,workspaceId:a.id,proposal:n,validations:s,nextRelease:{id:d.harnessRelease.id,contentHash:d.harnessRelease.contentHash},nextSourceRevision:d.sourceRevision,now:b});return p.receipt.decision!=="advanced"?await J(c.source,v):await k.rm(v,{recursive:!0,force:!0}),await k.rm(w,{force:!0}),p}catch(p){throw await J(c.source,v).catch(()=>{}),await k.rm(w,{force:!0}).catch(()=>{}),p}}finally{await k.rm(h,{recursive:!0,force:!0}).catch(()=>{})}}i(Un,"applyLocalHarnessRefinerProposal");async function Jn(r){let t=await r.store.getHarnessWorkspace(r.workspaceId);if(!t||t.location!=="local")throw new Error(`Local Harness workspace ${r.workspaceId} does not exist.`);if(t.currentChannel.release?.id!==r.rollbackOf.id||t.currentChannel.release.contentHash!==r.rollbackOf.contentHash)throw new Error("Harness rollback source is no longer the current release.");let n=await r.store.getHarnessReleaseRecord(r.targetRelease.contentHash);if(!n||n.workspaceId!==t.id||n.harnessRelease.id!==r.targetRelease.id)throw new Error("Harness rollback target is unavailable in this workspace.");let s=L(r.storeDir,t.id);if((await P({workspaceId:t.id,sourceDir:s.source})).sourceRevision!==t.sourceRevision)throw new Error("Harness source changed before rollback.");let a=H.join(s.root,`.source-rollback-${W()}`);await k.cp(H.join(n.bundlePath,"source"),a,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});try{if((await P({workspaceId:t.id,sourceDir:a})).sourceRevision!==n.sourceRevision)throw new Error("Harness rollback bundle does not reproduce its registered source revision.");let u=(r.now??(()=>new Date().toISOString()))(),h=H.join(s.root,`.source-backup-${W()}`),f=H.join(s.root,"source-swap.json");await ut(f,{schemaVersion:"openpond.localHarnessSourceSwap.v1",workspaceId:t.id,expectedWorkspaceRevision:t.revision,previousSourceRevision:t.sourceRevision,nextSourceRevision:n.sourceRevision,backupSource:h,candidateSource:a,createdAt:u}),await k.rename(s.source,h),await k.rename(a,s.source);try{let b=await r.store.rollbackHarnessWorkspaceAtomically({receiptId:r.receiptId,workspaceId:t.id,expectedWorkspaceRevision:t.revision,expectedChannelRevision:t.currentChannel.revision,targetRelease:r.targetRelease,targetSourceRevision:n.sourceRevision,rollbackOf:r.rollbackOf,now:u});return b.receipt.decision!=="rolled_back"?await J(s.source,h):await k.rm(h,{recursive:!0,force:!0}),await k.rm(f,{force:!0}),b}catch(b){throw await J(s.source,h).catch(()=>{}),await k.rm(f,{force:!0}).catch(()=>{}),b}}finally{await k.rm(a,{recursive:!0,force:!0}).catch(()=>{})}}i(Jn,"rollbackLocalHarnessWorkspaceRelease");async function Kn(r){let t=C.parse(r.proposal);if(t.expectedWorkspace.workspaceId!==r.workspace.id)throw new Error("Refiner proposal targets a different Harness workspace.");if(t.route==="memory")return Nt({proposal:t,now:r.now});let n=L(r.storeDir,r.workspace.id),s=await P({workspaceId:r.workspace.id,sourceDir:n.source});if(s.sourceRevision!==t.expectedWorkspace.sourceRevision)throw new Error("Refiner proposal source revision no longer matches the Local Harness workspace.");let o=H.join(n.root,`.validation-candidate-${W()}`);await k.cp(n.source,o,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});let a=(r.now??(()=>new Date().toISOString()))();try{await lt(o,t);let c=await P({workspaceId:r.workspace.id,sourceDir:o}),u=new Map(c.manifest.files.map(d=>[d.path,d])),h=new Map(t.edits.map(d=>[d.target,d])),f=it(s),b=it(c);return Promise.all(t.validationPlan.map(async d=>{let R="passed",v="The candidate Harness source compiles and preserves its manifest contract.";try{if(d.kind==="observed_recovery"){let w=t.evidence.filter(p=>p.kind==="recovery");if(w.length===0)throw new Error("Observed-recovery validation requires recorded recovery evidence.");v=`Validated ${w.length} immutable recovery evidence reference(s) before candidate advancement.`}else if(d.kind==="prompt"){let w=t.edits.filter(p=>p.route==="prompt"&&p.target!=="harness.json");if(w.length===0)throw new Error("Prompt validation requires an instruction-file edit.");for(let p of w){let y=u.get(p.target);if(p.operation==="delete"){if(y)throw new Error(`Deleted instruction ${p.target} remains declared.`)}else if(y?.kind!=="instruction")throw new Error(`Instruction ${p.target} is not declared in the candidate Harness.`);if(p.content!==null&&/\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]/i.test(p.content))throw new Error(`Instruction ${p.target} appears to contain credential material.`)}v=`Validated ${w.length} textual instruction edit(s) and compiled candidate ${c.harnessRelease.id}.`}else if(d.kind==="skill"){let w=t.edits.filter(p=>p.route==="skill"&&p.target!=="harness.json");if(w.length===0)throw new Error("Skill validation requires a declared Skill-file edit.");for(let p of w){let y=u.get(p.target);if(p.operation==="delete"){if(y)throw new Error(`Deleted Skill ${p.target} remains declared.`);continue}if(y?.kind!=="skill")throw new Error(`Skill ${p.target} is not declared in the candidate Harness.`);let S=h.get(p.target)?.content;if(!S)throw new Error(`Skill edit ${p.target} has no content.`);let I=N(S);if(!I.name||!I.description||I.messages.length>0)throw new Error(`Skill ${p.target} is invalid: ${I.messages.join(" ")}`)}v=`Validated ${w.length} Skill edit(s), Skill frontmatter, and compiled candidate ${c.harnessRelease.id}.`}else if(d.kind==="dependency"){let w=c.manifest.files.find(p=>p.kind==="dependency_lock");if(!w)throw new Error("Candidate Harness has no dependency lock.");JSON.parse(await k.readFile(dt(o,w.path),"utf8")),v=`Validated dependency lock ${w.path} and compiled candidate ${c.harnessRelease.id}.`}else if(d.kind==="schema")C.parse(t),v=`Validated proposal, manifest, and candidate release schemas for ${c.harnessRelease.id}.`;else if(d.kind==="package"){let w=t.edits.filter(p=>p.route==="agent"&&p.operation!=="delete"&&p.target!=="harness.json");for(let p of w){if(!p.content)throw new Error(`Agent edit ${p.target} has no source.`);Dt(p.content,{mode:"transform",sourceUrl:p.target,sourceMap:!1})}v=w.length>0?`Syntax-checked ${w.length} Agent source edit(s) and compiled candidate ${c.harnessRelease.id}.`:`Compiled candidate package ${c.harnessRelease.id} and preserved the Harness source manifest contract.`}else if(d.kind==="component_activation"){let w=t.edits.filter(p=>p.target!=="harness.json");if(w.length===0)throw new Error("Component activation requires a concrete Harness component edit.");if(t.route==="agent"){if(w.filter(y=>y.operation!=="delete").length>0)throw new Error("Desktop Work does not compile or execute released Agent source; use an active instruction or standalone Skill, or add an Agent executor before release.");v=`Confirmed ${w.length} deleted Agent component(s) were inactive in Desktop Work.`}else{if(!["prompt","skill"].includes(t.route))throw new Error(`Desktop Work has no activation policy for ${t.route} proposals.`);let p=t.route==="prompt"?"instruction":"skill";for(let y of w){let S=b.components.find(I=>I.path===y.target&&I.kind===p);if(y.operation==="delete"?S:!S)throw new Error(`${p} ${y.target} is not reflected in the candidate Desktop Work runtime surface.`)}if(f.contentHash===b.contentHash)throw new Error("The candidate does not change the effective Desktop Work runtime surface.");v=`Activated ${w.length} ${p} edit(s) in the candidate Desktop Work runtime surface.`}}else d.kind==="business_formula"?(R="blocked",v="Business or financial logic is retained for review until an approved deterministic fixture supplies inputs and expected outputs."):d.kind==="targeted_evaluation"?(R="blocked",v="This sensitive change requires an explicit authority-preserving targeted Evaluation before release."):d.kind==="file_render"?(R="blocked",v="File-render validation requires an exact produced artifact reference; no artifact was attached to this Harness-source proposal."):(R="blocked",v=`Local targeted validation does not yet own ${d.kind}; it requires its dedicated validator.`)}catch(w){R="failed",v=w instanceof Error?w.message:String(w)}return ee({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${t.id}-${d.id}`,proposal:{id:t.id,contentHash:t.contentHash},validationId:d.id,kind:d.kind,status:R,summary:v,evidenceRefs:t.evidence,createdAt:a,metadata:{candidateHarnessRelease:{id:c.harnessRelease.id,contentHash:c.harnessRelease.contentHash},sourceRevision:c.sourceRevision,...d.kind==="component_activation"?{targetRuntime:"desktop_work",beforeEffectiveRuntimeHash:f.contentHash,afterEffectiveRuntimeHash:b.contentHash,activatedComponentRefs:b.components,inactiveAgentRefs:b.inactiveAgents}:{}}})}))}catch(c){let u=c instanceof Error?c.message:String(c);return t.validationPlan.map(h=>ee({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${t.id}-${h.id}`,proposal:{id:t.id,contentHash:t.contentHash},validationId:h.id,kind:h.kind,status:"failed",summary:u,evidenceRefs:t.evidence,createdAt:a,metadata:{}}))}finally{await k.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}i(Kn,"validateLocalHarnessRefinerProposal");function it(r){let t=[...r.agentSnapshot.instructions.map(s=>({kind:"instruction",path:s.path,contentHash:s.contentHash})),...r.agentSnapshot.skills.map(s=>({kind:"skill",path:s.path,contentHash:s.contentHash}))].sort((s,o)=>s.path.localeCompare(o.path)),n=r.agentSnapshot.agents.map(s=>({path:s.path,contentHash:s.contentHash})).sort((s,o)=>s.path.localeCompare(o.path));return{contentHash:X({schemaVersion:"openpond.desktopWorkHarnessSurface.v1",components:t}),components:t,inactiveAgents:n}}i(it,"desktopWorkRuntimeSurface");function Nt(r){let t=(r.now??(()=>new Date().toISOString()))(),n=r.proposal.edits.find(s=>s.route==="memory");return r.proposal.validationPlan.map(s=>{let o="passed",a="Memory candidate is bounded, scoped, and contains no obvious credential material.";try{if(s.kind==="observed_recovery"){if(!r.proposal.evidence.some(c=>c.kind==="recovery"))throw new Error("Observed-recovery validation requires recorded recovery evidence.");a="Memory proposal is grounded in immutable recovery evidence."}else if(s.kind==="memory"){if(!n||!/^memory\/[a-z0-9][a-z0-9-]{0,119}$/.test(n.target))throw new Error("Memory proposal requires one safe memory/<slug> target.");let c=r.proposal.metadata.expectedMemory;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Memory proposal requires an expected revision snapshot.");let u=c;if(u.key!==Lt(n.target))throw new Error("Memory proposal expected revision targets a different key.");if(u.revision!==null&&(!Number.isInteger(u.revision)||Number(u.revision)<1))throw new Error("Memory proposal expected revision is invalid.");if(u.contentHash!==null&&typeof u.contentHash!="string")throw new Error("Memory proposal expected content hash is invalid.");if(u.status!==null&&u.status!=="active"&&u.status!=="deleted")throw new Error("Memory proposal expected status is invalid.");if(u.revision===null&&(u.contentHash!==null||u.status!==null))throw new Error("New memory snapshot must not claim existing content or status.");if(u.revision!==null&&(typeof u.contentHash!="string"||u.status===null))throw new Error("Existing memory snapshot requires its content hash and status.");if(n.operation==="delete"&&u.status!=="active")throw new Error("Memory deletion requires an active expected revision.");if(n.operation!=="delete"){if(!n.content?.trim()||n.content.length>24e3)throw new Error("Memory content must contain 1-24,000 characters.");if(/\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]/i.test(n.content))throw new Error("Memory content appears to contain credential material.")}}else o="blocked",a=`Memory validation cannot satisfy ${s.kind}.`}catch(c){o="failed",a=c instanceof Error?c.message:String(c)}return ee({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${r.proposal.id}-${s.id}`,proposal:{id:r.proposal.id,contentHash:r.proposal.contentHash},validationId:s.id,kind:s.kind,status:o,summary:a,evidenceRefs:r.proposal.evidence,createdAt:t,metadata:{externalState:"harness_memory"}})})}i(Nt,"validateMemoryProposal");function Lt(r){let t=r.replaceAll("\\","/"),n=/^memory\/([a-z0-9][a-z0-9-]{0,119})$/.exec(t);if(!n)throw new Error(`Invalid Harness memory target: ${r}.`);return n[1]}i(Lt,"memoryKeyFromTarget");async function ct(r){let t=await r.store.getHarnessWorkspace(r.workspaceId);if(!t)throw new Error(`Harness workspace ${r.workspaceId} does not exist.`);let n=L(r.storeDir,t.id),s=H.join(n.root,"source-swap.json"),o=await k.readFile(s,"utf8").then(JSON.parse).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(!o)return"none";let a=await P({workspaceId:t.id,sourceDir:n.source});if(t.sourceRevision===o.nextSourceRevision&&a.sourceRevision===o.nextSourceRevision)return await k.rm(o.backupSource,{recursive:!0,force:!0}),await k.rm(s,{force:!0}),"completed";let c=await P({workspaceId:t.id,sourceDir:o.backupSource});if(t.sourceRevision===o.previousSourceRevision&&c.sourceRevision===o.previousSourceRevision)return await J(n.source,o.backupSource),await k.rm(s,{force:!0}),"restored";throw new Error("Harness source-swap recovery cannot reconcile filesystem and workspace revisions.")}i(ct,"recoverLocalHarnessSourceSwap");async function lt(r,t){for(let n of t.edits){let s=dt(r,n.target);if(n.operation==="delete"){await k.rm(s,{force:!1});continue}if(n.content===null)throw new Error(`Refiner edit ${n.id} has no content.`);if(n.operation==="create")await k.mkdir(H.dirname(s),{recursive:!0}),await k.writeFile(s,n.content,{flag:"wx"});else{let o=await k.lstat(s);if(!o.isFile()||o.isSymbolicLink())throw new Error(`Refiner update target must be a regular file: ${n.target}`);await k.writeFile(s,n.content,{flag:"w"})}}}i(lt,"applyOverlayEdits");function dt(r,t){let n=H.resolve(r),s=H.resolve(n,...t.replaceAll("\\","/").split("/")),o=H.relative(n,s);if(!o||o.startsWith("..")||H.isAbsolute(o))throw new Error(`Refiner edit target escapes the Harness source: ${t}`);return s}i(dt,"containedPath");async function ut(r,t){let n=`${r}.${W()}.tmp`;await k.writeFile(n,`${JSON.stringify(t,null,2)}
|
|
6
|
-
`,{flag:"wx"}),await k.rename(n,r)}i(ut,"writeSwapJournal");async function J(r,t){await k.rm(r,{recursive:!0,force:!0}),await k.rename(t,r)}i(J,"restoreSource");var j="desktop-personal",pt="personal-default";async function es(r){let t=await r.store.getSelectedHarnessWorkspace({ownerKind:"personal",ownerId:j});if(t&&t.metadata.selectionEligible!==!1)return await ct({store:r.store,storeDir:r.storeDir,workspaceId:t.id}),he(r.store,t.id,t.currentChannel.release?.contentHash??null);let n=(await r.store.listHarnessWorkspaces({ownerKind:"personal",ownerId:j})).find(a=>a.metadata.selectionEligible!==!1);if(n)return await r.store.selectHarnessWorkspace({ownerKind:"personal",ownerId:j,workspaceId:n.id,updatedAt:(r.now??(()=>new Date().toISOString()))()}),he(r.store,n.id,n.currentChannel.release?.contentHash??null);let s=await r.loadProfileState(),o=s.mode==="local"&&s.sourcePath&&!s.error?await Oe({store:r.store,storeDir:r.storeDir,id:pt,ownerId:j,name:s.activeProfile?.trim()||"Personal Harness",profile:s,now:r.now}):await qe({store:r.store,storeDir:r.storeDir,id:pt,ownerId:j,name:"Personal Harness",now:r.now});return await r.store.selectHarnessWorkspace({ownerKind:"personal",ownerId:j,workspaceId:o.workspace.id,updatedAt:(r.now??(()=>new Date().toISOString()))()}),o.release}i(es,"ensureSelectedLocalHarnessWorkspace");async function mt(r){let t=await r.getSelectedHarnessWorkspace({ownerKind:"personal",ownerId:j});return t?he(r,t.id,t.currentChannel.release?.contentHash??null):null}i(mt,"resolveSelectedLocalHarnessRelease");async function he(r,t,n){if(!n)throw new Error(`Selected Harness workspace ${t} has no current release.`);let s=await r.getHarnessReleaseRecord(n);if(!s||s.workspaceId!==t)throw new Error(`Selected Harness workspace ${t} points to a missing release ${n}.`);return V(s.agentSnapshot,"Selected Agent snapshot"),V(s.harnessRelease,"Selected Harness release"),s}i(he,"requireCurrentRelease");import{promises as ht}from"node:fs";import x from"node:path";async function cs(r,t){if(t){let o=await r.getHarnessReleaseRecord(t.contentHash);if(!o||o.harnessRelease.id!==t.id)throw new Error("The selected immutable Harness release is unavailable.");let a=await r.getHarnessWorkspace(o.workspaceId);if(!a||a.ownerScope.kind!=="personal"||a.ownerScope.id!==j)throw new Error("The selected Harness release is not available to this local owner.");return V(o.agentSnapshot,"Selected Agent snapshot"),V(o.harnessRelease,"Selected Harness release"),ie({workspace:a,release:o})}let n=await mt(r);if(!n)return null;let s=await r.getSelectedHarnessWorkspace({ownerKind:"personal",ownerId:j});if(!s||s.id!==n.workspaceId)throw new Error("Selected Harness workspace changed while its release was being admitted.");return ie({workspace:s,release:n})}i(cs,"loadSelectedLocalHarnessRuntime");async function ie(r){let{workspace:t,release:n}=r;if(n.workspaceId!==t.id)throw new Error("Harness release does not belong to the requested workspace.");let s=x.join(n.bundlePath,"source");await Promise.all(n.harnessRelease.files.map(d=>Mt(s,d.path,d.contentHash)));let o=await Promise.all(n.agentSnapshot.instructions.map(async d=>({path:d.path,content:await fe(s,d.path,d.contentHash)}))),a=[],c=new Map;for(let d of n.agentSnapshot.skills){let R=await fe(s,d.path,d.contentHash),v=N(R);if(!v.name||!v.description||v.messages.length>0)throw new Error(`Released Harness Skill ${d.path} is invalid: ${v.messages.join(" ")||"missing name or description"}`);if(c.has(v.name))throw new Error(`Released Harness has duplicate Skill ${v.name}.`);let w=`${x.posix.dirname(d.path)}/`,p=n.harnessRelease.files.filter(S=>S.path.startsWith(w)&&S.path!==d.path).map(S=>S.path.slice(w.length)).sort(),y={name:v.name,description:v.description,path:d.path,scope:"profile",enabled:!0,sourcePath:s,charCount:R.length,sourceHash:d.contentHash,validationStatus:"valid",validationMessages:[],resourceFiles:p};a.push(y),c.set(y.name,async()=>{let S=await fe(s,d.path,d.contentHash),I=N(S);if(!I.name||!I.description||I.messages.length>0)throw new Error(`Released Harness Skill ${d.path} failed validation while loading.`);return{name:I.name,description:I.description,body:I.body,path:d.path,sourceHash:d.contentHash,charCount:S.length,packagePath:x.join(s,...x.posix.dirname(d.path).split("/")),resourceFiles:p}})}a.sort((d,R)=>d.name.localeCompare(R.name));let u={profileSourcePath:s,skills:a,readSkill:c.size>0?async d=>{let R=c.get(d);if(!R)throw new Error(`Released Harness Skill not found: ${d}`);return R()}:null},h=o.sort((d,R)=>d.path.localeCompare(R.path)).map(({path:d,content:R})=>[`Active Harness instruction (${d}):`,R.trim()].join(`
|
|
7
|
-
`)).filter(d=>d.trim().length>0),b=[["Harness capability receipt:",JSON.stringify({harnessRelease:{id:n.harnessRelease.id,contentHash:n.harnessRelease.contentHash},agentSnapshot:{id:n.agentSnapshot.id,contentHash:n.agentSnapshot.contentHash},files:n.harnessRelease.files.map(d=>({path:d.path,contentHash:d.contentHash})),skills:n.agentSnapshot.skills.map(d=>d.path),agents:n.agentSnapshot.agents.map(d=>d.path),tools:n.agentSnapshot.toolDeclarations.map(d=>d.name),capabilityRequirements:n.agentSnapshot.capabilityRequirements})].join(`
|
|
8
|
-
`),h.length>0?["Active Harness preflight:","Apply the following released instructions when planning work and immediately before every tool call.","Preflight each call: (1) identify any active instruction that matches the planned operation, (2) inspect the exact tool arguments for a forbidden pattern, and (3) rewrite the call before sending it when a pattern matches. Compliance is required even when the prohibited call might still succeed.",...h].join(`
|
|
9
|
-
|
|
10
|
-
`):null].filter(d=>!!d?.trim()).join(`
|
|
11
|
-
|
|
12
|
-
`);return{workspace:t,release:n,instructionContext:b,skillRuntime:u}}i(ie,"loadLocalHarnessRuntimeFromRelease");async function fe(r,t,n){let s=x.resolve(r,...t.split("/")),o=x.relative(x.resolve(r),s);if(!o||o.startsWith("..")||x.isAbsolute(o))throw new Error(`Released Harness asset escapes its bundle: ${t}`);let a=await ht.readFile(s),c=de(a);if(c!==n)throw new Error(`Released Harness asset ${t} is ${c}; expected ${n}.`);return new TextDecoder("utf-8",{fatal:!0}).decode(a)}i(fe,"readVerifiedAsset");async function Mt(r,t,n){let s=x.resolve(r,...t.split("/")),o=x.relative(x.resolve(r),s);if(!o||o.startsWith("..")||x.isAbsolute(o))throw new Error(`Released Harness asset escapes its bundle: ${t}`);let a=de(await ht.readFile(s));if(a!==n)throw new Error(`Released Harness asset ${t} is ${a}; expected ${n}.`)}i(Mt,"verifyAsset");import{randomUUID as Bt}from"node:crypto";var we=e.object({revision:e.number().int().nonnegative(),overlay:D}).strict(),Ft=we.extend({proposal:C}).strict(),ce=class{constructor(t){this.client=t}client;static{i(this,"HostedHarnessOverlayStorage")}async getHarnessRunOverlay(t){let n=await this.client.request({contractVersion:g,requestId:Bt(),operation:"harness/overlay/get",params:{runId:t}});return n===null?null:we.parse(n).overlay}async putHarnessRunOverlay(t){let n=D.parse(t.overlay);if(!t.requestId.trim()||n.revision!==(t.expectedRevision===null?0:t.expectedRevision+1))throw new Error("Hosted Harness overlay mutation requires a stable request and next revision.");let s=we.parse(await this.client.request({contractVersion:g,requestId:t.requestId,operation:"harness/overlay/put",params:{runId:n.runId,expectedRevision:t.expectedRevision,overlay:n}}));if(s.revision!==n.revision||s.overlay.contentHash!==n.contentHash)throw new Error("Host Harness overlay response changed committed identity.");return s.overlay}async createHarnessRunOverlay(t){if(t.revision!==0||t.status!=="active")throw new Error("A new Harness run overlay must be active at revision 0.");return this.putHarnessRunOverlay({overlay:t,expectedRevision:null,requestId:`harness-overlay:${t.runId}:${t.contentHash}`})}async ensureHarnessRunOverlay(t){let n=await this.getHarnessRunOverlay(t.runId);if(n){if(n.workspace.workspaceId!==t.workspace.id||n.baseHarnessRelease.id!==t.harnessRelease.id||n.baseHarnessRelease.contentHash!==t.harnessRelease.contentHash)throw new Error("The durable Agent run is already bound to another Harness release.");return n}let s=Z({schemaVersion:"openpond.harnessRunOverlay.v1",id:`overlay-${X({runId:t.runId,harnessRelease:t.harnessRelease}).slice(0,24)}`,runId:t.runId,baseHarnessRelease:t.harnessRelease,workspace:{workspaceId:t.workspace.id,revision:t.workspace.revision,sourceRevision:t.workspace.sourceRevision,channelRevision:t.workspace.currentChannel.revision},revision:0,status:"active",edits:[],createdAt:t.admittedAt,updatedAt:t.admittedAt,metadata:{}});return this.createHarnessRunOverlay(s)}async appendHarnessRunOverlayEditsAtomically(t){return this.transition(t,"append")}async freezeHarnessRunOverlayAtomically(t){return this.transition({...t,edits:[]},"freeze")}async abandonHarnessRunOverlayAtomically(t){return this.transition({...t,edits:[]},"abandon")}async freezeHarnessRunOverlayWithProposalAtomically(t){let n=await this.getHarnessRunOverlay(t.runId);if(!n||n.revision!==t.expectedRevision||n.status!=="active")throw new Error("Hosted Harness overlay revision or status changed.");let s=new Set(n.edits.map(f=>f.id));for(let f of t.edits){if(s.has(f.id))throw new Error(`Harness overlay edit id already exists: ${f.id}.`);s.add(f.id)}let{contentHash:o,...a}=n,c=Z({...a,revision:n.revision+1,status:"frozen",edits:[...n.edits,...t.edits],updatedAt:t.updatedAt}),u=C.parse(t.buildProposal(c)),h=Ft.parse(await this.client.request({contractVersion:g,requestId:`harness-proposal:${c.runId}:${u.contentHash}`,operation:"harness/overlay/freezeProposal",params:{runId:c.runId,expectedRevision:n.revision,overlay:c,proposal:u}}));if(h.overlay.contentHash!==c.contentHash||h.proposal.contentHash!==u.contentHash)throw new Error("Host Harness proposal response changed committed identity.");return{overlay:h.overlay,proposal:h.proposal}}async transition(t,n){let s=await this.getHarnessRunOverlay(t.runId);if(!s||s.revision!==t.expectedRevision||s.status==="abandoned"||n!=="abandon"&&s.status!=="active")throw new Error("Hosted Harness overlay revision or status changed.");if(n==="append"&&t.edits.length===0)throw new Error("Harness overlay append requires edits.");let o=new Set(s.edits.map(h=>h.id));for(let h of t.edits){if(o.has(h.id))throw new Error(`Harness overlay edit id already exists: ${h.id}.`);o.add(h.id)}let{contentHash:a,...c}=s,u=Z({...c,revision:s.revision+1,status:n==="append"?"active":n==="freeze"?"frozen":"abandoned",edits:[...s.edits,...t.edits],updatedAt:t.updatedAt});return this.putHarnessRunOverlay({overlay:u,expectedRevision:s.revision,requestId:`harness-overlay:${u.runId}:${u.contentHash}`})}};import{randomUUID as Ut}from"node:crypto";import{readFile as K}from"node:fs/promises";import $ from"node:path";var Jt=e.object({workspace:He,release:e.object({id:e.string().min(1),contentHash:e.string().regex(/^[a-f0-9]{64}$/),sourceRevision:e.string().min(1),assetsPath:e.string().min(1)}).strict()}).strict();async function G(r,t=null){let n=await r.request({contractVersion:g,requestId:Ut(),operation:"harness/get",params:{reference:t}});if(n===null)return null;let s=Jt.parse(n);if(!$.isAbsolute(s.release.assetsPath))throw new Error("Hosted Harness assets path must be absolute.");let[o,a]=await Promise.all([K($.join(s.release.assetsPath,"agent-snapshot.json"),"utf8"),K($.join(s.release.assetsPath,"harness-release.json"),"utf8")]),c=Te.parse({schemaVersion:"openpond.localHarnessReleaseRecord.v1",workspaceId:s.workspace.id,sourceRevision:s.release.sourceRevision,agentSnapshot:Ie.parse(JSON.parse(o)),harnessRelease:Se.parse(JSON.parse(a)),bundlePath:s.release.assetsPath,createdAt:new Date().toISOString()});if(c.harnessRelease.id!==s.release.id||c.harnessRelease.contentHash!==s.release.contentHash||(t!==null?t.id!==s.release.id||t.contentHash!==s.release.contentHash:s.workspace.currentChannel.release?.contentHash!==s.release.contentHash))throw new Error("Hosted Harness release differs from its bound workspace.");return ie({workspace:s.workspace,release:c})}i(G,"loadHostedHarnessRuntime");async function js(r,t){let n=t.profileComponentBinding,s=t.profileWorkflowBinding;if(n){if(s||t.currentProfile?.profileId!==n.profileId)throw new Error("Profile component binding differs from the session Profile reference.");let a=await ft(r,n.harnessRelease);if(wt(a,n.profileId,n.sourceRevision,t.currentProfile?.repositoryId),n.target.kind==="profile")return a;if(n.target.kind==="skill"){let f=n.target.skillPath;if(!a.release.agentSnapshot.skills.some(d=>d.path===f))throw new Error("Bound Profile Skill is unavailable in its released source.");let b=await K($.join(a.release.bundlePath,"source",f),"utf8");return{...a,instructionContext:[a.instructionContext,`Released Profile Skill (${f}):
|
|
13
|
-
${b}`].join(`
|
|
14
|
-
|
|
15
|
-
`)}}let c=await gt(a),u=n.target.actionId,h=c.actions.find(f=>f.id===u);if(!h)throw new Error("Bound Profile Agent action is unavailable in its released source.");return{...a,workflowAction:h}}if(s){if(t.currentProfile?.profileId!==s.profileId)throw new Error("Profile workflow binding differs from the session Profile reference.");let a=await ft(r,s.harnessRelease);wt(a,s.profileId,s.sourceRevision,t.currentProfile?.repositoryId);let c=await gt(a),u=Ee({binding:s,harnessRelease:a.release.harnessRelease,catalog:c.catalog,catalogHash:c.catalogHash}),h=u.invocation.kind==="agent_action"?u.invocation.actionId:null,f=h?c.actions.find(b=>b.id===h):void 0;if(h&&!f)throw new Error(`Bound Profile action ${h} is missing from its release.`);return{...a,workflow:u,...f?{workflowAction:f}:{}}}let o=await new ce(r).getHarnessRunOverlay(t.id);return G(r,o?.baseHarnessRelease??null)}i(js,"loadHostedHarnessRuntimeForSession");async function ft(r,t){let n=await G(r,t);if(!n)throw new Error("The bound Profile Harness release is unavailable.");return n}i(ft,"requireRelease");function wt(r,t,n,s){let o=r.release.harnessRelease.metadata.profile;if(!o||typeof o!="object"||o.id!==t||o.sourceRevision!==n||o.repositoryId!==void 0&&o.repositoryId!==s)throw new Error("Bound Profile source differs from its released Harness source.")}i(wt,"assertProfileProvenance");async function gt(r){let t=$.join(r.release.bundlePath,"source"),[n,s]=await Promise.all([K($.join(t,"workflows","catalog.json")),K($.join(t,"workflows","actions.json"))]);return te({agentSnapshot:r.release.agentSnapshot,harnessRelease:r.release.harnessRelease,catalogBytes:n,actionBytes:s})}i(gt,"loadHostedProfileCatalog");function qs(r){return Kt({runtime:st(r.ports),close:r.close})}i(qs,"createAppServer");function Kt(r){let t=!1;return{runtime:r.runtime,close:i(async()=>{t||(t=!0,await r.close?.())},"close")}}i(Kt,"attachAppServer");async function Os(r){let t=typeof r.appServer=="function"?null:r.appServer;try{await nt({host:t?.runtime??(async()=>(t=await r.appServer(),t.runtime)),readable:r.readable,writable:r.writable,hostStorageClient:r.hostStorageClient})}finally{await t?.close()}}i(Os,"runAppServerJsonl");import{randomBytes as Gt}from"node:crypto";function zs(){return ge()}i(zs,"appDataDir");function Ws(r){return E(r).config}i(Ws,"providersConfigPath");function Ds(r){return E(r).credentials}i(Ds,"providerSecretsConfigPath");function Ns(r){return E(r).key}i(Ns,"providerSecretsKeyPath");async function Ls(r){let t=E(r).token;return be(t,async()=>{let n=(await ve(t))?.trim(),s=process.env.OPENPOND_APP_TOKEN||n||Gt(32).toString("base64url");return s!==n&&await Y(t,s),{token:s,tokenFile:t}})}i(Ls,"ensureCapabilityToken");import O from"node:path";import{readFile as vt}from"node:fs/promises";var bt=e.object({profileId:e.string().min(1),sourceRevision:e.string().min(1),repositoryId:e.string().min(1),harnessRelease:e.object({id:e.string().min(1),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),workspaceId:e.string().min(1),assetsPath:e.string().min(1).refine(O.isAbsolute)}).strict();async function Ys(r,t){let n=bt.parse(t),s=await G(r,n.harnessRelease);if(!s||O.resolve(s.release.bundlePath)!==O.resolve(n.assetsPath))throw new Error("Hosted Profile release changed after admission.");let o=s.release.harnessRelease.metadata.profile;if(!o||typeof o!="object"||o.id!==n.profileId||o.sourceRevision!==n.sourceRevision||o.repositoryId!==void 0&&o.repositoryId!==n.repositoryId)throw new Error("Hosted Profile provenance differs from admitted release.");return{profile:Pe(),profileLibrary:je()}}i(Ys,"loadHostedProfileStateAndLibrary");async function Xs(r,t){let n=bt.parse(t),s=await G(r,n.harnessRelease);if(!s||O.resolve(s.release.bundlePath)!==O.resolve(n.assetsPath))throw new Error("Hosted Profile workflow release is unavailable.");let o=s.release.harnessRelease.metadata.profile;if(o?.id!==n.profileId||o.sourceRevision!==n.sourceRevision||o.repositoryId!==void 0&&o.repositoryId!==n.repositoryId)throw new Error("Hosted Profile workflow provenance changed.");let a=n.harnessRelease,c={source:"openpond_git",repositoryId:n.repositoryId,profileId:n.profileId};if(!s.release.harnessRelease.files.some(f=>f.path==="workflows/catalog.json"))return{profileRef:c,sourceRevision:n.sourceRevision,harnessRelease:a,workflows:[]};let u=O.join(s.release.bundlePath,"source","workflows"),h=te({agentSnapshot:s.release.agentSnapshot,harnessRelease:s.release.harnessRelease,catalogBytes:await vt(O.join(u,"catalog.json")),actionBytes:await vt(O.join(u,"actions.json"))});return{profileRef:c,sourceRevision:n.sourceRevision,harnessRelease:a,workflows:h.catalog.workflows.map(f=>({workflow:f,binding:{schemaVersion:"openpond.profileWorkflowBinding.v1",profileId:n.profileId,sourceRevision:n.sourceRevision,harnessRelease:a,catalogHash:h.catalogHash,workflowId:f.id}}))}}i(Xs,"listHostedProfileWorkflows");export{er as a,tr as b,rr as c,z as d,or as e,ar as f,ir as g,At as h,Dr as i,re as j,ur as k,Et as l,g as m,Pr as n,rt as o,Wt as p,ln as q,dn as r,hn as s,fn as t,ot as u,at as v,Un as w,Jn as x,Kn as y,j as z,es as A,mt as B,cs as C,ie as D,ce as E,G as F,js as G,qs as H,Os as I,zs as J,Ws as K,Ds as L,Ns as M,Ls as N,bt as O,Ys as P,Xs as Q};
|
|
@@ -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-OYJ73BSC.js";import"./chunk-XR6ZLKVW.js";import"./chunk-JLWAK5PS.js";import"./chunk-PMXE4CAA.js";import"./chunk-SRQVXHSM.js";import"./chunk-77BXXOHW.js";import"./chunk-TBX3Z7TX.js";import"./chunk-L3KS6MOV.js";import"./chunk-QWENRTVW.js";import"./chunk-6MI4KKWF.js";import"./chunk-JFSDNQHW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import"./chunk-5BFWDFPX.js";import"./chunk-6FA3GG5B.js";import"./chunk-IFP6W4OW.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-PZ2ZILPN.js";import{Aa as C,Ab as T,Ca as m,Da as j,Ea as x,Fa as F,Ga as v,Ha as P,Sa as J,b as d,c as w,e as b,fb as N,gb as q,jb as k,lb as A,mb as B,pb as H,qb as I,yb as E,zb as M}from"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import{d as O,f as S,h as g}from"./chunk-H7IWJN7L.js";import"./chunk-E4U7LXSW.js";import"./chunk-3M53YXEI.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-BOQBDCVU.js";import"./chunk-MXLB6MEW.js";import"./chunk-XCTFXXVY.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-OGPHXXCD.js";import"./chunk-BAKCGJ5D.js";import"./chunk-Z6F6PYF4.js";import"./chunk-QPZNN5Q3.js";import"./chunk-GLUWATL5.js";import"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import"./chunk-5BFWDFPX.js";import"./chunk-PZ2ZILPN.js";import"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-E4U7LXSW.js";import"./chunk-3M53YXEI.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-MXLB6MEW.js";import"./chunk-XCTFXXVY.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-OGPHXXCD.js";import"./chunk-BAKCGJ5D.js";import"./chunk-Z6F6PYF4.js";import"./chunk-QPZNN5Q3.js";import"./chunk-GLUWATL5.js";import"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import"./chunk-5BFWDFPX.js";import{a as c}from"./chunk-PZ2ZILPN.js";import"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-E4U7LXSW.js";import{c as p,f as u}from"./chunk-3M53YXEI.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{$a as ga,Aa as A,Ab as Ha,Ba as B,Bb as Ia,Ca as C,Da as D,Ea as E,Fa as F,Ga as G,Ha as H,Ia as I,Ja as J,Ka as K,La as L,Ma as M,Na as N,Oa as O,Pa as W,Qa as X,Ra as Y,Sa as Z,Ta as _,Ua as $,Va as aa,Wa as ba,Xa as ca,Ya as da,Za as ea,_a as fa,a as l,ab as ha,b as m,bb as ia,c as n,cb as ja,d as o,db as ka,e as p,eb as la,f as q,fb as ma,g as r,gb as na,h as s,hb as oa,i as t,ib as pa,j as u,jb as qa,kb as ra,lb as sa,mb as ta,nb as ua,ob as va,pb as wa,qb as xa,rb as ya,sb as za,tb as Aa,ub as Ba,va as v,vb as Ca,wa as w,wb as Da,xa as x,xb as Ea,ya as y,yb as Fa,za as z,zb as Ga}from"./chunk-IFP6W4OW.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,3 +0,0 @@
|
|
|
1
|
-
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{ka as n,oa as c}from"./chunk-JLWAK5PS.js";import"./chunk-PMXE4CAA.js";import{M as l}from"./chunk-77BXXOHW.js";import"./chunk-TBX3Z7TX.js";import"./chunk-L3KS6MOV.js";import"./chunk-QWENRTVW.js";import"./chunk-6MI4KKWF.js";import"./chunk-JFSDNQHW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import"./chunk-5BFWDFPX.js";import"./chunk-6FA3GG5B.js";import"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";import{mkdir as d}from"node:fs/promises";import s from"node:path";async function p(e){if(!s.isAbsolute(e.repoPath)||!s.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 l({repoPath:e.repoPath,profileId:e.profileId});if(o.error||o.mode!=="local"||o.activeProfile!==e.profileId||!o.sourcePath||!s.resolve(o.sourcePath).startsWith(`${s.resolve(e.repoPath)}${s.sep}`))throw new Error("Hosted Profile source is unavailable.");await d(e.outputDir,{recursive:!0});let t=await n({storeDir:e.outputDir,workspaceId:e.workspaceId,name:e.profileId,profile:o,sourceRevision:e.sourceRevision,repositoryId:e.repositoryId}),r=t.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:t,createdAt:new Date().toISOString()});return{workspaceId:e.workspaceId,sourceRevision:i.sourceRevision,harnessRelease:i.harnessRelease,agentSnapshot:i.agentSnapshot,bundlePath:i.bundlePath}}a(p,"compileHostedProfileRelease");async function P(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")),t=await p(o);process.stdout.write(`${JSON.stringify(t)}
|
|
3
|
-
`)}a(P,"runHostedProfileCompilerCli");export{p as compileHostedProfileRelease,P as runHostedProfileCompilerCli};
|
|
@@ -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-MXLB6MEW.js";import"./chunk-XCTFXXVY.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-77BXXOHW.js";import"./chunk-L3KS6MOV.js";import"./chunk-QWENRTVW.js";import"./chunk-6MI4KKWF.js";import"./chunk-JFSDNQHW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-OGPHXXCD.js";import"./chunk-BAKCGJ5D.js";import"./chunk-Z6F6PYF4.js";import"./chunk-QPZNN5Q3.js";import"./chunk-GLUWATL5.js";import"./chunk-B5LKUQGM.js";import{d as x,e as C}from"./chunk-MJC26GOX.js";import"./chunk-5BFWDFPX.js";import"./chunk-6FA3GG5B.js";import"./chunk-PZ2ZILPN.js";import"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-E4U7LXSW.js";import{a as E,f as b,h as k,i as _}from"./chunk-3M53YXEI.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-EFTLCT7C.js";import{m as h,n as I,v as P}from"./chunk-MXLB6MEW.js";import"./chunk-XCTFXXVY.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-DR3XPQRZ.js";import"./chunk-OGPHXXCD.js";import"./chunk-BAKCGJ5D.js";import"./chunk-Z6F6PYF4.js";import"./chunk-QPZNN5Q3.js";import"./chunk-GLUWATL5.js";import"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import"./chunk-5BFWDFPX.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import"./chunk-PZ2ZILPN.js";import"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-E4U7LXSW.js";import{c as u,d,e as w,f as S}from"./chunk-3M53YXEI.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};
|