openpond 0.2.33 → 0.2.34

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.
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{Hc as r}from"./chunks/chunk-DYHB6VMK.js";import"./chunks/chunk-BK4I7KE4.js";import{I as p,j as e}from"./chunks/chunk-U3TN2FNR.js";import"./chunks/chunk-PCAHFOCQ.js";import"./chunks/chunk-EWB4XTWR.js";import"./chunks/chunk-SRQVXHSM.js";import"./chunks/chunk-77BXXOHW.js";import"./chunks/chunk-TBX3Z7TX.js";import"./chunks/chunk-L3KS6MOV.js";import"./chunks/chunk-XEOEKFG6.js";import"./chunks/chunk-QWENRTVW.js";import"./chunks/chunk-6MI4KKWF.js";import"./chunks/chunk-JFSDNQHW.js";import"./chunks/chunk-SDO4FC4Q.js";import"./chunks/chunk-IR3YJWPW.js";import"./chunks/chunk-B5LKUQGM.js";import"./chunks/chunk-MJC26GOX.js";import"./chunks/chunk-5BFWDFPX.js";import"./chunks/chunk-6FA3GG5B.js";import"./chunks/chunk-IFP6W4OW.js";import"./chunks/chunk-ES2ISFJC.js";import"./chunks/chunk-H7IWJN7L.js";import"./chunks/chunk-FTQLQJQV.js";export{e as AGENT_PROTOCOL_VERSION,r as createOpenPondAppServer,p as runAppServerJsonl};
2
+ import{Hc as r}from"./chunks/chunk-MLBXB6IG.js";import"./chunks/chunk-C472WX3L.js";import{I as p,j as e}from"./chunks/chunk-CC7BNJCF.js";import"./chunks/chunk-UOPUBKJ4.js";import"./chunks/chunk-WJD5NVVH.js";import"./chunks/chunk-SRQVXHSM.js";import"./chunks/chunk-77BXXOHW.js";import"./chunks/chunk-TBX3Z7TX.js";import"./chunks/chunk-L3KS6MOV.js";import"./chunks/chunk-XEOEKFG6.js";import"./chunks/chunk-QWENRTVW.js";import"./chunks/chunk-6MI4KKWF.js";import"./chunks/chunk-JFSDNQHW.js";import"./chunks/chunk-SDO4FC4Q.js";import"./chunks/chunk-IR3YJWPW.js";import"./chunks/chunk-B5LKUQGM.js";import"./chunks/chunk-MJC26GOX.js";import"./chunks/chunk-5BFWDFPX.js";import"./chunks/chunk-6FA3GG5B.js";import"./chunks/chunk-IFP6W4OW.js";import"./chunks/chunk-ES2ISFJC.js";import"./chunks/chunk-H7IWJN7L.js";import"./chunks/chunk-FTQLQJQV.js";export{e as AGENT_PROTOCOL_VERSION,r as createOpenPondAppServer,p as runAppServerJsonl};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{Gc as c,Hc as d}from"./chunk-DYHB6VMK.js";import"./chunk-BK4I7KE4.js";import{I as b,j as a}from"./chunk-U3TN2FNR.js";import"./chunk-PCAHFOCQ.js";import"./chunk-EWB4XTWR.js";import"./chunk-SRQVXHSM.js";import"./chunk-77BXXOHW.js";import"./chunk-TBX3Z7TX.js";import"./chunk-L3KS6MOV.js";import"./chunk-XEOEKFG6.js";import"./chunk-QWENRTVW.js";import"./chunk-6MI4KKWF.js";import"./chunk-JFSDNQHW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import"./chunk-5BFWDFPX.js";import"./chunk-6FA3GG5B.js";import"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as AGENT_PROTOCOL_VERSION,c as APP_SERVER_COMPOSITION,d as createOpenPondAppServer,b as runAppServerJsonl};
2
+ import{Gc as c,Hc as d}from"./chunk-MLBXB6IG.js";import"./chunk-C472WX3L.js";import{I as b,j as a}from"./chunk-CC7BNJCF.js";import"./chunk-UOPUBKJ4.js";import"./chunk-WJD5NVVH.js";import"./chunk-SRQVXHSM.js";import"./chunk-77BXXOHW.js";import"./chunk-TBX3Z7TX.js";import"./chunk-L3KS6MOV.js";import"./chunk-XEOEKFG6.js";import"./chunk-QWENRTVW.js";import"./chunk-6MI4KKWF.js";import"./chunk-JFSDNQHW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-B5LKUQGM.js";import"./chunk-MJC26GOX.js";import"./chunk-5BFWDFPX.js";import"./chunk-6FA3GG5B.js";import"./chunk-IFP6W4OW.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as AGENT_PROTOCOL_VERSION,c as APP_SERVER_COMPOSITION,d as createOpenPondAppServer,b as runAppServerJsonl};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{d as F}from"./chunk-EWB4XTWR.js";import{a as o}from"./chunk-FTQLQJQV.js";import{spawn as nt,spawnSync as At}from"node:child_process";import{accessSync as vt,constants as Rt,existsSync as _t,promises as Bt}from"node:fs";import et from"node:path";var rt="Git is required for OpenPond app workspaces, but macOS reports Apple Command Line Tools are not installed. OpenPond skipped /usr/bin/git to avoid opening the Xcode installer prompt. Install Command Line Tools with `xcode-select --install`, install Git from Homebrew, or put a non-Apple git binary earlier on PATH.",T;function Lt(e){try{return _t(e)?(vt(e,Rt.X_OK),!0):!1}catch{return!1}}o(Lt,"isExecutable");function Ot(){let e=(process.env.PATH??"").split(et.delimiter).map(t=>t.trim()).filter(Boolean);for(let t of e){let n=et.join(t,"git");if(!(n==="/usr/bin/git"||n==="/bin/git")&&Lt(n))return n}return null}o(Ot,"firstNonAppleGitOnPath");function it(){let e=At("/usr/bin/xcode-select",["-p"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return e.status===0&&!!e.stdout.trim()}o(it,"appleDeveloperToolsAvailable");function Dt(e){if(e!=="git"||process.platform!=="darwin")return{command:e};if(T!==void 0)return{command:T};let t=Ot();return t?(T=t,{command:t}):it()?(T="git",{command:"git"}):{error:rt}}o(Dt,"resolveWorkspaceCommand");function u(e,t,n,r={},i){return new Promise(s=>{let a=Dt(e);if("error"in a){s({code:1,stdout:"",stderr:a.error});return}let c=nt(a.command,t,{cwd:n,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:[i===void 0?"ignore":"pipe","pipe","pipe"]}),d=[],p=[];i!==void 0&&c.stdin?.end(i),c.stdout?.on("data",h=>d.push(h)),c.stderr?.on("data",h=>p.push(h)),c.on("error",h=>{s({code:1,stdout:"",stderr:h.message})}),c.on("close",h=>{s({code:h??1,stdout:Buffer.concat(d).toString("utf8"),stderr:Buffer.concat(p).toString("utf8")})})})}o(u,"runCommand");function Gt(e){return!!(e&&e.includes(rt.slice(0,80)))}o(Gt,"isMacOSGitDeveloperToolsMissing");async function Se(e){await Bt.mkdir(e,{recursive:!0});let t=await u("git",["--version"],e);if(t.code===0)return{ok:!0,command:T??"git",version:(t.stdout||t.stderr).trim()};let n=t.stderr.trim()||t.stdout.trim()||"Git is required for OpenPond app workspaces.";return{ok:!1,error:n,installAction:process.platform==="darwin"&&Gt(n)?"macos_command_line_tools":"manual_git_install"}}o(Se,"checkWorkspaceGitAvailability");function ye(){if(process.platform!=="darwin")return{ok:!1,error:"Apple Command Line Tools installation is only available on macOS."};if(it())return{ok:!0,message:"Apple Command Line Tools already appear to be installed."};try{return nt("/usr/bin/xcode-select",["--install"],{detached:!0,stdio:"ignore"}).unref(),{ok:!0,message:"Opened the Apple Command Line Tools installer."}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}o(ye,"startMacOSCommandLineToolsInstall");import{promises as k}from"node:fs";import m from"node:path";var st=24e3,ot=8e4,It=512*1024,ct=15*1024*1024,Tt=20*1024*1024,Mt=new Set([".cache",".eggs",".git",".ipynb_checkpoints",".mypy_cache",".next",".nox",".nuxt",".openpond",".output",".parcel-cache",".pytest_cache",".pyre",".ruff_cache",".svelte-kit",".tox",".turbo",".venv","__pycache__","artifacts","build","coverage","dist","env","node_modules","out","site-packages","target","venv","volumes"]),zt=new Set([".7z",".avif",".db",".doc",".docx",".gif",".gz",".ico",".jpeg",".jpg",".mov",".mp4",".pdf",".png",".sqlite",".tar",".webp",".xls",".xlsm",".xlsx",".zip"]),$t=new Map([[".avif","image/avif"],[".gif","image/gif"],[".jpeg","image/jpeg"],[".jpg","image/jpeg"],[".png","image/png"],[".webp","image/webp"]]),Nt=new Map([[".m4v","video/x-m4v"],[".mov","video/quicktime"],[".mp4","video/mp4"],[".webm","video/webm"]]),Ht=new Set([".doc",".docx",".pdf"]);function Ut(e){return e.replace(/[^a-zA-Z0-9._-]/g,"-").slice(0,120)||"app"}o(Ut,"safeAppSegment");function N(e){if(!e)return"unknown";try{let t=new URL(e).hostname.toLowerCase();if(t==="github.com"||t.endsWith(".github.com"))return"github";if(t==="openpond.ai"||t.endsWith(".openpond.ai"))return"openpond"}catch{return"unknown"}return"local_git"}o(N,"sourceFromRemote");function $(e){return e.replace(/x-access-token:[^@]+@/g,"x-access-token:***@").replace(/Authorization:\s*Basic\s+[A-Za-z0-9+/=]+/gi,"Authorization: Basic ***")}o($,"redactRemoteUrl");async function G(e){try{return await k.access(e),!0}catch{return!1}}o(G,"pathExists");async function O(e){return await G(e)?(await u("git",["rev-parse","--git-dir"],e)).code===0:!1}o(O,"isGitRepo");function X(e){return e.length<=st?e:`${e.slice(0,st)}
2
+ import{d as F}from"./chunk-WJD5NVVH.js";import{a as o}from"./chunk-FTQLQJQV.js";import{spawn as nt,spawnSync as At}from"node:child_process";import{accessSync as vt,constants as Rt,existsSync as _t,promises as Bt}from"node:fs";import et from"node:path";var rt="Git is required for OpenPond app workspaces, but macOS reports Apple Command Line Tools are not installed. OpenPond skipped /usr/bin/git to avoid opening the Xcode installer prompt. Install Command Line Tools with `xcode-select --install`, install Git from Homebrew, or put a non-Apple git binary earlier on PATH.",T;function Lt(e){try{return _t(e)?(vt(e,Rt.X_OK),!0):!1}catch{return!1}}o(Lt,"isExecutable");function Ot(){let e=(process.env.PATH??"").split(et.delimiter).map(t=>t.trim()).filter(Boolean);for(let t of e){let n=et.join(t,"git");if(!(n==="/usr/bin/git"||n==="/bin/git")&&Lt(n))return n}return null}o(Ot,"firstNonAppleGitOnPath");function it(){let e=At("/usr/bin/xcode-select",["-p"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return e.status===0&&!!e.stdout.trim()}o(it,"appleDeveloperToolsAvailable");function Dt(e){if(e!=="git"||process.platform!=="darwin")return{command:e};if(T!==void 0)return{command:T};let t=Ot();return t?(T=t,{command:t}):it()?(T="git",{command:"git"}):{error:rt}}o(Dt,"resolveWorkspaceCommand");function u(e,t,n,r={},i){return new Promise(s=>{let a=Dt(e);if("error"in a){s({code:1,stdout:"",stderr:a.error});return}let c=nt(a.command,t,{cwd:n,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:[i===void 0?"ignore":"pipe","pipe","pipe"]}),d=[],p=[];i!==void 0&&c.stdin?.end(i),c.stdout?.on("data",h=>d.push(h)),c.stderr?.on("data",h=>p.push(h)),c.on("error",h=>{s({code:1,stdout:"",stderr:h.message})}),c.on("close",h=>{s({code:h??1,stdout:Buffer.concat(d).toString("utf8"),stderr:Buffer.concat(p).toString("utf8")})})})}o(u,"runCommand");function Gt(e){return!!(e&&e.includes(rt.slice(0,80)))}o(Gt,"isMacOSGitDeveloperToolsMissing");async function Se(e){await Bt.mkdir(e,{recursive:!0});let t=await u("git",["--version"],e);if(t.code===0)return{ok:!0,command:T??"git",version:(t.stdout||t.stderr).trim()};let n=t.stderr.trim()||t.stdout.trim()||"Git is required for OpenPond app workspaces.";return{ok:!1,error:n,installAction:process.platform==="darwin"&&Gt(n)?"macos_command_line_tools":"manual_git_install"}}o(Se,"checkWorkspaceGitAvailability");function ye(){if(process.platform!=="darwin")return{ok:!1,error:"Apple Command Line Tools installation is only available on macOS."};if(it())return{ok:!0,message:"Apple Command Line Tools already appear to be installed."};try{return nt("/usr/bin/xcode-select",["--install"],{detached:!0,stdio:"ignore"}).unref(),{ok:!0,message:"Opened the Apple Command Line Tools installer."}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}o(ye,"startMacOSCommandLineToolsInstall");import{promises as k}from"node:fs";import m from"node:path";var st=24e3,ot=8e4,It=512*1024,ct=15*1024*1024,Tt=20*1024*1024,Mt=new Set([".cache",".eggs",".git",".ipynb_checkpoints",".mypy_cache",".next",".nox",".nuxt",".openpond",".output",".parcel-cache",".pytest_cache",".pyre",".ruff_cache",".svelte-kit",".tox",".turbo",".venv","__pycache__","artifacts","build","coverage","dist","env","node_modules","out","site-packages","target","venv","volumes"]),zt=new Set([".7z",".avif",".db",".doc",".docx",".gif",".gz",".ico",".jpeg",".jpg",".mov",".mp4",".pdf",".png",".sqlite",".tar",".webp",".xls",".xlsm",".xlsx",".zip"]),$t=new Map([[".avif","image/avif"],[".gif","image/gif"],[".jpeg","image/jpeg"],[".jpg","image/jpeg"],[".png","image/png"],[".webp","image/webp"]]),Nt=new Map([[".m4v","video/x-m4v"],[".mov","video/quicktime"],[".mp4","video/mp4"],[".webm","video/webm"]]),Ht=new Set([".doc",".docx",".pdf"]);function Ut(e){return e.replace(/[^a-zA-Z0-9._-]/g,"-").slice(0,120)||"app"}o(Ut,"safeAppSegment");function N(e){if(!e)return"unknown";try{let t=new URL(e).hostname.toLowerCase();if(t==="github.com"||t.endsWith(".github.com"))return"github";if(t==="openpond.ai"||t.endsWith(".openpond.ai"))return"openpond"}catch{return"unknown"}return"local_git"}o(N,"sourceFromRemote");function $(e){return e.replace(/x-access-token:[^@]+@/g,"x-access-token:***@").replace(/Authorization:\s*Basic\s+[A-Za-z0-9+/=]+/gi,"Authorization: Basic ***")}o($,"redactRemoteUrl");async function G(e){try{return await k.access(e),!0}catch{return!1}}o(G,"pathExists");async function O(e){return await G(e)?(await u("git",["rev-parse","--git-dir"],e)).code===0:!1}o(O,"isGitRepo");function X(e){return e.length<=st?e:`${e.slice(0,st)}
3
3
 
4
4
  [diff truncated]`}o(X,"truncatePatch");function jt(e){return e.length<=ot?e:`${e.slice(0,ot)}
5
5
 
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{fa as Te,ha as L,ia as qe,ja as Oe,na as P,oa as Ce}from"./chunk-PCAHFOCQ.js";import{Ja as je,Ka as Pe,ce as Ae}from"./chunk-77BXXOHW.js";import{b as N}from"./chunk-L3KS6MOV.js";import{Ba as te,Ca as Ee,j as Ie,m as Se,p as He,r as D,s as C,t as xe,w as Z,y as ee}from"./chunk-5BFWDFPX.js";import{Bb as ye,c as ve,e as Y,f as be,g as ke,i as Re,u as de,v as X,w as V}from"./chunk-IFP6W4OW.js";import{b as e}from"./chunk-ES2ISFJC.js";import{a as Q,c as le,f as ge,h as E}from"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import M from"node:path";import{AsyncLocalStorage as kt}from"node:async_hooks";import{promises as _e}from"node:fs";var $e=new kt;function er(r,t=!1){let n=$e.getStore();n&&(t&&(n.length=0),n.push(r))}i(er,"onStartupFailure");async function tr(r,t){await ye(r);let n;try{n=await ke(M.join(E(r).runtime,"server-owner"),100)}catch(o){if(o instanceof le&&o.issue.code==="STORAGE_BUSY"){let a=await Re(M.join(E(r).runtime,"endpoint.json"),()=>null);throw new le({code:"RUNTIME_ALREADY_RUNNING",path:r,message:"An OpenPond runtime already owns this home.",action:a?.url?`Connect to the existing runtime at ${a.url}, or stop it before starting another.`:"Stop the existing runtime before starting another with this home."})}throw o}let s=[];try{let o=await Q(r,()=>$e.run(s,t)),a=o.close.bind(o);s.length=0;let c;return{...o,close:i(()=>c??=(async()=>{try{await Q(r,a)}finally{await _e.rm(M.join(E(r).runtime,"endpoint.json"),{force:!0}),await n()}})(),"close")}}catch(o){try{for(let a of s.reverse())await Promise.resolve().then(()=>Q(r,a)).catch(()=>{});await _e.rm(M.join(E(r).runtime,"endpoint.json"),{force:!0})}finally{await n()}throw o}}i(tr,"ownHomeRuntime");async function rr(r,t,n){await Y(M.join(E(r).runtime,"endpoint.json"),JSON.stringify({schemaVersion:"openpond.runtimeEndpoint.v1",pid:process.pid,url:t,serverId:n}))}i(rr,"publishRuntimeEndpoint");function or(r){if(!r.maxContextTokens||!r.usableContextTokens)return{shouldCompact:!1,projectedTokens:r.projectedTokens,thresholdTokens:Number.MAX_SAFE_INTEGER,usableContextTokens:0,maxContextTokens:0,tokenSource:"heuristic"};let t=Math.max(.01,Math.min(1,(r.triggerPercent??85)/100)),n=Math.max(1,Math.floor(r.usableContextTokens*t));return{shouldCompact:r.projectedTokens>=n,projectedTokens:r.projectedTokens,thresholdTokens:n,usableContextTokens:r.usableContextTokens,maxContextTokens:r.maxContextTokens,tokenSource:"heuristic"}}i(or,"agentCompactionDecision");async function ar(r){await r.started();try{return await r.compact()}catch(t){throw await r.failed(t),t}}i(ar,"runAgentCompaction");async function ir(r){let t=r.host.projectEvents(r.events),n=r.host.selectEvents(t,r.maxContextTokens),{summaryEvents:s,preservedEvents:o,preservedEventIds:a}=n;if(s.length===0)throw new Error("There is not enough prior context to compact.");let c=r.host.normalizeRecords(s),u=r.host.normalizeRecords(o),h=r.host.buildFileLedger(r.host.normalizeRecords(t)),f=r.host.serializeRecords(c,r.host.inputCharBudget(r.maxContextTokens));if(!f.text.trim())throw new Error("There is not enough prior context to compact.");let k=r.host.buildSummaryMessages({serializedHistory:f.text,fileLedger:h}),d=Date.now(),R=(await r.host.streamSummary({model:r.model,messages:k,signal:r.signal})).trim(),v=Date.now()-d;if(!R)throw new Error("Compaction summary was empty.");let w=r.host.estimateProjection({events:t,preservedEvents:o,summary:R}),p=r.host.createMetrics({sourceEvents:t.length,summarizedEvents:s.length,preservedEvents:o.length,sourceRecords:f.sourceRecordCount,includedRecords:f.includedRecordCount,omittedRecords:f.omittedRecordCount,preservedRecords:u.length,truncatedRecords:f.truncatedRecordCount,summaryInputTruncated:f.inputTruncated,sourceSelectionStrategy:f.selectionStrategy,summaryInputChars:f.inputChars,retainedTailTokens:n.retainedTailTokens,retainedTailBudgetTokens:n.retainedTailBudgetTokens,finalProviderContextTokens:w.inputTokensAfter,durationMs:v,fileLedgerEntries:h.length,splitTurnId:n.splitTurnId});return{summary:R,model:r.model,compactedThroughEventId:t[t.length-1]?.id??null,compactedThroughTurnId:r.host.lastTurnId(t),preservedFromEventId:o[0]?.id??null,preservedEventIds:a,preservedResourceRefs:r.host.durableResourceRefs(r.events),sourceEventCount:s.length,preservedEventCount:o.length,fileLedger:h,inputTokensBefore:w.inputTokensBefore,inputTokensAfter:w.inputTokensAfter,maxContextTokens:r.maxContextTokens,tokenSource:"heuristic",metrics:p}}i(ir,"runAgentCompactionProgram");var re="2026-09-20",ur=["initialize","initialized","runtime/capabilities","thread/start","thread/resume","thread/read","turn/start","turn/steer","task/inbox","task/queue","task/inputUpdate","turn/interrupt","approval/resolve","userInput/resolve","profile/workflows","profile/evaluations","profile/trainingSource","profile/evaluations/prepare","profile/evaluations/run","profile/evaluations/runSuite","profile/evaluations/executeCase","profile/evaluations/executeRun","profile/evaluations/compare","profile/evaluations/report","harness/inspect","harness/proposalReview","harness/review","harness/acceptEvaluationReview","harness/materializeEvaluationTaskset","harness/runEvaluationBaseline","harness/validate","harness/backgroundReview","harness/diff","harness/rollback","refiner/inspect","refiner/update","refiner/activate","refiner/rollback"],ze=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),We=e.object({jsonrpc:e.literal("2.0"),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),ue=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),result:e.unknown()}).strict(),pe=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number(),e.null()]),error:e.object({code:e.number().int(),message:e.string(),data:e.unknown().optional()}).strict()}).strict(),pr=e.union([ze,We,ue,pe]),Rt=e.object({protocolVersion:e.string().trim().min(1),client:e.object({name:e.string().trim().min(1),version:e.string().trim().min(1)}).strict(),capabilities:e.record(e.string(),e.unknown()).default({})}).strict(),ne=class{static{i(this,"AgentJsonRpcDispatcher")}#e;#t=null;#r=!1;constructor(t){this.#e=t}get initialized(){return this.#r}async handle(t){let n=We.safeParse(t);if(n.success&&!("id"in t)){if(n.data.method==="initialized"){if(!this.#t)throw new T(-32002,"initialize must be called first");this.#r=!0}return null}let s=ze.safeParse(t);if(!s.success)return Ve(null,-32600,"Invalid Request",s.error.flatten());let o=s.data;try{let a=await this.#n(o.method,o.params);return{jsonrpc:"2.0",id:o.id,result:a}}catch(a){let c=a instanceof T?a:new T(-32603,a instanceof Error?a.message:String(a));return Ve(o.id,c.code,c.message,c.data)}}async#n(t,n){if(t==="initialize"){let s=Rt.parse(n);if(s.protocolVersion!==re)throw new T(-32001,"Incompatible agent protocol version",{requested:s.protocolVersion,supported:re});return this.#t=s,{protocolVersion:re,server:{name:"openpond-app-server",version:"1"},capabilities:await this.#e.capabilities()}}if(!this.#r)throw new T(-32002,"initialized notification is required");switch(t){case"runtime/capabilities":return this.#e.capabilities(n);case"thread/start":return this.#e.threadStart(n);case"thread/resume":return this.#e.threadResume(n);case"thread/read":return this.#e.threadRead(n);case"turn/start":return this.#e.turnStart(n);case"turn/steer":return this.#e.turnSteer(n);case"task/inbox":return this.#e.taskInbox(n);case"task/queue":return this.#e.taskQueue(n);case"task/inputUpdate":return this.#e.taskInputUpdate(n);case"turn/interrupt":return this.#e.turnInterrupt(n);case"approval/resolve":return this.#e.approvalResolve(n);case"userInput/resolve":return this.#e.userInputResolve(n);case"profile/workflows":return this.#e.profileWorkflows(n);case"profile/evaluations":return this.#e.profileEvaluations(n);case"profile/trainingSource":return this.#e.profileTrainingSource(n);case"profile/evaluations/prepare":return this.#e.profileEvaluationPrepare(n);case"profile/evaluations/run":return this.#e.profileEvaluationRun(n);case"profile/evaluations/runSuite":return this.#e.profileEvaluationRunSuite(n);case"profile/evaluations/executeCase":return this.#e.profileEvaluationExecuteCase(n);case"profile/evaluations/executeRun":return this.#e.profileEvaluationExecuteRun(n);case"profile/evaluations/compare":return this.#e.profileEvaluationCompare(n);case"profile/evaluations/report":return this.#e.profileEvaluationReport(n);case"harness/inspect":return this.#e.harnessInspect(n);case"harness/proposalReview":return this.#e.harnessProposalReview(n);case"harness/review":return this.#e.harnessReview(n);case"harness/acceptEvaluationReview":return this.#e.harnessAcceptEvaluationReview(n);case"harness/materializeEvaluationTaskset":return this.#e.harnessMaterializeEvaluationTaskset(n);case"harness/runEvaluationBaseline":return this.#e.harnessRunEvaluationBaseline(n);case"harness/validate":return this.#e.harnessValidate(n);case"harness/backgroundReview":return this.#e.harnessBackgroundReview(n);case"harness/diff":return this.#e.harnessDiff(n);case"harness/rollback":return this.#e.harnessRollback(n);case"refiner/inspect":return this.#e.refinerInspect(n);case"refiner/update":return this.#e.refinerUpdate(n);case"refiner/activate":return this.#e.refinerActivate(n);case"refiner/rollback":return this.#e.refinerRollback(n);default:throw new T(-32601,`Method not found: ${t}`)}}},T=class extends Error{static{i(this,"JsonRpcDispatchError")}code;data;constructor(t,n,s){super(n),this.code=t,this.data=s}};function Ve(r,t,n,s){return{jsonrpc:"2.0",id:r,error:{code:t,message:n,...s===void 0?{}:{data:s}}}}i(Ve,"jsonRpcError");var m=e.string().trim().min(1).max(200),se=e.string().trim().min(1).max(32e3),B=e.number().int().nonnegative(),De=e.object({id:m,sessionId:m,senderSessionId:m.nullable(),senderKind:e.enum(["user","task","runtime"]),kind:e.enum(["steer","message","followup","queued","result"]),body:se,payload:e.record(e.string(),e.unknown()),idempotencyKey:m,replyTo:m.nullable(),expectedTurnId:m.nullable()}).strict(),yt=e.discriminatedUnion("action",[e.object({action:e.literal("resume"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("cancel"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("edit"),expectedRevision:e.number().int().positive(),body:se}).strict(),e.object({action:e.literal("steer"),expectedRevision:e.number().int().positive(),expectedTurnId:m}).strict()]),Ne=e.object({id:m,sessionId:m,turnId:m,targetSessionId:m.nullable(),targetTurnId:m.nullable(),targetInputId:m.nullable(),afterSequence:B,deadline:e.string(),state:e.enum(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:e.string(),updatedAt:e.string()}).strict(),Le=e.record(e.string(),e.unknown()),It=e.enum(["queued","running","completed","failed","cancelled","needs_resume"]),St=e.object({parentSessionId:m.nullable().optional(),childSessionId:m.nullable().optional(),status:e.array(It).nullable().optional(),afterId:e.string().max(200),limit:e.number().int().min(1).max(10)}).strict(),Me=e.discriminatedUnion("action",[e.object({action:e.literal("recoverTaskInboxOwners"),ownerId:m}).strict(),e.object({action:e.literal("hasTaskCompletion"),turnId:m}).strict(),e.object({action:e.literal("taskInboxSnapshot"),sessionId:m}).strict(),e.object({action:e.literal("taskInboxSnapshotInputs"),sessionId:m,afterSequence:B}).strict(),e.object({action:e.literal("declareTaskWork"),sessionId:m,turnId:m,ownerId:m,areas:e.array(se).max(100)}).strict(),e.object({action:e.literal("taskWorkAreas"),sessionId:m}).strict(),e.object({action:e.literal("admitTaskInput"),input:De}).strict(),e.object({action:e.literal("admitTaskInputs"),inputs:e.array(De).max(50)}).strict(),e.object({action:e.literal("rejectTaskInput"),id:m,error:se}).strict(),e.object({action:e.literal("getTaskInput"),id:m}).strict(),e.object({action:e.literal("taskInputsForSession"),sessionId:m,query:e.object({afterSequence:B.optional(),pendingOnly:e.boolean().optional(),limit:e.number().int().min(1).max(500).optional()}).strict()}).strict(),e.object({action:e.literal("mutateTaskInput"),sessionId:m,inputId:m,change:yt}).strict(),e.object({action:e.literal("openTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("renewTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("pendingTaskInputs"),sessionId:m,turnId:m,afterSequence:B}).strict(),e.object({action:e.literal("taskAssignmentInputs"),turnId:m,afterSequence:B}).strict(),e.object({action:e.literal("pauseTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("includeTaskInputs"),sessionId:m,turnId:m,ownerId:m,requestId:m}).strict(),e.object({action:e.literal("settleTaskInputRequest"),requestId:m,outcome:e.enum(["resolved","failed","replaced"])}).strict(),e.object({action:e.literal("sealTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("sealNativeTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("closeTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m,outcome:e.enum(["completed","failed","interrupted"])}).strict(),e.object({action:e.literal("taskInboxPaused"),sessionId:m}).strict(),e.object({action:e.literal("reserveTaskFollowup"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("taskInboxWakeTargets"),afterSessionId:e.string().max(200)}).strict(),e.object({action:e.literal("createTaskWait"),value:Ne}).strict(),e.object({action:e.literal("settleTaskWait"),id:m,state:Ne.shape.state}).strict(),e.object({action:e.literal("taskWaitsForSession"),sessionId:m,afterId:e.string().max(200)}).strict(),e.object({action:e.literal("commitSubagentCompletion"),value:Le,turnId:m}).strict(),e.object({action:e.literal("pendingTaskCompletions"),afterTurnId:e.string().max(200)}).strict(),e.object({action:e.literal("settleTaskCompletion"),turnId:m,inputId:m}).strict(),e.object({action:e.literal("upsertSubagentRun"),value:Le}).strict(),e.object({action:e.literal("getSubagentRun"),id:m}).strict(),e.object({action:e.literal("listSubagentRuns"),query:St}).strict()]);var oe=e.string().trim().min(1).max(191),Be=e.object({createdAt:e.string().min(1),id:oe}).strict(),Fe=e.enum(["trigger_decision","route_decision","refiner_outcome","proposal","targeted_validation","apply_receipt"]),Ue=e.discriminatedUnion("action",[e.object({action:e.literal("put_artifact"),workspaceId:oe,kind:Fe,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:oe,kind:Fe,before:Be.nullable(),limit:e.number().int().min(1).max(200)}).strict(),e.object({action:e.literal("pending_trigger_page"),workspaceId:oe,before:Be.nullable(),limit:e.number().int().min(1).max(200)}).strict()]);var A=e.string().trim().min(1).max(200),Je=e.string().regex(/^[a-f0-9]{64}$/),Ht=e.object({kind:e.enum(["structural","visual","test","user_review"]),status:e.enum(["passed","failed","not_run"]),label:e.string().trim().min(1).max(240),detail:e.string().trim().max(4e3).nullable().optional(),ref:e.string().trim().max(4096).nullable().optional()}),Ke=e.object({id:A,title:e.string().trim().min(1).max(240),sourceTaskId:A,sourceTurnId:A,revision:e.number().int().positive(),createdAt:e.string().datetime(),contentType:e.string().trim().min(1).max(200),sizeBytes:e.number().int().min(1).max(1e7),sha256:Je,validation:e.array(Ht).max(32)}).strict(),Ge=e.object({sessionId:A,turnId:A,output:Ke}).strict(),Qe=e.object({uploadId:A,index:e.number().int().min(0).max(1024),offset:e.number().int().min(0).max(1e7),sha256:Je,contentsBase64:e.string().min(1).max(131072)}).strict(),Ye=e.object({uploadId:A}).strict(),xt=Ke.pick({id:!0,title:!0,sourceTaskId:!0,sourceTurnId:!0,revision:!0,createdAt:!0,validation:!0}),Xe=e.object({sessionId:A,turnId:A,output:xt,sandboxPath:e.string().trim().min(1).max(4096)}).strict();var F=e.string().trim().min(1).max(200),Et=e.object({type:e.enum(["create","get","start","stop","exec","open_port","list_files","download_file","upload_file","search_files","delete_file","stat_file","mkdir","move_file","process_start","process_get","git_status","git_diff","git_export_patch","git_branch","git_commit","git_pull","git_push"]),sandboxId:F.optional(),payload:e.unknown().optional(),processId:F.optional(),failOnUnpreservedChanges:e.boolean().optional()}).strict().superRefine((r,t)=>{r.type!=="create"&&!r.sandboxId&&t.addIssue({code:"custom",message:"Sandbox identity is required."}),r.type==="process_get"&&!r.processId&&t.addIssue({code:"custom",message:"Process identity is required."})}),Ze=e.object({action:Et}).strict(),et=e.object({sessionId:F,turnId:F,name:F}).strict();var g=1,l=e.string().trim().min(1).max(191),q=e.number().int().min(1).max(200),jr=e.object({teamId:l,ownerUserId:l,workspaceId:l,conversationId:l,turnId:l,attempt:e.number().int().min(1),leaseGeneration:e.number().int().min(1)}).strict(),tt=e.discriminatedUnion("operation",[e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("sandbox/request"),params:Ze}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("embedding/authorize"),params:et}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/begin"),params:Ge}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/chunk"),params:Qe}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/complete"),params:Ye}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/saveSandboxFile"),params:Xe}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("settings/get"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/get"),params:e.object({reference:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/overlay/get"),params:e.object({runId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/overlay/put"),params:e.object({runId:l,expectedRevision:e.number().int().min(0).nullable(),overlay:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/overlay/freezeProposal"),params:e.object({runId:l,expectedRevision:e.number().int().min(0),overlay:e.record(e.string(),e.unknown()),proposal:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/get"),params:e.object({workspaceId:l,key:e.string().min(1).max(120)}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/list"),params:e.object({workspaceId:l,includeDeleted:e.boolean(),before:e.object({updatedAt:e.string(),key:e.string()}).strict().nullable(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/search"),params:e.object({workspaceId:l,query:e.string().trim().min(1).max(500),limit:e.number().int().min(1).max(20)}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/write"),params:e.object({input:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/state/read"),params:e.object({workspaceId:l,kind:e.enum(["selection","workspace_settings","evaluation_review_settings","candidates","cross_run_requests"]),afterId:l.nullable(),limit:e.number().int().min(1).max(100)}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/workspace/transition"),params:e.discriminatedUnion("action",[e.object({action:e.literal("advance"),receiptId:l,workspaceId:l,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),now:e.string()}).strict(),e.object({action:e.literal("reviewedAdvance"),receiptId:l,workspaceId:l,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),reviewer:l,now:e.string()}).strict(),e.object({action:e.literal("rollback"),receiptId:l,workspaceId:l,expectedWorkspaceRevision:e.number().int().nonnegative(),expectedChannelRevision:e.number().int().nonnegative(),targetRelease:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),targetSourceRevision:e.string().min(1),rollbackOf:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),now:e.string()}).strict()])}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("task-inbox/execute"),params:Me}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("refiner/execute"),params:e.object({action:Ue}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("create-improve/execute"),params:e.discriminatedUnion("action",[e.object({action:e.literal("get"),runId:l}).strict(),e.object({action:e.literal("page"),query:e.object({profileId:l.nullable(),targetKind:l.nullable(),targetId:l.nullable(),state:e.array(l).max(20)}).strict(),before:e.object({updatedAt:e.string(),id:l}).strict().nullable(),limit:q}).strict(),e.object({action:e.literal("put"),run:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("mutate"),mutation:e.record(e.string(),e.unknown()),next:e.record(e.string(),e.unknown())}).strict()])}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("approval/get"),params:e.object({approvalId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("approval/upsert"),params:e.object({approval:e.record(e.string(),e.unknown()),expectedRevision:e.number().int().min(1).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("usage/getByRequestId"),params:e.object({requestId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("usage/upsert"),params:e.object({record:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("usage/page"),params:e.object({query:e.object({sessionId:l.optional(),turnId:l.optional(),provider:l.optional(),model:l.optional(),startedAtFrom:e.string().optional(),startedAtTo:e.string().optional(),visibility:e.enum(["user_facing","background","system"]).optional(),status:e.enum(["started","completed","failed","interrupted","missing"]).optional()}).strict(),before:e.object({startedAt:e.string(),requestOrdinal:e.number().int().min(0),id:l}).strict().nullable(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("capabilities"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/count"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/get"),params:e.object({sessionId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/page"),params:e.object({afterId:l.nullable(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/put"),params:e.object({sessionId:l,expectedRevision:e.number().int().min(1).nullable(),session:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/count"),params:e.object({sessionId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/wakeCount"),params:e.object({sessionId:l,key:e.enum(["messageId","fromRunId"]),value:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/get"),params:e.object({turnId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/put"),params:e.object({sessionId:l,turnId:l,expectedRevision:e.number().int().min(1).nullable(),turn:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/latest"),params:e.object({sessionId:l,status:e.enum(["in_progress","completed","failed","interrupted"]).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/page"),params:e.object({sessionId:l,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("thread/turnPage"),params:e.object({sessionId:l,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("event/append"),params:e.object({event:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("events/page"),params:e.object({sessionId:l.nullable(),afterSequence:e.number().int().min(0),beforeSequence:e.number().int().min(1).nullable().optional(),limit:q,excludeReasoningDeltas:e.boolean().optional()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("events/latestAssistantText"),params:e.object({sessionId:l}).strict()}).strict()]),Pr=e.object({contractVersion:e.literal(g),operations:e.array(e.enum(["sandbox/request","embedding/authorize","output/begin","output/chunk","output/complete","output/saveSandboxFile","settings/get","harness/get","harness/overlay/get","harness/overlay/put","harness/overlay/freezeProposal","harness/memory/get","harness/memory/list","harness/memory/search","harness/memory/write","harness/state/read","harness/workspace/transition","task-inbox/execute","refiner/execute","create-improve/execute","approval/get","approval/upsert","usage/getByRequestId","usage/upsert","usage/page","session/count","session/get","session/page","session/put","turn/count","turn/wakeCount","turn/get","turn/put","turn/latest","turn/page","thread/turnPage","event/append","events/page","events/latestAssistantText"])).max(40),allowedTools:e.array(l).max(128),maxPageSize:q,maxRequestBytes:e.number().int().min(1).max(1e6),maxInFlight:e.number().int().min(1).max(64)}).strict();var rt=class{static{i(this,"AgentHostStorageClient")}#e=new Map;#t=null;#r=1;bind(t){if(this.#t)throw new Error("Host storage client is already bound.");this.#t=t}async request(t,n=15e3){let s=tt.parse(t);if(!this.#t)throw new Error("Host storage transport is unavailable.");if(this.#e.size>=32)throw new Error("Host storage request limit exceeded.");let o=`host-storage:${this.#r++}`,a={jsonrpc:"2.0",id:o,method:"host/storage",params:s};if(Buffer.byteLength(JSON.stringify(a))>256e3)throw new Error("Host storage request is too large.");let c=new Promise((u,h)=>{let f=setTimeout(()=>{this.#e.delete(o),h(new Error("Host storage request timed out."))},Math.max(1,Math.min(6e4,n)));this.#e.set(o,{resolve:u,reject:h,timer:f})});try{await this.#t(a)}catch(u){let h=this.#e.get(o);h&&(clearTimeout(h.timer),this.#e.delete(o),h.reject(u instanceof Error?u:new Error(String(u))))}return c}accept(t){let n=ue.safeParse(t),s=n.success?null:pe.safeParse(t),o=n.success?n.data:s?.success?s.data:null;if(!o||typeof o.id!="string"||!o.id.startsWith("host-storage:"))return!1;let a=this.#e.get(o.id);return a?(clearTimeout(a.timer),this.#e.delete(o.id),Buffer.byteLength(JSON.stringify(o))>1e6?(a.reject(new Error("Host storage response is too large.")),!0):("error"in o?a.reject(new Error(`Host storage request failed: ${o.error.message}`)):a.resolve(o.result),!0)):!0}close(){this.#t=null;for(let t of this.#e.values())clearTimeout(t.timer),t.reject(new Error("Host storage transport closed."));this.#e.clear()}};import{createHash as jt}from"node:crypto";function me(r){if(r===null||typeof r=="boolean"||typeof r=="string")return r;if(typeof r=="number"){if(!Number.isFinite(r))throw new Error("Canonical JSON cannot encode a non-finite number.");return r}if(Array.isArray(r))return r.map(me);if(typeof r=="object"){let t={};for(let n of Object.keys(r).sort()){let s=r[n];s!==void 0&&(t[n]=me(s))}return t}throw new Error(`Canonical JSON cannot encode ${typeof r}.`)}i(me,"canonicalJson");function z(r){return jt("sha256").update(JSON.stringify(me(r)),"utf8").digest("hex")}i(z,"canonicalHash");var Pt=e.enum(["thread.started","thread.resumed","turn.started","turn.steered","turn.interrupted","turn.completed","turn.failed","item.started","item.delta","item.completed","assistant.reasoning.delta","assistant.delta","tool.started","tool.completed","approval.requested","approval.resolved","user_input.requested","user_input.resolved","compaction.started","compaction.completed","harness.admitted","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","diagnostic"]),At=e.object({sequence:e.number().int().nonnegative(),name:Pt,source:e.enum(["runtime","provider","tool","host","refiner"]),status:e.string().trim().min(1).nullable().default(null),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1).nullable().default(null),callId:e.string().trim().min(1).nullable().default(null),output:e.string().nullable().default(null),error:e.string().nullable().default(null),data:e.record(e.string(),e.unknown()).default({})}).strict();function Dr(r){return z(At.parse(r))}i(Dr,"canonicalEventHash");import{once as Tt}from"node:events";import{createInterface as qt}from"node:readline";async function nt(r){let t=null,n=Promise.resolve(),s=[],o=i(w=>(n=n.then(async()=>{r.writable.write(`${JSON.stringify(w)}
2
+ import{fa as Te,ha as L,ia as qe,ja as Oe,na as P,oa as Ce}from"./chunk-UOPUBKJ4.js";import{Ja as je,Ka as Pe,ce as Ae}from"./chunk-77BXXOHW.js";import{b as N}from"./chunk-L3KS6MOV.js";import{Ba as te,Ca as Ee,j as Ie,m as Se,p as He,r as D,s as C,t as xe,w as Z,y as ee}from"./chunk-5BFWDFPX.js";import{Bb as ye,c as ve,e as Y,f as be,g as ke,i as Re,u as de,v as X,w as V}from"./chunk-IFP6W4OW.js";import{b as e}from"./chunk-ES2ISFJC.js";import{a as Q,c as le,f as ge,h as E}from"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import M from"node:path";import{AsyncLocalStorage as kt}from"node:async_hooks";import{promises as _e}from"node:fs";var $e=new kt;function er(r,t=!1){let n=$e.getStore();n&&(t&&(n.length=0),n.push(r))}i(er,"onStartupFailure");async function tr(r,t){await ye(r);let n;try{n=await ke(M.join(E(r).runtime,"server-owner"),100)}catch(o){if(o instanceof le&&o.issue.code==="STORAGE_BUSY"){let a=await Re(M.join(E(r).runtime,"endpoint.json"),()=>null);throw new le({code:"RUNTIME_ALREADY_RUNNING",path:r,message:"An OpenPond runtime already owns this home.",action:a?.url?`Connect to the existing runtime at ${a.url}, or stop it before starting another.`:"Stop the existing runtime before starting another with this home."})}throw o}let s=[];try{let o=await Q(r,()=>$e.run(s,t)),a=o.close.bind(o);s.length=0;let c;return{...o,close:i(()=>c??=(async()=>{try{await Q(r,a)}finally{await _e.rm(M.join(E(r).runtime,"endpoint.json"),{force:!0}),await n()}})(),"close")}}catch(o){try{for(let a of s.reverse())await Promise.resolve().then(()=>Q(r,a)).catch(()=>{});await _e.rm(M.join(E(r).runtime,"endpoint.json"),{force:!0})}finally{await n()}throw o}}i(tr,"ownHomeRuntime");async function rr(r,t,n){await Y(M.join(E(r).runtime,"endpoint.json"),JSON.stringify({schemaVersion:"openpond.runtimeEndpoint.v1",pid:process.pid,url:t,serverId:n}))}i(rr,"publishRuntimeEndpoint");function or(r){if(!r.maxContextTokens||!r.usableContextTokens)return{shouldCompact:!1,projectedTokens:r.projectedTokens,thresholdTokens:Number.MAX_SAFE_INTEGER,usableContextTokens:0,maxContextTokens:0,tokenSource:"heuristic"};let t=Math.max(.01,Math.min(1,(r.triggerPercent??85)/100)),n=Math.max(1,Math.floor(r.usableContextTokens*t));return{shouldCompact:r.projectedTokens>=n,projectedTokens:r.projectedTokens,thresholdTokens:n,usableContextTokens:r.usableContextTokens,maxContextTokens:r.maxContextTokens,tokenSource:"heuristic"}}i(or,"agentCompactionDecision");async function ar(r){await r.started();try{return await r.compact()}catch(t){throw await r.failed(t),t}}i(ar,"runAgentCompaction");async function ir(r){let t=r.host.projectEvents(r.events),n=r.host.selectEvents(t,r.maxContextTokens),{summaryEvents:s,preservedEvents:o,preservedEventIds:a}=n;if(s.length===0)throw new Error("There is not enough prior context to compact.");let c=r.host.normalizeRecords(s),u=r.host.normalizeRecords(o),h=r.host.buildFileLedger(r.host.normalizeRecords(t)),f=r.host.serializeRecords(c,r.host.inputCharBudget(r.maxContextTokens));if(!f.text.trim())throw new Error("There is not enough prior context to compact.");let k=r.host.buildSummaryMessages({serializedHistory:f.text,fileLedger:h}),d=Date.now(),R=(await r.host.streamSummary({model:r.model,messages:k,signal:r.signal})).trim(),v=Date.now()-d;if(!R)throw new Error("Compaction summary was empty.");let w=r.host.estimateProjection({events:t,preservedEvents:o,summary:R}),p=r.host.createMetrics({sourceEvents:t.length,summarizedEvents:s.length,preservedEvents:o.length,sourceRecords:f.sourceRecordCount,includedRecords:f.includedRecordCount,omittedRecords:f.omittedRecordCount,preservedRecords:u.length,truncatedRecords:f.truncatedRecordCount,summaryInputTruncated:f.inputTruncated,sourceSelectionStrategy:f.selectionStrategy,summaryInputChars:f.inputChars,retainedTailTokens:n.retainedTailTokens,retainedTailBudgetTokens:n.retainedTailBudgetTokens,finalProviderContextTokens:w.inputTokensAfter,durationMs:v,fileLedgerEntries:h.length,splitTurnId:n.splitTurnId});return{summary:R,model:r.model,compactedThroughEventId:t[t.length-1]?.id??null,compactedThroughTurnId:r.host.lastTurnId(t),preservedFromEventId:o[0]?.id??null,preservedEventIds:a,preservedResourceRefs:r.host.durableResourceRefs(r.events),sourceEventCount:s.length,preservedEventCount:o.length,fileLedger:h,inputTokensBefore:w.inputTokensBefore,inputTokensAfter:w.inputTokensAfter,maxContextTokens:r.maxContextTokens,tokenSource:"heuristic",metrics:p}}i(ir,"runAgentCompactionProgram");var re="2026-09-20",ur=["initialize","initialized","runtime/capabilities","thread/start","thread/resume","thread/read","turn/start","turn/steer","task/inbox","task/queue","task/inputUpdate","turn/interrupt","approval/resolve","userInput/resolve","profile/workflows","profile/evaluations","profile/trainingSource","profile/evaluations/prepare","profile/evaluations/run","profile/evaluations/runSuite","profile/evaluations/executeCase","profile/evaluations/executeRun","profile/evaluations/compare","profile/evaluations/report","harness/inspect","harness/proposalReview","harness/review","harness/acceptEvaluationReview","harness/materializeEvaluationTaskset","harness/runEvaluationBaseline","harness/validate","harness/backgroundReview","harness/diff","harness/rollback","refiner/inspect","refiner/update","refiner/activate","refiner/rollback"],ze=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),We=e.object({jsonrpc:e.literal("2.0"),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),ue=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),result:e.unknown()}).strict(),pe=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number(),e.null()]),error:e.object({code:e.number().int(),message:e.string(),data:e.unknown().optional()}).strict()}).strict(),pr=e.union([ze,We,ue,pe]),Rt=e.object({protocolVersion:e.string().trim().min(1),client:e.object({name:e.string().trim().min(1),version:e.string().trim().min(1)}).strict(),capabilities:e.record(e.string(),e.unknown()).default({})}).strict(),ne=class{static{i(this,"AgentJsonRpcDispatcher")}#e;#t=null;#r=!1;constructor(t){this.#e=t}get initialized(){return this.#r}async handle(t){let n=We.safeParse(t);if(n.success&&!("id"in t)){if(n.data.method==="initialized"){if(!this.#t)throw new T(-32002,"initialize must be called first");this.#r=!0}return null}let s=ze.safeParse(t);if(!s.success)return Ve(null,-32600,"Invalid Request",s.error.flatten());let o=s.data;try{let a=await this.#n(o.method,o.params);return{jsonrpc:"2.0",id:o.id,result:a}}catch(a){let c=a instanceof T?a:new T(-32603,a instanceof Error?a.message:String(a));return Ve(o.id,c.code,c.message,c.data)}}async#n(t,n){if(t==="initialize"){let s=Rt.parse(n);if(s.protocolVersion!==re)throw new T(-32001,"Incompatible agent protocol version",{requested:s.protocolVersion,supported:re});return this.#t=s,{protocolVersion:re,server:{name:"openpond-app-server",version:"1"},capabilities:await this.#e.capabilities()}}if(!this.#r)throw new T(-32002,"initialized notification is required");switch(t){case"runtime/capabilities":return this.#e.capabilities(n);case"thread/start":return this.#e.threadStart(n);case"thread/resume":return this.#e.threadResume(n);case"thread/read":return this.#e.threadRead(n);case"turn/start":return this.#e.turnStart(n);case"turn/steer":return this.#e.turnSteer(n);case"task/inbox":return this.#e.taskInbox(n);case"task/queue":return this.#e.taskQueue(n);case"task/inputUpdate":return this.#e.taskInputUpdate(n);case"turn/interrupt":return this.#e.turnInterrupt(n);case"approval/resolve":return this.#e.approvalResolve(n);case"userInput/resolve":return this.#e.userInputResolve(n);case"profile/workflows":return this.#e.profileWorkflows(n);case"profile/evaluations":return this.#e.profileEvaluations(n);case"profile/trainingSource":return this.#e.profileTrainingSource(n);case"profile/evaluations/prepare":return this.#e.profileEvaluationPrepare(n);case"profile/evaluations/run":return this.#e.profileEvaluationRun(n);case"profile/evaluations/runSuite":return this.#e.profileEvaluationRunSuite(n);case"profile/evaluations/executeCase":return this.#e.profileEvaluationExecuteCase(n);case"profile/evaluations/executeRun":return this.#e.profileEvaluationExecuteRun(n);case"profile/evaluations/compare":return this.#e.profileEvaluationCompare(n);case"profile/evaluations/report":return this.#e.profileEvaluationReport(n);case"harness/inspect":return this.#e.harnessInspect(n);case"harness/proposalReview":return this.#e.harnessProposalReview(n);case"harness/review":return this.#e.harnessReview(n);case"harness/acceptEvaluationReview":return this.#e.harnessAcceptEvaluationReview(n);case"harness/materializeEvaluationTaskset":return this.#e.harnessMaterializeEvaluationTaskset(n);case"harness/runEvaluationBaseline":return this.#e.harnessRunEvaluationBaseline(n);case"harness/validate":return this.#e.harnessValidate(n);case"harness/backgroundReview":return this.#e.harnessBackgroundReview(n);case"harness/diff":return this.#e.harnessDiff(n);case"harness/rollback":return this.#e.harnessRollback(n);case"refiner/inspect":return this.#e.refinerInspect(n);case"refiner/update":return this.#e.refinerUpdate(n);case"refiner/activate":return this.#e.refinerActivate(n);case"refiner/rollback":return this.#e.refinerRollback(n);default:throw new T(-32601,`Method not found: ${t}`)}}},T=class extends Error{static{i(this,"JsonRpcDispatchError")}code;data;constructor(t,n,s){super(n),this.code=t,this.data=s}};function Ve(r,t,n,s){return{jsonrpc:"2.0",id:r,error:{code:t,message:n,...s===void 0?{}:{data:s}}}}i(Ve,"jsonRpcError");var m=e.string().trim().min(1).max(200),se=e.string().trim().min(1).max(32e3),B=e.number().int().nonnegative(),De=e.object({id:m,sessionId:m,senderSessionId:m.nullable(),senderKind:e.enum(["user","task","runtime"]),kind:e.enum(["steer","message","followup","queued","result"]),body:se,payload:e.record(e.string(),e.unknown()),idempotencyKey:m,replyTo:m.nullable(),expectedTurnId:m.nullable()}).strict(),yt=e.discriminatedUnion("action",[e.object({action:e.literal("resume"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("cancel"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("edit"),expectedRevision:e.number().int().positive(),body:se}).strict(),e.object({action:e.literal("steer"),expectedRevision:e.number().int().positive(),expectedTurnId:m}).strict()]),Ne=e.object({id:m,sessionId:m,turnId:m,targetSessionId:m.nullable(),targetTurnId:m.nullable(),targetInputId:m.nullable(),afterSequence:B,deadline:e.string(),state:e.enum(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:e.string(),updatedAt:e.string()}).strict(),Le=e.record(e.string(),e.unknown()),It=e.enum(["queued","running","completed","failed","cancelled","needs_resume"]),St=e.object({parentSessionId:m.nullable().optional(),childSessionId:m.nullable().optional(),status:e.array(It).nullable().optional(),afterId:e.string().max(200),limit:e.number().int().min(1).max(10)}).strict(),Me=e.discriminatedUnion("action",[e.object({action:e.literal("recoverTaskInboxOwners"),ownerId:m}).strict(),e.object({action:e.literal("hasTaskCompletion"),turnId:m}).strict(),e.object({action:e.literal("taskInboxSnapshot"),sessionId:m}).strict(),e.object({action:e.literal("taskInboxSnapshotInputs"),sessionId:m,afterSequence:B}).strict(),e.object({action:e.literal("declareTaskWork"),sessionId:m,turnId:m,ownerId:m,areas:e.array(se).max(100)}).strict(),e.object({action:e.literal("taskWorkAreas"),sessionId:m}).strict(),e.object({action:e.literal("admitTaskInput"),input:De}).strict(),e.object({action:e.literal("admitTaskInputs"),inputs:e.array(De).max(50)}).strict(),e.object({action:e.literal("rejectTaskInput"),id:m,error:se}).strict(),e.object({action:e.literal("getTaskInput"),id:m}).strict(),e.object({action:e.literal("taskInputsForSession"),sessionId:m,query:e.object({afterSequence:B.optional(),pendingOnly:e.boolean().optional(),limit:e.number().int().min(1).max(500).optional()}).strict()}).strict(),e.object({action:e.literal("mutateTaskInput"),sessionId:m,inputId:m,change:yt}).strict(),e.object({action:e.literal("openTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("renewTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("pendingTaskInputs"),sessionId:m,turnId:m,afterSequence:B}).strict(),e.object({action:e.literal("taskAssignmentInputs"),turnId:m,afterSequence:B}).strict(),e.object({action:e.literal("pauseTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("includeTaskInputs"),sessionId:m,turnId:m,ownerId:m,requestId:m}).strict(),e.object({action:e.literal("settleTaskInputRequest"),requestId:m,outcome:e.enum(["resolved","failed","replaced"])}).strict(),e.object({action:e.literal("sealTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("sealNativeTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("closeTaskInboxTurn"),sessionId:m,turnId:m,ownerId:m,outcome:e.enum(["completed","failed","interrupted"])}).strict(),e.object({action:e.literal("taskInboxPaused"),sessionId:m}).strict(),e.object({action:e.literal("reserveTaskFollowup"),sessionId:m,turnId:m,ownerId:m}).strict(),e.object({action:e.literal("taskInboxWakeTargets"),afterSessionId:e.string().max(200)}).strict(),e.object({action:e.literal("createTaskWait"),value:Ne}).strict(),e.object({action:e.literal("settleTaskWait"),id:m,state:Ne.shape.state}).strict(),e.object({action:e.literal("taskWaitsForSession"),sessionId:m,afterId:e.string().max(200)}).strict(),e.object({action:e.literal("commitSubagentCompletion"),value:Le,turnId:m}).strict(),e.object({action:e.literal("pendingTaskCompletions"),afterTurnId:e.string().max(200)}).strict(),e.object({action:e.literal("settleTaskCompletion"),turnId:m,inputId:m}).strict(),e.object({action:e.literal("upsertSubagentRun"),value:Le}).strict(),e.object({action:e.literal("getSubagentRun"),id:m}).strict(),e.object({action:e.literal("listSubagentRuns"),query:St}).strict()]);var oe=e.string().trim().min(1).max(191),Be=e.object({createdAt:e.string().min(1),id:oe}).strict(),Fe=e.enum(["trigger_decision","route_decision","refiner_outcome","proposal","targeted_validation","apply_receipt"]),Ue=e.discriminatedUnion("action",[e.object({action:e.literal("put_artifact"),workspaceId:oe,kind:Fe,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:oe,kind:Fe,before:Be.nullable(),limit:e.number().int().min(1).max(200)}).strict(),e.object({action:e.literal("pending_trigger_page"),workspaceId:oe,before:Be.nullable(),limit:e.number().int().min(1).max(200)}).strict()]);var A=e.string().trim().min(1).max(200),Je=e.string().regex(/^[a-f0-9]{64}$/),Ht=e.object({kind:e.enum(["structural","visual","test","user_review"]),status:e.enum(["passed","failed","not_run"]),label:e.string().trim().min(1).max(240),detail:e.string().trim().max(4e3).nullable().optional(),ref:e.string().trim().max(4096).nullable().optional()}),Ke=e.object({id:A,title:e.string().trim().min(1).max(240),sourceTaskId:A,sourceTurnId:A,revision:e.number().int().positive(),createdAt:e.string().datetime(),contentType:e.string().trim().min(1).max(200),sizeBytes:e.number().int().min(1).max(1e7),sha256:Je,validation:e.array(Ht).max(32)}).strict(),Ge=e.object({sessionId:A,turnId:A,output:Ke}).strict(),Qe=e.object({uploadId:A,index:e.number().int().min(0).max(1024),offset:e.number().int().min(0).max(1e7),sha256:Je,contentsBase64:e.string().min(1).max(131072)}).strict(),Ye=e.object({uploadId:A}).strict(),xt=Ke.pick({id:!0,title:!0,sourceTaskId:!0,sourceTurnId:!0,revision:!0,createdAt:!0,validation:!0}),Xe=e.object({sessionId:A,turnId:A,output:xt,sandboxPath:e.string().trim().min(1).max(4096)}).strict();var F=e.string().trim().min(1).max(200),Et=e.object({type:e.enum(["create","get","start","stop","exec","open_port","list_files","download_file","upload_file","search_files","delete_file","stat_file","mkdir","move_file","process_start","process_get","git_status","git_diff","git_export_patch","git_branch","git_commit","git_pull","git_push"]),sandboxId:F.optional(),payload:e.unknown().optional(),processId:F.optional(),failOnUnpreservedChanges:e.boolean().optional()}).strict().superRefine((r,t)=>{r.type!=="create"&&!r.sandboxId&&t.addIssue({code:"custom",message:"Sandbox identity is required."}),r.type==="create"&&r.sandboxId&&t.addIssue({code:"custom",message:"Create cannot target a sandbox identity."}),r.type==="process_get"&&!r.processId&&t.addIssue({code:"custom",message:"Process identity is required."})}),Ze=e.object({action:Et}).strict(),et=e.object({sessionId:F,turnId:F,name:F}).strict();var g=1,l=e.string().trim().min(1).max(191),q=e.number().int().min(1).max(200),jr=e.object({teamId:l,ownerUserId:l,workspaceId:l,conversationId:l,turnId:l,attempt:e.number().int().min(1),leaseGeneration:e.number().int().min(1)}).strict(),tt=e.discriminatedUnion("operation",[e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("sandbox/request"),params:Ze}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("embedding/authorize"),params:et}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/begin"),params:Ge}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/chunk"),params:Qe}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/complete"),params:Ye}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("output/saveSandboxFile"),params:Xe}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("settings/get"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/get"),params:e.object({reference:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/overlay/get"),params:e.object({runId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/overlay/put"),params:e.object({runId:l,expectedRevision:e.number().int().min(0).nullable(),overlay:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/overlay/freezeProposal"),params:e.object({runId:l,expectedRevision:e.number().int().min(0),overlay:e.record(e.string(),e.unknown()),proposal:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/get"),params:e.object({workspaceId:l,key:e.string().min(1).max(120)}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/list"),params:e.object({workspaceId:l,includeDeleted:e.boolean(),before:e.object({updatedAt:e.string(),key:e.string()}).strict().nullable(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/search"),params:e.object({workspaceId:l,query:e.string().trim().min(1).max(500),limit:e.number().int().min(1).max(20)}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/memory/write"),params:e.object({input:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/state/read"),params:e.object({workspaceId:l,kind:e.enum(["selection","workspace_settings","evaluation_review_settings","candidates","cross_run_requests"]),afterId:l.nullable(),limit:e.number().int().min(1).max(100)}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("harness/workspace/transition"),params:e.discriminatedUnion("action",[e.object({action:e.literal("advance"),receiptId:l,workspaceId:l,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),now:e.string()}).strict(),e.object({action:e.literal("reviewedAdvance"),receiptId:l,workspaceId:l,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),reviewer:l,now:e.string()}).strict(),e.object({action:e.literal("rollback"),receiptId:l,workspaceId:l,expectedWorkspaceRevision:e.number().int().nonnegative(),expectedChannelRevision:e.number().int().nonnegative(),targetRelease:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),targetSourceRevision:e.string().min(1),rollbackOf:e.object({id:l,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),now:e.string()}).strict()])}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("task-inbox/execute"),params:Me}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("refiner/execute"),params:e.object({action:Ue}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("create-improve/execute"),params:e.discriminatedUnion("action",[e.object({action:e.literal("get"),runId:l}).strict(),e.object({action:e.literal("page"),query:e.object({profileId:l.nullable(),targetKind:l.nullable(),targetId:l.nullable(),state:e.array(l).max(20)}).strict(),before:e.object({updatedAt:e.string(),id:l}).strict().nullable(),limit:q}).strict(),e.object({action:e.literal("put"),run:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("mutate"),mutation:e.record(e.string(),e.unknown()),next:e.record(e.string(),e.unknown())}).strict()])}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("approval/get"),params:e.object({approvalId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("approval/upsert"),params:e.object({approval:e.record(e.string(),e.unknown()),expectedRevision:e.number().int().min(1).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("usage/getByRequestId"),params:e.object({requestId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("usage/upsert"),params:e.object({record:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("usage/page"),params:e.object({query:e.object({sessionId:l.optional(),turnId:l.optional(),provider:l.optional(),model:l.optional(),startedAtFrom:e.string().optional(),startedAtTo:e.string().optional(),visibility:e.enum(["user_facing","background","system"]).optional(),status:e.enum(["started","completed","failed","interrupted","missing"]).optional()}).strict(),before:e.object({startedAt:e.string(),requestOrdinal:e.number().int().min(0),id:l}).strict().nullable(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("capabilities"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/count"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/get"),params:e.object({sessionId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/page"),params:e.object({afterId:l.nullable(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("session/put"),params:e.object({sessionId:l,expectedRevision:e.number().int().min(1).nullable(),session:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/count"),params:e.object({sessionId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/wakeCount"),params:e.object({sessionId:l,key:e.enum(["messageId","fromRunId"]),value:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/get"),params:e.object({turnId:l}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/put"),params:e.object({sessionId:l,turnId:l,expectedRevision:e.number().int().min(1).nullable(),turn:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/latest"),params:e.object({sessionId:l,status:e.enum(["in_progress","completed","failed","interrupted"]).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("turn/page"),params:e.object({sessionId:l,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("thread/turnPage"),params:e.object({sessionId:l,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:q}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("event/append"),params:e.object({event:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("events/page"),params:e.object({sessionId:l.nullable(),afterSequence:e.number().int().min(0),beforeSequence:e.number().int().min(1).nullable().optional(),limit:q,excludeReasoningDeltas:e.boolean().optional()}).strict()}).strict(),e.object({contractVersion:e.literal(g),requestId:l,operation:e.literal("events/latestAssistantText"),params:e.object({sessionId:l}).strict()}).strict()]),Pr=e.object({contractVersion:e.literal(g),operations:e.array(e.enum(["sandbox/request","embedding/authorize","output/begin","output/chunk","output/complete","output/saveSandboxFile","settings/get","harness/get","harness/overlay/get","harness/overlay/put","harness/overlay/freezeProposal","harness/memory/get","harness/memory/list","harness/memory/search","harness/memory/write","harness/state/read","harness/workspace/transition","task-inbox/execute","refiner/execute","create-improve/execute","approval/get","approval/upsert","usage/getByRequestId","usage/upsert","usage/page","session/count","session/get","session/page","session/put","turn/count","turn/wakeCount","turn/get","turn/put","turn/latest","turn/page","thread/turnPage","event/append","events/page","events/latestAssistantText"])).max(40),allowedTools:e.array(l).max(128),maxPageSize:q,maxRequestBytes:e.number().int().min(1).max(1e6),maxInFlight:e.number().int().min(1).max(64)}).strict();var rt=class{static{i(this,"AgentHostStorageClient")}#e=new Map;#t=null;#r=1;bind(t){if(this.#t)throw new Error("Host storage client is already bound.");this.#t=t}async request(t,n=15e3){let s=tt.parse(t);if(!this.#t)throw new Error("Host storage transport is unavailable.");if(this.#e.size>=32)throw new Error("Host storage request limit exceeded.");let o=`host-storage:${this.#r++}`,a={jsonrpc:"2.0",id:o,method:"host/storage",params:s};if(Buffer.byteLength(JSON.stringify(a))>256e3)throw new Error("Host storage request is too large.");let c=new Promise((u,h)=>{let f=setTimeout(()=>{this.#e.delete(o),h(new Error("Host storage request timed out."))},Math.max(1,Math.min(6e4,n)));this.#e.set(o,{resolve:u,reject:h,timer:f})});try{await this.#t(a)}catch(u){let h=this.#e.get(o);h&&(clearTimeout(h.timer),this.#e.delete(o),h.reject(u instanceof Error?u:new Error(String(u))))}return c}accept(t){let n=ue.safeParse(t),s=n.success?null:pe.safeParse(t),o=n.success?n.data:s?.success?s.data:null;if(!o||typeof o.id!="string"||!o.id.startsWith("host-storage:"))return!1;let a=this.#e.get(o.id);return a?(clearTimeout(a.timer),this.#e.delete(o.id),Buffer.byteLength(JSON.stringify(o))>1e6?(a.reject(new Error("Host storage response is too large.")),!0):("error"in o?a.reject(new Error(`Host storage request failed: ${o.error.message}`)):a.resolve(o.result),!0)):!0}close(){this.#t=null;for(let t of this.#e.values())clearTimeout(t.timer),t.reject(new Error("Host storage transport closed."));this.#e.clear()}};import{createHash as jt}from"node:crypto";function me(r){if(r===null||typeof r=="boolean"||typeof r=="string")return r;if(typeof r=="number"){if(!Number.isFinite(r))throw new Error("Canonical JSON cannot encode a non-finite number.");return r}if(Array.isArray(r))return r.map(me);if(typeof r=="object"){let t={};for(let n of Object.keys(r).sort()){let s=r[n];s!==void 0&&(t[n]=me(s))}return t}throw new Error(`Canonical JSON cannot encode ${typeof r}.`)}i(me,"canonicalJson");function z(r){return jt("sha256").update(JSON.stringify(me(r)),"utf8").digest("hex")}i(z,"canonicalHash");var Pt=e.enum(["thread.started","thread.resumed","turn.started","turn.steered","turn.interrupted","turn.completed","turn.failed","item.started","item.delta","item.completed","assistant.reasoning.delta","assistant.delta","tool.started","tool.completed","approval.requested","approval.resolved","user_input.requested","user_input.resolved","compaction.started","compaction.completed","harness.admitted","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","diagnostic"]),At=e.object({sequence:e.number().int().nonnegative(),name:Pt,source:e.enum(["runtime","provider","tool","host","refiner"]),status:e.string().trim().min(1).nullable().default(null),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1).nullable().default(null),callId:e.string().trim().min(1).nullable().default(null),output:e.string().nullable().default(null),error:e.string().nullable().default(null),data:e.record(e.string(),e.unknown()).default({})}).strict();function Dr(r){return z(At.parse(r))}i(Dr,"canonicalEventHash");import{once as Tt}from"node:events";import{createInterface as qt}from"node:readline";async function nt(r){let t=null,n=Promise.resolve(),s=[],o=i(w=>(n=n.then(async()=>{r.writable.write(`${JSON.stringify(w)}
3
3
  `)||await Tt(r.writable,"drain")}),n),"write");r.hostStorageClient?.bind(w=>o(w));let a=i(()=>{if(!(!t?.initialized||s.length===0))for(let w of s.splice(0))o(w)},"flushPendingNotifications"),c,u=new Set,h=qt({input:r.readable,crlfDelay:1/0}),f=[],k=!1,d=null,R=i(async w=>{let p=t;if(!p)throw new Error("Agent runtime dispatcher is unavailable.");let y=(async()=>{let I=await p.handle(w);I&&await o(I),a()})(),S=w&&typeof w=="object"&&"method"in w?w.method:null;if(S==="initialize"||S==="initialized"){await y;return}u.add(y),y.finally(()=>u.delete(y))},"dispatch"),v=(async()=>{let w=typeof r.host=="function"?await r.host():r.host;for(t=new ne(w),c=w.subscribe?.(p=>{if(!t?.initialized){s.push(p);return}o(p)});f.length>0;)await R(f.shift());k=!0})().catch(w=>{d=w,h.close()});try{for await(let w of h){if(!w.trim())continue;if(Buffer.byteLength(w,"utf8")>1e6){await o({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Request exceeds the JSONL size limit"}});continue}let p;try{p=JSON.parse(w)}catch{await o({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}});continue}if(!r.hostStorageClient?.accept(p))if(k)await R(p);else if(f.length>=64){let y=p&&typeof p=="object"&&"id"in p?p.id:null;(typeof y=="string"||typeof y=="number")&&await o({jsonrpc:"2.0",id:y,error:{code:-32e3,message:"Runtime startup request limit exceeded"}})}else f.push(p)}if(await v,d)throw d;await Promise.all(u),await n}finally{r.hostStorageClient?.close(),c?.()}}i(nt,"runAgentJsonlServer");var ae=e.object({threadId:e.string().trim().min(1)}).passthrough(),Ot=ae.extend({includeHistory:e.boolean().optional()}),Ct=e.object({session:e.unknown()}).strict(),U=ae.extend({input:e.unknown()}),_t=U.extend({idempotencyKey:e.string().trim().min(1).max(200)}),$t=U.extend({inputId:e.string().trim().min(1)}),Vt=ae.extend({reason:e.string().trim().min(1).optional()}),zt=e.object({approvalId:e.string().trim().min(1),input:e.unknown()}).strict();function st(r){let t=i(async(s,o,a)=>{let c=performance.now();r.telemetry?.({method:s,phase:"started",threadId:o,durationMs:null,errorClass:null});try{let u=await a();return r.telemetry?.({method:s,phase:"completed",threadId:o,durationMs:performance.now()-c,errorClass:null}),u}catch(u){throw r.telemetry?.({method:s,phase:"failed",threadId:o,durationMs:performance.now()-c,errorClass:u instanceof Error?u.name:"UnknownError"}),u}},"run"),n=i(async(s,o="thread/read")=>{let{threadId:a,includeHistory:c}=Ot.parse(s);return t(o,a,async()=>{if(c===!1)return{thread:await r.readThread(a),turns:[],events:[]};let[u,h,f]=await Promise.all([r.readThread(a),r.listTurns(a),r.listEvents(a)]);return{thread:u,turns:h,events:f}})},"threadRead");return{capabilities:i(s=>t("runtime/capabilities",null,()=>r.capabilities(s)),"capabilities"),threadStart:i(async s=>t("thread/start",null,async()=>({thread:await r.createThread(Ct.parse(s).session)})),"threadStart"),threadResume:i(s=>n(s,"thread/resume"),"threadResume"),threadRead:n,turnStart:i(async s=>{let o=U.parse(s);return t("turn/start",o.threadId,async()=>({turn:await r.startTurn(o.threadId,o.input)}))},"turnStart"),turnSteer:i(async s=>{let o=U.parse(s);return t("turn/steer",o.threadId,async()=>({receipt:await r.steerTurn(o.threadId,o.input)}))},"turnSteer"),taskInbox:i(async s=>{let{threadId:o}=ae.parse(s);return t("task/inbox",o,()=>r.readTaskInbox(o))},"taskInbox"),taskQueue:i(async s=>{let o=_t.parse(s);return t("task/queue",o.threadId,()=>r.queueTaskInput(o.threadId,o.input,o.idempotencyKey))},"taskQueue"),taskInputUpdate:i(async s=>{let o=$t.parse(s);return t("task/inputUpdate",o.threadId,()=>r.updateTaskInput(o.threadId,o.inputId,o.input))},"taskInputUpdate"),turnInterrupt:i(async s=>{let o=Vt.parse(s);return t("turn/interrupt",o.threadId,async()=>({turn:await r.interruptTurn(o.threadId,o.reason)}))},"turnInterrupt"),approvalResolve:i(async s=>{let o=zt.parse(s);return t("approval/resolve",null,async()=>({approval:await r.resolveApproval(o.approvalId,o.input)}))},"approvalResolve"),userInputResolve:i(async s=>{let o=U.parse(s);return t("userInput/resolve",o.threadId,async()=>(r.isTurnActive(o.threadId)&&await r.waitForTurnSettlement(o.threadId),{turn:await r.startTurn(o.threadId,o.input)}))},"userInputResolve"),profileWorkflows:i(()=>t("profile/workflows",null,()=>r.listProfileWorkflows()),"profileWorkflows"),profileEvaluations:i(s=>t("profile/evaluations",null,()=>r.listProfileEvaluations(s)),"profileEvaluations"),profileTrainingSource:i(()=>t("profile/trainingSource",null,()=>r.loadProfileTrainingSource()),"profileTrainingSource"),profileEvaluationPrepare:i(s=>t("profile/evaluations/prepare",null,()=>r.prepareProfileEvaluationRun(s)),"profileEvaluationPrepare"),profileEvaluationRun:i(s=>t("profile/evaluations/run",null,()=>r.runPreparedProfileEvaluation(s)),"profileEvaluationRun"),profileEvaluationRunSuite:i(s=>t("profile/evaluations/runSuite",null,()=>r.runProfileEvaluationSuite(s)),"profileEvaluationRunSuite"),profileEvaluationExecuteCase:i(s=>t("profile/evaluations/executeCase",null,()=>r.executeProfileEvaluationCase(s)),"profileEvaluationExecuteCase"),profileEvaluationExecuteRun:i(s=>t("profile/evaluations/executeRun",null,()=>r.executeProfileEvaluationRun(s)),"profileEvaluationExecuteRun"),profileEvaluationCompare:i(s=>t("profile/evaluations/compare",null,()=>r.compareProfileEvaluationRuns(s)),"profileEvaluationCompare"),profileEvaluationReport:i(s=>t("profile/evaluations/report",null,()=>r.buildProfileEvaluationReport(s)),"profileEvaluationReport"),harnessInspect:i(()=>t("harness/inspect",null,()=>r.inspectHarness()),"harnessInspect"),harnessProposalReview:i(s=>t("harness/proposalReview",null,()=>r.reviewHarnessProposal(s)),"harnessProposalReview"),harnessReview:i(s=>t("harness/review",null,()=>r.reviewHarness(s)),"harnessReview"),harnessAcceptEvaluationReview:i(s=>t("harness/acceptEvaluationReview",null,()=>r.acceptHarnessEvaluationReview(s)),"harnessAcceptEvaluationReview"),harnessMaterializeEvaluationTaskset:i(s=>t("harness/materializeEvaluationTaskset",null,()=>r.materializeHarnessEvaluationTaskset(s)),"harnessMaterializeEvaluationTaskset"),harnessRunEvaluationBaseline:i(s=>t("harness/runEvaluationBaseline",null,()=>r.runHarnessEvaluationBaseline(s)),"harnessRunEvaluationBaseline"),harnessValidate:i(()=>t("harness/validate",null,()=>r.validateHarness()),"harnessValidate"),harnessBackgroundReview:i(s=>t("harness/backgroundReview",null,()=>r.updateHarnessBackgroundReview(s)),"harnessBackgroundReview"),harnessDiff:i(s=>t("harness/diff",null,()=>r.diffHarness(s)),"harnessDiff"),harnessRollback:i(s=>t("harness/rollback",null,()=>r.rollbackHarness(s)),"harnessRollback"),refinerInspect:i(()=>t("refiner/inspect",null,()=>r.inspectRefiner()),"refinerInspect"),refinerUpdate:i(s=>t("refiner/update",null,()=>r.updateRefiner(s)),"refinerUpdate"),refinerActivate:i(s=>t("refiner/activate",null,()=>r.activateRefiner(s)),"refinerActivate"),refinerRollback:i(s=>t("refiner/rollback",null,()=>r.rollbackRefiner(s)),"refinerRollback"),subscribe:r.subscribeEvents&&r.eventNotification?s=>r.subscribeEvents(o=>s(r.eventNotification(o))):void 0}}i(st,"createAgentRuntimeService");var _=e.string().regex(/^[a-f0-9]{64}$/),cn=e.object({harnessReleaseHash:_,instructionsHash:_,skillHashes:e.record(e.string(),_),agentAssetHashes:e.record(e.string(),_),toolCatalogHash:_,memoryRevision:e.number().int().nonnegative().nullable()}).strict(),Wt=e.object({protocolVersion:e.string().trim().min(1),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1),harnessReleaseHash:_,toolCatalogHash:_,context:e.record(e.string(),e.unknown()),pendingInteraction:e.record(e.string(),e.unknown()).nullable(),usage:e.record(e.string(),e.unknown())}).strict();function ln(r){return z(Wt.parse(r))}i(ln,"checkpointHash");function dn(r){return[r.system,...r.harnessInstructions,...r.skillInstructions,...r.hostInstructions??[]].map(t=>t.trim()).filter(Boolean).join(`
4
4
 
5
5
  `)}i(dn,"materializeAgentPrompt");function hn(r){let t=new Set,n=[...r].map(a=>{let c=a.name.trim();if(!c)throw new Error("Agent tool names cannot be empty.");if(t.has(c))throw new Error(`Duplicate agent tool: ${c}.`);if(t.add(c),!a.unavailableReason&&!a.executorAvailable)throw new Error(`Agent tool ${c} is declared as available without an executor.`);return{...a,name:c}}).sort((a,c)=>a.name.localeCompare(c.name)),s=n.filter(a=>!a.unavailableReason).map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema})),o=n.map(a=>({name:a.name,displayLabel:a.displayLabel??a.name,placement:a.placement,available:!a.unavailableReason,unavailableReason:a.unavailableReason??null}));return{byName:new Map(n.map(a=>[a.name,a])),tools:n,modelTools:s,capabilities:o,hash:z({modelTools:s,capabilities:o})}}i(hn,"createAgentToolCatalogProjection");async function fn(r,t){let n=r.byName.get(t.name);if(!n)throw new Error(`Unknown agent tool: ${t.name}.`);if(n.unavailableReason)throw new Error(`Agent tool ${t.name} is unavailable: ${n.unavailableReason}`);if(!n.execute)throw new Error(`Agent tool ${t.name} has no executor.`);let s=n.validateArguments?n.validateArguments(t.arguments):t.arguments;return n.execute(s,t.context)}i(fn,"executeProjectedAgentTool");var ot=class{static{i(this,"TaskSignals")}#e=new Map;notify(t){for(let n of[...this.#e.get(t)??[]])n()}subscribe(t,n){let s=this.#e.get(t);return s||this.#e.set(t,s=new Set),s.add(n),()=>{s.delete(n),s.size===0&&this.#e.delete(t)}}async wait(t){let n=i(()=>{},"wake"),s=0,o=i(()=>{s+=1,n()},"changed"),a=[...new Set(t.taskIds)].map(u=>this.subscribe(u,o)),c=setTimeout(o,Math.max(0,t.deadline-Date.now()));t.signal.addEventListener("abort",o);try{for(;;){t.signal.throwIfAborted();let u=s,h=await t.read();if(h!==null)return h;if(Date.now()>=t.deadline)return null;s===u&&await new Promise(f=>{n=f,(s!==u||t.signal.aborted)&&f()})}}finally{clearTimeout(c),t.signal.removeEventListener("abort",o);for(let u of a)u()}}},at=class{static{i(this,"TaskSerialExecutor")}#e=new Map;async run(t,n){let o=(this.#e.get(t)??Promise.resolve()).then(n),a=o.then(()=>{},()=>{});this.#e.set(t,a);try{return await o}finally{this.#e.get(t)===a&&this.#e.delete(t)}}};import{randomUUID as W}from"node:crypto";import{promises as b}from"node:fs";import{stripTypeScriptTypes as Dt}from"node:module";import H from"node:path";async function Un(r){let t=D.parse(r.overlay),n=C.parse(r.proposal),s=r.validations.map(f=>xe.parse(f));if((n.route==="agent"?n.edits.filter(f=>f.target!=="harness.json"&&f.operation!=="delete"):[]).length>0){let f=n.validationPlan.find(d=>d.kind==="component_activation"&&d.required);if(!f)throw new Error("Desktop Work Agent proposals require component-activation validation before review.");if(s.find(d=>d.validationId===f.id)?.status==="passed")throw new Error("Desktop Work cannot accept a passed Agent activation receipt until an Agent source executor exists.")}if(n.overlay.id!==t.id||n.overlay.revision!==t.revision||n.overlay.contentHash!==t.contentHash)throw new Error("Refiner proposal is not bound to the supplied run overlay.");if(t.status!=="frozen")throw new Error("Only a frozen run overlay can advance a Harness workspace.");let a=await r.store.getHarnessWorkspace(n.expectedWorkspace.workspaceId);if(!a)throw new Error(`Harness workspace ${n.expectedWorkspace.workspaceId} does not exist.`);if(a.location!=="local")throw new Error("The local Refiner can only advance a local Harness workspace.");let c=L(r.storeDir,a.id),u=await P({workspaceId:a.id,sourceDir:c.source});if(u.sourceRevision!==a.sourceRevision)throw new Error(`Harness source is ${u.sourceRevision}; workspace expects ${a.sourceRevision}. Record or revert the source change before refinement.`);let h=H.join(c.root,`.source-candidate-${W()}`);await b.cp(c.source,h,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});try{await lt(h,n);let f=await P({workspaceId:a.id,sourceDir:h}),k=(r.now??(()=>new Date().toISOString()))(),d=await Ce({storeDir:r.storeDir,workspaceId:a.id,compiled:f,createdAt:k});await r.store.saveHarnessReleaseRecord(d),await r.store.saveHarnessImprovementArtifact(a.id,"run_overlay",t),await r.store.saveHarnessImprovementArtifact(a.id,"proposal",n);for(let p of s)await r.store.saveHarnessImprovementArtifact(a.id,"targeted_validation",p);if(!Ae({workspace:a,proposal:n}).eligible&&!r.reviewAuthority)return r.store.advanceHarnessWorkspaceAtomically({receiptId:r.receiptId,workspaceId:a.id,proposal:n,validations:s,nextRelease:{id:d.harnessRelease.id,contentHash:d.harnessRelease.contentHash},nextSourceRevision:d.sourceRevision,now:k});let v=H.join(c.root,`.source-backup-${W()}`),w=H.join(c.root,"source-swap.json");await ut(w,{schemaVersion:"openpond.localHarnessSourceSwap.v1",workspaceId:a.id,expectedWorkspaceRevision:a.revision,previousSourceRevision:a.sourceRevision,nextSourceRevision:d.sourceRevision,backupSource:v,candidateSource:h,createdAt:k}),await b.rename(c.source,v),await b.rename(h,c.source);try{let p=r.reviewAuthority?await r.store.advanceReviewedHarnessWorkspaceAtomically({receiptId:r.receiptId,workspaceId:a.id,proposal:n,validations:s,nextRelease:{id:d.harnessRelease.id,contentHash:d.harnessRelease.contentHash},nextSourceRevision:d.sourceRevision,reviewer:r.reviewAuthority.reviewer,now:k}):await r.store.advanceHarnessWorkspaceAtomically({receiptId:r.receiptId,workspaceId:a.id,proposal:n,validations:s,nextRelease:{id:d.harnessRelease.id,contentHash:d.harnessRelease.contentHash},nextSourceRevision:d.sourceRevision,now:k});return p.receipt.decision!=="advanced"?await J(c.source,v):await b.rm(v,{recursive:!0,force:!0}),await b.rm(w,{force:!0}),p}catch(p){throw await J(c.source,v).catch(()=>{}),await b.rm(w,{force:!0}).catch(()=>{}),p}}finally{await b.rm(h,{recursive:!0,force:!0}).catch(()=>{})}}i(Un,"applyLocalHarnessRefinerProposal");async function Jn(r){let t=await r.store.getHarnessWorkspace(r.workspaceId);if(!t||t.location!=="local")throw new Error(`Local Harness workspace ${r.workspaceId} does not exist.`);if(t.currentChannel.release?.id!==r.rollbackOf.id||t.currentChannel.release.contentHash!==r.rollbackOf.contentHash)throw new Error("Harness rollback source is no longer the current release.");let n=await r.store.getHarnessReleaseRecord(r.targetRelease.contentHash);if(!n||n.workspaceId!==t.id||n.harnessRelease.id!==r.targetRelease.id)throw new Error("Harness rollback target is unavailable in this workspace.");let s=L(r.storeDir,t.id);if((await P({workspaceId:t.id,sourceDir:s.source})).sourceRevision!==t.sourceRevision)throw new Error("Harness source changed before rollback.");let a=H.join(s.root,`.source-rollback-${W()}`);await b.cp(H.join(n.bundlePath,"source"),a,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});try{if((await P({workspaceId:t.id,sourceDir:a})).sourceRevision!==n.sourceRevision)throw new Error("Harness rollback bundle does not reproduce its registered source revision.");let u=(r.now??(()=>new Date().toISOString()))(),h=H.join(s.root,`.source-backup-${W()}`),f=H.join(s.root,"source-swap.json");await ut(f,{schemaVersion:"openpond.localHarnessSourceSwap.v1",workspaceId:t.id,expectedWorkspaceRevision:t.revision,previousSourceRevision:t.sourceRevision,nextSourceRevision:n.sourceRevision,backupSource:h,candidateSource:a,createdAt:u}),await b.rename(s.source,h),await b.rename(a,s.source);try{let k=await r.store.rollbackHarnessWorkspaceAtomically({receiptId:r.receiptId,workspaceId:t.id,expectedWorkspaceRevision:t.revision,expectedChannelRevision:t.currentChannel.revision,targetRelease:r.targetRelease,targetSourceRevision:n.sourceRevision,rollbackOf:r.rollbackOf,now:u});return k.receipt.decision!=="rolled_back"?await J(s.source,h):await b.rm(h,{recursive:!0,force:!0}),await b.rm(f,{force:!0}),k}catch(k){throw await J(s.source,h).catch(()=>{}),await b.rm(f,{force:!0}).catch(()=>{}),k}}finally{await b.rm(a,{recursive:!0,force:!0}).catch(()=>{})}}i(Jn,"rollbackLocalHarnessWorkspaceRelease");async function Kn(r){let t=C.parse(r.proposal);if(t.expectedWorkspace.workspaceId!==r.workspace.id)throw new Error("Refiner proposal targets a different Harness workspace.");if(t.route==="memory")return Nt({proposal:t,now:r.now});let n=L(r.storeDir,r.workspace.id),s=await P({workspaceId:r.workspace.id,sourceDir:n.source});if(s.sourceRevision!==t.expectedWorkspace.sourceRevision)throw new Error("Refiner proposal source revision no longer matches the Local Harness workspace.");let o=H.join(n.root,`.validation-candidate-${W()}`);await b.cp(n.source,o,{recursive:!0,force:!1,errorOnExist:!0,verbatimSymlinks:!1});let a=(r.now??(()=>new Date().toISOString()))();try{await lt(o,t);let c=await P({workspaceId:r.workspace.id,sourceDir:o}),u=new Map(c.manifest.files.map(d=>[d.path,d])),h=new Map(t.edits.map(d=>[d.target,d])),f=it(s),k=it(c);return Promise.all(t.validationPlan.map(async d=>{let R="passed",v="The candidate Harness source compiles and preserves its manifest contract.";try{if(d.kind==="observed_recovery"){let w=t.evidence.filter(p=>p.kind==="recovery");if(w.length===0)throw new Error("Observed-recovery validation requires recorded recovery evidence.");v=`Validated ${w.length} immutable recovery evidence reference(s) before candidate advancement.`}else if(d.kind==="prompt"){let w=t.edits.filter(p=>p.route==="prompt"&&p.target!=="harness.json");if(w.length===0)throw new Error("Prompt validation requires an instruction-file edit.");for(let p of w){let y=u.get(p.target);if(p.operation==="delete"){if(y)throw new Error(`Deleted instruction ${p.target} remains declared.`)}else if(y?.kind!=="instruction")throw new Error(`Instruction ${p.target} is not declared in the candidate Harness.`);if(p.content!==null&&/\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]/i.test(p.content))throw new Error(`Instruction ${p.target} appears to contain credential material.`)}v=`Validated ${w.length} textual instruction edit(s) and compiled candidate ${c.harnessRelease.id}.`}else if(d.kind==="skill"){let w=t.edits.filter(p=>p.route==="skill"&&p.target!=="harness.json");if(w.length===0)throw new Error("Skill validation requires a declared Skill-file edit.");for(let p of w){let y=u.get(p.target);if(p.operation==="delete"){if(y)throw new Error(`Deleted Skill ${p.target} remains declared.`);continue}if(y?.kind!=="skill")throw new Error(`Skill ${p.target} is not declared in the candidate Harness.`);let S=h.get(p.target)?.content;if(!S)throw new Error(`Skill edit ${p.target} has no content.`);let I=N(S);if(!I.name||!I.description||I.messages.length>0)throw new Error(`Skill ${p.target} is invalid: ${I.messages.join(" ")}`)}v=`Validated ${w.length} Skill edit(s), Skill frontmatter, and compiled candidate ${c.harnessRelease.id}.`}else if(d.kind==="dependency"){let w=c.manifest.files.find(p=>p.kind==="dependency_lock");if(!w)throw new Error("Candidate Harness has no dependency lock.");JSON.parse(await b.readFile(dt(o,w.path),"utf8")),v=`Validated dependency lock ${w.path} and compiled candidate ${c.harnessRelease.id}.`}else if(d.kind==="schema")C.parse(t),v=`Validated proposal, manifest, and candidate release schemas for ${c.harnessRelease.id}.`;else if(d.kind==="package"){let w=t.edits.filter(p=>p.route==="agent"&&p.operation!=="delete"&&p.target!=="harness.json");for(let p of w){if(!p.content)throw new Error(`Agent edit ${p.target} has no source.`);Dt(p.content,{mode:"transform",sourceUrl:p.target,sourceMap:!1})}v=w.length>0?`Syntax-checked ${w.length} Agent source edit(s) and compiled candidate ${c.harnessRelease.id}.`:`Compiled candidate package ${c.harnessRelease.id} and preserved the Harness source manifest contract.`}else if(d.kind==="component_activation"){let w=t.edits.filter(p=>p.target!=="harness.json");if(w.length===0)throw new Error("Component activation requires a concrete Harness component edit.");if(t.route==="agent"){if(w.filter(y=>y.operation!=="delete").length>0)throw new Error("Desktop Work does not compile or execute released Agent source; use an active instruction or standalone Skill, or add an Agent executor before release.");v=`Confirmed ${w.length} deleted Agent component(s) were inactive in Desktop Work.`}else{if(!["prompt","skill"].includes(t.route))throw new Error(`Desktop Work has no activation policy for ${t.route} proposals.`);let p=t.route==="prompt"?"instruction":"skill";for(let y of w){let S=k.components.find(I=>I.path===y.target&&I.kind===p);if(y.operation==="delete"?S:!S)throw new Error(`${p} ${y.target} is not reflected in the candidate Desktop Work runtime surface.`)}if(f.contentHash===k.contentHash)throw new Error("The candidate does not change the effective Desktop Work runtime surface.");v=`Activated ${w.length} ${p} edit(s) in the candidate Desktop Work runtime surface.`}}else d.kind==="business_formula"?(R="blocked",v="Business or financial logic is retained for review until an approved deterministic fixture supplies inputs and expected outputs."):d.kind==="targeted_evaluation"?(R="blocked",v="This sensitive change requires an explicit authority-preserving targeted Evaluation before release."):d.kind==="file_render"?(R="blocked",v="File-render validation requires an exact produced artifact reference; no artifact was attached to this Harness-source proposal."):(R="blocked",v=`Local targeted validation does not yet own ${d.kind}; it requires its dedicated validator.`)}catch(w){R="failed",v=w instanceof Error?w.message:String(w)}return ee({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${t.id}-${d.id}`,proposal:{id:t.id,contentHash:t.contentHash},validationId:d.id,kind:d.kind,status:R,summary:v,evidenceRefs:t.evidence,createdAt:a,metadata:{candidateHarnessRelease:{id:c.harnessRelease.id,contentHash:c.harnessRelease.contentHash},sourceRevision:c.sourceRevision,...d.kind==="component_activation"?{targetRuntime:"desktop_work",beforeEffectiveRuntimeHash:f.contentHash,afterEffectiveRuntimeHash:k.contentHash,activatedComponentRefs:k.components,inactiveAgentRefs:k.inactiveAgents}:{}}})}))}catch(c){let u=c instanceof Error?c.message:String(c);return t.validationPlan.map(h=>ee({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${t.id}-${h.id}`,proposal:{id:t.id,contentHash:t.contentHash},validationId:h.id,kind:h.kind,status:"failed",summary:u,evidenceRefs:t.evidence,createdAt:a,metadata:{}}))}finally{await b.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}i(Kn,"validateLocalHarnessRefinerProposal");function it(r){let t=[...r.agentSnapshot.instructions.map(s=>({kind:"instruction",path:s.path,contentHash:s.contentHash})),...r.agentSnapshot.skills.map(s=>({kind:"skill",path:s.path,contentHash:s.contentHash}))].sort((s,o)=>s.path.localeCompare(o.path)),n=r.agentSnapshot.agents.map(s=>({path:s.path,contentHash:s.contentHash})).sort((s,o)=>s.path.localeCompare(o.path));return{contentHash:X({schemaVersion:"openpond.desktopWorkHarnessSurface.v1",components:t}),components:t,inactiveAgents:n}}i(it,"desktopWorkRuntimeSurface");function Nt(r){let t=(r.now??(()=>new Date().toISOString()))(),n=r.proposal.edits.find(s=>s.route==="memory");return r.proposal.validationPlan.map(s=>{let o="passed",a="Memory candidate is bounded, scoped, and contains no obvious credential material.";try{if(s.kind==="observed_recovery"){if(!r.proposal.evidence.some(c=>c.kind==="recovery"))throw new Error("Observed-recovery validation requires recorded recovery evidence.");a="Memory proposal is grounded in immutable recovery evidence."}else if(s.kind==="memory"){if(!n||!/^memory\/[a-z0-9][a-z0-9-]{0,119}$/.test(n.target))throw new Error("Memory proposal requires one safe memory/<slug> target.");let c=r.proposal.metadata.expectedMemory;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Memory proposal requires an expected revision snapshot.");let u=c;if(u.key!==Lt(n.target))throw new Error("Memory proposal expected revision targets a different key.");if(u.revision!==null&&(!Number.isInteger(u.revision)||Number(u.revision)<1))throw new Error("Memory proposal expected revision is invalid.");if(u.contentHash!==null&&typeof u.contentHash!="string")throw new Error("Memory proposal expected content hash is invalid.");if(u.status!==null&&u.status!=="active"&&u.status!=="deleted")throw new Error("Memory proposal expected status is invalid.");if(u.revision===null&&(u.contentHash!==null||u.status!==null))throw new Error("New memory snapshot must not claim existing content or status.");if(u.revision!==null&&(typeof u.contentHash!="string"||u.status===null))throw new Error("Existing memory snapshot requires its content hash and status.");if(n.operation==="delete"&&u.status!=="active")throw new Error("Memory deletion requires an active expected revision.");if(n.operation!=="delete"){if(!n.content?.trim()||n.content.length>24e3)throw new Error("Memory content must contain 1-24,000 characters.");if(/\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]/i.test(n.content))throw new Error("Memory content appears to contain credential material.")}}else o="blocked",a=`Memory validation cannot satisfy ${s.kind}.`}catch(c){o="failed",a=c instanceof Error?c.message:String(c)}return ee({schemaVersion:"openpond.harnessTargetedValidationReceipt.v1",id:`validation-${r.proposal.id}-${s.id}`,proposal:{id:r.proposal.id,contentHash:r.proposal.contentHash},validationId:s.id,kind:s.kind,status:o,summary:a,evidenceRefs:r.proposal.evidence,createdAt:t,metadata:{externalState:"harness_memory"}})})}i(Nt,"validateMemoryProposal");function Lt(r){let t=r.replaceAll("\\","/"),n=/^memory\/([a-z0-9][a-z0-9-]{0,119})$/.exec(t);if(!n)throw new Error(`Invalid Harness memory target: ${r}.`);return n[1]}i(Lt,"memoryKeyFromTarget");async function ct(r){let t=await r.store.getHarnessWorkspace(r.workspaceId);if(!t)throw new Error(`Harness workspace ${r.workspaceId} does not exist.`);let n=L(r.storeDir,t.id),s=H.join(n.root,"source-swap.json"),o=await b.readFile(s,"utf8").then(JSON.parse).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(!o)return"none";let a=await P({workspaceId:t.id,sourceDir:n.source});if(t.sourceRevision===o.nextSourceRevision&&a.sourceRevision===o.nextSourceRevision)return await b.rm(o.backupSource,{recursive:!0,force:!0}),await b.rm(s,{force:!0}),"completed";let c=await P({workspaceId:t.id,sourceDir:o.backupSource});if(t.sourceRevision===o.previousSourceRevision&&c.sourceRevision===o.previousSourceRevision)return await J(n.source,o.backupSource),await b.rm(s,{force:!0}),"restored";throw new Error("Harness source-swap recovery cannot reconcile filesystem and workspace revisions.")}i(ct,"recoverLocalHarnessSourceSwap");async function lt(r,t){for(let n of t.edits){let s=dt(r,n.target);if(n.operation==="delete"){await b.rm(s,{force:!1});continue}if(n.content===null)throw new Error(`Refiner edit ${n.id} has no content.`);if(n.operation==="create")await b.mkdir(H.dirname(s),{recursive:!0}),await b.writeFile(s,n.content,{flag:"wx"});else{let o=await b.lstat(s);if(!o.isFile()||o.isSymbolicLink())throw new Error(`Refiner update target must be a regular file: ${n.target}`);await b.writeFile(s,n.content,{flag:"w"})}}}i(lt,"applyOverlayEdits");function dt(r,t){let n=H.resolve(r),s=H.resolve(n,...t.replaceAll("\\","/").split("/")),o=H.relative(n,s);if(!o||o.startsWith("..")||H.isAbsolute(o))throw new Error(`Refiner edit target escapes the Harness source: ${t}`);return s}i(dt,"containedPath");async function ut(r,t){let n=`${r}.${W()}.tmp`;await b.writeFile(n,`${JSON.stringify(t,null,2)}