openpond 0.2.31 → 0.2.33
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 +14 -0
- package/dist/app-server.js +1 -1
- package/dist/chunks/{app-layer-ZZHTHTJU.js → app-layer-HK2GTSRX.js} +1 -1
- package/dist/chunks/app-server-runtime-365GFLRG.js +2 -0
- package/dist/chunks/{apps-C2BMJ7DO.js → apps-YJRRLX2N.js} +1 -1
- package/dist/chunks/{chunk-MVAJMRCW.js → chunk-77BXXOHW.js} +4 -4
- package/dist/chunks/{chunk-GCU66EAF.js → chunk-BK4I7KE4.js} +1 -1
- package/dist/chunks/{chunk-T22TCCWW.js → chunk-BOQBDCVU.js} +1 -1
- package/dist/chunks/chunk-CWW2EK77.js +4 -0
- package/dist/chunks/chunk-DYHB6VMK.js +578 -0
- package/dist/chunks/{chunk-JFR34MIK.js → chunk-E4U7LXSW.js} +2 -2
- package/dist/chunks/{chunk-CE27WEHK.js → chunk-EWB4XTWR.js} +1 -1
- package/dist/chunks/{chunk-QTEYV4TW.js → chunk-JFSDNQHW.js} +7 -7
- package/dist/chunks/chunk-PCAHFOCQ.js +2406 -0
- package/dist/chunks/{chunk-UU7RXSJS.js → chunk-PZ2ZILPN.js} +1 -1
- package/dist/chunks/{chunk-55UCBRIX.js → chunk-QWENRTVW.js} +4 -4
- package/dist/chunks/{chunk-JVIHGSOV.js → chunk-SRQVXHSM.js} +1 -1
- package/dist/chunks/chunk-TBX3Z7TX.js +2 -0
- package/dist/chunks/chunk-U3TN2FNR.js +15 -0
- package/dist/chunks/chunk-V23D3DDD.js +42 -0
- package/dist/chunks/cli-DKRMREVK.js +2 -0
- package/dist/chunks/{configuration-command-IHUB6BBM.js → configuration-command-CYUWO6CD.js} +1 -1
- package/dist/chunks/{core-commands-F2HIN7V4.js → core-commands-Z5C7S6OH.js} +1 -1
- package/dist/chunks/{desktop-test-BFFUGVRS.js → desktop-test-JBZCCTSN.js} +1 -1
- package/dist/chunks/{extension-D7IYZW7H.js → extension-RMJAXEKN.js} +1 -1
- package/dist/chunks/{help-5MKQV36D.js → help-QDMTLEIL.js} +1 -1
- package/dist/chunks/hosted-profile-compiler-KL7BXGRR.js +3 -0
- package/dist/chunks/{opchat-XO7EDHY7.js → opchat-MHH4C5YQ.js} +1 -1
- package/dist/chunks/{organizations-DIRGTVK5.js → organizations-5KM2JD32.js} +1 -1
- package/dist/chunks/{profile-EMVJ5DJQ.js → profile-KVDJTM4D.js} +1 -1
- package/dist/chunks/{project-agent-4QC7N3MB.js → project-agent-SXUMNJLZ.js} +1 -1
- package/dist/chunks/{sandbox-command-L263BBOL.js → sandbox-command-FQGX5MSS.js} +1 -1
- package/dist/chunks/{sandbox-template-RYKWTBW7.js → sandbox-template-Q6K5JXA3.js} +1 -1
- package/dist/chunks/{src-RINMQ7IQ.js → src-42VXY5DZ.js} +1 -1
- package/dist/chunks/{src-RM2LIZGT.js → src-RZFP5QEE.js} +111 -111
- package/dist/chunks/{teams-bot-NIZB6DOY.js → teams-bot-7TPB34DR.js} +1 -1
- package/dist/chunks/{workspaces-GPYDSN4C.js → workspaces-DOTGXXEV.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/web/assets/App-BKY1b22z.js +226 -0
- package/dist/web/assets/{AppDialog-C1cvE0gH.js → AppDialog-C64bP66E.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-BFJNR2ik.js → AppTerminalPanel-fVkWSvWK.js} +2 -2
- package/dist/web/assets/{AppsView-CReOofAf.js → AppsView-DHnab11q.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-CPxAck2O.js → BrowserSidebar-C7YeQ9KS.js} +1 -1
- package/dist/web/assets/{CartesianChart-SlZ8Qfkg.js → CartesianChart-CYX3IXBM.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-DgFEunqQ.js → CollaborationTabs-j2oBkesr.js} +1 -1
- package/dist/web/assets/{CommandMenu-BiROlSdv.js → CommandMenu-BN1a4dTn.js} +1 -1
- package/dist/web/assets/{CommunityView-DVST_ZxO.js → CommunityView-CNoxP71Z.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-jRBhdiFB.js → ComposerCreateImproveStrip-IoK3lqK8.js} +1 -1
- package/dist/web/assets/{GetStartedView-Ck4EW1_s.js → GetStartedView-QPabIxZC.js} +1 -1
- package/dist/web/assets/HostedModelLearningReview-CNd3-FrC.js +1 -0
- package/dist/web/assets/{HostedModelLearningSettings-BD7quEFA.js → HostedModelLearningSettings-TkSSxw8x.js} +1 -1
- package/dist/web/assets/{LabModelVersionDetailPage-8-Gb5AAH.js → LabModelVersionDetailPage-CRFw6V7e.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-DO-kFl9Z.js → LabSkillSidebar-Dl8KWUe0.js} +1 -1
- package/dist/web/assets/{LabsRoute-Dc9RQKdA.js → LabsRoute-BzdL7mUM.js} +4 -4
- package/dist/web/assets/{MainChatThread-DZXcFgmJ.js → MainChatThread-C3IdxbN3.js} +2 -2
- package/dist/web/assets/{MainPane-BYrnuI30.js → MainPane-BdR1K59_.js} +4 -4
- package/dist/web/assets/{MarkdownText-ueZFkEyk.js → MarkdownText-CkLxqh2M.js} +1 -1
- package/dist/web/assets/{NativeSkillSidebar-DlAX2-dH.js → NativeSkillSidebar-VkWpZX6S.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-BHYLG0IZ.js → NewExperienceSwitcher-D_K16Ho-.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-BwN6SnxR.js → NewProjectDialog-B6E1wWOM.js} +1 -1
- package/dist/web/assets/{OutputsPage-Q0kpdfq_.js → OutputsPage-27MuutGA.js} +1 -1
- package/dist/web/assets/{ProjectsPage-TnlBYfFy.js → ProjectsPage-CokpZHgx.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-D2qZ-1nK.js → RightChatPanelStack-B6JhJdlc.js} +1 -1
- package/dist/web/assets/{RightSidebarHomePanel-q6FF-DR9.js → RightSidebarHomePanel-nn0dqUF0.js} +1 -1
- package/dist/web/assets/{ScheduledWorkPage-BTX3Sjoa.js → ScheduledWorkPage-idJ8AO15.js} +1 -1
- package/dist/web/assets/{SettingsView-gAhNO4Rg.js → SettingsView-ZH2gDC6E.js} +3 -3
- package/dist/web/assets/{TeamChatView-DZtfZ12z.js → TeamChatView-B5cG9M6w.js} +1 -1
- package/dist/web/assets/{TerminalOverlay-MJqx0xg6.js → TerminalOverlay-9SPRce9W.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-ORoKcc3m.js → TrainingCreationPanel-2dkxe7py.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-oolNVDIx.js → TrainingDraftPanel-oYbOFapi.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-Lh_fLOcC.js → UsageSettingsSection-zWs4Z_9b.js} +1 -1
- package/dist/web/assets/{WorkSidebarPanel-BIqP9SXr.js → WorkSidebarPanel-CiBQztz6.js} +1 -1
- package/dist/web/assets/{WorkspaceDiffPanel-B0Zwyx9a.js → WorkspaceDiffPanel-BPt29A2a.js} +3 -3
- package/dist/web/assets/{WorkspaceEnvironmentMenu-BpgvG43X.js → WorkspaceEnvironmentMenu-pb6fs4-2.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-Bw5ADFuc.js → WorkspaceGitDialogs-DHD-L4Vs.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-BpivuGzo.js → WorkspaceMonacoEditor-BxtCNaRo.js} +3 -3
- package/dist/web/assets/{arrow-up-right-BjC4ygxR.js → arrow-up-right-DcP3EZaY.js} +1 -1
- package/dist/web/assets/{clipboard-BOJ-sNJz.js → clipboard-BXulVWTJ.js} +1 -1
- package/dist/web/assets/{cloud-upload-D-_3UWhI.js → cloud-upload-B3hP6o0H.js} +1 -1
- package/dist/web/assets/{cssMode-CnHRib-_.js → cssMode-c85YG3Pd.js} +1 -1
- package/dist/web/assets/{folder-open-CO3Vz0rT.js → folder-open-CtOXE4jL.js} +1 -1
- package/dist/web/assets/{folder-plus-CL6B10XJ.js → folder-plus-KO96VZiR.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-C_SNHoOD.js → git-commit-horizontal-Bhtev2bN.js} +1 -1
- package/dist/web/assets/{htmlMode-DBpIV7Gx.js → htmlMode-BbCawv2y.js} +1 -1
- package/dist/web/assets/{index-Dx0lr1R3.js → index-Hynq87d2.js} +2 -2
- package/dist/web/assets/{info-C1C3X2vW.js → info-Dqf1UVHA.js} +1 -1
- package/dist/web/assets/{jsonMode-B9puI-La.js → jsonMode-CFycP8DE.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-DwPRvLkn.js → lspLanguageFeatures-CYX4VXe2.js} +1 -1
- package/dist/web/assets/{minimize-2-Cr76Lc_J.js → minimize-2-BCmNskf_.js} +1 -1
- package/dist/web/assets/{monaco.contribution-DKa3PSXH.js → monaco.contribution-3ZJbmsu3.js} +2 -2
- package/dist/web/assets/{monaco.contribution-OemObo_b.js → monaco.contribution-CJYgsAyM.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CnlZLXhW.js → monaco.contribution-CPkt_0fd.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DQxsY08y.js → monaco.contribution-DR_TcZx7.js} +2 -2
- package/dist/web/assets/{monitor-CktBkAZk.js → monitor-DWlfguJj.js} +1 -1
- package/dist/web/assets/{python-CVC74_7Q.js → python-rAXzgbqp.js} +1 -1
- package/dist/web/assets/{refresh-cw-JaxiGpHD.js → refresh-cw-BUPgzu5R.js} +1 -1
- package/dist/web/assets/{save-DFm1K29k.js → save-Mb-ECgFZ.js} +1 -1
- package/dist/web/assets/{square-D5fFhDFt.js → square-CxNbsHso.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-D_EkCruq.js → toggleHighContrast-DUvtEJ40.js} +1 -1
- package/dist/web/assets/{tsMode-BczIS4rA.js → tsMode-IPAavolh.js} +1 -1
- package/dist/web/assets/{upload-DvED7nbd.js → upload-Bn6_UQEa.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-DWd5OvYb.js → useLocalAgentSchedules-DAHspLJg.js} +1 -1
- package/dist/web/assets/{useSessionTurnCache-oMoxBcGj.js → useSessionTurnCache-CUiJuUjd.js} +1 -1
- package/dist/web/assets/{wifi-off-BZL-Op_B.js → wifi-off-Bsy0Wjm8.js} +1 -1
- package/dist/web/assets/{workers-DapCJCaQ.js → workers-35o3qFXU.js} +1 -1
- package/dist/web/assets/{yaml-DB9KLqu1.js → yaml-Ba5fmKgb.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunks/app-server-runtime-256UCS6N.js +0 -2
- package/dist/chunks/chunk-4476RDBS.js +0 -41
- package/dist/chunks/chunk-L2UT3YIF.js +0 -5
- package/dist/chunks/chunk-L54LZUGH.js +0 -2
- package/dist/chunks/chunk-PSZKG3E3.js +0 -4
- package/dist/chunks/chunk-PZ6KPMEZ.js +0 -2992
- package/dist/chunks/cli-DSFTE4KT.js +0 -2
- package/dist/web/assets/App-BcbjzSeU.js +0 -226
- package/dist/web/assets/HostedModelLearningReview-DYFjp-96.js +0 -1
package/dist/web/assets/{useLocalAgentSchedules-DWd5OvYb.js → useLocalAgentSchedules-DAHspLJg.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as v,w as s}from"./App-
|
|
1
|
+
import{c as v,w as s}from"./App-BKY1b22z.js";import{r as c}from"./index-Hynq87d2.js";const m=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],x=v("rotate-ccw",m),I=5e3;function C(t){const[S,n]=c.useState([]),[y,r]=c.useState(!1),[w,l]=c.useState(null),[o,p]=c.useState(()=>new Set);c.useEffect(()=>{if(!t){n([]),l(null),r(!1);return}const e=t;let a=!1;async function d(g){if(!a){g&&r(!0);try{const h=await s.localAgentSchedules(e);if(a)return;n(h.schedules),l(null)}catch(h){a||l(f(h))}finally{!a&&g&&r(!1)}}}d(!0);const u=window.setInterval(()=>{d(!1)},I);return()=>{a=!0,window.clearInterval(u)}},[t]);async function L(){if(t){r(!0);try{const e=await s.syncLocalAgentSchedules(t);n(e.schedules),l(null)}catch(e){l(f(e))}finally{r(!1)}}}async function A(e){if(!(!t||o.has(e.id))){i(e.id,!0);try{await s.runLocalAgentSchedule(t,e.id);const a=await s.localAgentSchedules(t);n(a.schedules),l(null)}catch(a){l(f(a))}finally{i(e.id,!1)}}}async function E(e){if(!(!t||o.has(e.id))){i(e.id,!0);try{await s.patchLocalAgentSchedule(t,e.id,{enabled:!e.enabled});const a=await s.localAgentSchedules(t);n(a.schedules),l(null)}catch(a){l(f(a))}finally{i(e.id,!1)}}}function i(e,a){p(d=>{const u=new Set(d);return a?u.add(e):u.delete(e),u})}return{error:w,loading:y,pendingScheduleIds:o,refresh:L,run:A,schedules:S,toggle:E}}function f(t){return t instanceof Error?t.message:String(t)}export{x as R,C as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as f}from"./index-
|
|
1
|
+
import{r as f}from"./index-Hynq87d2.js";import{w as C}from"./App-BKY1b22z.js";function S(n,e,t){return new Set(n.filter(i=>{if(e.has(i.id))return!1;if(t===void 0)return!0;if(typeof i.timestamp!="string")return!1;const a=Date.parse(i.timestamp);return Number.isFinite(a)&&a>=t}).map(i=>i.id))}function h(n){let e=null;for(const t of n){if(typeof t.timestamp!="string")continue;const i=Date.parse(t.timestamp);Number.isFinite(i)&&(e=e===null?i:Math.max(e,i))}return e}function E(n,e){const t=f.useRef({scopeKey:e,ids:new Set(n.map(r=>r.id)),initialized:!1,liveCutoff:null}),i=t.current.scopeKey===e,d=i&&t.current.initialized?S(n,t.current.ids,t.current.liveCutoff??void 0):new Set;return f.useLayoutEffect(()=>{const r=t.current,s=r.scopeKey!==e,u=Date.now();t.current={scopeKey:e,ids:new Set(n.map(l=>l.id)),initialized:!s,liveCutoff:s?Math.max(u,h(n)??0):r.liveCutoff??Math.max(u,h(n)??0)}},[n,i,e]),d}const v=new Map,M=[200,600,1500];function x({connection:n,latestTurnId:e,sessionId:t,turnRunning:i}){const[a,d]=f.useState(()=>({sessionId:null,summaries:v}));return f.useEffect(()=>{if(!n||!t)return;let r=!1,s=null;const u=i?null:e,l=o=>{const c=M[o];c===void 0||r||(s=setTimeout(()=>{m(o+1)},c))},m=async o=>{try{const c=await C.usageTurnCache(n,t);if(r)return;const p=new Map(c.turns.map(w=>[w.turnId,w]));d({sessionId:t,summaries:p}),u&&!p.has(u)&&l(o)}catch{l(o)}};return m(0),()=>{r=!0,s!==null&&clearTimeout(s)}},[n,e,t,i]),a.sessionId===t?a.summaries:v}export{x as a,E as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as a}from"./App-
|
|
1
|
+
import{c as a}from"./App-BKY1b22z.js";const e=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],y=a("bell",e);const t=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],c=a("bell-off",t);const o=[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]],k=a("scroll-text",o);const h=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],p=a("wifi-off",h);export{c as B,k as S,p as W,y as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j7 as c}from"./WorkspaceMonacoEditor-
|
|
1
|
+
import{j7 as c}from"./WorkspaceMonacoEditor-BxtCNaRo.js";import"./toggleHighContrast-DUvtEJ40.js";function a(e,o){const r=globalThis.MonacoEnvironment;if(r?.createTrustedTypesPolicy)try{return r.createTrustedTypesPolicy(e,o)}catch(t){console.error(t);return}try{return globalThis.trustedTypes?.createPolicy(e,o)}catch(t){console.error(t);return}}let n;typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope"&&globalThis.workerttPolicy!==void 0?n=globalThis.workerttPolicy:n=a("defaultWorkerFactory",{createScriptURL:e=>e});function l(e){const o=e.label,r=globalThis.MonacoEnvironment;if(r){if(typeof r.getWorker=="function")return r.getWorker("workerMain.js",o);if(typeof r.getWorkerUrl=="function"){const t=r.getWorkerUrl("workerMain.js",o);return new Worker(n?n.createScriptURL(t):t,{name:o,type:"module"})}}if(e.createWorker)return e.createWorker();throw new Error("You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker")}function u(e){const o=Promise.resolve(l({label:e.label??"monaco-editor-worker",moduleId:e.moduleId,createWorker:e.createWorker})).then(r=>(r.postMessage("ignore"),r.postMessage(e.createData),r));return c.createWebWorker({worker:o,host:e.host,keepIdleModels:e.keepIdleModels})}export{u as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as e}from"./WorkspaceMonacoEditor-
|
|
1
|
+
import{l as e}from"./WorkspaceMonacoEditor-BxtCNaRo.js";import"./toggleHighContrast-DUvtEJ40.js";import"./index-Hynq87d2.js";const r={comments:{lineComment:"#"},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],folding:{offSide:!0},onEnterRules:[{beforeText:/:\s*$/,action:{indentAction:e.IndentAction.Indent}}]},l={tokenPostfix:".yaml",brackets:[{token:"delimiter.bracket",open:"{",close:"}"},{token:"delimiter.square",open:"[",close:"]"}],keywords:["true","True","TRUE","false","False","FALSE","null","Null","Null","~"],numberInteger:/(?:0|[+-]?[0-9]+)/,numberFloat:/(?:0|[+-]?[0-9]+)(?:\.[0-9]+)?(?:e[-+][1-9][0-9]*)?/,numberOctal:/0o[0-7]+/,numberHex:/0x[0-9a-fA-F]+/,numberInfinity:/[+-]?\.(?:inf|Inf|INF)/,numberNaN:/\.(?:nan|Nan|NAN)/,numberDate:/\d{4}-\d\d-\d\d([Tt ]\d\d:\d\d:\d\d(\.\d+)?(( ?[+-]\d\d?(:\d\d)?)|Z)?)?/,escapes:/\\(?:[btnfr\\"']|[0-7][0-7]?|[0-3][0-7]{2})/,tokenizer:{root:[{include:"@whitespace"},{include:"@comment"},[/%[^ ]+.*$/,"meta.directive"],[/---/,"operators.directivesEnd"],[/\.{3}/,"operators.documentEnd"],[/[-?:](?= )/,"operators"],{include:"@anchor"},{include:"@tagHandle"},{include:"@flowCollections"},{include:"@blockStyle"},[/@numberInteger(?![ \t]*\S+)/,"number"],[/@numberFloat(?![ \t]*\S+)/,"number.float"],[/@numberOctal(?![ \t]*\S+)/,"number.octal"],[/@numberHex(?![ \t]*\S+)/,"number.hex"],[/@numberInfinity(?![ \t]*\S+)/,"number.infinity"],[/@numberNaN(?![ \t]*\S+)/,"number.nan"],[/@numberDate(?![ \t]*\S+)/,"number.date"],[/(".*?"|'.*?'|[^#'"]*?)([ \t]*)(:)( |$)/,["type","white","operators","white"]],{include:"@flowScalars"},[/.+?(?=(\s+#|$))/,{cases:{"@keywords":"keyword","@default":"string"}}]],object:[{include:"@whitespace"},{include:"@comment"},[/\}/,"@brackets","@pop"],[/,/,"delimiter.comma"],[/:(?= )/,"operators"],[/(?:".*?"|'.*?'|[^,\{\[]+?)(?=: )/,"type"],{include:"@flowCollections"},{include:"@flowScalars"},{include:"@tagHandle"},{include:"@anchor"},{include:"@flowNumber"},[/[^\},]+/,{cases:{"@keywords":"keyword","@default":"string"}}]],array:[{include:"@whitespace"},{include:"@comment"},[/\]/,"@brackets","@pop"],[/,/,"delimiter.comma"],{include:"@flowCollections"},{include:"@flowScalars"},{include:"@tagHandle"},{include:"@anchor"},{include:"@flowNumber"},[/[^\],]+/,{cases:{"@keywords":"keyword","@default":"string"}}]],multiString:[[/^( +).+$/,"string","@multiStringContinued.$1"]],multiStringContinued:[[/^( *).+$/,{cases:{"$1==$S2":"string","@default":{token:"@rematch",next:"@popall"}}}]],whitespace:[[/[ \t\r\n]+/,"white"]],comment:[[/#.*$/,"comment"]],flowCollections:[[/\[/,"@brackets","@array"],[/\{/,"@brackets","@object"]],flowScalars:[[/"([^"\\]|\\.)*$/,"string.invalid"],[/'([^'\\]|\\.)*$/,"string.invalid"],[/'[^']*'/,"string"],[/"/,"string","@doubleQuotedString"]],doubleQuotedString:[[/[^\\"]+/,"string"],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/"/,"string","@pop"]],blockStyle:[[/[>|][0-9]*[+-]?$/,"operators","@multiString"]],flowNumber:[[/@numberInteger(?=[ \t]*[,\]\}])/,"number"],[/@numberFloat(?=[ \t]*[,\]\}])/,"number.float"],[/@numberOctal(?=[ \t]*[,\]\}])/,"number.octal"],[/@numberHex(?=[ \t]*[,\]\}])/,"number.hex"],[/@numberInfinity(?=[ \t]*[,\]\}])/,"number.infinity"],[/@numberNaN(?=[ \t]*[,\]\}])/,"number.nan"],[/@numberDate(?=[ \t]*[,\]\}])/,"number.date"]],tagHandle:[[/\![^ ]*/,"tag"]],anchor:[[/[&*][^ ]+/,"namespace"]]}};export{r as conf,l as language};
|
package/dist/web/index.html
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
<link rel="icon" type="image/png" sizes="16x16" href="./favicon-16x16.png" />
|
|
8
8
|
<link rel="apple-touch-icon" href="./openpond-icon.png" />
|
|
9
9
|
<title>OpenPond App</title>
|
|
10
|
-
<script type="module" crossorigin src="./assets/index-
|
|
10
|
+
<script type="module" crossorigin src="./assets/index-Hynq87d2.js"></script>
|
|
11
11
|
<link rel="stylesheet" crossorigin href="./assets/index-lqk3IxE0.css">
|
|
12
12
|
</head>
|
|
13
13
|
<body>
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{qd as c,rd as d}from"./chunk-PZ6KPMEZ.js";import"./chunk-GCU66EAF.js";import{j as a,x as b}from"./chunk-L2UT3YIF.js";import"./chunk-CE27WEHK.js";import"./chunk-JVIHGSOV.js";import"./chunk-MVAJMRCW.js";import"./chunk-L54LZUGH.js";import"./chunk-L3KS6MOV.js";import"./chunk-XEOEKFG6.js";import"./chunk-55UCBRIX.js";import"./chunk-6MI4KKWF.js";import"./chunk-QTEYV4TW.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 AGENT_PROTOCOL_VERSION,c as APP_SERVER_COMPOSITION,d as createOpenPondAppServer,b as runAppServerJsonl};
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{C as Oe,b as Te,c as Pe,m as h,o as xe,x as X}from"./chunk-L2UT3YIF.js";import{a as Q,b as Ie,h as Re}from"./chunk-CE27WEHK.js";import{i as Ce,o as Ae,q as Ee}from"./chunk-JVIHGSOV.js";import{Aa as C,Ae as ye,Ba as Se,Ea as H,Fa as k,Ga as K,Sa as B,U as q,we as A,ze as F}from"./chunk-MVAJMRCW.js";import{Aa as ae,Ca as ue,Da as le,Ea as ce,Fa as pe,Ha as de,W as O,b as oe,c as ie,gb as me,hb as ge,jb as Y,mb as he,pb as fe,qb as N,ub as ve,wb as we,xb as be}from"./chunk-IFP6W4OW.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as ne,d as U,f as se,h as E}from"./chunk-H7IWJN7L.js";import{a as u}from"./chunk-FTQLQJQV.js";import{promises as ee}from"node:fs";import ut from"node:os";import lt from"node:path";import{createServer as ct}from"node:http";import{randomBytes as pt}from"node:crypto";var tt=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)})]),rt=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(tt).max(100)}),o.strictObject({action:o.literal("replace"),expectedRevision:o.string(),text:o.string().max(1048576)}),o.strictObject({action:o.literal("validate"),text:o.string().max(1048576)}),o.strictObject({action:o.literal("restore"),expectedRevision:o.string(),revision:o.string()}),o.strictObject({action:o.literal("trust"),root:o.string(),accountId:o.string(),trusted:o.boolean()}),o.strictObject({action:o.literal("client-state"),owner:o.string(),patch:ve,importOnly:o.boolean().optional()})]);function ke(n){let e=null;async function t(s,i){let a=E(n).config,c=null,p=null,d=null;try{c=await ie(a),d=await N(n,{projectRoot:s,accountId:i}),s||(e=d)}catch(w){p=U(w,a)}let f=d??(s?null:e);return{path:a,text:c,rawRevision:oe(c),issue:p,effective:f,usingLastValid:!d&&!!f,applies:"next_turn",recoverableRevisions:await ue(n),clientState:p?null:await we(n)}}u(t,"status");async function r(s){let i=rt.parse(s);return i.action==="validate"?{valid:!0,document:ae(i.text,E(n).config)}:(i.action==="patch"&&await de(n,i.expectedRevision,i.operations),i.action==="replace"&&await le(n,i.expectedRevision,i.text),i.action==="restore"&&await ce(n,i.revision,i.expectedRevision),i.action==="trust"&&await fe(n,i.root,i.accountId,i.trusted),i.action==="client-state"?be(n,i.owner,i.patch,i.importOnly):t())}return u(r,"mutate"),{status:t,mutate:r,schema:pe}}u(ke,"createConfigurationPayloads");import{Buffer as _e}from"node:buffer";var j={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},nt=25*1024*1024,M=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{u(this,"HttpBodyError")}};function He(n,e,t={}){for(let[s,i]of Object.entries(j))e.setHeader(s,i);let r=Ne(n.headers.origin);return r?(e.setHeader("Vary",at(e.getHeader("Vary"))),st(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}u(He,"applyCorsHeaders");function st(n,e={}){if(n==="null")return!0;let t=Ue(n);return t?it(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Ue(s):null).filter(s=>!!s)).has(t):!1}u(st,"isAllowedCorsOrigin");function y(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...j}),n.end(JSON.stringify(t))}u(y,"sendJson");function $t(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...j}),n.end(t)}u($t,"sendText");function Wt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...j}),n.end(t)}u(Wt,"sendBinary");async function Z(n,e={}){let t=e.maxBytes??nt,r=Ne(n.headers["content-type"]),s=[],i=0;for await(let c of n){let p=_e.from(c);if(i+=p.byteLength,i>t)throw new M(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(p)}let a=_e.concat(s).toString("utf8").trim();if(!a)return{};if(!ot(r))throw new M(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(a)}catch{throw new M(400,"invalid_json","Request body is not valid JSON.")}}u(Z,"readJson");function Me(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}u(Me,"hasAuth");function Ne(n){return Array.isArray(n)?n[0]??null:n??null}u(Ne,"headerValue");function ot(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}u(ot,"isJsonContentType");function Ue(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}u(Ue,"normalizeOrigin");function it(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}u(it,"isLoopbackOrigin");function at(n){let t=(Array.isArray(n)?n.join(", "):n?String(n):"").split(",").map(r=>r.trim()).filter(Boolean);return t.some(r=>r.toLowerCase()==="origin")||t.push("Origin"),t.join(", ")}u(at,"appendVaryOrigin");function qe(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>`}u(qe,"startupRecoveryPage");var dt=o.strictObject({action:o.enum(["preview","migrate","restart","retry"]),sourceAppHome:o.string().optional(),sourceConfig:o.string().optional(),resolutions:me.optional()});function Be(n){return n instanceof ne&&/^(PRIVATE_STORAGE_|UNSAFE_STORAGE_|INVALID_CONFIG|CONFIG_|MIGRATION_|SOURCE_CHANGED_|CREDENTIAL_|UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|INVALID_ACCOUNT_|MISSING_INSTRUCTION_|INVALID_PROFILE_|DATABASE_RECOVERY_)/.test(n.issue.code)}u(Be,"isRecoverableStartupError");async function Fe(n,e,t){let r=/^(UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|UNSAFE_STORAGE_|PRIVATE_STORAGE_)/.test(t.issue.code),s=r?await ee.mkdtemp(lt.join(ut.tmpdir(),"openpond-recovery-")):n;return Te(s,async()=>{let{token:i,tokenFile:a}=await Oe(s),c=ke(n),p=t.issue,d,f=new Promise(v=>{d=v}),w=ct((v,m)=>{(async()=>{let b=new URL(v.url??"/","http://127.0.0.1");if(!He(v,m).allowed){y(m,403,{error:"Origin not allowed"});return}if(v.method==="OPTIONS"){y(m,204,{});return}if(v.method==="GET"&&b.pathname==="/health"){y(m,200,{ok:!0,server:"openpond-app-server",version:Ie,recovery:!0});return}if(v.method==="GET"&&b.pathname==="/"){let l=pt(18).toString("base64");m.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${l}'; style-src 'nonce-${l}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`}),m.end(qe(l));return}if(!Me(v,b,i)){y(m,401,{error:"Unauthorized"});return}let g=!r;if(v.method==="GET"&&b.pathname==="/v1/recovery"){y(m,200,{issue:p,configEditable:g,config:r?{path:E(n).config,text:null,rawRevision:"unavailable",issue:p,recoverableRevisions:[]}:await c.status(),migration:await ge(n).catch(l=>({issue:U(l,n)}))});return}if(v.method==="POST"&&b.pathname==="/v1/configuration"&&g){y(m,200,await c.mutate(await Z(v)));return}if(v.method==="POST"&&b.pathname==="/v1/recovery"){let l=dt.parse(await Z(v));if(r&&l.action!=="retry"&&l.action!=="preview")throw t;if(l.action==="restart"){y(m,200,await he(n));return}if(l.action==="preview"||l.action==="migrate"){y(m,200,await Y(n,{sourceAppHome:l.sourceAppHome,sourceConfig:l.sourceConfig,resolutions:l.resolutions,dryRun:l.action==="preview"}));return}await Y(n),await N(n),y(m,200,{ready:!0}),d();return}y(m,503,{error:`${p.message} ${p.action}`,issue:p,recovery:!0})})().catch(b=>{p=U(b,n),y(m,422,{error:`${p.message} ${p.action}`,issue:p})})});await new Promise((v,m)=>{w.once("error",m),w.listen(e,"127.0.0.1",()=>{w.off("error",m),v()})});let T=w.address().port,x=`http://127.0.0.1:${T}`;return await Pe(s,x,"startup-recovery"),{url:x,port:T,token:i,tokenFile:a,storePath:E(n).database,repaired:f,close:u(async()=>{w.closeIdleConnections(),await new Promise((v,m)=>w.close(b=>b?m(b):v())),r&&await ee.rm(s,{recursive:!0,force:!0})},"close")}}).catch(async i=>{throw r&&await ee.rm(s,{recursive:!0,force:!0}),i})}u(Fe,"startRecoveryServer");import{createHash as kt}from"node:crypto";import{createHash as mt,randomUUID as te}from"node:crypto";var je=o.object({approval:K,revision:o.number().int().positive()}).strict(),Le=o.object({record:B}).strict(),gt=o.object({startedAt:o.string().min(1),requestOrdinal:o.number().int().nonnegative(),id:o.string().min(1)}).strict(),ht=o.object({records:o.array(B).max(200),nextBefore:gt.nullable()}).strict(),Ve=1e4,L=class{constructor(e){this.client=e}client;static{u(this,"HostedApprovalStorage")}async readApproval(e){let t=await this.client.request({contractVersion:h,requestId:te(),operation:"approval/get",params:{approvalId:e}});return t===null?null:je.parse(t)}async getApproval(e){return(await this.readApproval(e))?.approval??null}async putApproval(e){let t=K.parse(e.approval);if(!e.requestId.trim())throw new Error("Approval mutation requires a stable request ID.");return je.parse(await this.client.request({contractVersion:h,requestId:e.requestId,operation:"approval/upsert",params:{approval:t,expectedRevision:e.expectedRevision}}))}},V=class{constructor(e){this.client=e}client;static{u(this,"HostedModelUsageStorage")}async upsertModelUsageRecord(e){let t=B.parse(e),r=mt("sha256").update(JSON.stringify(t)).digest("hex"),s=await this.client.request({contractVersion:h,requestId:`usage:${r}`,operation:"usage/upsert",params:{record:t}}),i=Le.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:h,requestId:te(),operation:"usage/getByRequestId",params:{requestId:e}});return t===null?null:Le.parse(t).record}async listModelUsageRecords(e={}){let t=e.limit===void 0||e.limit>=Ve,r=e.limit===void 0?Ve: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=[],a=null;for(;i.length<r+(t?1:0);){let c=ht.parse(await this.client.request({contractVersion:h,requestId:te(),operation:"usage/page",params:{query:s,before:a,limit:Math.min(200,r+(t?1:0)-i.length)}}));if(i.push(...c.records),i.length>r)throw new Error(`Hosted usage query exceeds ${r} rows; narrow its filters or use a streamed aggregation.`);if(c.nextBefore===null)break;if(c.records.length===0||JSON.stringify(c.nextBefore)===JSON.stringify(a))throw new Error("Host usage cursor did not advance.");a=c.nextBefore}return i}async listModelUsageRecordsComplete(e={}){return this.listModelUsageRecords(e)}};import{createHash as ft,randomUUID as De}from"node:crypto";var vt=o.object({updatedAt:o.string(),id:o.string().min(1)}).strict(),wt=o.object({entries:o.array(C).max(200),nextBefore:vt.nullable()}).strict(),bt=o.object({run:C,replayed:o.boolean()}).strict(),D=class{constructor(e){this.client=e}client;static{u(this,"HostedCreateImproveStorage")}async getCreateImproveRun(e){let t=await this.client.request({contractVersion:h,requestId:De(),operation:"create-improve/execute",params:{action:"get",runId:e}});return t===null?null:C.parse(t)}async listCreateImproveRuns(e={}){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250))),r=Array.isArray(e.state)?[...e.state]:e.state?[e.state]:[],s=[],i=null;for(;s.length<t;){let a=wt.parse(await this.client.request({contractVersion:h,requestId:De(),operation:"create-improve/execute",params:{action:"page",query:{profileId:e.profileId??null,targetKind:e.targetKind??null,targetId:e.targetId??null,state:r},before:i,limit:Math.min(50,t-s.length)}}));if(e.conversationId&&a.entries.some(c=>c.scope.conversationId!==e.conversationId))throw new Error("Hosted Create/Improve page crossed its conversation scope.");if(s.push(...a.entries),!a.nextBefore)break;if(a.entries.length===0||i&&(a.nextBefore.updatedAt>i.updatedAt||a.nextBefore.updatedAt===i.updatedAt&&a.nextBefore.id>=i.id))throw new Error("Hosted Create/Improve cursor did not advance.");i=a.nextBefore}return s}async upsertCreateImproveRun(e){let t=C.parse(e),r=`create-improve:${ft("sha256").update(JSON.stringify(t)).digest("hex")}`,s=await this.client.request({contractVersion:h,requestId:r,operation:"create-improve/execute",params:{action:"put",run:t}});return C.parse(o.object({run:o.unknown()}).strict().parse(s).run)}async mutateCreateImproveRun(e,t){let r=Se.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=C.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 bt.parse(await this.client.request({contractVersion:h,requestId:r.actionId,operation:"create-improve/execute",params:{action:"mutate",mutation:r,next:i}}))}};import{randomUUID as St}from"node:crypto";var yt=o.object({entries:o.array(o.object({sequence:o.number().int().positive(),event:q})).max(200),totalMatchingEvents:o.number().int().nonnegative(),remainingMatchingEvents:o.number().int().nonnegative()}).strict(),$=class{constructor(e){this.client=e}client;static{u(this,"HostedRuntimeEventStorage")}async runtimeEventsForSession(e,t={}){let r=t.limit==null?1e4:Math.max(0,Math.trunc(t.limit));if(r===0)return[];let s=Math.min(r,1e4),i=[],a=Math.max(0,t.afterSequence??0),c=0,p=t.names?new Set(t.names):null;for(;i.length<=s;){let d=await this.runtimeEventPageRows({sessionId:e,afterSequence:a,beforeSequence:null,limit:Math.min(200,s+1-i.length)});for(let f of d.entries){if(f.sequence<=a)throw new Error("Host event cursor did not advance.");if(a=f.sequence,c+=1,c>1e4)throw new Error("Hosted runtime event scan exceeds 10,000 rows; use a narrower query.");(!p||p.has(f.event.name))&&i.push(f.event)}if(d.entries.length===0||d.remainingMatchingEvents<=d.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=q.parse(e),r=await this.client.request({contractVersion:h,requestId:t.id,operation:"event/append",params:{event:t}});return o.object({event:q}).strict().parse(r).event}async runtimeEventPageRows(e){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit))),r=Math.max(0,Math.trunc(e.afterSequence)),s=e.beforeSequence,i=[],a=0,c=0;for(;i.length<t;){let p=Math.min(200,t-i.length),d=yt.parse(await this.client.request({contractVersion:h,requestId:`event-page:${St()}`,operation:"events/page",params:{sessionId:e.sessionId,afterSequence:r,beforeSequence:s,limit:p}}));if(i.length===0&&(a=d.totalMatchingEvents,c=d.remainingMatchingEvents),i=s===null?[...i,...d.entries]:[...d.entries,...i],d.entries.length<p||d.entries.length===0)break;if(s===null){let f=d.entries.at(-1).sequence;if(f<=r)throw new Error("Host event cursor did not advance.");r=f}else{let f=d.entries[0].sequence;if(f>=s)throw new Error("Host event cursor did not advance.");s=f}}return{entries:i,totalMatchingEvents:a,remainingMatchingEvents:c}}};import{randomUUID as S}from"node:crypto";var $e=o.object({revision:o.number().int().min(1),session:H}).strict(),We=o.object({revision:o.number().int().min(1),turn:k}).strict(),It=o.object({sessions:o.array(H).max(200),nextAfterId:o.string().min(1).nullable()}).strict(),Rt=o.object({turns:o.array(k).max(200),nextBeforeSortIndex:o.number().int().nonnegative().nullable()}).strict(),W=class{constructor(e){this.client=e}client;static{u(this,"HostedSessionStorage")}async count(){let e=await this.client.request({contractVersion:h,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:h,requestId:S(),operation:"session/get",params:{sessionId:e}});return t===null?null:$e.parse(t)}async sessionCount(){return this.count()}async sessionShells(){let e=[],t=null;do{let r=It.parse(await this.client.request({contractVersion:h,requestId:S(),operation:"session/page",params:{afterId:t,limit:Math.min(10,1001-e.length)}}));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=H.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=H.parse(e.session);return $e.parse(await this.client.request({contractVersion:h,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:h,requestId:S(),operation:"turn/get",params:{turnId:e}});return t===null?null:We.parse(t)}async getTurn(e){return(await this.readTurn(e))?.turn??null}async turnsForSession(e,t=50){let r=Math.max(1,Math.min(1e3,Math.trunc(t))),s=[],i=null;for(;s.length<r;){let a=Rt.parse(await this.client.request({contractVersion:h,requestId:S(),operation:"turn/page",params:{sessionId:e,beforeSortIndex:i,limit:Math.min(200,r-s.length)}}));if(s.push(...a.turns),a.nextBeforeSortIndex===null)break;if(i!==null&&a.nextBeforeSortIndex>=i)throw new Error("Host turn cursor did not advance.");i=a.nextBeforeSortIndex}return s}async countTurnsForSession(e){let t=await this.client.request({contractVersion:h,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:h,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:h,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:h,requestId:S(),operation:"turn/latest",params:{sessionId:e,status:t??null}});return r===null?null:k.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=k.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=k.parse(e.turn);return We.parse(await this.client.request({contractVersion:h,requestId:e.requestId,operation:"turn/put",params:{sessionId:t.sessionId,turnId:t.id,expectedRevision:e.expectedRevision,turn:t}}))}};import{createHash as Tt,randomUUID as Pt}from"node:crypto";var P=o.object({ok:o.literal(!0)}).strict(),G=o.array(A),xt=o.array(o.string()),Ct=o.object({turnId:o.string(),run:O}).strict(),At=o.object({inputs:o.array(A).max(10),hasMore:o.boolean()}).strict(),Et=o.object({items:o.array(F).max(10),hasMore:o.boolean()}).strict(),Ot=o.object({items:o.array(o.string()).max(200),hasMore:o.boolean()}).strict();function J(n,e){return`inbox:${n}:${Tt("sha256").update(JSON.stringify(e)).digest("hex")}`}u(J,"retryKey");var _=class{constructor(e){this.client=e}client;static{u(this,"HostedTaskInboxStorage")}async call(e,t,r=Pt()){let s=await this.client.request({contractVersion:h,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),At);for(let a of i.inputs){if(a.sequence<=s)throw new Error("Host task input cursor did not advance.");if(s=a.sequence,r.push(a),r.length>=t)break}if(!i.hasMore)return r;if(i.inputs.length===0)throw new Error("Host task input page made no progress.")}return r}async recoverTaskInboxOwners(e){return this.call({action:"recoverTaskInboxOwners",ownerId:e},o.array(o.object({sessionId:o.string(),turnId:o.string()}).strict()))}async hasTaskCompletion(e){return this.call({action:"hasTaskCompletion",turnId:e},o.boolean())}async taskInboxSnapshot(e){let t=await this.call({action:"taskInboxSnapshot",sessionId:e},ye),[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},xt)}async admitTaskInput(e){return this.call({action:"admitTaskInput",input:e},A)}async admitTaskInputs(e){return this.call({action:"admitTaskInputs",inputs:e},G)}async rejectTaskInput(e,t){await this.call({action:"rejectTaskInput",id:e,error:t},P)}async getTaskInput(e){return this.call({action:"getTaskInput",id:e},A.nullable())}async taskInputsForSession(e,t={}){let r=Math.max(1,Math.min(500,t.limit??128)),s=[],i=t.afterSequence??0;for(;s.length<r;){let a=Math.min(10,r-s.length),c=await this.call({action:"taskInputsForSession",sessionId:e,query:{afterSequence:i,pendingOnly:t.pendingOnly,limit:a}},G);if(!c.length)break;for(let p of c){if(p.sequence<=i)throw new Error("Host task input cursor did not advance.");i=p.sequence,s.push(p)}if(c.length<a)break}return s}async mutateTaskInput(e,t,r){return this.call({action:"mutateTaskInput",sessionId:e,inputId:t,change:r},A,J("mutate",{sessionId:e,inputId:t,change:r}))}async openTaskInboxTurn(e,t,r){await this.call({action:"openTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},P,J("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},G,J("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},G)}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},A.nullable(),J("reserve",{sessionId:e,turnId:t,ownerId:r}))}async taskInboxWakeTargets(){let e=[],t="";for(;;){let r=await this.call({action:"taskInboxWakeTargets",afterSessionId:t},Ot);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},F)}async settleTaskWait(e,t){return this.call({action:"settleTaskWait",id:e,state:t},F)}async taskWaitsForSession(e){let t=[],r="";for(;;){let s=await this.call({action:"taskWaitsForSession",sessionId:e,afterId:r},Et);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(Ct).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:O.parse(e)},O)}async getSubagentRun(e){return this.call({action:"getSubagentRun",id:e},O.nullable())}async listSubagentRuns(e={}){let r=[],s="",i=e.status?Array.isArray(e.status)?[...e.status]:[e.status]:null;for(;;){let a=await this.call({action:"listSubagentRuns",query:{parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,status:i,afterId:s,limit:10}},o.array(O).max(10));for(let c of a){if(c.id<=s)throw new Error("Host subagent run cursor did not advance.");if(s=c.id,r.push(c),r.length>1e3)throw new Error("Hosted subagent run list exceeds 1,000 rows; use a narrower session or status query.")}if(a.length<10)break}return r.sort((a,c)=>(c.updatedAt??c.createdAt).localeCompare(a.updatedAt??a.createdAt)),e.limit===void 0?r:r.slice(0,Math.max(1,Math.min(1e3,e.limit)))}async listActiveSubagentRuns(e={}){return this.listSubagentRuns({...e,status:e.status??["queued","running","needs_resume"]})}};var re=class extends _{static{u(this,"HostedTurnRepository")}sessions;events;approvals;usage;createImprove;constructor(e){super(e),this.sessions=new W(e),this.events=new $(e),this.approvals=new L(e),this.usage=new V(e),this.createImprove=new D(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:${kt("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 Ge(n){return new re(n)}u(Ge,"createHostedRuntimeCoreStorage");function Je(n=process.env){let e=n.OPENPOND_API_KEY?.trim(),t=n.OPENPOND_OPCHAT_API_URL?.trim(),r=n.OPENPOND_HOSTED_MODEL_ID?.trim();if(!e||!t||!r)throw new Error("Hosted model stream requires a host credential, API URL, and admitted model.");let s=new URL(t);if(s.protocol!=="https:"||s.username||s.password||s.search||s.hash)throw new Error("Hosted model stream API URL is invalid.");return u(async function*(a){if(a.model!==r)throw new Error("Hosted model selection changed outside host admission.");yield*Ce({...a,apiBaseUrl:s.toString(),token:e,model:r})},"streamHostedModel")}u(Je,"createHostedModelStreamFromEnvironment");import{existsSync as _t}from"node:fs";import R from"node:path";import{fileURLToPath as Ut}from"node:url";var ze=R.dirname(Ut(import.meta.url));function I(n,e,t){let r=n[e+1];if(!r||r.startsWith("--"))throw new Error(`${t} requires a value.`);return r}u(I,"requireValue");function Ye(n,e){let t=Number.parseInt(n,10);if(!Number.isFinite(t)||t<0||t>65535)throw new Error(`${e} must be a port from 0 to 65535.`);return t}u(Ye,"parsePort");function Xe(n){let e="serve",t=Q,r=17874,s=null,i=!1,a=!1,c=null,p,d=null,f=null,w=null,T=null,x="sqlite_bundle",v=0,m=n[0];if(m&&!m.startsWith("-")){if(m==="serve"||m==="server")e="serve";else if(m==="app-server")e="app-server";else if(m==="web")e="web";else{if(m==="help")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:c,runtimeStorage:x,help:!0};throw new Error(`Unknown command: ${m}`)}v=1}for(let g=v;g<n.length;g+=1){let l=n[g];if(l==="--help"||l==="-h")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:c,runtimeStorage:x,help:!0};if(l==="--listen"){let z=Re(I(n,g,l));t=z.host,r=Ye(String(z.port),l),g+=1}else if(l==="--hostname"||l==="--host")t=I(n,g,l),g+=1;else if(l==="--port")r=Ye(I(n,g,l),l),g+=1;else if(l==="--web-root")s=R.resolve(I(n,g,l)),g+=1;else if(l==="--source-browser-state")p=R.resolve(I(n,g,l)),g+=1;else{if(l==="--store-dir")throw new Error("--store-dir has been replaced by --home. Use --home <directory> or OPENPOND_HOME.");if(l==="--home")c=R.resolve(I(n,g,l)),g+=1;else if(l==="--runtime-storage"){if(I(n,g,l)!=="hosted-postgres")throw new Error("Unsupported app-server runtime storage.");x="hosted_postgres",g+=1}else if(l==="--profile-source-root")d=R.resolve(I(n,g,l)),g+=1;else if(l==="--profile-repository-id")f=I(n,g,l),g+=1;else if(l==="--profile-id")w=I(n,g,l),g+=1;else if(l==="--profile-revision")T=I(n,g,l),g+=1;else if(l==="--open-browser")i=!0;else if(l==="--print-access-url")a=!0;else throw new Error(`Unknown option: ${l}`)}}if(i&&a)throw new Error("--open-browser and --print-access-url cannot be used together.");if(e!=="web"&&(i||a))throw new Error("Browser options are only available in web mode.");let b=[d,f,w,T].filter(Boolean).length;if(b&&(b!==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(x==="hosted_postgres"&&(e!=="app-server"||c||b))throw new Error("Hosted Postgres app-server cannot use --home or local Profile source flags.");return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:c,runtimeStorage:x,sourceBrowserState:p,...b?{profileSource:{repoPath:d,repositoryId:f,profileId:w,sourceRevision:T}}:{},help:!1}}u(Xe,"parseCliArgs");function Ht(){return[process.env.OPENPOND_WEB_ROOT,R.resolve(process.cwd(),"apps/web/dist"),R.resolve(ze,"../../web/dist"),R.resolve(process.cwd(),"web"),R.resolve(ze,"../web")].filter(n=>!!n)}u(Ht,"defaultWebRootCandidates");function Mt(n){let e=n?[n]:Ht();for(let t of e){let r=R.resolve(t);if(_t(R.join(r,"index.html")))return r}return null}u(Mt,"resolveWebRoot");function Nt(n){let e=n==="0.0.0.0"||n==="::"?"127.0.0.1":n;return e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}u(Nt,"formatHostForUrl");function qt(n){return`http://${Nt(n.status.host)}:${n.status.port}`}u(qt,"browserBaseUrl");function Bt(n,e){let t=new URL(n),r=new URLSearchParams;return r.set("openpondServerUrl",n),r.set("openpondToken",e),t.hash=r.toString(),t.toString()}u(Bt,"tokenizedWebUrl");async function Ke(n,e=Ee){let t=Bt(n.baseUrl,n.token);if(n.printAccessUrl)return{stdout:[`OpenPond access URL: ${t}`],stderr:[]};if(!n.openBrowser)return{stdout:[`OpenPond web UI: ${n.baseUrl}`],stderr:[]};let r=await e(t);return r.opened?{stdout:[`Opened OpenPond in your browser: ${n.baseUrl}`],stderr:[]}:{stdout:[`OpenPond access URL: ${t}`],stderr:[`Could not open the system browser: ${r.error}`]}}u(Ke,"resolveWebLaunchMessages");function Ze(){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 ${Q})
|
|
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
|
-
--profile-source-root DIR Authorized Profile repository source for app-server
|
|
36
|
-
--profile-repository-id ID Source repository identity supplied by the host
|
|
37
|
-
--profile-id ID Profile within that source
|
|
38
|
-
--profile-revision REV Accepted immutable source revision
|
|
39
|
-
--open-browser Open the authenticated web URL in the system browser
|
|
40
|
-
--print-access-url Print the authenticated URL instead of opening it
|
|
41
|
-
`)}u(Ze,"printHelp");async function dn(n){let e=Xe(process.argv.slice(2));if(e.help){Ze();return}let t=e.mode==="web"?Mt(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 et(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(p){if(!Be(p))throw p;let d=await Fe(se({home:e.storeDir??void 0}),s,p);s=d.port,console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:"recovery",url:d.url,tokenFile:d.tokenFile,storePath:d.storePath})}`),console.error(`${p.issue.code}: ${p.issue.message} ${p.issue.action}`);let f=await Ke({baseUrl:d.url,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:d.token});for(let T of f.stdout)console.log(T);for(let T of f.stderr)console.error(T);let w=u(()=>{d.close().finally(()=>process.exit(0))},"close");process.once("SIGINT",w),process.once("SIGTERM",w);try{await d.repaired}finally{process.off("SIGINT",w),process.off("SIGTERM",w),await d.close()}}let i=e.mode==="web"?qt(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:Ae()})}`),i){let p=await Ke({baseUrl:i,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:r.token});for(let d of p.stderr)console.error(d);for(let d of p.stdout)console.log(d)}else console.log(`OpenPond API server: ${r.url}`);let a=!1,c=u(async()=>{a||(a=!0,await r.close(),process.exit(0))},"shutdown");process.on("SIGINT",()=>{c()}),process.on("SIGTERM",()=>{c()}),await new Promise(()=>{})}u(dn,"runOpenPondServerCli");async function mn(n){let e=process.argv.slice(2),t=Xe(!e[0]||e[0].startsWith("-")?["app-server",...e]:e);if(t.help){Ze();return}if(t.mode!=="app-server")throw new Error("The app-server entrypoint only accepts the app-server command.");await et(n,t.storeDir,t.profileSource,t.runtimeStorage)}u(mn,"runOpenPondAppServerCli");async function et(n,e,t,r="sqlite_bundle"){let s=new xe;if(r==="hosted_postgres"){if(e||t)throw new Error("Hosted Postgres app-server cannot use local storage sources.");await X({appServer:u(()=>n({hostStorageClient:s,runtimeStorage:{kind:"hosted_postgres",client:s,core:Ge(s),inbox:new _(s)},streamOpenPondHostedChatTurn:Je()}),"appServer"),readable:process.stdin,writable:process.stdout,hostStorageClient:s});return}e&&(process.env.OPENPOND_HOME=e);let i=await n({...e?{storeDir:e}:{},...t?{profileSource:t}:{},hostStorageClient:s});await X({appServer:i,readable:process.stdin,writable:process.stdout,hostStorageClient:s})}u(et,"runAgentServer");export{ke as a,M as b,He as c,y as d,$t as e,Wt as f,Z as g,Me as h,Ke as i,dn as j,mn as k};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{Bb as Q,c as D,e as C,f as W,g as G,i as K}from"./chunk-IFP6W4OW.js";import{b as e}from"./chunk-ES2ISFJC.js";import{a as A,c as B,f as L,h as g}from"./chunk-H7IWJN7L.js";import{a as o}from"./chunk-FTQLQJQV.js";import R from"node:path";import{AsyncLocalStorage as je}from"node:async_hooks";import{promises as Y}from"node:fs";var X=new je;function Ge(t,r=!1){let a=X.getStore();a&&(r&&(a.length=0),a.push(t))}o(Ge,"onStartupFailure");async function Ke(t,r){await Q(t);let a;try{a=await G(R.join(g(t).runtime,"server-owner"),100)}catch(i){if(i instanceof B&&i.issue.code==="STORAGE_BUSY"){let l=await K(R.join(g(t).runtime,"endpoint.json"),()=>null);throw new B({code:"RUNTIME_ALREADY_RUNNING",path:t,message:"An OpenPond runtime already owns this home.",action:l?.url?`Connect to the existing runtime at ${l.url}, or stop it before starting another.`:"Stop the existing runtime before starting another with this home."})}throw i}let n=[];try{let i=await A(t,()=>X.run(n,r)),l=i.close.bind(i);n.length=0;let d;return{...i,close:o(()=>d??=(async()=>{try{await A(t,l)}finally{await Y.rm(R.join(g(t).runtime,"endpoint.json"),{force:!0}),await a()}})(),"close")}}catch(i){try{for(let l of n.reverse())await Promise.resolve().then(()=>A(t,l)).catch(()=>{});await Y.rm(R.join(g(t).runtime,"endpoint.json"),{force:!0})}finally{await a()}throw i}}o(Ke,"ownHomeRuntime");async function Qe(t,r,a){await C(R.join(g(t).runtime,"endpoint.json"),JSON.stringify({schemaVersion:"openpond.runtimeEndpoint.v1",pid:process.pid,url:r,serverId:a}))}o(Qe,"publishRuntimeEndpoint");function Ze(t){if(!t.maxContextTokens||!t.usableContextTokens)return{shouldCompact:!1,projectedTokens:t.projectedTokens,thresholdTokens:Number.MAX_SAFE_INTEGER,usableContextTokens:0,maxContextTokens:0,tokenSource:"heuristic"};let r=Math.max(.01,Math.min(1,(t.triggerPercent??85)/100)),a=Math.max(1,Math.floor(t.usableContextTokens*r));return{shouldCompact:t.projectedTokens>=a,projectedTokens:t.projectedTokens,thresholdTokens:a,usableContextTokens:t.usableContextTokens,maxContextTokens:t.maxContextTokens,tokenSource:"heuristic"}}o(Ze,"agentCompactionDecision");async function et(t){await t.started();try{return await t.compact()}catch(r){throw await t.failed(r),r}}o(et,"runAgentCompaction");async function tt(t){let r=t.host.projectEvents(t.events),a=t.host.selectEvents(r,t.maxContextTokens),{summaryEvents:n,preservedEvents:i,preservedEventIds:l}=a;if(n.length===0)throw new Error("There is not enough prior context to compact.");let d=t.host.normalizeRecords(n),p=t.host.normalizeRecords(i),f=t.host.buildFileLedger(t.host.normalizeRecords(r)),h=t.host.serializeRecords(d,t.host.inputCharBudget(t.maxContextTokens));if(!h.text.trim())throw new Error("There is not enough prior context to compact.");let q=t.host.buildSummaryMessages({serializedHistory:h.text,fileLedger:f}),S=Date.now(),j=(await t.host.streamSummary({model:t.model,messages:q,signal:t.signal})).trim(),N=Date.now()-S;if(!j)throw new Error("Compaction summary was empty.");let m=t.host.estimateProjection({events:r,preservedEvents:i,summary:j}),b=t.host.createMetrics({sourceEvents:r.length,summarizedEvents:n.length,preservedEvents:i.length,sourceRecords:h.sourceRecordCount,includedRecords:h.includedRecordCount,omittedRecords:h.omittedRecordCount,preservedRecords:p.length,truncatedRecords:h.truncatedRecordCount,summaryInputTruncated:h.inputTruncated,sourceSelectionStrategy:h.selectionStrategy,summaryInputChars:h.inputChars,retainedTailTokens:a.retainedTailTokens,retainedTailBudgetTokens:a.retainedTailBudgetTokens,finalProviderContextTokens:m.inputTokensAfter,durationMs:N,fileLedgerEntries:f.length,splitTurnId:a.splitTurnId});return{summary:j,model:t.model,compactedThroughEventId:r[r.length-1]?.id??null,compactedThroughTurnId:t.host.lastTurnId(r),preservedFromEventId:i[0]?.id??null,preservedEventIds:l,preservedResourceRefs:t.host.durableResourceRefs(t.events),sourceEventCount:n.length,preservedEventCount:i.length,fileLedger:f,inputTokensBefore:m.inputTokensBefore,inputTokensAfter:m.inputTokensAfter,maxContextTokens:t.maxContextTokens,tokenSource:"heuristic",metrics:b}}o(tt,"runAgentCompactionProgram");var _="2026-09-20",it=["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"],ee=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(),te=e.object({jsonrpc:e.literal("2.0"),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),M=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),result:e.unknown()}).strict(),U=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(),st=e.union([ee,te,M,U]),ye=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(),H=class{static{o(this,"AgentJsonRpcDispatcher")}#e;#t=null;#r=!1;constructor(r){this.#e=r}get initialized(){return this.#r}async handle(r){let a=te.safeParse(r);if(a.success&&!("id"in r)){if(a.data.method==="initialized"){if(!this.#t)throw new x(-32002,"initialize must be called first");this.#r=!0}return null}let n=ee.safeParse(r);if(!n.success)return Z(null,-32600,"Invalid Request",n.error.flatten());let i=n.data;try{let l=await this.#n(i.method,i.params);return{jsonrpc:"2.0",id:i.id,result:l}}catch(l){let d=l instanceof x?l:new x(-32603,l instanceof Error?l.message:String(l));return Z(i.id,d.code,d.message,d.data)}}async#n(r,a){if(r==="initialize"){let n=ye.parse(a);if(n.protocolVersion!==_)throw new x(-32001,"Incompatible agent protocol version",{requested:n.protocolVersion,supported:_});return this.#t=n,{protocolVersion:_,server:{name:"openpond-app-server",version:"1"},capabilities:await this.#e.capabilities()}}if(!this.#r)throw new x(-32002,"initialized notification is required");switch(r){case"runtime/capabilities":return this.#e.capabilities(a);case"thread/start":return this.#e.threadStart(a);case"thread/resume":return this.#e.threadResume(a);case"thread/read":return this.#e.threadRead(a);case"turn/start":return this.#e.turnStart(a);case"turn/steer":return this.#e.turnSteer(a);case"task/inbox":return this.#e.taskInbox(a);case"task/queue":return this.#e.taskQueue(a);case"task/inputUpdate":return this.#e.taskInputUpdate(a);case"turn/interrupt":return this.#e.turnInterrupt(a);case"approval/resolve":return this.#e.approvalResolve(a);case"userInput/resolve":return this.#e.userInputResolve(a);case"profile/workflows":return this.#e.profileWorkflows(a);case"profile/evaluations":return this.#e.profileEvaluations(a);case"profile/trainingSource":return this.#e.profileTrainingSource(a);case"profile/evaluations/prepare":return this.#e.profileEvaluationPrepare(a);case"profile/evaluations/run":return this.#e.profileEvaluationRun(a);case"profile/evaluations/runSuite":return this.#e.profileEvaluationRunSuite(a);case"profile/evaluations/executeCase":return this.#e.profileEvaluationExecuteCase(a);case"profile/evaluations/executeRun":return this.#e.profileEvaluationExecuteRun(a);case"profile/evaluations/compare":return this.#e.profileEvaluationCompare(a);case"profile/evaluations/report":return this.#e.profileEvaluationReport(a);case"harness/inspect":return this.#e.harnessInspect(a);case"harness/proposalReview":return this.#e.harnessProposalReview(a);case"harness/review":return this.#e.harnessReview(a);case"harness/acceptEvaluationReview":return this.#e.harnessAcceptEvaluationReview(a);case"harness/materializeEvaluationTaskset":return this.#e.harnessMaterializeEvaluationTaskset(a);case"harness/runEvaluationBaseline":return this.#e.harnessRunEvaluationBaseline(a);case"harness/validate":return this.#e.harnessValidate(a);case"harness/backgroundReview":return this.#e.harnessBackgroundReview(a);case"harness/diff":return this.#e.harnessDiff(a);case"harness/rollback":return this.#e.harnessRollback(a);case"refiner/inspect":return this.#e.refinerInspect(a);case"refiner/update":return this.#e.refinerUpdate(a);case"refiner/activate":return this.#e.refinerActivate(a);case"refiner/rollback":return this.#e.refinerRollback(a);default:throw new x(-32601,`Method not found: ${r}`)}}},x=class extends Error{static{o(this,"JsonRpcDispatchError")}code;data;constructor(r,a,n){super(a),this.code=r,this.data=n}};function Z(t,r,a,n){return{jsonrpc:"2.0",id:t,error:{code:r,message:a,...n===void 0?{}:{data:n}}}}o(Z,"jsonRpcError");var c=e.string().trim().min(1).max(200),z=e.string().trim().min(1).max(32e3),T=e.number().int().nonnegative(),re=e.object({id:c,sessionId:c,senderSessionId:c.nullable(),senderKind:e.enum(["user","task","runtime"]),kind:e.enum(["steer","message","followup","queued","result"]),body:z,payload:e.record(e.string(),e.unknown()),idempotencyKey:c,replyTo:c.nullable(),expectedTurnId:c.nullable()}).strict(),Se=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:z}).strict(),e.object({action:e.literal("steer"),expectedRevision:e.number().int().positive(),expectedTurnId:c}).strict()]),ne=e.object({id:c,sessionId:c,turnId:c,targetSessionId:c.nullable(),targetTurnId:c.nullable(),targetInputId:c.nullable(),afterSequence:T,deadline:e.string(),state:e.enum(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:e.string(),updatedAt:e.string()}).strict(),ae=e.record(e.string(),e.unknown()),Re=e.enum(["queued","running","completed","failed","cancelled","needs_resume"]),Te=e.object({parentSessionId:c.nullable().optional(),childSessionId:c.nullable().optional(),status:e.array(Re).nullable().optional(),afterId:e.string().max(200),limit:e.number().int().min(1).max(10)}).strict(),ie=e.discriminatedUnion("action",[e.object({action:e.literal("recoverTaskInboxOwners"),ownerId:c}).strict(),e.object({action:e.literal("hasTaskCompletion"),turnId:c}).strict(),e.object({action:e.literal("taskInboxSnapshot"),sessionId:c}).strict(),e.object({action:e.literal("taskInboxSnapshotInputs"),sessionId:c,afterSequence:T}).strict(),e.object({action:e.literal("declareTaskWork"),sessionId:c,turnId:c,ownerId:c,areas:e.array(z).max(100)}).strict(),e.object({action:e.literal("taskWorkAreas"),sessionId:c}).strict(),e.object({action:e.literal("admitTaskInput"),input:re}).strict(),e.object({action:e.literal("admitTaskInputs"),inputs:e.array(re).max(50)}).strict(),e.object({action:e.literal("rejectTaskInput"),id:c,error:z}).strict(),e.object({action:e.literal("getTaskInput"),id:c}).strict(),e.object({action:e.literal("taskInputsForSession"),sessionId:c,query:e.object({afterSequence:T.optional(),pendingOnly:e.boolean().optional(),limit:e.number().int().min(1).max(500).optional()}).strict()}).strict(),e.object({action:e.literal("mutateTaskInput"),sessionId:c,inputId:c,change:Se}).strict(),e.object({action:e.literal("openTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c}).strict(),e.object({action:e.literal("renewTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c}).strict(),e.object({action:e.literal("pendingTaskInputs"),sessionId:c,turnId:c,afterSequence:T}).strict(),e.object({action:e.literal("taskAssignmentInputs"),turnId:c,afterSequence:T}).strict(),e.object({action:e.literal("pauseTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c}).strict(),e.object({action:e.literal("includeTaskInputs"),sessionId:c,turnId:c,ownerId:c,requestId:c}).strict(),e.object({action:e.literal("settleTaskInputRequest"),requestId:c,outcome:e.enum(["resolved","failed","replaced"])}).strict(),e.object({action:e.literal("sealTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c}).strict(),e.object({action:e.literal("sealNativeTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c}).strict(),e.object({action:e.literal("closeTaskInboxTurn"),sessionId:c,turnId:c,ownerId:c,outcome:e.enum(["completed","failed","interrupted"])}).strict(),e.object({action:e.literal("taskInboxPaused"),sessionId:c}).strict(),e.object({action:e.literal("reserveTaskFollowup"),sessionId:c,turnId:c,ownerId:c}).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:c,state:ne.shape.state}).strict(),e.object({action:e.literal("taskWaitsForSession"),sessionId:c,afterId:e.string().max(200)}).strict(),e.object({action:e.literal("commitSubagentCompletion"),value:ae,turnId:c}).strict(),e.object({action:e.literal("pendingTaskCompletions"),afterTurnId:e.string().max(200)}).strict(),e.object({action:e.literal("settleTaskCompletion"),turnId:c,inputId:c}).strict(),e.object({action:e.literal("upsertSubagentRun"),value:ae}).strict(),e.object({action:e.literal("getSubagentRun"),id:c}).strict(),e.object({action:e.literal("listSubagentRuns"),query:Te}).strict()]);var V=e.string().trim().min(1).max(191),se=e.object({createdAt:e.string().min(1),id:V}).strict(),oe=e.enum(["trigger_decision","route_decision","refiner_outcome","proposal","targeted_validation","apply_receipt"]),ce=e.discriminatedUnion("action",[e.object({action:e.literal("put_artifact"),workspaceId:V,kind:oe,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:V,kind:oe,before:se.nullable(),limit:e.number().int().min(1).max(200)}).strict(),e.object({action:e.literal("pending_trigger_page"),workspaceId:V,before:se.nullable(),limit:e.number().int().min(1).max(200)}).strict()]);var v=e.string().trim().min(1).max(200),le=e.string().regex(/^[a-f0-9]{64}$/),Ee=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()}),ue=e.object({id:v,title:e.string().trim().min(1).max(240),sourceTaskId:v,sourceTurnId:v,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:le,validation:e.array(Ee).max(32)}).strict(),de=e.object({sessionId:v,turnId:v,output:ue}).strict(),pe=e.object({uploadId:v,index:e.number().int().min(0).max(1024),offset:e.number().int().min(0).max(1e7),sha256:le,contentsBase64:e.string().min(1).max(131072)}).strict(),me=e.object({uploadId:v}).strict(),Pe=ue.pick({id:!0,title:!0,sourceTaskId:!0,sourceTurnId:!0,revision:!0,createdAt:!0,validation:!0}),he=e.object({sessionId:v,turnId:v,output:Pe,sandboxPath:e.string().trim().min(1).max(4096)}).strict();var E=e.string().trim().min(1).max(200),qe=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:E.optional(),payload:e.unknown().optional(),processId:E.optional(),failOnUnpreservedChanges:e.boolean().optional()}).strict().superRefine((t,r)=>{t.type!=="create"&&!t.sandboxId&&r.addIssue({code:"custom",message:"Sandbox identity is required."}),t.type==="process_get"&&!t.processId&&r.addIssue({code:"custom",message:"Process identity is required."})}),fe=e.object({action:qe}).strict(),be=e.object({sessionId:E,turnId:E,name:E}).strict();var u=1,s=e.string().trim().min(1).max(191),I=e.number().int().min(1).max(200),kt=e.object({teamId:s,ownerUserId:s,workspaceId:s,conversationId:s,turnId:s,attempt:e.number().int().min(1),leaseGeneration:e.number().int().min(1)}).strict(),ge=e.discriminatedUnion("operation",[e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("sandbox/request"),params:fe}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("embedding/authorize"),params:be}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("output/begin"),params:de}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("output/chunk"),params:pe}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("output/complete"),params:me}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("output/saveSandboxFile"),params:he}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("settings/get"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("harness/get"),params:e.object({reference:e.object({id:s,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("harness/overlay/get"),params:e.object({runId:s}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("harness/overlay/put"),params:e.object({runId:s,expectedRevision:e.number().int().min(0).nullable(),overlay:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("harness/overlay/freezeProposal"),params:e.object({runId:s,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(u),requestId:s,operation:e.literal("harness/memory/get"),params:e.object({workspaceId:s,key:e.string().min(1).max(120)}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("harness/memory/list"),params:e.object({workspaceId:s,includeDeleted:e.boolean(),before:e.object({updatedAt:e.string(),key:e.string()}).strict().nullable(),limit:I}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("harness/memory/write"),params:e.object({input:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("harness/state/read"),params:e.object({workspaceId:s,kind:e.enum(["selection","workspace_settings","evaluation_review_settings","candidates","cross_run_requests"]),afterId:s.nullable(),limit:e.number().int().min(1).max(100)}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("harness/workspace/transition"),params:e.discriminatedUnion("action",[e.object({action:e.literal("advance"),receiptId:s,workspaceId:s,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:s,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:s,workspaceId:s,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:s,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),reviewer:s,now:e.string()}).strict(),e.object({action:e.literal("rollback"),receiptId:s,workspaceId:s,expectedWorkspaceRevision:e.number().int().nonnegative(),expectedChannelRevision:e.number().int().nonnegative(),targetRelease:e.object({id:s,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),targetSourceRevision:e.string().min(1),rollbackOf:e.object({id:s,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),now:e.string()}).strict()])}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("task-inbox/execute"),params:ie}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("refiner/execute"),params:e.object({action:ce}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("create-improve/execute"),params:e.discriminatedUnion("action",[e.object({action:e.literal("get"),runId:s}).strict(),e.object({action:e.literal("page"),query:e.object({profileId:s.nullable(),targetKind:s.nullable(),targetId:s.nullable(),state:e.array(s).max(20)}).strict(),before:e.object({updatedAt:e.string(),id:s}).strict().nullable(),limit:I}).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(u),requestId:s,operation:e.literal("approval/get"),params:e.object({approvalId:s}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,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(u),requestId:s,operation:e.literal("usage/getByRequestId"),params:e.object({requestId:s}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("usage/upsert"),params:e.object({record:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("usage/page"),params:e.object({query:e.object({sessionId:s.optional(),turnId:s.optional(),provider:s.optional(),model:s.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:s}).strict().nullable(),limit:I}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("capabilities"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("session/count"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("session/get"),params:e.object({sessionId:s}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("session/page"),params:e.object({afterId:s.nullable(),limit:I}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("session/put"),params:e.object({sessionId:s,expectedRevision:e.number().int().min(1).nullable(),session:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("turn/count"),params:e.object({sessionId:s}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("turn/wakeCount"),params:e.object({sessionId:s,key:e.enum(["messageId","fromRunId"]),value:s}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("turn/get"),params:e.object({turnId:s}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("turn/put"),params:e.object({sessionId:s,turnId:s,expectedRevision:e.number().int().min(1).nullable(),turn:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("turn/latest"),params:e.object({sessionId:s,status:e.enum(["in_progress","completed","failed","interrupted"]).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("turn/page"),params:e.object({sessionId:s,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:I}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("thread/turnPage"),params:e.object({sessionId:s,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:I}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("event/append"),params:e.object({event:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("events/page"),params:e.object({sessionId:s.nullable(),afterSequence:e.number().int().min(0),beforeSequence:e.number().int().min(1).nullable().optional(),limit:I}).strict()}).strict(),e.object({contractVersion:e.literal(u),requestId:s,operation:e.literal("events/latestAssistantText"),params:e.object({sessionId:s}).strict()}).strict()]),jt=e.object({contractVersion:e.literal(u),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/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(s).max(128),maxPageSize:I,maxRequestBytes:e.number().int().min(1).max(1e6),maxInFlight:e.number().int().min(1).max(64)}).strict();var ve=class{static{o(this,"AgentHostStorageClient")}#e=new Map;#t=null;#r=1;bind(r){if(this.#t)throw new Error("Host storage client is already bound.");this.#t=r}async request(r,a=15e3){let n=ge.parse(r);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 i=`host-storage:${this.#r++}`,l={jsonrpc:"2.0",id:i,method:"host/storage",params:n};if(Buffer.byteLength(JSON.stringify(l))>256e3)throw new Error("Host storage request is too large.");let d=new Promise((p,f)=>{let h=setTimeout(()=>{this.#e.delete(i),f(new Error("Host storage request timed out."))},Math.max(1,Math.min(6e4,a)));this.#e.set(i,{resolve:p,reject:f,timer:h})});try{await this.#t(l)}catch(p){let f=this.#e.get(i);f&&(clearTimeout(f.timer),this.#e.delete(i),f.reject(p instanceof Error?p:new Error(String(p))))}return d}accept(r){let a=M.safeParse(r),n=a.success?null:U.safeParse(r),i=a.success?a.data:n?.success?n.data:null;if(!i||typeof i.id!="string"||!i.id.startsWith("host-storage:"))return!1;let l=this.#e.get(i.id);return l?(clearTimeout(l.timer),this.#e.delete(i.id),Buffer.byteLength(JSON.stringify(i))>1e6?(l.reject(new Error("Host storage response is too large.")),!0):("error"in i?l.reject(new Error(`Host storage request failed: ${i.error.message}`)):l.resolve(i.result),!0)):!0}close(){this.#t=null;for(let r of this.#e.values())clearTimeout(r.timer),r.reject(new Error("Host storage transport closed."));this.#e.clear()}};import{createHash as Ae}from"node:crypto";function $(t){if(t===null||typeof t=="boolean"||typeof t=="string")return t;if(typeof t=="number"){if(!Number.isFinite(t))throw new Error("Canonical JSON cannot encode a non-finite number.");return t}if(Array.isArray(t))return t.map($);if(typeof t=="object"){let r={};for(let a of Object.keys(t).sort()){let n=t[a];n!==void 0&&(r[a]=$(n))}return r}throw new Error(`Canonical JSON cannot encode ${typeof t}.`)}o($,"canonicalJson");function y(t){return Ae("sha256").update(JSON.stringify($(t)),"utf8").digest("hex")}o(y,"canonicalHash");var Ce=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"]),_e=e.object({sequence:e.number().int().nonnegative(),name:Ce,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 Ht(t){return y(_e.parse(t))}o(Ht,"canonicalEventHash");import{once as He}from"node:events";import{createInterface as ze}from"node:readline";async function we(t){let r=null,a=Promise.resolve(),n=[],i=o(m=>(a=a.then(async()=>{t.writable.write(`${JSON.stringify(m)}
|
|
3
|
-
`)||await He(t.writable,"drain")}),a),"write");t.hostStorageClient?.bind(m=>i(m));let l=o(()=>{if(!(!r?.initialized||n.length===0))for(let m of n.splice(0))i(m)},"flushPendingNotifications"),d,p=new Set,f=ze({input:t.readable,crlfDelay:1/0}),h=[],q=!1,S=null,j=o(async m=>{let b=r;if(!b)throw new Error("Agent runtime dispatcher is unavailable.");let w=(async()=>{let J=await b.handle(m);J&&await i(J),l()})(),F=m&&typeof m=="object"&&"method"in m?m.method:null;if(F==="initialize"||F==="initialized"){await w;return}p.add(w),w.finally(()=>p.delete(w))},"dispatch"),N=(async()=>{let m=typeof t.host=="function"?await t.host():t.host;for(r=new H(m),d=m.subscribe?.(b=>{if(!r?.initialized){n.push(b);return}i(b)});h.length>0;)await j(h.shift());q=!0})().catch(m=>{S=m,f.close()});try{for await(let m of f){if(!m.trim())continue;if(Buffer.byteLength(m,"utf8")>1e6){await i({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Request exceeds the JSONL size limit"}});continue}let b;try{b=JSON.parse(m)}catch{await i({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}});continue}if(!t.hostStorageClient?.accept(b))if(q)await j(b);else if(h.length>=64){let w=b&&typeof b=="object"&&"id"in b?b.id:null;(typeof w=="string"||typeof w=="number")&&await i({jsonrpc:"2.0",id:w,error:{code:-32e3,message:"Runtime startup request limit exceeded"}})}else h.push(b)}if(await N,S)throw S;await Promise.all(p),await a}finally{t.hostStorageClient?.close(),d?.()}}o(we,"runAgentJsonlServer");var O=e.object({threadId:e.string().trim().min(1)}).passthrough(),Ve=e.object({session:e.unknown()}).strict(),P=O.extend({input:e.unknown()}),Oe=P.extend({idempotencyKey:e.string().trim().min(1).max(200)}),Ne=P.extend({inputId:e.string().trim().min(1)}),Be=O.extend({reason:e.string().trim().min(1).optional()}),Me=e.object({approvalId:e.string().trim().min(1),input:e.unknown()}).strict();function xe(t){let r=o(async(n,i,l)=>{let d=performance.now();t.telemetry?.({method:n,phase:"started",threadId:i,durationMs:null,errorClass:null});try{let p=await l();return t.telemetry?.({method:n,phase:"completed",threadId:i,durationMs:performance.now()-d,errorClass:null}),p}catch(p){throw t.telemetry?.({method:n,phase:"failed",threadId:i,durationMs:performance.now()-d,errorClass:p instanceof Error?p.name:"UnknownError"}),p}},"run"),a=o(async(n,i="thread/read")=>{let{threadId:l}=O.parse(n);return r(i,l,async()=>{let[d,p,f]=await Promise.all([t.readThread(l),t.listTurns(l),t.listEvents(l)]);return{thread:d,turns:p,events:f}})},"threadRead");return{capabilities:o(n=>r("runtime/capabilities",null,()=>t.capabilities(n)),"capabilities"),threadStart:o(async n=>r("thread/start",null,async()=>({thread:await t.createThread(Ve.parse(n).session)})),"threadStart"),threadResume:o(n=>a(n,"thread/resume"),"threadResume"),threadRead:a,turnStart:o(async n=>{let i=P.parse(n);return r("turn/start",i.threadId,async()=>({turn:await t.startTurn(i.threadId,i.input)}))},"turnStart"),turnSteer:o(async n=>{let i=P.parse(n);return r("turn/steer",i.threadId,async()=>({receipt:await t.steerTurn(i.threadId,i.input)}))},"turnSteer"),taskInbox:o(async n=>{let{threadId:i}=O.parse(n);return r("task/inbox",i,()=>t.readTaskInbox(i))},"taskInbox"),taskQueue:o(async n=>{let i=Oe.parse(n);return r("task/queue",i.threadId,()=>t.queueTaskInput(i.threadId,i.input,i.idempotencyKey))},"taskQueue"),taskInputUpdate:o(async n=>{let i=Ne.parse(n);return r("task/inputUpdate",i.threadId,()=>t.updateTaskInput(i.threadId,i.inputId,i.input))},"taskInputUpdate"),turnInterrupt:o(async n=>{let i=Be.parse(n);return r("turn/interrupt",i.threadId,async()=>({turn:await t.interruptTurn(i.threadId,i.reason)}))},"turnInterrupt"),approvalResolve:o(async n=>{let i=Me.parse(n);return r("approval/resolve",null,async()=>({approval:await t.resolveApproval(i.approvalId,i.input)}))},"approvalResolve"),userInputResolve:o(async n=>{let i=P.parse(n);return r("userInput/resolve",i.threadId,async()=>(t.isTurnActive(i.threadId)&&await t.waitForTurnSettlement(i.threadId),{turn:await t.startTurn(i.threadId,i.input)}))},"userInputResolve"),profileWorkflows:o(()=>r("profile/workflows",null,()=>t.listProfileWorkflows()),"profileWorkflows"),profileEvaluations:o(n=>r("profile/evaluations",null,()=>t.listProfileEvaluations(n)),"profileEvaluations"),profileTrainingSource:o(()=>r("profile/trainingSource",null,()=>t.loadProfileTrainingSource()),"profileTrainingSource"),profileEvaluationPrepare:o(n=>r("profile/evaluations/prepare",null,()=>t.prepareProfileEvaluationRun(n)),"profileEvaluationPrepare"),profileEvaluationRun:o(n=>r("profile/evaluations/run",null,()=>t.runPreparedProfileEvaluation(n)),"profileEvaluationRun"),profileEvaluationRunSuite:o(n=>r("profile/evaluations/runSuite",null,()=>t.runProfileEvaluationSuite(n)),"profileEvaluationRunSuite"),profileEvaluationExecuteCase:o(n=>r("profile/evaluations/executeCase",null,()=>t.executeProfileEvaluationCase(n)),"profileEvaluationExecuteCase"),profileEvaluationExecuteRun:o(n=>r("profile/evaluations/executeRun",null,()=>t.executeProfileEvaluationRun(n)),"profileEvaluationExecuteRun"),profileEvaluationCompare:o(n=>r("profile/evaluations/compare",null,()=>t.compareProfileEvaluationRuns(n)),"profileEvaluationCompare"),profileEvaluationReport:o(n=>r("profile/evaluations/report",null,()=>t.buildProfileEvaluationReport(n)),"profileEvaluationReport"),harnessInspect:o(()=>r("harness/inspect",null,()=>t.inspectHarness()),"harnessInspect"),harnessProposalReview:o(n=>r("harness/proposalReview",null,()=>t.reviewHarnessProposal(n)),"harnessProposalReview"),harnessReview:o(n=>r("harness/review",null,()=>t.reviewHarness(n)),"harnessReview"),harnessAcceptEvaluationReview:o(n=>r("harness/acceptEvaluationReview",null,()=>t.acceptHarnessEvaluationReview(n)),"harnessAcceptEvaluationReview"),harnessMaterializeEvaluationTaskset:o(n=>r("harness/materializeEvaluationTaskset",null,()=>t.materializeHarnessEvaluationTaskset(n)),"harnessMaterializeEvaluationTaskset"),harnessRunEvaluationBaseline:o(n=>r("harness/runEvaluationBaseline",null,()=>t.runHarnessEvaluationBaseline(n)),"harnessRunEvaluationBaseline"),harnessValidate:o(()=>r("harness/validate",null,()=>t.validateHarness()),"harnessValidate"),harnessBackgroundReview:o(n=>r("harness/backgroundReview",null,()=>t.updateHarnessBackgroundReview(n)),"harnessBackgroundReview"),harnessDiff:o(n=>r("harness/diff",null,()=>t.diffHarness(n)),"harnessDiff"),harnessRollback:o(n=>r("harness/rollback",null,()=>t.rollbackHarness(n)),"harnessRollback"),refinerInspect:o(()=>r("refiner/inspect",null,()=>t.inspectRefiner()),"refinerInspect"),refinerUpdate:o(n=>r("refiner/update",null,()=>t.updateRefiner(n)),"refinerUpdate"),refinerActivate:o(n=>r("refiner/activate",null,()=>t.activateRefiner(n)),"refinerActivate"),refinerRollback:o(n=>r("refiner/rollback",null,()=>t.rollbackRefiner(n)),"refinerRollback"),subscribe:t.subscribeEvents&&t.eventNotification?n=>t.subscribeEvents(i=>n(t.eventNotification(i))):void 0}}o(xe,"createAgentRuntimeService");var k=e.string().regex(/^[a-f0-9]{64}$/),tr=e.object({harnessReleaseHash:k,instructionsHash:k,skillHashes:e.record(e.string(),k),agentAssetHashes:e.record(e.string(),k),toolCatalogHash:k,memoryRevision:e.number().int().nonnegative().nullable()}).strict(),Ue=e.object({protocolVersion:e.string().trim().min(1),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1),harnessReleaseHash:k,toolCatalogHash:k,context:e.record(e.string(),e.unknown()),pendingInteraction:e.record(e.string(),e.unknown()).nullable(),usage:e.record(e.string(),e.unknown())}).strict();function rr(t){return y(Ue.parse(t))}o(rr,"checkpointHash");function nr(t){return[t.system,...t.harnessInstructions,...t.skillInstructions,...t.hostInstructions??[]].map(r=>r.trim()).filter(Boolean).join(`
|
|
4
|
-
|
|
5
|
-
`)}o(nr,"materializeAgentPrompt");function or(t){let r=new Set,a=[...t].map(l=>{let d=l.name.trim();if(!d)throw new Error("Agent tool names cannot be empty.");if(r.has(d))throw new Error(`Duplicate agent tool: ${d}.`);if(r.add(d),!l.unavailableReason&&!l.executorAvailable)throw new Error(`Agent tool ${d} is declared as available without an executor.`);return{...l,name:d}}).sort((l,d)=>l.name.localeCompare(d.name)),n=a.filter(l=>!l.unavailableReason).map(l=>({name:l.name,description:l.description,inputSchema:l.inputSchema})),i=a.map(l=>({name:l.name,displayLabel:l.displayLabel??l.name,placement:l.placement,available:!l.unavailableReason,unavailableReason:l.unavailableReason??null}));return{byName:new Map(a.map(l=>[l.name,l])),tools:a,modelTools:n,capabilities:i,hash:y({modelTools:n,capabilities:i})}}o(or,"createAgentToolCatalogProjection");async function cr(t,r){let a=t.byName.get(r.name);if(!a)throw new Error(`Unknown agent tool: ${r.name}.`);if(a.unavailableReason)throw new Error(`Agent tool ${r.name} is unavailable: ${a.unavailableReason}`);if(!a.execute)throw new Error(`Agent tool ${r.name} has no executor.`);let n=a.validateArguments?a.validateArguments(r.arguments):r.arguments;return a.execute(n,r.context)}o(cr,"executeProjectedAgentTool");var Ie=class{static{o(this,"TaskSignals")}#e=new Map;notify(r){for(let a of[...this.#e.get(r)??[]])a()}subscribe(r,a){let n=this.#e.get(r);return n||this.#e.set(r,n=new Set),n.add(a),()=>{n.delete(a),n.size===0&&this.#e.delete(r)}}async wait(r){let a=o(()=>{},"wake"),n=0,i=o(()=>{n+=1,a()},"changed"),l=[...new Set(r.taskIds)].map(p=>this.subscribe(p,i)),d=setTimeout(i,Math.max(0,r.deadline-Date.now()));r.signal.addEventListener("abort",i);try{for(;;){r.signal.throwIfAborted();let p=n,f=await r.read();if(f!==null)return f;if(Date.now()>=r.deadline)return null;n===p&&await new Promise(h=>{a=h,(n!==p||r.signal.aborted)&&h()})}}finally{clearTimeout(d),r.signal.removeEventListener("abort",i);for(let p of l)p()}}},ke=class{static{o(this,"TaskSerialExecutor")}#e=new Map;async run(r,a){let i=(this.#e.get(r)??Promise.resolve()).then(a),l=i.then(()=>{},()=>{});this.#e.set(r,l);try{return await i}finally{this.#e.get(r)===l&&this.#e.delete(r)}}};function Cr(t){return $e({runtime:xe(t.ports),close:t.close})}o(Cr,"createAppServer");function $e(t){let r=!1;return{runtime:t.runtime,close:o(async()=>{r||(r=!0,await t.close?.())},"close")}}o($e,"attachAppServer");async function _r(t){let r=typeof t.appServer=="function"?null:t.appServer;try{await we({host:r?.runtime??(async()=>(r=await t.appServer(),r.runtime)),readable:t.readable,writable:t.writable,hostStorageClient:t.hostStorageClient})}finally{await r?.close()}}o(_r,"runAppServerJsonl");import{randomBytes as Fe}from"node:crypto";function Nr(){return L()}o(Nr,"appDataDir");function Br(t){return g(t).config}o(Br,"providersConfigPath");function Mr(t){return g(t).credentials}o(Mr,"providerSecretsConfigPath");function Ur(t){return g(t).key}o(Ur,"providerSecretsKeyPath");async function $r(t){let r=g(t).token;return W(r,async()=>{let a=(await D(r))?.trim(),n=process.env.OPENPOND_APP_TOKEN||a||Fe(32).toString("base64url");return n!==a&&await C(r,n),{token:n,tokenFile:r}})}o($r,"ensureCapabilityToken");export{Ge as a,Ke as b,Qe as c,y as d,Ze as e,et as f,tt as g,_e as h,Ht as i,_ as j,it as k,qe as l,u as m,jt as n,ve as o,Ue as p,rr as q,nr as r,or as s,cr as t,Ie as u,ke as v,Cr as w,_r as x,Nr as y,Br as z,Mr as A,Ur as B,$r as C};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{$b as Ne,Aa as _e,Cb as Le,Da as Be,Eb as Fe,Ha as De,Jb as Ve,Lb as $e,Mb as he,Pa as $,Pb as qe,Qb as J,Rb as X,Sa as te,Sb as ve,Ta as Ae,Tb as Oe,Ub as ze,Va as Ce,Wa as W,Wb as se,Xa as ue,Xb as L,Yb as ae,_b as Ge,ba as fe,bc as Ke,cc as We,da as K,dc as ge,ea as p,ec as Je,mc as ne,nc as Xe,p as Ee,r as Me,sc as re,wb as je}from"./chunk-QTEYV4TW.js";import{n as le,o as pe,p as Pe}from"./chunk-B5LKUQGM.js";import{$a as Y,Ab as N,Cb as U,Eb as Ie,Lb as v,Mb as j,Nb as P,Ob as He,Qb as Z,Sb as ee,a as D,bc as z,fb as be,ib as Te,jb as Se,kb as xe,lb as ye,sb as O,tb as G,vb as V,xb as Q}from"./chunk-5BFWDFPX.js";import{b as k}from"./chunk-ES2ISFJC.js";import{a as S}from"./chunk-FTQLQJQV.js";var oe=G.shape.id,Ye=k.object({schemaVersion:k.literal("openpond.modelBatchReviewInspection.v1"),packageHash:k.string().regex(/^[a-f0-9]{64}$/),definition:V,binding:be,evidence:k.array(N).min(1).max(1e4),decisions:k.array(Ie).min(1).max(1e4)}).strict(),ke=k.object({schemaVersion:k.literal("openpond.modelBatchReviewRequest.v1"),operationId:oe,modelId:oe,expectedModelRevision:k.number().int().positive(),tasksetRef:G,rewardBindingRef:G.nullable(),definition:k.object({name:k.string().trim().min(1).max(500).optional(),instructions:k.string().trim().min(1).max(2e4).optional(),inputSchema:O.optional(),outputSchema:O.optional(),requiredOutputs:V.shape.requiredOutputs}).strict(),examples:k.array(k.object({evidence:G,input:O.optional(),expected:O.nullable().optional(),evaluatorContext:O.nullable().optional(),proposedTarget:O.nullable().optional()}).strict()).max(1e4)}).strict(),Qe=k.object({schemaVersion:k.literal("openpond.modelBatchReviewReceipt.v1"),operationId:oe,modelId:oe,source:Q,evidence:k.array(N).min(1).max(1e4),proposals:k.array(U).max(1e4)}).strict();function ss(s){let e=L(s.source);if(e.modelResources||e.learningResources)throw new Error("Binding an ordinary Reward requires an ordinary source package.");let t=se(e);if(!t.trim())throw new Error("Add collection instructions before selecting a saved Reward.");let a=new Map,i=X(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 y=e.files.find(F=>F.asset.id===h);if(!y)throw new Error(`Source Taskset context is missing: ${h}.`);let A=new TextDecoder("utf-8",{fatal:!0}).decode(J(y));a.set(h,Z.parse(P({schemaVersion:"openpond.learningTextAsset.v1",id:h,revision:1,asset:y.asset,text:A})))}for(let h of s.assets){let y=e.files.find(A=>A.asset.id===h.id);if(y&&P({asset:y.asset}).contentHash!==P({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:g,environmentRelease:x,tools:R,capabilities:r,verifierSetRelease:w}=e.taskset,c=V.parse(P({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:g,environmentRelease:x,tools:R,capabilities:r,verifierSetRelease:w}})),l=he({...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 y="";for(let A of new TextEncoder().encode(h.text))y+=String.fromCharCode(A);d.set(h.id,{asset:h.asset,base64:btoa(y)})}let{taskset:H,executionResources:E,...M}=l;return ae({schemaVersion:"openpond.tasksetPackage.v1",taskset:H,...E,modelResources:M,files:[...d.values()]})}S(ss,"bindOrdinaryModelTasksetReward");function at(s){let{request:e,package:t}=s,a=t.learningResources;if(!a)throw new D("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])),g=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=>!g.has(p(o.evidence))))throw new D("model_review_evidence_mismatch",409);for(let o of[s.binding,...s.rewards,...s.assets])He(o);xe(s.binding,s.rewards);let R=new Map;for(let o of s.binding.sources){let I=s.rewards.find(ie=>j(v(ie),o.reward)),{contentHash:B,...q}=I;R.set(I.contentHash,Te({...q,id:`${m}-reward-${I.contentHash}`,revision:1}))}let r=[...R.values()],{contentHash:w,recipeRef:c,...l}=s.binding,d=Se({...l,id:`${m}-binding`,revision:1,sources:s.binding.sources.map(o=>({...o,reward:v(R.get(o.reward.contentHash))}))},r),H=r.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(H.map(o=>{let I=s.assets.find(B=>B.id===o.id);if(!I)throw new D("model_review_reward_asset_missing",422);if(ee(I,o),o.visibility==="policy")throw new D("reward_asset_visibility_invalid",422);return[I.id,I]})).values()],{environmentRelease:M,verifierSetRelease:h,...y}=i.definition.execution,{contentHash:A,...F}=i.definition,n=V.parse(P({...F,...e.definition,id:`${m}-definition`,revision:1,rewardBinding:v(d),execution:{...y,policy:{...y.policy,hiddenGraderRefs:ye(d,r).filter(o=>o.privileged).map(o=>o.id)}}})),f=Q.parse(P({schemaVersion:"openpond.learningSource.v1",id:m,revision:1,name:`${n.name} review`,kind:"direct",taskDefinition:v(n),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)}})),b=a.evidence.map(o=>{let I=u.get(p(v(o))),B=`review-${o.contentHash}`,q=p({instructions:n.instructions,inputSchema:n.inputSchema,outputSchema:n.outputSchema,requiredOutputs:n.requiredOutputs??[],input:I?.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 N.parse(P({schemaVersion:"openpond.taskEvidence.v1",id:Pe(f.id,o.submission.exampleId,B),revision:1,source:v(f),submission:{...o.submission,sourceId:f.id,taskDefinition:v(n),attemptId:B,observedOutput:q?null:o.submission.observedOutput,idempotencyKey:`${m}-${o.contentHash}`,...I?.input===void 0?{}:{input:I.input},...I?.expected===void 0?{}:{expected:I.expected},...I?.evaluatorContext===void 0?{}:{evaluatorContext:I.evaluatorContext}},supersedes:v(o),correctionFeedbackId:null,receivedAt:s.now}))}),_=b.flatMap(o=>{let I=u.get(p(o.supersedes)),B=x.get(p(o.supersedes)),q=I?.proposedTarget===void 0?B.approvedTarget:I.proposedTarget;return q===null?[]:[U.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:q,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:n,binding:d,rewards:r,assets:E,evidence:b,proposals:_}}S(at,"prepareModelBatchReview");var Ue=S(s=>`model-batch-review-${p([s.modelId,s.operationId])}`,"operation");function is(s){let e=L(s);if(!e.learningResources)throw new D("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(is,"inspectModelBatchPackage");async function nt(s,e){let t=ke.parse(e),a=await s.operation(Ue(t));if(!a)return null;if(a.requestHash!==p(t))throw new D("learning_idempotency_conflict",409);return Ze(s,t,a.resources)}S(nt,"findModelBatchReview");async function cs(s,e){let t=ke.parse(e.request),a=await nt(s,t);if(a)return a;let i=L(e.package);if(!i.learningResources)throw new D("model_review_batch_required",422);let m=z(i.taskset),u=t.rewardBindingRef,g=!u||j(u,v(m.binding)),x=g?m.binding:await pe(s,"binding",u),R=g?m.rewards:await Promise.all(x.sources.map(d=>pe(s,"reward",d.reward))),r=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=g?i.learningResources.assets:await Promise.all([...r].map(d=>le(s,"asset",d,1))),c=at({...e,request:t,package:i,binding:x,rewards:R,assets:w}),l=[];for(let d of c.assets){let H=await s.get("asset",d.id,1);if(H&&H.contentHash!==d.contentHash)throw new D("model_review_asset_conflict",409);H||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(cs,"beginModelBatchReview");async function Ze(s,e,t){let a=await Promise.all(t.map(i=>le(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 rt(s){let e=L(s.source),t=L(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(T=>T.taskset.graders.map(C=>C.kind==="custom_verifier"?{...C,exportName:C.exportName??"verify"}:C),"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(T=>[T.id,T])),g=X(t),x=X(e),R=S(T=>{let{id:C,revision:ce,contentHash:de,metadata:me,...st}=T,{javascriptEnvironment:lt,...Re}=me;return{...st,metadata:{...Re,resources:Re.resources??[]}}},"environmentContent"),r=S(T=>{if(!T)return null;let{id:C,revision:ce,contentHash:de,...me}=T.execution.javascript;return me},"javascriptContent"),w=p(R(e.environment))===p(R(t.environment))&&p(r(x))===p(r(g)),c=w?e.environment:t.environment,l=w?x:g,d=new Set([...m.assets.map(T=>T.id),...t.taskset.tasks.flatMap(T=>T.privilegedContextRef?[T.privilegedContextRef]:[]),...[t.environment.actionSchemaRef,t.environment.observationSchemaRef,t.environment.stateSchemaRef].flatMap(T=>T?[T.id]:[]),...g?.assets.map(T=>T.id)??[]]);for(let T of d){let C=t.files.find(de=>de.asset.id===T);if(!C)throw new Error(`Bound Taskset asset is missing: ${T}.`);let ce=new TextDecoder("utf-8",{fatal:!0}).decode(J(C));u.set(T,Z.parse(P({schemaVersion:"openpond.learningTextAsset.v1",id:T,revision:1,asset:C.asset,text:ce})))}let H=se(t),{contentHash:E,...M}=m.taskDefinition,{policy:h,environment:y,environmentRelease:A,tools:F,capabilities:n,verifierSetRelease:f}=t.taskset,b=V.parse(P({...M,instructions:H,execution:{policy:h,environment:y,environmentRelease:A,tools:F,capabilities:n,verifierSetRelease:f}})),{contentHash:_,...o}=t.taskset,I=Y.parse(P({...o,tasks:t.taskset.tasks.map(T=>m.instructionMode==="per_task"?T:{...T,policyVisibleContext:{...T.policyVisibleContext,instructions:H}})})),B=he({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:I,taskDefinition:b,executionResources:{environment:c,verifierSet:t.verifierSet},...l?{execution:l.execution}:{}}}),q=Ve.parse(B.taskset.metadata.modelTasksetDerivation);if(B.taskset.id!==a.tasksetId||B.taskset.revision!==a.tasksetRevision||p({...q,schemaVersion:a.lineage.schemaVersion})!==p(a.lineage))throw new Error("Bound draft differs from its retained ownership lineage.");let{taskset:ie,executionResources:et,...tt}=B;return ae({schemaVersion:"openpond.tasksetPackage.v1",taskset:ie,...et,modelResources:tt,files:t.files})}S(rt,"publishBoundModelTasksetDraftPackage");function us(s){let e=Ce.parse(s.request),t=Ae.parse(s.owner),a=L(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=$e({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 W.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),g={schemaVersion:"openpond.modelTasksetAuthoring.v1",owner:t,root:u,parent:v(a.taskset)};return W.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(g),tasksetRevision:m?a.taskset.revision+1:1,lineage:g})}S(us,"prepareModelTasksetDraft");function hs(s){let e=W.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=ot(s.edited),{contentHash:a,...i}=t.verifierSet,m=Me({...i,id:`${e.tasksetId}-verifiers`,revision:e.tasksetRevision,calibrationReceiptRefs:[],metadata:{sourceVerifierSet:v(t.verifierSet)}}),{contentHash:u,...g}=t.taskset,x=Y.parse(P({...g,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=X(t),r=R?[...t.files.filter(w=>w.asset.id!==Fe(t.taskset)),ve({...R.execution,verifierSet:m})]:t.files;return ae({schemaVersion:"openpond.tasksetPackage.v1",taskset:x,environment:t.environment,verifierSet:m,files:r})}S(hs,"publishModelTasksetDraftPackage");function ot(s){let e=L(s);if(e.modelResources||e.learningResources)throw new Error("This Taskset requires its bound or reviewed authoring workflow.");return e}S(ot,"requireOrdinaryPackage");function gs(s){let e=L(s.package),t=e.taskset,a=e.modelResources,i=e.learningResources?z(t):void 0,m=_e.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}),g=[];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 H=Je(c.verifierRef.contentHash);g.some(E=>E.path===H)||g.push({path:H,role:"verifier",content:l?ee(l,c.verifierRef):new TextDecoder("utf-8",{fatal:!0}).decode(J(d))})}let x=t.metadata.ordinaryAuthoring??t.metadata.starterAuthoring,R=De.array().max(1e5).parse(x?.graderFixtures??[]),r=t.environment.kind==="text"?"chat":t.environment.kind==="custom_program"?"program":t.environment.kind,w=$.parse({schemaVersion:"openpond.taskset.v1",id:t.id,revision:t.revision,profileId:s.profileId,profileRelease:null,createImproveRunId:null,name:s.name,objective:se(e),status:"needs_review",sourceRefs:[m],datasetArtifact:null,policy:t.policy,environment:{...u.environment,kind:r,entrypoint:t.environment.entrypoint,resources:Be.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:it(s.profileId,e.contentHash),portableEnvironment:t.environment,portableTools:t.tools,portableExecutionResources:{environment:e.environment,verifierSet:e.verifierSet}}},capabilities:{...u.capabilities,taskKind:r==="chat"?"chat":r==="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?ge(a.rewardBinding,a.rewards,a.assets):i?ge(i.binding,i.rewards,e.learningResources.assets):We(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:$.parse({...w,contentHash:te(w)}),generatedFiles:g}}S(gs,"prepareImportedTasksetPackage");function it(s,e){return`package-${p({profileId:s,packageHash:e})}`}S(it,"tasksetPackageSourceId");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=Le.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m))),g=S(M=>{if(!M)return null;let h=t.find(y=>y.asset.id===M.id&&y.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,r=je.parse(P({...R,id:`javascript-${s.id}`,revision:s.revision,module:g(u.javascript.module)}));if(p(r.tools)!==p(s.environment.metadata.portableTools)||p(r.tools.map(M=>M.name))!==p(s.environment.toolNames))throw new Error("Authored environment tools differ from the Taskset's declared tools.");let w=Ee({schemaVersion:"openpond.environmentRelease.v1",id:`environment-${s.id}`,revision:s.revision,contract:Ne(s),actionSchemaRef:g(u.environment.actionSchemaRef),observationSchemaRef:g(u.environment.observationSchemaRef),stateSchemaRef:g(u.environment.stateSchemaRef),artifactCollection:u.environment.artifactCollection,adapterConformanceHashes:{},metadata:{javascriptEnvironment:v(r),resources:s.environment.resources??[]}}),c=$.parse({...s,environment:{...s.environment,metadata:{...s.environment.metadata,portableExecutionResources:{environment:w}}}}),l=Ge({taskset:c,adapterId:a}),d=ve({javascript:r,environment:w,verifierSet:l.verifierSetRelease}),H=[...t.filter(M=>M.sourcePath!==i),{asset:d.asset,sourcePath:i}],E=$.parse({...c,metadata:{...c.metadata,portableFileInventory:H}});return{taskset:$.parse({...E,contentHash:te(E)}),inventory:H,generatedFiles:[{path:i,role:"environment",content:new TextDecoder().decode(J(d))}]}}S(ct,"prepareAuthoredToolEnvironment");var we=k.array(k.object({asset:fe,sourcePath:k.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 Ts(s){return dt.has(s)}S(Ts,"isGeneratedTasksetPublicationFilePath");function Ss(s,e,t){let a=$.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[n,f]of e){if(ue.parse(n),m+=f.byteLength,i.size>=1e4||m>qe*3/4)throw new Error("Taskset source exceeds the package byte limit.");i.set(n,f.slice())}let u=a.metrics?.customAggregator,g=u?i.get(u.module):void 0;if(u&&!g)throw new Error("Declared Taskset metric module is missing.");let x=u&&g?{...a.metrics,customAggregator:{...u,contentHash:K(g)}}:a.metrics,R=new Map,r=new Set,w=[],c=S((n,f,b,_)=>{let o=i.get(f);if(!o)throw new Error(`Declared Taskset file is missing: ${f}.`);return{id:n,path:f,contentHash:K(o),sizeBytes:o.byteLength,mediaType:b,visibility:_}},"ref"),l=S((n,f=n.path)=>{let b=R.get(n.id);if(b&&p(b)!==p({asset:n,sourcePath:f}))throw new Error(`Conflicting Taskset file identity: ${n.id}.`);let _=i.get(f);if(!_||_.length!==n.sizeBytes||K(_)!==n.contentHash)throw new Error(`Taskset file differs from its declared bytes: ${n.id}.`);R.set(n.id,{asset:n,sourcePath:f}),r.add(f)},"add");for(let n of a.tasks){let f=Ke(n);for(let b of f.artifactRefs)l(b,n.assets?.find(_=>_.id===b.id)?.artifactRef??b.path);for(let b of f.requiredOutputs??[])b.schemaRef&&l(b.schemaRef)}for(let n of a.environment.resources??[])l(c(n.id,n.path,n.mediaType??"application/octet-stream",n.visibility==="policy_visible"?"policy":"host_private"));let d=a.graders.map(n=>{if(n.kind==="custom_verifier"){let f=c(`verifier-${n.id}`,n.module,"application/javascript","host_private"),b=fe.safeParse(n.metadata.portableVerifierRef);return b.success&&b.data.contentHash===f.contentHash&&b.data.sizeBytes===f.sizeBytes&&(f=b.data),l(f,n.module),{...n,metadata:{...n.metadata,portableVerifierRef:f}}}if(n.kind==="human"||n.kind==="model_judge"){let f=new TextEncoder().encode(n.rubric),b=`graders/rubric-${K(f)}.md`;i.set(b,f);let _=c(`rubric-${n.id}`,b,"text/markdown","verifier");return l(_),w.push({path:b,role:"verifier",content:n.rubric}),{...n,metadata:{...n.metadata,portableRubricRef:_}}}return n});u&&![...R.values()].some(n=>n.asset.path===u.module&&n.sourcePath===u.module&&n.asset.visibility!=="policy")&&l(c(`metric-${p(u.module)}`,u.module,"application/javascript","host_private"));let H=we.parse(a.metadata.portableFileInventory??[]);for(let n of[...i.keys()].sort())if(!r.has(n)){let f=H.find(b=>b.sourcePath===n&&!R.has(b.asset.id));l(f?{...c(f.asset.id,n,f.asset.mediaType,f.asset.visibility),path:f.asset.path}:c(`taskset-file-${p(n)}`,n,"application/octet-stream","host_private"),n)}let{importedPackageHash:E,derivedPortableMetadata:M,...h}=a.metadata,y={...a.environment.metadata};if(y.portableExecutionResources!==void 0){let n=k.object({environment:k.unknown(),verifierSet:k.unknown().optional()}).parse(y.portableExecutionResources);y.portableExecutionResources={environment:n.environment}}let A=$.parse({...a,graders:d,metrics:x,environment:{...a.environment,metadata:y},metadata:{...h,...E===void 0?{}:{sourceImportedPackageHash:E},portableFileInventory:we.parse([...R.values()].sort((n,f)=>n.asset.id.localeCompare(f.asset.id)))}}),F=ct(A,i,[...R.values()],t);return{taskset:$.parse({...F.taskset,contentHash:te(F.taskset)}),generatedFiles:[...w,...F.generatedFiles]}}S(Ss,"prepareAuthoredTasksetSource");var mt=k.object({draft:ne,filePaths:k.array(k.object({assetId:k.string().min(1),paths:k.array(ue).min(1).max(1e4)}).strict()).max(1e4)}).strict();function Is(s){let e=L(s.source),t=ne.parse(s.sourceDraft),a=W.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=we.parse(t.metadata.portableFileInventory??[]),m=S(r=>re(r)?`source-artifacts/${e.contentHash}/${p(r)}/${r.split("/").at(-1)}`:r,"sourcePath");if([...t.tasks.flatMap(r=>(r.assets??[]).map(w=>w.artifactRef)),...(t.environment.resources??[]).map(r=>r.path),...e.taskset.tasks.flatMap(r=>(r.requiredOutputs??[]).flatMap(w=>w.schemaRef?[w.schemaRef.path]:[])),...t.metrics.customAggregator?[t.metrics.customAggregator.module]:[],...t.graders.flatMap(r=>r.kind==="custom_verifier"?[r.module]:[])].some(re))throw new Error("A referenced source asset occupies a reserved Taskset authoring path.");let g=e.files.map(r=>{let w=new Set([r.asset.path]);for(let c of i)c.asset.id===r.asset.id&&w.add(c.sourcePath);for(let c of t.tasks)for(let l of c.assets??[])l.id===r.asset.id&&w.add(l.artifactRef);for(let c of e.taskset.graders)if(c.kind==="custom_verifier"&&c.verifierRef.id===r.asset.id){let l=t.graders.find(d=>d.id===c.id);l?.kind==="custom_verifier"&&w.add(l.module)}return{assetId:r.asset.id,paths:[...w].map(m)}}),x={...t.metadata};if(e.modelResources)for(let r of["taskDefinition","rewardBinding","rewardExecution","derivedPortableMetadata","modelTasksetDerivation","importedPackageHash"])delete x[r];let R=ne.parse({...t,id:a.draftId,revision:1,status:"draft",graders:t.graders.map(r=>({...r,metadata:{...r.metadata,portableGrader:e.taskset.graders.find(w=>w.id===r.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(r=>({...r,sourcePath:m(r.sourcePath),asset:{...r.asset,id:re(r.sourcePath)?`source-artifact-${p({packageHash:e.contentHash,assetId:r.asset.id})}`:r.asset.id,path:m(r.asset.path)}}))}});return mt.parse({draft:R,filePaths:g})}S(Is,"prepareTasksetDraftSource");export{ke as a,ss as b,is as c,nt as d,cs as e,us as f,hs as g,gs as h,it as i,we as j,Ts as k,Ss as l,mt as m,Is as n};
|