principles-disciple 1.197.11 → 1.197.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle.js +4 -4
- package/dist/openclaw.plugin.json +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
package/dist/bundle.js
CHANGED
|
@@ -1008,7 +1008,7 @@ CONSTRAINTS:
|
|
|
1008
1008
|
- Output ONLY valid JSON \u2014 no markdown, no explanatory text, no code fences, no prose before or after
|
|
1009
1009
|
- Do NOT read files, call tools, or write to any database
|
|
1010
1010
|
${a}${s}`}buildPrompt(t,r={}){let{outputLanguage:o}=r,n=this.buildRouterInstruction({outputLanguage:o}),i={taskId:t.rootCauseOutput.taskId,rootCauseArtifactId:t.rootCauseArtifactId,rootCauseOutput:t.rootCauseOutput,distillerArtifactId:t.distillerArtifactId,distillerOutput:t.distillerOutput,routerInstruction:n};return{message:JSON.stringify(i),promptInput:i}}};Lu();var u6e=200,OLr="output_invalid";function wl(e,t,r){return{valid:!1,errors:[t,...r],errorCategory:OLr}}function PLr(){return{valid:!0,errors:[]}}var VG=class{async validate(t,r,o){if(typeof t!="object"||t===null)return wl(!1,"1 field invalid: output must be a non-null object",["output must be a non-null object"]);let n=o?.verbose===!0,i=[];if(t.confidence<0||t.confidence>1){let c=`confidence ${t.confidence} outside [0, 1] closed interval`;if(!n)return wl(!1,"1 field invalid: confidence",[c]);i.push(c)}if(!t.summary||t.summary.trim()===""){let c="summary must be a non-empty string";if(!n)return wl(!1,"1 field invalid: summary",[c]);i.push(c)}if(!t.rootCause||t.rootCause.trim()===""){let c="rootCause must be a non-empty string";if(!n)return wl(!1,"1 field invalid: rootCause",[c]);i.push(c)}for(let c of t.evidence){if(!c.sourceRef||c.sourceRef.trim()===""){let u="evidence[].sourceRef must be a non-empty string";if(!n)return wl(!1,"1 field invalid: evidence",[u]);i.push(u)}if(!c.note||c.note.trim()===""){let u="evidence[].note must be a non-empty string";if(!n)return wl(!1,"1 field invalid: evidence",[u]);i.push(u)}}for(let c of t.recommendations){if(!vo.Check(F2,c.kind)){let u=`recommendations[].kind "${c.kind}" is not a valid RecommendationKind`;if(!n)return wl(!1,"1 field invalid: recommendations",[u]);i.push(u)}if(!c.description||c.description.trim()===""){let u="recommendations[].description must be a non-empty string";if(!n)return wl(!1,"1 field invalid: recommendations",[u]);i.push(u)}if(c.kind==="principle"){if(!c.abstractedPrinciple||c.abstractedPrinciple.trim()===""){let u='recommendations[].abstractedPrinciple is required when kind is "principle"';if(!n)return wl(!1,"1 field invalid: recommendations",[u]);i.push(u)}if(c.abstractedPrinciple&&c.abstractedPrinciple.length>u6e){let u=`recommendations[].abstractedPrinciple must be ${u6e} characters or fewer`;if(!n)return wl(!1,"1 field invalid: recommendations",[u]);i.push(u)}}if(c.kind==="rule"){if(!c.triggerPattern||c.triggerPattern.trim()===""){let u='recommendations[].triggerPattern is required when kind is "rule"';if(!n)return wl(!1,"1 field invalid: recommendations",[u]);i.push(u)}if(!c.action||c.action.trim()===""){let u='recommendations[].action is required when kind is "rule"';if(!n)return wl(!1,"1 field invalid: recommendations",[u]);i.push(u)}}}if(n&&o?.sourceRefs){let c=new Set(o.sourceRefs);for(let u of t.evidence)if(u.sourceRef&&!c.has(u.sourceRef)){let l=`evidence[].sourceRef "${u.sourceRef}" not found in context sourceRefs`;i.push(l)}}if(!vo.Check(du,t)){let u=[...vo.Errors(du,t)].map(l=>`${l.path}: ${l.message}`);if(!n)return wl(!1,"1 field invalid: schema",u);i.push(...u)}if(i.length===0)return PLr();let a=i.length,s=`${a} field${a>1?"s":""} invalid`;return wl(!1,s,i)}};var f$=class extends Wc{committer;defaultValidator;constructor(t,r){super(t,r,{runnerName:"diag_router",expectedTaskKind:"diag_router",defaultAgentId:"main",resultRefPrefix:"diag-router",effectiveConfig:r.effectiveConfig}),this.committer=t.committer,this.defaultValidator=new VG}get permanentErrorCategories(){return new Set(["storage_unavailable","workspace_invalid","capability_missing","cancelled","input_invalid"])}async buildContext(t){let r=await this.stateManager.getTask(t);if(!r)throw new wt("input_invalid",`Task ${t} not found`);let n=Ka(r)?.dependencyTaskIds??[];if(n.length<2)throw new wt("input_invalid",`DiagRouter task ${t} requires at least 2 predecessor dependencies (rootcause + distiller), got ${n.length}`);let i=await Promise.allSettled(n.map(h=>this.artifactStore.listBySourceTaskId(h))),a,s,c,u;for(let h=0;h<i.length;h++){let f=i[h];if(!f||f.status!=="fulfilled"||f.value.length===0)continue;let[g]=f.value;if(!g)continue;let y=n[h];if(y===void 0)continue;let T=await this.stateManager.getTask(y);if(T){if(T.taskKind==="diag_rootcause"&&!a){a=g.artifactId;let v;try{v=JSON.parse(g.contentJson)}catch{throw new wt("input_invalid",`Failed to parse root cause artifact content for predecessor task ${y}`)}if(!vo.Check(vd,v)){let E=[...vo.Errors(vd,v)].slice(0,3).map(L=>`${L.path}: ${L.message}`);throw new wt("input_invalid",`Root cause artifact content failed schema validation for predecessor task ${y}: ${E.join("; ")}`)}s=v}else if(T.taskKind==="diag_distiller"&&!c){c=g.artifactId;let v;try{v=JSON.parse(g.contentJson)}catch{throw new wt("input_invalid",`Failed to parse distiller artifact content for predecessor task ${y}`)}if(!vo.Check(v_,v)){let E=[...vo.Errors(v_,v)].slice(0,3).map(L=>`${L.path}: ${L.message}`);throw new wt("input_invalid",`Distiller artifact content failed schema validation for predecessor task ${y}: ${E.join("; ")}`)}u=v}}}if(!a||!s)throw new wt("input_invalid",`No root cause artifact found for DiagRouter task ${t}`);if(!c||!u)throw new wt("input_invalid",`No distiller artifact found for DiagRouter task ${t}`);let l=[a,c];return{contextHash:Wc.hashContextRefs(l),contextRefs:l,rootCauseArtifactId:a,rootCauseOutput:s,distillerArtifactId:c,distillerOutput:u}}async invokeRuntime(t,r){let o=new JG,{message:n}=o.buildPrompt({rootCauseArtifactId:r.rootCauseArtifactId,rootCauseOutput:r.rootCauseOutput,distillerArtifactId:r.distillerArtifactId,distillerOutput:r.distillerOutput},{outputLanguage:this.resolvedOptions.outputLanguage});return this.runtimeAdapter.startRun({agentSpec:{agentId:this.resolvedOptions.agentId,schemaVersion:"v1"},taskRef:{taskId:t},inputPayload:n,contextItems:[],outputSchemaRef:"diagnostician-output-v1",timeoutMs:this.resolvedOptions.timeoutMs})}async validateOutput(t,r,o){if(!vo.Check(du,t))return{valid:!1,errors:[...vo.Errors(du,t)].slice(0,5).map(a=>`${a.path}: ${a.message}`),errorCategory:"output_invalid"};let n=await this.defaultValidator.validate(t,r);return{valid:n.valid,errors:n.errors,errorCategory:n.errorCategory}}async succeedTask(t,r,o,n,i,a){try{await this.stateManager.updateRunOutput(r,JSON.stringify(o))}catch(m){throw this.emitEvent("update_output_failed",t,{runId:r,errorMessage:m instanceof Error?m.message:String(m)}),m}let s;try{s=await this.committer.commit({runId:r,taskId:t,output:o,idempotencyKey:`${t}:${r}`})}catch(m){throw this.emitEvent("artifact_commit_failed",t,{taskId:t,runId:r,errorCategory:m instanceof wt?m.category:"artifact_commit_failed",errorMessage:m instanceof Error?m.message:String(m)}),m}for(let m=0;m<o.recommendations.length;m++){let p=o.recommendations[m];p&&this.emitEvent("candidate_registered",t,{candidateIndex:m,commitId:s.commitId,kind:p.kind,description:p.description,sourceRunId:r})}this.emitEvent("artifact_committed",t,{commitId:s.commitId,artifactId:s.artifactId,candidateCount:s.candidateCount,taskId:t,runId:r});let c=`commit://${s.commitId}`;try{await this.stateManager.markTaskSucceeded(t,c)}catch(m){throw this.emitEvent("mark_succeeded_failed",t,{taskId:t,runId:r,commitId:s.commitId,errorMessage:m instanceof Error?m.message:String(m)}),m}let u=o.recommendations.map(m=>m.kind),l={};for(let m of u)l[m]=(l[m]??0)+1;return this.emitEvent("task_succeeded",t,{attemptCount:n.attemptCount,resultRef:c,commitId:s.commitId,candidateCount:s.candidateCount,recommendationKindHistogram:l}),{status:"succeeded",taskId:t,runId:r,artifactId:s.artifactId,resultRef:c,contextHash:i,output:o,attemptCount:n.attemptCount}}postFetchTransform(t,r,o){if(Td(r,"taskId",t),typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r,i=o.rootCauseOutput.rootCause;i!==void 0&&(n.rootCause!==i&&n.rootCause!==void 0&&this.emitEvent("invariant_override",t,{field:"rootCause",reason:"LLM output did not match Stage A rootCause \u2014 overridden with upstream value"}),n.rootCause=i);let a=o.rootCauseOutput.evidence;a!==void 0&&(n.evidence!==a&&n.evidence!==void 0&&this.emitEvent("invariant_override",t,{field:"evidence",reason:"LLM output did not match Stage A evidence \u2014 overridden with upstream value"}),n.evidence=a);let s=o.distillerOutput.confidence;s!==void 0&&(n.confidence!==s&&n.confidence!==void 0&&this.emitEvent("invariant_override",t,{field:"confidence",reason:"LLM output did not match Stage B confidence \u2014 overridden with upstream value"}),n.confidence=s);let c=o.rootCauseOutput.intentTension;c!==void 0?(n.intentTension!==void 0&&this.emitEvent("invariant_override",t,{field:"intentTension",reason:"LLM output had intentTension \u2014 overridden with Stage A passthrough value (SPEC \xA718.1)"}),n.intentTension=c):n.intentTension!==void 0&&(this.emitEvent("invariant_override",t,{field:"intentTension",reason:"LLM output had intentTension but Stage A did not produce one \u2014 stripped (SPEC \xA718.2: additive only, never generates)"}),delete n.intentTension)}}emitSuccessTelemetry(t,r,o){let n=r.recommendations.map(a=>a.kind),i={};for(let a of n)i[a]=(i[a]??0)+1;this.emitEvent("router_completed",t,{recommendationKindHistogram:i})}};import{mkdir as LLr,rm as DLr,writeFile as $Lr}from"node:fs/promises";import{tmpdir as zLr}from"node:os";import{join as l6e}from"node:path";import{spawn as p6e,execSync as NLr}from"child_process";function MLr(e){if(process.platform!=="win32"||e.includes("/")||e.includes("\\"))return e;try{let r=NLr(`where.exe ${e}`,{encoding:"utf-8",timeout:5e3,windowsHide:!0}).split(`
|
|
1011
|
-
`).map(n=>n.trim()).filter(Boolean),o=r.find(n=>/\.(cmd|bat|exe)$/i.test(n));if(o){let n=o.replace(/\\/g,"/");if(/^\/[a-z]\//i.test(n)){let i=n;return(i[1]??"C").toUpperCase()+":"+i.slice(2).replace(/\//g,"\\")}return o}if(r.length>0){let n=r[0]??e;if(/^[A-Z]:/i.test(n))return n;if(/^\/[a-z]\//i.test(n)){let i=n;return(i[1]??"C").toUpperCase()+":"+i.slice(2).replace(/\//g,"\\")}return n}}catch{}return e}async function h$(e){if(typeof e.command!="string"||e.command.trim()==="")throw new TypeError("opts.command must be a non-empty string");let{command:t}=e,r=e.args??[];if(!Array.isArray(r)||r.some(L=>typeof L!="string"))throw new TypeError("opts.args must be an array of strings");let o=r,{cwd:n}=e,{timeoutMs:i}=e,a=e.killGracePeriodMs??3e3,s=Object.assign({},process.env,e.env??{}),c="",u="",l=MLr(t),m=process.platform==="win32"&&/\.(cmd|bat)$/i.test(l),p=process.platform!=="win32"?{command:l,args:o,shell:!1}:m?{command:"cmd.exe",args:["/c",l.replace(/\\/g,"/"),...o],shell:!1}:{command:l,args:o,shell:!1},h=p6e(p.command,p.args,{cwd:n,env:s,shell:p.shell,detached:process.platform!=="win32"});h.stdout?.on("data",L=>{c+=L.toString()}),h.stderr?.on("data",L=>{u+=L.toString()});let f=Date.now(),g=null,y=null,T=!1;function v(){let{pid:L}=h;if(L!=null)if(process.platform==="win32")p6e("taskkill",["/PID",String(L),"/T","/F"]).on("error",()=>{});else try{process.kill(-L,"SIGTERM")}catch{}}function E(){g!==null&&(clearTimeout(g),g=null),y!==null&&(clearTimeout(y),y=null)}return i!=null&&(g=setTimeout(()=>{if(T=!0,v(),process.platform!=="win32"){let{pid:L}=h;y=setTimeout(()=>{if(L!=null)try{process.kill(-L,"SIGKILL")}catch{}},a)}},i)),new Promise(L=>{let H=!1;function B(Te){H||(H=!0,E(),L(Te))}h.on("close",Te=>{let Ce=Date.now()-f;B({stdout:c,stderr:u,exitCode:T?null:Te,timedOut:T,durationMs:Ce})}),h.on("error",Te=>{let Ce=Date.now()-f,ye=Te,Pe;ye.code==="ENOENT"?Pe="ENOENT":ye.code==="EACCES"?Pe="EACCES":ye.code==="EMFILE"?Pe="EMFILE":ye.code&&(Pe="UNKNOWN"),B({stdout:"",stderr:ye.code?`ENOENT: ${ye.code}`:Te.message,exitCode:null,timedOut:T,durationMs:Ce,spawnError:Pe})})})}async function d6e(e,t){let r=t?l6e(t,".pd","tmp"):zLr();await LLr(r,{recursive:!0});let o=l6e(r,`msg-${Date.now()}-${Math.random().toString(36).slice(2,7)}.json`);return await $Lr(o,e,"utf8"),{arg:`@${o.replace(/\\/g,"/")}`,dir:r}}async function m6e(e){if(!e)return;let t=e.arg.replace(/^@/,"");try{await DLr(t,{force:!0})}catch{}}function f6e(e,t){for(let r of[e,t??""]){if(!r)continue;try{return JSON.parse(r)}catch{}let o=[],n=0,i=-1;for(let a=0;a<r.length;a++){let s=r[a];if(s){if(s==="{")i===-1&&(i=a),n++;else if(s==="}"&&(n--,n===0&&i!==-1)){try{o.push(JSON.parse(r.slice(i,a+1)))}catch{}i=-1}}}if(o.length>0)return o[o.length-1]}return null}function g$(e){let t=0,r=-1;for(let o=0;o<e.length;o++){let n=e[o];if(n==="{")r===-1&&(r=o),t++;else if(n==="}"&&(t--,t===0&&r!==-1)){try{return JSON.parse(e.slice(r,o+1))}catch{}r=-1}}return null}function ULr(e){if(typeof e!="object"||e===null)return null;let t=e;if(Array.isArray(t.payloads)&&t.payloads.length>0){let[o]=t.payloads;if(o&&typeof o.text=="string"){let n=o.text.trim();try{return JSON.parse(n)}catch{}let i=g$(n);if(i!==null)return i}}let r=e;if(r.result&&typeof r.result=="object"&&Array.isArray(r.result.payloads)&&r.result.payloads.length>0){let[o]=r.result.payloads;if(o&&typeof o.text=="string"){let n=o.text.trim();try{return JSON.parse(n)}catch{}let i=g$(n);if(i!==null)return i}}return null}function FLr(e){let t=e;if(Array.isArray(t.payloads)&&t.payloads.length>0){let[o]=t.payloads;if(o&&typeof o.text=="string"){let n=o.text.trim();try{return JSON.parse(n)}catch{}let i=g$(n);if(i!==null)return i}}let r=e;if(r.result&&typeof r.result=="object"&&Array.isArray(r.result.payloads)&&r.result.payloads.length>0){let[o]=r.result.payloads;if(o&&typeof o.text=="string"){let n=o.text.trim();try{return JSON.parse(n)}catch{}let i=g$(n);if(i!==null)return i}}return typeof e=="object"&&e!==null?e:null}var Cx=class e{runStateMap=new Map;runtimeMode;workspaceDir;agentId;eventEmitter;constructor(t){this.runtimeMode=t.runtimeMode,this.workspaceDir=t.workspaceDir,this.agentId=t.agentId??"main",this.eventEmitter=t.eventEmitter??ks}kind(){return"openclaw-cli"}async getCapabilities(){return{supportsStructuredJsonOutput:!0,supportsToolUse:!1,supportsWorkingDirectory:!1,supportsModelSelection:!1,supportsLongRunningSessions:!1,supportsCancellation:!0,supportsArtifactWriteBack:!1,supportsConcurrentRuns:!1,supportsStreaming:!1}}async healthCheck(){let t=[],r=!0,o=!1;try{let i=await h$({command:"openclaw",args:["--version"],cwd:this.workspaceDir,timeoutMs:1e4});if(i.spawnError==="ENOENT")return{healthy:!1,degraded:!1,warnings:["openclaw binary not found"],lastCheckedAt:new Date().toISOString()};if(i.spawnError==="EACCES"||i.spawnError==="EMFILE")return{healthy:!1,degraded:!1,warnings:[`openclaw binary not executable: ${i.spawnError}`],lastCheckedAt:new Date().toISOString()};if(i.timedOut)return{healthy:!1,degraded:!1,warnings:["openclaw --version timed out"],lastCheckedAt:new Date().toISOString()};i.exitCode!==null&&i.exitCode!==0&&(o=!0,t.push(`openclaw --version exited with code ${i.exitCode}`))}catch(i){return{healthy:!1,degraded:!1,warnings:[i instanceof Error?i.message:String(i)],lastCheckedAt:new Date().toISOString()}}try{let i=["agents","list","--json"];this.runtimeMode==="local"&&i.push("--local");let a=await h$({command:"openclaw",args:i,cwd:this.workspaceDir,timeoutMs:15e3});if(a.spawnError==="ENOENT")return{healthy:!1,degraded:!1,warnings:["openclaw binary not found"],lastCheckedAt:new Date().toISOString()};if(a.spawnError==="EACCES"||a.spawnError==="EMFILE")return{healthy:!1,degraded:!1,warnings:[`openclaw binary not executable: ${a.spawnError}`],lastCheckedAt:new Date().toISOString()};if(a.timedOut)o=!0,t.push("openclaw agents list timed out");else if(a.exitCode!==null&&a.exitCode!==0)o=!0,t.push(`openclaw agents list exited with code ${a.exitCode}`);else try{let s=a.stdout.indexOf("[");if(s===-1)throw new Error("No JSON array found");let c=a.stdout.slice(s);JSON.parse(c).map(m=>typeof m=="string"?m:m.id).includes(this.agentId)||(r=!1,t.push(`agent '${this.agentId}' not found in agents list`))}catch{o=!0,t.push("failed to parse agents list output")}}catch(i){return{healthy:!1,degraded:!1,warnings:[i instanceof Error?i.message:String(i)],lastCheckedAt:new Date().toISOString()}}let n;try{let i=`pd-runtime-probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;n=await d6e(JSON.stringify({probe:"pd-runtime-v2",instruction:'reply with {"ok":true} only'}),this.workspaceDir);let a=["agent","--agent",this.agentId,"--message",n.arg,"--session-id",i,"--timeout","240","--json"];this.runtimeMode==="local"&&a.push("--local");let s=await h$({command:"openclaw",args:a,cwd:this.workspaceDir,timeoutMs:24e4});if(s.spawnError==="ENOENT")return{healthy:!1,degraded:!1,warnings:["openclaw binary not found"],lastCheckedAt:new Date().toISOString()};if(s.spawnError==="EACCES"||s.spawnError==="EMFILE")return{healthy:!1,degraded:!1,warnings:[`openclaw binary not executable: ${s.spawnError}`],lastCheckedAt:new Date().toISOString()};if(s.timedOut)return{healthy:!1,degraded:!1,warnings:["openclaw agent probe timed out"],lastCheckedAt:new Date().toISOString()};if(s.exitCode!==null&&s.exitCode!==0)return{healthy:!1,degraded:!1,warnings:[`openclaw agent '${this.agentId}' probe failed with exit code ${s.exitCode}`,...s.stderr?[`stderr: ${s.stderr.substring(0,2e3)}`]:[]],lastCheckedAt:new Date().toISOString()};let c=f6e(s.stdout,s.stderr);if(c===null)return{healthy:!1,degraded:!1,warnings:["openclaw agent probe produced unparseable output"],lastCheckedAt:new Date().toISOString()};let u=FLr(c);if(typeof u!="object"||u===null||!Object.hasOwn(u,"ok")||u.ok!==!0){let l=c&&typeof c=="object"?JSON.stringify(c).substring(0,2e3):String(c).substring(0,2e3);return{healthy:!1,degraded:!1,warnings:[`openclaw agent '${this.agentId}' probe returned unexpected result: ${l}`],lastCheckedAt:new Date().toISOString()}}}catch(i){return{healthy:!1,degraded:!1,warnings:[i instanceof Error?i.message:String(i)],lastCheckedAt:new Date().toISOString()}}finally{await m6e(n)}return{healthy:r,degraded:o,warnings:t,lastCheckedAt:new Date().toISOString()}}static mapCliResultToTelemetry(t){return t.spawnError==="ENOENT"?{telemetryEventType:"runtime_invocation_failed",errorCategory:"runtime_unavailable",stderrExcerpt:t.stderr}:t.spawnError==="EACCES"||t.spawnError==="EMFILE"?{telemetryEventType:"runtime_invocation_failed",errorCategory:"execution_failed",stderrExcerpt:t.stderr}:t.timedOut?{telemetryEventType:"runtime_invocation_failed",errorCategory:"timeout",stderrExcerpt:t.stderr}:t.exitCode!==null&&t.exitCode!==0?{telemetryEventType:"runtime_invocation_failed",errorCategory:"execution_failed",stderrExcerpt:t.stderr}:{telemetryEventType:"runtime_invocation_succeeded",errorCategory:void 0,stderrExcerpt:void 0}}async startRun(t){let r=crypto.randomUUID(),o=new Date().toISOString(),n={runId:r,startedAt:o,cliOutput:null,completed:!1};this.runStateMap.set(r,n);let i=typeof t.inputPayload=="string"?t.inputPayload:JSON.stringify(t.inputPayload),a=Math.ceil((t.timeoutMs??6e5)/1e3),s=t.agentSpec?.agentId??"main",c=await d6e(i,this.workspaceDir),u=`pd-runtime-${r}`,l=["agent","--agent",s,"--message",c.arg,"--session-id",u,"--json"];this.runtimeMode==="local"&&l.push("--local"),l.push("--timeout",String(a)),this.eventEmitter.emitTelemetry({eventType:"runtime_invocation_started",traceId:t.taskRef?.taskId??r,timestamp:new Date().toISOString(),sessionId:"openclaw-cli-adapter",agentId:"openclaw-cli-adapter",payload:{runId:r,runtimeKind:"openclaw-cli",runtimeMode:this.runtimeMode,timeoutMs:t.timeoutMs}});let m=await(async()=>{try{return await h$({command:"openclaw",args:l,cwd:this.workspaceDir,timeoutMs:t.timeoutMs})}finally{await m6e(c)}})();n.cliOutput=m,n.completed=!0;let p=new Date().toISOString(),{telemetryEventType:h,errorCategory:f,stderrExcerpt:g}=e.mapCliResultToTelemetry(m);return this.eventEmitter.emitTelemetry({eventType:h,traceId:t.taskRef?.taskId??r,timestamp:p,sessionId:"openclaw-cli-adapter",agentId:"openclaw-cli-adapter",payload:{runId:r,runtimeKind:"openclaw-cli",runtimeMode:this.runtimeMode,exitCode:m.exitCode,timedOut:m.timedOut,...f?{errorCategory:f}:{},...g?{stderrExcerpt:g}:{}}}),{runId:r,runtimeKind:"openclaw-cli",startedAt:o}}async pollRun(t){let r=this.runStateMap.get(t);if(!r)throw new wt("output_invalid",`Run ${t} not found`);if(!r.completed||!r.cliOutput)return{runId:t,status:"running",startedAt:r.startedAt};let{cliOutput:o}=r;if(o.timedOut)return{runId:t,status:"timed_out",startedAt:r.startedAt,endedAt:new Date().toISOString(),reason:"CLI timeout exceeded"};if(o.exitCode!==null&&o.exitCode!==0){let n=o.stderr?o.stderr.substring(0,2e3):void 0;return{runId:t,status:"failed",startedAt:r.startedAt,endedAt:new Date().toISOString(),reason:n?`CLI exited with code ${o.exitCode}. stderr: ${n}`:`CLI exited with code ${o.exitCode}`}}return{runId:t,status:"succeeded",startedAt:r.startedAt,endedAt:new Date().toISOString()}}async fetchOutput(t){let r=this.runStateMap.get(t);if(!r||!r.completed||!r.cliOutput)throw new wt("output_invalid",`Run ${t} not completed`);let{cliOutput:o}=r;if(o.spawnError==="ENOENT")throw new wt("runtime_unavailable","openclaw binary not found");if(o.timedOut)throw new wt("timeout","CLI timeout exceeded");if(o.exitCode!==null&&o.exitCode!==0){let a=o.stderr?o.stderr.substring(0,2e3):void 0;throw new wt("execution_failed",a?`CLI exited with code ${o.exitCode}. stderr: ${a}`:`CLI exited with code ${o.exitCode}`)}let n,i=f6e(o.stdout,o.stderr);if(i!==null?n=ULr(i)??i:n=null,n===null){let a=[o.stdout,o.stderr??""];for(let s of a){if(!s)continue;let c=g$(s);if(c!==null){n=c;break}}if(n===null)for(let s of a){if(!s)continue;let c=HJe(s);if(c!==null){n=c;break}}if(n===null){let s=o.stdout||o.stderr||"",c=Ix(s.substring(0,2e3)),u=zm(typeof c=="string"?c:"",500);throw new wt("output_invalid","Failed to parse CLI output as JSON",{parseFailureReason:"no_json_object_found",boundedRawOutputPreview:u,nextAction:"Check openclaw agent output format; ensure agent returns valid JSON"})}}if(!vo.Check(du,n)){let a=[...vo.Errors(du,n)].slice(0,10).map(u=>({path:u.path,message:u.message})),s=p$(n),c=s.ok?ec(s.value,500):ec(n,500);throw new wt("output_invalid","CLI output does not match DiagnosticianOutputV1 schema",{parseFailureReason:"schema_validation_failed",boundedRawOutputPreview:c,schemaErrors:a,nextAction:"Review schema errors; check LLM output format and required fields"})}return{runId:t,payload:n}}async cancelRun(t){let r=this.runStateMap.get(t);r&&!r.completed&&(r.completed=!0)}async fetchArtifacts(t){return[]}};var dt={};to(dt,{Assign:()=>qLr,Clone:()=>b$,Create:()=>A2r,Discard:()=>O2r,Metrics:()=>Kh,Update:()=>P2r});var Kh={assign:0,create:0,clone:0,discard:0,update:0};function qLr(e,t){return Kh.assign+=1,{...e,...t}}var ae={};to(ae,{And:()=>zle,ArrayLiteral:()=>WDr,ArrowFunction:()=>jDr,Call:()=>GDr,ConstDeclaration:()=>HDr,Constant:()=>A6e,Entries:()=>zDr,Every:()=>$Dr,HasPropertyKey:()=>FDr,If:()=>XDr,IsArray:()=>I6e,IsAsyncIterator:()=>_Dr,IsBigInt:()=>yDr,IsBoolean:()=>xDr,IsConstructor:()=>CDr,IsDeepEqual:()=>qDr,IsEqual:()=>ADr,IsFunction:()=>IDr,IsGreaterEqualThan:()=>MDr,IsGreaterThan:()=>ODr,IsInteger:()=>bDr,IsIterator:()=>SDr,IsLessEqualThan:()=>NDr,IsLessThan:()=>PDr,IsMaxLength:()=>DDr,IsMinLength:()=>LDr,IsNull:()=>vDr,IsNumber:()=>TDr,IsObject:()=>C6e,IsObjectNotArray:()=>EDr,IsString:()=>RDr,IsSymbol:()=>wDr,IsUndefined:()=>kDr,Keys:()=>UDr,Member:()=>VDr,MultipleOf:()=>t2r,New:()=>JDr,Not:()=>k6e,Or:()=>w6e,PrefixIncrement:()=>e2r,ReduceAnd:()=>QDr,ReduceOr:()=>ZDr,Return:()=>YDr,Statements:()=>KDr,Ternary:()=>BDr});var N={};to(N,{Entries:()=>pDr,EntriesRegExp:()=>uDr,Every:()=>aDr,EveryAll:()=>sDr,GraphemeCount:()=>oDr,HasPropertyKey:()=>cDr,IsArray:()=>y$,IsAsyncIterator:()=>BLr,IsBigInt:()=>_$,IsBoolean:()=>S6e,IsClassInstance:()=>tDr,IsConstructor:()=>KLr,IsDeepEqual:()=>$le,IsEqual:()=>vn,IsFunction:()=>v6e,IsGreaterEqualThan:()=>E6e,IsGreaterThan:()=>QLr,IsInteger:()=>Lle,IsIterator:()=>HLr,IsLessEqualThan:()=>T6e,IsLessThan:()=>ZLr,IsMaxLength:()=>nDr,IsMinLength:()=>iDr,IsMultipleOf:()=>eDr,IsNull:()=>HG,IsNumber:()=>XG,IsObject:()=>yR,IsObjectNotArray:()=>XLr,IsString:()=>x$,IsSymbol:()=>YLr,IsUndefined:()=>Dle,IsUnsafePropertyKey:()=>R6e,IsValueLike:()=>rDr,Keys:()=>KG,Symbols:()=>lDr,TakeLeft:()=>YG,Values:()=>dDr});function Vb(e,t,r){return e>=t&&e<=r}function h6e(e){return Vb(e,127462,127487)}function WLr(e){return Vb(e,65024,65039)}function jLr(e){return Vb(e,768,879)||Vb(e,6832,6911)||Vb(e,7616,7679)||Vb(e,65056,65071)}function BG(e){return e>65535?2:1}function g6e(e,t){for(;t<e.length;){let r=e.codePointAt(t);if(jLr(r)||WLr(r))t+=BG(r);else break}return t}function Mle(e,t){let r=e.codePointAt(t),o=t+BG(r);for(o=g6e(e,o);o<e.length-1&&e[o]==="\u200D";){let n=e.codePointAt(o+1);o+=1+BG(n),o=g6e(e,o)}return h6e(r)&&o<e.length&&h6e(e.codePointAt(o))&&(o+=BG(e.codePointAt(o))),o}function _6e(e){return Vb(e,55296,56319)||Vb(e,768,879)||e===8205}function y6e(e){let t=0,r=0;for(;r<e.length;)r=Mle(e,r),t++;return t}function GLr(e,t){if(t===0)return!0;let r=0,o=0;for(;o<e.length;)if(o=Mle(e,o),r++,r>=t)return!0;return!1}function JLr(e,t){let r=0,o=0;for(;o<e.length;)if(o=Mle(e,o),r++,r>t)return!1;return!0}function x6e(e,t){if(t===0)return!0;let r=0;for(;r<e.length;){if(_6e(e.charCodeAt(r)))return GLr(e,t);if(r++,r>=t)return!0}return!1}function b6e(e,t){let r=0;for(;r<e.length;){if(_6e(e.charCodeAt(r)))return JLr(e,t);if(r++,r>t)return!1}return!0}function y$(e){return Array.isArray(e)}function BLr(e){return yR(e)&&Symbol.asyncIterator in e}function _$(e){return vn(typeof e,"bigint")}function S6e(e){return vn(typeof e,"boolean")}function KLr(e){if(Dle(e)||!v6e(e))return!1;let t=Function.prototype.toString.call(e);return!!(/^class\s/.test(t)||/\[native code\]/.test(t))}function v6e(e){return vn(typeof e,"function")}function Lle(e){return Number.isInteger(e)}function HLr(e){return yR(e)&&Symbol.iterator in e}function HG(e){return vn(e,null)}function XG(e){return Number.isFinite(e)}function XLr(e){return yR(e)&&!y$(e)}function yR(e){return vn(typeof e,"object")&&!HG(e)}function x$(e){return vn(typeof e,"string")}function YLr(e){return vn(typeof e,"symbol")}function Dle(e){return vn(e,void 0)}function vn(e,t){return e===t}function QLr(e,t){return e>t}function ZLr(e,t){return e<t}function T6e(e,t){return e<=t}function E6e(e,t){return e>=t}function eDr(e,t){if(_$(e)||_$(t))return BigInt(e)%BigInt(t)===0n;let r=1e-10;if(!XG(e)||Lle(e)&&1/t%1===0)return!0;let o=e%t;return Math.min(Math.abs(o),Math.abs(o-t))<r}function tDr(e){if(!yR(e))return!1;let t=globalThis.Object.getPrototypeOf(e);return HG(t)?!1:vn(typeof t.constructor,"function")&&!(vn(t.constructor,globalThis.Object)||vn(t.constructor.name,"Object"))}function rDr(e){return _$(e)||S6e(e)||HG(e)||XG(e)||x$(e)||Dle(e)}function oDr(e){return y6e(e)}function nDr(e,t){return b6e(e,t)}function iDr(e,t){return x6e(e,t)}function aDr(e,t,r){for(let o=t;o<e.length;o++)if(!r(e[o],o))return!1;return!0}function sDr(e,t,r){let o=!0;for(let n=t;n<e.length;n++)r(e[n],n)||(o=!1);return o}function YG(e,t,r){return vn(e.length,0)?r():t(e[0],e.slice(1))}function R6e(e){return vn(e,"__proto__")||vn(e,"constructor")||vn(e,"prototype")}function cDr(e,t){return R6e(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function uDr(e){return KG(e).map(t=>[new RegExp(`^${t}$`),e[t]])}function pDr(e){return Object.entries(e)}function KG(e){return Object.getOwnPropertyNames(e)}function lDr(e){return Object.getOwnPropertySymbols(e)}function dDr(e){return Object.values(e)}function mDr(e,t){if(!yR(t))return!1;let r=KG(e);return vn(r.length,KG(t).length)&&r.every(o=>$le(e[o],t[o]))}function fDr(e,t){return y$(t)&&vn(e.length,t.length)&&e.every((r,o)=>$le(e[o],t[o]))}function $le(e,t){return y$(e)?fDr(e,t):yR(e)?mDr(e,t):vn(e,t)}var hDr=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function gDr(e){return hDr.test(e)}function zle(e,t){return`(${e} && ${t})`}function w6e(e,t){return`(${e} || ${t})`}function k6e(e){return`!(${e})`}function I6e(e){return`Array.isArray(${e})`}function _Dr(e){return`Guard.IsAsyncIterator(${e})`}function yDr(e){return`typeof ${e} === "bigint"`}function xDr(e){return`typeof ${e} === "boolean"`}function bDr(e){return`Number.isInteger(${e})`}function SDr(e){return`Guard.IsIterator(${e})`}function vDr(e){return`${e} === null`}function TDr(e){return`Number.isFinite(${e})`}function EDr(e){return zle(C6e(e),k6e(I6e(e)))}function C6e(e){return`typeof ${e} === "object" && ${e} !== null`}function RDr(e){return`typeof ${e} === "string"`}function wDr(e){return`typeof ${e} === "symbol"`}function kDr(e){return`${e} === undefined`}function IDr(e){return`typeof ${e} === "function"`}function CDr(e){return`Guard.IsConstructor(${e})`}function ADr(e,t){return`${e} === ${t}`}function ODr(e,t){return`${e} > ${t}`}function PDr(e,t){return`${e} < ${t}`}function NDr(e,t){return`${e} <= ${t}`}function MDr(e,t){return`${e} >= ${t}`}function LDr(e,t){return`Guard.IsMinLength(${e}, ${t})`}function DDr(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function $Dr(e,t,r,o){return vn(t,"0")?`${e}.every((${r[0]}, ${r[1]}) => ${o})`:`((value, callback) => { for(let index = ${t}; index < value.length; index++) if (!callback(value[index], index)) return false; return true })(${e}, (${r[0]}, ${r[1]}) => ${o})`}function zDr(e){return`Object.entries(${e})`}function UDr(e){return`Object.getOwnPropertyNames(${e})`}function FDr(e,t){return vn(t,'"__proto__"')||vn(t,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function qDr(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function WDr(e){return`[${e.join(", ")}]`}function jDr(e,t){return`((${e.join(", ")}) => ${t})`}function GDr(e,t){return`${e}(${t.join(", ")})`}function JDr(e,t){return`new ${e}(${t.join(", ")})`}function VDr(e,t){return`${e}${gDr(t)?`.${t}`:`[${A6e(t)}]`}`}function A6e(e){return x$(e)?JSON.stringify(e):`${e}`}function BDr(e,t,r){return`(${e} ? ${t} : ${r})`}function KDr(e){return`{ ${e.join("; ")}; }`}function HDr(e,t){return`const ${e} = ${t}`}function XDr(e,t){return`if(${e}) { ${t} }`}function YDr(e){return`return ${e}`}function QDr(e){return vn(e.length,0)?"true":e.reduce((t,r)=>zle(t,r))}function ZDr(e){return vn(e.length,0)?"false":e.reduce((t,r)=>w6e(t,r))}function e2r(e){return`++${e}`}function t2r(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}var Sa={};to(Sa,{IsBigInt64Array:()=>h2r,IsBigUint64Array:()=>g2r,IsBoolean:()=>r2r,IsDate:()=>y2r,IsFloat32Array:()=>m2r,IsFloat64Array:()=>f2r,IsInt16Array:()=>u2r,IsInt32Array:()=>l2r,IsInt8Array:()=>a2r,IsMap:()=>b2r,IsNumber:()=>o2r,IsRegExp:()=>_2r,IsSet:()=>x2r,IsString:()=>n2r,IsTypeArray:()=>i2r,IsUint16Array:()=>p2r,IsUint32Array:()=>d2r,IsUint8Array:()=>s2r,IsUint8ClampedArray:()=>c2r});function r2r(e){return e instanceof Boolean}function o2r(e){return e instanceof Number}function n2r(e){return e instanceof String}function i2r(e){return globalThis.ArrayBuffer.isView(e)}function a2r(e){return e instanceof globalThis.Int8Array}function s2r(e){return e instanceof globalThis.Uint8Array}function c2r(e){return e instanceof globalThis.Uint8ClampedArray}function u2r(e){return e instanceof globalThis.Int16Array}function p2r(e){return e instanceof globalThis.Uint16Array}function l2r(e){return e instanceof globalThis.Int32Array}function d2r(e){return e instanceof globalThis.Uint32Array}function m2r(e){return e instanceof globalThis.Float32Array}function f2r(e){return e instanceof globalThis.Float64Array}function h2r(e){return e instanceof globalThis.BigInt64Array}function g2r(e){return e instanceof globalThis.BigUint64Array}function _2r(e){return e instanceof globalThis.RegExp}function y2r(e){return e instanceof globalThis.Date}function x2r(e){return e instanceof globalThis.Set}function b2r(e){return e instanceof globalThis.Map}function v2r(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~guard")}function T2r(e){return e.map(t=>Ule(t))}function E2r(e){let t={},r=Object.getOwnPropertyDescriptors(e);for(let o of Object.keys(r)){let n=r[o];N.HasPropertyKey(n,"value")&&Object.defineProperty(t,o,{...n,value:Ule(n.value)})}return t}function R2r(e){return new RegExp(e.source,e.flags)}function Ule(e){return e instanceof RegExp?R2r(e):v2r(e)?e:N.IsArray(e)?T2r(e):N.IsObject(e)?E2r(e):e}function b$(e){return Kh.clone+=1,Ule(e)}var mu={};to(mu,{Get:()=>I2r,Reset:()=>w2r,Set:()=>k2r});var Bb={immutableTypes:!1,maxErrors:8,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1};function w2r(){Bb.immutableTypes=!1,Bb.maxErrors=8,Bb.useAcceleration=!0,Bb.exactOptionalPropertyTypes=!1,Bb.enumerableKind=!1,Bb.correctiveParse=!1}function k2r(e){for(let t of N.Keys(e)){let r=e[t];r!==void 0&&Object.defineProperty(Bb,t,{value:r})}}function I2r(){return Bb}function C2r(e,t){for(let r of Object.keys(t))Object.defineProperty(e,r,{configurable:!0,writable:!0,enumerable:!1,value:t[r]});return e}function O6e(e,t){return{...e,...t}}function A2r(e,t,r={}){Kh.create+=1;let o=mu.Get(),n=O6e(t,r),i=o.enumerableKind?O6e(n,e):C2r(n,e);return o.immutableTypes?Object.freeze(i):i}function O2r(e,t){Kh.discard+=1;let r={},o=Object.getOwnPropertyDescriptors(b$(e)),n=new Set(t);for(let i of Object.keys(o))n.has(i)||Object.defineProperty(r,i,o[i]);return r}function P2r(e,t,r){Kh.update+=1;let o=mu.Get(),n=b$(e);for(let i of Object.keys(t))Object.defineProperty(n,i,{configurable:!0,writable:!0,enumerable:o.enumerableKind,value:t[i]});for(let i of Object.keys(r))Object.defineProperty(n,i,{configurable:!0,enumerable:!0,writable:!0,value:r[i]});return n}function Vr(e,t){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.IsEqual(e["~kind"],t)}function Bi(e){return N.IsObject(e)}function P6e(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.HasPropertyKey(e,"type")&&N.IsEqual(e["~kind"],"OptionalAddAction")&&Bi(e.type)}function N6e(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.HasPropertyKey(e,"type")&&N.IsEqual(e["~kind"],"OptionalRemoveAction")&&Bi(e.type)}function M6e(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.HasPropertyKey(e,"type")&&N.IsEqual(e["~kind"],"ReadonlyAddAction")&&Bi(e.type)}function L6e(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.HasPropertyKey(e,"type")&&N.IsEqual(e["~kind"],"ReadonlyRemoveAction")&&Bi(e.type)}function Io(e,t,r){return dt.Create({"~kind":"Deferred"},{action:e,parameters:t,options:r},{})}function Kb(e){return Vr(e,"Deferred")}function T_(e,t){return dt.Create({"~kind":"Promise"},{type:"promise",item:e},t)}function tc(e){return Vr(e,"Promise")}function D6e(e){return dt.Discard(e,["~kind","type","item"])}function $6e(e){return dt.Update(e,{"~immutable":!0},{})}function xR(e){return $6e(e)}function KC(e){return Bi(e)&&N.HasPropertyKey(e,"~immutable")}function HC(e){return dt.Discard(e,["~optional"])}function bR(e){return dt.Update(e,{"~optional":!0},{})}function Fle(e){return bR(e)}function gc(e){return Bi(e)&&N.HasPropertyKey(e,"~optional")}function QG(e){return dt.Discard(e,["~readonly"])}function SR(e){return dt.Update(e,{"~readonly":!0},{})}function qle(e){return SR(e)}function XC(e){return Bi(e)&&N.HasPropertyKey(e,"~readonly")}function z6e(e){return{enumerable:mu.Get().enumerableKind,writable:!1,configurable:!1,value:e}}var S$=class{constructor(){globalThis.Object.defineProperty(this,"~kind",z6e("Base")),globalThis.Object.defineProperty(this,"~guard",z6e({check:t=>this.Check(t),errors:t=>this.Errors(t)}))}Check(t){return!0}Errors(t){return[]}Convert(t){return t}Clean(t){return t}Default(t){return t}Create(){throw new Error("Create not implemented")}Clone(){throw Error("Clone not implemented")}};function Ed(e){return Vr(e,"Base")}function E_(e,t){return dt.Create({"~kind":"Array"},{type:"array",items:e},t)}function jn(e){return Vr(e,"Array")}function ZG(e){return dt.Discard(e,["~kind","type","items"])}function R_(e,t){return dt.Create({"~kind":"AsyncIterator"},{type:"asyncIterator",iteratorItems:e},t)}function jc(e){return Vr(e,"AsyncIterator")}function U6e(e){return dt.Discard(e,["~kind","type","iteratorItems"])}function Hb(e,t,r={}){return dt.Create({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:t},r)}function xs(e){return Vr(e,"Constructor")}function F6e(e){return dt.Discard(e,["~kind","type","parameters","instanceType"])}function Xb(e,t,r={}){return dt.Create({"~kind":"Function"},{type:"function",parameters:e,returnType:t},r)}function bs(e){return Vr(e,"Function")}function q6e(e){return dt.Discard(e,["~kind","type","parameters","returnType"])}function Uu(e,t){return dt.Create({"~kind":"Ref"},{$ref:e},t)}function bi(e){return Vr(e,"Ref")}function eJ(e,t){return dt.Create({"~kind":"Generic"},{type:"generic",parameters:e,expression:t})}function v$(e){return Vr(e,"Generic")}function tJ(e){return dt.Create({"~kind":"Any"},{},e)}function Gc(e){return Vr(e,"Any")}var W6e="(?!)";function qi(e){return dt.Create({"~kind":"Never"},{not:{}},e)}function Hh(e){return Vr(e,"Never")}function j6e(e){return N.Keys(e).filter(t=>!gc(e[t]))}function rJ(e){return N.Keys(e)}function oJ(e){return N.Values(e)}function Do(e,t={}){let r=j6e(e),o=r.length>0?{required:r}:{};return dt.Create({"~kind":"Object"},{type:"object",...o,properties:e},t)}function Po(e){return Vr(e,"Object")}function G6e(e){return dt.Discard(e,["~kind","type","properties","required"])}function gn(e,t={}){return dt.Create({"~kind":"Union"},{anyOf:e},t)}function zr(e){return Vr(e,"Union")}function J6e(e){return dt.Discard(e,["~kind","anyOf"])}function Xh(e){return dt.Create({"~kind":"Unknown"},{},e)}function fu(e){return Vr(e,"Unknown")}function Ax(e,t,r){let o=N.Keys(e).reduce((n,i)=>({...n,[i]:dt.Update(e[i],{},{$id:i})}),{});return dt.Create({"~kind":"Cyclic"},{$defs:o,$ref:t},r)}function oa(e){return Vr(e,"Cyclic")}function Wle(e){return N.IsObjectNotArray(e)&&N.HasPropertyKey(e,"~unsafe")&&N.IsNull(e["~unsafe"])}var un={};to(un,{Match:()=>N2r});function N2r(e,t){return t[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function Is(e){return Vr(e,"Infer")}function Ss(e){return Vr(e,"Enum")}function qm(e,t={}){return dt.Create({"~kind":"Intersect"},{allOf:e},t)}function Ao(e){return Vr(e,"Intersect")}function V6e(e){return dt.Discard(e,["~kind","allOf"])}var YC={};to(YC,{CanEvaluate:()=>L2r,Evaluate:()=>B6e});var jle;function M2r(){try{return B6e("null")(),!0}catch{return!1}}function L2r(){return N.IsUndefined(jle)&&(jle=M2r()),jle&&mu.Get().useAcceleration}function B6e(...e){return new globalThis.Function(...e)}var Wm={};to(Wm,{Hash:()=>Z2r,HashCode:()=>Z6e});function mi(){throw new Error("Unreachable")}function D2r(e){let t=new Set,r=e;for(;r&&r!==Object.prototype;){for(let o of Reflect.ownKeys(r))o!=="constructor"&&typeof o!="symbol"&&t.add(o);r=Object.getPrototypeOf(r)}return[...t]}function $2r(e){return typeof e=="number"}var fp;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(fp||(fp={}));var QC=BigInt("14695981039346656037"),[z2r,U2r]=[BigInt("1099511628211"),BigInt("18446744073709551616")],F2r=Array.from({length:256}).map((e,t)=>BigInt(t)),X6e=new Float64Array(1),Y6e=new DataView(X6e.buffer),Q6e=new Uint8Array(X6e.buffer);function Jc(e){QC=QC^F2r[e],QC=QC*z2r%U2r}function q2r(e){Jc(fp.Array);for(let t of e)Yb(t)}function W2r(e){Jc(fp.BigInt),Y6e.setBigInt64(0,e);for(let t of Q6e)Jc(t)}function K6e(e){Jc(fp.Boolean),Jc(e?1:0)}function j2r(e){Jc(fp.Constructor),Yb(e.toString())}function G2r(e){Jc(fp.Date),Yb(e.getTime())}function J2r(e){Jc(fp.Function),Yb(e.toString())}function V2r(e){Jc(fp.Null)}function H6e(e){Jc(fp.Number),Y6e.setFloat64(0,e,!0);for(let t of Q6e)Jc(t)}function B2r(e){Jc(fp.Object);for(let t of D2r(e).sort())Yb(t),Yb(e[t])}function K2r(e){Jc(fp.RegExp),Gle(e.toString())}var H2r=new TextEncoder;function Gle(e){Jc(fp.String);for(let t of H2r.encode(e))Jc(t)}function X2r(e){Jc(fp.Symbol),Yb(e.toString())}function Y2r(e){Jc(fp.TypeArray);let t=new Uint8Array(e.buffer);for(let r=0;r<t.length;r++)Jc(t[r])}function Q2r(e){return Jc(fp.Undefined)}function Yb(e){return Sa.IsTypeArray(e)?Y2r(e):Sa.IsDate(e)?G2r(e):Sa.IsRegExp(e)?K2r(e):Sa.IsBoolean(e)?K6e(e.valueOf()):Sa.IsString(e)?Gle(e.valueOf()):Sa.IsNumber(e)?H6e(e.valueOf()):$2r(e)?H6e(e):N.IsArray(e)?q2r(e):N.IsBoolean(e)?K6e(e):N.IsBigInt(e)?W2r(e):N.IsConstructor(e)?j2r(e):N.IsNull(e)?V2r(e):N.IsObject(e)?B2r(e):N.IsString(e)?Gle(e):N.IsSymbol(e)?X2r(e):N.IsUndefined(e)?Q2r(e):N.IsFunction(e)?J2r(e):mi()}function Z6e(e){return QC=BigInt("14695981039346656037"),Yb(e),QC}function Z2r(e){return Z6e(e).toString(16).padStart(16,"0")}function eVe(e){switch(e.keyword){case"additionalProperties":return"must not have additional properties";case"anyOf":return"must match a schema in anyOf";case"boolean":return"schema is false";case"const":return"must be equal to constant";case"contains":return"must contain at least 1 valid item";case"dependencies":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"dependentRequired":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"enum":return"must be equal to one of the allowed values";case"exclusiveMaximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"exclusiveMinimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"format":return`must match format "${e.params.format}"`;case"if":return`must match "${e.params.failingKeyword}" schema`;case"maxItems":return`must not have more than ${e.params.limit} items`;case"maxLength":return`must not have more than ${e.params.limit} characters`;case"maxProperties":return`must not have more than ${e.params.limit} properties`;case"maximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"minItems":return`must not have fewer than ${e.params.limit} items`;case"minLength":return`must not have fewer than ${e.params.limit} characters`;case"minProperties":return`must not have fewer than ${e.params.limit} properties`;case"minimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"multipleOf":return`must be multiple of ${e.params.multipleOf}`;case"not":return"must not be valid";case"oneOf":return"must match exactly one schema in oneOf";case"pattern":return`must match pattern "${e.params.pattern}"`;case"propertyNames":return`property names ${e.params.propertyNames.join(", ")} are invalid`;case"required":return`must have required properties ${e.params.requiredProperties.join(", ")}`;case"type":return typeof e.params.type=="string"?`must be ${e.params.type}`:`must be either ${e.params.type.join(" or ")}`;case"unevaluatedItems":return"must not have unevaluated items";case"unevaluatedProperties":return"must not have unevaluated properties";case"uniqueItems":return"must not have duplicate items";case"~guard":return"must match check function";case"~refine":return e.params.message;default:return"an unknown validation error occurred"}}var e$r=eVe;function tVe(){return e$r}function Rd(e){return Bi(e)&&N.HasPropertyKey(e,"~codec")&&N.IsObject(e["~codec"])&&N.HasPropertyKey(e["~codec"],"encode")&&N.HasPropertyKey(e["~codec"],"decode")}function r$r(e){return N.IsObjectNotArray(e)&&N.HasPropertyKey(e,"check")&&N.HasPropertyKey(e,"error")&&N.IsFunction(e.check)&&N.IsFunction(e.error)}function Jle(e){return Bi(e)&&N.HasPropertyKey(e,"~refine")&&N.IsArray(e["~refine"])&&N.Every(e["~refine"],0,t=>r$r(t))}var oVe="-?(?:0|[1-9][0-9]*)n";function Vle(e){return dt.Create({"~kind":"BigInt"},{type:"bigint"},e)}function wd(e){return Vr(e,"BigInt")}function qp(e){return Vr(e,"Boolean")}var nJ="-?(?:0|[1-9][0-9]*)";function T$(e){return dt.Create({"~kind":"Integer"},{type:"integer"},e)}function hu(e){return Vr(e,"Integer")}function w_(e,t){return dt.Create({"~kind":"Iterator"},{type:"iterator",iteratorItems:e},t)}function Vc(e){return Vr(e,"Iterator")}function nVe(e){return dt.Discard(e,["~kind","type","iteratorItems"])}var Ble=class extends Error{constructor(t){super("Invalid Literal value"),Object.defineProperty(this,"cause",{value:{value:t},writable:!1,configurable:!1,enumerable:!1})}};function o$r(e){return N.IsBigInt(e)?"bigint":N.IsBoolean(e)?"boolean":N.IsNumber(e)?"number":N.IsString(e)?"string":(()=>{throw new Ble(e)})()}function ri(e,t){return dt.Create({"~kind":"Literal"},{type:o$r(e),const:e},t)}function Kle(e){return N.IsBigInt(e)||N.IsBoolean(e)||N.IsNumber(e)||N.IsString(e)}function iVe(e){return Tn(e)&&N.IsBigInt(e.const)}function aVe(e){return Tn(e)&&N.IsBoolean(e.const)}function iJ(e){return Tn(e)&&N.IsNumber(e.const)}function aJ(e){return Tn(e)&&N.IsString(e.const)}function Tn(e){return Vr(e,"Literal")}function ZC(e){return dt.Create({"~kind":"Null"},{type:"null"},e)}function Ox(e){return Vr(e,"Null")}var sJ="-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?";function jm(e){return dt.Create({"~kind":"Number"},{type:"number"},e)}function Ha(e){return Vr(e,"Number")}function cJ(e){return dt.Create({"~kind":"Symbol"},{type:"symbol"},e)}function Qb(e){return Vr(e,"Symbol")}var uJ=".*";function kl(e){return dt.Create({"~kind":"String"},{type:"string"},e)}function _c(e){return Vr(e,"String")}function E$(e){let t=sVe(e);return N.IsEqual(t.length,2)?t[0]:[]}function n$r(e){return!0}function cVe(e){return N.TakeLeft(e,(t,r)=>i$r(t)?cVe(r):!1,()=>!0)}function uVe(e){return N.IsEqual(e.length,0)?!1:cVe(e)}function i$r(e){return zr(e)?uVe(e.anyOf):Tn(e)?n$r(e.const):!1}function pJ(e){return uVe(e)}function lJ(e){return dt.Create({"~kind":"TemplateLiteral"},{type:"string",pattern:e},{})}function pVe(e,t,r=[]){return N.TakeLeft(e,(o,n)=>pVe(n,t,[...r,`${o}${t}`]),()=>r)}function a$r(e,t){return N.IsEqual(e.length,0)?[`${t}`]:pVe(e,t)}function lVe(e,t,r=[]){return N.TakeLeft(t,(o,n)=>lVe(e,n,[...r,...dVe(e,o)]),()=>r)}function dVe(e,t){return zr(t)?lVe(e,t.anyOf):Tn(t)?a$r(e,t.const):mi()}function mVe(e,t){return N.TakeLeft(t,(r,o)=>mVe(dVe(e,r),o),()=>e)}function s$r(e){return e.map(t=>ri(t))}function c$r(e){let t=mVe([],e),r=s$r(t);return gn(r)}function u$r(e){return N.IsEqual(e.length,0)?mi():N.IsEqual(e.length,1)&&Tn(e[0])?e[0]:c$r(e)}function Hle(e){let t=E$(e);return N.IsEqual(t.length,0)?kl():pJ(t)?u$r(t):lJ(e)}function yc(e){let t=Hle(e);return Da(t)?kl():t}function Wp(e,t){let r="object",o={[e]:t};return dt.Create({"~kind":"Record"},{type:r,patternProperties:o})}function fVe(e){return Wp(Zb,e)}function hVe(e){return Do({true:e,false:e})}function p$r(e){return N.IsString(e)||N.IsNumber(e)?ri(e):N.IsNull(e)?ZC():qi()}function Yh(e){return e.map(r=>p$r(r))}function R$(e){let t=Yh(e);return gn(t)}function eS(e){return R$(e.enum)}function gVe(e,t){let r=R$(e);return tS(r,t)}function _Ve(e,t){return Wp(eA,t)}function xc(e,t={}){let[r,o,n]=[e,e.length,!1];return dt.Create({"~kind":"Tuple"},{type:"array",additionalItems:n,items:r,minItems:o},t)}function bn(e){return Vr(e,"Tuple")}function yVe(e){return dt.Discard(e,["~kind","type","items","minItems","additionalItems"])}function Xle(e){return e.reduceRight((r,o,n)=>({[n]:o,...r}),{})}function xVe(e){let t=Xle(e.items);return Do(t)}function l$r(e,t){return XC(e)?!!XC(t):!1}function d$r(e,t){return gc(e)?!!gc(t):!1}function m$r(e,t){let r=l$r(e,t),o=d$r(e,t),n=$a([e,t]),i=QG(HC(n));return r&&o?SR(bR(i)):r&&!o?SR(i):!r&&o?bR(i):i}function f$r(e,t,r){return r in e?r in t?m$r(e[r],t[r]):e[r]:r in t?t[r]:qi()}function h$r(e,t){return[...new Set([...N.Keys(t),...N.Keys(e)])].reduce((o,n)=>({...o,[n]:f$r(e,t,n)}),{})}function bVe(e){return Po(e)?e.properties:bn(e)?Xle(e.items):mi()}function SVe(e,t){let r=bVe(e),o=bVe(t),n=h$r(r,o);return Do(n)}function vVe(e,t){let r=vR(e,t);return N.IsEqual(r,k$)?e:N.IsEqual(r,I$)||N.IsEqual(r,w$)?t:qi()}function TVe(e){return Po(e)||bn(e)}function g$r(e,t){let r=zr(e),o=zr(t);return r||o}function _$r(e,t){let r=TR(e),o=TR(t),n=g$r(r,o),i=TVe(r),a=TVe(o);return n?$a([r,o]):i&&a?SVe(r,o):i&&!a?r:!i&&a?o:vVe(r,o)}function EVe(e,t,r=[]){return N.TakeLeft(t,(o,n)=>EVe(e,n,[...r,_$r(e,o)]),()=>N.IsEqual(r.length,0)?[e]:r)}function RVe(e,t,r=[]){return N.TakeLeft(e,(o,n)=>RVe(n,t,[...r,...C$([o],t)]),()=>r)}function C$(e,t=[]){return N.TakeLeft(e,(r,o)=>zr(r)?C$(o,RVe(r.anyOf,t)):C$(o,EVe(r,t)),()=>t)}function $a(e){let t=C$(e);return Yle(t)}function Gm(e){return Yle(e)}function TR(e){return Ao(e)?$a(e.allOf):zr(e)?Gm(e.anyOf):e}function ER(e){return N.IsEqual(e.length,1)?e[0]:N.IsEqual(e.length,0)?qi():gn(e)}function wVe(e,t){let r=$a(e);return tS(r,t)}function kVe(e,t){return N.IsString(e)||N.IsNumber(e)?Do({[e]:t}):N.IsEqual(e,!1)?Do({false:t}):N.IsEqual(e,!0)?Do({true:t}):Do({})}function IVe(e,t){return Wp(dJ,t)}function CVe(e,t){return N.HasPropertyKey(e,"pattern")&&(N.IsString(e.pattern)||e.pattern instanceof RegExp)?Wp(e.pattern.toString(),t):Wp(Zb,t)}function AVe(e,t){let r=E$(e);return pJ(r)?tS(yc(e),t):Wp(e,t)}function y$r(e){return zr(e)?Qh(e.anyOf):[e]}function Qh(e){return e.reduce((t,r)=>[...t,...y$r(r)],[])}function x$r(e){return e.some(t=>_c(t)||Ha(t)||hu(t))}function b$r(e,t){return N.IsEqual(x$r(e),!0)?Wp(Zb,t):void 0}function S$r(e,t){return e.reduce((r,o)=>Tn(o)&&(N.IsString(o.const)||N.IsNumber(o.const))?{...r,[o.const]:t}:r,{})}function v$r(e,t){let r=S$r(e,t);return Do(r)}function OVe(e,t){let r=Qh(e),o=b$r(r,t);return Bi(o)?o:v$r(r,t)}function tS(e,t){return Gc(e)?fVe(t):qp(e)?hVe(t):Ss(e)?gVe(e.enum,t):hu(e)?_Ve(e,t):Ao(e)?wVe(e.allOf,t):Tn(e)?kVe(e.const,t):Ha(e)?IVe(e,t):zr(e)?OVe(e.anyOf,t):_c(e)?CVe(e,t):Da(e)?AVe(e.pattern,t):Do({})}function Qle(e,t,r){return Bo([e])?dt.Update(tS(e,t),{},r):Zle(e,t,r)}function PVe(e,t,r,o,n){let i=Or(e,t,r),a=Or(e,t,o);return Qle(i,a,n)}var eA=`^${nJ}$`,dJ=`^${sJ}$`,Zb=`^${uJ}$`;function Zle(e,t,r={}){return Io("Record",[e,t],r)}function ede(e,t,r={}){return Qle(e,t,r)}function NVe(e,t){return Wp(e,t)}function Il(e){return N.Keys(e.patternProperties)[0]}function A$(e){let t=Il(e);return N.IsEqual(t,Zb)?kl():N.IsEqual(t,eA)?T$():N.IsEqual(t,dJ)?jm():Hle(t)}function bc(e){return e.patternProperties[Il(e)]}function za(e){return Vr(e,"Record")}function mJ(e){return dt.Create({"~kind":"Rest"},{type:"rest",items:e},{})}function RR(e){return Vr(e,"Rest")}function tde(e){return Vr(e,"This")}function fJ(e){return dt.Create({"~kind":"Undefined"},{type:"undefined"},e)}function Px(e){return Vr(e,"Undefined")}function kd(e){return Vr(e,"Void")}function MVe(e){return Vle()}function LVe(e){return kl()}function DVe(e){return jm()}function $Ve(e){return T$()}function zVe(e){return qi()}function UVe(e){return ri(e)}function FVe(e){return gn(e[1])}function qVe(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function WVe(e){return[e[0],...e[1]]}function jVe(e){return e[1]}function gJ(e){return vn(e.length,2)}function Cl(e,t,r){return gJ(e)?t(e[0],e[1]):r()}function P$r(e,t){return vn(t.indexOf(e),0)?[e,t.slice(e.length)]:[]}function k_(e,t){for(let r=0;r<e.length;r++){let o=P$r(e[r],t);if(gJ(o))return o}return[]}function wde(e,t){return Array.from({length:t-e+1},(r,o)=>String.fromCharCode(e+o))}var GVe=[...wde(97,122),...wde(65,90)],JVe="0",VVe=wde(49,57),tA=[JVe,...VVe],BVe=" ",O$=`
|
|
1011
|
+
`).map(n=>n.trim()).filter(Boolean),o=r.find(n=>/\.(cmd|bat|exe)$/i.test(n));if(o){let n=o.replace(/\\/g,"/");if(/^\/[a-z]\//i.test(n)){let i=n;return(i[1]??"C").toUpperCase()+":"+i.slice(2).replace(/\//g,"\\")}return o}if(r.length>0){let n=r[0]??e;if(/^[A-Z]:/i.test(n))return n;if(/^\/[a-z]\//i.test(n)){let i=n;return(i[1]??"C").toUpperCase()+":"+i.slice(2).replace(/\//g,"\\")}return n}}catch{}return e}async function h$(e){if(typeof e.command!="string"||e.command.trim()==="")throw new TypeError("opts.command must be a non-empty string");let{command:t}=e,r=e.args??[];if(!Array.isArray(r)||r.some(L=>typeof L!="string"))throw new TypeError("opts.args must be an array of strings");let o=r,{cwd:n}=e,{timeoutMs:i}=e,a=e.killGracePeriodMs??3e3,s=Object.assign({},process.env,e.env??{}),c="",u="",l=MLr(t),m=process.platform==="win32"&&/\.(cmd|bat)$/i.test(l),p=process.platform!=="win32"?{command:l,args:o,shell:!1}:m?{command:"cmd.exe",args:["/c",l.replace(/\\/g,"/"),...o],shell:!1}:{command:l,args:o,shell:!1},h=p6e(p.command,p.args,{cwd:n,env:s,shell:p.shell,detached:process.platform!=="win32"});h.stdout?.on("data",L=>{c+=L.toString()}),h.stderr?.on("data",L=>{u+=L.toString()});let f=Date.now(),g=null,y=null,T=!1;function v(){let{pid:L}=h;if(L!=null)if(process.platform==="win32")p6e("taskkill",["/PID",String(L),"/T","/F"]).on("error",()=>{});else try{process.kill(-L,"SIGTERM")}catch{}}function E(){g!==null&&(clearTimeout(g),g=null),y!==null&&(clearTimeout(y),y=null)}return i!=null&&(g=setTimeout(()=>{if(T=!0,v(),process.platform!=="win32"){let{pid:L}=h;y=setTimeout(()=>{if(L!=null)try{process.kill(-L,"SIGKILL")}catch{}},a)}},i)),new Promise(L=>{let H=!1;function B(Te){H||(H=!0,E(),L(Te))}h.on("close",Te=>{let Ce=Date.now()-f;B({stdout:c,stderr:u,exitCode:T?null:Te,timedOut:T,durationMs:Ce})}),h.on("error",Te=>{let Ce=Date.now()-f,ye=Te,Pe;ye.code==="ENOENT"?Pe="ENOENT":ye.code==="EACCES"?Pe="EACCES":ye.code==="EMFILE"?Pe="EMFILE":ye.code&&(Pe="UNKNOWN"),B({stdout:"",stderr:ye.code?`ENOENT: ${ye.code}`:Te.message,exitCode:null,timedOut:T,durationMs:Ce,spawnError:Pe})})})}async function d6e(e,t){let r=t?l6e(t,".pd","tmp"):zLr();await LLr(r,{recursive:!0});let o=l6e(r,`msg-${Date.now()}-${Math.random().toString(36).slice(2,7)}.json`);return await $Lr(o,e,"utf8"),{filePath:o}}async function m6e(e){if(e)try{await DLr(e.filePath,{force:!0})}catch{}}function f6e(e,t){for(let r of[e,t??""]){if(!r)continue;try{return JSON.parse(r)}catch{}let o=[],n=0,i=-1;for(let a=0;a<r.length;a++){let s=r[a];if(s){if(s==="{")i===-1&&(i=a),n++;else if(s==="}"&&(n--,n===0&&i!==-1)){try{o.push(JSON.parse(r.slice(i,a+1)))}catch{}i=-1}}}if(o.length>0)return o[o.length-1]}return null}function g$(e){let t=0,r=-1;for(let o=0;o<e.length;o++){let n=e[o];if(n==="{")r===-1&&(r=o),t++;else if(n==="}"&&(t--,t===0&&r!==-1)){try{return JSON.parse(e.slice(r,o+1))}catch{}r=-1}}return null}function ULr(e){if(typeof e!="object"||e===null)return null;let t=e;if(Array.isArray(t.payloads)&&t.payloads.length>0){let[o]=t.payloads;if(o&&typeof o.text=="string"){let n=o.text.trim();try{return JSON.parse(n)}catch{}let i=g$(n);if(i!==null)return i}}let r=e;if(r.result&&typeof r.result=="object"&&Array.isArray(r.result.payloads)&&r.result.payloads.length>0){let[o]=r.result.payloads;if(o&&typeof o.text=="string"){let n=o.text.trim();try{return JSON.parse(n)}catch{}let i=g$(n);if(i!==null)return i}}return null}function FLr(e){let t=e;if(Array.isArray(t.payloads)&&t.payloads.length>0){let[o]=t.payloads;if(o&&typeof o.text=="string"){let n=o.text.trim();try{return JSON.parse(n)}catch{}let i=g$(n);if(i!==null)return i}}let r=e;if(r.result&&typeof r.result=="object"&&Array.isArray(r.result.payloads)&&r.result.payloads.length>0){let[o]=r.result.payloads;if(o&&typeof o.text=="string"){let n=o.text.trim();try{return JSON.parse(n)}catch{}let i=g$(n);if(i!==null)return i}}return typeof e=="object"&&e!==null?e:null}var Cx=class e{runStateMap=new Map;runtimeMode;workspaceDir;agentId;eventEmitter;constructor(t){this.runtimeMode=t.runtimeMode,this.workspaceDir=t.workspaceDir,this.agentId=t.agentId??"main",this.eventEmitter=t.eventEmitter??ks}kind(){return"openclaw-cli"}async getCapabilities(){return{supportsStructuredJsonOutput:!0,supportsToolUse:!1,supportsWorkingDirectory:!1,supportsModelSelection:!1,supportsLongRunningSessions:!1,supportsCancellation:!0,supportsArtifactWriteBack:!1,supportsConcurrentRuns:!1,supportsStreaming:!1}}async healthCheck(){let t=[],r=!0,o=!1;try{let i=await h$({command:"openclaw",args:["--version"],cwd:this.workspaceDir,timeoutMs:1e4});if(i.spawnError==="ENOENT")return{healthy:!1,degraded:!1,warnings:["openclaw binary not found"],lastCheckedAt:new Date().toISOString()};if(i.spawnError==="EACCES"||i.spawnError==="EMFILE")return{healthy:!1,degraded:!1,warnings:[`openclaw binary not executable: ${i.spawnError}`],lastCheckedAt:new Date().toISOString()};if(i.timedOut)return{healthy:!1,degraded:!1,warnings:["openclaw --version timed out"],lastCheckedAt:new Date().toISOString()};i.exitCode!==null&&i.exitCode!==0&&(o=!0,t.push(`openclaw --version exited with code ${i.exitCode}`))}catch(i){return{healthy:!1,degraded:!1,warnings:[i instanceof Error?i.message:String(i)],lastCheckedAt:new Date().toISOString()}}try{let i=["agents","list","--json"];this.runtimeMode==="local"&&i.push("--local");let a=await h$({command:"openclaw",args:i,cwd:this.workspaceDir,timeoutMs:15e3});if(a.spawnError==="ENOENT")return{healthy:!1,degraded:!1,warnings:["openclaw binary not found"],lastCheckedAt:new Date().toISOString()};if(a.spawnError==="EACCES"||a.spawnError==="EMFILE")return{healthy:!1,degraded:!1,warnings:[`openclaw binary not executable: ${a.spawnError}`],lastCheckedAt:new Date().toISOString()};if(a.timedOut)o=!0,t.push("openclaw agents list timed out");else if(a.exitCode!==null&&a.exitCode!==0)o=!0,t.push(`openclaw agents list exited with code ${a.exitCode}`);else try{let s=a.stdout.indexOf("[");if(s===-1)throw new Error("No JSON array found");let c=a.stdout.slice(s);JSON.parse(c).map(m=>typeof m=="string"?m:m.id).includes(this.agentId)||(r=!1,t.push(`agent '${this.agentId}' not found in agents list`))}catch{o=!0,t.push("failed to parse agents list output")}}catch(i){return{healthy:!1,degraded:!1,warnings:[i instanceof Error?i.message:String(i)],lastCheckedAt:new Date().toISOString()}}let n;try{let i=`pd-runtime-probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;n=await d6e(JSON.stringify({probe:"pd-runtime-v2",instruction:'reply with {"ok":true} only'}),this.workspaceDir);let a=["agent","--agent",this.agentId,"--message-file",n.filePath,"--session-id",i,"--timeout","240","--json"];this.runtimeMode==="local"&&a.push("--local");let s=await h$({command:"openclaw",args:a,cwd:this.workspaceDir,timeoutMs:24e4});if(s.spawnError==="ENOENT")return{healthy:!1,degraded:!1,warnings:["openclaw binary not found"],lastCheckedAt:new Date().toISOString()};if(s.spawnError==="EACCES"||s.spawnError==="EMFILE")return{healthy:!1,degraded:!1,warnings:[`openclaw binary not executable: ${s.spawnError}`],lastCheckedAt:new Date().toISOString()};if(s.timedOut)return{healthy:!1,degraded:!1,warnings:["openclaw agent probe timed out"],lastCheckedAt:new Date().toISOString()};if(s.exitCode!==null&&s.exitCode!==0)return{healthy:!1,degraded:!1,warnings:[`openclaw agent '${this.agentId}' probe failed with exit code ${s.exitCode}`,...s.stderr?[`stderr: ${s.stderr.substring(0,2e3)}`]:[]],lastCheckedAt:new Date().toISOString()};let c=f6e(s.stdout,s.stderr);if(c===null)return{healthy:!1,degraded:!1,warnings:["openclaw agent probe produced unparseable output"],lastCheckedAt:new Date().toISOString()};let u=FLr(c);if(typeof u!="object"||u===null||!Object.hasOwn(u,"ok")||u.ok!==!0){let l=c&&typeof c=="object"?JSON.stringify(c).substring(0,2e3):String(c).substring(0,2e3);return{healthy:!1,degraded:!1,warnings:[`openclaw agent '${this.agentId}' probe returned unexpected result: ${l}`],lastCheckedAt:new Date().toISOString()}}}catch(i){return{healthy:!1,degraded:!1,warnings:[i instanceof Error?i.message:String(i)],lastCheckedAt:new Date().toISOString()}}finally{await m6e(n)}return{healthy:r,degraded:o,warnings:t,lastCheckedAt:new Date().toISOString()}}static mapCliResultToTelemetry(t){return t.spawnError==="ENOENT"?{telemetryEventType:"runtime_invocation_failed",errorCategory:"runtime_unavailable",stderrExcerpt:t.stderr}:t.spawnError==="EACCES"||t.spawnError==="EMFILE"?{telemetryEventType:"runtime_invocation_failed",errorCategory:"execution_failed",stderrExcerpt:t.stderr}:t.timedOut?{telemetryEventType:"runtime_invocation_failed",errorCategory:"timeout",stderrExcerpt:t.stderr}:t.exitCode!==null&&t.exitCode!==0?{telemetryEventType:"runtime_invocation_failed",errorCategory:"execution_failed",stderrExcerpt:t.stderr}:{telemetryEventType:"runtime_invocation_succeeded",errorCategory:void 0,stderrExcerpt:void 0}}async startRun(t){let r=crypto.randomUUID(),o=new Date().toISOString(),n={runId:r,startedAt:o,cliOutput:null,completed:!1};this.runStateMap.set(r,n);let i=typeof t.inputPayload=="string"?t.inputPayload:JSON.stringify(t.inputPayload),a=Math.ceil((t.timeoutMs??6e5)/1e3),s=t.agentSpec?.agentId??"main",c=await d6e(i,this.workspaceDir),u=`pd-runtime-${r}`,l=["agent","--agent",s,"--message-file",c.filePath,"--session-id",u,"--json"];this.runtimeMode==="local"&&l.push("--local"),l.push("--timeout",String(a)),this.eventEmitter.emitTelemetry({eventType:"runtime_invocation_started",traceId:t.taskRef?.taskId??r,timestamp:new Date().toISOString(),sessionId:"openclaw-cli-adapter",agentId:"openclaw-cli-adapter",payload:{runId:r,runtimeKind:"openclaw-cli",runtimeMode:this.runtimeMode,timeoutMs:t.timeoutMs}});let m=await(async()=>{try{return await h$({command:"openclaw",args:l,cwd:this.workspaceDir,timeoutMs:t.timeoutMs})}finally{await m6e(c)}})();n.cliOutput=m,n.completed=!0;let p=new Date().toISOString(),{telemetryEventType:h,errorCategory:f,stderrExcerpt:g}=e.mapCliResultToTelemetry(m);return this.eventEmitter.emitTelemetry({eventType:h,traceId:t.taskRef?.taskId??r,timestamp:p,sessionId:"openclaw-cli-adapter",agentId:"openclaw-cli-adapter",payload:{runId:r,runtimeKind:"openclaw-cli",runtimeMode:this.runtimeMode,exitCode:m.exitCode,timedOut:m.timedOut,...f?{errorCategory:f}:{},...g?{stderrExcerpt:g}:{}}}),{runId:r,runtimeKind:"openclaw-cli",startedAt:o}}async pollRun(t){let r=this.runStateMap.get(t);if(!r)throw new wt("output_invalid",`Run ${t} not found`);if(!r.completed||!r.cliOutput)return{runId:t,status:"running",startedAt:r.startedAt};let{cliOutput:o}=r;if(o.timedOut)return{runId:t,status:"timed_out",startedAt:r.startedAt,endedAt:new Date().toISOString(),reason:"CLI timeout exceeded"};if(o.exitCode!==null&&o.exitCode!==0){let n=o.stderr?o.stderr.substring(0,2e3):void 0;return{runId:t,status:"failed",startedAt:r.startedAt,endedAt:new Date().toISOString(),reason:n?`CLI exited with code ${o.exitCode}. stderr: ${n}`:`CLI exited with code ${o.exitCode}`}}return{runId:t,status:"succeeded",startedAt:r.startedAt,endedAt:new Date().toISOString()}}async fetchOutput(t){let r=this.runStateMap.get(t);if(!r||!r.completed||!r.cliOutput)throw new wt("output_invalid",`Run ${t} not completed`);let{cliOutput:o}=r;if(o.spawnError==="ENOENT")throw new wt("runtime_unavailable","openclaw binary not found");if(o.timedOut)throw new wt("timeout","CLI timeout exceeded");if(o.exitCode!==null&&o.exitCode!==0){let a=o.stderr?o.stderr.substring(0,2e3):void 0;throw new wt("execution_failed",a?`CLI exited with code ${o.exitCode}. stderr: ${a}`:`CLI exited with code ${o.exitCode}`)}let n,i=f6e(o.stdout,o.stderr);if(i!==null?n=ULr(i)??i:n=null,n===null){let a=[o.stdout,o.stderr??""];for(let s of a){if(!s)continue;let c=g$(s);if(c!==null){n=c;break}}if(n===null)for(let s of a){if(!s)continue;let c=HJe(s);if(c!==null){n=c;break}}if(n===null){let s=o.stdout||o.stderr||"",c=Ix(s.substring(0,2e3)),u=zm(typeof c=="string"?c:"",500);throw new wt("output_invalid","Failed to parse CLI output as JSON",{parseFailureReason:"no_json_object_found",boundedRawOutputPreview:u,nextAction:"Check openclaw agent output format; ensure agent returns valid JSON"})}}if(!vo.Check(du,n)){let a=[...vo.Errors(du,n)].slice(0,10).map(u=>({path:u.path,message:u.message})),s=p$(n),c=s.ok?ec(s.value,500):ec(n,500);throw new wt("output_invalid","CLI output does not match DiagnosticianOutputV1 schema",{parseFailureReason:"schema_validation_failed",boundedRawOutputPreview:c,schemaErrors:a,nextAction:"Review schema errors; check LLM output format and required fields"})}return{runId:t,payload:n}}async cancelRun(t){let r=this.runStateMap.get(t);r&&!r.completed&&(r.completed=!0)}async fetchArtifacts(t){return[]}};var dt={};to(dt,{Assign:()=>qLr,Clone:()=>b$,Create:()=>A2r,Discard:()=>O2r,Metrics:()=>Kh,Update:()=>P2r});var Kh={assign:0,create:0,clone:0,discard:0,update:0};function qLr(e,t){return Kh.assign+=1,{...e,...t}}var ae={};to(ae,{And:()=>zle,ArrayLiteral:()=>WDr,ArrowFunction:()=>jDr,Call:()=>GDr,ConstDeclaration:()=>HDr,Constant:()=>A6e,Entries:()=>zDr,Every:()=>$Dr,HasPropertyKey:()=>FDr,If:()=>XDr,IsArray:()=>I6e,IsAsyncIterator:()=>_Dr,IsBigInt:()=>yDr,IsBoolean:()=>xDr,IsConstructor:()=>CDr,IsDeepEqual:()=>qDr,IsEqual:()=>ADr,IsFunction:()=>IDr,IsGreaterEqualThan:()=>MDr,IsGreaterThan:()=>ODr,IsInteger:()=>bDr,IsIterator:()=>SDr,IsLessEqualThan:()=>NDr,IsLessThan:()=>PDr,IsMaxLength:()=>DDr,IsMinLength:()=>LDr,IsNull:()=>vDr,IsNumber:()=>TDr,IsObject:()=>C6e,IsObjectNotArray:()=>EDr,IsString:()=>RDr,IsSymbol:()=>wDr,IsUndefined:()=>kDr,Keys:()=>UDr,Member:()=>VDr,MultipleOf:()=>t2r,New:()=>JDr,Not:()=>k6e,Or:()=>w6e,PrefixIncrement:()=>e2r,ReduceAnd:()=>QDr,ReduceOr:()=>ZDr,Return:()=>YDr,Statements:()=>KDr,Ternary:()=>BDr});var N={};to(N,{Entries:()=>pDr,EntriesRegExp:()=>uDr,Every:()=>aDr,EveryAll:()=>sDr,GraphemeCount:()=>oDr,HasPropertyKey:()=>cDr,IsArray:()=>y$,IsAsyncIterator:()=>BLr,IsBigInt:()=>_$,IsBoolean:()=>S6e,IsClassInstance:()=>tDr,IsConstructor:()=>KLr,IsDeepEqual:()=>$le,IsEqual:()=>vn,IsFunction:()=>v6e,IsGreaterEqualThan:()=>E6e,IsGreaterThan:()=>QLr,IsInteger:()=>Lle,IsIterator:()=>HLr,IsLessEqualThan:()=>T6e,IsLessThan:()=>ZLr,IsMaxLength:()=>nDr,IsMinLength:()=>iDr,IsMultipleOf:()=>eDr,IsNull:()=>HG,IsNumber:()=>XG,IsObject:()=>yR,IsObjectNotArray:()=>XLr,IsString:()=>x$,IsSymbol:()=>YLr,IsUndefined:()=>Dle,IsUnsafePropertyKey:()=>R6e,IsValueLike:()=>rDr,Keys:()=>KG,Symbols:()=>lDr,TakeLeft:()=>YG,Values:()=>dDr});function Vb(e,t,r){return e>=t&&e<=r}function h6e(e){return Vb(e,127462,127487)}function WLr(e){return Vb(e,65024,65039)}function jLr(e){return Vb(e,768,879)||Vb(e,6832,6911)||Vb(e,7616,7679)||Vb(e,65056,65071)}function BG(e){return e>65535?2:1}function g6e(e,t){for(;t<e.length;){let r=e.codePointAt(t);if(jLr(r)||WLr(r))t+=BG(r);else break}return t}function Mle(e,t){let r=e.codePointAt(t),o=t+BG(r);for(o=g6e(e,o);o<e.length-1&&e[o]==="\u200D";){let n=e.codePointAt(o+1);o+=1+BG(n),o=g6e(e,o)}return h6e(r)&&o<e.length&&h6e(e.codePointAt(o))&&(o+=BG(e.codePointAt(o))),o}function _6e(e){return Vb(e,55296,56319)||Vb(e,768,879)||e===8205}function y6e(e){let t=0,r=0;for(;r<e.length;)r=Mle(e,r),t++;return t}function GLr(e,t){if(t===0)return!0;let r=0,o=0;for(;o<e.length;)if(o=Mle(e,o),r++,r>=t)return!0;return!1}function JLr(e,t){let r=0,o=0;for(;o<e.length;)if(o=Mle(e,o),r++,r>t)return!1;return!0}function x6e(e,t){if(t===0)return!0;let r=0;for(;r<e.length;){if(_6e(e.charCodeAt(r)))return GLr(e,t);if(r++,r>=t)return!0}return!1}function b6e(e,t){let r=0;for(;r<e.length;){if(_6e(e.charCodeAt(r)))return JLr(e,t);if(r++,r>t)return!1}return!0}function y$(e){return Array.isArray(e)}function BLr(e){return yR(e)&&Symbol.asyncIterator in e}function _$(e){return vn(typeof e,"bigint")}function S6e(e){return vn(typeof e,"boolean")}function KLr(e){if(Dle(e)||!v6e(e))return!1;let t=Function.prototype.toString.call(e);return!!(/^class\s/.test(t)||/\[native code\]/.test(t))}function v6e(e){return vn(typeof e,"function")}function Lle(e){return Number.isInteger(e)}function HLr(e){return yR(e)&&Symbol.iterator in e}function HG(e){return vn(e,null)}function XG(e){return Number.isFinite(e)}function XLr(e){return yR(e)&&!y$(e)}function yR(e){return vn(typeof e,"object")&&!HG(e)}function x$(e){return vn(typeof e,"string")}function YLr(e){return vn(typeof e,"symbol")}function Dle(e){return vn(e,void 0)}function vn(e,t){return e===t}function QLr(e,t){return e>t}function ZLr(e,t){return e<t}function T6e(e,t){return e<=t}function E6e(e,t){return e>=t}function eDr(e,t){if(_$(e)||_$(t))return BigInt(e)%BigInt(t)===0n;let r=1e-10;if(!XG(e)||Lle(e)&&1/t%1===0)return!0;let o=e%t;return Math.min(Math.abs(o),Math.abs(o-t))<r}function tDr(e){if(!yR(e))return!1;let t=globalThis.Object.getPrototypeOf(e);return HG(t)?!1:vn(typeof t.constructor,"function")&&!(vn(t.constructor,globalThis.Object)||vn(t.constructor.name,"Object"))}function rDr(e){return _$(e)||S6e(e)||HG(e)||XG(e)||x$(e)||Dle(e)}function oDr(e){return y6e(e)}function nDr(e,t){return b6e(e,t)}function iDr(e,t){return x6e(e,t)}function aDr(e,t,r){for(let o=t;o<e.length;o++)if(!r(e[o],o))return!1;return!0}function sDr(e,t,r){let o=!0;for(let n=t;n<e.length;n++)r(e[n],n)||(o=!1);return o}function YG(e,t,r){return vn(e.length,0)?r():t(e[0],e.slice(1))}function R6e(e){return vn(e,"__proto__")||vn(e,"constructor")||vn(e,"prototype")}function cDr(e,t){return R6e(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function uDr(e){return KG(e).map(t=>[new RegExp(`^${t}$`),e[t]])}function pDr(e){return Object.entries(e)}function KG(e){return Object.getOwnPropertyNames(e)}function lDr(e){return Object.getOwnPropertySymbols(e)}function dDr(e){return Object.values(e)}function mDr(e,t){if(!yR(t))return!1;let r=KG(e);return vn(r.length,KG(t).length)&&r.every(o=>$le(e[o],t[o]))}function fDr(e,t){return y$(t)&&vn(e.length,t.length)&&e.every((r,o)=>$le(e[o],t[o]))}function $le(e,t){return y$(e)?fDr(e,t):yR(e)?mDr(e,t):vn(e,t)}var hDr=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function gDr(e){return hDr.test(e)}function zle(e,t){return`(${e} && ${t})`}function w6e(e,t){return`(${e} || ${t})`}function k6e(e){return`!(${e})`}function I6e(e){return`Array.isArray(${e})`}function _Dr(e){return`Guard.IsAsyncIterator(${e})`}function yDr(e){return`typeof ${e} === "bigint"`}function xDr(e){return`typeof ${e} === "boolean"`}function bDr(e){return`Number.isInteger(${e})`}function SDr(e){return`Guard.IsIterator(${e})`}function vDr(e){return`${e} === null`}function TDr(e){return`Number.isFinite(${e})`}function EDr(e){return zle(C6e(e),k6e(I6e(e)))}function C6e(e){return`typeof ${e} === "object" && ${e} !== null`}function RDr(e){return`typeof ${e} === "string"`}function wDr(e){return`typeof ${e} === "symbol"`}function kDr(e){return`${e} === undefined`}function IDr(e){return`typeof ${e} === "function"`}function CDr(e){return`Guard.IsConstructor(${e})`}function ADr(e,t){return`${e} === ${t}`}function ODr(e,t){return`${e} > ${t}`}function PDr(e,t){return`${e} < ${t}`}function NDr(e,t){return`${e} <= ${t}`}function MDr(e,t){return`${e} >= ${t}`}function LDr(e,t){return`Guard.IsMinLength(${e}, ${t})`}function DDr(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function $Dr(e,t,r,o){return vn(t,"0")?`${e}.every((${r[0]}, ${r[1]}) => ${o})`:`((value, callback) => { for(let index = ${t}; index < value.length; index++) if (!callback(value[index], index)) return false; return true })(${e}, (${r[0]}, ${r[1]}) => ${o})`}function zDr(e){return`Object.entries(${e})`}function UDr(e){return`Object.getOwnPropertyNames(${e})`}function FDr(e,t){return vn(t,'"__proto__"')||vn(t,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function qDr(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function WDr(e){return`[${e.join(", ")}]`}function jDr(e,t){return`((${e.join(", ")}) => ${t})`}function GDr(e,t){return`${e}(${t.join(", ")})`}function JDr(e,t){return`new ${e}(${t.join(", ")})`}function VDr(e,t){return`${e}${gDr(t)?`.${t}`:`[${A6e(t)}]`}`}function A6e(e){return x$(e)?JSON.stringify(e):`${e}`}function BDr(e,t,r){return`(${e} ? ${t} : ${r})`}function KDr(e){return`{ ${e.join("; ")}; }`}function HDr(e,t){return`const ${e} = ${t}`}function XDr(e,t){return`if(${e}) { ${t} }`}function YDr(e){return`return ${e}`}function QDr(e){return vn(e.length,0)?"true":e.reduce((t,r)=>zle(t,r))}function ZDr(e){return vn(e.length,0)?"false":e.reduce((t,r)=>w6e(t,r))}function e2r(e){return`++${e}`}function t2r(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}var Sa={};to(Sa,{IsBigInt64Array:()=>h2r,IsBigUint64Array:()=>g2r,IsBoolean:()=>r2r,IsDate:()=>y2r,IsFloat32Array:()=>m2r,IsFloat64Array:()=>f2r,IsInt16Array:()=>u2r,IsInt32Array:()=>l2r,IsInt8Array:()=>a2r,IsMap:()=>b2r,IsNumber:()=>o2r,IsRegExp:()=>_2r,IsSet:()=>x2r,IsString:()=>n2r,IsTypeArray:()=>i2r,IsUint16Array:()=>p2r,IsUint32Array:()=>d2r,IsUint8Array:()=>s2r,IsUint8ClampedArray:()=>c2r});function r2r(e){return e instanceof Boolean}function o2r(e){return e instanceof Number}function n2r(e){return e instanceof String}function i2r(e){return globalThis.ArrayBuffer.isView(e)}function a2r(e){return e instanceof globalThis.Int8Array}function s2r(e){return e instanceof globalThis.Uint8Array}function c2r(e){return e instanceof globalThis.Uint8ClampedArray}function u2r(e){return e instanceof globalThis.Int16Array}function p2r(e){return e instanceof globalThis.Uint16Array}function l2r(e){return e instanceof globalThis.Int32Array}function d2r(e){return e instanceof globalThis.Uint32Array}function m2r(e){return e instanceof globalThis.Float32Array}function f2r(e){return e instanceof globalThis.Float64Array}function h2r(e){return e instanceof globalThis.BigInt64Array}function g2r(e){return e instanceof globalThis.BigUint64Array}function _2r(e){return e instanceof globalThis.RegExp}function y2r(e){return e instanceof globalThis.Date}function x2r(e){return e instanceof globalThis.Set}function b2r(e){return e instanceof globalThis.Map}function v2r(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~guard")}function T2r(e){return e.map(t=>Ule(t))}function E2r(e){let t={},r=Object.getOwnPropertyDescriptors(e);for(let o of Object.keys(r)){let n=r[o];N.HasPropertyKey(n,"value")&&Object.defineProperty(t,o,{...n,value:Ule(n.value)})}return t}function R2r(e){return new RegExp(e.source,e.flags)}function Ule(e){return e instanceof RegExp?R2r(e):v2r(e)?e:N.IsArray(e)?T2r(e):N.IsObject(e)?E2r(e):e}function b$(e){return Kh.clone+=1,Ule(e)}var mu={};to(mu,{Get:()=>I2r,Reset:()=>w2r,Set:()=>k2r});var Bb={immutableTypes:!1,maxErrors:8,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1};function w2r(){Bb.immutableTypes=!1,Bb.maxErrors=8,Bb.useAcceleration=!0,Bb.exactOptionalPropertyTypes=!1,Bb.enumerableKind=!1,Bb.correctiveParse=!1}function k2r(e){for(let t of N.Keys(e)){let r=e[t];r!==void 0&&Object.defineProperty(Bb,t,{value:r})}}function I2r(){return Bb}function C2r(e,t){for(let r of Object.keys(t))Object.defineProperty(e,r,{configurable:!0,writable:!0,enumerable:!1,value:t[r]});return e}function O6e(e,t){return{...e,...t}}function A2r(e,t,r={}){Kh.create+=1;let o=mu.Get(),n=O6e(t,r),i=o.enumerableKind?O6e(n,e):C2r(n,e);return o.immutableTypes?Object.freeze(i):i}function O2r(e,t){Kh.discard+=1;let r={},o=Object.getOwnPropertyDescriptors(b$(e)),n=new Set(t);for(let i of Object.keys(o))n.has(i)||Object.defineProperty(r,i,o[i]);return r}function P2r(e,t,r){Kh.update+=1;let o=mu.Get(),n=b$(e);for(let i of Object.keys(t))Object.defineProperty(n,i,{configurable:!0,writable:!0,enumerable:o.enumerableKind,value:t[i]});for(let i of Object.keys(r))Object.defineProperty(n,i,{configurable:!0,enumerable:!0,writable:!0,value:r[i]});return n}function Vr(e,t){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.IsEqual(e["~kind"],t)}function Bi(e){return N.IsObject(e)}function P6e(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.HasPropertyKey(e,"type")&&N.IsEqual(e["~kind"],"OptionalAddAction")&&Bi(e.type)}function N6e(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.HasPropertyKey(e,"type")&&N.IsEqual(e["~kind"],"OptionalRemoveAction")&&Bi(e.type)}function M6e(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.HasPropertyKey(e,"type")&&N.IsEqual(e["~kind"],"ReadonlyAddAction")&&Bi(e.type)}function L6e(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.HasPropertyKey(e,"type")&&N.IsEqual(e["~kind"],"ReadonlyRemoveAction")&&Bi(e.type)}function Io(e,t,r){return dt.Create({"~kind":"Deferred"},{action:e,parameters:t,options:r},{})}function Kb(e){return Vr(e,"Deferred")}function T_(e,t){return dt.Create({"~kind":"Promise"},{type:"promise",item:e},t)}function tc(e){return Vr(e,"Promise")}function D6e(e){return dt.Discard(e,["~kind","type","item"])}function $6e(e){return dt.Update(e,{"~immutable":!0},{})}function xR(e){return $6e(e)}function KC(e){return Bi(e)&&N.HasPropertyKey(e,"~immutable")}function HC(e){return dt.Discard(e,["~optional"])}function bR(e){return dt.Update(e,{"~optional":!0},{})}function Fle(e){return bR(e)}function gc(e){return Bi(e)&&N.HasPropertyKey(e,"~optional")}function QG(e){return dt.Discard(e,["~readonly"])}function SR(e){return dt.Update(e,{"~readonly":!0},{})}function qle(e){return SR(e)}function XC(e){return Bi(e)&&N.HasPropertyKey(e,"~readonly")}function z6e(e){return{enumerable:mu.Get().enumerableKind,writable:!1,configurable:!1,value:e}}var S$=class{constructor(){globalThis.Object.defineProperty(this,"~kind",z6e("Base")),globalThis.Object.defineProperty(this,"~guard",z6e({check:t=>this.Check(t),errors:t=>this.Errors(t)}))}Check(t){return!0}Errors(t){return[]}Convert(t){return t}Clean(t){return t}Default(t){return t}Create(){throw new Error("Create not implemented")}Clone(){throw Error("Clone not implemented")}};function Ed(e){return Vr(e,"Base")}function E_(e,t){return dt.Create({"~kind":"Array"},{type:"array",items:e},t)}function jn(e){return Vr(e,"Array")}function ZG(e){return dt.Discard(e,["~kind","type","items"])}function R_(e,t){return dt.Create({"~kind":"AsyncIterator"},{type:"asyncIterator",iteratorItems:e},t)}function jc(e){return Vr(e,"AsyncIterator")}function U6e(e){return dt.Discard(e,["~kind","type","iteratorItems"])}function Hb(e,t,r={}){return dt.Create({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:t},r)}function xs(e){return Vr(e,"Constructor")}function F6e(e){return dt.Discard(e,["~kind","type","parameters","instanceType"])}function Xb(e,t,r={}){return dt.Create({"~kind":"Function"},{type:"function",parameters:e,returnType:t},r)}function bs(e){return Vr(e,"Function")}function q6e(e){return dt.Discard(e,["~kind","type","parameters","returnType"])}function Uu(e,t){return dt.Create({"~kind":"Ref"},{$ref:e},t)}function bi(e){return Vr(e,"Ref")}function eJ(e,t){return dt.Create({"~kind":"Generic"},{type:"generic",parameters:e,expression:t})}function v$(e){return Vr(e,"Generic")}function tJ(e){return dt.Create({"~kind":"Any"},{},e)}function Gc(e){return Vr(e,"Any")}var W6e="(?!)";function qi(e){return dt.Create({"~kind":"Never"},{not:{}},e)}function Hh(e){return Vr(e,"Never")}function j6e(e){return N.Keys(e).filter(t=>!gc(e[t]))}function rJ(e){return N.Keys(e)}function oJ(e){return N.Values(e)}function Do(e,t={}){let r=j6e(e),o=r.length>0?{required:r}:{};return dt.Create({"~kind":"Object"},{type:"object",...o,properties:e},t)}function Po(e){return Vr(e,"Object")}function G6e(e){return dt.Discard(e,["~kind","type","properties","required"])}function gn(e,t={}){return dt.Create({"~kind":"Union"},{anyOf:e},t)}function zr(e){return Vr(e,"Union")}function J6e(e){return dt.Discard(e,["~kind","anyOf"])}function Xh(e){return dt.Create({"~kind":"Unknown"},{},e)}function fu(e){return Vr(e,"Unknown")}function Ax(e,t,r){let o=N.Keys(e).reduce((n,i)=>({...n,[i]:dt.Update(e[i],{},{$id:i})}),{});return dt.Create({"~kind":"Cyclic"},{$defs:o,$ref:t},r)}function oa(e){return Vr(e,"Cyclic")}function Wle(e){return N.IsObjectNotArray(e)&&N.HasPropertyKey(e,"~unsafe")&&N.IsNull(e["~unsafe"])}var un={};to(un,{Match:()=>N2r});function N2r(e,t){return t[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function Is(e){return Vr(e,"Infer")}function Ss(e){return Vr(e,"Enum")}function qm(e,t={}){return dt.Create({"~kind":"Intersect"},{allOf:e},t)}function Ao(e){return Vr(e,"Intersect")}function V6e(e){return dt.Discard(e,["~kind","allOf"])}var YC={};to(YC,{CanEvaluate:()=>L2r,Evaluate:()=>B6e});var jle;function M2r(){try{return B6e("null")(),!0}catch{return!1}}function L2r(){return N.IsUndefined(jle)&&(jle=M2r()),jle&&mu.Get().useAcceleration}function B6e(...e){return new globalThis.Function(...e)}var Wm={};to(Wm,{Hash:()=>Z2r,HashCode:()=>Z6e});function mi(){throw new Error("Unreachable")}function D2r(e){let t=new Set,r=e;for(;r&&r!==Object.prototype;){for(let o of Reflect.ownKeys(r))o!=="constructor"&&typeof o!="symbol"&&t.add(o);r=Object.getPrototypeOf(r)}return[...t]}function $2r(e){return typeof e=="number"}var fp;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(fp||(fp={}));var QC=BigInt("14695981039346656037"),[z2r,U2r]=[BigInt("1099511628211"),BigInt("18446744073709551616")],F2r=Array.from({length:256}).map((e,t)=>BigInt(t)),X6e=new Float64Array(1),Y6e=new DataView(X6e.buffer),Q6e=new Uint8Array(X6e.buffer);function Jc(e){QC=QC^F2r[e],QC=QC*z2r%U2r}function q2r(e){Jc(fp.Array);for(let t of e)Yb(t)}function W2r(e){Jc(fp.BigInt),Y6e.setBigInt64(0,e);for(let t of Q6e)Jc(t)}function K6e(e){Jc(fp.Boolean),Jc(e?1:0)}function j2r(e){Jc(fp.Constructor),Yb(e.toString())}function G2r(e){Jc(fp.Date),Yb(e.getTime())}function J2r(e){Jc(fp.Function),Yb(e.toString())}function V2r(e){Jc(fp.Null)}function H6e(e){Jc(fp.Number),Y6e.setFloat64(0,e,!0);for(let t of Q6e)Jc(t)}function B2r(e){Jc(fp.Object);for(let t of D2r(e).sort())Yb(t),Yb(e[t])}function K2r(e){Jc(fp.RegExp),Gle(e.toString())}var H2r=new TextEncoder;function Gle(e){Jc(fp.String);for(let t of H2r.encode(e))Jc(t)}function X2r(e){Jc(fp.Symbol),Yb(e.toString())}function Y2r(e){Jc(fp.TypeArray);let t=new Uint8Array(e.buffer);for(let r=0;r<t.length;r++)Jc(t[r])}function Q2r(e){return Jc(fp.Undefined)}function Yb(e){return Sa.IsTypeArray(e)?Y2r(e):Sa.IsDate(e)?G2r(e):Sa.IsRegExp(e)?K2r(e):Sa.IsBoolean(e)?K6e(e.valueOf()):Sa.IsString(e)?Gle(e.valueOf()):Sa.IsNumber(e)?H6e(e.valueOf()):$2r(e)?H6e(e):N.IsArray(e)?q2r(e):N.IsBoolean(e)?K6e(e):N.IsBigInt(e)?W2r(e):N.IsConstructor(e)?j2r(e):N.IsNull(e)?V2r(e):N.IsObject(e)?B2r(e):N.IsString(e)?Gle(e):N.IsSymbol(e)?X2r(e):N.IsUndefined(e)?Q2r(e):N.IsFunction(e)?J2r(e):mi()}function Z6e(e){return QC=BigInt("14695981039346656037"),Yb(e),QC}function Z2r(e){return Z6e(e).toString(16).padStart(16,"0")}function eVe(e){switch(e.keyword){case"additionalProperties":return"must not have additional properties";case"anyOf":return"must match a schema in anyOf";case"boolean":return"schema is false";case"const":return"must be equal to constant";case"contains":return"must contain at least 1 valid item";case"dependencies":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"dependentRequired":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"enum":return"must be equal to one of the allowed values";case"exclusiveMaximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"exclusiveMinimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"format":return`must match format "${e.params.format}"`;case"if":return`must match "${e.params.failingKeyword}" schema`;case"maxItems":return`must not have more than ${e.params.limit} items`;case"maxLength":return`must not have more than ${e.params.limit} characters`;case"maxProperties":return`must not have more than ${e.params.limit} properties`;case"maximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"minItems":return`must not have fewer than ${e.params.limit} items`;case"minLength":return`must not have fewer than ${e.params.limit} characters`;case"minProperties":return`must not have fewer than ${e.params.limit} properties`;case"minimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"multipleOf":return`must be multiple of ${e.params.multipleOf}`;case"not":return"must not be valid";case"oneOf":return"must match exactly one schema in oneOf";case"pattern":return`must match pattern "${e.params.pattern}"`;case"propertyNames":return`property names ${e.params.propertyNames.join(", ")} are invalid`;case"required":return`must have required properties ${e.params.requiredProperties.join(", ")}`;case"type":return typeof e.params.type=="string"?`must be ${e.params.type}`:`must be either ${e.params.type.join(" or ")}`;case"unevaluatedItems":return"must not have unevaluated items";case"unevaluatedProperties":return"must not have unevaluated properties";case"uniqueItems":return"must not have duplicate items";case"~guard":return"must match check function";case"~refine":return e.params.message;default:return"an unknown validation error occurred"}}var e$r=eVe;function tVe(){return e$r}function Rd(e){return Bi(e)&&N.HasPropertyKey(e,"~codec")&&N.IsObject(e["~codec"])&&N.HasPropertyKey(e["~codec"],"encode")&&N.HasPropertyKey(e["~codec"],"decode")}function r$r(e){return N.IsObjectNotArray(e)&&N.HasPropertyKey(e,"check")&&N.HasPropertyKey(e,"error")&&N.IsFunction(e.check)&&N.IsFunction(e.error)}function Jle(e){return Bi(e)&&N.HasPropertyKey(e,"~refine")&&N.IsArray(e["~refine"])&&N.Every(e["~refine"],0,t=>r$r(t))}var oVe="-?(?:0|[1-9][0-9]*)n";function Vle(e){return dt.Create({"~kind":"BigInt"},{type:"bigint"},e)}function wd(e){return Vr(e,"BigInt")}function qp(e){return Vr(e,"Boolean")}var nJ="-?(?:0|[1-9][0-9]*)";function T$(e){return dt.Create({"~kind":"Integer"},{type:"integer"},e)}function hu(e){return Vr(e,"Integer")}function w_(e,t){return dt.Create({"~kind":"Iterator"},{type:"iterator",iteratorItems:e},t)}function Vc(e){return Vr(e,"Iterator")}function nVe(e){return dt.Discard(e,["~kind","type","iteratorItems"])}var Ble=class extends Error{constructor(t){super("Invalid Literal value"),Object.defineProperty(this,"cause",{value:{value:t},writable:!1,configurable:!1,enumerable:!1})}};function o$r(e){return N.IsBigInt(e)?"bigint":N.IsBoolean(e)?"boolean":N.IsNumber(e)?"number":N.IsString(e)?"string":(()=>{throw new Ble(e)})()}function ri(e,t){return dt.Create({"~kind":"Literal"},{type:o$r(e),const:e},t)}function Kle(e){return N.IsBigInt(e)||N.IsBoolean(e)||N.IsNumber(e)||N.IsString(e)}function iVe(e){return Tn(e)&&N.IsBigInt(e.const)}function aVe(e){return Tn(e)&&N.IsBoolean(e.const)}function iJ(e){return Tn(e)&&N.IsNumber(e.const)}function aJ(e){return Tn(e)&&N.IsString(e.const)}function Tn(e){return Vr(e,"Literal")}function ZC(e){return dt.Create({"~kind":"Null"},{type:"null"},e)}function Ox(e){return Vr(e,"Null")}var sJ="-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?";function jm(e){return dt.Create({"~kind":"Number"},{type:"number"},e)}function Ha(e){return Vr(e,"Number")}function cJ(e){return dt.Create({"~kind":"Symbol"},{type:"symbol"},e)}function Qb(e){return Vr(e,"Symbol")}var uJ=".*";function kl(e){return dt.Create({"~kind":"String"},{type:"string"},e)}function _c(e){return Vr(e,"String")}function E$(e){let t=sVe(e);return N.IsEqual(t.length,2)?t[0]:[]}function n$r(e){return!0}function cVe(e){return N.TakeLeft(e,(t,r)=>i$r(t)?cVe(r):!1,()=>!0)}function uVe(e){return N.IsEqual(e.length,0)?!1:cVe(e)}function i$r(e){return zr(e)?uVe(e.anyOf):Tn(e)?n$r(e.const):!1}function pJ(e){return uVe(e)}function lJ(e){return dt.Create({"~kind":"TemplateLiteral"},{type:"string",pattern:e},{})}function pVe(e,t,r=[]){return N.TakeLeft(e,(o,n)=>pVe(n,t,[...r,`${o}${t}`]),()=>r)}function a$r(e,t){return N.IsEqual(e.length,0)?[`${t}`]:pVe(e,t)}function lVe(e,t,r=[]){return N.TakeLeft(t,(o,n)=>lVe(e,n,[...r,...dVe(e,o)]),()=>r)}function dVe(e,t){return zr(t)?lVe(e,t.anyOf):Tn(t)?a$r(e,t.const):mi()}function mVe(e,t){return N.TakeLeft(t,(r,o)=>mVe(dVe(e,r),o),()=>e)}function s$r(e){return e.map(t=>ri(t))}function c$r(e){let t=mVe([],e),r=s$r(t);return gn(r)}function u$r(e){return N.IsEqual(e.length,0)?mi():N.IsEqual(e.length,1)&&Tn(e[0])?e[0]:c$r(e)}function Hle(e){let t=E$(e);return N.IsEqual(t.length,0)?kl():pJ(t)?u$r(t):lJ(e)}function yc(e){let t=Hle(e);return Da(t)?kl():t}function Wp(e,t){let r="object",o={[e]:t};return dt.Create({"~kind":"Record"},{type:r,patternProperties:o})}function fVe(e){return Wp(Zb,e)}function hVe(e){return Do({true:e,false:e})}function p$r(e){return N.IsString(e)||N.IsNumber(e)?ri(e):N.IsNull(e)?ZC():qi()}function Yh(e){return e.map(r=>p$r(r))}function R$(e){let t=Yh(e);return gn(t)}function eS(e){return R$(e.enum)}function gVe(e,t){let r=R$(e);return tS(r,t)}function _Ve(e,t){return Wp(eA,t)}function xc(e,t={}){let[r,o,n]=[e,e.length,!1];return dt.Create({"~kind":"Tuple"},{type:"array",additionalItems:n,items:r,minItems:o},t)}function bn(e){return Vr(e,"Tuple")}function yVe(e){return dt.Discard(e,["~kind","type","items","minItems","additionalItems"])}function Xle(e){return e.reduceRight((r,o,n)=>({[n]:o,...r}),{})}function xVe(e){let t=Xle(e.items);return Do(t)}function l$r(e,t){return XC(e)?!!XC(t):!1}function d$r(e,t){return gc(e)?!!gc(t):!1}function m$r(e,t){let r=l$r(e,t),o=d$r(e,t),n=$a([e,t]),i=QG(HC(n));return r&&o?SR(bR(i)):r&&!o?SR(i):!r&&o?bR(i):i}function f$r(e,t,r){return r in e?r in t?m$r(e[r],t[r]):e[r]:r in t?t[r]:qi()}function h$r(e,t){return[...new Set([...N.Keys(t),...N.Keys(e)])].reduce((o,n)=>({...o,[n]:f$r(e,t,n)}),{})}function bVe(e){return Po(e)?e.properties:bn(e)?Xle(e.items):mi()}function SVe(e,t){let r=bVe(e),o=bVe(t),n=h$r(r,o);return Do(n)}function vVe(e,t){let r=vR(e,t);return N.IsEqual(r,k$)?e:N.IsEqual(r,I$)||N.IsEqual(r,w$)?t:qi()}function TVe(e){return Po(e)||bn(e)}function g$r(e,t){let r=zr(e),o=zr(t);return r||o}function _$r(e,t){let r=TR(e),o=TR(t),n=g$r(r,o),i=TVe(r),a=TVe(o);return n?$a([r,o]):i&&a?SVe(r,o):i&&!a?r:!i&&a?o:vVe(r,o)}function EVe(e,t,r=[]){return N.TakeLeft(t,(o,n)=>EVe(e,n,[...r,_$r(e,o)]),()=>N.IsEqual(r.length,0)?[e]:r)}function RVe(e,t,r=[]){return N.TakeLeft(e,(o,n)=>RVe(n,t,[...r,...C$([o],t)]),()=>r)}function C$(e,t=[]){return N.TakeLeft(e,(r,o)=>zr(r)?C$(o,RVe(r.anyOf,t)):C$(o,EVe(r,t)),()=>t)}function $a(e){let t=C$(e);return Yle(t)}function Gm(e){return Yle(e)}function TR(e){return Ao(e)?$a(e.allOf):zr(e)?Gm(e.anyOf):e}function ER(e){return N.IsEqual(e.length,1)?e[0]:N.IsEqual(e.length,0)?qi():gn(e)}function wVe(e,t){let r=$a(e);return tS(r,t)}function kVe(e,t){return N.IsString(e)||N.IsNumber(e)?Do({[e]:t}):N.IsEqual(e,!1)?Do({false:t}):N.IsEqual(e,!0)?Do({true:t}):Do({})}function IVe(e,t){return Wp(dJ,t)}function CVe(e,t){return N.HasPropertyKey(e,"pattern")&&(N.IsString(e.pattern)||e.pattern instanceof RegExp)?Wp(e.pattern.toString(),t):Wp(Zb,t)}function AVe(e,t){let r=E$(e);return pJ(r)?tS(yc(e),t):Wp(e,t)}function y$r(e){return zr(e)?Qh(e.anyOf):[e]}function Qh(e){return e.reduce((t,r)=>[...t,...y$r(r)],[])}function x$r(e){return e.some(t=>_c(t)||Ha(t)||hu(t))}function b$r(e,t){return N.IsEqual(x$r(e),!0)?Wp(Zb,t):void 0}function S$r(e,t){return e.reduce((r,o)=>Tn(o)&&(N.IsString(o.const)||N.IsNumber(o.const))?{...r,[o.const]:t}:r,{})}function v$r(e,t){let r=S$r(e,t);return Do(r)}function OVe(e,t){let r=Qh(e),o=b$r(r,t);return Bi(o)?o:v$r(r,t)}function tS(e,t){return Gc(e)?fVe(t):qp(e)?hVe(t):Ss(e)?gVe(e.enum,t):hu(e)?_Ve(e,t):Ao(e)?wVe(e.allOf,t):Tn(e)?kVe(e.const,t):Ha(e)?IVe(e,t):zr(e)?OVe(e.anyOf,t):_c(e)?CVe(e,t):Da(e)?AVe(e.pattern,t):Do({})}function Qle(e,t,r){return Bo([e])?dt.Update(tS(e,t),{},r):Zle(e,t,r)}function PVe(e,t,r,o,n){let i=Or(e,t,r),a=Or(e,t,o);return Qle(i,a,n)}var eA=`^${nJ}$`,dJ=`^${sJ}$`,Zb=`^${uJ}$`;function Zle(e,t,r={}){return Io("Record",[e,t],r)}function ede(e,t,r={}){return Qle(e,t,r)}function NVe(e,t){return Wp(e,t)}function Il(e){return N.Keys(e.patternProperties)[0]}function A$(e){let t=Il(e);return N.IsEqual(t,Zb)?kl():N.IsEqual(t,eA)?T$():N.IsEqual(t,dJ)?jm():Hle(t)}function bc(e){return e.patternProperties[Il(e)]}function za(e){return Vr(e,"Record")}function mJ(e){return dt.Create({"~kind":"Rest"},{type:"rest",items:e},{})}function RR(e){return Vr(e,"Rest")}function tde(e){return Vr(e,"This")}function fJ(e){return dt.Create({"~kind":"Undefined"},{type:"undefined"},e)}function Px(e){return Vr(e,"Undefined")}function kd(e){return Vr(e,"Void")}function MVe(e){return Vle()}function LVe(e){return kl()}function DVe(e){return jm()}function $Ve(e){return T$()}function zVe(e){return qi()}function UVe(e){return ri(e)}function FVe(e){return gn(e[1])}function qVe(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function WVe(e){return[e[0],...e[1]]}function jVe(e){return e[1]}function gJ(e){return vn(e.length,2)}function Cl(e,t,r){return gJ(e)?t(e[0],e[1]):r()}function P$r(e,t){return vn(t.indexOf(e),0)?[e,t.slice(e.length)]:[]}function k_(e,t){for(let r=0;r<e.length;r++){let o=P$r(e[r],t);if(gJ(o))return o}return[]}function wde(e,t){return Array.from({length:t-e+1},(r,o)=>String.fromCharCode(e+o))}var GVe=[...wde(97,122),...wde(65,90)],JVe="0",VVe=wde(49,57),tA=[JVe,...VVe],BVe=" ",O$=`
|
|
1012
1012
|
`;var rA="_";var KVe="$";var HVe="//",XVe="/*",M$r="*/";function YVe(e){let t=e.indexOf(M$r);return vn(t,-1)?"":e.slice(t+2)}function QVe(e){let t=e.indexOf(O$);return vn(t,-1)?"":e.slice(t)}function L$r(e){return e.replace(/^[ \t\r\f\v]+/,"")}function _J(e){let t=L$r(e);return t.startsWith(XVe)?_J(YVe(t.slice(2))):t.startsWith(HVe)?_J(QVe(t.slice(2))):t}function Zh(e){let t=e.trimStart();return t.startsWith(XVe)?Zh(YVe(t.slice(2))):t.startsWith(HVe)?Zh(QVe(t.slice(2))):t}var yKn=[...tA,rA];function kde(e,t){return k_([e],t)}function eg(e,t){return vn(e,"")?["",t]:e.startsWith(O$)?kde(e,_J(t)):e.startsWith(BVe)?kde(e,t):kde(e,Zh(t))}var F$r=[...GVe,rA,KVe];var JKn=[...F$r,...tA];var rHn=[...tA,rA];function q$r(e){return vn(e,"")?[]:[e.slice(0,1),e.slice(1)]}function ZVe(e,t){return YG(e,(r,o)=>t.startsWith(r)?!0:ZVe(o,t),()=>!1)}function P$(e,t,r=""){return Cl(q$r(t),(o,n)=>ZVe(e,t)?[r,t]:P$(e,n,`${r}${o}`),()=>[])}function eBe(e,t){return Cl(P$(e,t),(r,o)=>vn(r,"")?[]:[r,o],()=>[])}var fi=(e,t,r=()=>[])=>e.length===2?t(e):r();var j$r=e=>fi(eg("-?(?:0|[1-9][0-9]*)n",e),([t,r])=>[MVe(t),r]),G$r=e=>fi(eg(".*",e),([t,r])=>[LVe(t),r]),J$r=e=>fi(eg("-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?",e),([t,r])=>[DVe(t),r]),V$r=e=>fi(eg("-?(?:0|[1-9][0-9]*)",e),([t,r])=>[$Ve(t),r]),B$r=e=>fi(eg("(?!)",e),([t,r])=>[zVe(t),r]),K$r=e=>fi(eBe(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([t,r])=>[UVe(t),r]),H$r=e=>fi(fi(j$r(e),([t,r])=>[t,r],()=>fi(G$r(e),([t,r])=>[t,r],()=>fi(J$r(e),([t,r])=>[t,r],()=>fi(V$r(e),([t,r])=>[t,r],()=>fi(B$r(e),([t,r])=>[t,r],()=>fi(X$r(e),([t,r])=>[t,r],()=>fi(K$r(e),([t,r])=>[t,r],()=>[]))))))),([t,r])=>[t,r]),X$r=e=>fi(fi(eg("(",e),([t,r])=>fi(Cde(r),([o,n])=>fi(eg(")",n),([i,a])=>[[t,o,i],a]))),([t,r])=>[FVe(t),r]),tBe=e=>fi(fi(fi(Ide(e),([t,r])=>fi(eg("|",r),([o,n])=>fi(tBe(n),([i,a])=>[[t,o,i],a]))),([t,r])=>[t,r],()=>fi(fi(Ide(e),([t,r])=>[[t],r]),([t,r])=>[t,r],()=>fi([[],e],([t,r])=>[t,r],()=>[]))),([t,r])=>[qVe(t),r]),Ide=e=>fi(fi(H$r(e),([t,r])=>fi(Cde(r),([o,n])=>[[t,o],n])),([t,r])=>[WVe(t),r]),Cde=e=>fi(fi(tBe(e),([t,r])=>[t,r],()=>fi(Ide(e),([t,r])=>[t,r],()=>[])),([t,r])=>[t,r]),sVe=e=>fi(fi(eg("^",e),([t,r])=>fi(Cde(r),([o,n])=>fi(eg("$",n),([i,a])=>[[t,o,i],a]))),([t,r])=>[jVe(t),r]);function Q$r(e){return e.join("|")}function Z$r(e){return e.slice(1,e.length-1)}function ezr(e,t,r){return rS(t,`${r}${e}`)}function tzr(e,t){return rS(e,`${t}${oVe}`)}function rzr(e,t){return rS(e,`${t}${nJ}`)}function ozr(e,t){return rS(e,`${t}${sJ}`)}function nzr(e,t){return yJ(gn([ri("false"),ri("true")]),e,t)}function izr(e,t){return rS(e,`${t}${uJ}`)}function azr(e,t,r){return rS(t,`${r}${Z$r(e)}`)}function szr(e,t,r){let o=xJ(e,{});return yJ(o,t,r)}function czr(e,t,r){let o=Yh(e);return Ade(o,t,r)}function Ade(e,t,r,o=[]){return N.TakeLeft(e,(n,i)=>Ade(i,t,r,[...o,yJ(n,[],"")]),()=>rS(t,`${r}(${Q$r(o)})`))}function yJ(e,t,r){return Ss(e)?czr(e.enum,t,r):hu(e)?rzr(t,r):Tn(e)?ezr(e.const,t,r):wd(e)?tzr(t,r):qp(e)?nzr(t,r):Ha(e)?ozr(t,r):_c(e)?izr(t,r):Da(e)?azr(e.pattern,t,r):oBe(e)?szr(e.parameters[0],t,r):zr(e)?Ade(e.anyOf,t,r):W6e}function rS(e,t){return N.TakeLeft(e,(r,o)=>yJ(r,o,t),()=>t)}function uzr(e){return`^${rS(e,"")}$`}function rBe(e){let t=uzr(e);return lJ(t)}function xJ(e,t){return Bo(e)?dt.Update(rBe(e),{},t):rde(e,t)}function nBe(e,t,r,o){let n=Id(e,t,r);return xJ(n,o)}function rde(e,t={}){return Io("TemplateLiteral",[e],t)}function oBe(e){return Bi(e)&&N.HasPropertyKey(e,"action")&&N.IsEqual(e.action,"TemplateLiteral")}function Da(e){return Vr(e,"TemplateLiteral")}var Wo={};to(Wo,{ExtendsFalse:()=>En,ExtendsTrue:()=>ro,ExtendsUnion:()=>Ode,IsExtendsFalse:()=>pzr,IsExtendsTrue:()=>aBe,IsExtendsTrueLike:()=>oA,IsExtendsUnion:()=>iBe,Match:()=>rc});function Ode(e){return dt.Create({"~kind":"ExtendsUnion"},{inferred:e})}function iBe(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.HasPropertyKey(e,"inferred")&&N.IsEqual(e["~kind"],"ExtendsUnion")&&N.IsObject(e.inferred)}function ro(e){return dt.Create({"~kind":"ExtendsTrue"},{inferred:e})}function aBe(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.HasPropertyKey(e,"inferred")&&N.IsEqual(e["~kind"],"ExtendsTrue")&&N.IsObject(e.inferred)}function En(){return dt.Create({"~kind":"ExtendsFalse"},{})}function pzr(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.IsEqual(e["~kind"],"ExtendsFalse")}function oA(e){return iBe(e)||aBe(e)}function rc(e,t,r){return oA(e)?t(e.inferred):r()}function lzr(e,t,r,o){return rc(Si(e,r,o),n=>ro(dt.Assign(dt.Assign(e,n),{[t]:r})),()=>En())}function dzr(e,t){return ro(e)}function mzr(e,t,r){let o=R$(r);return Si(e,t,o)}function sBe(e,t,r){return N.TakeLeft(r,(o,n)=>rc(Si(e,t,o),i=>sBe(i,t,n),()=>En()),()=>ro(e))}function fzr(e,t,r){let o=yc(r);return Si(e,t,o)}function cBe(e,t,r){return N.TakeLeft(r,(o,n)=>rc(Si(e,t,o),i=>ro(i),()=>cBe(e,t,n)),()=>En())}function An(e,t,r){return Gc(r)?dzr(e,t):Ss(r)?mzr(e,t,r.enum):Is(r)?lzr(e,r.name,t,r.extends):Ao(r)?sBe(e,t,r.allOf):Da(r)?fzr(e,t,r.pattern):zr(r)?cBe(e,t,r.anyOf):fu(r)?ro(e):En()}function uBe(e,t,r){return Is(r)?An(e,t,r):Gc(r)?ro(e):fu(r)?ro(e):Ode(e)}function hzr(e,t){let r=KC(e),o=KC(t);return r&&o||!r&&o?!0:!(r&&!o)}function pBe(e,t,r,o){return jn(o)?hzr(t,o)?Si(e,r,o.items):En():An(e,t,o)}function lBe(e,t,r){return jc(r)?Si(e,t,r.iteratorItems):An(e,R_(t),r)}function dBe(e,t,r){return wd(r)?ro(e):An(e,t,r)}function mBe(e,t,r){return qp(r)?ro(e):An(e,t,r)}function gzr(e,t,r,o,n){let i=Is(o)?t:o,a=Is(o)?o:t,s=gc(t),c=gc(o);return!s&&c?En():rc(Si(e,i,a),u=>N$(u,r,n),()=>En())}function _zr(e,t,r,o){return N.TakeLeft(o,(n,i)=>gzr(e,t,r,n,i),()=>gc(t)?ro(e):En())}function yzr(e,t,r){return N.TakeLeft(t,(o,n)=>_zr(e,o,n,r),()=>ro(e))}function N$(e,t,r){return yzr(e,t,r)}function bJ(e,t,r){return kd(r)?ro(e):Si(e,t,r)}function fBe(e,t,r,o){return Gc(o)?ro(e):fu(o)?ro(e):xs(o)?rc(N$(e,t,o.parameters),n=>bJ(n,r,o.instanceType),()=>En()):En()}function hBe(e,t,r){return Si(e,eS(t),r)}function gBe(e,t,r,o){return Gc(o)?ro(e):fu(o)?ro(e):bs(o)?rc(N$(e,t,o.parameters),n=>bJ(n,r,o.returnType),()=>En()):En()}function _Be(e,t,r){return hu(r)?ro(e):Ha(r)?ro(e):An(e,t,r)}function yBe(e,t,r){let o=$a(t);return Si(e,o,r)}function xBe(e,t,r){return Vc(r)?Si(e,t,r.iteratorItems):An(e,w_(t),r)}function SJ(e,t,r){return t===r?ro(e):En()}function xzr(e,t,r){return Tn(r)?SJ(e,t,r.const):wd(r)?ro(e):An(e,ri(t),r)}function bzr(e,t,r){return Tn(r)?SJ(e,t,r.const):qp(r)?ro(e):An(e,ri(t),r)}function Szr(e,t,r){return Tn(r)?SJ(e,t,r.const):Ha(r)?ro(e):An(e,ri(t),r)}function vzr(e,t,r){return Tn(r)?SJ(e,t,r.const):_c(r)?ro(e):An(e,ri(t),r)}function bBe(e,t,r){return N.IsBigInt(t.const)?xzr(e,t.const,r):N.IsBoolean(t.const)?bzr(e,t.const,r):N.IsNumber(t.const)?Szr(e,t.const,r):N.IsString(t.const)?vzr(e,t.const,r):mi()}function SBe(e,t,r){return Is(r)?An(e,t,r):ro(e)}function vBe(e,t,r){return Ox(r)?ro(e):An(e,t,r)}function TBe(e,t,r){return Ha(r)?ro(e):An(e,t,r)}function Tzr(e,t,r){return gc(t)?gc(r)?ro(e):En():ro(e)}function Ezr(e,t,r){return Is(r)&&Hh(r.extends)?En():rc(Si(e,t,r),o=>Tzr(o,t,r),()=>En())}function Rzr(e,t){return e.reduce((r,o)=>o in t?oA(t[o])?{...r,...t[o].inferred}:mi():mi(),{})}function wzr(e,t,r){let o={};for(let a of N.Keys(r))o[a]=a in t?Ezr({},t[a],r[a]):gc(r[a])?Is(r[a])?ro(dt.Assign(e,{[r[a].name]:r[a].extends})):ro(e):En();let n=N.Values(o).every(a=>oA(a)),i=n?Rzr(N.Keys(o),o):{};return n?ro(i):En()}function kzr(e,t,r){let o=wzr(e,t,r);return oA(o)?ro(dt.Assign(e,o.inferred)):En()}function Izr(e,t,r){return kzr(e,t,r)}function EBe(e,t,r){return Po(r)?Izr(e,t,r.properties):An(e,Do(t),r)}function RBe(e,t,r){return tc(r)?Si(e,t,r.item):An(e,T_(t),r)}function wBe(e,t,r){return _c(r)?ro(e):An(e,t,r)}function kBe(e,t,r){return Qb(r)?ro(e):An(e,t,r)}function IBe(e,t,r){let o=yc(t);return Si(e,o,r)}function Pde(e,t){return dt.Create({"~kind":"Inferrable"},{name:e,type:t},{})}function M$(e){return N.IsObject(e)&&N.HasPropertyKey(e,"~kind")&&N.HasPropertyKey(e,"name")&&N.HasPropertyKey(e,"type")&&N.IsEqual(e["~kind"],"Inferrable")&&N.IsString(e.name)&&N.IsObject(e.type)}function Nde(e){return RR(e)?Is(e.items)?jn(e.items.extends)?Pde(e.items.name,e.items.extends.items):fu(e.items.extends)?Pde(e.items.name,e.items.extends):void 0:mi():void 0}function vJ(e){return Is(e)?Pde(e.name,e.extends):void 0}function Mde(e,t,r=[]){return N.TakeLeft(e,(o,n)=>rc(Si({},o,t),()=>Mde(n,t,[...r,o]),()=>{}),()=>r)}function CBe(e,t,r,o){let n=Mde(r,o);return N.IsArray(n)?ro(dt.Assign(e,{[t]:xc(n)})):En()}function TJ(e,t,r,o){let n=Mde(r,o);return N.IsArray(n)?ro(dt.Assign(e,{[t]:gn(n)})):En()}function Czr(e){return[...e].reverse()}function Lde(e,t){return t?Czr(e):e}function Azr(e){let t=e.length>0?e[0]:void 0,r=Bi(t)?Nde(t):void 0;return Bi(r)}function Ozr(e,t,r,o,n,i){return rc(Si(e,r,n),a=>ABe(a,t,o,i),()=>En())}function Pzr(e,t,r,o,n){let i=Nde(o);return M$(i)?CBe(e,i.name,Lde(r,t),i.type):N.TakeLeft(r,(a,s)=>Ozr(e,t,a,s,o,n),()=>En())}function Nzr(e,t,r,o){return N.TakeLeft(o,(n,i)=>Pzr(e,t,r,n,i),()=>N.IsEqual(r.length,0)?ro(e):En())}function ABe(e,t,r,o){return Nzr(e,t,r,o)}function Mzr(e,t,r){let o=oS(e,{callstack:[]},r),n=Azr(o);return ABe(e,n,Lde(t,n),Lde(o,n))}function OBe(e,t,r){let o=vJ(r);return M$(o)?TJ(e,o.name,t,o.type):N.TakeLeft(t,(n,i)=>rc(Si(e,n,r),a=>OBe(a,i,r),()=>En()),()=>ro(e))}function PBe(e,t,r){let o=oS(e,{callstack:[]},t);return bn(r)?Mzr(e,o,r.items):jn(r)?OBe(e,o,r.items):An(e,xc(o),r)}function NBe(e,t,r){return kd(r)?ro(e):Px(r)?ro(e):An(e,t,r)}function MBe(e,t,r){return N.TakeLeft(r,(o,n)=>rc(Si(e,t,o),i=>ro(i),()=>MBe(e,t,n)),()=>En())}function Dde(e,t,r){return N.TakeLeft(t,(o,n)=>rc(MBe(e,o,r),i=>Dde(i,n,r),()=>En()),()=>ro(e))}function LBe(e,t,r){let o=vJ(r);return M$(o)?TJ(e,o.name,t,o.type):zr(r)?Dde(e,t,r.anyOf):Dde(e,t,[r])}function DBe(e,t,r){return Is(r)?An(e,t,r):Gc(r)?ro(e):fu(r)?ro(e):En()}function $Be(e,t,r){return kd(r)?ro(e):An(e,t,r)}function Si(e,t,r){return Gc(t)?uBe(e,t,r):jn(t)?pBe(e,t,t.items,r):jc(t)?lBe(e,t.iteratorItems,r):wd(t)?dBe(e,t,r):qp(t)?mBe(e,t,r):xs(t)?fBe(e,t.parameters,t.instanceType,r):Ss(t)?hBe(e,t,r):bs(t)?gBe(e,t.parameters,t.returnType,r):hu(t)?_Be(e,t,r):Ao(t)?yBe(e,t.allOf,r):Vc(t)?xBe(e,t.iteratorItems,r):Tn(t)?bBe(e,t,r):Hh(t)?SBe(e,t,r):Ox(t)?vBe(e,t,r):Ha(t)?TBe(e,t,r):Po(t)?EBe(e,t.properties,r):tc(t)?RBe(e,t.item,r):_c(t)?wBe(e,t,r):Qb(t)?kBe(e,t,r):Da(t)?IBe(e,t.pattern,r):bn(t)?PBe(e,t.items,r):Px(t)?NBe(e,t,r):zr(t)?LBe(e,t.anyOf,r):fu(t)?DBe(e,t,r):kd(t)?$Be(e,t,r):En()}function Lzr(e,t){return $a([...e,Do(t)])}function zBe(e,t,r){return Bo(e)?dt.Update(Lzr(e,t),{},r):ode(e,t,r)}function UBe(e,t,r,o,n){let i=Id(e,t,r),a=L$(e,t,o);return zBe(i,a,n)}function ode(e,t,r={}){return Io("Interface",[e,t],r)}function nA(e){return Bi(e)&&N.HasPropertyKey(e,"action")&&N.IsEqual(e.action,"Interface")}function Dzr(e,t,r){return e.includes(r)?!0:nS([...e,r],t,t[r])}function FBe(e,t,r){let o=oJ(r);return wR(e,t,o)}function wR(e,t,r){return N.TakeLeft(r,(o,n)=>nS(e,t,o)?!0:wR(e,t,n),()=>!1)}function nS(e,t,r){return bi(r)?Dzr(e,t,r.$ref):jn(r)?nS(e,t,r.items):jc(r)?nS(e,t,r.iteratorItems):xs(r)?wR(e,t,[...r.parameters,r.instanceType]):bs(r)?wR(e,t,[...r.parameters,r.returnType]):nA(r)?FBe(e,t,r.parameters[1]):Ao(r)?wR(e,t,r.allOf):Vc(r)?nS(e,t,r.iteratorItems):Po(r)?FBe(e,t,r.properties):tc(r)?nS(e,t,r.item):zr(r)?wR(e,t,r.anyOf):bn(r)?wR(e,t,r.items):za(r)?nS(e,t,bc(r)):!1}function EJ(e,t,r){return nS(e,t,r)}function $zr(e,t){return t.reduce((r,o)=>o in e?EJ([o],e,e[o])?[...r,o]:r:mi(),[])}function qBe(e){let t=rJ(e);return $zr(e,t)}function zzr(e,t,r){return r.includes(t)?r:t in e?iS(e,e[t],[...r,t]):mi()}function WBe(e,t,r){let o=oJ(t);return iA(e,o,r)}function iA(e,t,r){return t.reduce((o,n)=>iS(e,n,o),r)}function iS(e,t,r){return bi(t)?zzr(e,t.$ref,r):jn(t)?iS(e,t.items,r):jc(t)?iS(e,t.iteratorItems,r):xs(t)?iA(e,[...t.parameters,t.instanceType],r):bs(t)?iA(e,[...t.parameters,t.returnType],r):nA(t)?WBe(e,t.parameters[1],r):Ao(t)?iA(e,t.allOf,r):Vc(t)?iS(e,t.iteratorItems,r):Po(t)?WBe(e,t.properties,r):tc(t)?iS(e,t.item,r):zr(t)?iA(e,t.anyOf,r):bn(t)?iA(e,t.items,r):za(t)?iS(e,bc(t),r):r}function jBe(e,t,r){return iS(e,r,[t])}function Uzr(e){return tJ()}function Fzr(e){return N.Keys(e).reduce((t,r)=>({...t,[r]:I_(e[r])}),{})}function D$(e){return e.reduce((t,r)=>[...t,I_(r)],[])}function I_(e){return bi(e)?Uzr(e.$ref):jn(e)?E_(I_(e.items),ZG(e)):jc(e)?R_(I_(e.iteratorItems)):xs(e)?Hb(D$(e.parameters),I_(e.instanceType)):bs(e)?Xb(D$(e.parameters),I_(e.returnType)):Ao(e)?qm(D$(e.allOf)):Vc(e)?w_(I_(e.iteratorItems)):Po(e)?Do(Fzr(e.properties)):tc(e)?T_(I_(e.item)):za(e)?ede(A$(e),I_(bc(e))):zr(e)?gn(D$(e.anyOf)):bn(e)?xc(D$(e.items)):e}function qzr(e,t){return t in e?I_(e[t]):Xh()}function GBe(e){return qzr(e.$defs,e.$ref)}function Wzr(e,t,r){let o=Id(e,{callstack:[]},t),n=L$({},{callstack:[]},r);return $a([...o,Do(n)])}function jzr(e,t){return N.Keys(e).filter(o=>t.includes(o)).reduce((o,n)=>{let i=e[n],a=nA(i)?Wzr(e,i.parameters[0],i.parameters[1]):i;return{...o,[n]:a}},{})}function JBe(e,t,r){let o=jBe(e,t,r),n=jzr(e,o);return Ax(n,t)}function VBe(e,t){return t in e?bi(e[t])?VBe(e,e[t].$ref):e[t]:qi()}function C_(e,t){return VBe(e,t)}function BBe(e){return oa(e)?GBe(e):Wle(e)?Xh():e}function Fu(e,t,r){let o=BBe(t),n=BBe(r);return Si(e,o,n)}var w$="equal",Gzr="disjoint",k$="left-inside",I$="right-inside";function vR(e,t){let r=[fu(e)?Wo.ExtendsFalse():Fu({},e,t),fu(e)?Wo.ExtendsTrue({}):Fu({},t,e)];return Wo.IsExtendsTrueLike(r[0])&&Wo.IsExtendsTrueLike(r[1])?w$:Wo.IsExtendsTrueLike(r[0])&&Wo.IsExtendsFalse(r[1])?k$:Wo.IsExtendsFalse(r[0])&&Wo.IsExtendsTrueLike(r[1])?I$:Gzr}function Jzr(e,t){return t.filter(r=>vR(e,r)!==I$)}function Vzr(e,t){let r=t.some(o=>{let n=vR(e,o);return N.IsEqual(n,k$)||N.IsEqual(n,w$)});return N.IsEqual(r,!1)}function Bzr(e,t){let r=TR(e);return Gc(r)?[r]:Vzr(r,t)?[...Jzr(r,t),r]:t}function Kzr(e){return e.reduce((t,r)=>Po(r)?[...t,r]:Hh(r)?t:Bzr(r,t),[])}function Yle(e){let t=Kzr(e),r=Qh(t);return r.length===0?qi():r.length===1?r[0]:gn(r)}function $de(e,t){return dt.Update(TR(e),{},t)}function KBe(e,t,r,o){let n=Or(e,t,r);return $de(n,o)}function $$(e,t=[]){return Kb(e)&&N.IsEqual(e.action,"Conditional")?bi(e.parameters[0])?$$(e.parameters[2],$$(e.parameters[3],[...t,e.parameters[0].$ref])):$$(e.parameters[2],$$(e.parameters[3],t)):Kb(e)&&N.IsEqual(e.action,"Mapped")&&Kb(e.parameters[1])&&N.IsEqual(e.parameters[1].action,"KeyOf")&&bi(e.parameters[1].parameters[0])?[...t,e.parameters[1].parameters[0].$ref]:t}function Hzr(e,t){return e.reduce((r,o)=>[...r,t.includes(o.name)],[])}function YBe(e,t,r=[]){return N.TakeLeft(e,(o,n)=>N.TakeLeft(t,(i,a)=>YBe(n,a,[...r,[i,o]]),()=>r),()=>r)}function Xzr(e){return zr(e)?[...e.anyOf]:[e]}function Yzr(e,t){return e.reduce((r,o)=>[...r,[...o,t]],[])}function HBe(e,t){return t.reduce((r,o)=>[...r,...Yzr(e,o)],[])}function XBe(e){return e.reduce((t,r)=>N.IsEqual(r[0],!0)?HBe(t,Xzr(r[1])):HBe(t,[r[1]]),[[]])}function QBe(e,t,r){let o=$$(r),n=Hzr(e,o),i=YBe(t,n);return Kb(r)&&N.IsEqual(r.action,"Conditional")||Kb(r)&&N.IsEqual(r.action,"Mapped")?XBe(i):[t]}function Qzr(){return["(not-resolvable)",qi()]}function Zzr(){return["(not-generic)",qi()]}function eUr(e,t,r){return[e,eJ(t,r)]}function tUr(e,t,r){return t in e?ZBe(e,t,e[t],r):Qzr()}function ZBe(e,t,r,o){return v$(r)?eUr(t,r.parameters,r.expression):bi(r)?tUr(e,r.$ref,o):Zzr()}function eKe(e,t,r){return ZBe(e,"(anonymous)",t,r)}function rUr(e,t,r){if(Is(t)||z$(t)||Wo.IsExtendsTrueLike(Fu({},t,r)))return;let o={parameter:e,expect:r,actual:t};throw new Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:o})}function tKe(e,t,r,o,n){let i=Or(e,t,n);return rUr(r,i,o),dt.Assign(e,{[r]:i})}function oUr(e,t,r,o,n){let i=Or(e,t,r.extends),a=Or(e,t,r.equals);return N.TakeLeft(n,(s,c)=>zde(tKe(e,t,r.name,i,s),t,o,c),()=>zde(tKe(e,t,r.name,i,a),t,o,[]))}function zde(e,t,r,o){return N.TakeLeft(r,(n,i)=>oUr(e,t,n,i,o),()=>e)}function rKe(e,t,r,o){return zde(e,t,r,o)}function nUr(e){return N.IsGreaterThan(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function iUr(e,t){return N.IsEqual(nUr(e),t)}function aUr(e,t,r,o,n,i){let a=rKe(e,t,o,i),s=Or(a,{callstack:[...t.callstack,r.$ref]},n);return Or(e,t,s)}function sUr(e,t,r,o,n,i){return i.reduce((a,s)=>[...a,aUr(e,t,r,o,n,s)],[])}function cUr(e,t,r,o,n,i){let a=QBe(o,i,n),s=sUr(e,t,r,o,n,a);return N.IsEqual(s.length,1)?s[0]:Gm(s)}function Ude(e,t,r,o){let n=Id(e,t,o),i=eKe(e,r,o),a=i[0],s=i[1];return v$(s)?iUr(t,a)?hJ(Uu(a),n):cUr(e,t,Uu(a),s.parameters,s.expression,n):hJ(r,n)}function hJ(e,t){return dt.Create({"~kind":"Call"},{target:e,arguments:t},{})}function z$(e){return Vr(e,"Call")}function oKe(e,t){return e(t)}function nKe(e,t){return N.IsString(t)?ri(oKe(e,t)):ri(t)}function iKe(e,t){let r=yc(t);return Nx(e,r)}function aKe(e,t){let r=t.map(o=>Nx(e,o));return gn(r)}function Nx(e,t){return Tn(t)?nKe(e,t.const):Da(t)?iKe(e,t.pattern):zr(t)?aKe(e,t.anyOf):t}function nde(e,t={}){return Io("Capitalize",[e],t)}function ide(e,t={}){return Io("Lowercase",[e],t)}function ade(e,t={}){return Io("Uncapitalize",[e],t)}function sde(e,t={}){return Io("Uppercase",[e],t)}var uUr=e=>e[0].toUpperCase()+e.slice(1),pUr=e=>e.toLowerCase(),lUr=e=>e[0].toLowerCase()+e.slice(1),dUr=e=>e.toUpperCase();function sKe(e,t){return Bo([e])?dt.Update(Nx(uUr,e),{},t):nde(e,t)}function cKe(e,t){return Bo([e])?dt.Update(Nx(pUr,e),{},t):ide(e,t)}function uKe(e,t){return Bo([e])?dt.Update(Nx(lUr,e),{},t):ade(e,t)}function pKe(e,t){return Bo([e])?dt.Update(Nx(dUr,e),{},t):sde(e,t)}function lKe(e,t,r,o){let n=Or(e,t,r);return sKe(n,o)}function dKe(e,t,r,o){let n=Or(e,t,r);return cKe(n,o)}function mKe(e,t,r,o){let n=Or(e,t,r);return uKe(n,o)}function fKe(e,t,r,o){let n=Or(e,t,r);return pKe(n,o)}function cde(e,t,r,o,n={}){return Io("Conditional",[e,t,r,o],n)}function mUr(e,t,r,o,n,i){let a=Fu(e,r,o);return Wo.IsExtendsUnion(a)?gn([Or(a.inferred,t,n),Or(e,t,i)]):Wo.IsExtendsTrue(a)?Or(a.inferred,t,n):Or(e,t,i)}function hKe(e,t,r,o,n,i,a){return Bo([r,o])?dt.Update(mUr(e,t,r,o,n,i),{},a):cde(r,o,n,i,a)}function gKe(e,t,r,o,n,i,a){let s=Or(e,t,r),c=Or(e,t,o);return hKe(e,t,s,c,n,i,a)}function ude(e,t={}){return Io("ConstructorParameters",[e],t)}function fUr(e){let t=xs(e)?e.parameters:[],r=oS({},{callstack:[]},t);return xc(r)}function _Ke(e,t){return Bo([e])?dt.Update(fUr(e),{},t):ude(e,t)}function yKe(e,t,r,o){let n=Or(e,t,r);return _Ke(n,o)}function pde(e,t,r={}){return Io("Exclude",[e,t],r)}function xKe(e,t){return e.reduce((r,o)=>[...r,...bKe(o,t)],[])}function bKe(e,t){let r=Fu({},e,t);return Wo.IsExtendsTrueLike(r)?[]:[e]}function SKe(e,t){let r=Ss(e)?xKe(Yh(e.enum),t):zr(e)?xKe(Qh(e.anyOf),t):bKe(e,t);return Gm(r)}function RJ(e,t,r){return Bo([e,t])?dt.Update(SKe(e,t),{},r):pde(e,t,r)}function vKe(e,t,r,o,n){let i=Or(e,t,r),a=Or(e,t,o);return RJ(i,a,n)}function lde(e,t,r={}){return Io("Extract",[e,t],r)}function EKe(e,t){return e.reduce((r,o)=>[...r,...RKe(o,t)],[])}function RKe(e,t){let r=Fu({},e,t);return Wo.IsExtendsTrueLike(r)?[e]:[]}function wKe(e,t){let r=Ss(e)?EKe(Yh(e.enum),t):zr(e)?EKe(Qh(e.anyOf),t):RKe(e,t);return Gm(r)}function TKe(e,t,r){return Bo([e,t])?dt.Update(wKe(e,t),{},r):lde(e,t,r)}function kKe(e,t,r,o,n){let i=Or(e,t,r),a=Or(e,t,o);return TKe(i,a,n)}function dde(e,t,r={}){return Io("Index",[e,t],r)}function AKe(e,t){let r=C_(e,t);return tg(r)}function hUr(e,t){let r=N.Keys(e).filter(l=>!N.HasPropertyKey(t,l)),o=N.Keys(t).filter(l=>!N.HasPropertyKey(e,l)),n=N.Keys(e).filter(l=>N.HasPropertyKey(t,l)),i=r.reduce((l,m)=>({...l,[m]:e[m]}),{}),a=o.reduce((l,m)=>({...l,[m]:t[m]}),{}),s=n.reduce((l,m)=>({...l,[m]:$a([e[m],t[m]])}),{}),c=dt.Assign(i,a);return dt.Assign(c,s)}function OKe(e){return e.reduce((t,r)=>hUr(t,tg(r)),{})}function PKe(e){let t=xVe(xc(e));return tg(t)}function gUr(e,t){return N.Keys(e).filter(n=>n in t).reduce((n,i)=>({...n,[i]:Gm([e[i],t[i]])}),{})}function NKe(e,t){return N.TakeLeft(e,(r,o)=>NKe(o,gUr(t,tg(r))),()=>t)}function MKe(e){return N.TakeLeft(e,(t,r)=>NKe(r,tg(t)),()=>mi())}function tg(e){return oa(e)?AKe(e.$defs,e.$ref):Ao(e)?OKe(e.allOf):zr(e)?MKe(e.anyOf):bn(e)?PKe(e.items):Po(e)?e.properties:{}}function aA(e){let t=tg(e);return Do(t)}var _Ur=new RegExp("^(?:0|[1-9][0-9]*)$");function sA(e){let t=`${e}`;return _Ur.test(t)?parseInt(t):e}function yUr(e){return ri(sA(e))}function LKe(e){return e.map(t=>DKe(t))}function DKe(e){return Ao(e)?qm(LKe(e.allOf)):zr(e)?gn(LKe(e.anyOf)):Tn(e)?yUr(e.const):e}function $Ke(e,t){let r=DKe(t),o=Fu({},r,jm());return Wo.IsExtendsTrueLike(o)?e:Tn(t)&&N.IsEqual(t.const,"length")?jm():qi()}function zKe(e,t){let r=C_(e,t);return A_(r)}function wJ(e){return e.reduce((t,r)=>[...t,...A_(r)],[])}function UKe(e){let t=Yh(e);return wJ(t)}function FKe(e){let t=$a(e);return A_(t)}function qKe(e){return[`${e}`]}function WKe(e){let t=yc(e);return A_(t)}function A_(e){return oa(e)?zKe(e.$defs,e.$ref):Ss(e)?UKe(e.enum):Ao(e)?FKe(e.allOf):Tn(e)?qKe(e.const):Da(e)?WKe(e.pattern):zr(e)?wJ(e.anyOf):[]}function cA(e){return A_(e)}function U$(e,t){return t.map(r=>aS(e,r))}function aS(e,t){return jn(t)?E_(aS(e,t.items)):jc(t)?R_(aS(e,t.iteratorItems)):xs(t)?Hb(U$(e,t.parameters),aS(e,t.instanceType)):bs(t)?Xb(U$(e,t.parameters),aS(e,t.returnType)):Vc(t)?w_(aS(e,t.iteratorItems)):tc(t)?T_(aS(e,t.item)):bn(t)?xc(U$(e,t.items)):zr(t)?gn(U$(e,t.anyOf)):Ao(t)?qm(U$(e,t.allOf)):tde(t)?Do(e):t}function jKe(e,t){return aS(e,t)}function xUr(e,t){let r=t in e?e[t]:qi();return jKe(e,r)}function GKe(e,t){return t.reduce((r,o)=>[...r,xUr(e,o)],[])}function bUr(e,t){let r=cA(t),o=GKe(e,r);return Gm(o)}var SUr=new RegExp(eA);function vUr(e){return e.filter(r=>SUr.test(r))}function TUr(e){let t=rJ(e),r=vUr(t),o=GKe(e,r);return Gm(o)}function JKe(e,t){return Ha(t)?TUr(e):bUr(e,t)}function EUr(e){return ri(sA(e))}function VKe(e){return e.map(t=>Fde(t))}function Fde(e){return Ao(e)?qm(VKe(e.allOf)):zr(e)?gn(VKe(e.anyOf)):Tn(e)?EUr(e.const):e}function RUr(e,t){return e.reduceRight((r,o,n)=>{let i=Fu({},ri(n),t);return Wo.IsExtendsTrueLike(i)?[o,...r]:r},[])}function wUr(e,t){let r=Fde(t),o=RUr(e,r);return ER(o)}function kUr(e){return ER(e)}function BKe(e,t){return Tn(t)&&N.IsEqual(t.const,"length")?ri(e.length):Ha(t)||hu(t)?kUr(e):wUr(e,t)}function KKe(e,t){return jn(e)?$Ke(e.items,t):Po(e)?JKe(e.properties,t):bn(e)?BKe(e.items,t):qi()}function IUr(e){return oa(e)||Ao(e)||zr(e)?aA(e):e}function CKe(e,t,r){return Bo([e,t])?dt.Update(KKe(IUr(e),t),{},r):dde(e,t,r)}function HKe(e,t,r,o,n){let i=Or(e,t,r),a=Or(e,t,o);return CKe(i,a,n)}function mde(e,t={}){return Io("InstanceType",[e],t)}function CUr(e){return xs(e)?e.instanceType:qi()}function XKe(e,t){return Bo([e])?dt.Update(CUr(e),{},t):mde(e,t)}function YKe(e,t,r,o={}){let n=Or(e,t,r);return XKe(n,o)}function fde(e,t={}){return Io("KeyOf",[e],t)}function ZKe(){return gn([jm(),kl(),cJ()])}function eHe(e){return jm()}function AUr(e){return e.reduce((r,o)=>Kle(o)?[...r,ri(sA(o))]:mi(),[])}function tHe(e){let t=N.Keys(e),r=AUr(t);return ER(r)}function rHe(e){return A$(e)}function oHe(e){let t=e.map((r,o)=>ri(o));return ER(t)}function nHe(e){return Gc(e)?ZKe():jn(e)?eHe(e.items):Po(e)?tHe(e.properties):za(e)?rHe(e):bn(e)?oHe(e.items):qi()}function OUr(e){return oa(e)||Ao(e)||zr(e)?aA(e):e}function QKe(e,t){return Bo([e])?dt.Update(nHe(OUr(e)),{},t):fde(e,t)}function iHe(e,t,r,o){let n=Or(e,t,r);return QKe(n,o)}function hde(e,t,r,o,n={}){return Io("Mapped",[e,t,r,o],n)}function PUr(e){let t=yc(e);return qde(t)}function sHe(e){return e.reduce((t,r)=>[...t,...qde(r)],[])}function NUr(e){return N.IsNumber(e)?[ri(`${e}`)]:[ri(e)]}function qde(e){return Ss(e)?sHe(Yh(e.enum)):Tn(e)?NUr(e.const):Da(e)?PUr(e.pattern):zr(e)?sHe(e.anyOf):[e]}function cHe(e){return qde(e)}function MUr(e){return Da(e)?yc(e.pattern):e}function LUr(e,t,r,o,n,i){let a=dt.Assign(e,{[r.name]:o}),s=Or(a,t,n),c=MUr(s),u=Or(a,t,i);return iJ(c)||aJ(c)?{[c.const]:u}:{}}function DUr(e,t,r,o,n,i){return o.reduce((a,s)=>[...a,LUr(e,t,r,s,n,i)],[])}function $Ur(e){return e.reduce((t,r)=>[...t,Do(r)],[])}function uHe(e,t,r,o,n,i){let a=cHe(o),s=DUr(e,t,r,a,n,i),c=$Ur(s);return $a(c)}function aHe(e,t,r,o,n,i,a){return Bo([o])?dt.Update(uHe(e,t,r,o,n,i),{},a):hde(r,o,n,i,a)}function pHe(e,t,r,o,n,i,a){let s=Or(e,t,o);return aHe(e,t,r,s,n,i,a)}function zUr(e,t){return N.Keys(e).filter(o=>t.includes(o)).reduce((o,n)=>({...o,[n]:JBe(e,n,e[n])}),{})}function UUr(e,t){return N.Keys(e).filter(o=>!t.includes(o)).reduce((o,n)=>({...o,[n]:Or(e,{callstack:[]},e[n])}),{})}function FUr(e,t){let r=qBe(e),o=zUr(e,r),n=UUr(e,r),i={...o,...n};return dt.Update(i,{},t)}function lHe(e,t,r,o){let n=dt.Assign(e,r);return FUr(n,o)}function gde(e,t={}){return Io("NonNullable",[e],t)}function qUr(e){let t=gn([ZC(),fJ()]);return RJ(e,t,{})}function dHe(e,t){return Bo([e])?dt.Update(qUr(e),{},t):gde(e,t)}function mHe(e,t,r,o){let n=Or(e,t,r);return dHe(n,o)}function _de(e,t,r={}){return Io("Omit",[e,t],r)}function kJ(e){let t=aA(e);return Po(t)?t.properties:mi()}function WUr(e,t){return N.Keys(e).reduce((o,n)=>t.includes(n)?o:{...o,[n]:e[n]},{})}function hHe(e,t){let r=kJ(e),o=cA(t),n=WUr(r,o);return Do(n)}function fHe(e,t,r){return Bo([e,t])?dt.Update(hHe(e,t),{},r):_de(e,t,r)}function gHe(e,t,r,o,n){let i=Or(e,t,r),a=Or(e,t,o);return fHe(i,a,n)}function yde(e,t){return Io("Options",[e,t],{})}function Wde(e,t){return jde(e,t)}function jde(e,t){return Bo([e])?dt.Update(e,{},t):yde(e,t)}function _He(e,t,r,o){let n=Or(e,t,r);return jde(n,o)}function xde(e,t={}){return Io("Parameters",[e],t)}function jUr(e){let t=bs(e)?e.parameters:[],r=oS({},{callstack:[]},t);return xc(r)}function yHe(e,t){return Bo([e])?dt.Update(jUr(e),{},t):xde(e,t)}function xHe(e,t,r,o){let n=Or(e,t,r);return yHe(n,o)}function bde(e,t={}){return Io("Partial",[e],t)}function SHe(e,t){let r=C_(e,t),o=sS(r);return Ax(dt.Assign(e,{[t]:o}),t)}function vHe(e){let t=e.map(r=>sS(r));return $a(t)}function THe(e){let t=e.map(r=>sS(r));return gn(t)}function EHe(e){let t=N.Keys(e).reduce((o,n)=>({...o,[n]:Fle(e[n])}),{});return Do(t)}function sS(e){return oa(e)?SHe(e.$defs,e.$ref):Ao(e)?vHe(e.allOf):zr(e)?THe(e.anyOf):Po(e)?EHe(e.properties):Do({})}function bHe(e,t){return Bo([e])?dt.Update(sS(e),{},t):bde(e,t)}function RHe(e,t,r,o){let n=Or(e,t,r);return bHe(n,o)}function Sde(e,t,r={}){return Io("Pick",[e,t],r)}function GUr(e,t){return N.Keys(e).reduce((o,n)=>t.includes(n)?dt.Assign(o,{[n]:e[n]}):o,{})}function kHe(e,t){let r=kJ(e),o=cA(t),n=GUr(r,o);return Do(n)}function wHe(e,t,r){return Bo([e,t])?dt.Update(kHe(e,t),{},r):Sde(e,t,r)}function IHe(e,t,r,o,n){let i=Or(e,t,r),a=Or(e,t,o);return wHe(i,a,n)}function vde(e,t={}){return Io("ReadonlyObject",[e],t)}function AHe(e){return xR(E_(e))}function OHe(e,t){let r=C_(e,t),o=cS(r);return Ax(dt.Assign(e,{[t]:o}),t)}function PHe(e){let t=e.map(r=>cS(r));return $a(t)}function NHe(e){let t=N.Keys(e).reduce((o,n)=>({...o,[n]:qle(e[n])}),{});return Do(t)}function MHe(e){return xR(xc(e))}function LHe(e){let t=e.map(r=>cS(r));return gn(t)}function cS(e){return jn(e)?AHe(e.items):oa(e)?OHe(e.$defs,e.$ref):Ao(e)?PHe(e.allOf):Po(e)?NHe(e.properties):bn(e)?MHe(e.items):zr(e)?LHe(e.anyOf):e}function CHe(e,t){return Bo([e])?dt.Update(cS(e),{},t):vde(e)}function DHe(e,t,r,o){let n=Or(e,t,r);return CHe(n,o)}function $He(e,t,r,o){return o in e?EJ([o],e,e[o])?r:Or(e,t,e[o]):r}function zHe(e,t){let r=C_(e,t),o=uS(r);return Ax(dt.Assign(e,{[t]:o}),t)}function UHe(e){let t=e.map(r=>uS(r));return $a(t)}function FHe(e){let t=e.map(r=>uS(r));return gn(t)}function qHe(e){let t=N.Keys(e).reduce((o,n)=>({...o,[n]:HC(e[n])}),{});return Do(t)}function uS(e){return oa(e)?zHe(e.$defs,e.$ref):Ao(e)?UHe(e.allOf):zr(e)?FHe(e.anyOf):Po(e)?qHe(e.properties):Do({})}function Tde(e,t={}){return Io("Required",[e],t)}function WHe(e,t){return Bo([e])?dt.Update(uS(e),{},t):Tde(e,t)}function jHe(e,t,r,o){let n=Or(e,t,r);return WHe(n,o)}function Ede(e,t={}){return Io("ReturnType",[e],t)}function JUr(e){return bs(e)?e.returnType:qi()}function GHe(e,t){return Bo([e])?dt.Update(JUr(e),{},t):Ede(e,t)}function JHe(e,t,r,o={}){let n=Or(e,t,r);return GHe(n,o)}function VUr(e){return RR(e)?bn(e.items)?Gde(e.items.items):Is(e.items)?[e]:bi(e.items)?[e]:[qi()]:[e]}function Gde(e){return e.reduce((r,o)=>[...r,...VUr(o)],[])}function Bo(e){return N.TakeLeft(e,(t,r)=>bi(t)?!1:Bo(r),()=>!0)}function F$(e,t,r){return L6e(e)?F$(e.type,"remove",r):N6e(e)?F$(e.type,t,"remove"):M6e(e)?F$(e.type,"add",r):P6e(e)?F$(e.type,t,"add"):[e,t,r]}function BUr(e,t){return N.IsEqual(e,"remove")?QG(t):N.IsEqual(e,"add")?SR(t):t}function KUr(e,t){return N.IsEqual(e,"remove")?HC(t):N.IsEqual(e,"add")?bR(t):t}function L$(e,t,r){return N.Keys(r).reduce((o,n)=>({...o,[n]:Or(e,t,r[n])}),{})}function oS(e,t,r){let o=Id(e,t,r);return Gde(o)}function Id(e,t,r){return r.map(o=>Or(e,t,o))}function HUr(e,t,r,o,n){return N.IsEqual(r,"Awaited")?VHe(e,t,o[0],n):N.IsEqual(r,"Capitalize")?lKe(e,t,o[0],n):N.IsEqual(r,"Conditional")?gKe(e,t,o[0],o[1],o[2],o[3],n):N.IsEqual(r,"ConstructorParameters")?yKe(e,t,o[0],n):N.IsEqual(r,"Evaluate")?KBe(e,t,o[0],n):N.IsEqual(r,"Exclude")?vKe(e,t,o[0],o[1],n):N.IsEqual(r,"Extract")?kKe(e,t,o[0],o[1],n):N.IsEqual(r,"Index")?HKe(e,t,o[0],o[1],n):N.IsEqual(r,"InstanceType")?YKe(e,t,o[0],n):N.IsEqual(r,"Interface")?UBe(e,t,o[0],o[1],n):N.IsEqual(r,"KeyOf")?iHe(e,t,o[0],n):N.IsEqual(r,"Lowercase")?dKe(e,t,o[0],n):N.IsEqual(r,"Mapped")?pHe(e,t,o[0],o[1],o[2],o[3],n):N.IsEqual(r,"Module")?lHe(e,t,o[0],n):N.IsEqual(r,"NonNullable")?mHe(e,t,o[0],n):N.IsEqual(r,"Pick")?IHe(e,t,o[0],o[1],n):N.IsEqual(r,"Options")?_He(e,t,o[0],o[1]):N.IsEqual(r,"Parameters")?xHe(e,t,o[0],n):N.IsEqual(r,"Partial")?RHe(e,t,o[0],n):N.IsEqual(r,"Omit")?gHe(e,t,o[0],o[1],n):N.IsEqual(r,"ReadonlyObject")?DHe(e,t,o[0],n):N.IsEqual(r,"Record")?PVe(e,t,o[0],o[1],n):N.IsEqual(r,"Required")?jHe(e,t,o[0],n):N.IsEqual(r,"ReturnType")?JHe(e,t,o[0],n):N.IsEqual(r,"TemplateLiteral")?nBe(e,t,o[0],n):N.IsEqual(r,"Uncapitalize")?mKe(e,t,o[0],n):N.IsEqual(r,"Uppercase")?fKe(e,t,o[0],n):Io(r,o,n)}function Or(e,t,r){let o=KC(r),n=F$(r,XC(r)?"add":"none",gc(r)?"add":"none"),i=Ed(n[0])?n[0].Clone():n[0],a=bi(i)?$He(e,t,i,i.$ref):jn(i)?E_(Or(e,t,i.items),ZG(i)):jc(i)?R_(Or(e,t,i.iteratorItems),U6e(i)):z$(i)?Ude(e,t,i.target,i.arguments):xs(i)?Hb(Id(e,t,i.parameters),Or(e,t,i.instanceType),F6e(i)):Kb(i)?HUr(e,t,i.action,i.parameters,i.options):bs(i)?Xb(Id(e,t,i.parameters),Or(e,t,i.returnType),q6e(i)):Ao(i)?qm(Id(e,t,i.allOf),V6e(i)):Vc(i)?w_(Or(e,t,i.iteratorItems),nVe(i)):Po(i)?Do(L$(e,t,i.properties),G6e(i)):tc(i)?T_(Or(e,t,i.item),D6e(i)):za(i)?NVe(Il(i),Or(e,t,bc(i))):RR(i)?mJ(Or(e,t,i.items)):bn(i)?xc(oS(e,t,i.items),yVe(i)):zr(i)?gn(Id(e,t,i.anyOf),J6e(i)):i,s=o?xR(a):a;return BUr(n[1],KUr(n[2],s))}function Cd(e,t){return Or(e,{callstack:[]},t)}function BHe(e){return tc(e)?BHe(e.item):e}function KHe(e,t){return Bo([e])?dt.Update(BHe(e),{},t):Rde(e,t)}function VHe(e,t,r,o){let n=Or(e,t,r);return KHe(n,o)}function Rde(e,t={}){return Io("Awaited",[e],t)}function rg(e,t={}){return $de(e,t)}var HHe=new Map;function XUr(e,t){return(r,o,n)=>{if(r.api!==e)throw new Error(`Mismatched api: ${r.api} expected ${e}`);return t(r,o,n)}}function YUr(e,t){return(r,o,n)=>{if(r.api!==e)throw new Error(`Mismatched api: ${r.api} expected ${e}`);return t(r,o,n)}}function og(e,t){HHe.set(e.api,{provider:{api:e.api,stream:XUr(e.api,e.stream),streamSimple:YUr(e.api,e.streamSimple)},sourceId:t})}function XHe(e){return HHe.get(e)?.provider}O_();ng();Jm();Jm();var wso=e=>import(e),oAt,nAt,iAt,aAt,sAt,cAt,uAt,pAt,lAt,dAt;function mAt(e,t){(async()=>{for await(let r of t)e.push(r);e.end()})()}function fAt(e,t){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function k0(e){return(t,r,o)=>{let n=new oc;return e().then(i=>{let a=i.stream(t,r,o);mAt(n,a)}).catch(i=>{let a=fAt(t,i);n.push({type:"error",reason:"error",error:a}),n.end(a)}),n}}function I0(e){return(t,r,o)=>{let n=new oc;return e().then(i=>{let a=i.streamSimple(t,r,o);mAt(n,a)}).catch(i=>{let a=fAt(t,i);n.push({type:"error",reason:"error",error:a}),n.end(a)}),n}}function hAt(){return oAt||=Promise.resolve().then(()=>(c8e(),s8e)).then(e=>{let t=e;return{stream:t.streamAnthropic,streamSimple:t.streamSimpleAnthropic}}),oAt}function gAt(){return nAt||=Promise.resolve().then(()=>(PXe(),OXe)).then(e=>{let t=e;return{stream:t.streamAzureOpenAIResponses,streamSimple:t.streamSimpleAzureOpenAIResponses}}),nAt}function _At(){return iAt||=Promise.resolve().then(()=>(lot(),pot)).then(e=>{let t=e;return{stream:t.streamGoogle,streamSimple:t.streamSimpleGoogle}}),iAt}function yAt(){return aAt||=Promise.resolve().then(()=>(got(),hot)).then(e=>{let t=e;return{stream:t.streamGoogleVertex,streamSimple:t.streamSimpleGoogleVertex}}),aAt}function xAt(){return sAt||=Promise.resolve().then(()=>(SCt(),bCt)).then(e=>{let t=e;return{stream:t.streamMistral,streamSimple:t.streamSimpleMistral}}),sAt}function bAt(){return cAt||=Promise.resolve().then(()=>(jCt(),WCt)).then(e=>{let t=e;return{stream:t.streamOpenAICodexResponses,streamSimple:t.streamSimpleOpenAICodexResponses}}),cAt}function SAt(){return uAt||=Promise.resolve().then(()=>(YCt(),XCt)).then(e=>{let t=e;return{stream:t.streamOpenAICompletions,streamSimple:t.streamSimpleOpenAICompletions}}),uAt}function vAt(){return pAt||=Promise.resolve().then(()=>(rAt(),tAt)).then(e=>{let t=e;return{stream:t.streamOpenAIResponses,streamSimple:t.streamSimpleOpenAIResponses}}),pAt}function TAt(){return lAt?Promise.resolve(lAt):(dAt||=wso("./amazon-bedrock.js").then(e=>{let t=e;return{stream:t.streamBedrock,streamSimple:t.streamSimpleBedrock}}),dAt)}var kso=k0(hAt),Iso=I0(hAt),Cso=k0(gAt),Aso=I0(gAt),Oso=k0(_At),Pso=I0(_At),Nso=k0(yAt),Mso=I0(yAt),Lso=k0(xAt),Dso=I0(xAt),$so=k0(bAt),zso=I0(bAt),Uso=k0(SAt),Fso=I0(SAt),qso=k0(vAt),Wso=I0(vAt),jso=k0(TAt),Gso=I0(TAt);function Jso(){og({api:"anthropic-messages",stream:kso,streamSimple:Iso}),og({api:"openai-completions",stream:Uso,streamSimple:Fso}),og({api:"mistral-conversations",stream:Lso,streamSimple:Dso}),og({api:"openai-responses",stream:qso,streamSimple:Wso}),og({api:"azure-openai-responses",stream:Cso,streamSimple:Aso}),og({api:"openai-codex-responses",stream:$so,streamSimple:zso}),og({api:"google-generative-ai",stream:Oso,streamSimple:Pso}),og({api:"google-vertex",stream:Nso,streamSimple:Mso}),og({api:"bedrock-converse-stream",stream:jso,streamSimple:Gso})}Jso();TAe();O_();function Vso(e){let t=XHe(e);if(!t)throw new Error(`No API provider registered for api: ${e}`);return t}function Bso(e,t,r){return Vso(e.api).streamSimple(e,t,r)}async function U1(e,t,r){return Bso(e,t,r).result()}EAe();Jm();GA();function Kso(e){return N.IsObject(e)&&N.HasPropertyKey(e,"check")&&N.HasPropertyKey(e,"errors")&&N.IsFunction(e.check)&&N.IsFunction(e.errors)}function eY(e){return N.HasPropertyKey(e,"~guard")&&Kso(e["~guard"])}function tY(e){return N.HasPropertyKey(e,"~refine")&&N.IsArray(e["~refine"])&&N.Every(e["~refine"],0,t=>N.IsObject(t)&&N.HasPropertyKey(t,"check")&&N.HasPropertyKey(t,"error")&&N.IsFunction(t.check)&&N.IsFunction(t.error))}function Xu(e){return N.IsObject(e)&&!N.IsArray(e)}function s5(e){return N.IsBoolean(e)}function Vo(e){return Xu(e)||s5(e)}function c5(e){return N.HasPropertyKey(e,"additionalItems")&&Vo(e.additionalItems)}function Qd(e){return N.HasPropertyKey(e,"additionalProperties")&&Vo(e.additionalProperties)}function rY(e){return N.HasPropertyKey(e,"allOf")&&N.IsArray(e.allOf)&&e.allOf.every(t=>Vo(t))}function u5(e){return N.HasPropertyKey(e,"$anchor")&&N.IsString(e.$anchor)}function oY(e){return N.HasPropertyKey(e,"anyOf")&&N.IsArray(e.anyOf)&&e.anyOf.every(t=>Vo(t))}function nY(e){return N.HasPropertyKey(e,"const")}function C0(e){return N.HasPropertyKey(e,"contains")&&Vo(e.contains)}function Hl(e){return N.HasPropertyKey(e,"default")}function p5(e){return N.HasPropertyKey(e,"dependencies")&&N.IsObject(e.dependencies)&&Object.values(e.dependencies).every(t=>Vo(t)||N.IsArray(t)&&t.every(r=>N.IsString(r)))}function l5(e){return N.HasPropertyKey(e,"dependentRequired")&&N.IsObject(e.dependentRequired)&&Object.values(e.dependentRequired).every(t=>N.IsArray(t)&&t.every(r=>N.IsString(r)))}function d5(e){return N.HasPropertyKey(e,"dependentSchemas")&&N.IsObject(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(t=>Vo(t))}function Kv(e){return N.HasPropertyKey(e,"$dynamicAnchor")&&N.IsString(e.$dynamicAnchor)}function iY(e){return N.HasPropertyKey(e,"$dynamicRef")&&N.IsString(e.$dynamicRef)}function aY(e){return N.HasPropertyKey(e,"else")&&Vo(e.else)}function sY(e){return N.HasPropertyKey(e,"enum")&&N.IsArray(e.enum)}function m5(e){return N.HasPropertyKey(e,"exclusiveMaximum")&&(N.IsNumber(e.exclusiveMaximum)||N.IsBigInt(e.exclusiveMaximum))}function Ug(e){return N.HasPropertyKey(e,"exclusiveMinimum")&&(N.IsNumber(e.exclusiveMinimum)||N.IsBigInt(e.exclusiveMinimum))}function tk(e){return N.HasPropertyKey(e,"format")&&N.IsString(e.format)}function A0(e){return N.HasPropertyKey(e,"$id")&&N.IsString(e.$id)}function cY(e){return N.HasPropertyKey(e,"if")&&Vo(e.if)}function Hv(e){return N.HasPropertyKey(e,"items")&&(Vo(e.items)||N.IsArray(e.items)&&e.items.every(t=>Vo(t)))}function uY(e){return Hv(e)&&N.IsArray(e.items)}function f5(e){return N.HasPropertyKey(e,"maximum")&&(N.IsNumber(e.maximum)||N.IsBigInt(e.maximum))}function h5(e){return N.HasPropertyKey(e,"maxContains")&&N.IsNumber(e.maxContains)}function rk(e){return N.HasPropertyKey(e,"maxItems")&&N.IsNumber(e.maxItems)}function g5(e){return N.HasPropertyKey(e,"maxLength")&&N.IsNumber(e.maxLength)}function _5(e){return N.HasPropertyKey(e,"maxProperties")&&N.IsNumber(e.maxProperties)}function Fg(e){return N.HasPropertyKey(e,"minimum")&&(N.IsNumber(e.minimum)||N.IsBigInt(e.minimum))}function O0(e){return N.HasPropertyKey(e,"minContains")&&N.IsNumber(e.minContains)}function P0(e){return N.HasPropertyKey(e,"minItems")&&N.IsNumber(e.minItems)}function ok(e){return N.HasPropertyKey(e,"minLength")&&N.IsNumber(e.minLength)}function nk(e){return N.HasPropertyKey(e,"minProperties")&&N.IsNumber(e.minProperties)}function y5(e){return N.HasPropertyKey(e,"multipleOf")&&(N.IsNumber(e.multipleOf)||N.IsBigInt(e.multipleOf))}function pY(e){return N.HasPropertyKey(e,"not")&&Vo(e.not)}function lY(e){return N.HasPropertyKey(e,"oneOf")&&N.IsArray(e.oneOf)&&e.oneOf.every(t=>Vo(t))}function ik(e){return N.HasPropertyKey(e,"pattern")&&(N.IsString(e.pattern)||e.pattern instanceof RegExp)}function Xv(e){return N.HasPropertyKey(e,"patternProperties")&&N.IsObject(e.patternProperties)&&Object.values(e.patternProperties).every(t=>Vo(t))}function N0(e){return N.HasPropertyKey(e,"prefixItems")&&N.IsArray(e.prefixItems)&&e.prefixItems.every(t=>Vo(t))}function Yv(e){return N.HasPropertyKey(e,"properties")&&N.IsObject(e.properties)&&Object.values(e.properties).every(t=>Vo(t))}function x5(e){return N.HasPropertyKey(e,"propertyNames")&&(N.IsObject(e.propertyNames)||Vo(e.propertyNames))}function Hso(e){return N.HasPropertyKey(e,"$recursiveAnchor")&&N.IsBoolean(e.$recursiveAnchor)}function dY(e){return Hso(e)&&N.IsEqual(e.$recursiveAnchor,!0)}function mY(e){return N.HasPropertyKey(e,"$recursiveRef")&&N.IsString(e.$recursiveRef)}function fY(e){return N.HasPropertyKey(e,"$ref")&&N.IsString(e.$ref)}function qg(e){return N.HasPropertyKey(e,"required")&&N.IsArray(e.required)&&e.required.every(t=>N.IsString(t))}function hY(e){return N.HasPropertyKey(e,"then")&&Vo(e.then)}function b5(e){return N.HasPropertyKey(e,"type")&&(N.IsString(e.type)||N.IsArray(e.type)&&e.type.every(t=>N.IsString(t)))}function hy(e){return N.HasPropertyKey(e,"uniqueItems")&&N.IsBoolean(e.uniqueItems)}function ak(e){return N.HasPropertyKey(e,"unevaluatedItems")&&Vo(e.unevaluatedItems)}function sk(e){return N.HasPropertyKey(e,"unevaluatedProperties")&&Vo(e.unevaluatedProperties)}function Xso(e){return ak(e)||sk(e)||N.Keys(e).some(t=>gY(e[t]))}function Yso(e){return e.some(t=>gY(t))}function gY(e){return N.IsArray(e)?Yso(e):N.IsObject(e)?Xso(e):!1}function EAt(e,t){return gY(t)||N.Keys(e).some(r=>gY(e[r]))}var _Y=class{constructor(t){this.hasUnevaluated=t}UseUnevaluated(){return this.hasUnevaluated}Push(){return ae.Call(ae.Member("context","Push"),[])}Pop(){return ae.Call(ae.Member("context","Pop"),[])}AddIndex(t){return ae.Call(ae.Member("context","AddIndex"),[t])}AddKey(t){return ae.Call(ae.Member("context","AddKey"),[t])}Merge(t){return ae.Call(ae.Member("context","Merge"),[t])}},wu=class{constructor(){let t=new Set,r=new Set;this.stack=[{indices:t,keys:r}]}Push(){let t=new Set,r=new Set;return this.stack.push({indices:t,keys:r}),!0}Pop(){return this.stack.pop(),!0}AddIndex(t){return this.GetIndices().add(t),!0}AddKey(t){return this.GetKeys().add(t),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(t){for(let r of t)r.GetIndices().forEach(o=>this.GetIndices().add(o)),r.GetKeys().forEach(o=>this.GetKeys().add(o));return!0}},S5=class extends wu{constructor(t){super(),this.callback=t}AddError(t){return this.callback(t),!1}},kc=class extends S5{constructor(){super(t=>this.errors.push(t)),this.errors=[]}AddError(t){return this.errors.push(t),!1}GetErrors(){return this.errors}};var yY={identifier:"External",variables:[]};function Xl(e){let t=`External[${yY.variables.length}]`;return yY.variables.push(e),t}function RAt(){yY.variables=[]}function wAt(){return{...yY}}function kAt(e,t,r,o){return ae.Call(ae.Member(ae.Member(Xl(r),"~guard"),"check"),[o])}function IAt(e,t,r,o){return r["~guard"].check(o)}function CAt(e,t,r,o,n,i){return n["~guard"].check(i)||t.AddError({keyword:"~guard",schemaPath:r,instancePath:o,params:{errors:n["~guard"].errors(i)}})}function AAt(e,t,r,o){let n=Xl(r["~refine"].map(i=>i));return ae.Every(n,ae.Constant(0),["refinement","_"],ae.Call(ae.Member("refinement","check"),[o]))}function OAt(e,t,r,o){return N.Every(r["~refine"],0,(n,i)=>n.check(o))}function PAt(e,t,r,o,n,i){return N.EveryAll(n["~refine"],0,(a,s)=>a.check(i)||t.AddError({keyword:"~refine",schemaPath:r,instancePath:o,params:{index:s,message:a.error(i)}}))}var Qso=0;function Ra(){return`var_${Qso++}`}function AAe(e){return Hv(e)&&N.IsArray(e.items)}function NAt(e,t,r,o){if(!AAe(r))return ae.Constant(!0);let[n,i]=[Ra(),Ra()],a=Zd(e,t,r.additionalItems,n),s=ae.IsLessThan(i,ae.Constant(r.items.length)),c=t.AddIndex(i),u=t.UseUnevaluated()?ae.Or(s,ae.And(a,c)):ae.Or(s,a);return ae.Call(ae.Member(o,"every"),[ae.ArrowFunction([n,i],u)])}function MAt(e,t,r,o){return AAe(r)?o.every((i,a)=>N.IsLessThan(a,r.items.length)||em(e,t,r.additionalItems,i)&&t.AddIndex(a)):!0}function LAt(e,t,r,o,n,i){return AAe(n)?i.every((s,c)=>{let u=`${r}/additionalItems`,l=`${o}/${c}`;return N.IsLessThan(c,n.items.length)||tm(e,t,u,l,n.additionalItems,s)&&t.AddIndex(c)}):!0}function Zso(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function OAe(e){let t=[];return Xv(e)&&t.push(...N.Keys(e.patternProperties)),Yv(e)&&t.push(...N.Keys(e.properties).map(Zso)),N.IsEqual(t.length,0)?"(?!)":`(${t.join("|")})`}function eco(e,t,r){return qg(t)&&Yv(t)&&!Xv(t)&&N.IsEqual(t.additionalProperties,!1)&&N.IsEqual(N.Keys(t.properties).length,t.required.length)}function tco(e,t,r){return ae.IsEqual(ae.Member(ae.Call(ae.Member("Object","getOwnPropertyNames"),[r]),"length"),ae.Constant(t.required.length))}function rco(e,t,r,o){let[n,i]=[Ra(),Ra()],a=Xl(new RegExp(OAe(r))),s=Zd(e,t,r.additionalProperties,`${o}[${n}]`),c=ae.Call(ae.Member(a,"test"),[n]),u=t.AddKey(n),l=t.UseUnevaluated()?ae.Or(c,ae.And(s,u)):ae.Or(c,s);return ae.Every(ae.Keys(o),ae.Constant(0),[n,i],l)}function DAt(e,t,r,o){return eco(t,r,o)?tco(t,r,o):rco(e,t,r,o)}function $At(e,t,r,o){let n=new RegExp(OAe(r));return N.Every(N.Keys(o),0,(a,s)=>n.test(a)||em(e,t,r.additionalProperties,o[a])&&t.AddKey(a))}function zAt(e,t,r,o,n,i){let a=new RegExp(OAe(n)),s=[];return N.EveryAll(N.Keys(i),0,(u,l)=>{let m=`${r}/additionalProperties`,p=`${o}/${u}`,h=new kc,f=a.test(u)||tm(e,h,m,p,n.additionalProperties,i[u])&&t.AddKey(u);return f||s.push(u),f})||t.AddError({keyword:"additionalProperties",schemaPath:r,instancePath:o,params:{additionalProperties:s}})}function Qv(e,t,r,o,n){let i=ae.ConstDeclaration("results","[]"),a=r.map((l,m)=>ae.ConstDeclaration(`context_${m}`,ae.New("CheckContext",[]))),s=r.map((l,m)=>ae.ConstDeclaration(`condition_${m}`,ae.Call(ae.ArrowFunction(["context"],Oi(e,t,l,o)),[`context_${m}`]))),c=r.map((l,m)=>ae.If(`condition_${m}`,ae.Call(ae.Member("results","push"),[`context_${m}`]))),u=ae.Return(ae.And(n,t.Merge("results")));return ae.Call(ae.ArrowFunction([],ae.Statements([i,...a,...s,...c,u])),[])}function oco(e,t,r,o){return Qv(e,t,r.allOf,o,ae.IsEqual(ae.Member("results","length"),ae.Constant(r.allOf.length)))}function nco(e,t,r,o){return ae.ReduceAnd(r.allOf.map(n=>Oi(e,t,n,o)))}function UAt(e,t,r,o){return t.UseUnevaluated()?oco(e,t,r,o):nco(e,t,r,o)}function FAt(e,t,r,o){let n=r.allOf.reduce((i,a)=>{let s=new wu;return Jn(e,s,a,o)?[...i,s]:i},[]);return N.IsEqual(n.length,r.allOf.length)&&t.Merge(n)}function qAt(e,t,r,o,n,i){let a=[],s=n.allOf.reduce((u,l,m)=>{let p=`${r}/allOf/${m}`,h=new kc,f=ia(e,h,p,o,l,i);return f||a.push(h),f?[...u,h]:u},[]),c=N.IsEqual(s.length,n.allOf.length)&&t.Merge(s);return c||a.forEach(u=>u.GetErrors().forEach(l=>t.AddError(l))),c}function ico(e,t,r,o){return Qv(e,t,r.anyOf,o,ae.IsGreaterThan(ae.Member("results","length"),ae.Constant(0)))}function aco(e,t,r,o){return ae.ReduceOr(r.anyOf.map(n=>Oi(e,t,n,o)))}function WAt(e,t,r,o){return t.UseUnevaluated()?ico(e,t,r,o):aco(e,t,r,o)}function jAt(e,t,r,o){let n=r.anyOf.reduce((i,a)=>{let s=new wu;return Jn(e,s,a,o)?[...i,s]:i},[]);return N.IsGreaterThan(n.length,0)&&t.Merge(n)}function GAt(e,t,r,o,n,i){let a=[],s=n.anyOf.reduce((u,l,m)=>{let p=new kc,h=`${r}/anyOf/${m}`,f=ia(e,p,h,o,l,i);return f||a.push(p),f?[...u,p]:u},[]),c=N.IsGreaterThan(s.length,0)&&t.Merge(s);return c||a.forEach(u=>u.GetErrors().forEach(l=>t.AddError(l))),c||t.AddError({keyword:"anyOf",schemaPath:r,instancePath:o,params:{}})}function JAt(e,t,r,o){return r?ae.Constant(!0):ae.Constant(!1)}function PAe(e,t,r,o){return r}function VAt(e,t,r,o,n,i){return PAe(e,t,n,i)||t.AddError({keyword:"boolean",schemaPath:r,instancePath:o,params:{}})}function BAt(e,t,r,o){return N.IsValueLike(r.const)?ae.IsEqual(o,ae.Constant(r.const)):ae.IsDeepEqual(o,Xl(r.const))}function NAe(e,t,r,o){return N.IsValueLike(r.const)?N.IsEqual(o,r.const):N.IsDeepEqual(o,r.const)}function KAt(e,t,r,o,n,i){return NAe(e,t,n,i)||t.AddError({keyword:"const",schemaPath:r,instancePath:o,params:{allowedValue:n.const}})}function HAt(e){return!(O0(e)&&N.IsEqual(e.minContains,0))}function XAt(e,t,r,o){if(!HAt(r))return ae.Constant(!0);let n=Ra(),i=ae.Not(ae.IsEqual(ae.Member(o,"length"),ae.Constant(0))),a=ae.Call(ae.Member(o,"some"),[ae.ArrowFunction([n],Oi(e,t,r.contains,n))]);return ae.And(i,a)}function MAe(e,t,r,o){return HAt(r)?!N.IsEqual(o.length,0)&&o.some(n=>Jn(e,t,r.contains,n)):!0}function YAt(e,t,r,o,n,i){return MAe(e,t,n,i)||t.AddError({keyword:"contains",schemaPath:r,instancePath:o,params:{minContains:1}})}function QAt(e,t,r,o){let n=ae.IsEqual(ae.Member(ae.Keys(o),"length"),ae.Constant(0)),i=ae.ReduceAnd(N.Entries(r.dependencies).map(([a,s])=>{let c=ae.Not(ae.HasPropertyKey(o,ae.Constant(a))),u=Oi(e,t,s,o),l=m=>ae.ReduceAnd(m.map(p=>ae.HasPropertyKey(o,ae.Constant(p))));return ae.Or(c,N.IsArray(s)?l(s):u)}));return ae.Or(n,i)}function ZAt(e,t,r,o){let n=N.IsEqual(N.Keys(o).length,0),i=N.Every(N.Entries(r.dependencies),0,([a,s])=>!N.HasPropertyKey(o,a)||(N.IsArray(s)?s.every(c=>N.HasPropertyKey(o,c)):Jn(e,t,s,o)));return n||i}function eOt(e,t,r,o,n,i){let a=N.IsEqual(N.Keys(i).length,0),s=N.EveryAll(N.Entries(n.dependencies),0,([c,u])=>{let l=`${r}/dependencies/${c}`;return!N.HasPropertyKey(i,c)||(N.IsArray(u)?u.every(m=>N.HasPropertyKey(i,m)||t.AddError({keyword:"dependencies",schemaPath:r,instancePath:o,params:{property:c,dependencies:u}})):ia(e,t,l,o,u,i))});return a||s}function tOt(e,t,r,o){let n=ae.IsEqual(ae.Member(ae.Keys(o),"length"),ae.Constant(0)),i=ae.ReduceAnd(N.Entries(r.dependentRequired).map(([a,s])=>{let c=ae.Not(ae.HasPropertyKey(o,ae.Constant(a))),u=ae.ReduceAnd(s.map(l=>ae.HasPropertyKey(o,ae.Constant(l))));return ae.Or(c,u)}));return ae.Or(n,i)}function rOt(e,t,r,o){let n=N.IsEqual(N.Keys(o).length,0),i=N.Every(N.Entries(r.dependentRequired),0,([a,s])=>!N.HasPropertyKey(o,a)||s.every(c=>N.HasPropertyKey(o,c)));return n||i}function oOt(e,t,r,o,n,i){let a=N.IsEqual(N.Keys(i).length,0),s=N.EveryAll(N.Entries(n.dependentRequired),0,([c,u])=>!N.HasPropertyKey(i,c)||N.EveryAll(u,0,l=>N.HasPropertyKey(i,l)||t.AddError({keyword:"dependentRequired",schemaPath:r,instancePath:o,params:{property:c,dependencies:u}})));return a||s}function nOt(e,t,r,o){let n=ae.IsEqual(ae.Member(ae.Keys(o),"length"),ae.Constant(0)),i=ae.ReduceAnd(N.Entries(r.dependentSchemas).map(([a,s])=>{let c=ae.Not(ae.HasPropertyKey(o,ae.Constant(a))),u=Oi(e,t,s,o);return ae.Or(c,u)}));return ae.Or(n,i)}function iOt(e,t,r,o){let n=N.IsEqual(N.Keys(o).length,0),i=N.Every(N.Entries(r.dependentSchemas),0,([a,s])=>!N.HasPropertyKey(o,a)||Jn(e,t,s,o));return n||i}function aOt(e,t,r,o,n,i){let a=N.IsEqual(N.Keys(i).length,0),s=N.EveryAll(N.Entries(n.dependentSchemas),0,([c,u])=>{let l=`${r}/dependentSchemas/${c}`;return!N.HasPropertyKey(i,c)||ia(e,t,l,o,u,i)});return a||s}function sOt(e,t,r,o){let n=e.DynamicRef(r)??!1;return M0(e,t,n,o)}function cOt(e,t,r,o){let n=e.DynamicRef(r)??!1;return Vo(n)&&Jn(e,t,n,o)}function uOt(e,t,r,o,n,i){let a=e.DynamicRef(n)??!1;return Vo(a)&&ia(e,t,"#",o,a,i)}function pOt(e,t,r,o){return ae.ReduceOr(r.enum.map(n=>{if(N.IsValueLike(n))return ae.IsEqual(o,ae.Constant(n));let i=Xl(n);return ae.IsDeepEqual(o,i)}))}function DAe(e,t,r,o){return r.enum.some(n=>N.IsValueLike(n)?N.IsEqual(o,n):N.IsDeepEqual(o,n))}function lOt(e,t,r,o,n,i){return DAe(e,t,n,i)||t.AddError({keyword:"enum",schemaPath:r,instancePath:o,params:{allowedValues:n.enum}})}function dOt(e,t,r,o){return ae.IsLessThan(o,ae.Constant(r.exclusiveMaximum))}function $Ae(e,t,r,o){return N.IsLessThan(o,r.exclusiveMaximum)}function mOt(e,t,r,o,n,i){return $Ae(e,t,n,i)||t.AddError({keyword:"exclusiveMaximum",schemaPath:r,instancePath:o,params:{comparison:"<",limit:n.exclusiveMaximum}})}function fOt(e,t,r,o){return ae.IsGreaterThan(o,ae.Constant(r.exclusiveMinimum))}function zAe(e,t,r,o){return N.IsGreaterThan(o,r.exclusiveMinimum)}function hOt(e,t,r,o,n,i){return zAe(e,t,n,i)||t.AddError({keyword:"exclusiveMinimum",schemaPath:r,instancePath:o,params:{comparison:">",limit:n.exclusiveMinimum}})}var uk={};to(uk,{Clear:()=>ROt,Entries:()=>Wco,Get:()=>Jco,Has:()=>Gco,IsDate:()=>F1,IsDateTime:()=>xY,IsDuration:()=>bY,IsEmail:()=>SY,IsHostname:()=>vY,IsIPv4:()=>RY,IsIPv6:()=>wY,IsIdnEmail:()=>TY,IsIdnHostname:()=>EY,IsIri:()=>IY,IsIriReference:()=>kY,IsJsonPointer:()=>AY,IsJsonPointerUriFragment:()=>CY,IsRegex:()=>OY,IsRelativeJsonPointer:()=>PY,IsTime:()=>q1,IsUri:()=>DY,IsUriReference:()=>NY,IsUriTemplate:()=>MY,IsUrl:()=>$Y,IsUuid:()=>zY,Reset:()=>wOt,Set:()=>jco,Test:()=>Vco});var sco=[0,31,28,31,30,31,30,31,31,30,31,30,31],cco=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function uco(e){return e%4===0&&(e%100!==0||e%400===0)}function F1(e){let t=cco.exec(e);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o===2&&uco(r)?29:sco[o])}var pco=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function q1(e,t=!0){let r=pco.exec(e);if(!r)return!1;let o=+r[1],n=+r[2],i=+r[3],a=r[4]==="-"?-1:1,s=+(r[5]||0),c=+(r[6]||0);if(s>23||c>59||t&&!r[4]&&e.toLowerCase().indexOf("z")===-1)return!1;if(o<=23&&n<=59&&i<60)return!0;let u=n-c*a,l=o-s*a-(u<0?1:0);return(l===23||l===-1)&&(u===59||u===-1)&&i<61}function xY(e,t=!0){let r=e.split(/T/i);return r.length===2&&F1(r[0])&&q1(r[1],t)}var lco=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function bY(e){return lco.test(e)}var dco=/^(?!.*\.\.)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;function SY(e){return dco.test(e)}function mco(e,t,r){e=r?Math.floor(e/700):e>>1,e+=Math.floor(e/t);let o=0;for(;e>455;)e=Math.floor(e/35),o+=36;return o+Math.floor(36*e/(e+38))}function gOt(e){let t=[],r=128,o=0,n=72,i=e.lastIndexOf("-");if(i>0)for(let s=0;s<i;s++){let c=e.charCodeAt(s);if(c>=128)throw new Error("Invalid punycode: non-basic before delimiter");t.push(c)}let a=i<0?0:i+1;for(;a<e.length;){let s=o,c=1,u=36;for(;;){if(a>=e.length)throw new Error("Invalid punycode: unexpected end of input");let m=e.charCodeAt(a++),p;if(m>=97&&m<=122)p=m-97;else if(m>=48&&m<=57)p=m-48+26;else if(m>=65&&m<=90)p=m-65;else throw new Error("Invalid punycode: bad digit character");o+=p*c;let h=u<=n?1:u>=n+26?26:u-n;if(p<h)break;c*=36-h,u+=36}let l=t.length+1;n=mco(o-s,l,s===0),r+=Math.floor(o/l),o%=l,t.splice(o,0,r),o++}return globalThis.String.fromCodePoint(...t)}function hco(e){return new RegExp("\\p{Mn}","u").test(String.fromCodePoint(e))}function gco(e){return new RegExp("\\p{Mc}","u").test(String.fromCodePoint(e))}function _co(e){return new RegExp("\\p{Me}","u").test(String.fromCodePoint(e))}function yco(e){return hco(e)||gco(e)||_co(e)}var xco=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),bco=new Set([2381,2509,2637,2765,2893,3021,3149,3277,3387,3388,3405,3530,6980,7082,7083,43456,69702,69759,69817,69939,69940,70080,70197,70477,70722,70850,71103,71231,71350,72767,73028,73029]);function Sco(e){return new RegExp("\\p{Script=Greek}","u").test(String.fromCodePoint(e))}function vco(e){return new RegExp("\\p{Script=Hebrew}","u").test(String.fromCodePoint(e))}function Tco(e){return new RegExp("\\p{Script=Hiragana}","u").test(String.fromCodePoint(e))}function Eco(e){return new RegExp("\\p{Script=Katakana}","u").test(String.fromCodePoint(e))}function Rco(e){return new RegExp("\\p{Script=Han}","u").test(String.fromCodePoint(e))}function wco(e){return e>=1632&&e<=1641}function kco(e){return e>=1776&&e<=1785}function Ico(e){return bco.has(e)}function _Ot(e){if(e.length===0)return!1;let t=[...e].map(a=>a.codePointAt(0)),r=t.length;if(t[0]===45||t[r-1]===45||r>=4&&t[2]===45&&t[3]===45||yco(t[0]))return!1;let o=!1,n=!1,i=!1;for(let a=0;a<r;a++){let s=t[a];if(xco.has(s))return!1;(Tco(s)||Eco(s)||Rco(s))&&(o=!0),wco(s)&&(n=!0),kco(s)&&(i=!0);let c=t[a-1],u=t[a+1];switch(s){case 183:if(c!==108||u!==108)return!1;break;case 885:if(u===void 0||!Sco(u))return!1;break;case 1523:case 1524:if(c===void 0||!vco(c))return!1;break;case 8205:if(c===void 0||!Ico(c))return!1;break;case 12539:break}}return!(e.includes("\u30FB")&&!o||n&&i)}function Cco(e){if(e.charCodeAt(0)===45||e.charCodeAt(e.length-1)===45||e.length>=4&&e.charCodeAt(2)===45&&e.charCodeAt(3)===45)return!1;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(!(r>=97&&r<=122||r>=65&&r<=90||r>=48&&r<=57||r===45))return!1}return!0}function yOt(e){return e.toLowerCase().startsWith("xn--")}function xOt(e){try{return _Ot(gOt(e.slice(4)))}catch{return!1}}function bOt(e){return e.length===0||e.length>63?!1:yOt(e)?xOt(e):_Ot(e)}function SOt(e){return e.length===0||e.length>63?!1:yOt(e)?xOt(e):Cco(e)}function vY(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split("."))if(!SOt(t))return!1;return!0}var Oco=/^(?!.*\.\.)[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+(?:\.[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+)*@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?)*$/iu;function TY(e){return Oco.test(e)}function EY(e){if(e.length===0||e.includes(" "))return!1;let t=e.normalize("NFC").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".");if(t.length>253)return!1;for(let r of t.split("."))if(!bOt(r))return!1;return!0}function UAe(e,t,r){let o=0,n=0,i=0,a=0;for(let s=t;s<r;s++){let c=e.charCodeAt(s);if(c===46){if(i===0||n>255||a===48&&i>1)return!1;o++,n=0,i=0,a=0}else if(c>=48&&c<=57)i===0&&(a=c),n=n*10+(c-48),i++;else return!1}return o===3&&i>0&&n<=255&&!(a===48&&i>1)}function RY(e){return UAe(e,0,e.length)}function Pco(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function wY(e){let t=e.length;if(t===0)return!1;let r=0,o=!1,n=0;if(e.charCodeAt(0)===58&&e.charCodeAt(1)===58){if(t===2)return!0;o=!0,n=2}for(;n<t;){let i=0,a=n;for(;n<t&&Pco(e.charCodeAt(n));)n++,i++;if(i===0)return!1;let s=e.charCodeAt(n);if(s===46){if(!UAe(e,a,t))return!1;r+=2,n=t;break}if(i>4)return!1;if(r++,n===t)break;if(s!==58)return!1;if(n++,e.charCodeAt(n)===58){if(o||e.charCodeAt(n+1)===58)return!1;if(o=!0,n++,n===t)break}}return o?r<=7:r===8}function vOt(e){try{return new URL(e,"http://example.com"),!0}catch{return!1}}function kY(e){if(e.includes(" ")||e.includes("\\")||/[\x00-\x1F\x7F]/.test(e)||/%(?![0-9a-fA-F]{2})/.test(e))return!1;if(e==="")return!0;let t=e.indexOf(":");return t>0&&/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e.substring(0,t))?vOt(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:vOt(e)}function IY(e){try{return new URL(e),!0}catch{return!1}}var Nco=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function CY(e){return Nco.test(e)}var Mco=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function AY(e){return Mco.test(e)}function OY(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}var Lco=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function PY(e){return Lco.test(e)}var Dco=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function NY(e){return Dco.test(e)}var $co=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;function MY(e){return $co.test(e)}function TOt(e){return e>=97&&e<=122||e>=65&&e<=90}function EOt(e){return TOt(e)||e>=48&&e<=57}function LY(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function zco(e){return EOt(e)||e===43||e===45||e===46}function FAe(e){return EOt(e)||e===45||e===46||e===95||e===126}function qAe(e){return e===33||e===36||e===38||e===39||e===40||e===41||e===42||e===43||e===44||e===59||e===61}function Uco(e){return FAe(e)||qAe(e)||e===58||e===64}function DY(e){let t=e.length;if(t===0||!TOt(e.charCodeAt(0)))return!1;let r=1;for(;r<t;){let o=e.charCodeAt(r);if(o===58)break;if(!zco(o))return!1;r++}if(e.charCodeAt(r)!==58)return!1;if(r++,e.charCodeAt(r)===47&&e.charCodeAt(r+1)===47){r+=2;let o=r,n=-1;for(let i=r;i<t;i++){let a=e.charCodeAt(i);if(a===64){n=i;break}if(a===47||a===63||a===35)break}if(n!==-1){for(let i=o;i<n;i++){let a=e.charCodeAt(i);if(a===91||a===93)return!1;if(a===37){if(i+2>=n||!LY(e.charCodeAt(i+1))||!LY(e.charCodeAt(i+2)))return!1;i+=2}else if(!FAe(a)&&!qAe(a)&&a!==58)return!1}r=n+1}if(e.charCodeAt(r)===91){for(r++;r<t&&e.charCodeAt(r)!==93;)r++;if(e.charCodeAt(r)!==93)return!1;r++}else for(;r<t;){let i=e.charCodeAt(r);if(i===47||i===63||i===35||i===58)break;if(i<128&&!FAe(i)&&!qAe(i))return!1;r++}if(e.charCodeAt(r)===58)for(r++;r<t;){let i=e.charCodeAt(r);if(i===47||i===63||i===35)break;if(i<48||i>57)return!1;r++}}for(;r<t;){let o=e.charCodeAt(r);if(o===37){if(r+2>=t||!LY(e.charCodeAt(r+1))||!LY(e.charCodeAt(r+2)))return!1;r+=2}else{if(o>127)return!1;if(!(Uco(o)||o===47||o===63||o===35))return!1}r++}return!0}var Fco=/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;function $Y(e){return Fco.test(e)}var qco=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function zY(e){return qco.test(e)}var ha=new Map;function ROt(){ha.clear()}function Wco(){return[...ha.entries()]}function jco(e,t){ha.set(e,t)}function Gco(e){return ha.has(e)}function Jco(e){return ha.get(e)}function Vco(e,t){return ha.get(e)?.(t)??!0}function wOt(){ROt(),ha.set("date-time",xY),ha.set("date",F1),ha.set("duration",bY),ha.set("email",SY),ha.set("hostname",vY),ha.set("idn-email",TY),ha.set("idn-hostname",EY),ha.set("ipv4",RY),ha.set("ipv6",wY),ha.set("iri-reference",kY),ha.set("iri",IY),ha.set("json-pointer-uri-fragment",CY),ha.set("json-pointer",AY),ha.set("regex",OY),ha.set("relative-json-pointer",PY),ha.set("time",q1),ha.set("uri-reference",NY),ha.set("uri-template",MY),ha.set("uri",DY),ha.set("url",$Y),ha.set("uuid",zY)}wOt();function kOt(e,t,r,o){return ae.Call(ae.Member("Format","Test"),[ae.Constant(r.format),o])}function WAe(e,t,r,o){return uk.Test(r.format,o)}function IOt(e,t,r,o,n,i){return WAe(e,t,n,i)||t.AddError({keyword:"format",schemaPath:r,instancePath:o,params:{format:n.format}})}function COt(e,t,r,o){let n=hY(r)?r.then:!0,i=aY(r)?r.else:!0;return ae.Ternary(Oi(e,t,r.if,o),Oi(e,t,n,o),Oi(e,t,i,o))}function AOt(e,t,r,o){let n=hY(r)?r.then:!0,i=aY(r)?r.else:!0;return Jn(e,t,r.if,o)?Jn(e,t,n,o):Jn(e,t,i,o)}function OOt(e,t,r,o,n,i){let a=hY(n)?n.then:!0,s=aY(n)?n.else:!0,c=new kc,u=ia(e,c,`${r}/if`,o,n.if,i)?ia(e,c,`${r}/then`,o,a,i)||t.AddError({keyword:"if",schemaPath:r,instancePath:o,params:{failingKeyword:"then"}}):ia(e,t,`${r}/else`,o,s,i)||t.AddError({keyword:"if",schemaPath:r,instancePath:o,params:{failingKeyword:"else"}});return u&&t.Merge([c]),u}function Bco(e,t,r,o){return ae.ReduceAnd(r.items.map((n,i)=>{let a=ae.IsLessEqualThan(ae.Member(o,"length"),ae.Constant(i)),s=Zd(e,t,n,`${o}[${i}]`),c=t.AddIndex(ae.Constant(i)),u=t.UseUnevaluated()?ae.And(s,c):s;return ae.Or(a,u)}))}function Kco(e,t,r,o){return N.Every(r.items,0,(n,i)=>N.IsLessEqualThan(o.length,i)||em(e,t,n,o[i])&&t.AddIndex(i))}function Hco(e,t,r,o,n,i){return N.EveryAll(n.items,0,(a,s)=>{let c=`${r}/items/${s}`,u=`${o}/${s}`;return N.IsLessEqualThan(i.length,s)||tm(e,t,c,u,a,i[s])&&t.AddIndex(s)})}function Xco(e,t,r,o){let n=N0(r)?r.prefixItems.length:0,i=Zd(e,t,r.items,"element"),a=t.AddIndex("index"),s=t.UseUnevaluated()?ae.And(i,a):i;return ae.Every(o,ae.Constant(n),["element","index"],s)}function Yco(e,t,r,o){let n=N0(r)?r.prefixItems.length:0;return N.Every(o,n,(i,a)=>em(e,t,r.items,i)&&t.AddIndex(a))}function Qco(e,t,r,o,n,i){let a=N0(n)?n.prefixItems.length:0;return N.EveryAll(i,a,(s,c)=>{let u=`${r}/items`,l=`${o}/${c}`;return tm(e,t,u,l,n.items,s)&&t.AddIndex(c)})}function POt(e,t,r,o){return uY(r)?Bco(e,t,r,o):Xco(e,t,r,o)}function NOt(e,t,r,o){return uY(r)?Kco(e,t,r,o):Yco(e,t,r,o)}function MOt(e,t,r,o,n,i){return uY(n)?Hco(e,t,r,o,n,i):Qco(e,t,r,o,n,i)}function LOt(e){return C0(e)}function DOt(e,t,r,o){if(!LOt(r))return ae.Constant(!0);let[n,i]=[Ra(),Ra()],a=ae.Call(ae.Member(o,"reduce"),[ae.ArrowFunction([n,i],ae.Ternary(Oi(e,t,r.contains,i),ae.PrefixIncrement(n),n)),ae.Constant(0)]);return ae.IsLessEqualThan(a,ae.Constant(r.maxContains))}function jAe(e,t,r,o){if(!LOt(r))return!0;let n=o.reduce((i,a)=>Jn(e,t,r.contains,a)?++i:i,0);return N.IsLessEqualThan(n,r.maxContains)}function $Ot(e,t,r,o,n,i){let a=O0(n)?n.minContains:1;return jAe(e,t,n,i)||t.AddError({keyword:"contains",schemaPath:r,instancePath:o,params:{minContains:a,maxContains:n.maxContains}})}function zOt(e,t,r,o){return ae.IsLessEqualThan(o,ae.Constant(r.maximum))}function GAe(e,t,r,o){return N.IsLessEqualThan(o,r.maximum)}function UOt(e,t,r,o,n,i){return GAe(e,t,n,i)||t.AddError({keyword:"maximum",schemaPath:r,instancePath:o,params:{comparison:"<=",limit:n.maximum}})}function FOt(e,t,r,o){return ae.IsLessEqualThan(ae.Member(o,"length"),ae.Constant(r.maxItems))}function JAe(e,t,r,o){return N.IsLessEqualThan(o.length,r.maxItems)}function qOt(e,t,r,o,n,i){return JAe(e,t,n,i)||t.AddError({keyword:"maxItems",schemaPath:r,instancePath:o,params:{limit:n.maxItems}})}function WOt(e,t,r,o){return ae.IsMaxLength(o,ae.Constant(r.maxLength))}function VAe(e,t,r,o){return N.IsMaxLength(o,r.maxLength)}function jOt(e,t,r,o,n,i){return VAe(e,t,n,i)||t.AddError({keyword:"maxLength",schemaPath:r,instancePath:o,params:{limit:n.maxLength}})}function GOt(e,t,r,o){return ae.IsLessEqualThan(ae.Member(ae.Keys(o),"length"),ae.Constant(r.maxProperties))}function BAe(e,t,r,o){return N.IsLessEqualThan(N.Keys(o).length,r.maxProperties)}function JOt(e,t,r,o,n,i){return BAe(e,t,n,i)||t.AddError({keyword:"maxProperties",schemaPath:r,instancePath:o,params:{limit:n.maxProperties}})}function VOt(e){return C0(e)}function BOt(e,t,r,o){if(!VOt(r))return ae.Constant(!0);let[n,i]=[Ra(),Ra()],a=ae.Call(ae.Member(o,"reduce"),[ae.ArrowFunction([n,i],ae.Ternary(Oi(e,t,r.contains,i),ae.PrefixIncrement(n),n)),ae.Constant(0)]);return ae.IsGreaterEqualThan(a,ae.Constant(r.minContains))}function KAe(e,t,r,o){if(!VOt(r))return!0;let n=o.reduce((i,a)=>Jn(e,t,r.contains,a)?++i:i,0);return N.IsGreaterEqualThan(n,r.minContains)}function KOt(e,t,r,o,n,i){return KAe(e,t,n,i)||t.AddError({keyword:"contains",schemaPath:r,instancePath:o,params:{minContains:n.minContains}})}function HOt(e,t,r,o){return ae.IsGreaterEqualThan(o,ae.Constant(r.minimum))}function HAe(e,t,r,o){return N.IsGreaterEqualThan(o,r.minimum)}function XOt(e,t,r,o,n,i){return HAe(e,t,n,i)||t.AddError({keyword:"minimum",schemaPath:r,instancePath:o,params:{comparison:">=",limit:n.minimum}})}function YOt(e,t,r,o){return ae.IsGreaterEqualThan(ae.Member(o,"length"),ae.Constant(r.minItems))}function XAe(e,t,r,o){return N.IsGreaterEqualThan(o.length,r.minItems)}function QOt(e,t,r,o,n,i){return XAe(e,t,n,i)||t.AddError({keyword:"minItems",schemaPath:r,instancePath:o,params:{limit:n.minItems}})}function ZOt(e,t,r,o){return ae.IsMinLength(o,ae.Constant(r.minLength))}function YAe(e,t,r,o){return N.IsMinLength(o,r.minLength)}function ePt(e,t,r,o,n,i){return YAe(e,t,n,i)||t.AddError({keyword:"minLength",schemaPath:r,instancePath:o,params:{limit:n.minLength}})}function tPt(e,t,r,o){return ae.IsGreaterEqualThan(ae.Member(ae.Keys(o),"length"),ae.Constant(r.minProperties))}function QAe(e,t,r,o){return N.IsGreaterEqualThan(N.Keys(o).length,r.minProperties)}function rPt(e,t,r,o,n,i){return QAe(e,t,n,i)||t.AddError({keyword:"minProperties",schemaPath:r,instancePath:o,params:{limit:n.minProperties}})}function oPt(e,t,r,o){return ae.MultipleOf(o,ae.Constant(r.multipleOf))}function ZAe(e,t,r,o){return N.IsMultipleOf(o,r.multipleOf)}function nPt(e,t,r,o,n,i){return ZAe(e,t,n,i)||t.AddError({keyword:"multipleOf",schemaPath:r,instancePath:o,params:{multipleOf:n.multipleOf}})}function Zco(e,t,r,o){return Qv(e,t,[r.not],o,ae.Not(ae.IsEqual(ae.Member("results","length"),ae.Constant(1))))}function euo(e,t,r,o){return ae.Not(Oi(e,t,r.not,o))}function iPt(e,t,r,o){return t.UseUnevaluated()?Zco(e,t,r,o):euo(e,t,r,o)}function eOe(e,t,r,o){let n=new wu;return!Jn(e,n,r.not,o)&&t.Merge([n])}function aPt(e,t,r,o,n,i){return eOe(e,t,n,i)||t.AddError({keyword:"not",schemaPath:r,instancePath:o,params:{}})}function tuo(e,t,r,o){return Qv(e,t,r.oneOf,o,ae.IsEqual(ae.Member("results","length"),ae.Constant(1)))}function ruo(e,t,r,o){let n=ae.ArrayLiteral(r.oneOf.map(a=>Oi(e,t,a,o))),i=ae.Call(ae.Member(n,"reduce"),[ae.ArrowFunction(["count","result"],ae.Ternary(ae.IsEqual("result",ae.Constant(!0)),ae.PrefixIncrement("count"),"count")),ae.Constant(0)]);return ae.IsEqual(i,ae.Constant(1))}function sPt(e,t,r,o){return t.UseUnevaluated()?tuo(e,t,r,o):ruo(e,t,r,o)}function cPt(e,t,r,o){let n=r.oneOf.reduce((i,a)=>{let s=new wu;return Jn(e,s,a,o)?[...i,s]:i},[]);return N.IsEqual(n.length,1)&&t.Merge(n)}function uPt(e,t,r,o,n,i){let a=[],s=[],c=n.oneOf.reduce((l,m,p)=>{let h=new kc,f=`${r}/oneOf/${p}`,g=ia(e,h,f,o,m,i);return g&&s.push(p),g||a.push(h),g?[...l,h]:l},[]),u=N.IsEqual(c.length,1)&&t.Merge(c);return!u&&N.IsEqual(s.length,0)&&a.forEach(l=>l.GetErrors().forEach(m=>t.AddError(m))),u||t.AddError({keyword:"oneOf",schemaPath:r,instancePath:o,params:{passingSchemas:s}})}function pPt(e,t,r,o){let n=Xl(N.IsString(r.pattern)?new RegExp(r.pattern,"u"):r.pattern);return ae.Call(ae.Member(n,"test"),[o])}function tOe(e,t,r,o){return(N.IsString(r.pattern)?new RegExp(r.pattern,"u"):r.pattern).test(o)}function lPt(e,t,r,o,n,i){return tOe(e,t,n,i)||t.AddError({keyword:"pattern",schemaPath:r,instancePath:o,params:{pattern:n.pattern}})}function dPt(e,t,r,o){return ae.ReduceAnd(N.Entries(r.patternProperties).map(([n,i])=>{let[a,s]=[Ra(),Ra()],c=Xl(new RegExp(n,"u")),u=ae.Not(ae.Call(ae.Member(c,"test"),[a])),l=Zd(e,t,i,s),m=t.AddKey(a),p=t.UseUnevaluated()?ae.Or(u,ae.And(l,m)):ae.Or(u,l);return ae.Every(ae.Entries(o),ae.Constant(0),[`[${a}, ${s}]`,"_"],p)}))}function mPt(e,t,r,o){return N.Every(N.Entries(r.patternProperties),0,([n,i])=>{let a=new RegExp(n,"u");return N.Every(N.Entries(o),0,([s,c])=>!a.test(s)||em(e,t,i,c)&&t.AddKey(s))})}function fPt(e,t,r,o,n,i){return N.EveryAll(N.Entries(n.patternProperties),0,([a,s])=>{let c=`${r}/patternProperties/${a}`,u=new RegExp(a,"u");return N.EveryAll(N.Entries(i),0,([l,m])=>{let p=`${o}/${l}`;return!u.test(l)||tm(e,t,c,p,s,m)&&t.AddKey(l)})})}function hPt(e,t,r,o){return ae.ReduceAnd(r.prefixItems.map((n,i)=>{let a=ae.IsLessEqualThan(ae.Member(o,"length"),ae.Constant(i)),s=Zd(e,t,n,`${o}[${i}]`),c=t.AddIndex(ae.Constant(i)),u=t.UseUnevaluated()?ae.And(s,c):s;return ae.Or(a,u)}))}function gPt(e,t,r,o){return N.IsEqual(o.length,0)||N.Every(r.prefixItems,0,(n,i)=>N.IsLessEqualThan(o.length,i)||em(e,t,n,o[i])&&t.AddIndex(i))}function _Pt(e,t,r,o,n,i){return N.IsEqual(i.length,0)||N.EveryAll(n.prefixItems,0,(a,s)=>{let c=`${r}/prefixItems/${s}`,u=`${o}/${s}`;return N.IsLessEqualThan(i.length,s)||tm(e,t,c,u,a,i[s])&&t.AddIndex(s)})}function UY(e,t){return e.includes(t)||mu.Get().exactOptionalPropertyTypes}function yPt(e,t){return ae.IsUndefined(ae.Member(e,t))}function rOe(e,t){return N.IsUndefined(e[t])}function xPt(e,t,r,o){let n=qg(r)?r.required:[],i=N.Entries(r.properties).map(([a,s])=>{let c=ae.Not(ae.HasPropertyKey(o,ae.Constant(a))),u=Zd(e,t,s,ae.Member(o,a)),l=t.AddKey(ae.Constant(a)),m=t.UseUnevaluated()?ae.And(u,l):u,p=n.includes(a)?m:ae.Or(c,m);return UY(n,a)?p:ae.Or(yPt(o,a),p)});return ae.ReduceAnd(i)}function bPt(e,t,r,o){let n=qg(r)?r.required:[];return N.Every(N.Entries(r.properties),0,([a,s])=>{let c=!N.HasPropertyKey(o,a)||em(e,t,s,o[a])&&t.AddKey(a);return UY(n,a)?c:rOe(o,a)||c})}function SPt(e,t,r,o,n,i){let a=qg(n)?n.required:[];return N.EveryAll(N.Entries(n.properties),0,([c,u])=>{let l=`${r}/properties/${c}`,m=`${o}/${c}`,p=()=>!N.HasPropertyKey(i,c)||tm(e,t,l,m,u,i[c])&&t.AddKey(c);return UY(a,c)?p():rOe(i,c)||p()})}function vPt(e,t,r,o){let[n,i]=[Ra(),Ra()];return ae.Every(ae.Keys(o),ae.Constant(0),[n,i],Oi(e,t,r.propertyNames,n))}function TPt(e,t,r,o){return N.Every(N.Keys(o),0,(n,i)=>Jn(e,t,r.propertyNames,n))}function EPt(e,t,r,o,n,i){let a=[];return N.EveryAll(N.Keys(i),0,(c,u)=>{let l=`${o}/${c}`,m=`${r}/propertyNames`,p=new kc,h=ia(e,p,m,l,n.propertyNames,c);return h||a.push(c),h})||t.AddError({keyword:"propertyNames",schemaPath:r,instancePath:o,params:{propertyNames:a}})}function RPt(e,t,r,o){let n=e.RecursiveRef(r)??!1;return M0(e,t,n,o)}function wPt(e,t,r,o){let n=e.RecursiveRef(r)??!1;return Vo(n)&&Jn(e,t,n,o)}function kPt(e,t,r,o,n,i){let a=e.RecursiveRef(n)??!1;return Vo(a)&&ia(e,t,"#",o,a,i)}function ouo(e,t,r,o){let n=ae.ArrowFunction(["context","value"],M0(e,t,r,"value")),i=ae.ArrowFunction(["context","value"],ae.Statements([ae.ConstDeclaration("nextContext",ae.New("CheckContext",[])),ae.ConstDeclaration("result",ae.Call(n,["nextContext","value"])),ae.If("result",t.Merge("[nextContext]")),ae.Return("result")]));return ae.Call(i,["context",o])}function nuo(e,t,r,o){return M0(e,t,r,o)}function IPt(e,t,r,o){let n=e.Ref(r)??!1;return t.UseUnevaluated()?ouo(e,t,n,o):nuo(e,t,n,o)}function CPt(e,t,r,o){let n=e.Ref(r)??!1,i=new wu,a=Vo(n)&&Jn(e,i,n,o);return a&&t.Merge([i]),a}function APt(e,t,r,o,n,i){let a=e.Ref(n)??!1,s=new kc,c=Vo(a)&&ia(e,s,"#",o,a,i);return c&&t.Merge([s]),c||s.GetErrors().forEach(u=>t.AddError(u)),c}function OPt(e,t,r,o){return ae.ReduceAnd(r.required.map(n=>ae.HasPropertyKey(o,ae.Constant(n))))}function PPt(e,t,r,o){return N.Every(r.required,0,n=>N.HasPropertyKey(o,n))}function NPt(e,t,r,o,n,i){let a=[];return N.EveryAll(n.required,0,c=>{let u=N.HasPropertyKey(i,c);return u||a.push(c),u})||t.AddError({keyword:"required",schemaPath:r,instancePath:o,params:{requiredProperties:a}})}function MPt(e,t,r,o){return N.IsEqual(r,"object")?ae.IsObjectNotArray(o):N.IsEqual(r,"array")?ae.IsArray(o):N.IsEqual(r,"boolean")?ae.IsBoolean(o):N.IsEqual(r,"integer")?ae.IsInteger(o):N.IsEqual(r,"number")?ae.IsNumber(o):N.IsEqual(r,"null")?ae.IsNull(o):N.IsEqual(r,"string")?ae.IsString(o):N.IsEqual(r,"asyncIterator")?ae.IsAsyncIterator(o):N.IsEqual(r,"bigint")?ae.IsBigInt(o):N.IsEqual(r,"constructor")?ae.IsConstructor(o):N.IsEqual(r,"function")?ae.IsFunction(o):N.IsEqual(r,"iterator")?ae.IsIterator(o):N.IsEqual(r,"symbol")?ae.IsSymbol(o):N.IsEqual(r,"undefined")?ae.IsUndefined(o):N.IsEqual(r,"void")?ae.IsUndefined(o):ae.Constant(!0)}function oOe(e,t,r,o,n){return N.IsEqual(r,"object")?N.IsObjectNotArray(n):N.IsEqual(r,"array")?N.IsArray(n):N.IsEqual(r,"boolean")?N.IsBoolean(n):N.IsEqual(r,"integer")?N.IsInteger(n):N.IsEqual(r,"number")?N.IsNumber(n):N.IsEqual(r,"null")?N.IsNull(n):N.IsEqual(r,"string")?N.IsString(n):N.IsEqual(r,"asyncIterator")?N.IsAsyncIterator(n):N.IsEqual(r,"bigint")?N.IsBigInt(n):N.IsEqual(r,"constructor")?N.IsConstructor(n):N.IsEqual(r,"function")?N.IsFunction(n):N.IsEqual(r,"iterator")?N.IsIterator(n):N.IsEqual(r,"symbol")?N.IsSymbol(n):N.IsEqual(r,"undefined")?N.IsUndefined(n):N.IsEqual(r,"void")?N.IsUndefined(n):!0}function iuo(e,t,r,o){return ae.ReduceOr(r.map(n=>MPt(e,t,n,o)))}function LPt(e,t,r,o,n){return r.some(i=>oOe(e,t,i,o,n))}function DPt(e,t,r,o){return N.IsArray(r.type)?iuo(e,t,r.type,o):MPt(e,t,r.type,o)}function $Pt(e,t,r,o){return N.IsArray(r.type)?LPt(e,t,r.type,r,o):oOe(e,t,r.type,r,o)}function zPt(e,t,r,o,n,i){return(N.IsArray(n.type)?LPt(e,t,n.type,n,i):oOe(e,t,n.type,n,i))||t.AddError({keyword:"type",schemaPath:r,instancePath:o,params:{type:n.type}})}function UPt(e,t,r,o){let[n,i]=[Ra(),Ra()],a=ae.Call(ae.Member("context","GetIndices"),[]),s=ae.Call(ae.Member("indices","has"),[n]),c=Oi(e,t,r.unevaluatedItems,i),u=ae.Call(ae.Member("context","AddIndex"),[n]),l=ae.Every(o,ae.Constant(0),[i,n],ae.And(ae.Or(s,c),u));return ae.Call(ae.ArrowFunction(["context"],ae.Statements([ae.ConstDeclaration("indices",a),ae.Return(l)])),["context"])}function FPt(e,t,r,o){let n=t.GetIndices();return N.Every(o,0,(i,a)=>(n.has(a)||Jn(e,t,r.unevaluatedItems,i))&&t.AddIndex(a))}function qPt(e,t,r,o,n,i){let a=t.GetIndices(),s=[];return N.EveryAll(i,0,(u,l)=>{let m=new kc,p=(a.has(l)||ia(e,m,r,o,n.unevaluatedItems,u))&&t.AddIndex(l);return p||s.push(l),p})||t.AddError({keyword:"unevaluatedItems",schemaPath:r,instancePath:o,params:{unevaluatedItems:s}})}function WPt(e,t,r,o){let[n,i]=[Ra(),Ra()],a=ae.Call(ae.Member("context","GetKeys"),[]),s=ae.Call(ae.Member("keys","has"),[n]),c=ae.Call(ae.Member("context","AddKey"),[n]),u=Oi(e,t,r.unevaluatedProperties,i),l=ae.Every(ae.Entries(o),ae.Constant(0),[`[${n}, ${i}]`,"_"],ae.Or(s,ae.And(u,c)));return ae.Call(ae.ArrowFunction(["context"],ae.Statements([ae.ConstDeclaration("keys",a),ae.Return(l)])),["context"])}function jPt(e,t,r,o){let n=t.GetKeys();return N.Every(N.Entries(o),0,([i,a])=>n.has(i)||Jn(e,t,r.unevaluatedProperties,a)&&t.AddKey(i))}function GPt(e,t,r,o,n,i){let a=t.GetKeys(),s=[];return N.EveryAll(N.Entries(i),0,([u,l])=>{let m=new kc,p=a.has(u)||ia(e,m,r,o,n.unevaluatedProperties,l)&&t.AddKey(u);return p||s.push(u),p})||t.AddError({keyword:"unevaluatedProperties",schemaPath:r,instancePath:o,params:{unevaluatedProperties:s}})}function nOe(e){return!N.IsEqual(e.uniqueItems,!1)}function JPt(e,t,r,o){if(!nOe(r))return ae.Constant(!0);let n=ae.Member(ae.New("Set",[ae.Call(ae.Member(o,"map"),[ae.Member("Hashing","Hash")])]),"size"),i=ae.Member(o,"length");return ae.IsEqual(n,i)}function VPt(e,t,r,o){if(!nOe(r))return!0;let n=new Set(o.map(Wm.Hash)).size,i=o.length;return N.IsEqual(n,i)}function BPt(e,t,r,o,n,i){if(!nOe(n))return!0;let a=new Set,s=i.reduce((u,l,m)=>{let p=Wm.Hash(l);return a.has(p)?[...u,m]:(a.add(p),u)},[]);return N.IsEqual(s.length,0)||t.AddError({keyword:"uniqueItems",schemaPath:r,instancePath:o,params:{duplicateItems:s}})}function v5(e,t){return b5(e)&&(N.IsArray(e.type)&&e.type.includes(t)||N.IsEqual(e.type,t))}function auo(e){return v5(e,"object")}function suo(e){return Xu(e)&&(Qd(e)||p5(e)||l5(e)||d5(e)||Yv(e)||Xv(e)||x5(e)||nk(e)||_5(e)||qg(e)||sk(e))}function cuo(e){return v5(e,"array")}function uuo(e){return Xu(e)&&(c5(e)||Hv(e)||C0(e)||h5(e)||rk(e)||O0(e)||P0(e)||N0(e)||ak(e)||hy(e))}function puo(e){return v5(e,"string")}function luo(e){return Xu(e)&&(ok(e)||g5(e)||tk(e)||ik(e))}function duo(e){return v5(e,"number")||v5(e,"bigint")}function muo(e){return Xu(e)&&(Fg(e)||f5(e)||m5(e)||Ug(e)||y5(e))}function Zd(e,t,r,o){return t.UseUnevaluated()?ae.And(ae.And(t.Push(),Oi(e,t,r,o)),t.Pop()):Oi(e,t,r,o)}function Oi(e,t,r,o){e.Push(r);let n=[];if(s5(r))return JAt(e,t,r,o);if(b5(r)&&n.push(DPt(e,t,r,o)),suo(r)){let a=[];qg(r)&&a.push(OPt(e,t,r,o)),Qd(r)&&a.push(DAt(e,t,r,o)),p5(r)&&a.push(QAt(e,t,r,o)),l5(r)&&a.push(tOt(e,t,r,o)),d5(r)&&a.push(nOt(e,t,r,o)),Xv(r)&&a.push(dPt(e,t,r,o)),Yv(r)&&a.push(xPt(e,t,r,o)),x5(r)&&a.push(vPt(e,t,r,o)),nk(r)&&a.push(tPt(e,t,r,o)),_5(r)&&a.push(GOt(e,t,r,o));let s=ae.ReduceAnd(a),c=ae.Or(ae.Not(ae.IsObjectNotArray(o)),s);n.push(auo(r)?s:c)}if(uuo(r)){let a=[];c5(r)&&a.push(NAt(e,t,r,o)),C0(r)&&a.push(XAt(e,t,r,o)),Hv(r)&&a.push(POt(e,t,r,o)),h5(r)&&a.push(DOt(e,t,r,o)),rk(r)&&a.push(FOt(e,t,r,o)),O0(r)&&a.push(BOt(e,t,r,o)),P0(r)&&a.push(YOt(e,t,r,o)),N0(r)&&a.push(hPt(e,t,r,o)),hy(r)&&a.push(JPt(e,t,r,o));let s=ae.ReduceAnd(a),c=ae.Or(ae.Not(ae.IsArray(o)),s);n.push(cuo(r)?s:c)}if(luo(r)){let a=[];g5(r)&&a.push(WOt(e,t,r,o)),ok(r)&&a.push(ZOt(e,t,r,o)),tk(r)&&a.push(kOt(e,t,r,o)),ik(r)&&a.push(pPt(e,t,r,o));let s=ae.ReduceAnd(a),c=ae.Or(ae.Not(ae.IsString(o)),s);n.push(puo(r)?s:c)}if(muo(r)){let a=[];m5(r)&&a.push(dOt(e,t,r,o)),Ug(r)&&a.push(fOt(e,t,r,o)),f5(r)&&a.push(zOt(e,t,r,o)),Fg(r)&&a.push(HOt(e,t,r,o)),y5(r)&&a.push(oPt(e,t,r,o));let s=ae.ReduceAnd(a),c=ae.Or(ae.Not(ae.Or(ae.IsNumber(o),ae.IsBigInt(o))),s);n.push(duo(r)?s:c)}fY(r)&&n.push(IPt(e,t,r,o)),mY(r)&&n.push(RPt(e,t,r,o)),iY(r)&&n.push(sOt(e,t,r,o)),eY(r)&&n.push(kAt(e,t,r,o)),nY(r)&&n.push(BAt(e,t,r,o)),sY(r)&&n.push(pOt(e,t,r,o)),cY(r)&&n.push(COt(e,t,r,o)),pY(r)&&n.push(iPt(e,t,r,o)),rY(r)&&n.push(UAt(e,t,r,o)),oY(r)&&n.push(WAt(e,t,r,o)),lY(r)&&n.push(sPt(e,t,r,o)),ak(r)&&n.push(ae.Or(ae.Not(ae.IsArray(o)),UPt(e,t,r,o))),sk(r)&&n.push(ae.Or(ae.Not(ae.IsObject(o)),WPt(e,t,r,o))),tY(r)&&n.push(AAt(e,t,r,o));let i=ae.ReduceAnd(n);return e.Pop(r),i}function em(e,t,r,o){return t.Push()&&Jn(e,t,r,o)&&t.Pop()}function Jn(e,t,r,o){e.Push(r);let n=s5(r)?PAe(e,t,r,o):(!b5(r)||$Pt(e,t,r,o))&&(!(N.IsObject(o)&&!N.IsArray(o))||(!qg(r)||PPt(e,t,r,o))&&(!Qd(r)||$At(e,t,r,o))&&(!p5(r)||ZAt(e,t,r,o))&&(!l5(r)||rOt(e,t,r,o))&&(!d5(r)||iOt(e,t,r,o))&&(!Xv(r)||mPt(e,t,r,o))&&(!Yv(r)||bPt(e,t,r,o))&&(!x5(r)||TPt(e,t,r,o))&&(!nk(r)||QAe(e,t,r,o))&&(!_5(r)||BAe(e,t,r,o)))&&(!N.IsArray(o)||(!c5(r)||MAt(e,t,r,o))&&(!C0(r)||MAe(e,t,r,o))&&(!Hv(r)||NOt(e,t,r,o))&&(!h5(r)||jAe(e,t,r,o))&&(!rk(r)||JAe(e,t,r,o))&&(!O0(r)||KAe(e,t,r,o))&&(!P0(r)||XAe(e,t,r,o))&&(!N0(r)||gPt(e,t,r,o))&&(!hy(r)||VPt(e,t,r,o)))&&(!N.IsString(o)||(!g5(r)||VAe(e,t,r,o))&&(!ok(r)||YAe(e,t,r,o))&&(!tk(r)||WAe(e,t,r,o))&&(!ik(r)||tOe(e,t,r,o)))&&(!(N.IsNumber(o)||N.IsBigInt(o))||(!m5(r)||$Ae(e,t,r,o))&&(!Ug(r)||zAe(e,t,r,o))&&(!f5(r)||GAe(e,t,r,o))&&(!Fg(r)||HAe(e,t,r,o))&&(!y5(r)||ZAe(e,t,r,o)))&&(!fY(r)||CPt(e,t,r,o))&&(!mY(r)||wPt(e,t,r,o))&&(!iY(r)||cOt(e,t,r,o))&&(!eY(r)||IAt(e,t,r,o))&&(!nY(r)||NAe(e,t,r,o))&&(!sY(r)||DAe(e,t,r,o))&&(!cY(r)||AOt(e,t,r,o))&&(!pY(r)||eOe(e,t,r,o))&&(!rY(r)||FAt(e,t,r,o))&&(!oY(r)||jAt(e,t,r,o))&&(!lY(r)||cPt(e,t,r,o))&&(!ak(r)||!N.IsArray(o)||FPt(e,t,r,o))&&(!sk(r)||!N.IsObject(o)||jPt(e,t,r,o))&&(!tY(r)||OAt(e,t,r,o));return e.Pop(r),n}function tm(e,t,r,o,n,i){return t.Push()&&ia(e,t,r,o,n,i)&&t.Pop()}function ia(e,t,r,o,n,i){e.Push(n);let a=s5(n)?VAt(e,t,r,o,n,i):!!(+(!b5(n)||zPt(e,t,r,o,n,i))&+(!(N.IsObject(i)&&!N.IsArray(i))||!!(+(!qg(n)||NPt(e,t,r,o,n,i))&+(!Qd(n)||zAt(e,t,r,o,n,i))&+(!p5(n)||eOt(e,t,r,o,n,i))&+(!l5(n)||oOt(e,t,r,o,n,i))&+(!d5(n)||aOt(e,t,r,o,n,i))&+(!Xv(n)||fPt(e,t,r,o,n,i))&+(!Yv(n)||SPt(e,t,r,o,n,i))&+(!x5(n)||EPt(e,t,r,o,n,i))&+(!nk(n)||rPt(e,t,r,o,n,i))&+(!_5(n)||JOt(e,t,r,o,n,i))))&+(!N.IsArray(i)||!!(+(!c5(n)||LAt(e,t,r,o,n,i))&+(!C0(n)||YAt(e,t,r,o,n,i))&+(!Hv(n)||MOt(e,t,r,o,n,i))&+(!h5(n)||$Ot(e,t,r,o,n,i))&+(!rk(n)||qOt(e,t,r,o,n,i))&+(!O0(n)||KOt(e,t,r,o,n,i))&+(!P0(n)||QOt(e,t,r,o,n,i))&+(!N0(n)||_Pt(e,t,r,o,n,i))&+(!hy(n)||BPt(e,t,r,o,n,i))))&+(!N.IsString(i)||!!(+(!g5(n)||jOt(e,t,r,o,n,i))&+(!ok(n)||ePt(e,t,r,o,n,i))&+(!tk(n)||IOt(e,t,r,o,n,i))&+(!ik(n)||lPt(e,t,r,o,n,i))))&+(!(N.IsNumber(i)||N.IsBigInt(i))||!!(+(!m5(n)||mOt(e,t,r,o,n,i))&+(!Ug(n)||hOt(e,t,r,o,n,i))&+(!f5(n)||UOt(e,t,r,o,n,i))&+(!Fg(n)||XOt(e,t,r,o,n,i))&+(!y5(n)||nPt(e,t,r,o,n,i))))&+(!fY(n)||APt(e,t,r,o,n,i))&+(!mY(n)||kPt(e,t,r,o,n,i))&+(!iY(n)||uOt(e,t,r,o,n,i))&+(!eY(n)||CAt(e,t,r,o,n,i))&+(!nY(n)||KAt(e,t,r,o,n,i))&+(!sY(n)||lOt(e,t,r,o,n,i))&+(!cY(n)||OOt(e,t,r,o,n,i))&+(!pY(n)||aPt(e,t,r,o,n,i))&+(!rY(n)||qAt(e,t,r,o,n,i))&+(!oY(n)||GAt(e,t,r,o,n,i))&+(!lY(n)||uPt(e,t,r,o,n,i))&+(!ak(n)||!N.IsArray(i)||qPt(e,t,r,o,n,i))&+(!sk(n)||!N.IsObject(i)||GPt(e,t,r,o,n,i)))&&(!tY(n)||PAt(e,t,r,o,n,i));return e.Pop(n),a}var T5=new Map;function fuo(e,t,r,o){return e.UseUnevaluated()?ae.Call(`check_${r}`,["context",o]):ae.Call(`check_${r}`,[o])}function huo(e,t,r,o){let n=Oi(e,t,r,"value");return t.UseUnevaluated()?ae.ConstDeclaration(`check_${o}`,ae.ArrowFunction(["context","value"],n)):ae.ConstDeclaration(`check_${o}`,ae.ArrowFunction(["value"],n))}function KPt(){T5.clear()}function HPt(){return[...T5.values()]}function M0(e,t,r,o){let n=Xu(r)?Wm.Hash({__baseURL:e.BaseURL().href,...r}):Wm.Hash(r),i=fuo(t,r,n,o);return T5.has(n)||(T5.set(n,""),T5.set(n,huo(e,t,r,n))),i}var Zv={};to(Zv,{DynamicRef:()=>Auo,Ref:()=>aOe});var Sp={};to(Sp,{Delete:()=>Tuo,Get:()=>Suo,Has:()=>buo,Indices:()=>E5,Set:()=>vuo});function XPt(e){if(e.length===0)throw Error("Cannot set root")}function YPt(e){if(!N.IsObject(e))throw Error("Cannot set value")}function guo(e){if(N.IsUnsafePropertyKey(e))throw Error("Pointer contains unsafe property key")}function QPt(e){for(let t of e)guo(t)}function _uo(e){return/^(0|[1-9]\d*)$/.test(e)}function ZPt(e){return[e.slice(0,e.length-1),e.slice(e.length-1)[0]]}function yuo(e,t){return N.IsObject(t)&&N.HasPropertyKey(t,e)}function xuo(e,t){return N.IsObject(t)&&!N.IsUnsafePropertyKey(e)?t[e]:void 0}function iOe(e,t){return e.reduce((r,o)=>xuo(o,r),t)}function E5(e){if(N.IsEqual(e.length,0))return[];let t=e.split("/").map(r=>r.replace(/~1/g,"/").replace(/~0/g,"~"));return t.length>0&&t[0]===""?t.slice(1):t}function buo(e,t){let r=e;return E5(t).every(o=>yuo(o,r)?(r=r[o],!0):!1)}function Suo(e,t){let r=E5(t);return iOe(r,e)}function vuo(e,t,r){let o=E5(t);XPt(o),QPt(o);let[n,i]=ZPt(o),a=iOe(n,e);return YPt(a),a[i]=r,e}function Tuo(e,t){let r=E5(t);XPt(r),QPt(r);let[o,n]=ZPt(r),i=iOe(o,e);return YPt(i),N.IsArray(i)&&_uo(n)?i.splice(+n,1):delete i[n],e}function Euo(e,t,r){if(e.$id===r.hash)return e;let o=new URL(e.$id,t.href),n=new URL(r.href,t.href);if(N.IsEqual(o.pathname,n.pathname))return r.hash.startsWith("#")?eNt(e,t,r):e}function Ruo(e,t,r){let o=new URL(`#${e.$anchor}`,t.href),n=new URL(r.href,t.href);return N.IsEqual(o.href,n.href)?e:void 0}function wuo(e,t,r){let o=new URL(`#${e.$dynamicAnchor}`,t.href),n=new URL(r.href,t.href);return N.IsEqual(o.href,n.href)?e:void 0}function eNt(e,t,r){if(r.href.endsWith("#"))return e;if(!r.hash.startsWith("#"))return;let o=decodeURIComponent(r.hash.slice(1));if(o.startsWith("/"))return Sp.Get(e,o)}function kuo(e,t,r){if(A0(e)){let o=Euo(e,t,r);if(!N.IsUndefined(o))return o}if(u5(e)){let o=Ruo(e,t,r);if(!N.IsUndefined(o))return o}if(Kv(e)){let o=wuo(e,t,r);if(!N.IsUndefined(o))return o}return eNt(e,t,r)}function Iuo(e,t,r){return e.reduce((o,n)=>{let i=sOe(n,t,r);return N.IsUndefined(i)?o:i},void 0)}function Cuo(e,t,r){return N.Keys(e).reduce((o,n)=>{let i=sOe(e[n],t,r);return N.IsUndefined(i)?o:i},void 0)}function sOe(e,t,r){let o=Xu(e)&&A0(e)?new URL(e.$id,t.href):t;if(Xu(e)){let n=kuo(e,o,r);if(!N.IsUndefined(n))return n}if(N.IsArray(e))return Iuo(e,o,r);if(N.IsObject(e))return Cuo(e,o,r)}function aOe(e,t){let r=new URL("http://unknown/"),o=A0(e)?new URL(e.$id,r.href):r,n=new URL(t,o.href);return sOe(e,o,n)}function Auo(e,t,r,o){let n=r.$dynamicRef.startsWith("#")?aOe(t,r.$dynamicRef):aOe(e,r.$dynamicRef);return N.IsUndefined(n)?void 0:!Xu(n)||!Kv(n)||new URL(r.$dynamicRef,"http://unknown/").hash.startsWith("#/")?n:o.find(s=>s.$dynamicAnchor===n.$dynamicAnchor)??n}var W1=function(e,t,r,o){if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?o:r==="a"?o.call(e):o?o.value:t.get(e)},eT,tNt,rNt,oNt,nNt,L0=class{constructor(t,r){eT.add(this),this.context=t,this.schema=r,this.ids=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[]}BaseURL(){return this.ids.reduce((t,r)=>new URL(r.$id,t),new URL("http://unknown"))}Base(){return this.ids[this.ids.length-1]??this.schema}Push(t){Xu(t)&&(A0(t)&&(this.ids.push(t),W1(this,eT,"m",tNt).call(this,t)),u5(t)&&this.anchors.push(t),dY(t)&&this.recursiveAnchors.push(t),Kv(t)&&this.dynamicAnchors.push(t))}Pop(t){Xu(t)&&(A0(t)&&(this.ids.pop(),W1(this,eT,"m",rNt).call(this,t)),u5(t)&&this.anchors.pop(),dY(t)&&this.recursiveAnchors.pop(),Kv(t)&&this.dynamicAnchors.pop())}Ref(t){return W1(this,eT,"m",oNt).call(this,t)??W1(this,eT,"m",nNt).call(this,t)}RecursiveRef(t){return dY(this.Base())?Zv.Ref(this.recursiveAnchors[0],t.$recursiveRef):Zv.Ref(this.Base(),t.$recursiveRef)}DynamicRef(t){let r=this.schema;return Zv.DynamicRef(r,this.Base(),t,this.dynamicAnchors)}};eT=new WeakSet,tNt=function e(t,r=!0){if(!Xu(t))return;let o=t;if(!(!r&&A0(o))){!r&&Kv(o)&&this.dynamicAnchors.push(o);for(let n of N.Keys(o))W1(this,eT,"m",e).call(this,o[n],!1)}},rNt=function e(t,r=!0){if(!Xu(t))return;let o=t;if(!(!r&&A0(o))){!r&&Kv(o)&&this.dynamicAnchors.pop();for(let n of N.Keys(o))W1(this,eT,"m",e).call(this,o[n],!1)}},oNt=function(t){return N.HasPropertyKey(this.context,t.$ref)?this.context[t.$ref]:void 0},nNt=function(t){let r=this.schema;return t.$ref.startsWith("#")?Zv.Ref(this.Base(),t.$ref):Zv.Ref(r,t.$ref)};function Ouo(e){let t=e.Functions().join(`;
|
|
1013
1013
|
`),r=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${t}; return (value) => { ${r.join("; ")} }`}function Puo(e,t){return YC.Evaluate("CheckContext","Guard","Format","Hashing",e.External().identifier,t)(wu,N,uk,Wm,e.External().variables)}function Nuo(e){let t=new L0(e.Context(),e.Schema()),r=new wu;return o=>Jn(t,r,e.Schema(),o)}function Muo(e,t){return YC.CanEvaluate()?Puo(e,t):Nuo(e)}var R5=class{constructor(t,r,o){this.isAccelerated=t,this.code=r,this.check=o}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(t){return this.check(t)}},w5=class{constructor(t,r,o,n,i,a){this.context=t,this.schema=r,this.external=o,this.functions=n,this.entry=i,this.useUnevaluated=a}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let t=Ouo(this),r=Muo(this,t);return new R5(YC.CanEvaluate(),t,r)}};function FY(...e){let[t,r]=un.Match(e,{2:(c,u)=>[c,u],1:c=>[{},c]});RAt(),KPt();let o=new L0(t,r),n=new _Y(EAt(t,r)),i=M0(o,n,r,"value"),a=HPt(),s=wAt();return new w5(t,r,s,a,i,n.UseUnevaluated())}function qY(...e){let[t,r,o]=un.Match(e,{3:(l,m,p)=>[l,m,p],2:(l,m)=>[{},l,m]}),n=mu.Get(),i=tVe(),a=[],s=new L0(t,r),c=new S5(l=>{if(!N.IsGreaterEqualThan(a.length,n.maxErrors))return a.push({...l,message:i(l)})});return[ia(s,c,"#","",r,o),a]}function uOe(...e){let[t,r,o]=un.Match(e,{3:(a,s,c)=>[a,s,c],2:(a,s)=>[{},a,s]}),n=new L0(t,r),i=new wu;return Jn(n,i,r,o)}function Sn(...e){let[t,r,o]=un.Match(e,{3:(n,i,a)=>[n,i,a],2:(n,i)=>[{},n,i]});return uOe(t,r,o)}function rm(...e){let[t,r,o]=un.Match(e,{3:(a,s,c)=>[a,s,c],2:(a,s)=>[{},a,s]}),[n,i]=qY(t,r,o);return i}var D0=class extends Error{constructor(t,r,o){super(t),Object.defineProperty(this,"cause",{value:{source:t,errors:o,value:r},writable:!1,configurable:!1,enumerable:!1})}};function WY(...e){let[t,r,o]=un.Match(e,{3:(i,a,s)=>[i,a,s],2:(i,a)=>[{},i,a]});if(!Sn(t,r,o))throw new D0("Assert",o,rm(t,r,o))}function iNt(e,t,r){return N.IsArray(r)?r.map(o=>Ic(e,t.items,o)):r}function aNt(e,t,r){return t.Clean(r)}function sNt(e,t,r){return Ic({...e,...t.$defs},Uu(t.$ref),r)}function $uo(e,t){let r=N.HasPropertyKey(t,"unevaluatedProperties")?{additionalProperties:t.unevaluatedProperties}:{},o=Cd(e,t),n=rg(o);return Po(n)?Wde(n,r):n}function cNt(e,t,r){let o=$uo(e,t);return Ic(e,o,r)}function jY(e){return N.HasPropertyKey(e,"additionalProperties")?e.additionalProperties:void 0}function uNt(e,t,r){if(!N.IsObject(r)||N.IsArray(r))return r;let o=jY(t);for(let n of N.Keys(r)){if(N.HasPropertyKey(t.properties,n)){r[n]=Ic(e,t.properties[n],r[n]);continue}if(N.IsBoolean(o)&&N.IsEqual(o,!0)||Bi(o)&&Sn(e,o,r[n])){r[n]=Ic(e,o,r[n]);continue}delete r[n]}return r}function pNt(e,t,r){if(!N.IsObject(r))return r;let o=jY(t),[n,i]=[new RegExp(Il(t)),bc(t)];for(let a of N.Keys(r)){if(n.test(a)){r[a]=Ic(e,i,r[a]);continue}if(N.IsBoolean(o)&&N.IsEqual(o,!0)||Bi(o)&&Sn(e,o,r[a])){r[a]=Ic(e,o,r[a]);continue}delete r[a]}return r}function lNt(e,t,r){return N.HasPropertyKey(e,t.$ref)?Ic(e,e[t.$ref],r):r}function dNt(e,t,r){if(!N.IsArray(r))return r;let o=Math.min(r.length,t.items.length);for(let n=0;n<o;n++)r[n]=Ic(e,t.items[n],r[n]);return N.IsGreaterThan(r.length,o)?r.slice(0,o):r}function zuo(e){let t={};for(let r of N.Keys(e))N.IsUnsafePropertyKey(r)||(t[r]=Xn(e[r]));for(let r of N.Symbols(e))t[r]=Xn(e[r]);return t}function Uuo(e){return N.IsClassInstance(e)?e:zuo(e)}function Fuo(e){return e.map(t=>Xn(t))}function quo(e){return e.slice()}function Wuo(e){return new Map(Xn([...e.entries()]))}function juo(e){return new Set(Xn([...e.values()]))}function Xn(e){return Sa.IsTypeArray(e)?quo(e):Sa.IsMap(e)?Wuo(e):Sa.IsSet(e)?juo(e):N.IsArray(e)?Fuo(e):N.IsObject(e)?Uuo(e):e}function mNt(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))}function k5(e,t=1){return e.sort((r,o)=>{let n=vR(r,o);return(N.IsEqual(n,"disjoint")?mNt(r,o):N.IsEqual(n,"right-inside")?1:N.IsEqual(n,"left-inside")?-1:mNt(r,o))*t})}function fNt(e,t,r){for(let o of k5(t.anyOf)){let n=Ic(e,o,Xn(r));if(Sn(e,o,n))return n}return r}function Ic(e,t,r){return jn(t)?iNt(e,t,r):Ed(t)?aNt(e,t,r):oa(t)?sNt(e,t,r):Ao(t)?cNt(e,t,r):Po(t)?uNt(e,t,r):za(t)?pNt(e,t,r):bi(t)?lNt(e,t,r):bn(t)?dNt(e,t,r):zr(t)?fNt(e,t,r):r}function om(...e){let[t,r,o]=un.Match(e,{3:(n,i,a)=>[n,i,a],2:(n,i)=>[{},n,i]});return Ic(t,r,o)}var ni={};to(ni,{Fail:()=>lk,IsOk:()=>pOe,Ok:()=>yo,TryArray:()=>Guo,TryBigInt:()=>lOe,TryBoolean:()=>rpo,TryNull:()=>spo,TryNumber:()=>lpo,TryString:()=>dpo,TryUndefined:()=>_po});function pOe(e){return N.IsObject(e)&&N.HasPropertyKey(e,"value")}function yo(e){return{value:e}}function lk(){}function Guo(e){return N.IsArray(e)?yo(e):yo([e])}function Juo(e){return N.IsEqual(e,!0)?yo(BigInt(1)):yo(BigInt(0))}var Vuo=/^-?(0|[1-9]\d*)n$/,Buo=/^-?(0|[1-9]\d*)\.\d+$/,Kuo=/^-?(0|[1-9]\d*)$/;function Huo(e){return Vuo.test(e)}function Xuo(e){return Buo.test(e)}function Yuo(e){return Kuo.test(e)}function Quo(e){let t=e.toLowerCase();return Huo(e)?yo(BigInt(e.slice(0,e.length-1))):Xuo(e)?yo(BigInt(e.split(".")[0])):Yuo(e)?yo(BigInt(e)):N.IsEqual(t,"false")?yo(BigInt(0)):N.IsEqual(t,"true")?yo(BigInt(1)):void 0}function lOe(e){return N.IsBigInt(e)?yo(e):N.IsBoolean(e)?Juo(e):N.IsNumber(e)?yo(BigInt(Math.trunc(e))):N.IsNull(e)?yo(BigInt(0)):N.IsString(e)?Quo(e):N.IsUndefined(e)?yo(BigInt(0)):void 0}function Zuo(e){return N.IsEqual(e,BigInt(0))?yo(!1):N.IsEqual(e,BigInt(1))?yo(!0):void 0}function epo(e){return N.IsEqual(e,0)?yo(!1):N.IsEqual(e,1)?yo(!0):void 0}function tpo(e){return N.IsEqual(e.toLowerCase(),"false")?yo(!1):N.IsEqual(e.toLowerCase(),"true")?yo(!0):N.IsEqual(e,"0")?yo(!1):N.IsEqual(e,"1")?yo(!0):void 0}function rpo(e){return N.IsBigInt(e)?Zuo(e):N.IsBoolean(e)?yo(e):N.IsNumber(e)?epo(e):N.IsNull(e)?yo(!1):N.IsString(e)?tpo(e):N.IsUndefined(e)?yo(!1):void 0}function opo(e){return N.IsEqual(e,BigInt(0))?yo(null):void 0}function npo(e){return N.IsEqual(e,!1)?yo(null):void 0}function ipo(e){return N.IsEqual(e,0)?yo(null):void 0}function apo(e){let t=e.toLowerCase();return N.IsEqual(t,"undefined")||N.IsEqual(t,"null")||N.IsEqual(e,"")||N.IsEqual(e,"0")?yo(null):void 0}function spo(e){return N.IsBigInt(e)?opo(e):N.IsBoolean(e)?npo(e):N.IsNumber(e)?ipo(e):N.IsNull(e)?yo(null):N.IsString(e)?apo(e):N.IsUndefined(e)?yo(null):void 0}var hNt=BigInt(Number.MAX_SAFE_INTEGER),gNt=BigInt(Number.MIN_SAFE_INTEGER);function cpo(e){return e<=hNt&&e>=gNt?yo(Number(e)):void 0}function upo(e){return yo(e?1:0)}function ppo(e){let t=+e;if(N.IsNumber(t))return yo(t);let r=e.toLowerCase();if(N.IsEqual(r,"false"))return yo(0);if(N.IsEqual(r,"true"))return yo(1);let o=lOe(e);return pOe(o)?o.value<=hNt&&o.value>=gNt?yo(Number(o.value)):void 0:void 0}function lpo(e){return N.IsBigInt(e)?cpo(e):N.IsBoolean(e)?upo(e):N.IsNumber(e)?yo(e):N.IsNull(e)?yo(0):N.IsString(e)?ppo(e):N.IsUndefined(e)?yo(0):void 0}function dpo(e){return N.IsBigInt(e)?yo(e.toString()):N.IsBoolean(e)?yo(e.toString()):N.IsNumber(e)?yo(e.toString()):N.IsNull(e)?yo("null"):N.IsString(e)?yo(e):N.IsUndefined(e)?yo(""):void 0}function mpo(e){return N.IsEqual(e,BigInt(0))?yo(void 0):void 0}function fpo(e){return N.IsEqual(e,!1)?yo(void 0):void 0}function hpo(e){return N.IsEqual(e,0)?yo(void 0):void 0}function gpo(e){let t=e.toLowerCase();return N.IsEqual(t,"undefined")||N.IsEqual(t,"null")||N.IsEqual(e,"")||N.IsEqual(e,"0")?yo(void 0):void 0}function _po(e){return N.IsBigInt(e)?mpo(e):N.IsBoolean(e)?fpo(e):N.IsNumber(e)?hpo(e):N.IsNull(e)?yo(void 0):N.IsString(e)?gpo(e):N.IsUndefined(e)?yo(e):void 0}function _Nt(e,t,r){return ni.TryArray(r).value.map(n=>zs(e,t.items,n))}function yNt(e,t,r){return t.Convert(r)}function xNt(e,t,r){let o=ni.TryBigInt(r);return ni.IsOk(o)?o.value:r}function bNt(e,t,r){let o=ni.TryBoolean(r);return ni.IsOk(o)?o.value:r}function SNt(e,t,r){return zs({...e,...t.$defs},Uu(t.$ref),r)}function GY(e,t,r){if(t.anyOf.some(a=>Sn(e,a,r)))return r;let i=t.anyOf.map(a=>zs(e,a,Xn(r))).find(a=>Sn(e,t,a));return N.IsUndefined(i)?r:i}function vNt(e,t,r){let o=eS(t);return GY(e,o,r)}function TNt(e,t,r){let o=ni.TryNumber(r);return ni.IsOk(o)?Math.trunc(o.value):r}function ENt(e,t,r){let o=Cd(e,t),n=rg(o);return zs(e,n,r)}function ypo(e,t,r){let o=ni.TryBigInt(r);return ni.IsOk(o)&&N.IsEqual(t.const,o.value)?o.value:r}function xpo(e,t,r){let o=ni.TryBoolean(r);return ni.IsOk(o)&&N.IsEqual(t.const,o.value)?o.value:r}function bpo(e,t,r){let o=ni.TryNumber(r);return ni.IsOk(o)&&N.IsEqual(t.const,o.value)?o.value:r}function Spo(e,t,r){let o=ni.TryString(r);return ni.IsOk(o)&&N.IsEqual(t.const,o.value)?o.value:r}function RNt(e,t,r){return N.IsEqual(t.const,r)?r:iVe(t)?ypo(e,t,r):aVe(t)?xpo(e,t,r):iJ(t)?bpo(e,t,r):aJ(t)?Spo(e,t,r):mi()}function wNt(e,t,r){let o=ni.TryNull(r);return ni.IsOk(o)?o.value:r}function kNt(e,t,r){let o=ni.TryNumber(r);return ni.IsOk(o)?o.value:r}function JY(e,t,r,o){let n=N.Keys(o);for(let[i,a]of t)for(let s of n)i.test(s)||(o[s]=zs(e,r,o[s]));return o}function I5(e,t,r){return gc(e)&&N.IsUndefined(r[t])}function vpo(e,t,r){let o=N.EntriesRegExp(t.properties),n=N.Keys(r);for(let[i,a]of o)for(let s of n)!i.test(s)||I5(a,s,r)||(r[s]=zs(e,a,r[s]));return N.HasPropertyKey(t,"additionalProperties")&&N.IsObject(t.additionalProperties)?JY(e,o,t.additionalProperties,r):r}function INt(e,t,r){return N.IsObjectNotArray(r)?vpo(e,t,r):r}function Tpo(e,t,r){let o=N.EntriesRegExp(t.patternProperties),n=N.Keys(r);for(let[i,a]of o)for(let s of n)i.test(s)&&(r[s]=zs(e,a,r[s]));return N.HasPropertyKey(t,"additionalProperties")&&N.IsObject(t.additionalProperties)?JY(e,o,t.additionalProperties,r):r}function CNt(e,t,r){return N.IsObjectNotArray(r)?Tpo(e,t,r):r}function ANt(e,t,r){return N.HasPropertyKey(e,t.$ref)?zs(e,e[t.$ref],r):r}function ONt(e,t,r){let o=ni.TryString(r);return ni.IsOk(o)?o.value:r}function PNt(e,t,r){let o=yc(t.pattern);return zs(e,o,r)}function NNt(e,t,r){if(!N.IsArray(r))return r;for(let o=0;o<Math.min(t.items.length,r.length);o++)r[o]=zs(e,t.items[o],r[o]);return r}function MNt(e,t,r){let o=ni.TryUndefined(r);return ni.IsOk(o)?o.value:r}function LNt(e,t,r){let o=ni.TryUndefined(r);return ni.IsOk(o)?void 0:r}function zs(e,t,r){return jn(t)?_Nt(e,t,r):Ed(t)?yNt(e,t,r):wd(t)?xNt(e,t,r):qp(t)?bNt(e,t,r):oa(t)?SNt(e,t,r):Ss(t)?vNt(e,t,r):hu(t)?TNt(e,t,r):Ao(t)?ENt(e,t,r):Tn(t)?RNt(e,t,r):Ox(t)?wNt(e,t,r):Ha(t)?kNt(e,t,r):Po(t)?INt(e,t,r):za(t)?CNt(e,t,r):bi(t)?ANt(e,t,r):_c(t)?ONt(e,t,r):Da(t)?PNt(e,t,r):bn(t)?NNt(e,t,r):Px(t)?MNt(e,t,r):zr(t)?GY(e,t,r):kd(t)?LNt(e,t,r):r}function Pf(...e){let[t,r,o]=un.Match(e,{3:(n,i,a)=>[n,i,a],2:(n,i)=>[{},n,i]});return zs(t,r,o)}function DNt(e,t,r){if(!N.IsArray(r))return r;for(let o=0;o<r.length;o++)r[o]=sc(e,t.items,r[o]);return r}function $Nt(e,t,r){return t.Default(r)}function zNt(e,t,r){return sc({...e,...t.$defs},Uu(t.$ref),r)}function UNt(e,t){return N.IsUndefined(t)?N.IsFunction(e.default)?e.default():Xn(e.default):t}function FNt(e,t,r){let o=Cd(e,t),n=rg(o);return sc(e,n,r)}function qNt(e,t,r){if(!N.IsObject(r))return r;let o=N.Keys(t.properties);for(let n of o){let i=sc(e,t.properties[n],r[n]);N.IsUndefined(i)&&(gc(t.properties[n])||!N.HasPropertyKey(t.properties[n],"default"))||(r[n]=sc(e,t.properties[n],r[n]))}if(!Qd(t)||N.IsBoolean(t.additionalProperties))return r;for(let n of N.Keys(r))o.includes(n)||(r[n]=sc(e,t.additionalProperties,r[n]));return r}function WNt(e,t,r){if(!N.IsObject(r))return r;let[o,n]=[new RegExp(Il(t)),bc(t)];for(let i of N.Keys(r))o.test(i)&&Hl(n)&&(r[i]=sc(e,n,r[i]));if(!Qd(t))return r;for(let i of N.Keys(r))o.test(i)||(r[i]=sc(e,t.additionalProperties,r[i]));return r}function jNt(e,t,r){return N.HasPropertyKey(e,t.$ref)?sc(e,e[t.$ref],r):r}function GNt(e,t,r){if(!N.IsArray(r))return r;let[o,n]=[t.items,Math.max(t.items.length,r.length)];for(let i=0;i<n;i++)i<o.length&&(r[i]=sc(e,o[i],r[i]));return r}function JNt(e,t,r){for(let o of t.anyOf){let n=sc(e,o,Xn(r));if(Sn(e,o,n))return n}return r}function sc(e,t,r){let o=Hl(t)?UNt(t,r):r;return jn(t)?DNt(e,t,o):Ed(t)?$Nt(e,t,o):oa(t)?zNt(e,t,o):Ao(t)?FNt(e,t,o):Po(t)?qNt(e,t,o):za(t)?WNt(e,t,o):bi(t)?jNt(e,t,o):bn(t)?GNt(e,t,o):zr(t)?JNt(e,t,o):o}function gy(...e){let[t,r,o]=un.Match(e,{3:(n,i,a)=>[n,i,a],2:(n,i)=>[{},n,i]});return sc(t,r,o)}function j1(e){return(...t)=>{let[r,o,n]=un.Match(t,{3:(i,a,s)=>[i,a,s],2:(i,a)=>[{},i,a]});return e.reduce((i,a)=>a(r,o,i),n)}}function Epo(e,t,r){return t["~codec"].decode(r)}function Rpo(e,t,r){return t["~codec"].encode(r)}function ga(e,t,r,o){return Rd(r)?N.IsEqual(e,"Decode")?Epo(t,r,o):Rpo(t,r,o):o}function wpo(e,t,r,o){if(!N.IsArray(o))return mi();for(let n=0;n<o.length;n++)o[n]=wa(e,t,r.items,o[n]);return ga(e,t,r,o)}function kpo(e,t,r,o){let n=ga(e,t,r,o);if(!N.IsArray(n))return n;for(let i=0;i<n.length;i++)n[i]=wa(e,t,r.items,n[i]);return n}function VNt(e,t,r,o){return N.IsEqual(e,"Decode")?wpo(e,t,r,o):kpo(e,t,r,o)}function BNt(e,t,r,o){return o=wa(e,{...t,...r.$defs},Uu(r.$ref),o),ga(e,t,r,o)}function KNt(e){return e.reduce((t,r)=>({...t,...r}),{})}function HNt(e,t){for(let r of t)if(!N.IsDeepEqual(e,r))return r;return e}function Ipo(e,t,r,o){if(N.IsEqual(r.allOf.length,0))return ga(e,t,r,o);let n=r.allOf.map(s=>wa(e,t,s,om(s,Xn(o)))),a=n.every(s=>N.IsObject(s))?KNt(n):HNt(o,n);return ga(e,t,r,a)}function Cpo(e,t,r,o){if(N.IsEqual(r.allOf.length,0))return ga(e,t,r,o);let n=ga(e,t,r,o),i=r.allOf.map(s=>wa(e,t,s,om(s,Xn(n))));return i.every(s=>N.IsObject(s))?KNt(i):HNt(n,i)}function XNt(e,t,r,o){return N.IsEqual(e,"Decode")?Ipo(e,t,r,o):Cpo(e,t,r,o)}function Apo(e,t,r,o){if(!N.IsObjectNotArray(o))return mi();for(let n of N.Keys(r.properties))!N.HasPropertyKey(o,n)||I5(r.properties[n],n,o)||(o[n]=wa(e,t,r.properties[n],o[n]));return ga(e,t,r,o)}function Opo(e,t,r,o){let n=ga(e,t,r,o);if(!N.IsObjectNotArray(n))return n;for(let i of N.Keys(r.properties))!N.HasPropertyKey(n,i)||I5(r.properties[i],i,n)||(n[i]=wa(e,t,r.properties[i],n[i]));return n}function YNt(e,t,r,o){return N.IsEqual(e,"Decode")?Apo(e,t,r,o):Opo(e,t,r,o)}function Ppo(e,t,r,o){if(!N.IsObjectNotArray(o))return mi();let n=new RegExp(Il(r));for(let i of N.Keys(o))n.test(i)||mi(),o[i]=wa(e,t,bc(r),o[i]);return ga(e,t,r,o)}function Npo(e,t,r,o){let n=ga(e,t,r,o);if(!N.IsObjectNotArray(n))return n;let i=new RegExp(Il(r));for(let a of N.Keys(n))i.test(a)&&(n[a]=wa(e,t,bc(r),n[a]));return n}function QNt(e,t,r,o){return N.IsEqual(e,"Decode")?Ppo(e,t,r,o):Npo(e,t,r,o)}function ZNt(e,t,r,o){return N.HasPropertyKey(t,r.$ref)?wa(e,t,t[r.$ref],o):o}function e1t(e,t,r,o){return N.IsEqual(e,"Decode")?ga(e,t,r,ZNt(e,t,r,o)):ZNt(e,t,r,ga(e,t,r,o))}function Mpo(e,t,r,o){if(!N.IsArray(o))return mi();for(let n=0;n<Math.min(r.items.length,o.length);n++)o[n]=wa(e,t,r.items[n],o[n]);return ga(e,t,r,o)}function Lpo(e,t,r,o){let n=ga(e,t,r,o);if(!N.IsArray(n))return o;for(let i=0;i<Math.min(r.items.length,n.length);i++)n[i]=wa(e,t,r.items[i],n[i]);return n}function t1t(e,t,r,o){return N.IsEqual(e,"Decode")?Mpo(e,t,r,o):Lpo(e,t,r,o)}function Dpo(e,t,r,o){for(let n of k5(r.anyOf,1)){if(!Sn(t,n,o))continue;let i=wa(e,t,n,o);return ga(e,t,r,i)}return o}function $po(e,t,r,o){let n=ga(e,t,r,o);for(let i of k5(r.anyOf,-1)){let a=wa(e,t,i,Xn(n));if(Sn(t,i,a))return a}return n}function r1t(e,t,r,o){return N.IsEqual(e,"Decode")?Dpo(e,t,r,o):$po(e,t,r,o)}function wa(e,t,r,o){return jn(r)?VNt(e,t,r,o):oa(r)?BNt(e,t,r,o):Ao(r)?XNt(e,t,r,o):Po(r)?YNt(e,t,r,o):za(r)?QNt(e,t,r,o):bi(r)?e1t(e,t,r,o):bn(r)?t1t(e,t,r,o):zr(r)?r1t(e,t,r,o):ga(e,t,r,o)}var dOe=class extends D0{constructor(t,r){super("Decode",t,r)}};function zpo(e,t,r){if(!Sn(e,t,r))throw new dOe(r,rm(e,t,r));return r}function Upo(e,t,r){return wa("Decode",e,t,r)}var Fpo=j1([(e,t,r)=>Xn(r),(e,t,r)=>gy(e,t,r),(e,t,r)=>Pf(e,t,r),(e,t,r)=>om(e,t,r),(e,t,r)=>zpo(e,t,r),(e,t,r)=>Upo(e,t,r)]);function VY(...e){let[t,r,o]=un.Match(e,{3:(n,i,a)=>[n,i,a],2:(n,i)=>[{},n,i]});return Fpo(t,r,o)}var mOe=class extends D0{constructor(t,r){super("Encode",t,r)}};function qpo(e,t,r){if(!Sn(e,t,r))throw new mOe(r,rm(e,t,r));return r}function Wpo(e,t,r){return wa("Encode",e,t,r)}var jpo=j1([(e,t,r)=>Xn(r),(e,t,r)=>Wpo(e,t,r),(e,t,r)=>gy(e,t,r),(e,t,r)=>Pf(e,t,r),(e,t,r)=>om(e,t,r),(e,t,r)=>qpo(e,t,r)]);function BY(...e){let[t,r,o]=un.Match(e,{3:(n,i,a)=>[n,i,a],2:(n,i)=>[{},n,i]});return jpo(t,r,o)}function Gpo(e,t){return Rd(t)||tT(e,t.items)}function Jpo(e,t){return Rd(t)||o1t({...e,...t.$defs},Uu(t.$ref))}function Vpo(e,t){return Rd(t)||t.allOf.some(r=>tT(e,r))}function Bpo(e,t){return Rd(t)||N.Keys(t.properties).some(r=>tT(e,t.properties[r]))}function Kpo(e,t){return Rd(t)||tT(e,bc(t))}function o1t(e,t){return fOe.has(t.$ref)?!1:(fOe.add(t.$ref),Rd(t)||N.HasPropertyKey(e,t.$ref)&&tT(e,e[t.$ref]))}function Hpo(e,t){return Rd(t)||t.items.some(r=>tT(e,r))}function Xpo(e,t){return Rd(t)||t.anyOf.some(r=>tT(e,r))}function tT(e,t){return jn(t)?Gpo(e,t):oa(t)?Jpo(e,t):Ao(t)?Vpo(e,t):Po(t)?Bpo(e,t):za(t)?Kpo(e,t):bi(t)?o1t(e,t):bn(t)?Hpo(e,t):zr(t)?Xpo(e,t):Rd(t)}var fOe=new Set;function KY(...e){let[t,r]=un.Match(e,{2:(o,n)=>[o,n],1:o=>[{},o]});return fOe.clear(),tT(t,r)}var Nf=class extends Error{constructor(t,r){super(r),this.type=t}};function n1t(e,t){return N.IsFunction(t.default)?t.default(t):N.IsObject(t.default)?Xn(t.default):t.default}function i1t(e,t){if(hy(t)&&!Hl(t))throw new Nf(t,"Arrays with uniqueItems constraints must specify a default annotation");let r=P0(t)?t.minItems:0;return Array.from({length:r},()=>ka(e,t.items))}async function*Ypo(){}function a1t(e,t){return Ypo()}function s1t(e,t){return t.Create()}function c1t(e,t){return Ug(t)?BigInt(t.exclusiveMinimum)+BigInt(1):Fg(t)?BigInt(t.minimum):BigInt(0)}function u1t(e,t){return!1}function p1t(e,t){let r=ka(e,t.instanceType);return class{constructor(){Object.assign(this,r)}}}function l1t(e,t){return ka({...e,...t.$defs},Uu(t.$ref))}function d1t(e,t){return ka(e,eS(t))}function m1t(e,t){let r=ka(e,t.returnType);return()=>r}function f1t(e,t){return Ug(t)&&N.IsNumber(t.exclusiveMinimum)?t.exclusiveMinimum+1:Fg(t)?t.minimum:0}function h1t(e,t){let r=Cd(e,t),o=rg(r);return ka(e,o)}function*Qpo(){}function g1t(e,t){return Qpo()}function _1t(e,t){return t.const}function y1t(e,t){throw new Nf(t,"Cannot create TNever types")}function x1t(e,t){return null}function b1t(e,t){return Ug(t)&&N.IsNumber(t.exclusiveMinimum)?t.exclusiveMinimum+1:Fg(t)?t.minimum:0}function S1t(e,t){return(N.IsUndefined(t.required)?[]:t.required).reduce((o,n)=>({...o,[n]:ka(e,t.properties[n])}),{})}function v1t(e,t){return Promise.resolve(ka(e,t.item))}function T1t(e,t){if(nk(t)&&!Hl(t))throw new Nf(t,"Record with the minProperties constraint must have a default annotation");return{}}function E1t(e,t){return N.HasPropertyKey(e,t.$ref)?ka(e,e[t.$ref]):(()=>{throw new Nf(t,"Unable to deref Ref")})()}function R1t(e,t){if((ik(t)||tk(t))&&!Hl(t))throw Error("Strings with format or pattern constraints must specify default");let o=ok(t)?t.minLength:0;return"".padEnd(o)}function w1t(e,t){return Symbol()}function k1t(e,t){let r=yc(t.pattern);if(_c(r))throw new Nf(t,"Unable to create TemplateLiteral due to infinite type expansion");return ka(e,r)}function I1t(e,t){return Array.from({length:t.minItems},(r,o)=>ka(e,t.items[o]))}function C1t(e,t){if(N.IsEqual(t.anyOf.length,0))throw Error("Unable to create Union with no variants");return ka(e,t.anyOf[0])}function ka(e,t){return Hl(t)?n1t(e,t):jn(t)?i1t(e,t):jc(t)?a1t(e,t):Ed(t)?s1t(e,t):wd(t)?c1t(e,t):qp(t)?u1t(e,t):xs(t)?p1t(e,t):oa(t)?l1t(e,t):Ss(t)?d1t(e,t):bs(t)?m1t(e,t):hu(t)?f1t(e,t):Ao(t)?h1t(e,t):Vc(t)?g1t(e,t):Tn(t)?_1t(e,t):Hh(t)?y1t(e,t):Ox(t)?x1t(e,t):Ha(t)?b1t(e,t):Po(t)?S1t(e,t):tc(t)?v1t(e,t):za(t)?T1t(e,t):bi(t)?E1t(e,t):_c(t)?R1t(e,t):Qb(t)?w1t(e,t):Da(t)?k1t(e,t):bn(t)?I1t(e,t):Px(t)?void 0:zr(t)?C1t(e,t):kd(t)?void 0:void 0}function Cc(...e){let[t,r]=un.Match(e,{2:(o,n)=>[o,n],1:o=>[{},o]});return ka(t,r)}function HY(e,t){return N.IsDeepEqual(e,t)}function XY(e){return Wm.Hash(e)}var C5=class extends Error{constructor(t){super(t)}};function A1t(e,t,r,o){if(!N.IsArray(r))Sp.Set(e,t,Xn(o));else{for(let n=0;n<o.length;n++)G1(e,`${t}/${n}`,r[n],o[n]);r.splice(o.length)}}function hOe(e){if(N.IsUnsafePropertyKey(e))throw Error("Attempted to Mutate with unsafe property key")}function O1t(e,t,r,o){if(!N.IsObjectNotArray(r))Sp.Set(e,t,Xn(o));else{let n=N.Keys(r),i=N.Keys(o);for(let a of n)hOe(a),i.includes(a)||delete r[a];for(let a of i)hOe(a),n.includes(a)||(r[a]=o[a]);for(let a of i)hOe(a),G1(e,`${t}/${a}`,r[a],o[a])}}function P1t(e,t,r,o){r!==o&&Sp.Set(e,t,o)}function G1(e,t,r,o){return N.IsArray(o)?A1t(e,t,r,o):N.IsObject(o)?O1t(e,t,r,o):P1t(e,t,r,o)}function N1t(e){return Sa.IsTypeArray(e)||Sa.IsDate(e)||Sa.IsMap(e)||Sa.IsSet(e)||N.IsNumber(e)||N.IsString(e)||N.IsBoolean(e)||N.IsSymbol(e)}function Zpo(e,t){return N.IsObjectNotArray(e)&&N.IsArray(t)||N.IsArray(e)&&N.IsObjectNotArray(t)}function M1t(e,t){if(N1t(e)||N1t(t))throw new C5("Only object and array types can be mutated at the root level");if(Zpo(e,t))throw new C5("Cannot assign due type mismatch of assignable values");G1(e,"",e,t)}var J1=class extends D0{constructor(t,r){super("Parse",t,r)}};function elo(e,t,r){if(!Sn(e,t,r))throw new J1(r,rm(e,t,r));return r}var gOe=j1([(e,t,r)=>Xn(r),(e,t,r)=>gy(e,t,r),(e,t,r)=>Pf(e,t,r),(e,t,r)=>om(e,t,r),(e,t,r)=>elo(e,t,r)]);function L1t(...e){let[t,r,o]=un.Match(e,{3:(i,a,s)=>[i,a,s],2:(i,a)=>[{},i,a]});if(Sn(t,r,o))return o;if(mu.Get().correctiveParse)return gOe(t,r,o);throw new J1(o,rm(t,r,o))}function YY(e,t){return{type:"update",path:e,value:t}}function $1t(e,t){return{type:"insert",path:e,value:t}}function z1t(e){return{type:"delete",path:e}}function D1t(e){if(!(N.IsObject(e)&&N.IsEqual(N.Symbols(e).length,0)))throw new Error("Cannot create diffs for objects with symbols keys")}function*tlo(e,t,r){if(!N.IsObject(r)||N.IsArray(r))return yield YY(e,r);D1t(t),D1t(r);let o=N.Keys(t),n=N.Keys(r);for(let i of n)N.HasPropertyKey(t,i)||N.IsUnsafePropertyKey(i)||(yield $1t(`${e}/${i}`,r[i]));for(let i of o)N.HasPropertyKey(r,i)&&(N.IsUnsafePropertyKey(i)||HY(t,r)||(yield*QY(`${e}/${i}`,t[i],r[i])));for(let i of o)N.HasPropertyKey(r,i)||N.IsUnsafePropertyKey(i)||(yield z1t(`${e}/${i}`))}function*rlo(e,t,r){if(!N.IsArray(r))return yield YY(e,r);for(let o=0;o<Math.min(t.length,r.length);o++)yield*QY(`${e}/${o}`,t[o],r[o]);for(let o=0;o<r.length;o++)o<t.length||(yield $1t(`${e}/${o}`,r[o]));for(let o=t.length-1;o>=0;o--)o<r.length||(yield z1t(`${e}/${o}`))}function*olo(e,t,r){let o=globalThis.Object.getPrototypeOf(t).constructor.name,n=globalThis.Object.getPrototypeOf(r).constructor.name;if(Sa.IsTypeArray(r)&&N.IsEqual(t.length,r.length)&&N.IsEqual(o,n))for(let a=0;a<Math.min(t.length,r.length);a++)yield*QY(`${e}/${a}`,t[a],r[a]);else return yield YY(e,r)}function*nlo(e,t,r){t!==r&&(yield YY(e,r))}function*QY(e,t,r){return Sa.IsTypeArray(t)?yield*olo(e,t,r):N.IsArray(t)?yield*rlo(e,t,r):N.IsObject(t)?yield*tlo(e,t,r):yield*nlo(e,t,r)}function U1t(e,t){return[...QY("",e,t)]}var ilo=Do({type:ri("insert"),path:kl(),value:Xh()}),alo=Object({type:ri("update"),path:kl(),value:Xh()}),slo=Do({type:ri("delete"),path:kl()}),ims=gn([ilo,alo,slo]);function clo(e){return e.length>0&&e[0].path===""&&e[0].type==="update"}function ulo(e){return e.length===0}function F1t(e,t){if(clo(t))return Xn(t[0].value);if(ulo(t))return Xn(e);let r=Xn(e);for(let o of t)switch(o.type){case"insert":{Sp.Set(r,o.path,o.value);break}case"update":{Sp.Set(r,o.path,o.value);break}case"delete":{Sp.Delete(r,o.path);break}}return r}var $0=class extends Error{constructor(t,r,o,n){super(n),this.context=t,this.type=r,this.value=o}};function plo(e){let[t,r]=[new Set,[]];for(let o of e){let n=XY(o);t.has(n)||(t.add(n),r.push(o))}return r}function q1t(e,t,r){if(Sn(e,t,r))return r;let o=N.IsArray(r)?r:Cc(e,t),n=P0(t)&&o.length<t.minItems?[...o,...Array.from({length:t.minItems-o.length},()=>Cc(e,t))]:o,a=(rk(t)&&n.length>t.maxItems?n.slice(0,t.maxItems):n).map(c=>Us(e,t.items,c));if(!hy(t)||hy(t)&&!N.IsEqual(t.uniqueItems,!0))return a;let s=plo(a);if(!Sn(e,t,s))throw new $0(e,t,r,"Failed to repair Array due to uniqueItems constraint");return s}function ZY(e,t,r){if(Sn(e,t,r))return r;let o=Pf(e,t,r);return Sn(e,t,o)?o:Cc(e,t)}function W1t(e,t,r){return ZY(e,t,r)}function j1t(e,t,r){let o=eS(t);return Us(e,o,r)}function G1t(e,t,r){let o=Cd(e,t),n=rg(o);return Us(e,n,r)}function J1t(e,t,r){if(Sn(e,t,r))return r;if(!N.IsObjectNotArray(r))return Cc(e,t);let o=new Set(N.IsUndefined(t.required)?[]:t.required),n={};for(let[a,s]of N.Entries(t.properties))!o.has(a)&&N.IsUndefined(r[a])||(n[a]=a in r?Us(e,s,r[a]):Cc(e,s));let i=N.Keys(t.properties);if(Qd(t)&&N.IsObject(t.additionalProperties))for(let a of N.Keys(r))i.includes(a)||(n[a]=Us(e,t.additionalProperties,r[a]));return n}function V1t(e,t,r){if(Sn(e,t,r))return r;if(N.IsNull(r)||!N.IsObject(r)||N.IsArray(r))return Cc(e,t);let o=new RegExp(Il(t)),n=bc(t),i=new Set,a={};for(let[s,c]of N.Entries(r))o.test(s)&&(a[s]=Us(e,n,c),i.add(s));if(Qd(t))for(let s of N.Keys(r))i.has(s)||(a[s]=Us(e,t.additionalProperties,r[s]));return a}function B1t(e,t,r){return N.HasPropertyKey(e,t.$ref)?Us(e,e[t.$ref],r):(()=>{throw new $0(e,t,r,"Unable to de-reference target type")})()}function K1t(e,t,r){let o=yc(t.pattern);return Us(e,o,r)}function H1t(e,t,r){return Sn(e,t,r)?r:N.IsArray(r)?t.items.map((o,n)=>Us(e,o,r[n])):Cc(e,t)}function X1t(e,t,r){return bi(t)?N.HasPropertyKey(e,t.$ref)?X1t(e,e[t.$ref],r):(()=>{throw new Error("Unable to Deref target")})():t}function llo(e,t,r){if(!(Po(t)&&N.IsObject(r)))return 0;let o=N.Keys(r);return N.Entries(t.properties).reduce((i,[a,s])=>{let c=Tn(s)&&N.IsEqual(s.const,r[a])?100:0,u=Sn(e,s,r[a])?10:0,l=o.includes(a)?1:0;return i+(c+u+l)},0)}function Y1t(e,t,r){let o=t.anyOf.map(a=>X1t(e,a,r)),[n,i]=[o[0],0];for(let a of o){let s=llo(e,a,r);s>i&&(n=a,i=s)}return n}function dlo(e,t,r){let o=gn(Qh(t.anyOf)),n=Y1t(e,o,r);return Us(e,n,r)}function Q1t(e,t,r){return Sn(e,t,r)?Xn(r):Hl(t)?Cc(e,t):dlo(e,t,r)}function mlo(e,t,r){if(Sa.IsDate(r)||Sa.IsMap(r)||Sa.IsSet(r)||Sa.IsTypeArray(r)||N.IsConstructor(r)||N.IsFunction(r))throw new $0(e,t,r,"Value is not repairable")}function flo(e,t,r){if(jc(t)||Vc(t)||xs(t)||bs(t)||Hh(t)||tc(t))throw new $0(e,t,r,"Type is not repairable")}function Z1t(e,t,r){return Jle(t)?Sn(e,t,r)?r:Cc(e,t):r}function Us(e,t,r){if(Ed(t)){let n=W1t(e,t,r);return Z1t(e,t,n)}mlo(e,t,r),flo(e,t,r);let o=jn(t)?q1t(e,t,r):Ss(t)?j1t(e,t,r):Ao(t)?G1t(e,t,r):Po(t)?J1t(e,t,r):za(t)?V1t(e,t,r):bi(t)?B1t(e,t,r):Da(t)?K1t(e,t,r):bn(t)?H1t(e,t,r):zr(t)?Q1t(e,t,r):ZY(e,t,r);return Z1t(e,t,o)}function eMt(...e){let[t,r,o]=un.Match(e,{3:(i,a,s)=>[i,a,s],2:(i,a)=>[{},i,a]}),n=Us(t,r,o);return WY(t,r,n),n}var V1={};to(V1,{Assert:()=>WY,Check:()=>Sn,Clean:()=>om,Clone:()=>Xn,Convert:()=>Pf,Create:()=>Cc,Decode:()=>VY,Default:()=>gy,Diff:()=>U1t,Encode:()=>BY,Equal:()=>HY,Errors:()=>rm,HasCodec:()=>KY,Hash:()=>XY,Mutate:()=>M1t,Parse:()=>L1t,Patch:()=>F1t,Pointer:()=>Sp,Repair:()=>eMt});var A5=class e extends S${constructor(...t){super();let r=un.Match(t,{3:(o,n,i)=>[o,n,i],2:(o,n)=>[o,n]});if(r.length===3&&r[1]instanceof w5&&r[2]instanceof R5){let[o,n,i]=r;this.hasCodec=o,this.buildResult=n,this.evaluateResult=i}else{let[o,n]=r;this.hasCodec=KY(o,n),this.buildResult=FY(o,n),this.evaluateResult=this.buildResult.Evaluate()}}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(t){return this.evaluateResult.Check(t)}Parse(t){if(this.Check(t))return t;if(mu.Get().correctiveParse)return gOe(this.Context(),this.Type(),t);throw new J1(t,this.Errors(t))}Errors(t){return this.IsAccelerated()&&this.Check(t)?[]:rm(this.Context(),this.Type(),t)}Clean(t){return om(this.Context(),this.Type(),t)}Convert(t){return Pf(this.Context(),this.Type(),t)}Create(){return Cc(this.Context(),this.Type())}Default(t){return gy(this.Context(),this.Type(),t)}Decode(t){return this.hasCodec?VY(this.Context(),this.Type(),t):this.Parse(t)}Encode(t){return this.hasCodec?BY(this.Context(),this.Type(),t):this.Parse(t)}Clone(){return new e(this.hasCodec,this.buildResult,this.evaluateResult)}};function eQ(...e){let[t,r]=un.Match(e,{2:(o,n)=>[o,n],1:o=>[{},o]});return new A5(t,r)}var hlo=S.Object({candidateIndex:S.Number(),badDecision:S.String({minLength:1}),betterDecision:S.String({minLength:1}),rationale:S.String({minLength:1}),confidence:S.Number({minimum:0,maximum:1}),riskLevel:S.Union([S.Literal("low"),S.Literal("medium"),S.Literal("high")]),strategicPerspective:S.String({minLength:1})}),tMt=S.Object({valid:S.Boolean(),taskId:S.String({minLength:1}),candidates:S.Array(hlo,{minItems:1,maxItems:5}),sourcePrincipleId:S.Optional(S.String()),sourcePainId:S.Optional(S.String()),contextRefs:S.Array(S.String()),generatedAt:S.String({minLength:1}),reason:S.Optional(S.String())}),glo=new Set(["low","medium","high"]),O5=class{async validate(t,r){let o=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};let n=t;if(n.taskId!==r&&o.push(`taskId mismatch: expected ${r}, got ${String(n.taskId)}`),n.valid!==!0&&o.push("output.valid must be true"),!Array.isArray(n.candidates))o.push("candidates must be an array");else{(n.candidates.length<1||n.candidates.length>5)&&o.push("candidates must have 1-5 items");for(let i=0;i<n.candidates.length;i++){let a=n.candidates[i];if(!a){o.push(`candidates[${i}] is null/undefined`);continue}typeof a.candidateIndex!="number"&&o.push(`candidates[${i}].candidateIndex must be number`),(typeof a.badDecision!="string"||a.badDecision.trim()==="")&&o.push(`candidates[${i}].badDecision must be non-empty string`),(typeof a.betterDecision!="string"||a.betterDecision.trim()==="")&&o.push(`candidates[${i}].betterDecision must be non-empty string`),(typeof a.rationale!="string"||a.rationale.trim()==="")&&o.push(`candidates[${i}].rationale must be non-empty string`),typeof a.confidence!="number"?o.push(`candidates[${i}].confidence must be number`):(a.confidence<0||a.confidence>1)&&o.push(`candidates[${i}].confidence must be in [0, 1]`),(typeof a.riskLevel!="string"||!glo.has(a.riskLevel))&&o.push(`candidates[${i}].riskLevel must be low|medium|high`),(typeof a.strategicPerspective!="string"||a.strategicPerspective.trim()==="")&&o.push(`candidates[${i}].strategicPerspective must be non-empty string`)}}return Array.isArray(n.contextRefs)||o.push("contextRefs must be an array"),(typeof n.generatedAt!="string"||n.generatedAt.trim()==="")&&o.push("generatedAt must be non-empty string"),o.length>0?{valid:!1,errors:o,errorCategory:"output_invalid"}:{valid:!0,errors:[]}}};var _lo=S.Object({title:S.String({minLength:1}),rationale:S.String({minLength:1}),scope:S.String({minLength:1}),confidence:S.Number({minimum:0,maximum:1})}),rMt=S.Object({taskId:S.String({minLength:1}),sourceDreamerArtifactId:S.String({minLength:1}),thesis:S.String({minLength:1}),principleCandidate:_lo,risks:S.Array(S.String()),generatedAt:S.String({minLength:1})});var ylo=S.Object({title:S.String({minLength:1}),statement:S.String({minLength:1}),rationale:S.String({minLength:1}),applicability:S.Array(S.String()),antiPatterns:S.Array(S.String()),confidence:S.Number({minimum:0,maximum:1})}),xlo=S.Object({dreamerArtifactId:S.Optional(S.String()),philosopherArtifactId:S.String({minLength:1})}),oMt=S.Object({taskId:S.String({minLength:1}),sourcePhilosopherArtifactId:S.String({minLength:1}),principleDraft:ylo,sourceTrace:xlo,risks:S.Array(S.String()),generatedAt:S.String({minLength:1})});var nMt={read:"read",read_file:"read",read_many_files:"read",grep:"search",grep_search:"search",search_file_content:"search",glob:"search",write:"write",write_file:"write",edit:"write",edit_file:"write",replace:"write",apply_patch:"write",bash:"execute",exec:"execute",execute:"execute",run_shell_command:"execute",sessions_spawn:"agent"};function tQ(e){if(typeof e!="string"||!Object.hasOwn(nMt,e))return"other";let t=nMt[e];return t!==void 0?t:"other"}function _Oe(e,t,r){if(e.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let o=0,n=0,i=new Set,a=t===null?"unknown":"no",{calls:s}=e;for(let c of s){let u=c.canonicalKind;u==="read"||u==="search"?(o++,t!==null&&c.normalizedPath===t&&(a="yes")):u==="write"&&(n++,typeof c.normalizedPath=="string"&&i.add(c.normalizedPath))}return{priorReadOfTarget:a,readCount:o,writeCount:n,uniqueWritePathCount:i.size,sameActionBlockCount:r}}var iMt={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(iMt);var yOe={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze(yOe.calls);Object.freeze(yOe);var aMt={version:2,history:yOe,facts:iMt};Object.freeze(aMt);var B1=aMt;var sMt=S.Object({scribeArtifactId:S.String({minLength:1}),philosopherArtifactId:S.Optional(S.String({minLength:1})),dreamerArtifactId:S.Optional(S.String({minLength:1}))}),bOe=S.Object({taskId:S.String({minLength:1}),sourceScribeArtifactId:S.String({minLength:1}),implementationCode:S.String({minLength:1}),goldenTraceCases:S.Array(S.Object({caseId:S.String({minLength:1}),kind:S.Union([S.Literal("positive"),S.Literal("negative")]),toolName:S.String({minLength:1}),params:S.Record(S.String(),S.Unknown()),expectedDecision:S.Union([S.Literal("allow"),S.Literal("block"),S.Literal("propose_correction")]),expectedProposedParams:S.Optional(S.Record(S.String(),S.Unknown())),expectedApplicationMode:S.Optional(S.Union([S.Literal("shadow"),S.Literal("live")]))}),{minItems:2,maxItems:10}),affectedTools:S.Array(S.String({minLength:1}),{minItems:1}),implementationSummary:S.String({minLength:1}),risks:S.Array(S.String()),sourceTrace:sMt,generatedAt:S.String({minLength:1}),requiresContextVersion:S.Optional(S.Literal(2)),evidenceRefs:S.Optional(S.Array(S.String({minLength:1})))});var cMt=S.Object({decision:S.Union([S.Literal("approved"),S.Literal("needs_revision"),S.Literal("rejected")]),summary:S.String({minLength:1}),score:S.Number({minimum:0,maximum:1}),strengths:S.Array(S.String()),concerns:S.Array(S.String()),requiredChanges:S.Array(S.String())}),uMt=S.Object({artificerArtifactId:S.String({minLength:1}),scribeArtifactId:S.Optional(S.String()),philosopherArtifactId:S.Optional(S.String()),dreamerArtifactId:S.Optional(S.String())}),SOe=S.Object({taskId:S.String({minLength:1}),sourceArtificerArtifactId:S.String({minLength:1}),evaluation:cMt,sourceTrace:uMt,risks:S.Array(S.String()),generatedAt:S.String({minLength:1})});var pMt=S.Object({decision:S.Union([S.Literal("approve_rollout"),S.Literal("needs_revision"),S.Literal("reject")]),summary:S.String({minLength:1}),confidence:S.Number({minimum:0,maximum:1}),requiredChanges:S.Array(S.String()),rolloutRisks:S.Array(S.String()),safetyChecks:S.Array(S.String())}),lMt=S.Object({evaluatorArtifactId:S.String({minLength:1}),artificerArtifactId:S.Optional(S.String()),scribeArtifactId:S.Optional(S.String()),philosopherArtifactId:S.Optional(S.String()),dreamerArtifactId:S.Optional(S.String())}),vOe=S.Object({taskId:S.String({minLength:1}),sourceEvaluatorArtifactId:S.String({minLength:1}),review:pMt,sourceTrace:lMt,risks:S.Array(S.String()),generatedAt:S.String({minLength:1})});var blo=S.Object({userMessage:S.String({minLength:1})}),TOe=S.Object({damageDetected:S.Boolean(),severity:S.Union([S.Literal("mild"),S.Literal("moderate"),S.Literal("severe")]),confidence:S.Number({minimum:0,maximum:1}),reason:S.String()});var Slo=S.Object({parentSessionId:S.String(),workspaceDir:S.String(),keywordStoreSummary:S.Object({totalKeywords:S.Number(),terms:S.Array(S.Object({term:S.String(),weight:S.Number(),hitCount:S.Number(),truePositiveCount:S.Number(),falsePositiveCount:S.Number()}))}),recentMessages:S.Array(S.String()),trajectoryHistory:S.Array(S.Object({sessionId:S.String(),timestamp:S.String(),term:S.String(),userMessage:S.String()}))}),EOe=S.Object({updated:S.Boolean(),updates:S.Optional(S.Record(S.String(),S.Object({action:S.Union([S.Literal("add"),S.Literal("update"),S.Literal("remove")]),weight:S.Optional(S.Number()),falsePositiveRate:S.Optional(S.Number()),reasoning:S.String()}))),fpTerms:S.Optional(S.Array(S.String())),fpAnalysisStatus:S.Optional(S.Union([S.Literal("completed"),S.Literal("skipped")])),summary:S.String()}),P5=class e{runtimeAdapter;timeoutMs;agentId;constructor(t,r){this.runtimeAdapter=t.runtimeAdapter,this.timeoutMs=r?.timeoutMs??3e4,this.agentId=r?.agentId??"correction-observer"}static buildPrompt(t){let{keywordStoreSummary:r,recentMessages:o,trajectoryHistory:n}=t,i=80,a=r.terms.map(u=>` - term="${u.term}", weight=${u.weight}, hits=${u.hitCount}, TP=${u.truePositiveCount}, FP=${u.falsePositiveCount}`).join(`
|
|
1014
1014
|
`),s=o.length>0?o.map(u=>` - ${JSON.stringify(u)}`).join(`
|
|
@@ -1053,7 +1053,7 @@ ${a}${s}`}buildPrompt(t,r={}){let{outputLanguage:o}=r,n=this.buildRouterInstruct
|
|
|
1053
1053
|
apiKeyEnv: ANTHROPIC_AUTH_TOKEN
|
|
1054
1054
|
baseUrl: https://token-plan-cn.xiaomimimo.com/v1
|
|
1055
1055
|
|
|
1056
|
-
If you want to use the OpenClaw CLI runtime instead, set runtimeKind: openclaw-cli`)}}function cQ(e,t){let r=oQ(e,"diagnostician");if(!r.ok)return{ok:!1,reason:r.readiness,message:r.reason,nextAction:r.nextAction};let o=nQ(r.profile,t);if(o.readiness!=="ready")return{ok:!1,reason:o.readiness,message:o.reason??`Agent runtime profile '${r.profileId}' is not ready`,nextAction:o.nextAction??"Check .pd/config.yaml runtime profile configuration"};let n=iQ(r.profile,"");if(n.runtimeKind==="pi-ai")return{runtimeKind:"pi-ai",provider:n.provider,model:n.model,apiKeyEnv:n.apiKeyEnv,baseUrl:n.baseUrl,timeoutMs:n.timeoutMs??mk,maxRetries:n.maxRetries,agentId:"main",...n.systemPrompt?{systemPrompt:n.systemPrompt}:{}};let i={runtimeKind:"openclaw-cli",timeoutMs:mk,agentId:"main"};return n.openclawMode!=="default"&&(i.openclawMode=n.openclawMode),i}var zMt=new Map,aQ=class{async run(t){return{status:"failed",taskId:t,errorCategory:"capability_missing",failureReason:"Diagnostician pipeline is disabled by feature flag (diagnostician_split_pipeline=false)",attemptCount:1}}};async function uQ(e){let t;if(e.effectiveConfig){let v=e.getEnvVar??(E=>process.env[E]);t=cQ(e.effectiveConfig,v)}else t=UMt(e.stateDir);if(sQ(t))throw new Error(`[PainSignalRuntimeFactory] Config resolution failed: ${t.reason}. ${t.message}. nextAction: ${t.nextAction}`);FMt(t);let r=!0;if(e.effectiveConfig){let v=mp(e.effectiveConfig),E=Fm(v,"diagnostician_split_pipeline"),L=Fm(v,"diagnostician_async_cli");if(E&&!L){let H=e.effectiveConfig.featuresChangedFromDefault?.includes("diagnostician_split_pipeline")??!1,B=e.effectiveConfig.featuresChangedFromDefault?.includes("diagnostician_async_cli")??!1;if(H||B)throw new wt("input_invalid","diagnostician_split_pipeline requires diagnostician_async_cli=on (3 serial LLM calls would block the sync CLI 540s+)")}r=E}let o=`${e.workspaceDir}:${t.runtimeKind}:${t.openclawMode??""}:${r?"split":"disabled"}`,n=zMt.get(o);if(n)return n;let i=new Rx({workspaceDir:e.workspaceDir});await i.initialize();let a=new Tl(e.workspaceDir),s=new DC(a),c=new Y2(a),u=new MC(a),l=new LC(i.taskStore,u),m=new UC(i.taskStore,s,i.runStore,{sourceTraceLocator:l}),p=t.runtimeKind==="pi-ai"?new nm({provider:String(t.provider),model:String(t.model),apiKeyEnv:String(t.apiKeyEnv),maxRetries:t.maxRetries,timeoutMs:t.timeoutMs,baseUrl:t.baseUrl,workspace:e.workspaceDir,...t.systemPrompt?{systemPrompt:t.systemPrompt}:{}}):new Cx({runtimeMode:t.openclawMode??"default",workspaceDir:e.workspaceDir}),h=Cle(e.effectiveConfig?.config.principles?.outputLanguage),f=h.outputLanguage;h.degradationWarning&&ks.emitTelemetry({eventType:"degradation_triggered",traceId:`output-language-config-${Date.now()}`,timestamp:new Date().toISOString(),sessionId:"",payload:{component:"PainSignalRuntimeFactory",reason:"invalid_output_language_config",warning:h.degradationWarning,fallbackValue:h.outputLanguage}});let g;if(r){let v=new l$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,validator:new U2,contextAssembler:m,intentDocReader:e.intentDocReader},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f,effectiveConfig:e.effectiveConfig}),E=new m$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,validator:new d$},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f,effectiveConfig:e.effectiveConfig}),L=new f$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,committer:c},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f});g=new o$({rootCauseRunner:v,distillerRunner:E,routerRunner:L,stateManager:i,committer:c,perStageTimeoutMs:t.timeoutMs??mk})}else g=new aQ;let y=new W2({stateManager:i,ledgerAdapter:e.ledgerAdapter}),T=new X2({stateManager:i,runner:g,intakeService:y,ledgerAdapter:e.ledgerAdapter,autoIntakeEnabled:e.autoIntakeEnabled??!0,workspaceDir:e.workspaceDir});return zMt.set(o,T),T}var qMt=["deterministic","weak_heuristic","manual_only"];function zlo(e){return e.startsWith("candidate://")?e.slice(12):e}function Ulo(e,t){if(!qMt.includes(e.evaluability))throw new Error(`Invalid evaluability value: ${e.evaluability}. Must be one of: ${qMt.join(", ")}`);return{id:e.id,version:1,text:e.text,triggerPattern:e.triggerPattern??"",action:e.action??"",status:"candidate",evaluability:e.evaluability,priority:"P1",scope:"general",valueScore:0,adherenceRate:0,painPreventedCount:0,derivedFromPainIds:[t],ruleIds:[],conflictsWithPrincipleIds:[],createdAt:e.createdAt,updatedAt:e.createdAt}}var oT=class{#e;#t=new Map;constructor(t){this.#e=t.stateDir}writeProbationEntry(t){let r=zlo(t.sourceRef),o=this.#t.get(r);if(o)return o;let n=Ulo(t,r);return hR(this.#e,n),this.#t.set(r,t),t}existsForCandidate(t){let r=this.#t.get(t);if(r)return r;let o=xi(this.#e),n=Object.values(o.tree.principles).find(i=>i.derivedFromPainIds.includes(t));return n?{id:n.id,title:"",status:"probation",sourceRef:`candidate://${t}`,artifactRef:"",taskRef:"",text:n.text,triggerPattern:n.triggerPattern,action:n.action,evaluability:"weak_heuristic",createdAt:n.createdAt}:null}activatePrinciple(t){try{return $u(this.#e,t,{status:"active",updatedAt:new Date().toISOString()}),{ok:!0}}catch(r){return{ok:!1,reason:`ledger_activate_failed: ${r instanceof Error?r.message:String(r)}`}}}};import Blo from"better-sqlite3";import*as L5 from"fs";import*as fk from"path";function Klo(){return new Date().toISOString()}function Hlo(e){return e.slice(0,10)}function jMt(e){return e>=70?"severe":e>=40?"moderate":"mild"}function WMt(e,t){L5.mkdirSync(fk.dirname(e),{recursive:!0}),L5.appendFileSync(e,`${JSON.stringify(t)}
|
|
1056
|
+
If you want to use the OpenClaw CLI runtime instead, set runtimeKind: openclaw-cli`)}}function cQ(e,t){let r=oQ(e,"diagnostician");if(!r.ok)return{ok:!1,reason:r.readiness,message:r.reason,nextAction:r.nextAction};let o=nQ(r.profile,t);if(o.readiness!=="ready")return{ok:!1,reason:o.readiness,message:o.reason??`Agent runtime profile '${r.profileId}' is not ready`,nextAction:o.nextAction??"Check .pd/config.yaml runtime profile configuration"};let n=iQ(r.profile,"");if(n.runtimeKind==="pi-ai")return{runtimeKind:"pi-ai",provider:n.provider,model:n.model,apiKeyEnv:n.apiKeyEnv,baseUrl:n.baseUrl,timeoutMs:n.timeoutMs??mk,maxRetries:n.maxRetries,agentId:"main",...n.systemPrompt?{systemPrompt:n.systemPrompt}:{}};let i={runtimeKind:"openclaw-cli",timeoutMs:mk,agentId:"main"};return n.openclawMode!=="default"&&(i.openclawMode=n.openclawMode),i}var zMt=new Map,aQ=class{async run(t){return{status:"failed",taskId:t,errorCategory:"capability_missing",failureReason:"Diagnostician pipeline is disabled by feature flag (diagnostician_split_pipeline=false)",attemptCount:1}}};async function uQ(e){let t;if(e.effectiveConfig){let v=e.getEnvVar??(E=>process.env[E]);t=cQ(e.effectiveConfig,v)}else t=UMt(e.stateDir);if(sQ(t))throw new Error(`[PainSignalRuntimeFactory] Config resolution failed: ${t.reason}. ${t.message}. nextAction: ${t.nextAction}`);FMt(t);let r=!0;if(e.effectiveConfig){let v=mp(e.effectiveConfig),E=Fm(v,"diagnostician_split_pipeline"),L=Fm(v,"diagnostician_async_cli");if(E&&!L){let H=e.effectiveConfig.featuresChangedFromDefault?.includes("diagnostician_split_pipeline")??!1,B=e.effectiveConfig.featuresChangedFromDefault?.includes("diagnostician_async_cli")??!1;if(H||B)throw new wt("input_invalid","diagnostician_split_pipeline requires diagnostician_async_cli=on (3 serial LLM calls would block the sync CLI 540s+)")}r=E}let o=`${e.workspaceDir}:${t.runtimeKind}:${t.openclawMode??""}:${r?"split":"disabled"}`,n=zMt.get(o);if(n)return n;let i=new Rx({workspaceDir:e.workspaceDir});await i.initialize();let a=new Tl(e.workspaceDir),s=new DC(a),c=new Y2(a),u=new MC(a),l=new LC(i.taskStore,u),m=new UC(i.taskStore,s,i.runStore,{sourceTraceLocator:l,trajectoryTurnReader:e.trajectoryTurnReader}),p=t.runtimeKind==="pi-ai"?new nm({provider:String(t.provider),model:String(t.model),apiKeyEnv:String(t.apiKeyEnv),maxRetries:t.maxRetries,timeoutMs:t.timeoutMs,baseUrl:t.baseUrl,workspace:e.workspaceDir,...t.systemPrompt?{systemPrompt:t.systemPrompt}:{}}):new Cx({runtimeMode:t.openclawMode??"default",workspaceDir:e.workspaceDir}),h=Cle(e.effectiveConfig?.config.principles?.outputLanguage),f=h.outputLanguage;h.degradationWarning&&ks.emitTelemetry({eventType:"degradation_triggered",traceId:`output-language-config-${Date.now()}`,timestamp:new Date().toISOString(),sessionId:"",payload:{component:"PainSignalRuntimeFactory",reason:"invalid_output_language_config",warning:h.degradationWarning,fallbackValue:h.outputLanguage}});let g;if(r){let v=new l$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,validator:new U2,contextAssembler:m,intentDocReader:e.intentDocReader},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f,effectiveConfig:e.effectiveConfig}),E=new m$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,validator:new d$},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f,effectiveConfig:e.effectiveConfig}),L=new f$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,committer:c},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f});g=new o$({rootCauseRunner:v,distillerRunner:E,routerRunner:L,stateManager:i,committer:c,perStageTimeoutMs:t.timeoutMs??mk})}else g=new aQ;let y=new W2({stateManager:i,ledgerAdapter:e.ledgerAdapter}),T=new X2({stateManager:i,runner:g,intakeService:y,ledgerAdapter:e.ledgerAdapter,autoIntakeEnabled:e.autoIntakeEnabled??!0,workspaceDir:e.workspaceDir});return zMt.set(o,T),T}var qMt=["deterministic","weak_heuristic","manual_only"];function zlo(e){return e.startsWith("candidate://")?e.slice(12):e}function Ulo(e,t){if(!qMt.includes(e.evaluability))throw new Error(`Invalid evaluability value: ${e.evaluability}. Must be one of: ${qMt.join(", ")}`);return{id:e.id,version:1,text:e.text,triggerPattern:e.triggerPattern??"",action:e.action??"",status:"candidate",evaluability:e.evaluability,priority:"P1",scope:"general",valueScore:0,adherenceRate:0,painPreventedCount:0,derivedFromPainIds:[t],ruleIds:[],conflictsWithPrincipleIds:[],createdAt:e.createdAt,updatedAt:e.createdAt}}var oT=class{#e;#t=new Map;constructor(t){this.#e=t.stateDir}writeProbationEntry(t){let r=zlo(t.sourceRef),o=this.#t.get(r);if(o)return o;let n=Ulo(t,r);return hR(this.#e,n),this.#t.set(r,t),t}existsForCandidate(t){let r=this.#t.get(t);if(r)return r;let o=xi(this.#e),n=Object.values(o.tree.principles).find(i=>i.derivedFromPainIds.includes(t));return n?{id:n.id,title:"",status:"probation",sourceRef:`candidate://${t}`,artifactRef:"",taskRef:"",text:n.text,triggerPattern:n.triggerPattern,action:n.action,evaluability:"weak_heuristic",createdAt:n.createdAt}:null}activatePrinciple(t){try{return $u(this.#e,t,{status:"active",updatedAt:new Date().toISOString()}),{ok:!0}}catch(r){return{ok:!1,reason:`ledger_activate_failed: ${r instanceof Error?r.message:String(r)}`}}}};import Blo from"better-sqlite3";import*as L5 from"fs";import*as fk from"path";function Klo(){return new Date().toISOString()}function Hlo(e){return e.slice(0,10)}function jMt(e){return e>=70?"severe":e>=40?"moderate":"mild"}function WMt(e,t){L5.mkdirSync(fk.dirname(e),{recursive:!0}),L5.appendFileSync(e,`${JSON.stringify(t)}
|
|
1057
1057
|
`,"utf8")}function Xlo(e){return e.prepare("PRAGMA table_info(sessions)").all().map(r=>r.name)}function Ylo(e){return Object.hasOwn(e,"name")}function Qlo(e){let t=[],r=["schema_version","ingest_checkpoint","sessions","assistant_turns","user_turns","tool_calls","pain_events","gate_blocks","trust_changes","principle_events","task_outcomes","correction_samples","sample_reviews","exports_audit","evolution_tasks","evolution_events"];e.exec(`
|
|
1058
1058
|
CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL);
|
|
1059
1059
|
CREATE TABLE IF NOT EXISTS ingest_checkpoint (
|
|
@@ -1253,7 +1253,7 @@ If you want to use the OpenClaw CLI runtime instead, set runtimeKind: openclaw-c
|
|
|
1253
1253
|
UPDATE pain_events
|
|
1254
1254
|
SET runtime_task_id = COALESCE(?, runtime_task_id)
|
|
1255
1255
|
WHERE canonical_pain_id = ?
|
|
1256
|
-
`).run(a??null,i);let h=c.prepare("SELECT id FROM pain_events WHERE canonical_pain_id = ?").get(i);return h&&typeof h=="object"&&Object.hasOwn(h,"id")&&typeof h.id=="number"?h.id:void 0}throw p}}finally{c.close()}}function pQ(e){let t=Klo(),r=[],o=e.data.score??80,n=e.data.sessionId??"cli",i=Hlo(t),a={warnings:r};try{let s=fk.join(e.stateDir,"logs",`events_${i}.jsonl`);WMt(s,{ts:t,date:i,type:"pain_signal",category:"detected",sessionId:n,workspaceDir:e.workspaceDir,data:{eventId:e.data.painId,score:o,source:e.data.source,reason:Lm(e.data.reason??"",e.workspaceDir),severity:jMt(o),origin:e.data.source==="manual"?"user_manual":"system_infer"}}),a.eventLogPath=s}catch(s){r.push(`event log write failed: ${s instanceof Error?s.message:String(s)}`)}try{let s=fk.join(e.workspaceDir,"memory","evolution.jsonl"),c={painId:e.data.painId,painType:e.data.painType,source:e.data.source,reason:Lm(e.data.reason??"",e.workspaceDir),score:e.data.score,sessionId:e.data.sessionId,provenance:e.data.provenance,evidenceCount:e.data.evidence?.length??0};WMt(s,{ts:t,type:"pain_detected",data:c}),a.evolutionStreamPath=s}catch(s){r.push(`evolution stream write failed: ${s instanceof Error?s.message:String(s)}`)}try{a.trajectoryPainEventId=Zlo({stateDir:e.stateDir,data:e.data,timestamp:t,workspaceDir:e.workspaceDir,canonicalPainId:e.canonicalPainId,runtimeTaskId:e.runtimeTaskId})}catch(s){r.push(`trajectory pain_events write failed: ${s instanceof Error?s.message:String(s)}`)}return a}function edo(e){if(e.errorCategory)return M2[e.errorCategory]??"runtime_unavailable";if(e.status==="failed"){if(e.candidateIds.length===0)return"candidate_missing";if(e.ledgerEntryIds.length===0)return"ledger_write_failed"}}function tdo(e){if(e instanceof wt&&e.category)return M2[e.category]??"runtime_unavailable";let t=e instanceof Error?e.message:String(e);return/api[_\s]?key|not found in env|missing required/i.test(t)?"config_missing":/timeout|timed[_\s]?out/i.test(t)?"runtime_timeout":/output.*invalid|validation.*fail/i.test(t)?"output_invalid":"runtime_unavailable"}var hk=class{opts;constructor(t){this.opts=t}async recordPain(t){let r=Date.now(),{painId:o}=t,n=t.taskId??H2(o),i={painId:o,painType:t.painType,source:t.source,reason:t.reason,score:t.score,sessionId:t.sessionId,agentId:t.agentId,taskId:n,traceId:t.traceId,provenance:t.provenance,evidence:t.evidence};try{if(this.opts.asyncMode){let m=await(await uQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,ledgerAdapter:this.opts.ledgerAdapter,owner:this.opts.owner,autoIntakeEnabled:!1,effectiveConfig:this.opts.effectiveConfig,getEnvVar:this.opts.getEnvVar,intentDocReader:this.opts.intentDocReader})).submitPainSignal(i),p=[];t.recordObservability!==!1&&(p=pQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:i,canonicalPainId:o,runtimeTaskId:m.taskId}).warnings);let h=Date.now()-r;return{status:"submitted",painId:o,taskId:m.taskId,candidateIds:[],ledgerEntryIds:[],observabilityWarnings:p,latencyMs:h,message:`Diagnosis submitted. Use 'pd task show ${m.taskId}' to check progress.`}}let s=await(await uQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,ledgerAdapter:this.opts.ledgerAdapter,owner:this.opts.owner,autoIntakeEnabled:this.opts.autoIntakeEnabled,effectiveConfig:this.opts.effectiveConfig,getEnvVar:this.opts.getEnvVar,intentDocReader:this.opts.intentDocReader})).onPainDetected(i),c=[];t.recordObservability!==!1&&(c=pQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:i,canonicalPainId:o,runtimeTaskId:n}).warnings);let u=Date.now()-r;return{status:s.status,painId:s.painId,taskId:s.taskId,runId:s.runId,artifactId:s.artifactId,candidateIds:s.candidateIds,ledgerEntryIds:s.ledgerEntryIds,admissionResults:s.admissionResults,message:s.message,observabilityWarnings:c,failureCategory:edo(s),latencyMs:u}}catch(a){let s=Date.now()-r;return{status:"failed",painId:o,taskId:n,candidateIds:[],ledgerEntryIds:[],message:a instanceof Error?a.message:String(a),observabilityWarnings:[],failureCategory:tdo(a),latencyMs:s}}}};var kOe=[{pattern:/Physical interception|physical blocking|物理拦截/i,description:"Remove Physical interception / physical blocking / \u7269\u7406\u62E6\u622A references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/Single source of truth.*PLAN/i,description:"Remove Single source of truth PLAN references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/PLAN\.md` \(status: READY\)|PLAN\.md`(状态:READY)/,description:"Remove PLAN.md status: READY references (AGENTS.md, THINKING_OS.md)",filenameSuffixes:["AGENTS.md","THINKING_OS.md"],actionType:"remove-line"},{pattern:/project physical plan|项目物理计划/i,description:"Remove project physical plan / \u9879\u76EE\u7269\u7406\u8BA1\u5212 references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/L2 delegation.*(PLAN|gate|blocking)|L2 委派.*(PLAN|gate|拦截)/i,description:"Remove L2 delegation / L2 \u59D4\u6D3E tied to PLAN.md gate enforcement (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/ or `PLAN\.md`/,description:'Replace "or PLAN.md" in T-02 PHYSICAL_MEMORY_PERSISTENCE (en)',filenameSuffixes:["THINKING_OS.md"],actionType:"replace",replacement:""},{pattern:/或 `PLAN\.md`/,description:'Replace "\u6216 PLAN.md" in T-02 PHYSICAL_MEMORY_PERSISTENCE (zh)',filenameSuffixes:["THINKING_OS.md"],actionType:"replace",replacement:""},{pattern:/PLAN\.md mechanism protects|PLAN\.md 机制保护/,description:"Remove PLAN.md mechanism protects / PLAN.md \u673A\u5236\u4FDD\u62A4 lines (MEMORY.md)",filenameSuffixes:["MEMORY.md"],actionType:"remove-line"},{pattern:/STATUS: READY|STATUS:READY/,description:"Remove STATUS: READY references (MEMORY.md)",filenameSuffixes:["MEMORY.md"],actionType:"remove-line"},{pattern:/Ensure `PLAN\.md` contains `## Target Files` heading|确保 `PLAN\.md` 包含 `## Target Files` 标题/,description:"Remove PLAN.md Target Files heading checks (admin/SKILL.md)",filenameSuffixes:["admin/SKILL.md"],actionType:"remove-line"},{pattern:/,\s*`PLAN\.md`\s*/,description:"Remove PLAN.md from list as trailing item (admin/SKILL.md, pd-grooming/SKILL.md)",filenameSuffixes:["admin/SKILL.md","pd-grooming/SKILL.md"],actionType:"replace",replacement:""},{pattern:/`PLAN\.md`\s*,\s*/,description:"Remove PLAN.md from list as leading item (admin/SKILL.md, pd-grooming/SKILL.md)",filenameSuffixes:["admin/SKILL.md","pd-grooming/SKILL.md"],actionType:"replace",replacement:""},{pattern:/Check `PLAN\.md` or early conversation/,description:"Replace Check PLAN.md or early conversation (en, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"Check early conversation context"},{pattern:/Update `PLAN\.md`/,description:"Replace Update PLAN.md with Update memory/.scratchpad.md (en, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"Update `memory/.scratchpad.md`"},{pattern:/检查 `PLAN\.md` 或早期对话/,description:"Replace Check PLAN.md or early conversation (zh, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"\u68C0\u67E5\u65E9\u671F\u5BF9\u8BDD\u4E0A\u4E0B\u6587"},{pattern:/更新 `PLAN\.md`/,description:"Replace Update PLAN.md (zh, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"\u66F4\u65B0 `memory/.scratchpad.md`"},{pattern:/, `PLAN\.md`, and /,description:"Remove PLAN.md from task descriptions (en, report/SKILL.md)",filenameSuffixes:["report/SKILL.md"],actionType:"replace",replacement:" and "},{pattern:/、`PLAN\.md` 和/,description:"Remove PLAN.md from task descriptions (zh, report/SKILL.md)",filenameSuffixes:["report/SKILL.md"],actionType:"replace",replacement:"\u548C"}],odo=kOe.map(e=>({pattern:e.pattern,description:e.description}));function wOe(e,t){let r=e.replace(/\\/g,"/");return r===t||r.endsWith("/"+t)}function IOe(e,t){if(e.length===0)return{migrated:e,changed:!1};let r=kOe.filter(p=>p.filenameSuffixes.some(h=>wOe(t,h)));if(r.length===0)return{migrated:e,changed:!1};let o=r.filter(p=>p.actionType==="remove-line"),n=r.filter(p=>p.actionType==="replace"),i=[],a=!1,s=e.split(`
|
|
1256
|
+
`).run(a??null,i);let h=c.prepare("SELECT id FROM pain_events WHERE canonical_pain_id = ?").get(i);return h&&typeof h=="object"&&Object.hasOwn(h,"id")&&typeof h.id=="number"?h.id:void 0}throw p}}finally{c.close()}}function pQ(e){let t=Klo(),r=[],o=e.data.score??80,n=e.data.sessionId??"cli",i=Hlo(t),a={warnings:r};try{let s=fk.join(e.stateDir,"logs",`events_${i}.jsonl`);WMt(s,{ts:t,date:i,type:"pain_signal",category:"detected",sessionId:n,workspaceDir:e.workspaceDir,data:{eventId:e.data.painId,score:o,source:e.data.source,reason:Lm(e.data.reason??"",e.workspaceDir),severity:jMt(o),origin:e.data.source==="manual"?"user_manual":"system_infer"}}),a.eventLogPath=s}catch(s){r.push(`event log write failed: ${s instanceof Error?s.message:String(s)}`)}try{let s=fk.join(e.workspaceDir,"memory","evolution.jsonl"),c={painId:e.data.painId,painType:e.data.painType,source:e.data.source,reason:Lm(e.data.reason??"",e.workspaceDir),score:e.data.score,sessionId:e.data.sessionId,provenance:e.data.provenance,evidenceCount:e.data.evidence?.length??0};WMt(s,{ts:t,type:"pain_detected",data:c}),a.evolutionStreamPath=s}catch(s){r.push(`evolution stream write failed: ${s instanceof Error?s.message:String(s)}`)}try{a.trajectoryPainEventId=Zlo({stateDir:e.stateDir,data:e.data,timestamp:t,workspaceDir:e.workspaceDir,canonicalPainId:e.canonicalPainId,runtimeTaskId:e.runtimeTaskId})}catch(s){r.push(`trajectory pain_events write failed: ${s instanceof Error?s.message:String(s)}`)}return a}function edo(e){if(e.errorCategory)return M2[e.errorCategory]??"runtime_unavailable";if(e.status==="failed"){if(e.candidateIds.length===0)return"candidate_missing";if(e.ledgerEntryIds.length===0)return"ledger_write_failed"}}function tdo(e){if(e instanceof wt&&e.category)return M2[e.category]??"runtime_unavailable";let t=e instanceof Error?e.message:String(e);return/api[_\s]?key|not found in env|missing required/i.test(t)?"config_missing":/timeout|timed[_\s]?out/i.test(t)?"runtime_timeout":/output.*invalid|validation.*fail/i.test(t)?"output_invalid":"runtime_unavailable"}var hk=class{opts;constructor(t){this.opts=t}async recordPain(t){let r=Date.now(),{painId:o}=t,n=t.taskId??H2(o),i={painId:o,painType:t.painType,source:t.source,reason:t.reason,score:t.score,sessionId:t.sessionId,agentId:t.agentId,taskId:n,traceId:t.traceId,provenance:t.provenance,evidence:t.evidence};try{if(this.opts.asyncMode){let m=await(await uQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,ledgerAdapter:this.opts.ledgerAdapter,owner:this.opts.owner,autoIntakeEnabled:!1,effectiveConfig:this.opts.effectiveConfig,getEnvVar:this.opts.getEnvVar,intentDocReader:this.opts.intentDocReader,trajectoryTurnReader:this.opts.trajectoryTurnReader})).submitPainSignal(i),p=[];t.recordObservability!==!1&&(p=pQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:i,canonicalPainId:o,runtimeTaskId:m.taskId}).warnings);let h=Date.now()-r;return{status:"submitted",painId:o,taskId:m.taskId,candidateIds:[],ledgerEntryIds:[],observabilityWarnings:p,latencyMs:h,message:`Diagnosis submitted. Use 'pd task show ${m.taskId}' to check progress.`}}let s=await(await uQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,ledgerAdapter:this.opts.ledgerAdapter,owner:this.opts.owner,autoIntakeEnabled:this.opts.autoIntakeEnabled,effectiveConfig:this.opts.effectiveConfig,getEnvVar:this.opts.getEnvVar,intentDocReader:this.opts.intentDocReader,trajectoryTurnReader:this.opts.trajectoryTurnReader})).onPainDetected(i),c=[];t.recordObservability!==!1&&(c=pQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:i,canonicalPainId:o,runtimeTaskId:n}).warnings);let u=Date.now()-r;return{status:s.status,painId:s.painId,taskId:s.taskId,runId:s.runId,artifactId:s.artifactId,candidateIds:s.candidateIds,ledgerEntryIds:s.ledgerEntryIds,admissionResults:s.admissionResults,message:s.message,observabilityWarnings:c,failureCategory:edo(s),latencyMs:u}}catch(a){let s=Date.now()-r;return{status:"failed",painId:o,taskId:n,candidateIds:[],ledgerEntryIds:[],message:a instanceof Error?a.message:String(a),observabilityWarnings:[],failureCategory:tdo(a),latencyMs:s}}}};var kOe=[{pattern:/Physical interception|physical blocking|物理拦截/i,description:"Remove Physical interception / physical blocking / \u7269\u7406\u62E6\u622A references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/Single source of truth.*PLAN/i,description:"Remove Single source of truth PLAN references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/PLAN\.md` \(status: READY\)|PLAN\.md`(状态:READY)/,description:"Remove PLAN.md status: READY references (AGENTS.md, THINKING_OS.md)",filenameSuffixes:["AGENTS.md","THINKING_OS.md"],actionType:"remove-line"},{pattern:/project physical plan|项目物理计划/i,description:"Remove project physical plan / \u9879\u76EE\u7269\u7406\u8BA1\u5212 references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/L2 delegation.*(PLAN|gate|blocking)|L2 委派.*(PLAN|gate|拦截)/i,description:"Remove L2 delegation / L2 \u59D4\u6D3E tied to PLAN.md gate enforcement (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/ or `PLAN\.md`/,description:'Replace "or PLAN.md" in T-02 PHYSICAL_MEMORY_PERSISTENCE (en)',filenameSuffixes:["THINKING_OS.md"],actionType:"replace",replacement:""},{pattern:/或 `PLAN\.md`/,description:'Replace "\u6216 PLAN.md" in T-02 PHYSICAL_MEMORY_PERSISTENCE (zh)',filenameSuffixes:["THINKING_OS.md"],actionType:"replace",replacement:""},{pattern:/PLAN\.md mechanism protects|PLAN\.md 机制保护/,description:"Remove PLAN.md mechanism protects / PLAN.md \u673A\u5236\u4FDD\u62A4 lines (MEMORY.md)",filenameSuffixes:["MEMORY.md"],actionType:"remove-line"},{pattern:/STATUS: READY|STATUS:READY/,description:"Remove STATUS: READY references (MEMORY.md)",filenameSuffixes:["MEMORY.md"],actionType:"remove-line"},{pattern:/Ensure `PLAN\.md` contains `## Target Files` heading|确保 `PLAN\.md` 包含 `## Target Files` 标题/,description:"Remove PLAN.md Target Files heading checks (admin/SKILL.md)",filenameSuffixes:["admin/SKILL.md"],actionType:"remove-line"},{pattern:/,\s*`PLAN\.md`\s*/,description:"Remove PLAN.md from list as trailing item (admin/SKILL.md, pd-grooming/SKILL.md)",filenameSuffixes:["admin/SKILL.md","pd-grooming/SKILL.md"],actionType:"replace",replacement:""},{pattern:/`PLAN\.md`\s*,\s*/,description:"Remove PLAN.md from list as leading item (admin/SKILL.md, pd-grooming/SKILL.md)",filenameSuffixes:["admin/SKILL.md","pd-grooming/SKILL.md"],actionType:"replace",replacement:""},{pattern:/Check `PLAN\.md` or early conversation/,description:"Replace Check PLAN.md or early conversation (en, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"Check early conversation context"},{pattern:/Update `PLAN\.md`/,description:"Replace Update PLAN.md with Update memory/.scratchpad.md (en, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"Update `memory/.scratchpad.md`"},{pattern:/检查 `PLAN\.md` 或早期对话/,description:"Replace Check PLAN.md or early conversation (zh, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"\u68C0\u67E5\u65E9\u671F\u5BF9\u8BDD\u4E0A\u4E0B\u6587"},{pattern:/更新 `PLAN\.md`/,description:"Replace Update PLAN.md (zh, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"\u66F4\u65B0 `memory/.scratchpad.md`"},{pattern:/, `PLAN\.md`, and /,description:"Remove PLAN.md from task descriptions (en, report/SKILL.md)",filenameSuffixes:["report/SKILL.md"],actionType:"replace",replacement:" and "},{pattern:/、`PLAN\.md` 和/,description:"Remove PLAN.md from task descriptions (zh, report/SKILL.md)",filenameSuffixes:["report/SKILL.md"],actionType:"replace",replacement:"\u548C"}],odo=kOe.map(e=>({pattern:e.pattern,description:e.description}));function wOe(e,t){let r=e.replace(/\\/g,"/");return r===t||r.endsWith("/"+t)}function IOe(e,t){if(e.length===0)return{migrated:e,changed:!1};let r=kOe.filter(p=>p.filenameSuffixes.some(h=>wOe(t,h)));if(r.length===0)return{migrated:e,changed:!1};let o=r.filter(p=>p.actionType==="remove-line"),n=r.filter(p=>p.actionType==="replace"),i=[],a=!1,s=e.split(`
|
|
1257
1257
|
`),c=[];for(let p of s){let h=!1;for(let f of o)if(f.pattern.test(p)){h=!0,i.includes(f.description)||i.push(f.description),wOe(t,"MEMORY.md")&&(a=!0);break}h||c.push(p)}let u=c.join(`
|
|
1258
1258
|
`);for(let p of n){let h=p.replacement??"",f=u,g=p.pattern.flags.includes("g")?p.pattern.flags:p.pattern.flags+"g",y=new RegExp(p.pattern.source,g);u=u.replace(y,h),u!==f&&!i.includes(p.description)&&i.push(p.description)}if(a){let p="[Historical: confirm-first gate was removed in PRI-286. This section is preserved for reference only.]";u.endsWith(`
|
|
1259
1259
|
`)||(u=u+`
|
|
@@ -2054,7 +2054,7 @@ ${o.join(`
|
|
|
2054
2054
|
`).replace(/\n{3,}/g,`
|
|
2055
2055
|
|
|
2056
2056
|
`).trim()}function lb(e,t){let r=[];if(!e.trajectory||t==="unknown")return r.push({sourceRef:"owner_message:unavailable",note:`trajectory_unavailable: ${e.trajectory?"unknown_session":"no_trajectory_db"}`}),r.slice(0,Ex);try{let n=[...e.trajectory.listUserTurnsForSession(t)??[]].reverse().find(i=>i.correctionDetected);if(n){let i=GD((n.rawExcerpt??"").slice(0,fR));r.push({sourceRef:`owner_message:${n.createdAt}`,note:i})}}catch(o){r.push({sourceRef:"owner_message:unavailable",note:`trajectory_user_turns_unavailable: ${String(o).slice(0,100)}`})}try{let n=(e.trajectory.listAssistantTurns(t)??[]).slice(-3);for(let i of n){if(r.length>=Ex)break;let a=GD((i.sanitizedText??"").slice(0,fR)),s=i.stopReason==="length"?" [TRUNCATED: output cut off by length limit]":"";r.push({sourceRef:`agent_turn:${i.createdAt}`,note:a+s})}}catch(o){r.length<Ex&&r.push({sourceRef:"agent_turn:unavailable",note:`trajectory_assistant_turns_unavailable: ${String(o).slice(0,100)}`})}try{let n=(e.trajectory.listToolCallsForSession(t)??[]).filter(i=>i.outcome==="failure").slice(-3);for(let i of n){if(r.length>=Ex)break;let a=i.resultPreview?` | ${i.resultPreview.slice(0,200)}`:"",s=`Tool ${i.toolName} failed: ${i.errorType??"unknown"} (exitCode: ${i.exitCode??"N/A"})${a}`;r.push({sourceRef:`tool_call_failure:${i.createdAt}`,note:GD(s.slice(0,fR))})}}catch(o){r.length===0&&r.push({sourceRef:"tool_call_failure:unavailable",note:`trajectory_tool_calls_unavailable: ${String(o).slice(0,100)}`})}return r.length===0&&r.push({sourceRef:"trajectory:empty",note:"trajectory_available_but_empty: no user correction or assistant turns found"}),r.slice(0,Ex)}var JD=500;function Rxr(e){if(e==null)return null;try{if(typeof e=="string")return e.length>JD?`${e.slice(0,JD-3)}...`:e;if(typeof e=="object"&&!Array.isArray(e)){let t=e;if(Array.isArray(t.content)){let o=[];for(let n of t.content)if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n;i.type==="text"&&typeof i.text=="string"&&o.push(i.text)}if(o.length>0){let n=o.join(`
|
|
2057
|
-
`);return n.length>JD?`${n.slice(0,JD-3)}...`:n}}let r=JSON.stringify(t,(o,n)=>{if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let i=Object.keys(n);if(i.length>10){let a={};for(let s of i.slice(0,10))a[s]=n[s];return a.__truncated__=!0,a}}return n},2);if(r&&r!=="{}")return r.length>JD?`${r.slice(0,JD-3)}...`:r}return null}catch{return"[result_preview_extraction_failed]"}}function wxr(e){let t=e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:null,r=t&&t.details&&typeof t.details=="object"&&!Array.isArray(t.details)?t.details:null,o=t?.exitCode,n=r?.exitCode,i=typeof o=="number"?o:typeof n=="number"?n:0,a=!!e.error||i!==0,s=ED({toolName:e.toolName,error:e.error,exitCode:i}),c=a?s.failureSource:void 0;return{isFailure:a,exitCode:i,failureSource:c}}function kxr(e,t,r,o){let n=e.params,i=n&&typeof n=="object"&&!Array.isArray(n)?n:{},a=i.file_path||i.path||i.file,s=typeof a=="string"?ryr(a,r):"unknown",c=gse(s,o.risk_paths),u;if(e.error)u=String(e.error);else if(typeof e.result=="string")u=e.result;else try{u=JSON.stringify(e.result)}catch{u=`[unserializable result: ${typeof e.result}]`}let l=sxr(u),m=WD(l),p=hxr(1,!1,!1,c?20:0,r);return{params:{filePath:a,content:i.content,text:i.text,newString:i.new_string,query:i.query,input:i.input,arguments:i.arguments},relPath:s,isRisk:c,errorType:mTn(e.error||u),errorHash:m,errorText:u,painScore:p,traceId:PI()}}function Ixr(e,t,r,o,n,i,a,s){let c=a.get("scores.tool_failure_friction")||30,u=LD(e,c,o.errorHash,i,{source:r.failureSource});return Txr(i,t.toolName,{filePath:o.relPath,reason:o.isRisk?"risky":"tool",sessionId:e}),s.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:o.params.filePath,error:t.error?String(t.error).substring(0,200):void 0,errorType:o.errorType,gfi:u.currentGfi,consecutiveErrors:u.consecutiveErrors,exitCode:r.exitCode,gfiBefore:n,gfiAfter:u.currentGfi}),s.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"failure",durationMs:t.durationMs,exitCode:r.exitCode,errorType:o.errorType,errorMessage:t.error?String(t.error):void 0,gfiBefore:n,gfiAfter:u.currentGfi,paramsJson:iqe(t.params,i),resultPreview:Rxr(t.result)}),u}function Cxr(e,t,r,o,n,i,a){let s=Sm(e),c=s?.gfiBySource?.tool_failure||0,u=s?.gfiBySource?.dispatch_error||0,l=s||xh(e,i);return c>0&&(l=xh(e,i,{source:"tool_failure",amount:c*.5})),u>0&&(l=xh(e,i,{source:"dispatch_error",amount:u*.5})),vxr(i,t.toolName,{sessionId:e,reason:"tool_success"}),a.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"success",durationMs:t.durationMs,exitCode:r.exitCode,gfiBefore:n,gfiAfter:l.currentGfi,paramsJson:iqe(t.params,i),resultPreview:Rxr(t.result)}),a.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:o.params.filePath,gfi:l.currentGfi,gfiBefore:n,gfiAfter:l.currentGfi}),l}function Axr(e,t,r){let o=typeof t.params.filePath=="string"?t.params.filePath.replace(/\\/g,"/"):"",n=/(?:^|\/)memory\//.test(o)||o.endsWith("/MEMORY.md")||o==="MEMORY.md",i=o==="PLAN.md"||o.endsWith("/PLAN.md");(n||i)&&r.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:t.params.filePath??"unknown",type:n?"memory":"plan",contentLength:t.params.content?.length??t.params.newString?.length??0}),e.toolName==="memory_store"&&r.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:"DATABASE",type:"memory",contentLength:t.params.text?.length??0})}function dTn(e,t){return e.contextTags.includes(t)||e.trigger.includes(t)}function aqe(e,t,r,o,n){let i=Nyr(e,r);for(let a of i){let s=o.evolutionReducer.getPrincipleById(a);s&&dTn(s,t)&&o.evolutionReducer.recordProbationFeedback(a,n)}rj(e,r)}var Exr=["write","edit","apply_patch","write_file","edit_file","replace"];function Oxr(e,t,r,o,n,i,a,s){let c=process.env.PD_E2E_MODE==="1";if(!(c?[...Exr,...lj]:Exr).includes(e.toolName)||!r.isFailure)return r.isFailure&&pr.log(a,"PAIN_ADMISSION_SKIPPED",JSON.stringify({hook:"after_tool_call",reason:"not_a_write_tool_failure",tool:e.toolName,failureSource:r.failureSource,sessionId:i,nextAction:"No pain task created; failure is outside write-tool admission scope. Retry or investigate if unexpected."})),{admitted:!1,stage:"not_applicable",reason:"not_a_write_tool_failure",detail:`tool=${e.toolName}, isFailure=${r.isFailure}`};let l=r.failureSource??"tool_failure",m=IE(l,i,o?.lastErrorHash),p={observedAt:new Date().toISOString(),workspaceId:a,sessionId:i,toolName:e.toolName,failureSource:r.failureSource,toolNotFound:r.failureSource==="dispatch_error",nonZeroExit:r.exitCode!==0},h=Ky(p),f=(o??n)?.consecutiveErrors,g=c?Math.max(4,f??0):f,y=AE(h,t.painScore,{consecutiveErrors:g,isRisky:t.isRisk}),T=Hy({triageResult:y,isOwnerManual:!1,isCooldownActive:m,isValid:!0,score:t.painScore,sessionId:i});return pr.log(a,"TRIGGER_DECISION",JSON.stringify({outcome:T.outcome,sourceKind:T.sourceKind,reason:T.reason,nextAction:T.nextAction,triageDecision:T.triageDecision,tool:e.toolName,path:t.relPath})),T.shouldCreateDiagnosticTask?(CE(l,i,o?.lastErrorHash),{admitted:!0,stage:"trigger_admitted",reason:T.reason,detail:`outcome=${T.outcome}, sourceKind=${T.sourceKind}, nextAction=${T.nextAction}`}):{admitted:!1,stage:"trigger_rejected",reason:T.reason,detail:`outcome=${T.outcome}, sourceKind=${T.sourceKind}, nextAction=${T.nextAction}`}}function Pxr(e,t,r,o,n,i,a,s,c){if(!n.admitted)return;let u=o.failureSource??"tool_failure",l=`pain_${Date.now()}_${r.errorHash.slice(0,8)}`;e.trajectory?.recordPainEvent({sessionId:i,source:u,score:r.painScore,reason:`Tool ${t.toolName} failed on ${r.relPath}`,severity:r.painScore>=70?"severe":r.painScore>=40?"moderate":"mild",origin:"system_infer",text:Yse(r.params.text??r.params.content,s)||void 0,canonicalPainId:l});try{gxr(s,{reason:`Tool ${t.toolName} failed on ${r.relPath}. Error: ${t.error??"Non-zero exit code"}`,source:u,score:String(r.painScore)},()=>e.evolutionReducer.getActivePrinciples().map(p=>({id:p.id,trigger:p.trigger,valueMetrics:p.valueMetrics})),(p,h)=>{let f=e.evolutionReducer.getPrincipleById(p);if(f){f.valueMetrics=h;try{e.principleTreeLedger.updatePrincipleValueMetrics(p,{principleId:p,painPreventedCount:h.painPreventedCount,lastPainPreventedAt:h.lastPainPreventedAt,calculatedAt:h.calculatedAt,avgPainSeverityPrevented:0,totalOpportunities:0,adheredCount:0,violatedCount:0,implementationCost:0,benefitScore:0})}catch(g){pr.log(s,"METRICS_UPDATE_SKIP",String(g))}}})}catch(p){pr.log(s,"PRINCIPLE_TRACK_SKIP",String(p))}e.eventLog.recordPainSignal(i,{score:r.painScore,source:u,reason:`Tool ${t.toolName} failed on ${r.relPath}`,isRisky:r.isRisk}),Jse(s,e.trajectory).logPainDetected({traceId:r.traceId,source:u,reason:`Tool ${t.toolName} failed on ${r.relPath}`,score:r.painScore,toolName:t.toolName,filePath:r.relPath,sessionId:i}),c(e,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:l,painType:u,source:t.toolName,reason:`Tool ${t.toolName} failed on ${r.relPath}; diagnosticGate=${n.reason}`,score:r.painScore,sessionId:i,traceId:r.traceId,agentId:a,provenance:"automatic_hook",evidence:lb(e,i)}},{recordObservability:!1})}function mTn(e){if(!e)return"Unknown";let t=String(e);return t.includes("EACCES")||t.includes("permission denied")?"EACCES":t.includes("ENOENT")||t.includes("no such file")?"ENOENT":t.includes("EISDIR")?"EISDIR":t.includes("ENOSPC")?"ENOSPC":t.includes("SyntaxError")?"SyntaxError":t.includes("TypeError")?"TypeError":t.includes("ReferenceError")?"ReferenceError":t.includes("timeout")||t.includes("ETIMEDOUT")?"Timeout":t.includes("network")||t.includes("ECONNREFUSED")?"Network":"Other"}function fTn(e){let t=new oT({stateDir:e.stateDir}),r=Pp(e.workspaceDir);return new hk({workspaceDir:e.workspaceDir,stateDir:e.stateDir,ledgerAdapter:t,owner:"openclaw-plugin",autoIntakeEnabled:!0,effectiveConfig:r.effective,getEnvVar:o=>process.env[o],intentDocReader:Gse(e.workspaceDir,FD(e.workspaceDir))})}async function ll(e,t,r){try{e.evolutionReducer.emitSync(t)}catch(o){pr.log(e.workspaceDir,"EVOLUTION_EMIT_WARN",`Failed to emit evolution event: ${String(o)}`)}if(t.type==="pain_detected"){let o=t.data;try{let n=fTn(e);(o.source==="manual"||o.source==="pain"||o.source==="skill:pain")&&pr.log(e.workspaceDir,"TRIGGER_DECISION",JSON.stringify({outcome:"manual_owner_admitted",sourceKind:"owner_reported",reason:"Owner explicit manual pain. Bypasses triage and cooldown.",nextAction:"create_diagnostic_task",painId:o.painId,score:o.score}));let a=r?.recordObservability??!0,s=await n.recordPain({painId:o.painId,painType:o.painType,source:o.source,reason:o.reason,score:o.score,sessionId:o.sessionId,agentId:o.agentId,taskId:o.taskId,traceId:o.traceId,provenance:o.provenance,evidence:o.evidence,recordObservability:a});s.status==="failed"&&s.failureCategory?pr.log(e.workspaceDir,"PAIN_SERVICE_FAILED",JSON.stringify({painId:s.painId,taskId:s.taskId,failureCategory:s.failureCategory,latencyMs:s.latencyMs,message:s.message})):s.status==="skipped"&&pr.log(e.workspaceDir,"PAIN_SERVICE_SKIPPED",JSON.stringify({painId:s.painId,taskId:s.taskId,latencyMs:s.latencyMs,message:s.message}))}catch(n){pr.log(e.workspaceDir,"PAIN_SERVICE_ERROR",`recordPain threw: ${String(n)}`);let i=n instanceof Error?n.message:String(n),a=!1;try{let s=new Tl({workspaceDir:e.workspaceDir});try{let u=new D4(s).insertDeadLetter({painId:o.painId,painData:o});u.ok?a=!0:pr.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",u.error)}finally{s.close()}}catch(s){pr.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",String(s))}pr.log(e.workspaceDir,"PAIN_DEAD_LETTER",JSON.stringify({painId:o.painId,painType:o.painType,source:o.source,score:o.score,deadLetterInserted:a,error:i,nextAction:`Run 'pd pain retry --pain-id ${o.painId}' to replay this pain signal`}))}}}function hTn(e){return`pain_${Date.now()}_${WD(e).slice(0,8)}`}function Nxr(e,t,r){let o;try{o=lxr(t,r,"after_tool_call")}catch(g){pr.log(t.workspaceDir??"unknown","WORKSPACE_RESOLUTION_FAILED",JSON.stringify({hook:"after_tool_call",sessionId:t.sessionId??"unknown",toolName:e.toolName,reason:"workspace_resolution_failed",nextAction:"check_plugin_config_workspace_resolution",error:String(g).slice(0,200)}));return}let n=no.fromHookContextExplicit({...t,workspaceDir:o}),{config:i}=n,a=t.sessionId||"unknown",s=t.sessionId?Sm(t.sessionId):void 0,c=s?.currentGfi??0,u=n.resolve("PROFILE"),l=qD({});if(Qse.existsSync(u))try{let g=Qse.readFileSync(u,"utf8");g.length>1024*1024?pr.log(o,"PROFILE_PARSE_WARN","PROFILE.json exceeds 1 MB, skipping"):l=qD(JSON.parse(g))}catch(g){pr.log(o,"PROFILE_PARSE_WARN",`Failed to parse PROFILE.json: ${String(g)}`)}if(e.toolName==="pain"||e.toolName==="skill:pain"){gTn(e,t,n,o,a);return}let m=wxr(e),p=kxr(e,m,o,l),h;m.isFailure?(h=Ixr(a,e,m,p,c,o,i,n),aqe(a,e.toolName,o,n,!1)):(Cxr(a,e,m,p,c,o,n),aqe(a,e.toolName,o,n,!0),Axr(e,p,n));let f=Oxr(e,p,m,h,s,a,o,i);f.stage!=="not_applicable"&&Pxr(n,e,p,m,f,a,t.agentId,o,ll)}function gTn(e,t,r,o,n){let i=e.params,a=i&&typeof i=="object"&&!Array.isArray(i)?i:{},s=a.input||a.arguments||"Manual intervention",c=PI();LD(n,100,"manual_pain",o,{source:"manual_pain"}),pr.log(o,"MANUAL_PAIN",`User manually triggered pain: ${s}`),r.eventLog.recordPainSignal(n,{score:100,source:"manual",reason:`User intervention: ${s}`,isRisky:!0});let u=hTn(n);r.trajectory?.recordPainEvent?.({sessionId:n,source:"manual",score:100,reason:`User intervention: ${s}`,origin:"user_manual",text:s,canonicalPainId:u}),Jse(o,r.trajectory).logPainDetected({traceId:c,source:"manual",reason:`User intervention: ${s}`,score:100,toolName:e.toolName,sessionId:n});let m=ru(o,"painEvidenceAdmission"),p=ru(o,"painEvidenceAdmissionDefault");if(m.enabled&&p.enabled){let f=N4({sessionId:n}),g=Ky(f),y=AE(g,100),T=IE(g,n,"manual_pain"),v=Hy({triageResult:y,isOwnerManual:!0,isCooldownActive:T,isValid:!0,score:100,sessionId:n});Pp(o).effective&&pr.log(o,"TRIGGER_DECISION",JSON.stringify({outcome:v.outcome,sourceKind:v.sourceKind,reason:v.reason,nextAction:v.nextAction,isOwnerManual:!0,sessionId:n,score:100})),v.shouldCreateDiagnosticTask?(CE(g,n,"manual_pain"),ll(r,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:u,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:n,traceId:c,agentId:t.agentId,provenance:n&&n!=="unknown"?"openclaw_context_bound":"owner_reported_no_host_trace",evidence:lb(r,n)}},{recordObservability:!1})):pr.log(o,"MANUAL_PAIN_SKIPPED",v.reason)}else{let f=Sm(n),g=jD({source:"manual",score:100,currentGfi:f?.currentGfi??0,sessionId:n});if(!g.shouldDiagnose){pr.log(o,"MANUAL_PAIN_SKIPPED",`Manual pain within cooldown: ${g.detail}`);let y;try{y=JSON.stringify({reason:g.reason,detail:g.detail,source:"manual",sessionId:n,gfi:0,score:100})}catch(v){pr.log(o,"PAYLOAD_SERIALIZE_FAILED",String(v)),y=JSON.stringify({reason:g.reason,detail:"(log serialization failed)"})}pr.log(o,"PAIN_GATE_REJECTED",y),Pp(o).effective&&pr.log(o,"TRIGGER_DECISION",JSON.stringify({outcome:"cooldown_skipped",sourceKind:"owner_reported",reason:`Manual pain within cooldown: ${g.detail}`,nextAction:"wait_for_cooldown_or_manual_retrigger",isOwnerManual:!0,sessionId:n,score:100}));return}ll(r,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:u,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:n,traceId:c,agentId:t.agentId,provenance:n&&n!=="unknown"?"openclaw_context_bound":"owner_reported_no_host_trace",evidence:lb(r,n)}},{recordObservability:!1})}}var yTn={enableLlmStage:!0,llmTimeoutMs:3e4,promptTemplate:"",strongPainScore:70,strongRateLimitPerHour:5};function sqe(e){return e==="user"||e==="api"||e===void 0}function xTn(){return{version:1,terms:{\u8FD9\u662F\u9519\u7684:{term:"\u8FD9\u662F\u9519\u7684",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u8981\u81EA\u4F5C\u4E3B\u5F20:{term:"\u4E0D\u8981\u81EA\u4F5C\u4E3B\u5F20",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u5E94\u8BE5\u8FD9\u4E48\u505A:{term:"\u4E0D\u5E94\u8BE5\u8FD9\u4E48\u505A",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u5BF9:{term:"\u4E0D\u5BF9",category:"correction",weight:.5,precision:"ambiguous",source:"seed"},\u9519\u4E86:{term:"\u9519\u4E86",category:"correction",weight:.5,precision:"ambiguous",source:"seed"},\u641E\u4EC0\u4E48:{term:"\u641E\u4EC0\u4E48",category:"empathy",weight:.5,precision:"ambiguous",source:"seed"}}}}var bTn=3600*1e3,Zse=class{wctx;store;config;llmClassifier;rateLimit=new Map;constructor(t,r={}){this.wctx=t,this.store=r.keywordStore??xTn(),this.config=r.config??yTn,this.llmClassifier=r.llmClassifier??null}detectSync(t,r,o,n){if(!sqe(o))return;let i=new Date().toISOString(),a=sse(t,r,this.store,this.config,i),s={sessionId:r,turnIndex:n?.turnIndex??Date.now(),rawText:t,correctionDetected:a.isSignal&&a.strength==="STRONG",correctionCue:a.matchedTerms.length>0?a.matchedTerms.join(", "):null,referencesAssistantTurnId:n?.referencesAssistantTurnId??null};try{this.wctx.trajectory?.recordUserTurn?.(s)}catch(c){pr.log(this.wctx.workspaceDir,"SIGNAL_TRAJECTORY_FAIL",`recordUserTurn threw: ${String(c)}`)}if(a.isSignal&&a.strength==="STRONG"&&a.matchedPrecision==="high"){this.routeStrong(a,r);return}if(a.needsLlmConfirmation){let c={output:a,sessionId:r,text:t,traceId:PI()};this.detectAsyncAndRoute(c)}}async detectAsyncAndRoute(t){let r;if(this.llmClassifier&&this.config.enableLlmStage){let o=null;try{o=await this.llmClassifier(t.text,this.config.promptTemplate)}catch(i){pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL",`LLM classifier threw: ${String(i)}`)}let n=new Date().toISOString();o?r=F4(o,t.text,t.sessionId,this.config,n):(pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL","LLM returned invalid result, treating as none"),r=F4({is_feedback:!1,type:"none",confidence:1,reason:"LLM parse failed"},t.text,t.sessionId,this.config,n))}else{if(t.output.matchedPrecision==="ambiguous"&&t.output.matchedTerms.length>0&&t.output.matchedTerms.some(n=>this.store.terms[n]?.category==="empathy")){pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED_WEAK","LLM unavailable, routing empathy ambiguous as WEAK (GFI accumulation, no STRONG trigger)");let n={...t.output,isSignal:!0,type:"empathy",strength:"WEAK",detectionSource:"keyword",needsLlmConfirmation:!1};this.routeWeak(n,t.sessionId);return}pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED","LLM unavailable, dropping candidate (no STRONG trigger)");return}r.isSignal&&r.strength==="STRONG"?this.routeStrong(r,t.sessionId):r.isSignal&&r.strength==="WEAK"&&this.routeWeak(r,t.sessionId)}routeStrong(t,r){if(!this.tryConsumeRateLimit(r)){pr.log(this.wctx.workspaceDir,"SIGNAL_STRONG_RATE_LIMITED","STRONG signal suppressed by rate limit");return}let o=t.llmReason||(t.matchedTerms.length>0?`User correction detected: ${t.matchedTerms.join(", ")}`:"User correction detected");ll(this.wctx,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:`correction_${PI()}`,painType:"user_frustration",source:"user_correction",reason:o,score:this.config.strongPainScore,sessionId:r,agentId:"main",provenance:"openclaw_context_bound",evidence:[{sourceRef:"signal_collector",note:t.evidence.excerpt}]}},{recordObservability:!0}).catch(n=>{pr.log(this.wctx.workspaceDir,"SIGNAL_EMIT_FAIL",`emitPainDetectedEvent failed: ${String(n)}`)})}routeWeak(t,r){try{let o=_Tn("sha256").update(`${t.evidence.detectedAt}:${r}`).digest("hex").slice(0,32);LD(r,20,o,this.wctx.workspaceDir,{source:"user_empathy"})}catch(o){pr.log(this.wctx.workspaceDir,"SIGNAL_TRACK_FRICTION_FAIL",`trackFriction threw: ${String(o)}`)}}tryConsumeRateLimit(t){let r=this.config.strongRateLimitPerHour,o=Date.now(),n=this.rateLimit.get(t);return(!n||o-n.windowStart>=bTn)&&(n={count:0,windowStart:o},this.rateLimit.set(t,n)),n.count>=r?!1:(n.count+=1,!0)}};function Mxr(e,t){try{let r=W4(e.workspaceDir,"signal_collector","signalCollector",t);if(!r.enabled)return t?.debug?.(`[PD:Signal] LLM classifier disabled: ${r.reason}`),null;if(r.readiness!=="not_ready"&&r.readiness!=="ready")return t?.debug?.(`[PD:Signal] LLM classifier not ready (${r.readiness}): ${r.reason}. ${r.nextAction}`),null;if(!r.provider||!r.model||!r.apiKeyEnv)return t?.debug?.("[PD:Signal] LLM classifier missing provider/model/apiKeyEnv"),null;let o=new nm({provider:r.provider,model:r.model,apiKeyEnv:r.apiKeyEnv,timeoutMs:r.timeoutMs??3e4,baseUrl:r.baseUrl??void 0,workspace:e.workspaceDir});return async(i,a)=>{let s=nse(i);try{let c=await o.startRun({agentSpec:{agentId:"signal-collector",schemaVersion:"1"},inputPayload:{prompt:s},contextItems:[],timeoutMs:r.timeoutMs??3e4}),u=await o.pollRun(c.runId),l=Date.now()+(r.timeoutMs??3e4);for(;u.status==="running"&&Date.now()<l;)await new Promise(g=>setTimeout(g,500)),u=await o.pollRun(c.runId);if(u.status!=="succeeded")return pr.log(e.workspaceDir,"SIGNAL_LLM_TIMEOUT",JSON.stringify({status:u.status})),null;let p=(await o.fetchOutput(c.runId))?.payload,h="";if(typeof p=="string")h=p;else if(typeof p=="object"&&p!==null&&Object.hasOwn(p,"output")){let g=p.output;typeof g=="string"&&(h=g)}let f=ise(h);return f.valid?f.value:null}catch(c){return pr.log(e.workspaceDir,"SIGNAL_LLM_FAILED",String(c).slice(0,200)),null}}}catch(r){return t?.warn?.(`[PD:Signal] createSignalLlmClassifierFromConfig failed: ${String(r)}`),null}}var STn=6e4,Lxr=new Map,vTn=256,cqe=new Map;function TTn(e,t){if(Object.hasOwn(e,t))return Object.getOwnPropertyDescriptor(e,t)?.value}function ETn(e){if(typeof e!="object"||e===null)return;let t=TTn(e,"code");return typeof t=="string"?t:void 0}function RTn(e){let t=Lxr.get(e);return t||(t=new Map,Lxr.set(e,t)),t}function $xr(e,t){return typeof e!="object"||e===null||!Object.hasOwn(e,"role")?!1:Object.getOwnPropertyDescriptor(e,"role")?.value===t}function wTn(e,t,r){let o=e.trajectory?.listUserTurnsForSession?.(t)??[];return o.length>0?o.reduce((n,i)=>Math.max(n,i.turnIndex),0)+1:r.filter(n=>$xr(n,"user")).length+1}function kTn(e,t,r){let o=cqe.get(e);o||(o=new Set,cqe.set(e,o));let n=`${t}\0${r}`;if(o.has(n))return!1;if(o.add(n),o.size>vTn){let i=o.values().next().value;typeof i=="string"&&o.delete(i)}return!0}function ITn(e,t,r){return cqe.get(e)?.has(`${t}\0${r}`)??!1}function CTn(e,t){let r=RTn(t),o=Date.now(),n=r.get(e);try{let a=NI.statSync(e).mtimeMs;if(n&&o-n.loadedAt<STn&&n.mtime===a)return n.content;let s=NI.readFileSync(e,"utf8");return r.set(e,{content:s,mtime:a,loadedAt:o}),s}catch(i){return r.delete(e),ETn(i)!=="ENOENT"&&console.warn(`[PD:Prompt] cachedReadFile failed: path=${e}, workspace=${t}, error=${String(i)}`),""}}var Dxr=new Map;function ATn(e,t){let r=Dxr.get(e.workspaceDir);if(!r){let o=Mxr(e,t);r=new Zse(e,{llmClassifier:o}),Dxr.set(e.workspaceDir,r)}return r}function MI(e){return{...Pp(e).effective.resolvedContextInjection}}async function zxr(e,t){let{workspaceDir:r}=t,o=t.api?.logger;if(o?.info?.(`[PD:Prompt] handleBeforePromptBuild called: workspaceDir=${!!r}, trigger=${t.trigger}, sessionId=${t.sessionId?.substring(0,20)}`),!r){o?.warn?.("[PD:Prompt] workspaceDir is missing \u2014 skipping PD context injection");return}let n=no.fromHookContext(t),{runId:i,sessionKey:a,trigger:s,sessionId:c}=t,u=sqe(s),l=t.api;c&&n.trajectory?.recordSession?.({sessionId:c});let m=null;if(c&&u&&e.messages.some($t=>$xr($t,"assistant"))){let $t=n.trajectory?.listAssistantTurns?.(c)??[];m=$t[$t.length-1]?.id??null}let p=MI(n.workspaceDir),h=Dse(s,c),f=c?Sm(c):void 0,g,y="",T="";s==="user"&&c&&f&&f.currentGfi>=100&&xh(c,r),g=exr();let v=txr(),{message:E,isAgentToAgent:L}=Zyr(e.prompt,c),H=!1;if(u&&c&&l&&!L&&(H=!0),E&&c&&u&&!L&&(i&&ITn(n.workspaceDir,a??c,i)?o?.info?.(`[PD:Prompt] duplicate signal run skipped: runId=${i}, sessionId=${c.substring(0,20)}`):(i||o?.warn?.(`[PD:Prompt] runId missing; signal collection cannot be deduplicated: sessionId=${c.substring(0,20)}`),ATn(n,o).detectSync(E,c,s??"api",{referencesAssistantTurnId:m,turnIndex:wTn(n,c,e.messages)}),i&&kTn(n.workspaceDir,a??c,i))),s==="heartbeat"||s==="cron"){if(c){let fr=Dyr(c);if(fr>=1){let Ot=Lyr(c,fr);Ot&&o?.info?.(`[PD:GFI] Heartbeat decay applied: ${fr}min elapsed, GFI now ${Ot.currentGfi.toFixed(1)}`)}}let $t=n.resolve("HEARTBEAT");if(NI.existsSync($t))try{let fr=NI.readFileSync($t,"utf8");y+=rxr(fr)}catch(fr){o?.error(`[PD:Prompt] Failed to read HEARTBEAT: ${String(fr)}`)}}let B="";try{let $t=n.evolutionReducer.getActivePrinciples();$t.length>0&&(B=oxr($t))}catch($t){o?.warn?.(`[PD:Prompt] Failed to load core principles from reducer: ${String($t)}`)}let Te="";if(p.thinkingOs){let $t=n.resolve("THINKING_OS");try{let fr=CTn($t,n.workspaceDir);fr&&(Te=fr.trim())}catch(fr){o?.error(`[PD:Prompt] Failed to read THINKING_OS: ${String(fr)}`)}}let Ce="",ye="";if(!h&&p.projectFocus!=="off"){let $t=n.resolve("CURRENT_FOCUS"),fr=_h.getExtensionRoot(),{content:Ot,recovered:vr,validationErrors:Zr}=Xyr($t,fr||"",o);if(vr&&o?.info?.("[PD:Prompt] CURRENT_FOCUS.md was recovered from template"),Zr.length>0&&o?.warn?.(`[PD:Prompt] CURRENT_FOCUS validation errors: ${Zr.join(", ")}`),Ot.trim())try{let{stateDir:Di}=n,aa=Hyr($t,r,Di);aa.compressed?o?.info?.(`[PD:Prompt] Auto-compressed CURRENT_FOCUS: ${aa.oldLines} \u2192 ${aa.newLines} lines. Milestones archived: ${aa.milestonesArchived}`):aa.reason==="Rate limited (24h interval)"&&o?.debug?.(`[PD:Prompt] Auto-compress skipped: ${aa.reason}`);let mr=aa.newContent?.trim()||Ot.trim();if(mr){let Eo=ij(mr);if(Eo&&(ye=aj(Eo)),p.projectFocus==="summary")Ce=$D(mr,30);else{let fn=await Vyr($t,3);if(fn.length>0){let au=fn.map((ai,Ji)=>`
|
|
2057
|
+
`);return n.length>JD?`${n.slice(0,JD-3)}...`:n}}let r=JSON.stringify(t,(o,n)=>{if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let i=Object.keys(n);if(i.length>10){let a={};for(let s of i.slice(0,10))a[s]=n[s];return a.__truncated__=!0,a}}return n},2);if(r&&r!=="{}")return r.length>JD?`${r.slice(0,JD-3)}...`:r}return null}catch{return"[result_preview_extraction_failed]"}}function wxr(e){let t=e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:null,r=t&&t.details&&typeof t.details=="object"&&!Array.isArray(t.details)?t.details:null,o=t?.exitCode,n=r?.exitCode,i=typeof o=="number"?o:typeof n=="number"?n:0,a=!!e.error||i!==0,s=ED({toolName:e.toolName,error:e.error,exitCode:i}),c=a?s.failureSource:void 0;return{isFailure:a,exitCode:i,failureSource:c}}function kxr(e,t,r,o){let n=e.params,i=n&&typeof n=="object"&&!Array.isArray(n)?n:{},a=i.file_path||i.path||i.file,s=typeof a=="string"?ryr(a,r):"unknown",c=gse(s,o.risk_paths),u;if(e.error)u=String(e.error);else if(typeof e.result=="string")u=e.result;else try{u=JSON.stringify(e.result)}catch{u=`[unserializable result: ${typeof e.result}]`}let l=sxr(u),m=WD(l),p=hxr(1,!1,!1,c?20:0,r);return{params:{filePath:a,content:i.content,text:i.text,newString:i.new_string,query:i.query,input:i.input,arguments:i.arguments},relPath:s,isRisk:c,errorType:mTn(e.error||u),errorHash:m,errorText:u,painScore:p,traceId:PI()}}function Ixr(e,t,r,o,n,i,a,s){let c=a.get("scores.tool_failure_friction")||30,u=LD(e,c,o.errorHash,i,{source:r.failureSource});return Txr(i,t.toolName,{filePath:o.relPath,reason:o.isRisk?"risky":"tool",sessionId:e}),s.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:o.params.filePath,error:t.error?String(t.error).substring(0,200):void 0,errorType:o.errorType,gfi:u.currentGfi,consecutiveErrors:u.consecutiveErrors,exitCode:r.exitCode,gfiBefore:n,gfiAfter:u.currentGfi}),s.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"failure",durationMs:t.durationMs,exitCode:r.exitCode,errorType:o.errorType,errorMessage:t.error?String(t.error):void 0,gfiBefore:n,gfiAfter:u.currentGfi,paramsJson:iqe(t.params,i),resultPreview:Rxr(t.result)}),u}function Cxr(e,t,r,o,n,i,a){let s=Sm(e),c=s?.gfiBySource?.tool_failure||0,u=s?.gfiBySource?.dispatch_error||0,l=s||xh(e,i);return c>0&&(l=xh(e,i,{source:"tool_failure",amount:c*.5})),u>0&&(l=xh(e,i,{source:"dispatch_error",amount:u*.5})),vxr(i,t.toolName,{sessionId:e,reason:"tool_success"}),a.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"success",durationMs:t.durationMs,exitCode:r.exitCode,gfiBefore:n,gfiAfter:l.currentGfi,paramsJson:iqe(t.params,i),resultPreview:Rxr(t.result)}),a.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:o.params.filePath,gfi:l.currentGfi,gfiBefore:n,gfiAfter:l.currentGfi}),l}function Axr(e,t,r){let o=typeof t.params.filePath=="string"?t.params.filePath.replace(/\\/g,"/"):"",n=/(?:^|\/)memory\//.test(o)||o.endsWith("/MEMORY.md")||o==="MEMORY.md",i=o==="PLAN.md"||o.endsWith("/PLAN.md");(n||i)&&r.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:t.params.filePath??"unknown",type:n?"memory":"plan",contentLength:t.params.content?.length??t.params.newString?.length??0}),e.toolName==="memory_store"&&r.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:"DATABASE",type:"memory",contentLength:t.params.text?.length??0})}function dTn(e,t){return e.contextTags.includes(t)||e.trigger.includes(t)}function aqe(e,t,r,o,n){let i=Nyr(e,r);for(let a of i){let s=o.evolutionReducer.getPrincipleById(a);s&&dTn(s,t)&&o.evolutionReducer.recordProbationFeedback(a,n)}rj(e,r)}var Exr=["write","edit","apply_patch","write_file","edit_file","replace"];function Oxr(e,t,r,o,n,i,a,s){let c=process.env.PD_E2E_MODE==="1";if(!(c?[...Exr,...lj]:Exr).includes(e.toolName)||!r.isFailure)return r.isFailure&&pr.log(a,"PAIN_ADMISSION_SKIPPED",JSON.stringify({hook:"after_tool_call",reason:"not_a_write_tool_failure",tool:e.toolName,failureSource:r.failureSource,sessionId:i,nextAction:"No pain task created; failure is outside write-tool admission scope. Retry or investigate if unexpected."})),{admitted:!1,stage:"not_applicable",reason:"not_a_write_tool_failure",detail:`tool=${e.toolName}, isFailure=${r.isFailure}`};let l=r.failureSource??"tool_failure",m=IE(l,i,o?.lastErrorHash),p={observedAt:new Date().toISOString(),workspaceId:a,sessionId:i,toolName:e.toolName,failureSource:r.failureSource,toolNotFound:r.failureSource==="dispatch_error",nonZeroExit:r.exitCode!==0},h=Ky(p),f=(o??n)?.consecutiveErrors,g=c?Math.max(4,f??0):f,y=AE(h,t.painScore,{consecutiveErrors:g,isRisky:t.isRisk}),T=Hy({triageResult:y,isOwnerManual:!1,isCooldownActive:m,isValid:!0,score:t.painScore,sessionId:i});return pr.log(a,"TRIGGER_DECISION",JSON.stringify({outcome:T.outcome,sourceKind:T.sourceKind,reason:T.reason,nextAction:T.nextAction,triageDecision:T.triageDecision,tool:e.toolName,path:t.relPath})),T.shouldCreateDiagnosticTask?(CE(l,i,o?.lastErrorHash),{admitted:!0,stage:"trigger_admitted",reason:T.reason,detail:`outcome=${T.outcome}, sourceKind=${T.sourceKind}, nextAction=${T.nextAction}`}):{admitted:!1,stage:"trigger_rejected",reason:T.reason,detail:`outcome=${T.outcome}, sourceKind=${T.sourceKind}, nextAction=${T.nextAction}`}}function Pxr(e,t,r,o,n,i,a,s,c){if(!n.admitted)return;let u=o.failureSource??"tool_failure",l=`pain_${Date.now()}_${r.errorHash.slice(0,8)}`;e.trajectory?.recordPainEvent({sessionId:i,source:u,score:r.painScore,reason:`Tool ${t.toolName} failed on ${r.relPath}`,severity:r.painScore>=70?"severe":r.painScore>=40?"moderate":"mild",origin:"system_infer",text:Yse(r.params.text??r.params.content,s)||void 0,canonicalPainId:l});try{gxr(s,{reason:`Tool ${t.toolName} failed on ${r.relPath}. Error: ${t.error??"Non-zero exit code"}`,source:u,score:String(r.painScore)},()=>e.evolutionReducer.getActivePrinciples().map(p=>({id:p.id,trigger:p.trigger,valueMetrics:p.valueMetrics})),(p,h)=>{let f=e.evolutionReducer.getPrincipleById(p);if(f){f.valueMetrics=h;try{e.principleTreeLedger.updatePrincipleValueMetrics(p,{principleId:p,painPreventedCount:h.painPreventedCount,lastPainPreventedAt:h.lastPainPreventedAt,calculatedAt:h.calculatedAt,avgPainSeverityPrevented:0,totalOpportunities:0,adheredCount:0,violatedCount:0,implementationCost:0,benefitScore:0})}catch(g){pr.log(s,"METRICS_UPDATE_SKIP",String(g))}}})}catch(p){pr.log(s,"PRINCIPLE_TRACK_SKIP",String(p))}e.eventLog.recordPainSignal(i,{score:r.painScore,source:u,reason:`Tool ${t.toolName} failed on ${r.relPath}`,isRisky:r.isRisk}),Jse(s,e.trajectory).logPainDetected({traceId:r.traceId,source:u,reason:`Tool ${t.toolName} failed on ${r.relPath}`,score:r.painScore,toolName:t.toolName,filePath:r.relPath,sessionId:i}),c(e,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:l,painType:u,source:t.toolName,reason:`Tool ${t.toolName} failed on ${r.relPath}; diagnosticGate=${n.reason}`,score:r.painScore,sessionId:i,traceId:r.traceId,agentId:a,provenance:"automatic_hook",evidence:lb(e,i)}},{recordObservability:!1})}function mTn(e){if(!e)return"Unknown";let t=String(e);return t.includes("EACCES")||t.includes("permission denied")?"EACCES":t.includes("ENOENT")||t.includes("no such file")?"ENOENT":t.includes("EISDIR")?"EISDIR":t.includes("ENOSPC")?"ENOSPC":t.includes("SyntaxError")?"SyntaxError":t.includes("TypeError")?"TypeError":t.includes("ReferenceError")?"ReferenceError":t.includes("timeout")||t.includes("ETIMEDOUT")?"Timeout":t.includes("network")||t.includes("ECONNREFUSED")?"Network":"Other"}function fTn(e){let t=new oT({stateDir:e.stateDir}),r=Pp(e.workspaceDir),o={listUserTurnsForSession:n=>e.trajectory.listUserTurnsForSession(n),listAssistantTurns:n=>e.trajectory.listAssistantTurns(n)};return new hk({workspaceDir:e.workspaceDir,stateDir:e.stateDir,ledgerAdapter:t,owner:"openclaw-plugin",autoIntakeEnabled:!0,effectiveConfig:r.effective,getEnvVar:n=>process.env[n],intentDocReader:Gse(e.workspaceDir,FD(e.workspaceDir)),trajectoryTurnReader:o})}async function ll(e,t,r){try{e.evolutionReducer.emitSync(t)}catch(o){pr.log(e.workspaceDir,"EVOLUTION_EMIT_WARN",`Failed to emit evolution event: ${String(o)}`)}if(t.type==="pain_detected"){let o=t.data;try{let n=fTn(e);(o.source==="manual"||o.source==="pain"||o.source==="skill:pain")&&pr.log(e.workspaceDir,"TRIGGER_DECISION",JSON.stringify({outcome:"manual_owner_admitted",sourceKind:"owner_reported",reason:"Owner explicit manual pain. Bypasses triage and cooldown.",nextAction:"create_diagnostic_task",painId:o.painId,score:o.score}));let a=r?.recordObservability??!0,s=await n.recordPain({painId:o.painId,painType:o.painType,source:o.source,reason:o.reason,score:o.score,sessionId:o.sessionId,agentId:o.agentId,taskId:o.taskId,traceId:o.traceId,provenance:o.provenance,evidence:o.evidence,recordObservability:a});s.status==="failed"&&s.failureCategory?pr.log(e.workspaceDir,"PAIN_SERVICE_FAILED",JSON.stringify({painId:s.painId,taskId:s.taskId,failureCategory:s.failureCategory,latencyMs:s.latencyMs,message:s.message})):s.status==="skipped"&&pr.log(e.workspaceDir,"PAIN_SERVICE_SKIPPED",JSON.stringify({painId:s.painId,taskId:s.taskId,latencyMs:s.latencyMs,message:s.message}))}catch(n){pr.log(e.workspaceDir,"PAIN_SERVICE_ERROR",`recordPain threw: ${String(n)}`);let i=n instanceof Error?n.message:String(n),a=!1;try{let s=new Tl({workspaceDir:e.workspaceDir});try{let u=new D4(s).insertDeadLetter({painId:o.painId,painData:o});u.ok?a=!0:pr.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",u.error)}finally{s.close()}}catch(s){pr.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",String(s))}pr.log(e.workspaceDir,"PAIN_DEAD_LETTER",JSON.stringify({painId:o.painId,painType:o.painType,source:o.source,score:o.score,deadLetterInserted:a,error:i,nextAction:`Run 'pd pain retry --pain-id ${o.painId}' to replay this pain signal`}))}}}function hTn(e){return`pain_${Date.now()}_${WD(e).slice(0,8)}`}function Nxr(e,t,r){let o;try{o=lxr(t,r,"after_tool_call")}catch(g){pr.log(t.workspaceDir??"unknown","WORKSPACE_RESOLUTION_FAILED",JSON.stringify({hook:"after_tool_call",sessionId:t.sessionId??"unknown",toolName:e.toolName,reason:"workspace_resolution_failed",nextAction:"check_plugin_config_workspace_resolution",error:String(g).slice(0,200)}));return}let n=no.fromHookContextExplicit({...t,workspaceDir:o}),{config:i}=n,a=t.sessionId||"unknown",s=t.sessionId?Sm(t.sessionId):void 0,c=s?.currentGfi??0,u=n.resolve("PROFILE"),l=qD({});if(Qse.existsSync(u))try{let g=Qse.readFileSync(u,"utf8");g.length>1024*1024?pr.log(o,"PROFILE_PARSE_WARN","PROFILE.json exceeds 1 MB, skipping"):l=qD(JSON.parse(g))}catch(g){pr.log(o,"PROFILE_PARSE_WARN",`Failed to parse PROFILE.json: ${String(g)}`)}if(e.toolName==="pain"||e.toolName==="skill:pain"){gTn(e,t,n,o,a);return}let m=wxr(e),p=kxr(e,m,o,l),h;m.isFailure?(h=Ixr(a,e,m,p,c,o,i,n),aqe(a,e.toolName,o,n,!1)):(Cxr(a,e,m,p,c,o,n),aqe(a,e.toolName,o,n,!0),Axr(e,p,n));let f=Oxr(e,p,m,h,s,a,o,i);f.stage!=="not_applicable"&&Pxr(n,e,p,m,f,a,t.agentId,o,ll)}function gTn(e,t,r,o,n){let i=e.params,a=i&&typeof i=="object"&&!Array.isArray(i)?i:{},s=a.input||a.arguments||"Manual intervention",c=PI();LD(n,100,"manual_pain",o,{source:"manual_pain"}),pr.log(o,"MANUAL_PAIN",`User manually triggered pain: ${s}`),r.eventLog.recordPainSignal(n,{score:100,source:"manual",reason:`User intervention: ${s}`,isRisky:!0});let u=hTn(n);r.trajectory?.recordPainEvent?.({sessionId:n,source:"manual",score:100,reason:`User intervention: ${s}`,origin:"user_manual",text:s,canonicalPainId:u}),Jse(o,r.trajectory).logPainDetected({traceId:c,source:"manual",reason:`User intervention: ${s}`,score:100,toolName:e.toolName,sessionId:n});let m=ru(o,"painEvidenceAdmission"),p=ru(o,"painEvidenceAdmissionDefault");if(m.enabled&&p.enabled){let f=N4({sessionId:n}),g=Ky(f),y=AE(g,100),T=IE(g,n,"manual_pain"),v=Hy({triageResult:y,isOwnerManual:!0,isCooldownActive:T,isValid:!0,score:100,sessionId:n});Pp(o).effective&&pr.log(o,"TRIGGER_DECISION",JSON.stringify({outcome:v.outcome,sourceKind:v.sourceKind,reason:v.reason,nextAction:v.nextAction,isOwnerManual:!0,sessionId:n,score:100})),v.shouldCreateDiagnosticTask?(CE(g,n,"manual_pain"),ll(r,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:u,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:n,traceId:c,agentId:t.agentId,provenance:n&&n!=="unknown"?"openclaw_context_bound":"owner_reported_no_host_trace",evidence:lb(r,n)}},{recordObservability:!1})):pr.log(o,"MANUAL_PAIN_SKIPPED",v.reason)}else{let f=Sm(n),g=jD({source:"manual",score:100,currentGfi:f?.currentGfi??0,sessionId:n});if(!g.shouldDiagnose){pr.log(o,"MANUAL_PAIN_SKIPPED",`Manual pain within cooldown: ${g.detail}`);let y;try{y=JSON.stringify({reason:g.reason,detail:g.detail,source:"manual",sessionId:n,gfi:0,score:100})}catch(v){pr.log(o,"PAYLOAD_SERIALIZE_FAILED",String(v)),y=JSON.stringify({reason:g.reason,detail:"(log serialization failed)"})}pr.log(o,"PAIN_GATE_REJECTED",y),Pp(o).effective&&pr.log(o,"TRIGGER_DECISION",JSON.stringify({outcome:"cooldown_skipped",sourceKind:"owner_reported",reason:`Manual pain within cooldown: ${g.detail}`,nextAction:"wait_for_cooldown_or_manual_retrigger",isOwnerManual:!0,sessionId:n,score:100}));return}ll(r,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:u,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:n,traceId:c,agentId:t.agentId,provenance:n&&n!=="unknown"?"openclaw_context_bound":"owner_reported_no_host_trace",evidence:lb(r,n)}},{recordObservability:!1})}}var yTn={enableLlmStage:!0,llmTimeoutMs:3e4,promptTemplate:"",strongPainScore:70,strongRateLimitPerHour:5};function sqe(e){return e==="user"||e==="api"||e===void 0}function xTn(){return{version:1,terms:{\u8FD9\u662F\u9519\u7684:{term:"\u8FD9\u662F\u9519\u7684",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u8981\u81EA\u4F5C\u4E3B\u5F20:{term:"\u4E0D\u8981\u81EA\u4F5C\u4E3B\u5F20",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u5E94\u8BE5\u8FD9\u4E48\u505A:{term:"\u4E0D\u5E94\u8BE5\u8FD9\u4E48\u505A",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u5BF9:{term:"\u4E0D\u5BF9",category:"correction",weight:.5,precision:"ambiguous",source:"seed"},\u9519\u4E86:{term:"\u9519\u4E86",category:"correction",weight:.5,precision:"ambiguous",source:"seed"},\u641E\u4EC0\u4E48:{term:"\u641E\u4EC0\u4E48",category:"empathy",weight:.5,precision:"ambiguous",source:"seed"}}}}var bTn=3600*1e3,Zse=class{wctx;store;config;llmClassifier;rateLimit=new Map;constructor(t,r={}){this.wctx=t,this.store=r.keywordStore??xTn(),this.config=r.config??yTn,this.llmClassifier=r.llmClassifier??null}detectSync(t,r,o,n){if(!sqe(o))return;let i=new Date().toISOString(),a=sse(t,r,this.store,this.config,i),s={sessionId:r,turnIndex:n?.turnIndex??Date.now(),rawText:t,correctionDetected:a.isSignal&&a.strength==="STRONG",correctionCue:a.matchedTerms.length>0?a.matchedTerms.join(", "):null,referencesAssistantTurnId:n?.referencesAssistantTurnId??null};try{this.wctx.trajectory?.recordUserTurn?.(s)}catch(c){pr.log(this.wctx.workspaceDir,"SIGNAL_TRAJECTORY_FAIL",`recordUserTurn threw: ${String(c)}`)}if(a.isSignal&&a.strength==="STRONG"&&a.matchedPrecision==="high"){this.routeStrong(a,r);return}if(a.needsLlmConfirmation){let c={output:a,sessionId:r,text:t,traceId:PI()};this.detectAsyncAndRoute(c)}}async detectAsyncAndRoute(t){let r;if(this.llmClassifier&&this.config.enableLlmStage){let o=null;try{o=await this.llmClassifier(t.text,this.config.promptTemplate)}catch(i){pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL",`LLM classifier threw: ${String(i)}`)}let n=new Date().toISOString();o?r=F4(o,t.text,t.sessionId,this.config,n):(pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL","LLM returned invalid result, treating as none"),r=F4({is_feedback:!1,type:"none",confidence:1,reason:"LLM parse failed"},t.text,t.sessionId,this.config,n))}else{if(t.output.matchedPrecision==="ambiguous"&&t.output.matchedTerms.length>0&&t.output.matchedTerms.some(n=>this.store.terms[n]?.category==="empathy")){pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED_WEAK","LLM unavailable, routing empathy ambiguous as WEAK (GFI accumulation, no STRONG trigger)");let n={...t.output,isSignal:!0,type:"empathy",strength:"WEAK",detectionSource:"keyword",needsLlmConfirmation:!1};this.routeWeak(n,t.sessionId);return}pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED","LLM unavailable, dropping candidate (no STRONG trigger)");return}r.isSignal&&r.strength==="STRONG"?this.routeStrong(r,t.sessionId):r.isSignal&&r.strength==="WEAK"&&this.routeWeak(r,t.sessionId)}routeStrong(t,r){if(!this.tryConsumeRateLimit(r)){pr.log(this.wctx.workspaceDir,"SIGNAL_STRONG_RATE_LIMITED","STRONG signal suppressed by rate limit");return}let o=t.llmReason||(t.matchedTerms.length>0?`User correction detected: ${t.matchedTerms.join(", ")}`:"User correction detected");ll(this.wctx,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:`correction_${PI()}`,painType:"user_frustration",source:"user_correction",reason:o,score:this.config.strongPainScore,sessionId:r,agentId:"main",provenance:"openclaw_context_bound",evidence:[{sourceRef:"signal_collector",note:t.evidence.excerpt}]}},{recordObservability:!0}).catch(n=>{pr.log(this.wctx.workspaceDir,"SIGNAL_EMIT_FAIL",`emitPainDetectedEvent failed: ${String(n)}`)})}routeWeak(t,r){try{let o=_Tn("sha256").update(`${t.evidence.detectedAt}:${r}`).digest("hex").slice(0,32);LD(r,20,o,this.wctx.workspaceDir,{source:"user_empathy"})}catch(o){pr.log(this.wctx.workspaceDir,"SIGNAL_TRACK_FRICTION_FAIL",`trackFriction threw: ${String(o)}`)}}tryConsumeRateLimit(t){let r=this.config.strongRateLimitPerHour,o=Date.now(),n=this.rateLimit.get(t);return(!n||o-n.windowStart>=bTn)&&(n={count:0,windowStart:o},this.rateLimit.set(t,n)),n.count>=r?!1:(n.count+=1,!0)}};function Mxr(e,t){try{let r=W4(e.workspaceDir,"signal_collector","signalCollector",t);if(!r.enabled)return t?.debug?.(`[PD:Signal] LLM classifier disabled: ${r.reason}`),null;if(r.readiness!=="not_ready"&&r.readiness!=="ready")return t?.debug?.(`[PD:Signal] LLM classifier not ready (${r.readiness}): ${r.reason}. ${r.nextAction}`),null;if(!r.provider||!r.model||!r.apiKeyEnv)return t?.debug?.("[PD:Signal] LLM classifier missing provider/model/apiKeyEnv"),null;let o=new nm({provider:r.provider,model:r.model,apiKeyEnv:r.apiKeyEnv,timeoutMs:r.timeoutMs??3e4,baseUrl:r.baseUrl??void 0,workspace:e.workspaceDir});return async(i,a)=>{let s=nse(i);try{let c=await o.startRun({agentSpec:{agentId:"signal-collector",schemaVersion:"1"},inputPayload:{prompt:s},contextItems:[],timeoutMs:r.timeoutMs??3e4}),u=await o.pollRun(c.runId),l=Date.now()+(r.timeoutMs??3e4);for(;u.status==="running"&&Date.now()<l;)await new Promise(g=>setTimeout(g,500)),u=await o.pollRun(c.runId);if(u.status!=="succeeded")return pr.log(e.workspaceDir,"SIGNAL_LLM_TIMEOUT",JSON.stringify({status:u.status})),null;let p=(await o.fetchOutput(c.runId))?.payload,h="";if(typeof p=="string")h=p;else if(typeof p=="object"&&p!==null&&Object.hasOwn(p,"output")){let g=p.output;typeof g=="string"&&(h=g)}let f=ise(h);return f.valid?f.value:null}catch(c){return pr.log(e.workspaceDir,"SIGNAL_LLM_FAILED",String(c).slice(0,200)),null}}}catch(r){return t?.warn?.(`[PD:Signal] createSignalLlmClassifierFromConfig failed: ${String(r)}`),null}}var STn=6e4,Lxr=new Map,vTn=256,cqe=new Map;function TTn(e,t){if(Object.hasOwn(e,t))return Object.getOwnPropertyDescriptor(e,t)?.value}function ETn(e){if(typeof e!="object"||e===null)return;let t=TTn(e,"code");return typeof t=="string"?t:void 0}function RTn(e){let t=Lxr.get(e);return t||(t=new Map,Lxr.set(e,t)),t}function $xr(e,t){return typeof e!="object"||e===null||!Object.hasOwn(e,"role")?!1:Object.getOwnPropertyDescriptor(e,"role")?.value===t}function wTn(e,t,r){let o=e.trajectory?.listUserTurnsForSession?.(t)??[];return o.length>0?o.reduce((n,i)=>Math.max(n,i.turnIndex),0)+1:r.filter(n=>$xr(n,"user")).length+1}function kTn(e,t,r){let o=cqe.get(e);o||(o=new Set,cqe.set(e,o));let n=`${t}\0${r}`;if(o.has(n))return!1;if(o.add(n),o.size>vTn){let i=o.values().next().value;typeof i=="string"&&o.delete(i)}return!0}function ITn(e,t,r){return cqe.get(e)?.has(`${t}\0${r}`)??!1}function CTn(e,t){let r=RTn(t),o=Date.now(),n=r.get(e);try{let a=NI.statSync(e).mtimeMs;if(n&&o-n.loadedAt<STn&&n.mtime===a)return n.content;let s=NI.readFileSync(e,"utf8");return r.set(e,{content:s,mtime:a,loadedAt:o}),s}catch(i){return r.delete(e),ETn(i)!=="ENOENT"&&console.warn(`[PD:Prompt] cachedReadFile failed: path=${e}, workspace=${t}, error=${String(i)}`),""}}var Dxr=new Map;function ATn(e,t){let r=Dxr.get(e.workspaceDir);if(!r){let o=Mxr(e,t);r=new Zse(e,{llmClassifier:o}),Dxr.set(e.workspaceDir,r)}return r}function MI(e){return{...Pp(e).effective.resolvedContextInjection}}async function zxr(e,t){let{workspaceDir:r}=t,o=t.api?.logger;if(o?.info?.(`[PD:Prompt] handleBeforePromptBuild called: workspaceDir=${!!r}, trigger=${t.trigger}, sessionId=${t.sessionId?.substring(0,20)}`),!r){o?.warn?.("[PD:Prompt] workspaceDir is missing \u2014 skipping PD context injection");return}let n=no.fromHookContext(t),{runId:i,sessionKey:a,trigger:s,sessionId:c}=t,u=sqe(s),l=t.api;c&&n.trajectory?.recordSession?.({sessionId:c});let m=null;if(c&&u&&e.messages.some($t=>$xr($t,"assistant"))){let $t=n.trajectory?.listAssistantTurns?.(c)??[];m=$t[$t.length-1]?.id??null}let p=MI(n.workspaceDir),h=Dse(s,c),f=c?Sm(c):void 0,g,y="",T="";s==="user"&&c&&f&&f.currentGfi>=100&&xh(c,r),g=exr();let v=txr(),{message:E,isAgentToAgent:L}=Zyr(e.prompt,c),H=!1;if(u&&c&&l&&!L&&(H=!0),E&&c&&u&&!L&&(i&&ITn(n.workspaceDir,a??c,i)?o?.info?.(`[PD:Prompt] duplicate signal run skipped: runId=${i}, sessionId=${c.substring(0,20)}`):(i||o?.warn?.(`[PD:Prompt] runId missing; signal collection cannot be deduplicated: sessionId=${c.substring(0,20)}`),ATn(n,o).detectSync(E,c,s??"api",{referencesAssistantTurnId:m,turnIndex:wTn(n,c,e.messages)}),i&&kTn(n.workspaceDir,a??c,i))),s==="heartbeat"||s==="cron"){if(c){let fr=Dyr(c);if(fr>=1){let Ot=Lyr(c,fr);Ot&&o?.info?.(`[PD:GFI] Heartbeat decay applied: ${fr}min elapsed, GFI now ${Ot.currentGfi.toFixed(1)}`)}}let $t=n.resolve("HEARTBEAT");if(NI.existsSync($t))try{let fr=NI.readFileSync($t,"utf8");y+=rxr(fr)}catch(fr){o?.error(`[PD:Prompt] Failed to read HEARTBEAT: ${String(fr)}`)}}let B="";try{let $t=n.evolutionReducer.getActivePrinciples();$t.length>0&&(B=oxr($t))}catch($t){o?.warn?.(`[PD:Prompt] Failed to load core principles from reducer: ${String($t)}`)}let Te="";if(p.thinkingOs){let $t=n.resolve("THINKING_OS");try{let fr=CTn($t,n.workspaceDir);fr&&(Te=fr.trim())}catch(fr){o?.error(`[PD:Prompt] Failed to read THINKING_OS: ${String(fr)}`)}}let Ce="",ye="";if(!h&&p.projectFocus!=="off"){let $t=n.resolve("CURRENT_FOCUS"),fr=_h.getExtensionRoot(),{content:Ot,recovered:vr,validationErrors:Zr}=Xyr($t,fr||"",o);if(vr&&o?.info?.("[PD:Prompt] CURRENT_FOCUS.md was recovered from template"),Zr.length>0&&o?.warn?.(`[PD:Prompt] CURRENT_FOCUS validation errors: ${Zr.join(", ")}`),Ot.trim())try{let{stateDir:Di}=n,aa=Hyr($t,r,Di);aa.compressed?o?.info?.(`[PD:Prompt] Auto-compressed CURRENT_FOCUS: ${aa.oldLines} \u2192 ${aa.newLines} lines. Milestones archived: ${aa.milestonesArchived}`):aa.reason==="Rate limited (24h interval)"&&o?.debug?.(`[PD:Prompt] Auto-compress skipped: ${aa.reason}`);let mr=aa.newContent?.trim()||Ot.trim();if(mr){let Eo=ij(mr);if(Eo&&(ye=aj(Eo)),p.projectFocus==="summary")Ce=$D(mr,30);else{let fn=await Vyr($t,3);if(fn.length>0){let au=fn.map((ai,Ji)=>`
|
|
2058
2058
|
---
|
|
2059
2059
|
|
|
2060
2060
|
**\u5386\u53F2\u7248\u672C v${fn.length-Ji}**
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles. Stop correcting the same AI behavior across sessions.",
|
|
5
|
-
"version": "1.197.
|
|
5
|
+
"version": "1.197.13",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onCapabilities": [
|
|
8
8
|
"hook"
|
package/openclaw.plugin.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles. Stop correcting the same AI behavior across sessions.",
|
|
5
|
-
"version": "1.197.
|
|
5
|
+
"version": "1.197.13",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onCapabilities": [
|
|
8
8
|
"hook"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "principles-disciple",
|
|
3
|
-
"version": "1.197.
|
|
3
|
+
"version": "1.197.13",
|
|
4
4
|
"description": "Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles. Stop correcting the same AI behavior across sessions.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|