principles-disciple 3.1.2 → 3.1.4
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 +2 -2
- package/dist/openclaw.plugin.json +5 -1
- package/openclaw.plugin.json +5 -1
- package/package.json +8 -8
package/dist/bundle.js
CHANGED
|
@@ -1192,7 +1192,7 @@ ${a}${s}`}buildPrompt(t,n={}){let{outputLanguage:r}=n,i=this.buildRouterInstruct
|
|
|
1192
1192
|
${i}
|
|
1193
1193
|
|
|
1194
1194
|
Received arguments:
|
|
1195
|
-
${JSON.stringify(t.arguments,null,2)}`;throw new Error(o)}t1();Ct();Ct();var Z0n={name:"AWS credentials or bearer token",login:async e=>{e.signal.throwIfAborted();let t=await e.prompt({type:"select",message:"Select Amazon Bedrock authentication method:",options:[{id:"bearer-token",label:"Bearer token"},{id:"aws-profile",label:"AWS profile"},{id:"credential-chain",label:"Existing AWS credential chain"}]});if(e.signal.throwIfAborted(),t==="bearer-token")return{type:"api_key",key:await e.prompt({type:"secret",message:"Enter Amazon Bedrock bearer token"})};if(e.notify({type:"info",message:"Amazon Bedrock supports AWS profiles, IAM credentials, and role-based credentials.",links:[{label:"AWS credential provider chain",url:"https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html"}]}),t==="aws-profile")return{type:"api_key",env:{AWS_PROFILE:await e.prompt({type:"text",message:"Enter AWS profile name"})}};if(t!=="credential-chain")throw new Error(`Unknown Amazon Bedrock auth method: ${t}`);return await e.prompt({type:"text",message:"Configure AWS credentials, then press Enter to continue"}),{type:"api_key"}},resolve:async({ctx:e,credential:t,signal:n})=>{let r=async i=>{n.throwIfAborted();let o=await e.env(i);return n.throwIfAborted(),o};if(t?.key)return{auth:{apiKey:t.key},env:t.env,source:"stored credential"};if(await r("AWS_BEARER_TOKEN_BEDROCK"))return{auth:{},source:"AWS_BEARER_TOKEN_BEDROCK"};if(t?.env?.AWS_PROFILE??await r("AWS_PROFILE"))return{auth:{},env:t?.env,source:t?.env?.AWS_PROFILE?"stored credential":"AWS_PROFILE"};if(await r("AWS_ACCESS_KEY_ID")&&await r("AWS_SECRET_ACCESS_KEY"))return{auth:{},source:"AWS access keys"};if(await r("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"))return{auth:{},source:"ECS task role"};if(await r("AWS_CONTAINER_CREDENTIALS_FULL_URI"))return{auth:{},source:"ECS task role"};if(await r("AWS_WEB_IDENTITY_TOKEN_FILE"))return{auth:{},source:"web identity token"}}};function Git(){return Ye({id:"amazon-bedrock",name:"Amazon Bedrock",auth:{apiKey:Z0n},models:Object.values(I3),api:F8()})}Ct();function qit(){return Ye({id:"ant-ling",name:"Ant Ling",baseUrl:"https://api.ant-ling.com/v1",auth:{apiKey:ot("Ant Ling API key",["ANT_LING_API_KEY"])},models:Object.values(E3),api:xt()})}var e_n=function(e,t){return typeof e=="string"&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(n,r,i,o,a){return r?t?".jsx":".js":i&&(!o||!a)?n:i+o+"."+a.toLowerCase()+"js"}):e},gy=e=>{let t=import.meta.url.endsWith(".js")?e.replace(/\.ts$/,".js"):e;return import(e_n(t))},Ps;var Kit=async()=>Ps?Ps.anthropic():(await gy("./anthropic.ts")).anthropicOAuth,Vit=async()=>Ps?Ps.openaiCodex():(await gy("./openai-codex.ts")).openaiCodexOAuth,zit=async()=>Ps?Ps.openaiChatGPT():(await gy("./openai-chatgpt.ts")).openaiChatGPTOAuth,Yit=async()=>Ps?Ps.githubCopilot():(await gy("./github-copilot.ts")).githubCopilotOAuth,Jit=async()=>Ps?Ps.openrouter():(await gy("./openrouter.ts")).openRouterOAuth,Xit=async()=>Ps?Ps.kimiCoding():(await gy("./kimi-coding.ts")).kimiCodingOAuth,Zit=async()=>Ps?Ps.meta():(await gy("./meta.ts")).metaOAuth,eot=async()=>Ps?Ps.xai():(await gy("./xai.ts")).xaiOAuth,tot=async e=>Ps?Ps.radius(e):(await gy("./radius.ts")).createRadiusOAuth(e);t1();Ct();function t_n(){return{name:"Anthropic API key",login:async e=>{e.signal.throwIfAborted();let t=await e.prompt({type:"secret",message:"Enter Anthropic API key"});return e.signal.throwIfAborted(),{type:"api_key",key:t}},resolve:async({ctx:e,credential:t,signal:n})=>{if(n.throwIfAborted(),t?.key)return{auth:{apiKey:t.key},env:t.env,source:"stored credential"};let r=await e.env(e1);if(n.throwIfAborted(),r)return{auth:{headers:{Authorization:`Bearer ${r}`}},source:e1};for(let o of[Jse,Xse]){let a=await e.env(o);if(n.throwIfAborted(),a)return{auth:{apiKey:a},source:o}}let i={};for(let o of[X4,Z4,tq]){let a=await e.env(o);if(n.throwIfAborted(),!a)return;i[o]=a}for(let o of[eq,nq]){let a=await e.env(o);n.throwIfAborted(),a&&(i[o]=a)}return{auth:{},env:i,source:"workload identity federation"}}}}function not(){return Ye({id:"anthropic",name:"Anthropic",baseUrl:"https://api.anthropic.com",auth:{apiKey:t_n(),oauth:Ts({name:"Anthropic (Claude Pro/Max)",isSubscription:!0,load:Kit})},models:Object.values(w3),api:go()})}wpe();rd();Ct();function rot(e,t){return{...e,baseUrl:xpe(e,t)}}function iot(e,t){let n=L8(e,t);return n===e.id?t:{...t,onPayload:async(r,i)=>{let o={...r,model:n};return await t?.onPayload?.(o,i)??o}}}function n_n(e){return{stream:(t,n,r)=>pp(t,async()=>e.stream(rot(t,r),n,iot(t,r))),streamSimple:(t,n,r)=>pp(t,async()=>e.streamSimple(rot(t,r),n,iot(t,r)))}}function oot(){return Ye({id:"azure",name:"Azure",auth:{apiKey:ot("Azure OpenAI API key",["AZURE_OPENAI_API_KEY"])},models:Object.values(S3),api:{"azure-openai-responses":B8(),"openai-completions":n_n(xt())}})}Ct();function aot(){return Ye({id:"baseten",name:"Baseten",baseUrl:"https://inference.baseten.co/v1",auth:{apiKey:ot("Baseten API key",["BASETEN_API_KEY"])},models:Object.values(k3),api:xt()})}Ct();function sot(){return Ye({id:"cerebras",name:"Cerebras",baseUrl:"https://api.cerebras.ai/v1",auth:{apiKey:ot("Cerebras API key",["CEREBRAS_API_KEY"])},models:Object.values(T3),api:xt()})}Ct();var H0e="CLOUDFLARE_API_KEY",r_n="CLOUDFLARE_ACCOUNT_ID",i_n="CLOUDFLARE_GATEWAY_ID";async function $0e(e,t,n,r){let i=n?e===H0e?n.key:n.env?.[e]:void 0;if(i!==void 0)return i;r.throwIfAborted();let o=await t.env(e);return r.throwIfAborted(),o}async function cot(e,t,n,r){let i=await $0e(H0e,t,n,r),o=await $0e(r_n,t,n,r),a=e==="ai-gateway"?await $0e(i_n,t,n,r):void 0;if(!(!i||!o||e==="ai-gateway"&&!a))return{apiKey:i,env:{CLOUDFLARE_ACCOUNT_ID:o,...a?{CLOUDFLARE_GATEWAY_ID:a}:{}},source:n?"stored credential":H0e}}function uot(){return{name:"Cloudflare API key",login:async e=>{let t=await e.prompt({type:"secret",message:"Enter Cloudflare API key"}),n=await e.prompt({type:"text",message:"Enter Cloudflare account ID"});return{type:"api_key",key:t,env:{CLOUDFLARE_ACCOUNT_ID:n}}},resolve:async({ctx:e,credential:t,signal:n})=>{let r=await cot("workers-ai",e,t,n);if(r)return{auth:{apiKey:r.apiKey},env:r.env,source:r.source}}}}function lot(){return{name:"Cloudflare API key",login:async e=>{let t=await e.prompt({type:"secret",message:"Enter Cloudflare API key"}),n=await e.prompt({type:"text",message:"Enter Cloudflare account ID"}),r=await e.prompt({type:"text",message:"Enter Cloudflare AI Gateway ID"});return{type:"api_key",key:t,env:{CLOUDFLARE_ACCOUNT_ID:n,CLOUDFLARE_GATEWAY_ID:r}}},resolve:async({ctx:e,credential:t,signal:n})=>{let r=await cot("ai-gateway",e,t,n);if(r)return{auth:{headers:{"cf-aig-authorization":`Bearer ${r.apiKey}`,Authorization:null,"x-api-key":null}},env:r.env,source:r.source}}}}var j0e="CLOUDFLARE_ACCOUNT_ID",G0e="CLOUDFLARE_GATEWAY_ID";function q0e(e,t){if(!t)return e;let n=e.baseUrl.replaceAll(`{${j0e}}`,t[j0e]??`{${j0e}}`).replaceAll(`{${G0e}}`,t[G0e]??`{${G0e}}`);return n===e.baseUrl?e:{...e,baseUrl:n}}function kD(e){return{stream:(t,n,r)=>e.stream(q0e(t,r?.env),n,r),streamSimple:(t,n,r)=>e.streamSimple(q0e(t,r?.env),n,r)}}function dot(e){return{classify:(t,n,r)=>e.classify(q0e(t,r?.env),n,r)}}function pot(){return Ye({id:"cloudflare-ai-gateway",name:"Cloudflare AI Gateway",auth:{apiKey:lot()},models:Object.values(D3),api:{"anthropic-messages":kD(go()),"openai-completions":kD(xt()),"openai-responses":kD(Nc())}})}var got=()=>({classify:async(e,t,n)=>(await Promise.resolve().then(()=>(hot(),mot))).classify(e,t,n)});Ct();function Aot(){return Ye({id:"cloudflare-workers-ai",name:"Cloudflare Workers AI",auth:{apiKey:uot()},models:[...Object.values(L3),...Object.values(bAe)],api:kD(xt()),classifiers:{"cloudflare-workers-ai-system-one":dot(got())}})}Ct();function yot(){return Ye({id:"deepseek",name:"DeepSeek",baseUrl:"https://api.deepseek.com",auth:{apiKey:ot("DeepSeek API key",["DEEPSEEK_API_KEY"])},models:Object.values(M3),api:xt()})}Ct();function _ot(){return Ye({id:"fireworks",name:"Fireworks",baseUrl:"https://api.fireworks.ai/inference",auth:{apiKey:ot("Fireworks API key",["FIREWORKS_API_KEY"])},models:Object.values(F3),api:{"anthropic-messages":go(),"openai-completions":xt()}})}Ct();function Iot(){return Ye({id:"github-copilot",name:"GitHub Copilot",baseUrl:"https://api.individual.githubcopilot.com",auth:{apiKey:ot("GitHub Copilot token",["COPILOT_GITHUB_TOKEN"]),oauth:Ts({name:"GitHub Copilot",isSubscription:!0,load:Yit})},models:Object.values(Q3),filterModels:(e,t)=>{if(t?.type!=="oauth")return e;let n=t.availableModelIds;if(!Array.isArray(n)||!n.every(i=>typeof i=="string"))return e;let r=new Set(n);return e.filter(i=>r.has(i.id))},api:{"anthropic-messages":go(),"openai-completions":xt(),"openai-responses":Nc()}})}Ct();function vot(){return Ye({id:"google",name:"Google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",auth:{apiKey:ot("Gemini API key",["GEMINI_API_KEY"])},models:Object.values($3),api:qO()})}Ct();var m_n="~/.config/gcloud/application_default_credentials.json",h_n={name:"Google Cloud credentials",login:async e=>{e.signal.throwIfAborted();let t=await e.prompt({type:"select",message:"Select Google Vertex AI authentication method:",options:[{id:"api-key",label:"Google Cloud API key"},{id:"adc",label:"Application Default Credentials"},{id:"service-account",label:"Service account credentials file"}]});if(e.signal.throwIfAborted(),t==="api-key")return{type:"api_key",key:await e.prompt({type:"secret",message:"Enter Google Cloud API key"})};if(t!=="adc"&&t!=="service-account")throw new Error(`Unknown Google Vertex AI auth method: ${t}`);e.notify({type:"info",message:t==="adc"?"Run `gcloud auth application-default login`, then provide the project and location.":"Provide a service account credentials file, project, and location.",links:[{label:"Application Default Credentials",url:"https://cloud.google.com/docs/authentication/provide-credentials-adc"}]});let n=await e.prompt({type:"text",message:"Enter Google Cloud project ID"}),r=await e.prompt({type:"text",message:"Enter Google Cloud location"}),i=t==="service-account"?await e.prompt({type:"text",message:"Enter service account credentials file path"}):void 0;return{type:"api_key",env:{GOOGLE_CLOUD_PROJECT:n,GOOGLE_CLOUD_LOCATION:r,...i?{GOOGLE_APPLICATION_CREDENTIALS:i}:{}}}},resolve:async({ctx:e,credential:t,signal:n})=>{let r=async u=>{n.throwIfAborted();let l=await e.env(u);return n.throwIfAborted(),l},i=t?.key??await r("GOOGLE_CLOUD_API_KEY");if(i)return{auth:{apiKey:i},source:t?.key?"stored credential":"GOOGLE_CLOUD_API_KEY"};let o=t?.env?.GOOGLE_APPLICATION_CREDENTIALS??await r("GOOGLE_APPLICATION_CREDENTIALS");n.throwIfAborted();let a=await e.fileExists(o??m_n);n.throwIfAborted();let s=t?.env?.GOOGLE_CLOUD_PROJECT??await r("GOOGLE_CLOUD_PROJECT")??await r("GCLOUD_PROJECT"),c=t?.env?.GOOGLE_CLOUD_LOCATION??await r("GOOGLE_CLOUD_LOCATION");if(a&&s&&c)return{auth:{},env:t?.env,source:t?"stored credential":"gcloud application default credentials"}}};function Eot(){return Ye({id:"google-vertex",name:"Google Vertex AI",auth:{apiKey:h_n},models:Object.values(j3),api:c3()})}Ct();function xot(){return Ye({id:"groq",name:"Groq",baseUrl:"https://api.groq.com/openai/v1",auth:{apiKey:ot("Groq API key",["GROQ_API_KEY"])},models:Object.values(q3),api:xt()})}Ct();function wot(){return Ye({id:"huggingface",name:"Hugging Face",baseUrl:"https://router.huggingface.co/v1",auth:{apiKey:ot("Hugging Face token",["HF_TOKEN"])},models:Object.values(V3),api:xt()})}Ct();function bot(){return Ye({id:"kimi-coding",name:"Kimi For Coding",baseUrl:"https://api.kimi.com/coding",auth:{apiKey:ot("Kimi API key",["KIMI_API_KEY"]),oauth:Ts({name:"Kimi Code (subscription)",isSubscription:!0,loginLabel:"Sign in with Kimi Code",load:Xit})},models:Object.values(Y3),api:go()})}Ct();function Sot(){return Ye({id:"meta",name:"Meta",baseUrl:"https://api.meta.ai/v1",auth:{apiKey:ot("Meta Model API key",["META_API_KEY"]),oauth:Ts({name:"Meta (Muse subscription)",isSubscription:!0,loginLabel:"Sign in with Meta",load:Zit})},models:Object.values(X3),api:Nc()})}Ct();function Cot(){return Ye({id:"minimax",name:"MiniMax",baseUrl:"https://api.minimax.io/anthropic",auth:{apiKey:ot("MiniMax API key",["MINIMAX_API_KEY"])},models:Object.values(ez),api:go()})}Ct();function kot(){return Ye({id:"minimax-cn",name:"MiniMax CN",baseUrl:"https://api.minimaxi.com/anthropic",auth:{apiKey:ot("MiniMax CN API key",["MINIMAX_CN_API_KEY"])},models:Object.values(nz),api:go()})}Ct();function Rot(){return Ye({id:"mistral",name:"Mistral",baseUrl:"https://api.mistral.ai",auth:{apiKey:ot("Mistral API key",["MISTRAL_API_KEY"])},models:Object.values(iz),api:l3()})}Ct();function Tot(){return Ye({id:"moonshotai",name:"Moonshot AI",baseUrl:"https://api.moonshot.ai/v1",auth:{apiKey:ot("Moonshot AI API key",["MOONSHOT_API_KEY"])},models:Object.values(az),api:xt()})}Ct();function Oot(){return Ye({id:"moonshotai-cn",name:"Moonshot AI CN",baseUrl:"https://api.moonshot.cn/v1",auth:{apiKey:ot("Moonshot AI API key",["MOONSHOT_API_KEY"])},models:Object.values(cz),api:xt()})}Ct();function Dot(){return Ye({id:"nvidia",name:"NVIDIA",baseUrl:"https://integrate.api.nvidia.com/v1",auth:{apiKey:ot("NVIDIA API key",["NVIDIA_API_KEY"])},models:Object.values(lz),api:xt()})}var Mot=()=>({classify:async(e,t,n)=>(await Promise.resolve().then(()=>(Not(),Lot))).classify(e,t,n)});Ct();function Bot(){return Ye({id:"openai",name:"OpenAI",baseUrl:"https://api.openai.com/v1",auth:{apiKey:ot("OpenAI API key",["OPENAI_API_KEY"]),oauth:Ts({name:"OpenAI (ChatGPT subscription)",isSubscription:!0,loginLabel:"Sign in with ChatGPT",load:zit})},models:[...Object.values(pz),...Object.values(SAe)],filterAllModels:(e,t)=>t?.type==="oauth"?e.filter(n=>!em(n,"classifier")):e,api:Nc(),classifiers:{"openai-decisions":Mot()}})}Ct();function Fot(){return Ye({id:"openai-codex",name:"OpenAI Codex (legacy)",baseUrl:"https://chatgpt.com/backend-api",auth:{oauth:Ts({name:"OpenAI (ChatGPT Plus/Pro)",isSubscription:!0,load:Vit})},models:Object.values(mz),api:h3()})}var RI=()=>({classify:async(e,t,n)=>(await Promise.resolve().then(()=>(Qot(),Uot))).classify(e,t,n)});Ct();var Wot="x-opencode-session";function C_n(e,t){let n=t.toLowerCase();return Object.keys(e??{}).some(r=>r.toLowerCase()===n)}function $ot(e){return!e?.sessionId||C_n(e.headers,Wot)?e:{...e,headers:{...e.headers,[Wot]:e.sessionId}}}function Ay(e){return{...e,stream:(t,n,r)=>e.stream(t,n,$ot(r)),streamSimple:(t,n,r)=>e.streamSimple(t,n,$ot(r))}}function Hot(){return Ye({id:"opencode",name:"OpenCode Zen",auth:{apiKey:ot("OpenCode API key",["OPENCODE_API_KEY"])},models:[...Object.values(gz),...Object.values(CAe)],api:{"anthropic-messages":Ay(go()),"google-generative-ai":Ay(qO()),"openai-completions":Ay(xt()),"openai-responses":Ay(Nc())},classifiers:{"typesafe-system-one":RI()}})}Ct();function jot(){return Ye({id:"opencode-go",name:"OpenCode Go",auth:{apiKey:ot("OpenCode API key",["OPENCODE_API_KEY"])},models:Object.values(yz),api:{"anthropic-messages":Ay(go()),"openai-completions":Ay(xt()),"openai-responses":Ay(Nc())}})}var Got=()=>({generateImages:async(e,t,n)=>(await Promise.resolve().then(()=>(PAe(),DAe))).generateImages(e,t,n)});Ct();var k_n="https://openrouter.ai/api/v1";function qot(){return Ye({id:"openrouter",name:"OpenRouter",baseUrl:k_n,auth:{apiKey:ot("OpenRouter API key",["OPENROUTER_API_KEY"]),oauth:Ts({name:"OpenRouter OAuth",loginLabel:"Sign in with OpenRouter",load:Jit})},models:[...Object.values(Iz),...Object.values(kAe),...Object.values(RAe)],api:{"anthropic-messages":go(),"openai-completions":xt()},images:{"openrouter-images":Got()},classifiers:{"typesafe-system-one":RI()}})}Ct();function Kot(){return Ye({id:"qwen-token-plan",name:"Qwen Token Plan",baseUrl:"https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",auth:{apiKey:ot("Qwen Token Plan API key",["QWEN_TOKEN_PLAN_API_KEY"])},models:Object.values(Ez),api:xt()})}Ct();function Vot(){return Ye({id:"qwen-token-plan-cn",name:"Qwen Token Plan CN",baseUrl:"https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",auth:{apiKey:ot("Qwen Token Plan CN API key",["QWEN_TOKEN_PLAN_CN_API_KEY"])},models:Object.values(wz),api:xt()})}Ct();function zot(){return Ye({id:"qwen-token-plan-individual",name:"Qwen Token Plan Individual",baseUrl:"https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",auth:{apiKey:ot("Qwen Token Plan Individual API key",["QWEN_TOKEN_PLAN_API_KEY"])},models:Object.values(Sz),api:xt()})}var V0e="https://radius.pi.dev";function R_n(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return typeof t.id=="string"&&typeof t.name=="string"&&typeof t.reasoning=="boolean"&&Array.isArray(t.input)&&typeof t.cost=="object"&&t.cost!==null&&!Array.isArray(t.cost)&&typeof t.contextWindow=="number"&&typeof t.maxTokens=="number"}function Yot(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let{baseUrl:t,models:n}=e;if(!(typeof t!="string"||!Array.isArray(n)))return{baseUrl:t,models:n.filter(R_n).map(r=>({...r}))}}function z0e(e){return(/^https?:\/\//iu.test(e)?e:`https://${e}`).replace(/\/+$/u,"")}function T_n(e){return Yot(e?.gatewayConfig)}function Y0e(e,t){return t.models.map(n=>({...n,api:"pi-messages",provider:e,baseUrl:t.baseUrl}))}function Jot(e,t){let n=T_n(t);return n?Y0e(e,n):[]}function O_n(e){let t=e.trim();return t.length>512?`${t.slice(0,512)}\u2026`:t}async function Xot(e,t,n){let r={accept:"application/json"};t&&(r.authorization=`Bearer ${t}`);let i=await fetch(new URL("/v1/config",e),{headers:r,signal:n});if(!i.ok)throw new Error(`Could not load Radius config from ${e}: ${i.status}: ${O_n(await i.text())}`);let o=Yot(await i.json());if(!o)throw new Error(`Invalid Radius config from ${e}`);return o}function Zot(e={}){let t=e.id??"radius",n=e.name??"Radius",r=z0e(e.gateway??V0e),i=r===z0e(V0e)?Object.values(kz).map(s=>({...s,provider:t})):[],o,a=y3();return{id:t,name:n,auth:{apiKey:ot("Radius API key",["RADIUS_API_KEY"]),oauth:Ts({name:n,load:()=>tot({name:n,gateway:r})})},getModels:()=>o??i,refreshModels:async s=>{let c=s.stored;if(c){let f=c.models.filter(m=>m.provider===t);if(!await s.publish({update:()=>{o=f}}))return}if(!c&&s.credential?.type==="oauth"){let f=Jot(t,s.credential);if(f.length>0&&!await s.publish({persist:{models:f,checkedAt:Date.now()},update:()=>{o=f}}))return}if(!s.allowNetwork||s.signal.aborted)return;let u=s.credential?.type==="oauth"?s.credential.access:s.credential?.key,l=await Xot(r,u,s.signal);if(s.signal.aborted)return;let p=Y0e(t,l);await s.publish({persist:{models:p,checkedAt:Date.now()},update:()=>{o=p}})},stream:(s,c,u)=>a.stream(s,c,u),streamSimple:(s,c,u)=>a.streamSimple(s,c,u)}}Ct();function eat(){return Ye({id:"together",name:"Together",baseUrl:"https://api.together.ai/v1",auth:{apiKey:ot("Together API key",["TOGETHER_API_KEY"])},models:Object.values(Tz),api:xt()})}Ct();function tat(){return Ye({id:"typesafe",name:"TypeSafe",auth:{apiKey:ot("TypeSafe API key",["TYPESAFE_API_KEY"])},models:Object.values(TAe),classifiers:{"typesafe-system-one":RI()}})}Ct();function nat(){return Ye({id:"vercel-ai-gateway",name:"Vercel AI Gateway",baseUrl:"https://ai-gateway.vercel.sh",auth:{apiKey:ot("Vercel AI Gateway API key",["AI_GATEWAY_API_KEY"])},models:[...Object.values(Pz),...Object.values(OAe)],api:go(),classifiers:{"typesafe-system-one":RI()}})}Ct();function rat(){return Ye({id:"xai",name:"xAI",baseUrl:"https://api.x.ai/v1",auth:{apiKey:ot("xAI API key",["XAI_API_KEY"]),oauth:Ts({name:"xAI (Grok/X subscription)",isSubscription:!0,loginLabel:"Sign in with SuperGrok or X Premium",load:eot})},models:Object.values(Nz),api:Nc()})}Ct();function iat(){return Ye({id:"xiaomi",name:"Xiaomi",baseUrl:"https://api.xiaomimimo.com/v1",auth:{apiKey:ot("Xiaomi API key",["XIAOMI_API_KEY"])},models:Object.values(Bz),api:xt()})}Ct();function oat(){return Ye({id:"xiaomi-token-plan-ams",name:"Xiaomi Token Plan AMS",baseUrl:"https://token-plan-ams.xiaomimimo.com/v1",auth:{apiKey:ot("Xiaomi Token Plan AMS API key",["XIAOMI_TOKEN_PLAN_AMS_API_KEY"])},models:Object.values(Uz),api:xt()})}Ct();function aat(){return Ye({id:"xiaomi-token-plan-cn",name:"Xiaomi Token Plan CN",baseUrl:"https://token-plan-cn.xiaomimimo.com/v1",auth:{apiKey:ot("Xiaomi Token Plan CN API key",["XIAOMI_TOKEN_PLAN_CN_API_KEY"])},models:Object.values(Wz),api:xt()})}Ct();function sat(){return Ye({id:"xiaomi-token-plan-sgp",name:"Xiaomi Token Plan SGP",baseUrl:"https://token-plan-sgp.xiaomimimo.com/v1",auth:{apiKey:ot("Xiaomi Token Plan SGP API key",["XIAOMI_TOKEN_PLAN_SGP_API_KEY"])},models:Object.values(Hz),api:xt()})}Ct();function cat(){return Ye({id:"zai",name:"Z.AI",baseUrl:"https://api.z.ai/api/coding/paas/v4",auth:{apiKey:ot("Z.AI API key",["ZAI_API_KEY"])},models:Object.values(Gz),api:xt()})}Ct();function uat(){return Ye({id:"zai-coding-cn",name:"Z.AI Coding CN",baseUrl:"https://open.bigmodel.cn/api/coding/paas/v4",auth:{apiKey:ot("Z.AI Coding CN API key",["ZAI_CODING_CN_API_KEY"])},models:Object.values(Kz),api:xt()})}function lat(e,t){return Vz[e]?.[t]}function dat(){return Object.keys(Vz)}function pat(e){let t=Vz[e];return Object.values(t??{})}function D_n(){return[Git(),qit(),not(),oot(),aot(),sot(),pot(),Aot(),yot(),_ot(),Iot(),vot(),Eot(),xot(),wot(),bot(),Sot(),Cot(),kot(),Rot(),Tot(),Oot(),Dot(),Bot(),Fot(),Hot(),jot(),qot(),Kot(),Vot(),zot(),Zot(),eat(),tat(),nat(),rat(),iat(),oat(),aat(),sat(),cat(),uat()]}function fat(e){let t=_Ue(e);for(let n of D_n())t.setProvider(n);return t}ud();var Bw=lat,hat=pat,wU=dat,gat=new Map;function P_n(e,t){return(n,r,i)=>{if(n.api!==e)throw new Error(`Mismatched api: ${n.api} expected ${e}`);return t(n,r,i)}}function L_n(e,t){return(n,r,i)=>{if(n.api!==e)throw new Error(`Mismatched api: ${n.api} expected ${e}`);return t(n,r,i)}}function N_n(e,t){gat.set(e.api,{provider:{api:e.api,stream:P_n(e.api,e.stream),streamSimple:L_n(e.api,e.streamSimple)},sourceId:t})}function i7(e){return gat.get(e)?.provider}var M_n=[["anthropic-messages",go()],["openai-completions",xt()],["openai-responses",Nc()],["openai-codex-responses",h3()],["azure-openai-responses",B8()],["google-generative-ai",qO()],["google-vertex",c3()],["mistral-conversations",l3()],["bedrock-converse-stream",F8()],["pi-messages",y3()]],Aat=new Map;function B_n(){for(let[e,t]of M_n)i7(e)||N_n({api:e,stream:t.stream,streamSimple:t.streamSimple}),Aat.set(e,i7(e))}B_n();var yat=fat(),F_n="<authenticated>";function _at(e){return typeof e=="string"&&e.trim().length>0}function mat(e,t){if(_at(t?.apiKey))return t;let n=nUe(e.provider,t?.env);return!n||n===F_n?t:{...t,apiKey:n}}function U_n(e){return _at(e?.apiKey)||typeof e?.headers?.["cf-aig-authorization"]=="string"}function Q_n(e){if(i7(e.api)!==Aat.get(e.api))return;let t=yat.getProvider(e.provider);return t?.getModels().some(n=>n.api===e.api)?t:void 0}function W_n(e){let t=i7(e);if(!t)throw new Error(`No API provider registered for api: ${e}`);return t}function J0e(e,t,n){let r=IA(t),i=Q_n(e);return i?e.provider.startsWith("cloudflare-")&&!U_n(n)?yat.streamSimple(e,r,n):i.streamSimple(e,r,mat(e,n)):W_n(e.api).streamSimple(e,r,mat(e,n))}async function TI(e,t,n){return J0e(e,t,n).result()}function a7(){return wU()}function X0e(e){return a7().includes(e)}var o7;function bU(e){return e.trim().toLowerCase()}function Z0e(){if(o7!==void 0)return o7;let e=new Map;for(let t of wU()){let n=hat(t);for(let r of n){let i={provider:t,modelId:r.id,contextWindowTokens:r.contextWindow},o=bU(r.id),a=e.get(o);a?a.push(i):e.set(o,[i])}}return o7={exact(t,n){let r=bU(t);return e.get(bU(n))?.find(i=>bU(i.provider)===r)},byModelId(t){return e.get(bU(t))??[]}},o7}var aJ=Hs(agt(),1);import{EventEmitter as SMn}from"node:events";var CMn=e=>{};function kMn(e={bodyTimeout:0,headersTimeout:0}){let t=new aJ.Agent(e);return SMn.prototype.on.call(t,"error",CMn),(r,i)=>aJ.fetch(r,{...i,dispatcher:t})}var sgt;function RMn(){return sgt??=kMn(),sgt}var TMn=new Set(["google-generative-ai","google-vertex"]);function OMn(e){return e!==void 0&&!TMn.has(e)}function Rg(e){return OMn(e)?RMn():globalThis.fetch}po();kn();en();var DMn=d.Object({candidateIndex:d.Number(),badDecision:d.String({minLength:1}),betterDecision:d.String({minLength:1}),rationale:d.String({minLength:1}),confidence:d.Number({minimum:0,maximum:1}),riskLevel:d.Union([d.Literal("low"),d.Literal("medium"),d.Literal("high")]),strategicPerspective:d.String({minLength:1})}),cgt=d.Object({valid:d.Boolean(),taskId:d.String({minLength:1}),candidates:d.Array(DMn,{minItems:1,maxItems:5}),sourcePrincipleId:d.Optional(d.String()),sourcePainId:d.Optional(d.String()),contextRefs:d.Array(d.String()),generatedAt:d.String({minLength:1}),reason:d.Optional(d.String())}),PMn=new Set(["low","medium","high"]),NQ=class{async validate(t,n){let r=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};let i=t;if(i.taskId!==n&&r.push(`taskId mismatch: expected ${n}, got ${String(i.taskId)}`),i.valid!==!0&&r.push("output.valid must be true"),!Array.isArray(i.candidates))r.push("candidates must be an array");else{(i.candidates.length<1||i.candidates.length>5)&&r.push("candidates must have 1-5 items");for(let o=0;o<i.candidates.length;o++){let a=i.candidates[o];if(!a){r.push(`candidates[${o}] is null/undefined`);continue}typeof a.candidateIndex!="number"&&r.push(`candidates[${o}].candidateIndex must be number`),(typeof a.badDecision!="string"||a.badDecision.trim()==="")&&r.push(`candidates[${o}].badDecision must be non-empty string`),(typeof a.betterDecision!="string"||a.betterDecision.trim()==="")&&r.push(`candidates[${o}].betterDecision must be non-empty string`),(typeof a.rationale!="string"||a.rationale.trim()==="")&&r.push(`candidates[${o}].rationale must be non-empty string`),typeof a.confidence!="number"?r.push(`candidates[${o}].confidence must be number`):(a.confidence<0||a.confidence>1)&&r.push(`candidates[${o}].confidence must be in [0, 1]`),(typeof a.riskLevel!="string"||!PMn.has(a.riskLevel))&&r.push(`candidates[${o}].riskLevel must be low|medium|high`),(typeof a.strategicPerspective!="string"||a.strategicPerspective.trim()==="")&&r.push(`candidates[${o}].strategicPerspective must be non-empty string`)}}return Array.isArray(i.contextRefs)||r.push("contextRefs must be an array"),(typeof i.generatedAt!="string"||i.generatedAt.trim()==="")&&r.push("generatedAt must be non-empty string"),r.length>0?{valid:!1,errors:r,errorCategory:"output_invalid"}:{valid:!0,errors:[]}}};en();var LMn=d.Object({title:d.String({minLength:1}),rationale:d.String({minLength:1}),scope:d.String({minLength:1}),confidence:d.Number({minimum:0,maximum:1})}),ugt=d.Object({taskId:d.String({minLength:1}),sourceDreamerArtifactId:d.String({minLength:1}),thesis:d.String({minLength:1}),principleCandidate:LMn,risks:d.Array(d.String()),generatedAt:d.String({minLength:1})}),MQ=class{async validate(t,n){let r=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};let i=t;if(i.taskId!==n&&r.push(`taskId mismatch: expected ${n}, got ${String(i.taskId)}`),(typeof i.sourceDreamerArtifactId!="string"||i.sourceDreamerArtifactId.trim()==="")&&r.push("sourceDreamerArtifactId must be non-empty string"),(typeof i.thesis!="string"||i.thesis.trim()==="")&&r.push("thesis must be non-empty string"),typeof i.principleCandidate!="object"||i.principleCandidate===null)r.push("principleCandidate must be an object");else{let o=i.principleCandidate;(typeof o.title!="string"||o.title.trim()==="")&&r.push("principleCandidate.title must be non-empty string"),(typeof o.rationale!="string"||o.rationale.trim()==="")&&r.push("principleCandidate.rationale must be non-empty string"),(typeof o.scope!="string"||o.scope.trim()==="")&&r.push("principleCandidate.scope must be non-empty string"),typeof o.confidence!="number"?r.push("principleCandidate.confidence must be number"):(o.confidence<0||o.confidence>1)&&r.push("principleCandidate.confidence must be in [0, 1]")}return Array.isArray(i.risks)?i.risks.some(o=>typeof o!="string")&&r.push("risks must contain only strings"):r.push("risks must be an array"),(typeof i.generatedAt!="string"||i.generatedAt.trim()==="")&&r.push("generatedAt must be non-empty string"),r.length>0?{valid:!1,errors:r,errorCategory:"output_invalid"}:{valid:!0,errors:[]}}};en();function Qxe(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e,n=r=>Object.hasOwn(t,r)&&typeof t[r]=="string"&&t[r].trim()!=="";return n("ownerIntent")&&n("targetBehavior")&&n("forbiddenBehavior")&&n("evidenceSource")&&n("validationExpectation")}function ZI(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(!Object.hasOwn(t,"intentContract"))return null;let n=t.intentContract;return Qxe(n)?n:null}var lgt=new Set(["__proto__","constructor","prototype"]);function Uxe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yP(e){if(!Uxe(e)||Object.keys(e).some(t=>lgt.has(t))||e.version!==1||!Array.isArray(e.requiredFacts))return!1;for(let t of e.requiredFacts)if(!Uxe(t)||Object.keys(t).some(n=>lgt.has(n))||typeof t.factKind!="string"||t.factKind.trim()===""||typeof t.required!="boolean"||typeof t.textualBasis!="string"||t.textualBasis.trim()==="")return!1;return!0}function Ru(e){if(!Uxe(e)||!Object.hasOwn(e,"executionConditions"))return{conditions:null,corrupted:!1};let t=e.executionConditions;return yP(t)?{conditions:t,corrupted:!1}:{conditions:null,corrupted:!0}}function sJ(e){return e.toLowerCase().replace(/[\s`'"“”‘’、,。:;!?()\]{}()【】,.;:!?\-—_/\\*#]+/gu,"")}var NMn=4;function cJ(e,t){let n=sJ(e);return n.length<NMn||t.length===0?!1:t.includes(n)}var dgt=["confirm","approv","\u6279\u51C6","\u786E\u8BA4"];function BQ(e){let t=[],n=(o,a)=>{typeof a=="string"&&a.trim()!==""&&t.push({name:o,text:a})};if(typeof e=="object"&&e!==null){let o=e,a=typeof o.principleDraft=="object"&&o.principleDraft!==null?o.principleDraft:{};if(n("principleDraft.statement",a.statement),typeof o.intentContract=="object"&&o.intentContract!==null){let s=o.intentContract;n("intentContract.ownerIntent",s.ownerIntent),n("intentContract.targetBehavior",s.targetBehavior),n("intentContract.forbiddenBehavior",s.forbiddenBehavior),n("intentContract.validationExpectation",s.validationExpectation)}}let r=sJ(t.map(o=>o.text).join(" ")),i=t.filter(o=>dgt.some(a=>o.text.toLowerCase().includes(a))).map(o=>o.name);return{normalisedText:r,approvalSignalFields:i,hasApprovalSignal:i.length>0}}function MMn(e){if(typeof e!="string"||e.length===0)return[];let t=e.toLowerCase();return dgt.filter(n=>t.includes(n))}function uJ(e){let t=e.requiredFacts.filter(r=>r.required).map(r=>r.factKind.toLowerCase()).join(" ");if(/approv/.test(t))return null;if(e.scribeMaterial.hasApprovalSignal)return{pool:"scribe",fields:e.scribeMaterial.approvalSignalFields};let n=MMn(e.upstreamNormalisedText);return n.length>0?{pool:"upstream",fields:n}:null}var BMn=d.Object({title:d.String({minLength:1}),statement:d.String({minLength:1}),rationale:d.String({minLength:1}),applicability:d.Array(d.String()),antiPatterns:d.Array(d.String()),confidence:d.Number({minimum:0,maximum:1})}),FMn=d.Object({dreamerArtifactId:d.Optional(d.String()),philosopherArtifactId:d.String({minLength:1})}),UMn=d.Object({ownerIntent:d.String({minLength:1}),targetBehavior:d.String({minLength:1}),forbiddenBehavior:d.String({minLength:1}),evidenceSource:d.String({minLength:1}),validationExpectation:d.String({minLength:1})}),QMn=d.Object({version:d.Literal(1),requiredFacts:d.Array(d.Object({factKind:d.String({minLength:1}),required:d.Boolean(),textualBasis:d.String({minLength:1})}))}),pgt=d.Object({taskId:d.String({minLength:1}),sourcePhilosopherArtifactId:d.String({minLength:1}),principleDraft:BMn,sourceTrace:FMn,risks:d.Array(d.String()),generatedAt:d.String({minLength:1}),intentContract:UMn,executionConditions:QMn,ownerRequirementGaps:d.Optional(d.Array(d.String({minLength:1})))});function Sb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var _P=class{requireRuleCodeContracts;constructor(t={}){this.requireRuleCodeContracts=t.requireRuleCodeContracts??!1}async validate(t,n,r,i){let o=[];if(!Sb(t))return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};if((!Object.hasOwn(t,"taskId")||t.taskId!==n)&&o.push(`taskId mismatch: expected ${n}, got ${String(t.taskId)}`),!Object.hasOwn(t,"sourcePhilosopherArtifactId")||typeof t.sourcePhilosopherArtifactId!="string"||t.sourcePhilosopherArtifactId.trim()===""?o.push("sourcePhilosopherArtifactId must be non-empty string"):r&&t.sourcePhilosopherArtifactId!==r&&o.push(`sourcePhilosopherArtifactId mismatch: expected ${r}, got ${t.sourcePhilosopherArtifactId}`),!Object.hasOwn(t,"principleDraft")||!Sb(t.principleDraft))o.push("principleDraft must be an object");else{let u=t.principleDraft;(!Object.hasOwn(u,"title")||typeof u.title!="string"||u.title.trim()==="")&&o.push("principleDraft.title must be non-empty string"),(!Object.hasOwn(u,"statement")||typeof u.statement!="string"||u.statement.trim()==="")&&o.push("principleDraft.statement must be non-empty string"),(!Object.hasOwn(u,"rationale")||typeof u.rationale!="string"||u.rationale.trim()==="")&&o.push("principleDraft.rationale must be non-empty string"),!Object.hasOwn(u,"applicability")||!Array.isArray(u.applicability)?o.push("principleDraft.applicability must be an array"):u.applicability.every(l=>typeof l=="string")||o.push("principleDraft.applicability must be an array of strings"),!Object.hasOwn(u,"antiPatterns")||!Array.isArray(u.antiPatterns)?o.push("principleDraft.antiPatterns must be an array"):u.antiPatterns.every(l=>typeof l=="string")||o.push("principleDraft.antiPatterns must be an array of strings"),!Object.hasOwn(u,"confidence")||typeof u.confidence!="number"?o.push("principleDraft.confidence must be number"):(u.confidence<0||u.confidence>1)&&o.push("principleDraft.confidence must be in [0, 1]")}if(!Object.hasOwn(t,"sourceTrace")||!Sb(t.sourceTrace))o.push("sourceTrace must be an object");else{let u=t.sourceTrace;!Object.hasOwn(u,"philosopherArtifactId")||typeof u.philosopherArtifactId!="string"||u.philosopherArtifactId.trim()===""?o.push("sourceTrace.philosopherArtifactId must be non-empty string"):r&&u.philosopherArtifactId!==r&&o.push(`sourceTrace.philosopherArtifactId mismatch: expected ${r}, got ${u.philosopherArtifactId}`),Object.hasOwn(u,"dreamerArtifactId")&&u.dreamerArtifactId!==void 0&&(typeof u.dreamerArtifactId!="string"||u.dreamerArtifactId.trim()==="")&&o.push("sourceTrace.dreamerArtifactId must be non-empty string when present")}!Object.hasOwn(t,"risks")||!Array.isArray(t.risks)?o.push("risks must be an array"):t.risks.every(u=>typeof u=="string")||o.push("risks must be an array of strings"),Object.hasOwn(t,"ownerRequirementGaps")&&t.ownerRequirementGaps!==void 0&&(Array.isArray(t.ownerRequirementGaps)?t.ownerRequirementGaps.every(u=>typeof u=="string"&&u.trim()!=="")||o.push("ownerRequirementGaps must be an array of non-empty strings"):o.push("ownerRequirementGaps must be an array"));let a=Object.hasOwn(t,"intentContract")&&t.intentContract!==void 0;this.requireRuleCodeContracts&&!a&&o.push("intentContract is required for new RuleCode generation"),a&&(Qxe(t.intentContract)||o.push("intentContract must contain non-empty string fields: ownerIntent, targetBehavior, forbiddenBehavior, evidenceSource, validationExpectation"));let s=Object.hasOwn(t,"executionConditions")&&t.executionConditions!==void 0;this.requireRuleCodeContracts&&!s&&o.push("executionConditions is required for new RuleCode generation");let c=!1;if(s&&(c=yP(t.executionConditions),c||o.push("executionConditions must be { version: 1, requiredFacts: [{ factKind: non-empty string, required: boolean, textualBasis: non-empty string }] }")),this.requireRuleCodeContracts&&c&&i?.upstreamAnchorMaterial!=null&&i.upstreamAnchorMaterial.normalisedText.length>0&&Sb(t.executionConditions)&&Array.isArray(t.executionConditions.requiredFacts)){let u=BQ(t).normalisedText+" "+i.upstreamAnchorMaterial.normalisedText;for(let[l,p]of t.executionConditions.requiredFacts.entries())Sb(p)&&p.required===!0&&(typeof p.textualBasis!="string"||typeof p.factKind!="string"||cJ(p.textualBasis,u)||o.push(`executionConditions.requiredFacts[${l}] (factKind '${p.factKind}') textualBasis ("${p.textualBasis.replace(/\s+/g," ").slice(0,120)}") is not a continuous verbatim span of the Owner-attributed material \u2014 rewrite it as one continuous original sentence copied from the source (no citation labels, no ellipsis-omitted reconstruction)`))}if(this.requireRuleCodeContracts&&c&&i!=null&&Sb(t.executionConditions)&&Array.isArray(t.executionConditions.requiredFacts)){let u=t.executionConditions.requiredFacts.flatMap(p=>!Sb(p)||typeof p.factKind!="string"||typeof p.required!="boolean"?[]:[{factKind:p.factKind,required:p.required}]),l=uJ({scribeMaterial:BQ(t),upstreamNormalisedText:i.upstreamAnchorMaterial?.normalisedText??"",requiredFacts:u});l!==null&&o.push(`executionConditions: ${l.pool} material carries approval semantics (${l.fields.join(", ")}) but no REQUIRED approval-kind fact is declared \u2014 declare the approval dependency (factKind e.g. 'design_approval', required: true) with its textual basis, or correct the draft text if it overstates the requirement`)}return(!Object.hasOwn(t,"generatedAt")||typeof t.generatedAt!="string"||t.generatedAt.trim()==="")&&o.push("generatedAt must be non-empty string"),o.length>0?{valid:!1,errors:o,errorCategory:"output_invalid"}:{valid:!0,errors:[]}}};function fgt(e){if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,"intentContract"))return!1;let t=Reflect.get(e,"intentContract");if(typeof t!="string")return!1;let n;try{n=JSON.parse(t)}catch{return!1}return typeof n!="object"||n===null||Array.isArray(n)?!1:(Reflect.set(e,"intentContract",n),!0)}en();var Wxe=new Set(["read","search","write","execute","agent","other"]);function mgt(e){return typeof e=="string"&&Wxe.has(e)}var IP=Object.freeze({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",execute_command:"execute",run_script:"execute",code_interpreter:"execute",sessions_spawn:"agent"});var WMn=["unregistered_scope","workspace_mismatch","session_mismatch","task_mismatch","spec_changed","scope_mismatch","declaration_revoked","source_unavailable","malformed_declaration","capability_unsupported","host_identity_unavailable","project_scope_mismatch","declaration_unavailable","declaration_invalid","spec_path_invalid","spec_digest_mismatch","target_scope_unknown","action_scope_unknown"];function $Mn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function HMn(e,t){return t.every(n=>Object.hasOwn(e,n))}function jMn(e){return typeof e=="string"&&e.trim().length>0}function Cb(e){return e===null||jMn(e)}function GMn(e){return e==="approved"||e==="not_approved"||e==="not_required"||e==="unknown"}function qMn(e){return typeof e=="string"&&WMn.includes(e)}function FQ(e){return!$Mn(e)||!HMn(e,["version","sourceRef","revision","requiresApproval","taskRef","specDigest","scopeRef","decisionTaskRef","decisionSpecDigest","decisionScopeRef","resolution","revoked"])||e.version!==1||!Cb(e.sourceRef)||e.revision!==null&&(typeof e.revision!="number"||!Number.isSafeInteger(e.revision)||e.revision<1)||typeof e.requiresApproval!="boolean"||!Cb(e.taskRef)||!Cb(e.specDigest)||!Cb(e.scopeRef)||!Cb(e.decisionTaskRef)||!Cb(e.decisionSpecDigest)||!Cb(e.decisionScopeRef)||!GMn(e.resolution)||typeof e.revoked!="boolean"||Object.hasOwn(e,"invalidationReason")&&!qMn(e.invalidationReason)||!Object.hasOwn(e,"invalidationReason")&&e.invalidationReason!==void 0?!1:e.resolution==="unknown"?!0:e.resolution==="not_required"&&e.requiresApproval===!1&&e.sourceRef===null?e.taskRef!==null&&e.revision===null&&e.decisionTaskRef===null&&e.decisionSpecDigest===null&&e.decisionScopeRef===null&&!e.revoked:!([e.sourceRef,e.revision,e.taskRef,e.specDigest,e.scopeRef,e.decisionTaskRef,e.decisionSpecDigest,e.decisionScopeRef].some(n=>n===null)||e.taskRef!==e.decisionTaskRef||e.specDigest!==e.decisionSpecDigest||e.scopeRef!==e.decisionScopeRef||e.revoked&&e.resolution!=="not_approved")}var KMn=new Set(["read","search","write","execute","agent","other"]),VMn=new Set(["yes","no","unknown"]),zMn=new Set(["success","failure","blocked"]),YMn=new Set(["available","unavailable"]),JMn=new Set(["__proto__","constructor","prototype"]),XMn={valid:!0,errors:[]};function dJ(e){return e.length===0?XMn:{valid:!1,errors:e}}function kb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pJ(e){for(let t of Object.keys(e))if(JMn.has(t))return!1;return!0}function ZMn(e){return typeof e=="number"&&Number.isFinite(e)}function lJ(e){return e===null||typeof e=="number"&&Number.isFinite(e)&&e>=0}function UQ(e){if(typeof e!="string"||!Object.hasOwn(IP,e))return"other";let t=IP[e];return t!==void 0?t:"other"}function hgt(e){if(!kb(e))return{valid:!1,errors:["record must be a plain object"]};if(!pJ(e))return{valid:!1,errors:["record must not carry prototype-pollution keys"]};let t=[];ZMn(e.sequenceId)||t.push("sequenceId must be a finite number");let{toolName:n}=e;(typeof n!="string"||n.length===0)&&t.push("toolName must be a non-empty string");let{canonicalKind:r}=e;(typeof r!="string"||!KMn.has(r))&&t.push("canonicalKind must be a valid CanonicalKind");let{normalizedPath:i}=e;i!==null&&typeof i!="string"&&t.push("normalizedPath must be a string or null"),kb(e.paramsSummary)||t.push("paramsSummary must be a plain object");let{outcome:o}=e;return(typeof o!="string"||!zMn.has(o))&&t.push("outcome must be success | failure | blocked"),dJ(t)}function ggt(e){if(!kb(e))return{valid:!1,errors:["history window must be a plain object"]};if(!pJ(e))return{valid:!1,errors:["history window must not carry prototype-pollution keys"]};let t=[],{status:n}=e;(typeof n!="string"||!YMn.has(n))&&t.push("status must be available | unavailable");let{unavailableReason:r}=e;r!==void 0&&typeof r!="string"&&t.push("unavailableReason must be a string or undefined"),typeof e.truncated!="boolean"&&t.push("truncated must be a boolean");let{calls:i}=e;if(!Array.isArray(i))t.push("calls must be an array");else for(let o=0;o<i.length;o++){let a=hgt(i[o]);a.valid||t.push(`calls[${o}] invalid: ${a.errors.join("; ")}`)}return dJ(t)}function Agt(e){if(!kb(e))return{valid:!1,errors:["facts must be a plain object"]};if(!pJ(e))return{valid:!1,errors:["facts must not carry prototype-pollution keys"]};let t=[],{priorReadOfTarget:n}=e;return(typeof n!="string"||!VMn.has(n))&&t.push("priorReadOfTarget must be yes | no | unknown"),lJ(e.readCount)||t.push("readCount must be a non-negative finite number or null"),lJ(e.writeCount)||t.push("writeCount must be a non-negative finite number or null"),lJ(e.uniqueWritePathCount)||t.push("uniqueWritePathCount must be a non-negative finite number or null"),lJ(e.sameActionBlockCount)||t.push("sameActionBlockCount must be a non-negative finite number or null"),Object.hasOwn(e,"designGate")&&!FQ(e.designGate)&&t.push("designGate must be a valid versioned host fact"),dJ(t)}function qc(e){if(!kb(e))return{valid:!1,errors:["context must be a plain object"]};if(!pJ(e))return{valid:!1,errors:["context must not carry prototype-pollution keys"]};let t=[];e.version!==2&&t.push("version must be 2");let n=ggt(e.history);n.valid||t.push(`history invalid: ${n.errors.join("; ")}`);let r=Agt(e.facts);r.valid||t.push(`facts invalid: ${r.errors.join("; ")}`);let{history:i}=e,{facts:o}=e;return n.valid&&r.valid&&kb(i)&&kb(o)&&i.status==="unavailable"&&(o.priorReadOfTarget!=="unknown"&&t.push('unavailable invariant: priorReadOfTarget must be "unknown" when history is unavailable'),o.readCount!==null&&t.push("unavailable invariant: readCount must be null when history is unavailable"),o.writeCount!==null&&t.push("unavailable invariant: writeCount must be null when history is unavailable"),o.uniqueWritePathCount!==null&&t.push("unavailable invariant: uniqueWritePathCount must be null when history is unavailable"),o.sameActionBlockCount!==null&&t.push("unavailable invariant: sameActionBlockCount must be null when history is unavailable")),dJ(t)}function ev(e,t,n){if(e.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let r=0,i=0,o=new Set,a=t===null?"unknown":"no",{calls:s}=e;for(let c of s){let u=c.canonicalKind;u==="read"||u==="search"?(r++,t!==null&&c.normalizedPath===t&&(a="yes")):u==="write"&&(i++,typeof c.normalizedPath=="string"&&o.add(c.normalizedPath))}return{priorReadOfTarget:a,readCount:r,writeCount:i,uniqueWritePathCount:o.size,sameActionBlockCount:n}}var ygt={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(ygt);var $xe={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze($xe.calls);Object.freeze($xe);var _gt={version:2,history:$xe,facts:ygt};Object.freeze(_gt);var Wa=_gt;var Egt=d.Object({scribeArtifactId:d.String({minLength:1}),philosopherArtifactId:d.Optional(d.String({minLength:1})),dreamerArtifactId:d.Optional(d.String({minLength:1}))}),Hxe=d.Object({taskId:d.String({minLength:1}),sourceScribeArtifactId:d.String({minLength:1}),implementationCode:d.String({minLength:1}),goldenTraceCases:d.Array(d.Object({caseId:d.String({minLength:1}),kind:d.Union([d.Literal("positive"),d.Literal("negative")]),toolName:d.String({minLength:1}),params:d.Record(d.String(),d.Unknown()),expectedDecision:d.Union([d.Literal("allow"),d.Literal("block"),d.Literal("propose_correction")]),expectedProposedParams:d.Optional(d.Record(d.String(),d.Unknown())),expectedApplicationMode:d.Optional(d.Union([d.Literal("shadow"),d.Literal("live")]))}),{minItems:2,maxItems:10}),affectedTools:d.Array(d.String({minLength:1}),{minItems:1}),implementationSummary:d.String({minLength:1}),risks:d.Array(d.String()),sourceTrace:Egt,generatedAt:d.String({minLength:1}),requiresContextVersion:d.Optional(d.Literal(2)),evidenceRefs:d.Optional(d.Array(d.String({minLength:1})))});function Rb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var eBn=new Set(["allow","block","propose_correction"]),Igt=10,vgt=2;function tBn(e){let t=[];if(!Array.isArray(e))return t.push("goldenTraceCases must be an array"),t;e.length<vgt&&t.push(`goldenTraceCases must contain at least ${vgt} cases (1 positive + 1 negative), got ${e.length}`),e.length>Igt&&t.push(`goldenTraceCases must contain at most ${Igt} cases, got ${e.length}`);let n=!1,r=!1;return e.forEach((i,o)=>{let a=`goldenTraceCases[${o}]`;if(!Rb(i)){t.push(`${a} must be an object`);return}(!Object.hasOwn(i,"caseId")||typeof i.caseId!="string"||i.caseId.trim()==="")&&t.push(`${a}.caseId must be a non-empty string`),!Object.hasOwn(i,"kind")||i.kind!=="positive"&&i.kind!=="negative"?t.push(`${a}.kind must be 'positive' or 'negative'`):i.kind==="positive"?n=!0:r=!0,(!Object.hasOwn(i,"toolName")||typeof i.toolName!="string"||i.toolName.trim()==="")&&t.push(`${a}.toolName must be a non-empty string`),(!Object.hasOwn(i,"params")||!Rb(i.params))&&t.push(`${a}.params must be an object`),!Object.hasOwn(i,"expectedDecision")||typeof i.expectedDecision!="string"||!eBn.has(i.expectedDecision)?t.push(`${a}.expectedDecision must be one of allow|block|propose_correction, got ${String(i.expectedDecision)}`):i.kind==="positive"&&i.expectedDecision!=="allow"&&t.push(`${a}: positive cases must expect allow (got ${i.expectedDecision})`),i.expectedDecision==="propose_correction"&&((!Object.hasOwn(i,"expectedProposedParams")||!Rb(i.expectedProposedParams))&&t.push(`${a}.expectedProposedParams is required when expectedDecision is propose_correction`),(!Object.hasOwn(i,"expectedApplicationMode")||i.expectedApplicationMode!=="shadow"&&i.expectedApplicationMode!=="live")&&t.push(`${a}.expectedApplicationMode must be shadow or live when expectedDecision is propose_correction`))}),Array.isArray(e)&&e.length>0&&(n||t.push("goldenTraceCases must include at least one positive case"),r||t.push("goldenTraceCases must include at least one negative case")),t}function nBn(e){let t=[];return Array.isArray(e)?(e.length===0&&t.push("affectedTools must be a non-empty array"),e.forEach((n,r)=>{(typeof n!="string"||n.trim()==="")&&t.push(`affectedTools[${r}] must be a non-empty string`)}),t):(t.push("affectedTools must be an array"),t)}var vP=class{async validate(t,n,r){let i=[];if(!Rb(t))return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};let o=t;if((!Object.hasOwn(o,"taskId")||o.taskId!==n)&&i.push(`taskId mismatch: expected ${n}, got ${String(o.taskId)}`),!Object.hasOwn(o,"sourceScribeArtifactId")||typeof o.sourceScribeArtifactId!="string"||o.sourceScribeArtifactId.trim()===""?i.push("sourceScribeArtifactId must be non-empty string"):r&&o.sourceScribeArtifactId!==r&&i.push(`sourceScribeArtifactId mismatch: expected ${r}, got ${o.sourceScribeArtifactId}`),(!Object.hasOwn(o,"implementationCode")||typeof o.implementationCode!="string"||o.implementationCode.trim()==="")&&i.push("implementationCode must be a non-empty string"),(!Object.hasOwn(o,"implementationSummary")||typeof o.implementationSummary!="string"||o.implementationSummary.trim()==="")&&i.push("implementationSummary must be a non-empty string"),!Object.hasOwn(o,"goldenTraceCases"))i.push("goldenTraceCases is required");else{let u=tBn(o.goldenTraceCases);i.push(...u)}let a=Object.hasOwn(o,"requiresContextVersion"),{requiresContextVersion:s}=o,c=a&&typeof s=="number"&&s===2;if(a&&(typeof s!="number"||s!==2)&&i.push(`requiresContextVersion must be 2 (only v2 is supported), got ${String(s)}`),Array.isArray(o.goldenTraceCases)){let u=o.goldenTraceCases;for(let l=0;l<u.length;l++){let p=u[l];if(!Rb(p))continue;if(c&&Object.hasOwn(p,"expectedDecision")&&p.expectedDecision==="propose_correction"&&i.push(`goldenTraceCases[${l}].expectedDecision 'propose_correction' is forbidden in v2 seed rules (only allow/block permitted)`),!Object.hasOwn(p,"ruleContext")){c&&i.push(`goldenTraceCases[${l}].ruleContext is required when requiresContextVersion: 2 is declared`);continue}let f=p.ruleContext;if(!c){i.push(`goldenTraceCases[${l}].ruleContext is only allowed when requiresContextVersion: 2 is declared (v1 rules must not read input.context)`);continue}if(f===void 0){i.push(`goldenTraceCases[${l}].ruleContext is required when requiresContextVersion: 2 is declared`);continue}let m=qc(f);m.valid||i.push(`goldenTraceCases[${l}].ruleContext invalid: ${m.errors.join("; ")}`)}}if(!Object.hasOwn(o,"affectedTools"))i.push("affectedTools is required");else{let u=nBn(o.affectedTools);i.push(...u)}if(!Object.hasOwn(o,"sourceTrace")||!Rb(o.sourceTrace))i.push("sourceTrace must be an object");else{let u=o.sourceTrace;!Object.hasOwn(u,"scribeArtifactId")||typeof u.scribeArtifactId!="string"||u.scribeArtifactId.trim()===""?i.push("sourceTrace.scribeArtifactId must be non-empty string"):r&&u.scribeArtifactId!==r&&i.push(`sourceTrace.scribeArtifactId mismatch: expected ${r}, got ${u.scribeArtifactId}`),Object.hasOwn(u,"philosopherArtifactId")&&u.philosopherArtifactId!==void 0&&(typeof u.philosopherArtifactId!="string"||u.philosopherArtifactId.trim()==="")&&i.push("sourceTrace.philosopherArtifactId must be non-empty string if present"),Object.hasOwn(u,"dreamerArtifactId")&&u.dreamerArtifactId!==void 0&&(typeof u.dreamerArtifactId!="string"||u.dreamerArtifactId.trim()==="")&&i.push("sourceTrace.dreamerArtifactId must be non-empty string if present")}return!Object.hasOwn(o,"risks")||!Array.isArray(o.risks)?i.push("risks must be an array"):o.risks.every(u=>typeof u=="string")||i.push("risks must be an array of strings"),typeof o.sourceScribeArtifactId=="string"&&o.sourceScribeArtifactId.trim()!==""&&Rb(o.sourceTrace)&&Object.hasOwn(o.sourceTrace,"scribeArtifactId")&&typeof o.sourceTrace.scribeArtifactId=="string"&&o.sourceScribeArtifactId!==o.sourceTrace.scribeArtifactId&&i.push("sourceScribeArtifactId and sourceTrace.scribeArtifactId must match"),(!Object.hasOwn(o,"generatedAt")||typeof o.generatedAt!="string"||o.generatedAt.trim()==="")&&i.push("generatedAt must be non-empty string"),c&&(!Object.hasOwn(o,"evidenceRefs")||!Array.isArray(o.evidenceRefs)||o.evidenceRefs.length===0?i.push("evidenceRefs is required and must be a non-empty array for v2 rules"):o.evidenceRefs.every(u=>typeof u=="string"&&u.trim()!=="")||i.push("evidenceRefs must be an array of non-empty strings")),i.length>0?{valid:!1,errors:i,errorCategory:"output_invalid"}:{valid:!0,errors:[]}}};var Dy=Object.freeze([Object.freeze({capabilityId:"pd_status",channel:"cli",cliCommand:"pd activation list --json"}),Object.freeze({capabilityId:"rulecode_deactivate",channel:"cli",cliCommand:"pd activation deactivate --activation-id recovery-probe"}),Object.freeze({capabilityId:"rulecode_global_pause",channel:"console",consoleRoute:"/api/activations/emergency-pause"}),Object.freeze({capabilityId:"owner_review_access",channel:"console",consoleRoute:"/api/activations/{activationId}/owner-review"})]);en();po();var Gxe="",rBn="|;&<>()";function fJ(e){return rBn.includes(e)?`${Gxe}${e}`:e}function xgt(e){return e.replaceAll(Gxe,"")}function jxe(e){if(e.includes(Gxe))return null;let t=[],n="",r=!1,i=0,o=e.length,a="plain";for(;i<o;){let s=e[i];if(s===void 0)break;if(a==="single"){s==="'"?a="plain":n+=fJ(s),i+=1;continue}if(a==="double"){if(s==='"')a="plain";else if(s==="\\"&&i+1<o&&'"\\$`'.includes(e[i+1]??"")){n+=fJ(e[i+1]??""),i+=2;continue}else n+=fJ(s);i+=1;continue}if(s==="'"){a="single",r=!0,i+=1;continue}if(s==='"'){a="double",r=!0,i+=1;continue}if(s==="\\"&&i+1<o){n+=fJ(e[i+1]??""),r=!0,i+=2;continue}if(s==="\r"||s===`
|
|
1195
|
+
${JSON.stringify(t.arguments,null,2)}`;throw new Error(o)}t1();Ct();Ct();var Z0n={name:"AWS credentials or bearer token",login:async e=>{e.signal.throwIfAborted();let t=await e.prompt({type:"select",message:"Select Amazon Bedrock authentication method:",options:[{id:"bearer-token",label:"Bearer token"},{id:"aws-profile",label:"AWS profile"},{id:"credential-chain",label:"Existing AWS credential chain"}]});if(e.signal.throwIfAborted(),t==="bearer-token")return{type:"api_key",key:await e.prompt({type:"secret",message:"Enter Amazon Bedrock bearer token"})};if(e.notify({type:"info",message:"Amazon Bedrock supports AWS profiles, IAM credentials, and role-based credentials.",links:[{label:"AWS credential provider chain",url:"https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html"}]}),t==="aws-profile")return{type:"api_key",env:{AWS_PROFILE:await e.prompt({type:"text",message:"Enter AWS profile name"})}};if(t!=="credential-chain")throw new Error(`Unknown Amazon Bedrock auth method: ${t}`);return await e.prompt({type:"text",message:"Configure AWS credentials, then press Enter to continue"}),{type:"api_key"}},resolve:async({ctx:e,credential:t,signal:n})=>{let r=async i=>{n.throwIfAborted();let o=await e.env(i);return n.throwIfAborted(),o};if(t?.key)return{auth:{apiKey:t.key},env:t.env,source:"stored credential"};if(await r("AWS_BEARER_TOKEN_BEDROCK"))return{auth:{},source:"AWS_BEARER_TOKEN_BEDROCK"};if(t?.env?.AWS_PROFILE??await r("AWS_PROFILE"))return{auth:{},env:t?.env,source:t?.env?.AWS_PROFILE?"stored credential":"AWS_PROFILE"};if(await r("AWS_ACCESS_KEY_ID")&&await r("AWS_SECRET_ACCESS_KEY"))return{auth:{},source:"AWS access keys"};if(await r("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"))return{auth:{},source:"ECS task role"};if(await r("AWS_CONTAINER_CREDENTIALS_FULL_URI"))return{auth:{},source:"ECS task role"};if(await r("AWS_WEB_IDENTITY_TOKEN_FILE"))return{auth:{},source:"web identity token"}}};function Git(){return Ye({id:"amazon-bedrock",name:"Amazon Bedrock",auth:{apiKey:Z0n},models:Object.values(I3),api:F8()})}Ct();function qit(){return Ye({id:"ant-ling",name:"Ant Ling",baseUrl:"https://api.ant-ling.com/v1",auth:{apiKey:ot("Ant Ling API key",["ANT_LING_API_KEY"])},models:Object.values(E3),api:xt()})}var e_n=function(e,t){return typeof e=="string"&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(n,r,i,o,a){return r?t?".jsx":".js":i&&(!o||!a)?n:i+o+"."+a.toLowerCase()+"js"}):e},gy=e=>{let t=import.meta.url.endsWith(".js")?e.replace(/\.ts$/,".js"):e;return import(e_n(t))},Ps;var Kit=async()=>Ps?Ps.anthropic():(await gy("./anthropic.ts")).anthropicOAuth,Vit=async()=>Ps?Ps.openaiCodex():(await gy("./openai-codex.ts")).openaiCodexOAuth,zit=async()=>Ps?Ps.openaiChatGPT():(await gy("./openai-chatgpt.ts")).openaiChatGPTOAuth,Yit=async()=>Ps?Ps.githubCopilot():(await gy("./github-copilot.ts")).githubCopilotOAuth,Jit=async()=>Ps?Ps.openrouter():(await gy("./openrouter.ts")).openRouterOAuth,Xit=async()=>Ps?Ps.kimiCoding():(await gy("./kimi-coding.ts")).kimiCodingOAuth,Zit=async()=>Ps?Ps.meta():(await gy("./meta.ts")).metaOAuth,eot=async()=>Ps?Ps.xai():(await gy("./xai.ts")).xaiOAuth,tot=async e=>Ps?Ps.radius(e):(await gy("./radius.ts")).createRadiusOAuth(e);t1();Ct();function t_n(){return{name:"Anthropic API key",login:async e=>{e.signal.throwIfAborted();let t=await e.prompt({type:"secret",message:"Enter Anthropic API key"});return e.signal.throwIfAborted(),{type:"api_key",key:t}},resolve:async({ctx:e,credential:t,signal:n})=>{if(n.throwIfAborted(),t?.key)return{auth:{apiKey:t.key},env:t.env,source:"stored credential"};let r=await e.env(e1);if(n.throwIfAborted(),r)return{auth:{headers:{Authorization:`Bearer ${r}`}},source:e1};for(let o of[Jse,Xse]){let a=await e.env(o);if(n.throwIfAborted(),a)return{auth:{apiKey:a},source:o}}let i={};for(let o of[X4,Z4,tq]){let a=await e.env(o);if(n.throwIfAborted(),!a)return;i[o]=a}for(let o of[eq,nq]){let a=await e.env(o);n.throwIfAborted(),a&&(i[o]=a)}return{auth:{},env:i,source:"workload identity federation"}}}}function not(){return Ye({id:"anthropic",name:"Anthropic",baseUrl:"https://api.anthropic.com",auth:{apiKey:t_n(),oauth:Ts({name:"Anthropic (Claude Pro/Max)",isSubscription:!0,load:Kit})},models:Object.values(w3),api:go()})}wpe();rd();Ct();function rot(e,t){return{...e,baseUrl:xpe(e,t)}}function iot(e,t){let n=L8(e,t);return n===e.id?t:{...t,onPayload:async(r,i)=>{let o={...r,model:n};return await t?.onPayload?.(o,i)??o}}}function n_n(e){return{stream:(t,n,r)=>pp(t,async()=>e.stream(rot(t,r),n,iot(t,r))),streamSimple:(t,n,r)=>pp(t,async()=>e.streamSimple(rot(t,r),n,iot(t,r)))}}function oot(){return Ye({id:"azure",name:"Azure",auth:{apiKey:ot("Azure OpenAI API key",["AZURE_OPENAI_API_KEY"])},models:Object.values(S3),api:{"azure-openai-responses":B8(),"openai-completions":n_n(xt())}})}Ct();function aot(){return Ye({id:"baseten",name:"Baseten",baseUrl:"https://inference.baseten.co/v1",auth:{apiKey:ot("Baseten API key",["BASETEN_API_KEY"])},models:Object.values(k3),api:xt()})}Ct();function sot(){return Ye({id:"cerebras",name:"Cerebras",baseUrl:"https://api.cerebras.ai/v1",auth:{apiKey:ot("Cerebras API key",["CEREBRAS_API_KEY"])},models:Object.values(T3),api:xt()})}Ct();var H0e="CLOUDFLARE_API_KEY",r_n="CLOUDFLARE_ACCOUNT_ID",i_n="CLOUDFLARE_GATEWAY_ID";async function $0e(e,t,n,r){let i=n?e===H0e?n.key:n.env?.[e]:void 0;if(i!==void 0)return i;r.throwIfAborted();let o=await t.env(e);return r.throwIfAborted(),o}async function cot(e,t,n,r){let i=await $0e(H0e,t,n,r),o=await $0e(r_n,t,n,r),a=e==="ai-gateway"?await $0e(i_n,t,n,r):void 0;if(!(!i||!o||e==="ai-gateway"&&!a))return{apiKey:i,env:{CLOUDFLARE_ACCOUNT_ID:o,...a?{CLOUDFLARE_GATEWAY_ID:a}:{}},source:n?"stored credential":H0e}}function uot(){return{name:"Cloudflare API key",login:async e=>{let t=await e.prompt({type:"secret",message:"Enter Cloudflare API key"}),n=await e.prompt({type:"text",message:"Enter Cloudflare account ID"});return{type:"api_key",key:t,env:{CLOUDFLARE_ACCOUNT_ID:n}}},resolve:async({ctx:e,credential:t,signal:n})=>{let r=await cot("workers-ai",e,t,n);if(r)return{auth:{apiKey:r.apiKey},env:r.env,source:r.source}}}}function lot(){return{name:"Cloudflare API key",login:async e=>{let t=await e.prompt({type:"secret",message:"Enter Cloudflare API key"}),n=await e.prompt({type:"text",message:"Enter Cloudflare account ID"}),r=await e.prompt({type:"text",message:"Enter Cloudflare AI Gateway ID"});return{type:"api_key",key:t,env:{CLOUDFLARE_ACCOUNT_ID:n,CLOUDFLARE_GATEWAY_ID:r}}},resolve:async({ctx:e,credential:t,signal:n})=>{let r=await cot("ai-gateway",e,t,n);if(r)return{auth:{headers:{"cf-aig-authorization":`Bearer ${r.apiKey}`,Authorization:null,"x-api-key":null}},env:r.env,source:r.source}}}}var j0e="CLOUDFLARE_ACCOUNT_ID",G0e="CLOUDFLARE_GATEWAY_ID";function q0e(e,t){if(!t)return e;let n=e.baseUrl.replaceAll(`{${j0e}}`,t[j0e]??`{${j0e}}`).replaceAll(`{${G0e}}`,t[G0e]??`{${G0e}}`);return n===e.baseUrl?e:{...e,baseUrl:n}}function kD(e){return{stream:(t,n,r)=>e.stream(q0e(t,r?.env),n,r),streamSimple:(t,n,r)=>e.streamSimple(q0e(t,r?.env),n,r)}}function dot(e){return{classify:(t,n,r)=>e.classify(q0e(t,r?.env),n,r)}}function pot(){return Ye({id:"cloudflare-ai-gateway",name:"Cloudflare AI Gateway",auth:{apiKey:lot()},models:Object.values(D3),api:{"anthropic-messages":kD(go()),"openai-completions":kD(xt()),"openai-responses":kD(Nc())}})}var got=()=>({classify:async(e,t,n)=>(await Promise.resolve().then(()=>(hot(),mot))).classify(e,t,n)});Ct();function Aot(){return Ye({id:"cloudflare-workers-ai",name:"Cloudflare Workers AI",auth:{apiKey:uot()},models:[...Object.values(L3),...Object.values(bAe)],api:kD(xt()),classifiers:{"cloudflare-workers-ai-system-one":dot(got())}})}Ct();function yot(){return Ye({id:"deepseek",name:"DeepSeek",baseUrl:"https://api.deepseek.com",auth:{apiKey:ot("DeepSeek API key",["DEEPSEEK_API_KEY"])},models:Object.values(M3),api:xt()})}Ct();function _ot(){return Ye({id:"fireworks",name:"Fireworks",baseUrl:"https://api.fireworks.ai/inference",auth:{apiKey:ot("Fireworks API key",["FIREWORKS_API_KEY"])},models:Object.values(F3),api:{"anthropic-messages":go(),"openai-completions":xt()}})}Ct();function Iot(){return Ye({id:"github-copilot",name:"GitHub Copilot",baseUrl:"https://api.individual.githubcopilot.com",auth:{apiKey:ot("GitHub Copilot token",["COPILOT_GITHUB_TOKEN"]),oauth:Ts({name:"GitHub Copilot",isSubscription:!0,load:Yit})},models:Object.values(Q3),filterModels:(e,t)=>{if(t?.type!=="oauth")return e;let n=t.availableModelIds;if(!Array.isArray(n)||!n.every(i=>typeof i=="string"))return e;let r=new Set(n);return e.filter(i=>r.has(i.id))},api:{"anthropic-messages":go(),"openai-completions":xt(),"openai-responses":Nc()}})}Ct();function vot(){return Ye({id:"google",name:"Google",baseUrl:"https://generativelanguage.googleapis.com/v1beta",auth:{apiKey:ot("Gemini API key",["GEMINI_API_KEY"])},models:Object.values($3),api:qO()})}Ct();var m_n="~/.config/gcloud/application_default_credentials.json",h_n={name:"Google Cloud credentials",login:async e=>{e.signal.throwIfAborted();let t=await e.prompt({type:"select",message:"Select Google Vertex AI authentication method:",options:[{id:"api-key",label:"Google Cloud API key"},{id:"adc",label:"Application Default Credentials"},{id:"service-account",label:"Service account credentials file"}]});if(e.signal.throwIfAborted(),t==="api-key")return{type:"api_key",key:await e.prompt({type:"secret",message:"Enter Google Cloud API key"})};if(t!=="adc"&&t!=="service-account")throw new Error(`Unknown Google Vertex AI auth method: ${t}`);e.notify({type:"info",message:t==="adc"?"Run `gcloud auth application-default login`, then provide the project and location.":"Provide a service account credentials file, project, and location.",links:[{label:"Application Default Credentials",url:"https://cloud.google.com/docs/authentication/provide-credentials-adc"}]});let n=await e.prompt({type:"text",message:"Enter Google Cloud project ID"}),r=await e.prompt({type:"text",message:"Enter Google Cloud location"}),i=t==="service-account"?await e.prompt({type:"text",message:"Enter service account credentials file path"}):void 0;return{type:"api_key",env:{GOOGLE_CLOUD_PROJECT:n,GOOGLE_CLOUD_LOCATION:r,...i?{GOOGLE_APPLICATION_CREDENTIALS:i}:{}}}},resolve:async({ctx:e,credential:t,signal:n})=>{let r=async u=>{n.throwIfAborted();let l=await e.env(u);return n.throwIfAborted(),l},i=t?.key??await r("GOOGLE_CLOUD_API_KEY");if(i)return{auth:{apiKey:i},source:t?.key?"stored credential":"GOOGLE_CLOUD_API_KEY"};let o=t?.env?.GOOGLE_APPLICATION_CREDENTIALS??await r("GOOGLE_APPLICATION_CREDENTIALS");n.throwIfAborted();let a=await e.fileExists(o??m_n);n.throwIfAborted();let s=t?.env?.GOOGLE_CLOUD_PROJECT??await r("GOOGLE_CLOUD_PROJECT")??await r("GCLOUD_PROJECT"),c=t?.env?.GOOGLE_CLOUD_LOCATION??await r("GOOGLE_CLOUD_LOCATION");if(a&&s&&c)return{auth:{},env:t?.env,source:t?"stored credential":"gcloud application default credentials"}}};function Eot(){return Ye({id:"google-vertex",name:"Google Vertex AI",auth:{apiKey:h_n},models:Object.values(j3),api:c3()})}Ct();function xot(){return Ye({id:"groq",name:"Groq",baseUrl:"https://api.groq.com/openai/v1",auth:{apiKey:ot("Groq API key",["GROQ_API_KEY"])},models:Object.values(q3),api:xt()})}Ct();function wot(){return Ye({id:"huggingface",name:"Hugging Face",baseUrl:"https://router.huggingface.co/v1",auth:{apiKey:ot("Hugging Face token",["HF_TOKEN"])},models:Object.values(V3),api:xt()})}Ct();function bot(){return Ye({id:"kimi-coding",name:"Kimi For Coding",baseUrl:"https://api.kimi.com/coding",auth:{apiKey:ot("Kimi API key",["KIMI_API_KEY"]),oauth:Ts({name:"Kimi Code (subscription)",isSubscription:!0,loginLabel:"Sign in with Kimi Code",load:Xit})},models:Object.values(Y3),api:go()})}Ct();function Sot(){return Ye({id:"meta",name:"Meta",baseUrl:"https://api.meta.ai/v1",auth:{apiKey:ot("Meta Model API key",["META_API_KEY"]),oauth:Ts({name:"Meta (Muse subscription)",isSubscription:!0,loginLabel:"Sign in with Meta",load:Zit})},models:Object.values(X3),api:Nc()})}Ct();function Cot(){return Ye({id:"minimax",name:"MiniMax",baseUrl:"https://api.minimax.io/anthropic",auth:{apiKey:ot("MiniMax API key",["MINIMAX_API_KEY"])},models:Object.values(ez),api:go()})}Ct();function kot(){return Ye({id:"minimax-cn",name:"MiniMax CN",baseUrl:"https://api.minimaxi.com/anthropic",auth:{apiKey:ot("MiniMax CN API key",["MINIMAX_CN_API_KEY"])},models:Object.values(nz),api:go()})}Ct();function Rot(){return Ye({id:"mistral",name:"Mistral",baseUrl:"https://api.mistral.ai",auth:{apiKey:ot("Mistral API key",["MISTRAL_API_KEY"])},models:Object.values(iz),api:l3()})}Ct();function Tot(){return Ye({id:"moonshotai",name:"Moonshot AI",baseUrl:"https://api.moonshot.ai/v1",auth:{apiKey:ot("Moonshot AI API key",["MOONSHOT_API_KEY"])},models:Object.values(az),api:xt()})}Ct();function Oot(){return Ye({id:"moonshotai-cn",name:"Moonshot AI CN",baseUrl:"https://api.moonshot.cn/v1",auth:{apiKey:ot("Moonshot AI API key",["MOONSHOT_API_KEY"])},models:Object.values(cz),api:xt()})}Ct();function Dot(){return Ye({id:"nvidia",name:"NVIDIA",baseUrl:"https://integrate.api.nvidia.com/v1",auth:{apiKey:ot("NVIDIA API key",["NVIDIA_API_KEY"])},models:Object.values(lz),api:xt()})}var Mot=()=>({classify:async(e,t,n)=>(await Promise.resolve().then(()=>(Not(),Lot))).classify(e,t,n)});Ct();function Bot(){return Ye({id:"openai",name:"OpenAI",baseUrl:"https://api.openai.com/v1",auth:{apiKey:ot("OpenAI API key",["OPENAI_API_KEY"]),oauth:Ts({name:"OpenAI (ChatGPT subscription)",isSubscription:!0,loginLabel:"Sign in with ChatGPT",load:zit})},models:[...Object.values(pz),...Object.values(SAe)],filterAllModels:(e,t)=>t?.type==="oauth"?e.filter(n=>!em(n,"classifier")):e,api:Nc(),classifiers:{"openai-decisions":Mot()}})}Ct();function Fot(){return Ye({id:"openai-codex",name:"OpenAI Codex (legacy)",baseUrl:"https://chatgpt.com/backend-api",auth:{oauth:Ts({name:"OpenAI (ChatGPT Plus/Pro)",isSubscription:!0,load:Vit})},models:Object.values(mz),api:h3()})}var RI=()=>({classify:async(e,t,n)=>(await Promise.resolve().then(()=>(Qot(),Uot))).classify(e,t,n)});Ct();var Wot="x-opencode-session";function C_n(e,t){let n=t.toLowerCase();return Object.keys(e??{}).some(r=>r.toLowerCase()===n)}function $ot(e){return!e?.sessionId||C_n(e.headers,Wot)?e:{...e,headers:{...e.headers,[Wot]:e.sessionId}}}function Ay(e){return{...e,stream:(t,n,r)=>e.stream(t,n,$ot(r)),streamSimple:(t,n,r)=>e.streamSimple(t,n,$ot(r))}}function Hot(){return Ye({id:"opencode",name:"OpenCode Zen",auth:{apiKey:ot("OpenCode API key",["OPENCODE_API_KEY"])},models:[...Object.values(gz),...Object.values(CAe)],api:{"anthropic-messages":Ay(go()),"google-generative-ai":Ay(qO()),"openai-completions":Ay(xt()),"openai-responses":Ay(Nc())},classifiers:{"typesafe-system-one":RI()}})}Ct();function jot(){return Ye({id:"opencode-go",name:"OpenCode Go",auth:{apiKey:ot("OpenCode API key",["OPENCODE_API_KEY"])},models:Object.values(yz),api:{"anthropic-messages":Ay(go()),"openai-completions":Ay(xt()),"openai-responses":Ay(Nc())}})}var Got=()=>({generateImages:async(e,t,n)=>(await Promise.resolve().then(()=>(PAe(),DAe))).generateImages(e,t,n)});Ct();var k_n="https://openrouter.ai/api/v1";function qot(){return Ye({id:"openrouter",name:"OpenRouter",baseUrl:k_n,auth:{apiKey:ot("OpenRouter API key",["OPENROUTER_API_KEY"]),oauth:Ts({name:"OpenRouter OAuth",loginLabel:"Sign in with OpenRouter",load:Jit})},models:[...Object.values(Iz),...Object.values(kAe),...Object.values(RAe)],api:{"anthropic-messages":go(),"openai-completions":xt()},images:{"openrouter-images":Got()},classifiers:{"typesafe-system-one":RI()}})}Ct();function Kot(){return Ye({id:"qwen-token-plan",name:"Qwen Token Plan",baseUrl:"https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",auth:{apiKey:ot("Qwen Token Plan API key",["QWEN_TOKEN_PLAN_API_KEY"])},models:Object.values(Ez),api:xt()})}Ct();function Vot(){return Ye({id:"qwen-token-plan-cn",name:"Qwen Token Plan CN",baseUrl:"https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",auth:{apiKey:ot("Qwen Token Plan CN API key",["QWEN_TOKEN_PLAN_CN_API_KEY"])},models:Object.values(wz),api:xt()})}Ct();function zot(){return Ye({id:"qwen-token-plan-individual",name:"Qwen Token Plan Individual",baseUrl:"https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",auth:{apiKey:ot("Qwen Token Plan Individual API key",["QWEN_TOKEN_PLAN_API_KEY"])},models:Object.values(Sz),api:xt()})}var V0e="https://radius.pi.dev";function R_n(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return typeof t.id=="string"&&typeof t.name=="string"&&typeof t.reasoning=="boolean"&&Array.isArray(t.input)&&typeof t.cost=="object"&&t.cost!==null&&!Array.isArray(t.cost)&&typeof t.contextWindow=="number"&&typeof t.maxTokens=="number"}function Yot(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let{baseUrl:t,models:n}=e;if(!(typeof t!="string"||!Array.isArray(n)))return{baseUrl:t,models:n.filter(R_n).map(r=>({...r}))}}function z0e(e){return(/^https?:\/\//iu.test(e)?e:`https://${e}`).replace(/\/+$/u,"")}function T_n(e){return Yot(e?.gatewayConfig)}function Y0e(e,t){return t.models.map(n=>({...n,api:"pi-messages",provider:e,baseUrl:t.baseUrl}))}function Jot(e,t){let n=T_n(t);return n?Y0e(e,n):[]}function O_n(e){let t=e.trim();return t.length>512?`${t.slice(0,512)}\u2026`:t}async function Xot(e,t,n){let r={accept:"application/json"};t&&(r.authorization=`Bearer ${t}`);let i=await fetch(new URL("/v1/config",e),{headers:r,signal:n});if(!i.ok)throw new Error(`Could not load Radius config from ${e}: ${i.status}: ${O_n(await i.text())}`);let o=Yot(await i.json());if(!o)throw new Error(`Invalid Radius config from ${e}`);return o}function Zot(e={}){let t=e.id??"radius",n=e.name??"Radius",r=z0e(e.gateway??V0e),i=r===z0e(V0e)?Object.values(kz).map(s=>({...s,provider:t})):[],o,a=y3();return{id:t,name:n,auth:{apiKey:ot("Radius API key",["RADIUS_API_KEY"]),oauth:Ts({name:n,load:()=>tot({name:n,gateway:r})})},getModels:()=>o??i,refreshModels:async s=>{let c=s.stored;if(c){let f=c.models.filter(m=>m.provider===t);if(!await s.publish({update:()=>{o=f}}))return}if(!c&&s.credential?.type==="oauth"){let f=Jot(t,s.credential);if(f.length>0&&!await s.publish({persist:{models:f,checkedAt:Date.now()},update:()=>{o=f}}))return}if(!s.allowNetwork||s.signal.aborted)return;let u=s.credential?.type==="oauth"?s.credential.access:s.credential?.key,l=await Xot(r,u,s.signal);if(s.signal.aborted)return;let p=Y0e(t,l);await s.publish({persist:{models:p,checkedAt:Date.now()},update:()=>{o=p}})},stream:(s,c,u)=>a.stream(s,c,u),streamSimple:(s,c,u)=>a.streamSimple(s,c,u)}}Ct();function eat(){return Ye({id:"together",name:"Together",baseUrl:"https://api.together.ai/v1",auth:{apiKey:ot("Together API key",["TOGETHER_API_KEY"])},models:Object.values(Tz),api:xt()})}Ct();function tat(){return Ye({id:"typesafe",name:"TypeSafe",auth:{apiKey:ot("TypeSafe API key",["TYPESAFE_API_KEY"])},models:Object.values(TAe),classifiers:{"typesafe-system-one":RI()}})}Ct();function nat(){return Ye({id:"vercel-ai-gateway",name:"Vercel AI Gateway",baseUrl:"https://ai-gateway.vercel.sh",auth:{apiKey:ot("Vercel AI Gateway API key",["AI_GATEWAY_API_KEY"])},models:[...Object.values(Pz),...Object.values(OAe)],api:go(),classifiers:{"typesafe-system-one":RI()}})}Ct();function rat(){return Ye({id:"xai",name:"xAI",baseUrl:"https://api.x.ai/v1",auth:{apiKey:ot("xAI API key",["XAI_API_KEY"]),oauth:Ts({name:"xAI (Grok/X subscription)",isSubscription:!0,loginLabel:"Sign in with SuperGrok or X Premium",load:eot})},models:Object.values(Nz),api:Nc()})}Ct();function iat(){return Ye({id:"xiaomi",name:"Xiaomi",baseUrl:"https://api.xiaomimimo.com/v1",auth:{apiKey:ot("Xiaomi API key",["XIAOMI_API_KEY"])},models:Object.values(Bz),api:xt()})}Ct();function oat(){return Ye({id:"xiaomi-token-plan-ams",name:"Xiaomi Token Plan AMS",baseUrl:"https://token-plan-ams.xiaomimimo.com/v1",auth:{apiKey:ot("Xiaomi Token Plan AMS API key",["XIAOMI_TOKEN_PLAN_AMS_API_KEY"])},models:Object.values(Uz),api:xt()})}Ct();function aat(){return Ye({id:"xiaomi-token-plan-cn",name:"Xiaomi Token Plan CN",baseUrl:"https://token-plan-cn.xiaomimimo.com/v1",auth:{apiKey:ot("Xiaomi Token Plan CN API key",["XIAOMI_TOKEN_PLAN_CN_API_KEY"])},models:Object.values(Wz),api:xt()})}Ct();function sat(){return Ye({id:"xiaomi-token-plan-sgp",name:"Xiaomi Token Plan SGP",baseUrl:"https://token-plan-sgp.xiaomimimo.com/v1",auth:{apiKey:ot("Xiaomi Token Plan SGP API key",["XIAOMI_TOKEN_PLAN_SGP_API_KEY"])},models:Object.values(Hz),api:xt()})}Ct();function cat(){return Ye({id:"zai",name:"Z.AI",baseUrl:"https://api.z.ai/api/coding/paas/v4",auth:{apiKey:ot("Z.AI API key",["ZAI_API_KEY"])},models:Object.values(Gz),api:xt()})}Ct();function uat(){return Ye({id:"zai-coding-cn",name:"Z.AI Coding CN",baseUrl:"https://open.bigmodel.cn/api/coding/paas/v4",auth:{apiKey:ot("Z.AI Coding CN API key",["ZAI_CODING_CN_API_KEY"])},models:Object.values(Kz),api:xt()})}function lat(e,t){return Vz[e]?.[t]}function dat(){return Object.keys(Vz)}function pat(e){let t=Vz[e];return Object.values(t??{})}function D_n(){return[Git(),qit(),not(),oot(),aot(),sot(),pot(),Aot(),yot(),_ot(),Iot(),vot(),Eot(),xot(),wot(),bot(),Sot(),Cot(),kot(),Rot(),Tot(),Oot(),Dot(),Bot(),Fot(),Hot(),jot(),qot(),Kot(),Vot(),zot(),Zot(),eat(),tat(),nat(),rat(),iat(),oat(),aat(),sat(),cat(),uat()]}function fat(e){let t=_Ue(e);for(let n of D_n())t.setProvider(n);return t}ud();var Bw=lat,hat=pat,wU=dat,gat=new Map;function P_n(e,t){return(n,r,i)=>{if(n.api!==e)throw new Error(`Mismatched api: ${n.api} expected ${e}`);return t(n,r,i)}}function L_n(e,t){return(n,r,i)=>{if(n.api!==e)throw new Error(`Mismatched api: ${n.api} expected ${e}`);return t(n,r,i)}}function N_n(e,t){gat.set(e.api,{provider:{api:e.api,stream:P_n(e.api,e.stream),streamSimple:L_n(e.api,e.streamSimple)},sourceId:t})}function i7(e){return gat.get(e)?.provider}var M_n=[["anthropic-messages",go()],["openai-completions",xt()],["openai-responses",Nc()],["openai-codex-responses",h3()],["azure-openai-responses",B8()],["google-generative-ai",qO()],["google-vertex",c3()],["mistral-conversations",l3()],["bedrock-converse-stream",F8()],["pi-messages",y3()]],Aat=new Map;function B_n(){for(let[e,t]of M_n)i7(e)||N_n({api:e,stream:t.stream,streamSimple:t.streamSimple}),Aat.set(e,i7(e))}B_n();var yat=fat(),F_n="<authenticated>";function _at(e){return typeof e=="string"&&e.trim().length>0}function mat(e,t){if(_at(t?.apiKey))return t;let n=nUe(e.provider,t?.env);return!n||n===F_n?t:{...t,apiKey:n}}function U_n(e){return _at(e?.apiKey)||typeof e?.headers?.["cf-aig-authorization"]=="string"}function Q_n(e){if(i7(e.api)!==Aat.get(e.api))return;let t=yat.getProvider(e.provider);return t?.getModels().some(n=>n.api===e.api)?t:void 0}function W_n(e){let t=i7(e);if(!t)throw new Error(`No API provider registered for api: ${e}`);return t}function J0e(e,t,n){let r=IA(t),i=Q_n(e);return i?e.provider.startsWith("cloudflare-")&&!U_n(n)?yat.streamSimple(e,r,n):i.streamSimple(e,r,mat(e,n)):W_n(e.api).streamSimple(e,r,mat(e,n))}async function TI(e,t,n){return J0e(e,t,n).result()}function a7(){return wU()}function X0e(e){return a7().includes(e)}var o7;function bU(e){return e.trim().toLowerCase()}function Z0e(){if(o7!==void 0)return o7;let e=new Map;for(let t of wU()){let n=hat(t);for(let r of n){let i={provider:t,modelId:r.id,contextWindowTokens:r.contextWindow},o=bU(r.id),a=e.get(o);a?a.push(i):e.set(o,[i])}}return o7={exact(t,n){let r=bU(t);return e.get(bU(n))?.find(i=>bU(i.provider)===r)},byModelId(t){return e.get(bU(t))??[]}},o7}var aJ=Hs(agt(),1);import{EventEmitter as SMn}from"node:events";var CMn=e=>{};function kMn(e={bodyTimeout:0,headersTimeout:0}){let t=new aJ.Agent(e);return SMn.prototype.on.call(t,"error",CMn),async(r,i)=>await aJ.fetch(r,{...i,dispatcher:t})}var sgt;function RMn(){return sgt??=kMn(),sgt}var TMn=new Set(["google-generative-ai","google-vertex"]);function OMn(e){return e!==void 0&&!TMn.has(e)}function Rg(e){return OMn(e)?RMn():globalThis.fetch}po();kn();en();var DMn=d.Object({candidateIndex:d.Number(),badDecision:d.String({minLength:1}),betterDecision:d.String({minLength:1}),rationale:d.String({minLength:1}),confidence:d.Number({minimum:0,maximum:1}),riskLevel:d.Union([d.Literal("low"),d.Literal("medium"),d.Literal("high")]),strategicPerspective:d.String({minLength:1})}),cgt=d.Object({valid:d.Boolean(),taskId:d.String({minLength:1}),candidates:d.Array(DMn,{minItems:1,maxItems:5}),sourcePrincipleId:d.Optional(d.String()),sourcePainId:d.Optional(d.String()),contextRefs:d.Array(d.String()),generatedAt:d.String({minLength:1}),reason:d.Optional(d.String())}),PMn=new Set(["low","medium","high"]),NQ=class{async validate(t,n){let r=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};let i=t;if(i.taskId!==n&&r.push(`taskId mismatch: expected ${n}, got ${String(i.taskId)}`),i.valid!==!0&&r.push("output.valid must be true"),!Array.isArray(i.candidates))r.push("candidates must be an array");else{(i.candidates.length<1||i.candidates.length>5)&&r.push("candidates must have 1-5 items");for(let o=0;o<i.candidates.length;o++){let a=i.candidates[o];if(!a){r.push(`candidates[${o}] is null/undefined`);continue}typeof a.candidateIndex!="number"&&r.push(`candidates[${o}].candidateIndex must be number`),(typeof a.badDecision!="string"||a.badDecision.trim()==="")&&r.push(`candidates[${o}].badDecision must be non-empty string`),(typeof a.betterDecision!="string"||a.betterDecision.trim()==="")&&r.push(`candidates[${o}].betterDecision must be non-empty string`),(typeof a.rationale!="string"||a.rationale.trim()==="")&&r.push(`candidates[${o}].rationale must be non-empty string`),typeof a.confidence!="number"?r.push(`candidates[${o}].confidence must be number`):(a.confidence<0||a.confidence>1)&&r.push(`candidates[${o}].confidence must be in [0, 1]`),(typeof a.riskLevel!="string"||!PMn.has(a.riskLevel))&&r.push(`candidates[${o}].riskLevel must be low|medium|high`),(typeof a.strategicPerspective!="string"||a.strategicPerspective.trim()==="")&&r.push(`candidates[${o}].strategicPerspective must be non-empty string`)}}return Array.isArray(i.contextRefs)||r.push("contextRefs must be an array"),(typeof i.generatedAt!="string"||i.generatedAt.trim()==="")&&r.push("generatedAt must be non-empty string"),r.length>0?{valid:!1,errors:r,errorCategory:"output_invalid"}:{valid:!0,errors:[]}}};en();var LMn=d.Object({title:d.String({minLength:1}),rationale:d.String({minLength:1}),scope:d.String({minLength:1}),confidence:d.Number({minimum:0,maximum:1})}),ugt=d.Object({taskId:d.String({minLength:1}),sourceDreamerArtifactId:d.String({minLength:1}),thesis:d.String({minLength:1}),principleCandidate:LMn,risks:d.Array(d.String()),generatedAt:d.String({minLength:1})}),MQ=class{async validate(t,n){let r=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};let i=t;if(i.taskId!==n&&r.push(`taskId mismatch: expected ${n}, got ${String(i.taskId)}`),(typeof i.sourceDreamerArtifactId!="string"||i.sourceDreamerArtifactId.trim()==="")&&r.push("sourceDreamerArtifactId must be non-empty string"),(typeof i.thesis!="string"||i.thesis.trim()==="")&&r.push("thesis must be non-empty string"),typeof i.principleCandidate!="object"||i.principleCandidate===null)r.push("principleCandidate must be an object");else{let o=i.principleCandidate;(typeof o.title!="string"||o.title.trim()==="")&&r.push("principleCandidate.title must be non-empty string"),(typeof o.rationale!="string"||o.rationale.trim()==="")&&r.push("principleCandidate.rationale must be non-empty string"),(typeof o.scope!="string"||o.scope.trim()==="")&&r.push("principleCandidate.scope must be non-empty string"),typeof o.confidence!="number"?r.push("principleCandidate.confidence must be number"):(o.confidence<0||o.confidence>1)&&r.push("principleCandidate.confidence must be in [0, 1]")}return Array.isArray(i.risks)?i.risks.some(o=>typeof o!="string")&&r.push("risks must contain only strings"):r.push("risks must be an array"),(typeof i.generatedAt!="string"||i.generatedAt.trim()==="")&&r.push("generatedAt must be non-empty string"),r.length>0?{valid:!1,errors:r,errorCategory:"output_invalid"}:{valid:!0,errors:[]}}};en();function Qxe(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e,n=r=>Object.hasOwn(t,r)&&typeof t[r]=="string"&&t[r].trim()!=="";return n("ownerIntent")&&n("targetBehavior")&&n("forbiddenBehavior")&&n("evidenceSource")&&n("validationExpectation")}function ZI(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(!Object.hasOwn(t,"intentContract"))return null;let n=t.intentContract;return Qxe(n)?n:null}var lgt=new Set(["__proto__","constructor","prototype"]);function Uxe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yP(e){if(!Uxe(e)||Object.keys(e).some(t=>lgt.has(t))||e.version!==1||!Array.isArray(e.requiredFacts))return!1;for(let t of e.requiredFacts)if(!Uxe(t)||Object.keys(t).some(n=>lgt.has(n))||typeof t.factKind!="string"||t.factKind.trim()===""||typeof t.required!="boolean"||typeof t.textualBasis!="string"||t.textualBasis.trim()==="")return!1;return!0}function Ru(e){if(!Uxe(e)||!Object.hasOwn(e,"executionConditions"))return{conditions:null,corrupted:!1};let t=e.executionConditions;return yP(t)?{conditions:t,corrupted:!1}:{conditions:null,corrupted:!0}}function sJ(e){return e.toLowerCase().replace(/[\s`'"“”‘’、,。:;!?()\]{}()【】,.;:!?\-—_/\\*#]+/gu,"")}var NMn=4;function cJ(e,t){let n=sJ(e);return n.length<NMn||t.length===0?!1:t.includes(n)}var dgt=["confirm","approv","\u6279\u51C6","\u786E\u8BA4"];function BQ(e){let t=[],n=(o,a)=>{typeof a=="string"&&a.trim()!==""&&t.push({name:o,text:a})};if(typeof e=="object"&&e!==null){let o=e,a=typeof o.principleDraft=="object"&&o.principleDraft!==null?o.principleDraft:{};if(n("principleDraft.statement",a.statement),typeof o.intentContract=="object"&&o.intentContract!==null){let s=o.intentContract;n("intentContract.ownerIntent",s.ownerIntent),n("intentContract.targetBehavior",s.targetBehavior),n("intentContract.forbiddenBehavior",s.forbiddenBehavior),n("intentContract.validationExpectation",s.validationExpectation)}}let r=sJ(t.map(o=>o.text).join(" ")),i=t.filter(o=>dgt.some(a=>o.text.toLowerCase().includes(a))).map(o=>o.name);return{normalisedText:r,approvalSignalFields:i,hasApprovalSignal:i.length>0}}function MMn(e){if(typeof e!="string"||e.length===0)return[];let t=e.toLowerCase();return dgt.filter(n=>t.includes(n))}function uJ(e){let t=e.requiredFacts.filter(r=>r.required).map(r=>r.factKind.toLowerCase()).join(" ");if(/approv/.test(t))return null;if(e.scribeMaterial.hasApprovalSignal)return{pool:"scribe",fields:e.scribeMaterial.approvalSignalFields};let n=MMn(e.upstreamNormalisedText);return n.length>0?{pool:"upstream",fields:n}:null}var BMn=d.Object({title:d.String({minLength:1}),statement:d.String({minLength:1}),rationale:d.String({minLength:1}),applicability:d.Array(d.String()),antiPatterns:d.Array(d.String()),confidence:d.Number({minimum:0,maximum:1})}),FMn=d.Object({dreamerArtifactId:d.Optional(d.String()),philosopherArtifactId:d.String({minLength:1})}),UMn=d.Object({ownerIntent:d.String({minLength:1}),targetBehavior:d.String({minLength:1}),forbiddenBehavior:d.String({minLength:1}),evidenceSource:d.String({minLength:1}),validationExpectation:d.String({minLength:1})}),QMn=d.Object({version:d.Literal(1),requiredFacts:d.Array(d.Object({factKind:d.String({minLength:1}),required:d.Boolean(),textualBasis:d.String({minLength:1})}))}),pgt=d.Object({taskId:d.String({minLength:1}),sourcePhilosopherArtifactId:d.String({minLength:1}),principleDraft:BMn,sourceTrace:FMn,risks:d.Array(d.String()),generatedAt:d.String({minLength:1}),intentContract:UMn,executionConditions:QMn,ownerRequirementGaps:d.Optional(d.Array(d.String({minLength:1})))});function Sb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var _P=class{requireRuleCodeContracts;constructor(t={}){this.requireRuleCodeContracts=t.requireRuleCodeContracts??!1}async validate(t,n,r,i){let o=[];if(!Sb(t))return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};if((!Object.hasOwn(t,"taskId")||t.taskId!==n)&&o.push(`taskId mismatch: expected ${n}, got ${String(t.taskId)}`),!Object.hasOwn(t,"sourcePhilosopherArtifactId")||typeof t.sourcePhilosopherArtifactId!="string"||t.sourcePhilosopherArtifactId.trim()===""?o.push("sourcePhilosopherArtifactId must be non-empty string"):r&&t.sourcePhilosopherArtifactId!==r&&o.push(`sourcePhilosopherArtifactId mismatch: expected ${r}, got ${t.sourcePhilosopherArtifactId}`),!Object.hasOwn(t,"principleDraft")||!Sb(t.principleDraft))o.push("principleDraft must be an object");else{let u=t.principleDraft;(!Object.hasOwn(u,"title")||typeof u.title!="string"||u.title.trim()==="")&&o.push("principleDraft.title must be non-empty string"),(!Object.hasOwn(u,"statement")||typeof u.statement!="string"||u.statement.trim()==="")&&o.push("principleDraft.statement must be non-empty string"),(!Object.hasOwn(u,"rationale")||typeof u.rationale!="string"||u.rationale.trim()==="")&&o.push("principleDraft.rationale must be non-empty string"),!Object.hasOwn(u,"applicability")||!Array.isArray(u.applicability)?o.push("principleDraft.applicability must be an array"):u.applicability.every(l=>typeof l=="string")||o.push("principleDraft.applicability must be an array of strings"),!Object.hasOwn(u,"antiPatterns")||!Array.isArray(u.antiPatterns)?o.push("principleDraft.antiPatterns must be an array"):u.antiPatterns.every(l=>typeof l=="string")||o.push("principleDraft.antiPatterns must be an array of strings"),!Object.hasOwn(u,"confidence")||typeof u.confidence!="number"?o.push("principleDraft.confidence must be number"):(u.confidence<0||u.confidence>1)&&o.push("principleDraft.confidence must be in [0, 1]")}if(!Object.hasOwn(t,"sourceTrace")||!Sb(t.sourceTrace))o.push("sourceTrace must be an object");else{let u=t.sourceTrace;!Object.hasOwn(u,"philosopherArtifactId")||typeof u.philosopherArtifactId!="string"||u.philosopherArtifactId.trim()===""?o.push("sourceTrace.philosopherArtifactId must be non-empty string"):r&&u.philosopherArtifactId!==r&&o.push(`sourceTrace.philosopherArtifactId mismatch: expected ${r}, got ${u.philosopherArtifactId}`),Object.hasOwn(u,"dreamerArtifactId")&&u.dreamerArtifactId!==void 0&&(typeof u.dreamerArtifactId!="string"||u.dreamerArtifactId.trim()==="")&&o.push("sourceTrace.dreamerArtifactId must be non-empty string when present")}!Object.hasOwn(t,"risks")||!Array.isArray(t.risks)?o.push("risks must be an array"):t.risks.every(u=>typeof u=="string")||o.push("risks must be an array of strings"),Object.hasOwn(t,"ownerRequirementGaps")&&t.ownerRequirementGaps!==void 0&&(Array.isArray(t.ownerRequirementGaps)?t.ownerRequirementGaps.every(u=>typeof u=="string"&&u.trim()!=="")||o.push("ownerRequirementGaps must be an array of non-empty strings"):o.push("ownerRequirementGaps must be an array"));let a=Object.hasOwn(t,"intentContract")&&t.intentContract!==void 0;this.requireRuleCodeContracts&&!a&&o.push("intentContract is required for new RuleCode generation"),a&&(Qxe(t.intentContract)||o.push("intentContract must contain non-empty string fields: ownerIntent, targetBehavior, forbiddenBehavior, evidenceSource, validationExpectation"));let s=Object.hasOwn(t,"executionConditions")&&t.executionConditions!==void 0;this.requireRuleCodeContracts&&!s&&o.push("executionConditions is required for new RuleCode generation");let c=!1;if(s&&(c=yP(t.executionConditions),c||o.push("executionConditions must be { version: 1, requiredFacts: [{ factKind: non-empty string, required: boolean, textualBasis: non-empty string }] }")),this.requireRuleCodeContracts&&c&&i?.upstreamAnchorMaterial!=null&&i.upstreamAnchorMaterial.normalisedText.length>0&&Sb(t.executionConditions)&&Array.isArray(t.executionConditions.requiredFacts)){let u=BQ(t).normalisedText+" "+i.upstreamAnchorMaterial.normalisedText;for(let[l,p]of t.executionConditions.requiredFacts.entries())Sb(p)&&p.required===!0&&(typeof p.textualBasis!="string"||typeof p.factKind!="string"||cJ(p.textualBasis,u)||o.push(`executionConditions.requiredFacts[${l}] (factKind '${p.factKind}') textualBasis ("${p.textualBasis.replace(/\s+/g," ").slice(0,120)}") is not a continuous verbatim span of the Owner-attributed material \u2014 rewrite it as one continuous original sentence copied from the source (no citation labels, no ellipsis-omitted reconstruction)`))}if(this.requireRuleCodeContracts&&c&&i!=null&&Sb(t.executionConditions)&&Array.isArray(t.executionConditions.requiredFacts)){let u=t.executionConditions.requiredFacts.flatMap(p=>!Sb(p)||typeof p.factKind!="string"||typeof p.required!="boolean"?[]:[{factKind:p.factKind,required:p.required}]),l=uJ({scribeMaterial:BQ(t),upstreamNormalisedText:i.upstreamAnchorMaterial?.normalisedText??"",requiredFacts:u});l!==null&&o.push(`executionConditions: ${l.pool} material carries approval semantics (${l.fields.join(", ")}) but no REQUIRED approval-kind fact is declared \u2014 declare the approval dependency (factKind e.g. 'design_approval', required: true) with its textual basis, or correct the draft text if it overstates the requirement`)}return(!Object.hasOwn(t,"generatedAt")||typeof t.generatedAt!="string"||t.generatedAt.trim()==="")&&o.push("generatedAt must be non-empty string"),o.length>0?{valid:!1,errors:o,errorCategory:"output_invalid"}:{valid:!0,errors:[]}}};function fgt(e){if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,"intentContract"))return!1;let t=Reflect.get(e,"intentContract");if(typeof t!="string")return!1;let n;try{n=JSON.parse(t)}catch{return!1}return typeof n!="object"||n===null||Array.isArray(n)?!1:(Reflect.set(e,"intentContract",n),!0)}en();var Wxe=new Set(["read","search","write","execute","agent","other"]);function mgt(e){return typeof e=="string"&&Wxe.has(e)}var IP=Object.freeze({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",execute_command:"execute",run_script:"execute",code_interpreter:"execute",sessions_spawn:"agent"});var WMn=["unregistered_scope","workspace_mismatch","session_mismatch","task_mismatch","spec_changed","scope_mismatch","declaration_revoked","source_unavailable","malformed_declaration","capability_unsupported","host_identity_unavailable","project_scope_mismatch","declaration_unavailable","declaration_invalid","spec_path_invalid","spec_digest_mismatch","target_scope_unknown","action_scope_unknown"];function $Mn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function HMn(e,t){return t.every(n=>Object.hasOwn(e,n))}function jMn(e){return typeof e=="string"&&e.trim().length>0}function Cb(e){return e===null||jMn(e)}function GMn(e){return e==="approved"||e==="not_approved"||e==="not_required"||e==="unknown"}function qMn(e){return typeof e=="string"&&WMn.includes(e)}function FQ(e){return!$Mn(e)||!HMn(e,["version","sourceRef","revision","requiresApproval","taskRef","specDigest","scopeRef","decisionTaskRef","decisionSpecDigest","decisionScopeRef","resolution","revoked"])||e.version!==1||!Cb(e.sourceRef)||e.revision!==null&&(typeof e.revision!="number"||!Number.isSafeInteger(e.revision)||e.revision<1)||typeof e.requiresApproval!="boolean"||!Cb(e.taskRef)||!Cb(e.specDigest)||!Cb(e.scopeRef)||!Cb(e.decisionTaskRef)||!Cb(e.decisionSpecDigest)||!Cb(e.decisionScopeRef)||!GMn(e.resolution)||typeof e.revoked!="boolean"||Object.hasOwn(e,"invalidationReason")&&!qMn(e.invalidationReason)||!Object.hasOwn(e,"invalidationReason")&&e.invalidationReason!==void 0?!1:e.resolution==="unknown"?!0:e.resolution==="not_required"&&e.requiresApproval===!1&&e.sourceRef===null?e.taskRef!==null&&e.revision===null&&e.decisionTaskRef===null&&e.decisionSpecDigest===null&&e.decisionScopeRef===null&&!e.revoked:!([e.sourceRef,e.revision,e.taskRef,e.specDigest,e.scopeRef,e.decisionTaskRef,e.decisionSpecDigest,e.decisionScopeRef].some(n=>n===null)||e.taskRef!==e.decisionTaskRef||e.specDigest!==e.decisionSpecDigest||e.scopeRef!==e.decisionScopeRef||e.revoked&&e.resolution!=="not_approved")}var KMn=new Set(["read","search","write","execute","agent","other"]),VMn=new Set(["yes","no","unknown"]),zMn=new Set(["success","failure","blocked"]),YMn=new Set(["available","unavailable"]),JMn=new Set(["__proto__","constructor","prototype"]),XMn={valid:!0,errors:[]};function dJ(e){return e.length===0?XMn:{valid:!1,errors:e}}function kb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pJ(e){for(let t of Object.keys(e))if(JMn.has(t))return!1;return!0}function ZMn(e){return typeof e=="number"&&Number.isFinite(e)}function lJ(e){return e===null||typeof e=="number"&&Number.isFinite(e)&&e>=0}function UQ(e){if(typeof e!="string"||!Object.hasOwn(IP,e))return"other";let t=IP[e];return t!==void 0?t:"other"}function hgt(e){if(!kb(e))return{valid:!1,errors:["record must be a plain object"]};if(!pJ(e))return{valid:!1,errors:["record must not carry prototype-pollution keys"]};let t=[];ZMn(e.sequenceId)||t.push("sequenceId must be a finite number");let{toolName:n}=e;(typeof n!="string"||n.length===0)&&t.push("toolName must be a non-empty string");let{canonicalKind:r}=e;(typeof r!="string"||!KMn.has(r))&&t.push("canonicalKind must be a valid CanonicalKind");let{normalizedPath:i}=e;i!==null&&typeof i!="string"&&t.push("normalizedPath must be a string or null"),kb(e.paramsSummary)||t.push("paramsSummary must be a plain object");let{outcome:o}=e;return(typeof o!="string"||!zMn.has(o))&&t.push("outcome must be success | failure | blocked"),dJ(t)}function ggt(e){if(!kb(e))return{valid:!1,errors:["history window must be a plain object"]};if(!pJ(e))return{valid:!1,errors:["history window must not carry prototype-pollution keys"]};let t=[],{status:n}=e;(typeof n!="string"||!YMn.has(n))&&t.push("status must be available | unavailable");let{unavailableReason:r}=e;r!==void 0&&typeof r!="string"&&t.push("unavailableReason must be a string or undefined"),typeof e.truncated!="boolean"&&t.push("truncated must be a boolean");let{calls:i}=e;if(!Array.isArray(i))t.push("calls must be an array");else for(let o=0;o<i.length;o++){let a=hgt(i[o]);a.valid||t.push(`calls[${o}] invalid: ${a.errors.join("; ")}`)}return dJ(t)}function Agt(e){if(!kb(e))return{valid:!1,errors:["facts must be a plain object"]};if(!pJ(e))return{valid:!1,errors:["facts must not carry prototype-pollution keys"]};let t=[],{priorReadOfTarget:n}=e;return(typeof n!="string"||!VMn.has(n))&&t.push("priorReadOfTarget must be yes | no | unknown"),lJ(e.readCount)||t.push("readCount must be a non-negative finite number or null"),lJ(e.writeCount)||t.push("writeCount must be a non-negative finite number or null"),lJ(e.uniqueWritePathCount)||t.push("uniqueWritePathCount must be a non-negative finite number or null"),lJ(e.sameActionBlockCount)||t.push("sameActionBlockCount must be a non-negative finite number or null"),Object.hasOwn(e,"designGate")&&!FQ(e.designGate)&&t.push("designGate must be a valid versioned host fact"),dJ(t)}function qc(e){if(!kb(e))return{valid:!1,errors:["context must be a plain object"]};if(!pJ(e))return{valid:!1,errors:["context must not carry prototype-pollution keys"]};let t=[];e.version!==2&&t.push("version must be 2");let n=ggt(e.history);n.valid||t.push(`history invalid: ${n.errors.join("; ")}`);let r=Agt(e.facts);r.valid||t.push(`facts invalid: ${r.errors.join("; ")}`);let{history:i}=e,{facts:o}=e;return n.valid&&r.valid&&kb(i)&&kb(o)&&i.status==="unavailable"&&(o.priorReadOfTarget!=="unknown"&&t.push('unavailable invariant: priorReadOfTarget must be "unknown" when history is unavailable'),o.readCount!==null&&t.push("unavailable invariant: readCount must be null when history is unavailable"),o.writeCount!==null&&t.push("unavailable invariant: writeCount must be null when history is unavailable"),o.uniqueWritePathCount!==null&&t.push("unavailable invariant: uniqueWritePathCount must be null when history is unavailable"),o.sameActionBlockCount!==null&&t.push("unavailable invariant: sameActionBlockCount must be null when history is unavailable")),dJ(t)}function ev(e,t,n){if(e.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let r=0,i=0,o=new Set,a=t===null?"unknown":"no",{calls:s}=e;for(let c of s){let u=c.canonicalKind;u==="read"||u==="search"?(r++,t!==null&&c.normalizedPath===t&&(a="yes")):u==="write"&&(i++,typeof c.normalizedPath=="string"&&o.add(c.normalizedPath))}return{priorReadOfTarget:a,readCount:r,writeCount:i,uniqueWritePathCount:o.size,sameActionBlockCount:n}}var ygt={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(ygt);var $xe={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze($xe.calls);Object.freeze($xe);var _gt={version:2,history:$xe,facts:ygt};Object.freeze(_gt);var Wa=_gt;var Egt=d.Object({scribeArtifactId:d.String({minLength:1}),philosopherArtifactId:d.Optional(d.String({minLength:1})),dreamerArtifactId:d.Optional(d.String({minLength:1}))}),Hxe=d.Object({taskId:d.String({minLength:1}),sourceScribeArtifactId:d.String({minLength:1}),implementationCode:d.String({minLength:1}),goldenTraceCases:d.Array(d.Object({caseId:d.String({minLength:1}),kind:d.Union([d.Literal("positive"),d.Literal("negative")]),toolName:d.String({minLength:1}),params:d.Record(d.String(),d.Unknown()),expectedDecision:d.Union([d.Literal("allow"),d.Literal("block"),d.Literal("propose_correction")]),expectedProposedParams:d.Optional(d.Record(d.String(),d.Unknown())),expectedApplicationMode:d.Optional(d.Union([d.Literal("shadow"),d.Literal("live")]))}),{minItems:2,maxItems:10}),affectedTools:d.Array(d.String({minLength:1}),{minItems:1}),implementationSummary:d.String({minLength:1}),risks:d.Array(d.String()),sourceTrace:Egt,generatedAt:d.String({minLength:1}),requiresContextVersion:d.Optional(d.Literal(2)),evidenceRefs:d.Optional(d.Array(d.String({minLength:1})))});function Rb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var eBn=new Set(["allow","block","propose_correction"]),Igt=10,vgt=2;function tBn(e){let t=[];if(!Array.isArray(e))return t.push("goldenTraceCases must be an array"),t;e.length<vgt&&t.push(`goldenTraceCases must contain at least ${vgt} cases (1 positive + 1 negative), got ${e.length}`),e.length>Igt&&t.push(`goldenTraceCases must contain at most ${Igt} cases, got ${e.length}`);let n=!1,r=!1;return e.forEach((i,o)=>{let a=`goldenTraceCases[${o}]`;if(!Rb(i)){t.push(`${a} must be an object`);return}(!Object.hasOwn(i,"caseId")||typeof i.caseId!="string"||i.caseId.trim()==="")&&t.push(`${a}.caseId must be a non-empty string`),!Object.hasOwn(i,"kind")||i.kind!=="positive"&&i.kind!=="negative"?t.push(`${a}.kind must be 'positive' or 'negative'`):i.kind==="positive"?n=!0:r=!0,(!Object.hasOwn(i,"toolName")||typeof i.toolName!="string"||i.toolName.trim()==="")&&t.push(`${a}.toolName must be a non-empty string`),(!Object.hasOwn(i,"params")||!Rb(i.params))&&t.push(`${a}.params must be an object`),!Object.hasOwn(i,"expectedDecision")||typeof i.expectedDecision!="string"||!eBn.has(i.expectedDecision)?t.push(`${a}.expectedDecision must be one of allow|block|propose_correction, got ${String(i.expectedDecision)}`):i.kind==="positive"&&i.expectedDecision!=="allow"&&t.push(`${a}: positive cases must expect allow (got ${i.expectedDecision})`),i.expectedDecision==="propose_correction"&&((!Object.hasOwn(i,"expectedProposedParams")||!Rb(i.expectedProposedParams))&&t.push(`${a}.expectedProposedParams is required when expectedDecision is propose_correction`),(!Object.hasOwn(i,"expectedApplicationMode")||i.expectedApplicationMode!=="shadow"&&i.expectedApplicationMode!=="live")&&t.push(`${a}.expectedApplicationMode must be shadow or live when expectedDecision is propose_correction`))}),Array.isArray(e)&&e.length>0&&(n||t.push("goldenTraceCases must include at least one positive case"),r||t.push("goldenTraceCases must include at least one negative case")),t}function nBn(e){let t=[];return Array.isArray(e)?(e.length===0&&t.push("affectedTools must be a non-empty array"),e.forEach((n,r)=>{(typeof n!="string"||n.trim()==="")&&t.push(`affectedTools[${r}] must be a non-empty string`)}),t):(t.push("affectedTools must be an array"),t)}var vP=class{async validate(t,n,r){let i=[];if(!Rb(t))return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};let o=t;if((!Object.hasOwn(o,"taskId")||o.taskId!==n)&&i.push(`taskId mismatch: expected ${n}, got ${String(o.taskId)}`),!Object.hasOwn(o,"sourceScribeArtifactId")||typeof o.sourceScribeArtifactId!="string"||o.sourceScribeArtifactId.trim()===""?i.push("sourceScribeArtifactId must be non-empty string"):r&&o.sourceScribeArtifactId!==r&&i.push(`sourceScribeArtifactId mismatch: expected ${r}, got ${o.sourceScribeArtifactId}`),(!Object.hasOwn(o,"implementationCode")||typeof o.implementationCode!="string"||o.implementationCode.trim()==="")&&i.push("implementationCode must be a non-empty string"),(!Object.hasOwn(o,"implementationSummary")||typeof o.implementationSummary!="string"||o.implementationSummary.trim()==="")&&i.push("implementationSummary must be a non-empty string"),!Object.hasOwn(o,"goldenTraceCases"))i.push("goldenTraceCases is required");else{let u=tBn(o.goldenTraceCases);i.push(...u)}let a=Object.hasOwn(o,"requiresContextVersion"),{requiresContextVersion:s}=o,c=a&&typeof s=="number"&&s===2;if(a&&(typeof s!="number"||s!==2)&&i.push(`requiresContextVersion must be 2 (only v2 is supported), got ${String(s)}`),Array.isArray(o.goldenTraceCases)){let u=o.goldenTraceCases;for(let l=0;l<u.length;l++){let p=u[l];if(!Rb(p))continue;if(c&&Object.hasOwn(p,"expectedDecision")&&p.expectedDecision==="propose_correction"&&i.push(`goldenTraceCases[${l}].expectedDecision 'propose_correction' is forbidden in v2 seed rules (only allow/block permitted)`),!Object.hasOwn(p,"ruleContext")){c&&i.push(`goldenTraceCases[${l}].ruleContext is required when requiresContextVersion: 2 is declared`);continue}let f=p.ruleContext;if(!c){i.push(`goldenTraceCases[${l}].ruleContext is only allowed when requiresContextVersion: 2 is declared (v1 rules must not read input.context)`);continue}if(f===void 0){i.push(`goldenTraceCases[${l}].ruleContext is required when requiresContextVersion: 2 is declared`);continue}let m=qc(f);m.valid||i.push(`goldenTraceCases[${l}].ruleContext invalid: ${m.errors.join("; ")}`)}}if(!Object.hasOwn(o,"affectedTools"))i.push("affectedTools is required");else{let u=nBn(o.affectedTools);i.push(...u)}if(!Object.hasOwn(o,"sourceTrace")||!Rb(o.sourceTrace))i.push("sourceTrace must be an object");else{let u=o.sourceTrace;!Object.hasOwn(u,"scribeArtifactId")||typeof u.scribeArtifactId!="string"||u.scribeArtifactId.trim()===""?i.push("sourceTrace.scribeArtifactId must be non-empty string"):r&&u.scribeArtifactId!==r&&i.push(`sourceTrace.scribeArtifactId mismatch: expected ${r}, got ${u.scribeArtifactId}`),Object.hasOwn(u,"philosopherArtifactId")&&u.philosopherArtifactId!==void 0&&(typeof u.philosopherArtifactId!="string"||u.philosopherArtifactId.trim()==="")&&i.push("sourceTrace.philosopherArtifactId must be non-empty string if present"),Object.hasOwn(u,"dreamerArtifactId")&&u.dreamerArtifactId!==void 0&&(typeof u.dreamerArtifactId!="string"||u.dreamerArtifactId.trim()==="")&&i.push("sourceTrace.dreamerArtifactId must be non-empty string if present")}return!Object.hasOwn(o,"risks")||!Array.isArray(o.risks)?i.push("risks must be an array"):o.risks.every(u=>typeof u=="string")||i.push("risks must be an array of strings"),typeof o.sourceScribeArtifactId=="string"&&o.sourceScribeArtifactId.trim()!==""&&Rb(o.sourceTrace)&&Object.hasOwn(o.sourceTrace,"scribeArtifactId")&&typeof o.sourceTrace.scribeArtifactId=="string"&&o.sourceScribeArtifactId!==o.sourceTrace.scribeArtifactId&&i.push("sourceScribeArtifactId and sourceTrace.scribeArtifactId must match"),(!Object.hasOwn(o,"generatedAt")||typeof o.generatedAt!="string"||o.generatedAt.trim()==="")&&i.push("generatedAt must be non-empty string"),c&&(!Object.hasOwn(o,"evidenceRefs")||!Array.isArray(o.evidenceRefs)||o.evidenceRefs.length===0?i.push("evidenceRefs is required and must be a non-empty array for v2 rules"):o.evidenceRefs.every(u=>typeof u=="string"&&u.trim()!=="")||i.push("evidenceRefs must be an array of non-empty strings")),i.length>0?{valid:!1,errors:i,errorCategory:"output_invalid"}:{valid:!0,errors:[]}}};var Dy=Object.freeze([Object.freeze({capabilityId:"pd_status",channel:"cli",cliCommand:"pd activation list --json"}),Object.freeze({capabilityId:"rulecode_deactivate",channel:"cli",cliCommand:"pd activation deactivate --activation-id recovery-probe"}),Object.freeze({capabilityId:"rulecode_global_pause",channel:"console",consoleRoute:"/api/activations/emergency-pause"}),Object.freeze({capabilityId:"owner_review_access",channel:"console",consoleRoute:"/api/activations/{activationId}/owner-review"})]);en();po();var Gxe="",rBn="|;&<>()";function fJ(e){return rBn.includes(e)?`${Gxe}${e}`:e}function xgt(e){return e.replaceAll(Gxe,"")}function jxe(e){if(e.includes(Gxe))return null;let t=[],n="",r=!1,i=0,o=e.length,a="plain";for(;i<o;){let s=e[i];if(s===void 0)break;if(a==="single"){s==="'"?a="plain":n+=fJ(s),i+=1;continue}if(a==="double"){if(s==='"')a="plain";else if(s==="\\"&&i+1<o&&'"\\$`'.includes(e[i+1]??"")){n+=fJ(e[i+1]??""),i+=2;continue}else n+=fJ(s);i+=1;continue}if(s==="'"){a="single",r=!0,i+=1;continue}if(s==='"'){a="double",r=!0,i+=1;continue}if(s==="\\"&&i+1<o){n+=fJ(e[i+1]??""),r=!0,i+=2;continue}if(s==="\r"||s===`
|
|
1196
1196
|
`){(r||n)&&(t.push(n),n="",r=!1),s==="\r"&&e[i+1]===`
|
|
1197
1197
|
`&&(i+=1),t.push(`
|
|
1198
1198
|
`),i+=1;continue}if(" ".includes(s)){(r||n)&&(t.push(n),n="",r=!1),i+=1;continue}if("|;&<>()".includes(s)){(r||n)&&(t.push(n),n="",r=!1);let c=s,u=e[i+1];s==="<"&&u===">"?c="<>":(s==="|"||s==="&"||s===">"||s==="<")&&u===s&&(c+=u),(s===">"||s==="<")&&u==="("&&(c+=u),t.push(c),i+=c.length;continue}n+=s,r=!0,i+=1}return a!=="plain"?null:((r||n)&&t.push(n),t)}function bgt(e){if(/[\\$`|;&<>()*?~{}]/.test(e)||[...e].some(i=>i.charCodeAt(0)<32))return;let t=jxe(e);if(!t)return;let n=[...t],r=n.findIndex(i=>i==="-w"||i==="--workspace");if(r!==-1){let i=n[r+1];if(r!==n.length-2||!i||i.startsWith("-"))return;n.splice(r,2)}for(let i of Dy){if(i.channel!=="cli"||!i.cliCommand||i.capabilityId!=="pd_status"&&i.capabilityId!=="rulecode_deactivate")continue;let o=jxe(i.cliCommand);if(!o||o.length!==n.length)continue;if(o.every((s,c)=>i.capabilityId==="rulecode_deactivate"&&o[c-1]==="--activation-id"?/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/.test(n[c]??""):s===n[c]))return i.capabilityId}}var iBn=new Set([">",">>","<>","&>","&>>","2>","2>>"]);function oBn(e){let t=[],n=[],r=!1,i=!1,o=!1,a=(s=!1)=>{if(n.length===0&&!r&&!i&&!o)if(s)o=!0;else return;t.push({command:n[0]===void 0?null:xgt(n[0]),hasOutputRedirect:r,hasInputRedirect:i,unsupported:o,args:n.slice(1).map(xgt),substitutions:[]}),n=[],r=!1,i=!1,o=!1};for(let s=0;s<e.length;s+=1){let c=e[s];if(c===`
|
|
@@ -1943,7 +1943,7 @@ CONSTRAINTS:
|
|
|
1943
1943
|
`).run(n.decidedAt,n.subject.activationId,n.subject.artifactId),p=i.prepare(`
|
|
1944
1944
|
UPDATE activation_control_states SET version = version + 1, updated_at = ?
|
|
1945
1945
|
WHERE activation_id = ? AND enforcement = 'eligible' AND version = ?
|
|
1946
|
-
`).run(n.decidedAt,n.subject.activationId,t.expectedControlVersion);if(l.changes!==1||p.changes!==1)throw new Error("Promotion state changed during atomic commit");return i.exec("COMMIT"),{activationId:n.subject.activationId,decisionId:n.decisionId,promotedAt:n.decidedAt}}catch(o){try{i.exec("ROLLBACK")}catch{}throw o}}};function _X(){return{consecutiveErrors:0,consecutiveBlocks:[],latestEligible:[]}}function IX(e,t){if(t.protectedCapabilityMatched)return{state:e,trip:"protected_capability_matched"};if(t.neutralProbeFailed)return{state:e,trip:"host_liveness_probe_failed"};if(t.healthFailure)return{state:e,trip:"runtime_health_failure"};let n=t.decision==="error"?e.consecutiveErrors+1:0,r=t.decision==="block"?[...e.consecutiveBlocks,{toolName:t.toolName}].slice(-5):[],i=[...e.latestEligible,{blocked:t.decision==="block",outsideApprovedScope:t.outsideApprovedScope}].slice(-20),o={consecutiveErrors:n,consecutiveBlocks:r,latestEligible:i};return n>=3?{state:o,trip:"three_consecutive_errors"}:r.length>=5&&new Set(r.map(a=>a.toolName)).size>=3?{state:o,trip:"broad_consecutive_blocking"}:i.length===20&&i.filter(a=>a.blocked&&a.outsideApprovedScope).length/20>.8?{state:o,trip:"outside_scope_block_ratio"}:{state:o,trip:null}}import{createHash as I5n,randomUUID as $Zi}from"node:crypto";function Pg(e){return`sha256:${I5n("sha256").update(JSON.stringify(e),"utf8").digest("hex")}`}function Yb(e,t,n){if(typeof n!="string"||n.length===0)return{outcome:"no_binding"};let r=e.artifact_id,i=e.artifact_kind,o=e.source_task_id,a=e.source_principle_id,s=e.source_rule_id,c=e.lineage_artifact_ids,u=e.validation_status,l=e.created_at,p=e.updated_at;if(!(typeof r=="string"&&r.length>0&&typeof i=="string"&&typeof o=="string"&&(typeof a=="string"||a===null)&&(typeof s=="string"||s===null)&&typeof c=="string"&&typeof u=="string"&&typeof l=="string"&&typeof p=="string"))return{outcome:"unverifiable",error:"artifact row integrity does not allow digest re-verification"};let m;try{m=Pg(up({artifact_id:r,artifact_kind:i,source_task_id:o,source_principle_id:a,source_rule_id:s,lineage_artifact_ids:c,validation_status:u,content_json:t,created_at:l,updated_at:p}))}catch(g){return{outcome:"unverifiable",error:g instanceof Error?g.message:String(g)}}return m!==n?{outcome:"tampered",actualDigest:m}:{outcome:"verified"}}en();po();var G0t={schemaVersion:d.Union([d.Literal("approval-review"),d.Literal("approval-review-v1")]),approvalId:d.String({minLength:1}),artifactId:d.String({minLength:1}),channel:d.Union([d.Literal("prompt"),d.Literal("skill"),d.Literal("code_tool_hook"),d.Literal("defer_archive")])},q0t=d.Union([d.Object({...G0t,artifactState:d.Literal("present"),artifactDigest:d.String({pattern:"^sha256:[a-f0-9]{64}$"})},{additionalProperties:!1}),d.Object({...G0t,artifactState:d.Literal("missing")},{additionalProperties:!1})]);function K0t(e){return nt.Check(q0t,e)}function vX(e,t,n,r=!1){return!K0t(n)||n.approvalId!==e.approvalId||n.artifactId!==e.artifactId||n.channel!==e.channel?!1:n.artifactState==="missing"?r&&t===null:t!==null&&t.artifactId===e.artifactId&&Pg(t)===n.artifactDigest}function zP(){return{ok:!1,error:"stale_review",reason:"The approval material or target changed after review.",nextAction:"Reload this approval and review the current material before deciding again."}}function zbe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Vbe(e){if(!zbe(e))return!1;let t=n=>e[n]===null||typeof e[n]=="string";if(typeof e.artifact_id!="string"||typeof e.artifact_kind!="string"||typeof e.source_task_id!="string"||!t("source_principle_id")||!t("source_rule_id")||typeof e.lineage_artifact_ids!="string"||typeof e.validation_status!="string"||typeof e.content_json!="string"||typeof e.created_at!="string"||typeof e.updated_at!="string")return!1;try{let n=JSON.parse(e.lineage_artifact_ids);return Array.isArray(n)&&n.every(r=>typeof r=="string")}catch{return!1}}function V0t(e){return e==="pending"||e==="approved"||e==="rejected"||e==="cancelled"}function YP(e,t){if(!Object.hasOwn(e,t))return null;let n=e[t];return typeof n=="string"?n:null}function Ml(e,t){if(!Object.hasOwn(e,t))return;let n=e[t];if(n!==null)return typeof n=="string"?n:void 0}function v5n(e,t){if(!Object.hasOwn(e,t))return;let n=e[t];if(n!==null)return typeof n=="number"?n:void 0}function DW(e){if(!zbe(e))return null;let t=YP(e,"approval_id"),n=YP(e,"artifact_id"),r=YP(e,"channel"),i=YP(e,"risk_level"),o=YP(e,"status"),a=YP(e,"requested_at");return!t||!n||!r||!i||!o||!a?null:{approvalId:t,artifactId:n,artifactDigest:Ml(e,"artifact_digest"),channel:r,riskLevel:i,status:o,confidence:v5n(e,"confidence"),requestedAt:a,decidedAt:Ml(e,"decided_at"),decidedBy:Ml(e,"decided_by"),decisionNote:Ml(e,"decision_note"),rejectionReason:Ml(e,"rejection_reason"),summary:Ml(e,"summary"),triggerReason:Ml(e,"trigger_reason"),confidenceExplanation:Ml(e,"confidence_explanation"),effectDescription:Ml(e,"effect_description"),rejectionEffect:Ml(e,"rejection_effect"),editedAt:Ml(e,"edited_at"),editedBy:Ml(e,"edited_by"),editReason:Ml(e,"edit_reason"),previousArtifactId:Ml(e,"previous_artifact_id")}}function EX(e){return{approvalId:e.approval_id,artifactId:e.artifact_id,artifactDigest:e.artifact_digest??void 0,channel:e.channel,riskLevel:e.risk_level,status:e.status,confidence:e.confidence??void 0,requestedAt:e.requested_at,decidedAt:e.decided_at??void 0,decidedBy:e.decided_by??void 0,decisionNote:e.decision_note??void 0,rejectionReason:e.rejection_reason??void 0,summary:e.summary??void 0,triggerReason:e.trigger_reason??void 0,confidenceExplanation:e.confidence_explanation??void 0,effectDescription:e.effect_description??void 0,rejectionEffect:e.rejection_effect??void 0,editedAt:e.edited_at??void 0,editedBy:e.edited_by??void 0,editReason:e.edit_reason??void 0,previousArtifactId:e.previous_artifact_id??void 0}}function E5n(e,t){return"apr_"+t+"_"+e}var Jb=class{connection;constructor(t){this.connection=t}async enqueue(t,n){let r=this.connection.getDb();if(!r.prepare("SELECT 1 FROM pi_artifacts WHERE artifact_id = ?").get(t.artifactId))throw new Error(`approvals.artifact_id references non-existent pi_artifact: ${t.artifactId}`);let o=E5n(t.artifactId,t.channel);r.prepare("INSERT OR IGNORE INTO approvals (approval_id, artifact_id, channel, risk_level, status, confidence, requested_at, summary, trigger_reason, confidence_explanation, effect_description, rejection_effect) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(o,t.artifactId,t.channel,t.riskLevel,"pending",t.confidence??null,n,t.summary??null,t.triggerReason??null,t.confidenceExplanation??null,t.effectDescription??null,t.rejectionEffect??null);let a=r.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(o);if(!a)throw new Error("ApprovalQueue enqueue failed: no row found for "+o);return EX(a)}async getById(t){let r=this.connection.getDb().prepare("SELECT * FROM approvals WHERE approval_id = ?").get(t);return r?EX(r):null}async listPending(t){let n=this.connection.getDb(),r="SELECT * FROM approvals WHERE status = 'pending'",i=[];return t?.channel&&(r+=" AND channel = ?",i.push(t.channel)),t?.riskLevel&&(r+=" AND risk_level = ?",i.push(t.riskLevel)),n.prepare(r).all(...i).map(EX)}async listAll(t){let n=this.connection.getDb(),r=[],i=[];t?.status&&(r.push("status = ?"),i.push(t.status)),t?.channel&&(r.push("channel = ?"),i.push(t.channel));let o="SELECT * FROM approvals";r.length>0&&(o+=" WHERE "+r.join(" AND ")),o+=" ORDER BY requested_at DESC";let a=t?.page??1,s=t?.pageSize??0;if(s>0){let u=(a-1)*s;o+=" LIMIT ? OFFSET ?",i.push(s,u)}return n.prepare(o).all(...i).map(EX)}async countByStatus(){let n=this.connection.getDb().prepare("SELECT status, COUNT(*) as cnt FROM approvals GROUP BY status").all(),r={pending:0,approved:0,rejected:0,cancelled:0};for(let i of n)V0t(i.status)&&(r[i.status]=i.cnt);return r}async approve(t,n,r,i){let o=this.connection.getDb(),a=new Date().toISOString();o.exec("BEGIN IMMEDIATE");try{let s=o.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);if(s===void 0)return o.exec("COMMIT"),{ok:!1,error:"not_found"};if(!zbe(s)||typeof s.status!="string"||!V0t(s.status))throw new Error(`ApprovalQueue approve failed: malformed decision status for ${t}`);if(s.status!=="pending")return o.exec("COMMIT"),{ok:!1,error:"already_decided",status:s.status};let c=DW(o.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(t));if(!c)throw new Error(`ApprovalQueue approve failed: malformed row for ${t}`);let u=o.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(c.artifactId);if(!Vbe(u)){if(i)return o.exec("COMMIT"),zP();throw new Error(`ApprovalQueue approve failed: current PI artifact snapshot is missing or malformed for ${c.artifactId}`)}if(i&&!vX(c,up(u),i))return o.exec("COMMIT"),zP();let l=Pg(up(u)),p=DW(o.prepare("UPDATE approvals SET status = 'approved', decided_at = ?, decided_by = ?, decision_note = ?, artifact_digest = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(a,n,r??null,l,t));if(!p)throw new Error(`ApprovalQueue approve failed: pending decision disappeared for ${t}`);return o.exec("COMMIT"),{ok:!0,record:p}}catch(s){try{o.exec("ROLLBACK")}catch{}throw s}}async reject(t,n,r,i){return i?this.guardedMutation({approvalId:t,guard:i,allowMissing:!0,mutate:()=>this.rejectUnchecked(t,n,r)}):this.rejectUnchecked(t,n,r)}rejectUnchecked(t,n,r){let i=this.connection.getDb(),o=new Date().toISOString(),a=DW(i.prepare("UPDATE approvals SET status = 'rejected', decided_at = ?, decided_by = ?, rejection_reason = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(o,n,r,t));if(!a){let s=i.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);return s?{ok:!1,error:"already_decided",status:s.status}:{ok:!1,error:"not_found"}}return{ok:!0,record:a}}async resetToPending(t){let n=this.connection.getDb(),r=n.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);return r?r.status!=="approved"?{ok:!1,error:"not_approved"}:(n.prepare("UPDATE approvals SET status = 'pending', decided_at = NULL, decided_by = NULL, decision_note = NULL, artifact_digest = NULL WHERE approval_id = ? AND status = 'approved'").run(t),{ok:!0}):{ok:!1,error:"not_found"}}async edit(t){return t.expectedReview?this.guardedMutation({approvalId:t.approvalId,guard:t.expectedReview,allowMissing:!1,mutate:()=>this.editUnchecked(t),newArtifactId:t.newArtifactId,expectedNewArtifactDigest:t.expectedNewArtifactDigest}):this.editUnchecked(t)}editUnchecked(t){let n=this.connection.getDb(),r=DW(n.prepare("UPDATE approvals SET previous_artifact_id = artifact_id, artifact_id = ?, artifact_digest = NULL, edited_at = ?, edited_by = ?, edit_reason = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(t.newArtifactId,t.now,t.editedBy,t.editReason,t.approvalId));if(!r){let i=n.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t.approvalId);return i?{ok:!1,error:"already_decided",status:i.status}:{ok:!1,error:"not_found"}}return{ok:!0,record:r}}guardedMutation(t){let{approvalId:n,guard:r,allowMissing:i,mutate:o,newArtifactId:a}=t,s=this.connection.getDb();s.exec("BEGIN IMMEDIATE");try{let c=DW(s.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(n)),u;if(!c)u={ok:!1,error:"not_found"};else if(c.status!=="pending")u={ok:!1,error:"already_decided",status:c.status};else{let l=s.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(c.artifactId),p=Vbe(l)?up(l):null;if(l!==void 0&&p===null||!vX(c,p,r,i))u=zP();else if(a!==void 0){let f=s.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(a);u=p!==null&&Vbe(f)&&f.validation_status==="validated"&&Pg(up(f))===t.expectedNewArtifactDigest&&Fm(up(f),p)?o():zP()}else u=o()}return s.exec("COMMIT"),u}catch(c){try{s.exec("ROLLBACK")}catch{}throw c}}};import{createHash as x5n}from"node:crypto";var Xb=4e3;function PW(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function w5n(e){try{return JSON.parse(e)}catch{return null}}function LW(e){return e.filter(t=>t.channel==="prompt"&&t.action==="prompt_activate"&&t.deactivatedAt===null)}function JP(e,t){if(!PW(e))return{ok:!1,warning:`artifact_query_unexpected: artifactId=${t.artifactId}; nextAction=check_pi_artifacts_table`};let n=Object.hasOwn(e,"artifact_id")&&typeof e.artifact_id=="string"&&e.artifact_id.length>0?e.artifact_id:null,r=Object.hasOwn(e,"artifact_kind")&&typeof e.artifact_kind=="string"?e.artifact_kind:null,i=Object.hasOwn(e,"content_json")&&typeof e.content_json=="string"?e.content_json:null,o=Object.hasOwn(e,"validation_status")&&typeof e.validation_status=="string"?e.validation_status:null;if(!n)return{ok:!1,warning:`artifact_not_found: artifactId=${t.artifactId} activationId=${t.activationId}; nextAction=verify_artifact_exists_or_remove_stale_activation`};if(r!=="principle")return{ok:!1,warning:`artifact_not_principle: artifactId=${n} kind=${r??"missing"}; nextAction=skip_non_principle_activations`};if(o!=="validated")return{ok:!1,warning:`artifact_not_validated: artifactId=${n} status=${o??"missing"}; nextAction=skip_unvalidated_artifacts`};if(i===null)return{ok:!1,warning:`artifact_missing_content_json: artifactId=${n}; nextAction=ensure_artifact_has_content_json`};let a=w5n(i);if(a===null)return{ok:!1,warning:`artifact_content_json_parse_error: artifactId=${t.artifactId} reason=invalid_json; nextAction=fix_artifact_content_json`};if(!PW(a))return{ok:!1,warning:`artifact_content_malformed: artifactId=${t.artifactId} reason=parsed_to_non_object; nextAction=fix_artifact_content_json`};let s=Object.hasOwn(a,"principleId")&&typeof a.principleId=="string"?a.principleId:void 0,c=Object.hasOwn(a,"text")&&typeof a.text=="string"?a.text:void 0,u=Object.hasOwn(a,"principleDraft")&&PW(a.principleDraft)?a.principleDraft:null,l=u&&Object.hasOwn(u,"title")&&typeof u.title=="string"?u.title:void 0,p=u&&Object.hasOwn(u,"statement")&&typeof u.statement=="string"?u.statement:void 0,f=s&&s.length>0?s:l,m=c&&c.length>0?c:p;return!f||f.length===0?{ok:!1,warning:`artifact_missing_principle_id: artifactId=${t.artifactId}; nextAction=ensure_artifact_has_principleId_or_principleDraft_title`}:!m||m.length===0?{ok:!1,warning:`artifact_missing_text: artifactId=${t.artifactId} principleId=${f}; nextAction=ensure_artifact_has_text_or_principleDraft_statement`}:{ok:!0,principle:{principleId:f,text:m,artifactContentSha256:x5n("sha256").update(i,"utf8").digest("hex"),artifactId:t.artifactId,activationId:t.activationId}}}function z0t(){return["","## \u3010ACTIVE BEHAVIOR DIRECTIVES\u3011","",'Active behavior directives are operating constraints learned from prior owner corrections. Each directive carries its authorization: authority="owner" (approved in the owner approval queue) or authority="system_policy" (auto-activated by low-risk policy).',"These directives are mandatory for this session unless they conflict with safety, security, or higher-priority system policy.","For ambiguous coding or file-changing tasks, follow these directives before using mutating tools.",""]}function Y0t(e,t){let n=e.authority==="owner"||e.authority==="system_policy"?` authority="${e.authority}"`:"";return[`<directive id="${t(e.principleId)}" source="runtime_v2_activation"${n}>`,`MANDATORY: ${t(e.text)}`,"Apply this as an active behavior constraint. Do not treat this as background context.","</directive>",""]}function J0t(e){return e?["Self-report (OWNER visibility): when a directive above actually changes what you do in this turn, append exactly ONE line at the end of your reply in this format:","\u{1F4CC} \u5E94\u7528\u4E86\u4F60\u7684\u539F\u5219\u300C<directive id>\u300D\uFF1A<\u7528\u4E00\u53E5\u8BDD\u8BF4\u660E\u4F60\u8FD9\u6B21\u505A\u6CD5\u6709\u4F55\u4E0D\u540C>","Use the directive's exact id attribute. At most one line per directive per session. Omit the line entirely if no directive changed your behavior.",""]:[]}function X0t(){return["Note: These directives do not override safety, security, or core system policy."]}function NW(e,t){let n=t?.escapeFn??(i=>i),r=Y0t(e,n);return r.reduce((i,o)=>i+o.length,0)+r.length}function xX(e){let t=[...z0t(),...J0t(e?.selfReportInstruction===!0),...X0t()];return t.reduce((n,r)=>n+r.length,0)+t.length-1}function Lg(e,t,n){if(t.size===0)return"";let r=n?.escapeFn??(o=>o),i=[...z0t()];for(let o of e)t.has(o.principleId)&&i.push(...Y0t(o,r));return i.push(...J0t(n?.selfReportInstruction===!0)),i.push(...X0t()),i.join(`
|
|
1946
|
+
`).run(n.decidedAt,n.subject.activationId,t.expectedControlVersion);if(l.changes!==1||p.changes!==1)throw new Error("Promotion state changed during atomic commit");return i.exec("COMMIT"),{activationId:n.subject.activationId,decisionId:n.decisionId,promotedAt:n.decidedAt}}catch(o){try{i.exec("ROLLBACK")}catch{}throw o}}};function _X(){return{consecutiveErrors:0,consecutiveBlocks:[],latestEligible:[]}}function IX(e,t){if(t.protectedCapabilityMatched)return{state:e,trip:"protected_capability_matched"};if(t.neutralProbeFailed)return{state:e,trip:"host_liveness_probe_failed"};if(t.healthFailure)return{state:e,trip:"runtime_health_failure"};let n=t.decision==="error"?e.consecutiveErrors+1:0,r=t.decision==="block"?[...e.consecutiveBlocks,{toolName:t.toolName}].slice(-5):[],i=[...e.latestEligible,{blocked:t.decision==="block",outsideApprovedScope:t.outsideApprovedScope}].slice(-20),o={consecutiveErrors:n,consecutiveBlocks:r,latestEligible:i};return n>=3?{state:o,trip:"three_consecutive_errors"}:r.length>=5&&new Set(r.map(a=>a.toolName)).size>=3?{state:o,trip:"broad_consecutive_blocking"}:i.length===20&&i.filter(a=>a.blocked&&a.outsideApprovedScope).length/20>.8?{state:o,trip:"outside_scope_block_ratio"}:{state:o,trip:null}}import{createHash as I5n,randomUUID as $Zi}from"node:crypto";function Pg(e){return`sha256:${I5n("sha256").update(JSON.stringify(e),"utf8").digest("hex")}`}function Yb(e,t,n){if(typeof n!="string"||n.length===0)return{outcome:"no_binding"};let r=e.artifact_id,i=e.artifact_kind,o=e.source_task_id,a=e.source_principle_id,s=e.source_rule_id,c=e.lineage_artifact_ids,u=e.validation_status,l=e.created_at,p=e.updated_at;if(!(typeof r=="string"&&r.length>0&&typeof i=="string"&&typeof o=="string"&&(typeof a=="string"||a===null)&&(typeof s=="string"||s===null)&&typeof c=="string"&&typeof u=="string"&&typeof l=="string"&&typeof p=="string"))return{outcome:"unverifiable",error:"artifact row integrity does not allow digest re-verification"};let m;try{m=Pg(up({artifact_id:r,artifact_kind:i,source_task_id:o,source_principle_id:a,source_rule_id:s,lineage_artifact_ids:c,validation_status:u,content_json:t,created_at:l,updated_at:p}))}catch(g){return{outcome:"unverifiable",error:g instanceof Error?g.message:String(g)}}return m!==n?{outcome:"tampered",actualDigest:m}:{outcome:"verified"}}en();po();var G0t={schemaVersion:d.Union([d.Literal("approval-review"),d.Literal("approval-review-v1")]),approvalId:d.String({minLength:1}),artifactId:d.String({minLength:1}),channel:d.Union([d.Literal("prompt"),d.Literal("skill"),d.Literal("code_tool_hook"),d.Literal("defer_archive")])},q0t=d.Union([d.Object({...G0t,artifactState:d.Literal("present"),artifactDigest:d.String({pattern:"^sha256:[a-f0-9]{64}$"})},{additionalProperties:!1}),d.Object({...G0t,artifactState:d.Literal("missing")},{additionalProperties:!1})]);function K0t(e){return nt.Check(q0t,e)}function vX(e,t,n,r=!1){return!K0t(n)||n.approvalId!==e.approvalId||n.artifactId!==e.artifactId||n.channel!==e.channel?!1:n.artifactState==="missing"?r&&t===null:t!==null&&t.artifactId===e.artifactId&&Pg(t)===n.artifactDigest}function zP(){return{ok:!1,error:"stale_review",reason:"The approval material or target changed after review.",nextAction:"Reload this approval and review the current material before deciding again."}}function zbe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Vbe(e){if(!zbe(e))return!1;let t=n=>e[n]===null||typeof e[n]=="string";if(typeof e.artifact_id!="string"||typeof e.artifact_kind!="string"||typeof e.source_task_id!="string"||!t("source_principle_id")||!t("source_rule_id")||typeof e.lineage_artifact_ids!="string"||typeof e.validation_status!="string"||typeof e.content_json!="string"||typeof e.created_at!="string"||typeof e.updated_at!="string")return!1;try{let n=JSON.parse(e.lineage_artifact_ids);return Array.isArray(n)&&n.every(r=>typeof r=="string")}catch{return!1}}function V0t(e){return e==="pending"||e==="approved"||e==="rejected"||e==="cancelled"}function YP(e,t){if(!Object.hasOwn(e,t))return null;let n=e[t];return typeof n=="string"?n:null}function Ml(e,t){if(!Object.hasOwn(e,t))return;let n=e[t];if(n!==null)return typeof n=="string"?n:void 0}function v5n(e,t){if(!Object.hasOwn(e,t))return;let n=e[t];if(n!==null)return typeof n=="number"?n:void 0}function DW(e){if(!zbe(e))return null;let t=YP(e,"approval_id"),n=YP(e,"artifact_id"),r=YP(e,"channel"),i=YP(e,"risk_level"),o=YP(e,"status"),a=YP(e,"requested_at");return!t||!n||!r||!i||!o||!a?null:{approvalId:t,artifactId:n,artifactDigest:Ml(e,"artifact_digest"),channel:r,riskLevel:i,status:o,confidence:v5n(e,"confidence"),requestedAt:a,decidedAt:Ml(e,"decided_at"),decidedBy:Ml(e,"decided_by"),decisionNote:Ml(e,"decision_note"),rejectionReason:Ml(e,"rejection_reason"),summary:Ml(e,"summary"),triggerReason:Ml(e,"trigger_reason"),confidenceExplanation:Ml(e,"confidence_explanation"),effectDescription:Ml(e,"effect_description"),rejectionEffect:Ml(e,"rejection_effect"),editedAt:Ml(e,"edited_at"),editedBy:Ml(e,"edited_by"),editReason:Ml(e,"edit_reason"),previousArtifactId:Ml(e,"previous_artifact_id")}}function EX(e){return{approvalId:e.approval_id,artifactId:e.artifact_id,artifactDigest:e.artifact_digest??void 0,channel:e.channel,riskLevel:e.risk_level,status:e.status,confidence:e.confidence??void 0,requestedAt:e.requested_at,decidedAt:e.decided_at??void 0,decidedBy:e.decided_by??void 0,decisionNote:e.decision_note??void 0,rejectionReason:e.rejection_reason??void 0,summary:e.summary??void 0,triggerReason:e.trigger_reason??void 0,confidenceExplanation:e.confidence_explanation??void 0,effectDescription:e.effect_description??void 0,rejectionEffect:e.rejection_effect??void 0,editedAt:e.edited_at??void 0,editedBy:e.edited_by??void 0,editReason:e.edit_reason??void 0,previousArtifactId:e.previous_artifact_id??void 0}}function E5n(e,t){return"apr_"+t+"_"+e}var Jb=class{connection;constructor(t){this.connection=t}async enqueue(t,n){let r=this.connection.getDb();if(!r.prepare("SELECT 1 FROM pi_artifacts WHERE artifact_id = ?").get(t.artifactId))throw new Error(`approvals.artifact_id references non-existent pi_artifact: ${t.artifactId}`);let o=E5n(t.artifactId,t.channel);r.prepare("INSERT OR IGNORE INTO approvals (approval_id, artifact_id, channel, risk_level, status, confidence, requested_at, summary, trigger_reason, confidence_explanation, effect_description, rejection_effect) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(o,t.artifactId,t.channel,t.riskLevel,"pending",t.confidence??null,n,t.summary??null,t.triggerReason??null,t.confidenceExplanation??null,t.effectDescription??null,t.rejectionEffect??null);let a=r.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(o);if(!a)throw new Error("ApprovalQueue enqueue failed: no row found for "+o);return EX(a)}async getById(t){let r=this.connection.getDb().prepare("SELECT * FROM approvals WHERE approval_id = ?").get(t);return r?EX(r):null}async listPending(t){let n=this.connection.getDb(),r="SELECT * FROM approvals WHERE status = 'pending'",i=[];return t?.channel&&(r+=" AND channel = ?",i.push(t.channel)),t?.riskLevel&&(r+=" AND risk_level = ?",i.push(t.riskLevel)),n.prepare(r).all(...i).map(EX)}async listAll(t){let n=this.connection.getDb(),r=[],i=[];t?.status&&(r.push("status = ?"),i.push(t.status)),t?.channel&&(r.push("channel = ?"),i.push(t.channel));let o="SELECT * FROM approvals";r.length>0&&(o+=" WHERE "+r.join(" AND ")),o+=" ORDER BY requested_at DESC";let a=t?.page??1,s=t?.pageSize??0;if(s>0){let u=(a-1)*s;o+=" LIMIT ? OFFSET ?",i.push(s,u)}return n.prepare(o).all(...i).map(EX)}async countByStatus(){let n=this.connection.getDb().prepare("SELECT status, COUNT(*) as cnt FROM approvals GROUP BY status").all(),r={pending:0,approved:0,rejected:0,cancelled:0};for(let i of n)V0t(i.status)&&(r[i.status]=i.cnt);return r}async approve(t,n,r,i){let o=this.connection.getDb(),a=new Date().toISOString();o.exec("BEGIN IMMEDIATE");try{let s=o.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);if(s===void 0)return o.exec("COMMIT"),{ok:!1,error:"not_found"};if(!zbe(s)||typeof s.status!="string"||!V0t(s.status))throw new Error(`ApprovalQueue approve failed: malformed decision status for ${t}`);if(s.status!=="pending")return o.exec("COMMIT"),{ok:!1,error:"already_decided",status:s.status};let c=DW(o.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(t));if(!c)throw new Error(`ApprovalQueue approve failed: malformed row for ${t}`);let u=o.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(c.artifactId);if(!Vbe(u)){if(i)return o.exec("COMMIT"),zP();throw new Error(`ApprovalQueue approve failed: current PI artifact snapshot is missing or malformed for ${c.artifactId}`)}if(i&&!vX(c,up(u),i))return o.exec("COMMIT"),zP();let l=Pg(up(u)),p=DW(o.prepare("UPDATE approvals SET status = 'approved', decided_at = ?, decided_by = ?, decision_note = ?, artifact_digest = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(a,n,r??null,l,t));if(!p)throw new Error(`ApprovalQueue approve failed: pending decision disappeared for ${t}`);return o.exec("COMMIT"),{ok:!0,record:p}}catch(s){try{o.exec("ROLLBACK")}catch{}throw s}}async reject(t,n,r,i){return i?this.guardedMutation({approvalId:t,guard:i,allowMissing:!0,mutate:()=>this.rejectUnchecked(t,n,r)}):this.rejectUnchecked(t,n,r)}rejectUnchecked(t,n,r){let i=this.connection.getDb(),o=new Date().toISOString(),a=DW(i.prepare("UPDATE approvals SET status = 'rejected', decided_at = ?, decided_by = ?, rejection_reason = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(o,n,r,t));if(!a){let s=i.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);return s?{ok:!1,error:"already_decided",status:s.status}:{ok:!1,error:"not_found"}}return{ok:!0,record:a}}async resetToPending(t){let n=this.connection.getDb(),r=n.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);return r?r.status!=="approved"?{ok:!1,error:"not_approved"}:(n.prepare("UPDATE approvals SET status = 'pending', decided_at = NULL, decided_by = NULL, decision_note = NULL, artifact_digest = NULL WHERE approval_id = ? AND status = 'approved'").run(t),{ok:!0}):{ok:!1,error:"not_found"}}async edit(t){return t.expectedReview?this.guardedMutation({approvalId:t.approvalId,guard:t.expectedReview,allowMissing:!1,mutate:()=>this.editUnchecked(t),newArtifactId:t.newArtifactId,expectedNewArtifactDigest:t.expectedNewArtifactDigest}):this.editUnchecked(t)}editUnchecked(t){let n=this.connection.getDb(),r=DW(n.prepare("UPDATE approvals SET previous_artifact_id = artifact_id, artifact_id = ?, artifact_digest = NULL, edited_at = ?, edited_by = ?, edit_reason = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(t.newArtifactId,t.now,t.editedBy,t.editReason,t.approvalId));if(!r){let i=n.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t.approvalId);return i?{ok:!1,error:"already_decided",status:i.status}:{ok:!1,error:"not_found"}}return{ok:!0,record:r}}guardedMutation(t){let{approvalId:n,guard:r,allowMissing:i,mutate:o,newArtifactId:a}=t,s=this.connection.getDb();s.exec("BEGIN IMMEDIATE");try{let c=DW(s.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(n)),u;if(!c)u={ok:!1,error:"not_found"};else if(c.status!=="pending")u={ok:!1,error:"already_decided",status:c.status};else{let l=s.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(c.artifactId),p=Vbe(l)?up(l):null;if(l!==void 0&&p===null||!vX(c,p,r,i))u=zP();else if(a!==void 0){let f=s.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(a);u=p!==null&&Vbe(f)&&f.validation_status==="validated"&&Pg(up(f))===t.expectedNewArtifactDigest&&Fm(up(f),p)?o():zP()}else u=o()}return s.exec("COMMIT"),u}catch(c){try{s.exec("ROLLBACK")}catch{}throw c}}};import{createHash as x5n}from"node:crypto";var Xb=4e3;function PW(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function w5n(e){try{return JSON.parse(e)}catch{return null}}function LW(e){return e.filter(t=>t.channel==="prompt"&&t.action==="prompt_activate"&&t.deactivatedAt===null)}function JP(e,t){if(!PW(e))return{ok:!1,warning:`artifact_query_unexpected: artifactId=${t.artifactId}; nextAction=check_pi_artifacts_table`};let n=Object.hasOwn(e,"artifact_id")&&typeof e.artifact_id=="string"&&e.artifact_id.length>0?e.artifact_id:null,r=Object.hasOwn(e,"artifact_kind")&&typeof e.artifact_kind=="string"?e.artifact_kind:null,i=Object.hasOwn(e,"content_json")&&typeof e.content_json=="string"?e.content_json:null,o=Object.hasOwn(e,"validation_status")&&typeof e.validation_status=="string"?e.validation_status:null;if(!n)return{ok:!1,warning:`artifact_not_found: artifactId=${t.artifactId} activationId=${t.activationId}; nextAction=verify_artifact_exists_or_remove_stale_activation`};if(r!=="principle")return{ok:!1,warning:`artifact_not_principle: artifactId=${n} kind=${r??"missing"}; nextAction=skip_non_principle_activations`};if(o!=="validated")return{ok:!1,warning:`artifact_not_validated: artifactId=${n} status=${o??"missing"}; nextAction=skip_unvalidated_artifacts`};if(i===null)return{ok:!1,warning:`artifact_missing_content_json: artifactId=${n}; nextAction=ensure_artifact_has_content_json`};let a=w5n(i);if(a===null)return{ok:!1,warning:`artifact_content_json_parse_error: artifactId=${t.artifactId} reason=invalid_json; nextAction=fix_artifact_content_json`};if(!PW(a))return{ok:!1,warning:`artifact_content_malformed: artifactId=${t.artifactId} reason=parsed_to_non_object; nextAction=fix_artifact_content_json`};let s=Object.hasOwn(a,"principleId")&&typeof a.principleId=="string"?a.principleId:void 0,c=Object.hasOwn(a,"text")&&typeof a.text=="string"?a.text:void 0,u=Object.hasOwn(a,"principleDraft")&&PW(a.principleDraft)?a.principleDraft:null,l=u&&Object.hasOwn(u,"title")&&typeof u.title=="string"?u.title:void 0,p=u&&Object.hasOwn(u,"statement")&&typeof u.statement=="string"?u.statement:void 0,f=s&&s.length>0?s:l,m=c&&c.length>0?c:p;return!f||f.length===0?{ok:!1,warning:`artifact_missing_principle_id: artifactId=${t.artifactId}; nextAction=ensure_artifact_has_principleId_or_principleDraft_title`}:!m||m.length===0?{ok:!1,warning:`artifact_missing_text: artifactId=${t.artifactId} principleId=${f}; nextAction=ensure_artifact_has_text_or_principleDraft_statement`}:{ok:!0,principle:{principleId:f,text:m,artifactContentSha256:x5n("sha256").update(i,"utf8").digest("hex"),artifactId:t.artifactId,activationId:t.activationId}}}function z0t(){return["","## \u3010ACTIVE BEHAVIOR DIRECTIVES\u3011","",'Active behavior directives are operating constraints learned from prior owner corrections. Each directive carries its authorization: authority="owner" (approved in the owner approval queue) or authority="system_policy" (auto-activated by low-risk policy).',"These directives are mandatory active behavior constraints for this session, not background context, unless they conflict with safety, security, or higher-priority system policy.","For ambiguous coding or file-changing tasks, follow these directives before using mutating tools.",""]}function Y0t(e,t){let n=e.authority==="owner"||e.authority==="system_policy"?` authority="${e.authority}"`:"";return[`<directive id="${t(e.principleId)}" source="runtime_v2_activation"${n}>`,`MANDATORY: ${t(e.text)}`,"</directive>",""]}function J0t(e){return e?["Self-report (OWNER visibility): when a directive above actually changes what you do in this turn, append exactly ONE line at the end of your reply in this format:","\u{1F4CC} \u5E94\u7528\u4E86\u4F60\u7684\u539F\u5219\u300C<directive id>\u300D\uFF1A<\u7528\u4E00\u53E5\u8BDD\u8BF4\u660E\u4F60\u8FD9\u6B21\u505A\u6CD5\u6709\u4F55\u4E0D\u540C>","Use the directive's exact id attribute. At most one line per directive per session. Omit the line entirely if no directive changed your behavior.",""]:[]}function X0t(){return["Note: These directives do not override safety, security, or core system policy."]}function NW(e,t){let n=t?.escapeFn??(i=>i),r=Y0t(e,n);return r.reduce((i,o)=>i+o.length,0)+r.length}function xX(e){let t=[...z0t(),...J0t(e?.selfReportInstruction===!0),...X0t()];return t.reduce((n,r)=>n+r.length,0)+t.length-1}function Lg(e,t,n){if(t.size===0)return"";let r=n?.escapeFn??(o=>o),i=[...z0t()];for(let o of e)t.has(o.principleId)&&i.push(...Y0t(o,r));return i.push(...J0t(n?.selfReportInstruction===!0)),i.push(...X0t()),i.join(`
|
|
1947
1947
|
`)}var pv="model_aware",Xbe=4e3,Zbe=128e3,MW=1250,BW=32e3,XP=Xb,Z0t=7e3,e_t=XP+Z0t;function ZP(e){return e+Z0t}var eS=1024,tS=1e8,eSe=new Set(["model","modelsConfig","agentContextTokens"]);function fv(e){return typeof e=="number"&&Number.isInteger(e)&&e>=eS&&e<=tS}function Zb(e){if(!fv(e))return XP;let t=Math.floor(Xbe*e/Zbe);return Math.min(BW,Math.max(MW,t))}function Ybe(e){return{budgetChars:XP,capacitySource:"legacy_fallback",capacityStatus:"unknown",contextWindowTokens:null,policyVersion:pv,fallbackReason:e.reason,fallbackDetail:e.detail}}function Jbe(e){return typeof e=="string"&&e.length>0?e:void 0}function wX(e,t){let n=t.skipReason===null?"host_capacity_absent":t.skipReason,r=(l,p)=>Ybe({reason:t.skipReason??l,detail:`${n};${l}:${p}`}),i=e?.catalog,o=Jbe(e?.modelIdentity?.modelId),a=Jbe(e?.modelIdentity?.providerId);if(i===void 0)return t.skipReason===null&&o===void 0?Ybe({reason:"host_capacity_absent",detail:"host_capacity_absent;no-facts-at-all"}):r("catalog_unavailable","no-catalog-binding");if(o===void 0)return t.skipReason===null?Ybe({reason:"host_capacity_absent",detail:"host_capacity_absent;no-model-context"}):r("model_identity_absent","no-model-id");if(a!==void 0){let l=i.exact(a,o);return l===void 0?r("catalog_no_exact_match",`${a}/${o}`):fv(l.contextWindowTokens)?{budgetChars:Zb(l.contextWindowTokens),capacitySource:"pi_catalog_exact",capacityStatus:"confirmed",contextWindowTokens:l.contextWindowTokens,policyVersion:pv}:r("catalog_metadata_invalid",`${a}/${o}`)}let s=i.byModelId(o);if(s.length===0)return r("catalog_no_match_for_model_id",o);let[c]=s;return c===void 0||!s.every(l=>fv(l.contextWindowTokens))?r("catalog_metadata_invalid",o):s.every(l=>l.contextWindowTokens===c.contextWindowTokens)?{budgetChars:Zb(c.contextWindowTokens),capacitySource:"pi_catalog_model_id",capacityStatus:"confirmed",contextWindowTokens:c.contextWindowTokens,policyVersion:pv}:r("catalog_ambiguous_model_id",o)}function mv(e){let t=e?.operatorDeclared?.contextWindowTokens;if(t!==void 0&&fv(t))return{budgetChars:Zb(t),capacitySource:"operator_declared",capacityStatus:"confirmed",contextWindowTokens:t,policyVersion:pv};let n=e?.hostCapacity;if(n!==void 0){let r=n.contextTokenBudget!==void 0,i=n.contextWindowSource!==void 0;if(!r&&!i)return wX(e,{skipReason:null,detail:"host_capacity_absent"});let o=Jbe(n.contextWindowSource);if(!(o!==void 0&&eSe.has(o)))return wX(e,{skipReason:"host_capacity_source_untrusted",detail:`host_capacity_source_untrusted:${o??"absent"}`});if(!fv(n.contextTokenBudget))return wX(e,{skipReason:"host_capacity_invalid_value",detail:"host_capacity_invalid_value"});let s=n.contextTokenBudget;return{budgetChars:Zb(s),capacitySource:"host_effective_window",capacityStatus:"confirmed",contextWindowTokens:s,policyVersion:pv}}return wX(e,{skipReason:null,detail:"host_capacity_absent"})}import Qeo from"better-sqlite3";import Keo from"better-sqlite3";import eto from"better-sqlite3";en();function hv(e){if(!e||typeof e!="object")return!1;let t=e,n=["high","medium","low"];if(typeof t.confidence!="string"||!n.includes(t.confidence))return!1;let r=o=>Array.isArray(o)&&o.length>0&&o.every(a=>typeof a=="string"&&a.length>0),i=o=>Array.isArray(o)&&o.every(a=>Array.isArray(a)&&a.every(s=>typeof s=="string"));return r(t.applicabilityTags)&&r(t.positiveSignals)&&r(t.negativeSignals)&&i(t.toolSequenceHints)}var bX=d.Union([d.Literal("candidate"),d.Literal("probation"),d.Literal("active"),d.Literal("deprecated"),d.Literal("archived")]),rSe=d.Union([d.Literal("deterministic"),d.Literal("weak_heuristic"),d.Literal("manual_only")]);var iSe=d.Object({applicabilityTags:d.Array(d.String()),positiveSignals:d.Array(d.String()),negativeSignals:d.Array(d.String()),toolSequenceHints:d.Array(d.Array(d.String())),confidence:d.Union([d.Literal("high"),d.Literal("medium"),d.Literal("low")])}),n_t=d.Object({name:d.String(),type:d.Union([d.Literal("hook"),d.Literal("gate"),d.Literal("skill"),d.Literal("test"),d.Literal("prompt")]),triggerCondition:d.String(),enforcement:d.Union([d.Literal("block"),d.Literal("warn"),d.Literal("log")]),action:d.String(),implementationHint:d.Optional(d.String())}),r_t=d.Object({painPreventedCount:d.Number(),lastPainPreventedAt:d.Optional(d.String()),calculatedAt:d.String()}),V5n=d.Object({id:d.String(),version:d.Number(),text:d.String(),source:d.Object({painId:d.String(),painType:d.Union([d.Literal("tool_failure"),d.Literal("dispatch_error"),d.Literal("subagent_error"),d.Literal("user_frustration")]),timestamp:d.String()}),trigger:d.String(),action:d.String(),guardrails:d.Optional(d.Array(d.String())),contextTags:d.Array(d.String()),validation:d.Object({successCount:d.Number(),conflictCount:d.Number()}),status:bX,feedbackScore:d.Number(),usageCount:d.Number(),createdAt:d.String(),activatedAt:d.Optional(d.String()),deprecatedAt:d.Optional(d.String()),evaluability:rSe,detectorMetadata:d.Optional(iSe),abstractedPrinciple:d.Optional(d.String()),coreAxiomId:d.Optional(d.String()),priority:d.Optional(d.Union([d.Literal("P0"),d.Literal("P1"),d.Literal("P2")])),scope:d.Optional(d.Union([d.Literal("general"),d.Literal("domain")])),domain:d.Optional(d.String()),suggestedRules:d.Optional(d.Array(n_t)),valueMetrics:d.Optional(r_t)}),z5n=d.Union([d.Literal("pain_detected"),d.Literal("candidate_created"),d.Literal("principle_promoted"),d.Literal("principle_deprecated"),d.Literal("principle_rolled_back"),d.Literal("circuit_breaker_opened"),d.Literal("legacy_import")]),nSe=d.Object({painId:d.String(),painType:d.Union([d.Literal("tool_failure"),d.Literal("dispatch_error"),d.Literal("subagent_error"),d.Literal("user_frustration")]),source:d.String(),reason:d.String(),score:d.Optional(d.Number()),sessionId:d.Optional(d.String()),agentId:d.Optional(d.String()),taskId:d.Optional(d.String()),traceId:d.Optional(d.String()),provenance:d.Optional(d.Union([d.Literal("host_context_bound"),d.Literal("owner_reported_no_host_trace"),d.Literal("automatic_hook"),d.Literal("openclaw_context_bound")])),hostKind:d.Optional(d.Union([d.Literal("openclaw"),d.Literal("codex"),d.Literal("workbuddy")]))}),i_t=d.Object({painId:d.String(),principleId:d.String(),trigger:d.String(),action:d.String(),status:d.Literal("candidate"),painType:d.Optional(d.Union([d.Literal("tool_failure"),d.Literal("dispatch_error"),d.Literal("subagent_error"),d.Literal("user_frustration")])),evaluability:d.Optional(rSe),detectorMetadata:d.Optional(iSe),abstractedPrinciple:d.Optional(d.String()),coreAxiomId:d.Optional(d.String())}),o_t=d.Object({principleId:d.String(),from:bX,to:bX,reason:d.String(),successCount:d.Optional(d.Number())}),a_t=d.Object({principleId:d.String(),reason:d.String(),triggeredBy:d.Union([d.Literal("auto"),d.Literal("manual")])}),s_t=d.Object({principleId:d.String(),reason:d.String(),triggeredBy:d.Union([d.Literal("user_command"),d.Literal("auto_conflict")]),blacklistPattern:d.Optional(d.String()),relatedPainId:d.Optional(d.String())}),c_t=d.Object({taskId:d.String(),painId:d.String(),failCount:d.Number(),reason:d.String(),requireHuman:d.Boolean(),nextRetryAt:d.Optional(d.String())}),u_t=d.Object({sourceFile:d.String(),content:d.String(),contentHash:d.Optional(d.String())}),Y5n=d.Union([d.Object({ts:d.String(),type:d.Literal("pain_detected"),data:nSe}),d.Object({ts:d.String(),type:d.Literal("pain_recorded"),data:nSe}),d.Object({ts:d.String(),type:d.Literal("candidate_created"),data:i_t}),d.Object({ts:d.String(),type:d.Literal("principle_promoted"),data:o_t}),d.Object({ts:d.String(),type:d.Literal("principle_deprecated"),data:a_t}),d.Object({ts:d.String(),type:d.Literal("principle_rolled_back"),data:s_t}),d.Object({ts:d.String(),type:d.Literal("circuit_breaker_opened"),data:c_t}),d.Object({ts:d.String(),type:d.Literal("legacy_import"),data:u_t})]);en();var eL=200,tL=[{term:"\u4E0D\u662F\u8FD9\u4E2A",weight:.6,source:"seed",addedAt:""},{term:"\u4E0D\u5BF9",weight:.5,source:"seed",addedAt:""},{term:"\u9519\u4E86",weight:.5,source:"seed",addedAt:""},{term:"\u641E\u9519\u4E86",weight:.7,source:"seed",addedAt:""},{term:"\u7406\u89E3\u9519\u4E86",weight:.7,source:"seed",addedAt:""},{term:"\u4F60\u7406\u89E3\u9519\u4E86",weight:.8,source:"seed",addedAt:""},{term:"\u91CD\u65B0\u6765",weight:.6,source:"seed",addedAt:""},{term:"\u518D\u8BD5\u4E00\u6B21",weight:.4,source:"seed",addedAt:""},{term:"you are wrong",weight:.7,source:"seed",addedAt:""},{term:"wrong file",weight:.6,source:"seed",addedAt:""},{term:"not this",weight:.4,source:"seed",addedAt:""},{term:"redo",weight:.6,source:"seed",addedAt:""},{term:"try again",weight:.4,source:"seed",addedAt:""},{term:"again",weight:.3,source:"seed",addedAt:""},{term:"please redo",weight:.6,source:"seed",addedAt:""},{term:"please try again",weight:.5,source:"seed",addedAt:""}],l_t=d.Object({term:d.String(),weight:d.Number(),source:d.Union([d.Literal("seed"),d.Literal("llm"),d.Literal("user")]),addedAt:d.String(),hitCount:d.Optional(d.Number({minimum:0})),truePositiveCount:d.Optional(d.Number({minimum:0})),falsePositiveCount:d.Optional(d.Number({minimum:0})),lastHitAt:d.Optional(d.String())}),J5n=d.Object({keywords:d.Array(l_t),version:d.Integer({minimum:0}),lastOptimizedAt:d.String()});var FW=class{registry=new Map;register(t){this.registry.set(t.agentId,t)}async dispatch(t,n){let r=this.registry.get(t);if(!r)throw new Error(`Agent ${t} is not registered in AgentScheduler`);return r.runner.run(n)}getRegisteredAgents(){return Array.from(this.registry.values()).map(t=>({agentId:t.agentId,mode:t.mode}))}};function gv(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Ng(e){return typeof e=="string"}function SX(e){return typeof e=="boolean"}function $m(e){return typeof e=="number"&&Number.isFinite(e)}function er(e,t){return{path:e,message:t}}function Gn(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var gHn=new Set(["info","warning","error","fatal"]);function AHn(e,t){let n=[];return Gn(e,"gate")!==void 0&&n.push(er(`${t}.gate`,"deprecated: the built-in PLAN/confirm-first gate was removed (PRI-286); this key has no effect and can be deleted")),(Gn(e,"progressive_gate")!==void 0||Gn(e,"progressiveGate")!==void 0)&&n.push(er(`${t}.progressive_gate`,"deprecated: plan-approval gating was removed (PRI-286); this key has no effect and can be deleted")),Gn(e,"progressiveGate")!==void 0&&n.push(er(`${t}.progressiveGate`,"deprecated: plan-approval gating was removed (PRI-286); legacy camelCase alias, this key has no effect and can be deleted")),(Gn(e,"thinking_checkpoint")!==void 0||Gn(e,"thinkingCheckpoint")!==void 0)&&n.push(er(`${t}.thinking_checkpoint`,"deprecated: the thinking-checkpoint gate is retired; this key has no effect and can be deleted")),Gn(e,"thinkingCheckpoint")!==void 0&&n.push(er(`${t}.thinkingCheckpoint`,"deprecated: the thinking-checkpoint gate is retired; legacy camelCase alias, this key has no effect and can be deleted")),n}function yHn(e,t){let n=[];if(!gv(e))return n.push(er(t,`tests must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Gn(e,"on_change");i!==void 0&&(Ng(i)&&HC.includes(i)?r.on_change=i:n.push(er(`${t}.on_change`,`must be one of: ${HC.join(", ")}`)));let o=Gn(e,"on_risk_change");o!==void 0&&(Ng(o)&&HC.includes(o)?r.on_risk_change=o:n.push(er(`${t}.on_risk_change`,`must be one of: ${HC.join(", ")}`)));let a=Gn(e,"commands");if(a!==void 0)if(gv(a)){let s={};for(let c of Object.keys(a)){let u=a[c];Ng(u)?s[c]=u:n.push(er(`${t}.commands.${c}`,"command value must be a string"))}r.commands=s}else n.push(er(`${t}.commands`,"must be an object (string\u2192string map)"));return{value:r,warnings:n}}function _Hn(e,t){let n=[];if(!gv(e))return n.push(er(t,`adaptive must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Gn(e,"enabled");i!==void 0&&(SX(i)?r.enabled=i:n.push(er(`${t}.enabled`,"must be boolean")));let o=Gn(e,"spiral_boost");o!==void 0&&($m(o)?r.spiral_boost=o:n.push(er(`${t}.spiral_boost`,"must be a finite number")));let a=Gn(e,"min_threshold");a!==void 0&&($m(a)?r.min_threshold=a:n.push(er(`${t}.min_threshold`,"must be a finite number")));let s=Gn(e,"max_threshold");s!==void 0&&($m(s)?r.max_threshold=s:n.push(er(`${t}.max_threshold`,"must be a finite number")));let c=Gn(e,"backlog_trigger");c!==void 0&&($m(c)?r.backlog_trigger=c:n.push(er(`${t}.backlog_trigger`,"must be a finite number")));let u=Gn(e,"hard_failure_trigger");u!==void 0&&($m(u)?r.hard_failure_trigger=u:n.push(er(`${t}.hard_failure_trigger`,"must be a finite number")));let l=Gn(e,"low_recent_success_boost");l!==void 0&&($m(l)?r.low_recent_success_boost=l:n.push(er(`${t}.low_recent_success_boost`,"must be a finite number")));let p=Gn(e,"high_recent_pain_boost");return p!==void 0&&($m(p)?r.high_recent_pain_boost=p:n.push(er(`${t}.high_recent_pain_boost`,"must be a finite number"))),{value:r,warnings:n}}function IHn(e,t){let n=[];if(!gv(e))return n.push(er(t,`pain must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Gn(e,"soft_capture_threshold");i!==void 0&&($m(i)?r.soft_capture_threshold=i:n.push(er(`${t}.soft_capture_threshold`,"must be a finite number")));let o=Gn(e,"adaptive");if(o!==void 0){let a=_Hn(o,`${t}.adaptive`);a.value&&(r.adaptive=a.value),n.push(...a.warnings)}return{value:r,warnings:n}}function vHn(e,t){let n=[];if(!gv(e))return n.push(er(t,`lifecycle must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Gn(e,"enabled");i!==void 0&&(SX(i)?r.enabled=i:n.push(er(`${t}.enabled`,"must be boolean")));let o=Gn(e,"heartbeat_stale_hours");return o!==void 0&&($m(o)?r.heartbeat_stale_hours=o:n.push(er(`${t}.heartbeat_stale_hours`,"must be a finite number"))),{value:r,warnings:n}}function EHn(e,t){let n=[];if(!gv(e))return n.push(er(t,`edit_verification must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Gn(e,"enabled");i!==void 0&&(SX(i)?r.enabled=i:n.push(er(`${t}.enabled`,"must be boolean")));let o=Gn(e,"max_file_size_bytes");o!==void 0&&($m(o)&&o>=0?r.max_file_size_bytes=o:n.push(er(`${t}.max_file_size_bytes`,"must be a non-negative number")));let a=Gn(e,"fuzzy_match_enabled");a!==void 0&&(SX(a)?r.fuzzy_match_enabled=a:n.push(er(`${t}.fuzzy_match_enabled`,"must be boolean")));let s=Gn(e,"fuzzy_match_threshold");s!==void 0&&($m(s)&&s>0&&s<=1?r.fuzzy_match_threshold=s:n.push(er(`${t}.fuzzy_match_threshold`,"must be a number in (0, 1]")));let c=Gn(e,"skip_large_file_action");return c!==void 0&&(c==="warn"||c==="block"?r.skip_large_file_action=c:n.push(er(`${t}.skip_large_file_action`,'must be "warn" or "block"'))),{value:r,warnings:n}}function xHn(e,t){let n=[];if(!Array.isArray(e))return n.push(er(t,`custom_guards must be an array, got ${typeof e}`)),{warnings:n};let r=[];for(let i=0;i<e.length;i++){let o=e[i];if(!gv(o)){n.push(er(`${t}[${i}]`,"must be an object"));continue}let a=Gn(o,"pattern"),s=Gn(o,"message"),c=Gn(o,"severity");if(!Ng(a)||a.length===0){n.push(er(`${t}[${i}].pattern`,"must be a non-empty string"));continue}r.push({pattern:a,message:Ng(s)?s:"Custom guard triggered",severity:Ng(c)&&gHn.has(c.toLowerCase())?c.toLowerCase():"error"})}return{value:r,warnings:n}}function oSe(e,t="profile"){let n=[];if(!gv(e))return{ok:!1,errors:[er(t,`profile must be an object, got ${typeof e}`)]};let r={},i=Gn(e,"audit_level");i!==void 0&&(Ng(i)&&Qj.includes(i)?r.audit_level=i:n.push(er(`${t}.audit_level`,`must be one of: ${Qj.join(", ")}, got ${JSON.stringify(i)}`)));let o=Gn(e,"evolution_mode");o!==void 0&&(Ng(o)&&Wj.includes(o)?r.evolution_mode=o:n.push(er(`${t}.evolution_mode`,`must be one of: ${Wj.join(", ")}, got ${JSON.stringify(o)}`)));let a=Gn(e,"risk_paths");a!==void 0&&(Array.isArray(a)?r.risk_paths=a.filter(Ng):Ng(a)?r.risk_paths=[a]:n.push(er(`${t}.risk_paths`,"must be an array of strings or a single string"))),n.push(...AHn(e,t));let s=Gn(e,"tests");if(s!==void 0){let f=yHn(s,`${t}.tests`);f.value&&(r.tests=f.value),n.push(...f.warnings)}let c=Gn(e,"pain");if(c!==void 0){let f=IHn(c,`${t}.pain`);f.value&&(r.pain=f.value),n.push(...f.warnings)}let u=Gn(e,"lifecycle");if(u!==void 0){let f=vHn(u,`${t}.lifecycle`);f.value&&(r.lifecycle=f.value),n.push(...f.warnings)}let l=Gn(e,"edit_verification");if(l!==void 0){let f=EHn(l,`${t}.edit_verification`);f.value&&(r.edit_verification=f.value),n.push(...f.warnings)}let p=Gn(e,"custom_guards");if(p!==void 0){let f=xHn(p,`${t}.custom_guards`);f.value&&(r.custom_guards=f.value),n.push(...f.warnings)}return{ok:!0,value:r,warnings:n}}var x_t=new Set(["enabled","runtimeProfile","timeoutMs"]),w_t=new Set(["declaredContextWindowTokens","hosts"]);function sc(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function ta(e){return typeof e=="string"}function aSe(e){return typeof e=="boolean"}function Bl(e){return typeof e=="number"&&Number.isFinite(e)}function je(e,t,n){return{path:e,reason:t,nextAction:n}}function bn(e,t){if(!Ea.has(t))return Object.hasOwn(e,t)?e[t]:void 0}function CX(e){return Bl(e)&&Number.isInteger(e)&&e>=eS&&e<=tS}function Wi(e){if(e===null)return"null";if(e===void 0)return"undefined";let t=typeof e;if(t==="string"){let n=e;return n.length>50?`"${n.slice(0,50)}\u2026"`:`"${n}"`}return t==="number"||t==="boolean"?String(e):Array.isArray(e)?`array(${e.length})`:t==="object"?"object":t}function wHn(e,t,n){let r=[];if(!sc(e))return{ok:!1,errors:[je(t,`feature '${n}' must be an object, got ${typeof e}`,`Fix feature '${n}' to be an object with category and enabled fields`)]};let i=bn(e,"category");i===void 0?r.push(je(`${t}.category`,`feature '${n}' missing required field 'category'`,`Add 'category' to feature '${n}' (one of: ${EE.join(", ")})`)):(!ta(i)||!EE.includes(i))&&r.push(je(`${t}.category`,`feature '${n}' category must be one of: ${EE.join(", ")}, got ${Wi(i)}`,`Change category of feature '${n}' to one of: ${EE.join(", ")}`));let o=bn(e,"enabled");o===void 0?r.push(je(`${t}.enabled`,`feature '${n}' missing required field 'enabled'`,`Add 'enabled' (boolean) to feature '${n}'`)):aSe(o)||r.push(je(`${t}.enabled`,`feature '${n}' enabled must be boolean, got ${typeof o}`,`Change enabled of feature '${n}' to true or false`));let a=bn(e,"source");return a!==void 0&&(typeof a!="string"||!CM.includes(a))&&r.push(je(`${t}.source`,`feature '${n}' source must be one of: ${CM.join(", ")}, got ${Wi(a)}`,`Set source to one of: ${CM.join(", ")}, or remove it (legacy override)`)),r.length>0?{ok:!1,errors:r}:{ok:!0,value:{category:i,enabled:o,...a!==void 0&&typeof a=="string"&&CM.includes(a)?{source:a}:{}}}}function bHn(e,t,n){let r=[],i=bn(e,"provider");i!==void 0&&!ta(i)&&r.push(je(`${t}.provider`,`profile '${n}' provider must be a string, got ${typeof i}`,`Fix provider in profile '${n}'`));let o=bn(e,"model");o!==void 0&&!ta(o)&&r.push(je(`${t}.model`,`profile '${n}' model must be a string, got ${typeof o}`,`Fix model in profile '${n}'`));let a=bn(e,"source");a!==void 0&&!ta(a)&&r.push(je(`${t}.source`,`profile '${n}' source must be a string, got ${typeof a}`,`Fix source in profile '${n}'`));let s=["apiKey","api_key","token","gatewayToken","gateway_token","secret","password","auth"];for(let u of s)Object.hasOwn(e,u)&&r.push(je(`${t}.${u}`,`profile '${n}' contains forbidden secret field '${u}'`,`Remove '${u}' from profile '${n}' \u2014 PD does not store provider credentials (ADR-0016 \xA72.2)`));if(r.length>0)return{ok:!1,errors:r};let c={type:"openclaw"};return ta(i)&&(c.provider=i),ta(o)&&(c.model=o),ta(a)&&(c.source=a),{ok:!0,value:c}}function SHn(e,t,n){let r=[],i=bn(e,"provider");i===void 0?r.push(je(`${t}.provider`,`profile '${n}' missing required field 'provider'`,`Add 'provider' to profile '${n}' (e.g. "anthropic", "openai")`)):ta(i)||r.push(je(`${t}.provider`,`profile '${n}' provider must be a string, got ${Wi(i)}`,`Fix provider in profile '${n}'`));let o=bn(e,"model");o===void 0?r.push(je(`${t}.model`,`profile '${n}' missing required field 'model'`,`Add 'model' to profile '${n}' (e.g. "claude-3-5-sonnet")`)):ta(o)||r.push(je(`${t}.model`,`profile '${n}' model must be a string, got ${Wi(o)}`,`Fix model in profile '${n}'`));let a=bn(e,"apiKeyEnv");a===void 0?r.push(je(`${t}.apiKeyEnv`,`profile '${n}' missing required field 'apiKeyEnv'`,`Add 'apiKeyEnv' to profile '${n}' (e.g. "ANTHROPIC_API_KEY")`)):ta(a)||r.push(je(`${t}.apiKeyEnv`,`profile '${n}' apiKeyEnv must be a string (env var name), got ${Wi(a)}`,`Fix apiKeyEnv in profile '${n}' to be an environment variable name`));let s=bn(e,"baseUrl");s!==void 0&&!ta(s)&&r.push(je(`${t}.baseUrl`,`profile '${n}' baseUrl must be a string, got ${typeof s}`,`Fix baseUrl in profile '${n}'`));let c=bn(e,"timeoutMs");c!==void 0&&!Bl(c)&&r.push(je(`${t}.timeoutMs`,`profile '${n}' timeoutMs must be a finite number, got ${Wi(c)}`,`Fix timeoutMs in profile '${n}'`)),Bl(c)&&c<=0&&r.push(je(`${t}.timeoutMs`,`profile '${n}' timeoutMs must be positive, got ${c}`,`Set timeoutMs in profile '${n}' to a positive number`));let u=bn(e,"maxRetries");u!==void 0&&!Bl(u)&&r.push(je(`${t}.maxRetries`,`profile '${n}' maxRetries must be a finite number, got ${Wi(u)}`,`Fix maxRetries in profile '${n}'`)),Bl(u)&&u<0&&r.push(je(`${t}.maxRetries`,`profile '${n}' maxRetries must be non-negative, got ${u}`,`Set maxRetries in profile '${n}' to a non-negative integer`)),Bl(u)&&!Number.isInteger(u)&&r.push(je(`${t}.maxRetries`,`profile '${n}' maxRetries must be an integer, got ${u}`,`Set maxRetries in profile '${n}' to a non-negative integer`));let l=bn(e,"maxTokens");l!==void 0&&!Bl(l)&&r.push(je(`${t}.maxTokens`,`profile '${n}' maxTokens must be a finite number, got ${Wi(l)}`,`Fix maxTokens in profile '${n}'`)),Bl(l)&&l<=0&&r.push(je(`${t}.maxTokens`,`profile '${n}' maxTokens must be positive, got ${l}`,`Set maxTokens in profile '${n}' to a positive number`));let p=["minimal","low","medium","high","xhigh"],f=bn(e,"reasoning");f!==void 0&&f!==!1&&!(ta(f)&&p.includes(f))&&r.push(je(`${t}.reasoning`,`profile '${n}' reasoning must be one of: ${p.join(", ")} or false, got ${Wi(f)}`,`Fix reasoning in profile '${n}'`));let m=["apiKey","api_key","token","gatewayToken","gateway_token","secret","password","auth"];for(let h of m)Object.hasOwn(e,h)&&r.push(je(`${t}.${h}`,`profile '${n}' contains forbidden secret field '${h}'`,`Remove '${h}' from profile '${n}' \u2014 use 'apiKeyEnv' for env var name reference (ADR-0016 \xA72.2)`));if(r.length>0)return{ok:!1,errors:r};let g={type:"pi-ai",provider:i,model:o,apiKeyEnv:a};return ta(s)&&(g.baseUrl=s),Bl(c)&&(g.timeoutMs=c),Bl(u)&&(g.maxRetries=u),Bl(l)&&(g.maxTokens=l),f!==void 0&&(g.reasoning=f),{ok:!0,value:g}}function CHn(e,t,n){if(!sc(e))return{ok:!1,errors:[je(t,`profile '${n}' must be an object, got ${typeof e}`,`Fix profile '${n}' to be an object with type, provider, model fields`)]};for(let i of Ea)if(Object.hasOwn(e,i))return{ok:!1,errors:[je(`${t}.${i}`,`profile '${n}' contains dangerous key '${i}'`,`Remove '${i}' from profile '${n}'`)]};let r=bn(e,"type");return r===void 0?{ok:!1,errors:[je(`${t}.type`,`profile '${n}' missing required field 'type'`,`Add 'type' to profile '${n}' (one of: ${$C.join(", ")})`)]}:!ta(r)||!$C.includes(r)?{ok:!1,errors:[je(`${t}.type`,`profile '${n}' type must be one of: ${$C.join(", ")}, got ${Wi(r)}`,`Fix type in profile '${n}'`)]}:r==="openclaw"?bHn(e,t,n):SHn(e,t,n)}function kHn(e,t,n){let r=[];if(!sc(e))return{ok:!1,errors:[je(t,`agent '${n}' must be an object, got ${typeof e}`,`Fix agent '${n}' to be an object with enabled and optional runtimeProfile fields`)]};let i=bn(e,"enabled");i===void 0?r.push(je(`${t}.enabled`,`agent '${n}' missing required field 'enabled'`,`Add 'enabled' (boolean) to agent '${n}'`)):aSe(i)||r.push(je(`${t}.enabled`,`agent '${n}' enabled must be boolean, got ${typeof i}`,`Change enabled of agent '${n}' to true or false`));let o=bn(e,"runtimeProfile");if(o!==void 0&&!ta(o)&&r.push(je(`${t}.runtimeProfile`,`agent '${n}' runtimeProfile must be a string, got ${typeof o}`,`Fix runtimeProfile of agent '${n}' to a profile ID`)),r.length>0)return{ok:!1,errors:r};let a={enabled:i};return ta(o)&&(a.runtimeProfile=o),{ok:!0,value:a}}var b_t=new Set(["empathyObserver"]);function RHn(e,t){let n=[],r=[];if(!sc(e))return{ok:!1,errors:[je(t,`internalAgents must be an object, got ${typeof e}`,"Fix internalAgents to be an object with defaultRuntime and agents")]};let i=bn(e,"defaultRuntime");i===void 0?n.push(je(`${t}.defaultRuntime`,"missing required field defaultRuntime","Add defaultRuntime with a runtime profile ID")):(!ta(i)||i.length===0)&&n.push(je(`${t}.defaultRuntime`,`defaultRuntime must be a non-empty string, got ${Wi(i)}`,"Fix defaultRuntime to a valid runtime profile ID"));let o=bn(e,"agents"),a={};if(o===void 0)n.push(je(`${t}.agents`,"missing required field agents",`Add agents section with per-agent bindings: ${ou.join(", ")}`));else if(!sc(o))n.push(je(`${t}.agents`,`agents must be an object, got ${typeof o}`,"Fix agents to be an object mapping agent names to bindings"));else{for(let c of ou){let u=bn(o,c);if(u===void 0)continue;let l=kHn(u,`${t}.agents.${c}`,c);l.ok?a[c]=l.value:n.push(...l.errors)}for(let c of Object.keys(o))Ea.has(c)||b_t.has(c)||ou.includes(c)||n.push(je(`${t}.agents.${c}`,`unknown agent key '${c}'`,`Remove unknown agent '${c}' or use a known agent name: ${ou.join(", ")}`));for(let c of b_t)Object.hasOwn(o,c)&&r.push(`${t}.agents.${c} is a retired no-op (the agent had no runtime consumer and has been removed) and is now ignored \u2014 remove it from .pd/config.yaml`)}let s=new Set(["defaultRuntime","agents"]);for(let c of Object.keys(e))Ea.has(c)||s.has(c)||n.push(je(`${t}.${c}`,`unknown key '${c}' in internalAgents`,`Remove unknown key '${c}' from internalAgents`));return n.length>0?{ok:!1,errors:n}:{ok:!0,warnings:r,value:{defaultRuntime:i,agents:a}}}function THn(e,t){let n=[];if(!sc(e))return{ok:!1,errors:[je(t,`ui must be an object, got ${typeof e}`,"Fix ui to be an object with diagnostics settings")]};let r=bn(e,"diagnostics");if(!sc(r))return{ok:!1,errors:[je(`${t}.diagnostics`,`ui.diagnostics must be an object, got ${typeof r}`,"Fix ui.diagnostics to be an object with mode field")]};let i=bn(r,"mode");return i===void 0?n.push(je(`${t}.diagnostics.mode`,"missing required field mode",`Add mode to ui.diagnostics (one of: ${xE.join(", ")})`)):(!ta(i)||!xE.includes(i))&&n.push(je(`${t}.diagnostics.mode`,`mode must be one of: ${xE.join(", ")}, got ${Wi(i)}`,`Fix mode to one of: ${xE.join(", ")}`)),n.length>0?{ok:!1,errors:n}:{ok:!0,value:{diagnostics:{mode:i}}}}function OHn(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("/")}function DHn(e){return kM.some(t=>t===e)}function PHn(e,t){let n=[];if(!sc(e))return{ok:!1,errors:[je(t,`workspace must be an object, got ${typeof e}`,"Fix workspace to be an object with a default field")]};for(let s of Ea)if(Object.hasOwn(e,s))return{ok:!1,errors:[je(`${t}.${s}`,`workspace contains dangerous key '${s}'`,`Remove '${s}' from workspace`)]};let r=bn(e,"default");r===void 0?n.push(je(`${t}.default`,"workspace missing required field default","Add default path to workspace section (must be an absolute path)")):!ta(r)||r.length===0?n.push(je(`${t}.default`,`workspace.default must be a non-empty string, got ${Wi(r)}`,"Set workspace.default to an absolute directory path")):OHn(r)||n.push(je(`${t}.default`,`workspace.default must be an absolute path, got "${r}"`,'Use an absolute path like "D:\\.openclaw\\workspace" or "/home/user/.openclaw/workspace"'));let i=bn(e,"environment"),o;i!==void 0&&(ta(i)&&DHn(i)?o=i:n.push(je(`${t}.environment`,`workspace.environment must be one of ${kM.join("|")}, got ${Wi(i)}`,`Set workspace.environment to one of ${kM.join(", ")}, or remove the key to leave the environment unknown`)));let a=new Set(["default","environment"]);for(let s of Object.keys(e))Ea.has(s)||a.has(s)||n.push(je(`${t}.${s}`,`unknown key '${s}' in workspace`,`Remove unknown key '${s}' from workspace`));return n.length>0?{ok:!1,errors:n}:!ta(r)||r.length===0?{ok:!1,errors:[je(`${t}.default`,"workspace.default validation invariant failed","Re-validate the workspace section; this error indicates a validator bug \u2014 please report it")]}:{ok:!0,value:{default:r,...o!==void 0?{environment:o}:{}}}}function LHn(e,t){let n=[],r=[];if(!sc(e))return{ok:!1,errors:[je(t,"contextInjection must be an object","Fix contextInjection to be an object with optional thinkingOs and projectFocus fields")]};for(let c of Ea)if(Object.hasOwn(e,c))return{ok:!1,errors:[je(`${t}.${c}`,`contextInjection contains dangerous key '${c}'`,`Remove '${c}' from contextInjection`)]};let i={},o=bn(e,"thinkingOs");o!==void 0&&(aSe(o)?i.thinkingOs=o:n.push(je(`${t}.thinkingOs`,"contextInjection.thinkingOs must be a boolean","Set contextInjection.thinkingOs to true or false")));let a=bn(e,"projectFocus");a!==void 0&&(!ta(a)||!RM.includes(a)?n.push(je(`${t}.projectFocus`,`contextInjection.projectFocus must be one of: ${RM.join(", ")}, got ${Wi(a)}`,`Set contextInjection.projectFocus to one of: ${RM.join(", ")}`)):i.projectFocus=a);let s=new Set(["thinkingOs","projectFocus","evolutionContext"]);for(let c of Object.keys(e))Ea.has(c)||s.has(c)||n.push(je(`${t}.${c}`,`unknown key '${c}' in contextInjection`,`Remove unknown key '${c}' from contextInjection`));return Object.hasOwn(e,"evolutionContext")&&r.push(`${t}.evolutionContext is a retired no-op (no runtime consumer ever read it) and is now ignored \u2014 remove it from .pd/config.yaml`),n.length>0?{ok:!1,errors:n}:{ok:!0,value:i,warnings:r}}function kX(e){let t=[],n=[];if(e==null)return{ok:!1,errors:[je("","config is null or undefined","Provide a valid .pd/config.yaml file or use defaults")]};if(!sc(e))return{ok:!1,errors:[je("",`config root must be an object, got ${typeof e}`,"Fix .pd/config.yaml to be a YAML object")]};for(let R of Ea)Object.hasOwn(e,R)&&t.push(je(R,`root contains dangerous key '${R}'`,`Remove '${R}' from config root`));let r=bn(e,"version");r===void 0?t.push(je("version","missing required field version",`Add version: ${1} to config`)):(!Bl(r)||r!==1)&&t.push(je("version",`version must be ${1}, got ${Wi(r)}`,`Set version to ${1}`));let i=bn(e,"workspace"),o;if(i!==void 0){let R=PHn(i,"workspace");R.ok?o=R.value:t.push(...R.errors)}let a=bn(e,"features"),s={};if(a===void 0)t.push(je("features","missing required field features","Add features section with prompt, code_tool_hook, defer_archive entries"));else if(!sc(a))t.push(je("features",`features must be an object, got ${typeof a}`,"Fix features to be an object mapping flag names to {category, enabled}"));else for(let R of Object.keys(a)){if(Ea.has(R)){t.push(je(`features.${R}`,`dangerous key '${R}' rejected`,`Remove '${R}' from features`));continue}let M=wHn(a[R],`features.${R}`,R);M.ok?s[R]=M.value:t.push(...M.errors)}let c=bn(e,"runtimeProfiles"),u={};if(c===void 0)t.push(je("runtimeProfiles","missing required field runtimeProfiles","Add runtimeProfiles section with at least one profile"));else if(!sc(c))t.push(je("runtimeProfiles",`runtimeProfiles must be an object, got ${typeof c}`,"Fix runtimeProfiles to be an object mapping profile IDs to profile definitions"));else for(let R of Object.keys(c)){if(Ea.has(R)){t.push(je(`runtimeProfiles.${R}`,`dangerous key '${R}' rejected`,`Remove '${R}' from runtimeProfiles`));continue}let M=CHn(c[R],`runtimeProfiles.${R}`,R);M.ok?(u[R]=M.value,M.value.type==="openclaw"&&n.push(`runtime profile '${R}' uses the retired 'openclaw' backend (ADR-0029): PD no longer runs internal agents through a host CLI session, so agents bound to it report needs_setup until a pi-ai profile is configured`)):t.push(...M.errors)}let l=bn(e,"internalAgents"),p;if(l===void 0)t.push(je("internalAgents","missing required field internalAgents","Add internalAgents section with defaultRuntime"));else{let R=RHn(l,"internalAgents");R.ok?(p=R.value,n.push(...R.warnings)):t.push(...R.errors)}let f=bn(e,"ui"),m;if(f!==void 0){let R=THn(f,"ui");R.ok?m=R.value:t.push(...R.errors)}let g=bn(e,"profile"),h;if(g!==void 0){let R=oSe(g);if(R.ok)h=R.value;else for(let M of R.errors)t.push(je(M.path,M.message,"Fix profile section in .pd/config.yaml"))}let y=bn(e,"contextInjection"),I;if(y!==void 0){let R=LHn(y,"contextInjection");R.ok?(I=R.value,n.push(...R.warnings)):t.push(...R.errors)}let v=bn(e,"reuseEvaluation"),w;if(v!==void 0)if(!sc(v))t.push(je("reuseEvaluation",`reuseEvaluation must be an object, got ${Wi(v)}`,"Set reuseEvaluation to a mapping (e.g. reuseEvaluation: { enabled: true })"));else{for(let $ of Object.keys(v))x_t.has($)||t.push(je(`reuseEvaluation.${$}`,`unknown key '${$}' in reuseEvaluation`,`Remove '${$}'; only ${[...x_t].join(", ")} are supported`));let R=bn(v,"enabled");R!==void 0&&typeof R!="boolean"&&t.push(je("reuseEvaluation.enabled",`enabled must be a boolean, got ${Wi(R)}`,"Set reuseEvaluation.enabled to true or false"));let M=bn(v,"runtimeProfile");M!==void 0&&(typeof M!="string"||M.trim()==="")&&t.push(je("reuseEvaluation.runtimeProfile",`runtimeProfile must be a non-empty string, got ${Wi(M)}`,"Set reuseEvaluation.runtimeProfile to a runtimeProfiles id, or remove the key to fall back to internalAgents.defaultRuntime"));let H=bn(v,"timeoutMs");H!==void 0&&(!Bl(H)||!Number.isFinite(H)||H<=0)&&t.push(je("reuseEvaluation.timeoutMs",`timeoutMs must be a positive number of milliseconds, got ${Wi(H)}`,"Set reuseEvaluation.timeoutMs to a positive integer (e.g. 60000), or remove the key to use the profile timeout")),t.every($=>!$.path.startsWith("reuseEvaluation"))&&(w={enabled:R===void 0?!0:R,...typeof M=="string"&&M.trim()!==""?{runtimeProfile:M}:{},...Bl(H)&&H>0?{timeoutMs:H}:{}})}let b=bn(e,"promptBudget"),k;if(b!==void 0)if(!sc(b))t.push(je("promptBudget",`promptBudget must be an object, got ${Wi(b)}`,"Set promptBudget to a mapping (e.g. promptBudget: { declaredContextWindowTokens: 262144 })"));else{for(let H of Object.keys(b))w_t.has(H)||t.push(je(`promptBudget.${H}`,`unknown key '${H}' in promptBudget`,`Remove '${H}'; only ${[...w_t].join(", ")} are supported`));let R=bn(b,"declaredContextWindowTokens");R!==void 0&&!CX(R)&&t.push(je("promptBudget.declaredContextWindowTokens",`declaredContextWindowTokens must be an integer between ${eS} and ${tS}, got ${Wi(R)}`,"Set promptBudget.declaredContextWindowTokens to the model context window in tokens (e.g. 262144), or remove the key"));let M=bn(b,"hosts");if(M!==void 0)if(!sc(M))t.push(je("promptBudget.hosts",`hosts must be an object, got ${Wi(M)}`,`Set promptBudget.hosts to a mapping keyed by ${wE.join(", ")}`));else for(let[H,$]of Object.entries(M))wE.includes(H)?CX($)||t.push(je(`promptBudget.hosts.${H}`,`host window must be an integer between ${eS} and ${tS}, got ${Wi($)}`,`Set promptBudget.hosts.${H} to the model context window in tokens (e.g. 262144), or remove the key`)):t.push(je(`promptBudget.hosts.${H}`,`unknown host '${H}' in promptBudget.hosts`,`Only ${wE.join(", ")} are supported`));t.every(H=>!H.path.startsWith("promptBudget"))&&(k={...CX(R)?{declaredContextWindowTokens:R}:{},...sc(M)&&Object.keys(M).length>0?{hosts:Object.fromEntries(Object.entries(M).filter(([H,$])=>wE.includes(H)&&CX($)))}:{}})}let P=bn(e,"principles"),B;if(P!==void 0)if(!sc(P))t.push(je("principles",`principles must be an object, got ${Wi(P)}`,"Set principles to a mapping (e.g. principles: { outputLanguage: zh-CN })"));else{let R=Object.hasOwn(P,"outputLanguage")?P.outputLanguage:void 0;R===void 0?B={}:Mj(R)?B={outputLanguage:R}:t.push(je("principles.outputLanguage",`outputLanguage must be one of ${IE.join(", ")}, got ${Wi(R)}`,`Set principles.outputLanguage to one of: ${IE.join(", ")}`))}return t.length>0?{ok:!1,errors:t}:p?{ok:!0,value:{version:1,...o?{workspace:o}:{},features:s,runtimeProfiles:u,internalAgents:p,ui:m??{diagnostics:{mode:"simple"}},...B?{principles:B}:{},...w?{reuseEvaluation:w}:{},...k?{promptBudget:k}:{},...h?{profile:h}:{},...I?{contextInjection:I}:{}},warnings:n}:{ok:!1,errors:[je("internalAgents","internalAgents validation unexpectedly failed","Check internalAgents configuration")]}}var NHn={on_change:"smoke",on_risk_change:"unit",commands:{}},S_t={enabled:!0,spiral_boost:20,min_threshold:15,max_threshold:70,backlog_trigger:6,hard_failure_trigger:1,low_recent_success_boost:15,high_recent_pain_boost:10},MHn={soft_capture_threshold:30,adaptive:{...S_t}},BHn={enabled:!0,heartbeat_stale_hours:72},FHn={enabled:!0,max_file_size_bytes:10*1024*1024,fuzzy_match_enabled:!0,fuzzy_match_threshold:.8,skip_large_file_action:"warn"};var ao={audit_level:"medium",risk_paths:[],evolution_mode:"realtime",tests:{...NHn},pain:{soft_capture_threshold:MHn.soft_capture_threshold,adaptive:{...S_t}},lifecycle:{...BHn},edit_verification:{...FHn},custom_guards:[]};function RX(e){return e?{audit_level:e.audit_level??ao.audit_level,risk_paths:e.risk_paths??ao.risk_paths,evolution_mode:e.evolution_mode??ao.evolution_mode,tests:{on_change:e.tests?.on_change??ao.tests.on_change,on_risk_change:e.tests?.on_risk_change??ao.tests.on_risk_change,commands:{...ao.tests.commands,...e.tests?.commands??{}}},pain:{soft_capture_threshold:e.pain?.soft_capture_threshold??ao.pain.soft_capture_threshold,adaptive:{enabled:e.pain?.adaptive?.enabled??ao.pain.adaptive.enabled,spiral_boost:e.pain?.adaptive?.spiral_boost??ao.pain.adaptive.spiral_boost,min_threshold:e.pain?.adaptive?.min_threshold??ao.pain.adaptive.min_threshold,max_threshold:e.pain?.adaptive?.max_threshold??ao.pain.adaptive.max_threshold,backlog_trigger:e.pain?.adaptive?.backlog_trigger??ao.pain.adaptive.backlog_trigger,hard_failure_trigger:e.pain?.adaptive?.hard_failure_trigger??ao.pain.adaptive.hard_failure_trigger,low_recent_success_boost:e.pain?.adaptive?.low_recent_success_boost??ao.pain.adaptive.low_recent_success_boost,high_recent_pain_boost:e.pain?.adaptive?.high_recent_pain_boost??ao.pain.adaptive.high_recent_pain_boost}},lifecycle:{enabled:e.lifecycle?.enabled??ao.lifecycle.enabled,heartbeat_stale_hours:e.lifecycle?.heartbeat_stale_hours??ao.lifecycle.heartbeat_stale_hours},edit_verification:{enabled:e.edit_verification?.enabled??ao.edit_verification.enabled,max_file_size_bytes:e.edit_verification?.max_file_size_bytes??ao.edit_verification.max_file_size_bytes,fuzzy_match_enabled:e.edit_verification?.fuzzy_match_enabled??ao.edit_verification.fuzzy_match_enabled,fuzzy_match_threshold:e.edit_verification?.fuzzy_match_threshold??ao.edit_verification.fuzzy_match_threshold,skip_large_file_action:e.edit_verification?.skip_large_file_action??ao.edit_verification.skip_large_file_action},custom_guards:e.custom_guards??ao.custom_guards}:{...ao}}function C_t(e){return e?{thinkingOs:e.thinkingOs??DM.thinkingOs,projectFocus:e.projectFocus??DM.projectFocus}:{...DM}}function Av(e){if(e==null)return{config:Gj(),source:"defaults",warnings:[],featuresChangedFromDefault:[],resolvedProfile:RX({}),resolvedContextInjection:C_t(void 0)};let t=[],n=[],{normalized:r,warnings:i}=$j(e.features);t.push(...i);let o={};for(let[b,k]of Object.entries(O0))if(Object.hasOwn(r,b)){let P=r[b];if(!P){o[b]={...k};continue}if(k.category==="gone"){o[b]={...k},P.enabled&&(t.push(`feature '${b}': gone flag cannot be re-enabled`),n.push(b));continue}if(k.category==="core"&&!P.enabled){o[b]={category:P.category,enabled:!1,...P.source?{source:P.source}:{}},t.push(`feature '${b}': core flag explicitly disabled via config (emergency disable)`),n.push(b);continue}(P.category!==k.category||P.enabled!==k.enabled)&&n.push(b),o[b]={category:P.category,enabled:P.enabled,...P.source?{source:P.source}:{}}}else o[b]={...k};for(let b of Object.keys(r))Ea.has(b)||Object.hasOwn(o,b)||t.push(`feature '${b}': unknown flag ignored (not a registered capability)`);let a={};for(let[b,k]of Object.entries(e.runtimeProfiles))Ea.has(b)||(a[b]={...k});Object.hasOwn(a,bE)||(a[bE]={...jj},t.push(`runtime profile '${bE}' not found in config, using default`));let s=TM(),c={};for(let b of ou){let k=e.internalAgents.agents[b],P=s.agents[b];k!==void 0?c[b]={enabled:k.enabled,runtimeProfile:k.runtimeProfile??e.internalAgents.defaultRuntime}:c[b]={enabled:P.enabled,runtimeProfile:e.internalAgents.defaultRuntime}}for(let b of ou){let k=c[b];k&&k.enabled&&k.runtimeProfile&&!Object.hasOwn(a,k.runtimeProfile)&&t.push(`agent '${b}': runtime profile '${k.runtimeProfile}' not found in runtimeProfiles`)}let u=r.diagnostician_split_pipeline;if(u!==void 0&&u.enabled===!1&&c.diagnostician?.enabled===!0){c.diagnostician={enabled:!1,runtimeProfile:e.internalAgents.defaultRuntime};let b=u.source??"unknown";t.push(`PRI-638 cutover: legacy diagnostician_split_pipeline=false (source: ${b}) honored as internalAgents.agents.diagnostician.enabled=false to avoid silently enabling a previously-disabled LLM pipeline. Recovery: toggle Diagnostician ON in Console \u2192 Control Center (the writer retires the conflicting legacy override), or edit .pd/config.yaml to remove the legacy diagnostician_split_pipeline flag. A standalone internalAgents.agents.diagnostician.enabled=true is NOT sufficient while the legacy override remains false.`)}let l={defaultRuntime:e.internalAgents.defaultRuntime,agents:c},p=e.reuseEvaluation??{},f=p.runtimeProfile??e.internalAgents.defaultRuntime;(p.enabled??PM.enabled)&&!Object.hasOwn(a,f)&&t.push(`reuseEvaluation: runtime profile '${f}' not found in runtimeProfiles (the capability will not run until a configured profile is available)`);let g={enabled:p.enabled??PM.enabled,runtimeProfile:f,...p.timeoutMs!==void 0?{timeoutMs:p.timeoutMs}:{}},h=e.ui??{...OM},y=e.principles??{outputLanguage:void 0},I=RX(e.profile??{}),v=C_t(e.contextInjection);return{config:{version:1,...e.workspace?{workspace:e.workspace}:{},features:o,runtimeProfiles:a,internalAgents:l,ui:h,principles:y,reuseEvaluation:g,...e.promptBudget?{promptBudget:e.promptBudget}:{},...e.profile?{profile:e.profile}:{},...e.contextInjection?{contextInjection:e.contextInjection}:{}},source:"user_config",warnings:t,featuresChangedFromDefault:n,resolvedProfile:I,resolvedContextInjection:v}}function UW(e,t){return e?.hosts?.[t]??e?.declaredContextWindowTokens}var $Hn=new Set(["owner_reported","agent_on_owner_request","tool_failure","dispatch_error","provider_failure","rate_limit","rulehost_block","empathy_inferred","semantic","llm_paralysis","subagent_error","unknown"]);function TX(e){return typeof e=="string"&&$Hn.has(e)}var sSe=new Map([["owner_reported",{kind:"owner_reported",defaultDecision:"admit",reason:"Owner explicitly reported pain. Highest confidence signal.",nextAction:"none"}],["agent_on_owner_request",{kind:"agent_on_owner_request",defaultDecision:"admit",reason:"Agent recorded pain at owner request. Owner intent preserved.",nextAction:"none"}],["tool_failure",{kind:"tool_failure",defaultDecision:"evidence_only",reason:"Tool failure is a technical trajectory fact, never a behavioral-deviation Pain by itself (Phase A).",nextAction:"store_as_evidence_for_later_correlation"}],["dispatch_error",{kind:"dispatch_error",defaultDecision:"evidence_only",reason:"Dispatch/subagent routing error. Not a behavior pattern.",nextAction:"store_as_evidence_for_later_correlation"}],["provider_failure",{kind:"provider_failure",defaultDecision:"health_only",reason:"LLM provider failure. Infrastructure health signal, not owner-relevant behavior.",nextAction:"record_in_health_telemetry"}],["rate_limit",{kind:"rate_limit",defaultDecision:"health_only",reason:"LLM provider rate limit. Infrastructure health signal, not owner-relevant behavior.",nextAction:"record_in_health_telemetry"}],["rulehost_block",{kind:"rulehost_block",defaultDecision:"evidence_only",reason:"RuleHost block is a technical block fact. Correct blocks are not Owner pain; wrong blocks reach correction detection (Phase A).",nextAction:"store_as_evidence_for_later_correlation"}],["empathy_inferred",{kind:"empathy_inferred",defaultDecision:"owner_confirm",reason:"Empathy-inferred frustration. Never silently creates diagnosis (PRODUCT_IDENTITY: owner-governed).",nextAction:"request_owner_confirmation_before_diagnosis"}],["semantic",{kind:"semantic",defaultDecision:"evidence_only",reason:"Keyword/detection match. Not explicit owner pain. Needs accumulation.",nextAction:"store_as_evidence_for_later_correlation"}],["llm_paralysis",{kind:"llm_paralysis",defaultDecision:"evidence_only",reason:"Session health signal. Not sufficient for diagnosis on its own.",nextAction:"store_as_evidence_for_later_correlation"}],["subagent_error",{kind:"subagent_error",defaultDecision:"evidence_only",reason:"Subagent workflow failure. Not a behavior pattern by itself.",nextAction:"store_as_evidence_for_later_correlation"}],["unknown",{kind:"unknown",defaultDecision:"evidence_only",reason:"Unclassified source. Conservative default.",nextAction:"classify_source_kind_and_store_as_evidence"}]]);function nL(e){return sSe.get(e)}function OX(e){let t=TX(e.sourceKind)?e.sourceKind:"unknown",n=nL(t);return n?{decision:n.defaultDecision,sourceKind:t,reason:n.reason,nextAction:n.nextAction}:{decision:"evidence_only",sourceKind:"unknown",reason:`Source kind '${t}' not found in descriptor registry. Conservative default.`,nextAction:"classify_source_kind_and_store_as_evidence"}}function rL(e){let{isManualEntry:t,isGateBlock:n,isSubagentError:r,isRateLimit:i,toolName:o,failureSource:a,detectionSource:s,nonZeroExit:c,timedOut:u,toolNotFound:l}=e;if(t)return"owner_reported";if(n)return"rulehost_block";if(r)return"subagent_error";if(i===!0)return"rate_limit";if(i===!1)return"provider_failure";if(o==="pain"||o==="skill:pain")return e.provenance==="host_context_bound"?"agent_on_owner_request":"owner_reported";if(a)return a==="dispatch_error"?"dispatch_error":"tool_failure";if(l||(o!==void 0||c||u||l)&&(!o||o.trim()===""))return"dispatch_error";if(c||u)return"tool_failure";if(s){if(s==="llm_paralysis")return"llm_paralysis";if(s.startsWith("llm_"))return"semantic";if(s==="user_empathy")return"empathy_inferred"}return"unknown"}function HHn(e){if(!e)return"tool_failure";let t=String(e);return/\btool\s+(?:\S+\s+)?not\s+found\b/i.test(t)||/\bunknown\s+tool\b/i.test(t)?"dispatch_error":"tool_failure"}function iL(e){let{toolName:t,error:n,provenance:r}=e,i=typeof e.exitCode=="number"&&e.exitCode!==0,o;return!t||t.trim()===""?o="dispatch_error":o=HHn(n),!n&&!i&&(o=void 0),{observedAt:new Date().toISOString(),toolName:t,failureSource:o,nonZeroExit:i,provenance:r}}function QW(e){return{observedAt:new Date().toISOString(),isManualEntry:!0,sessionId:e.sessionId}}function k_t(e,t){let n=[];return e&&n.push(`kind=${e.kind}`),n.push(`score=${t.score}`),t.sessionId&&n.push(`session=${t.sessionId.slice(0,8)}`),n.join(", ")}function jHn(e){return{outcome:"refused",reason:e.validationError??"Input validation failed. Evidence is malformed or incomplete.",nextAction:"fix_input_and_retry_or_classify_as_unknown",sourceKind:e.triageResult.sourceKind,triageDecision:e.triageResult.decision,shouldCreateDiagnosticTask:!1,decidedAt:new Date().toISOString(),operatorNote:`validationError=${e.validationError??"unknown"}`}}function GHn(e){return{outcome:"manual_owner_admitted",reason:"Owner explicit manual pain. Bypasses triage and cooldown. Highest confidence signal.",nextAction:"create_diagnostic_task",sourceKind:e.triageResult.sourceKind,triageDecision:e.triageResult.decision,shouldCreateDiagnosticTask:!0,decidedAt:new Date().toISOString(),operatorNote:`score=${e.score}, sessionId=${e.sessionId??"unknown"}`}}function qHn(e){let{triageResult:t}=e,n=nL(t.sourceKind),r=new Date().toISOString();switch(t.decision){case"admit":return e.isCooldownActive&&!e.cooldownBypassAllowed?{outcome:"cooldown_skipped",reason:`Admitted by triage but cooldown is active for source '${t.sourceKind}'. Cooldown prevents diagnosis to avoid duplicate tasks.`,nextAction:"wait_for_cooldown_or_manual_retrigger",sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`cooldown_active=true, score=${e.score}`}:{outcome:"diagnosis_created",reason:t.reason,nextAction:t.nextAction==="none"?"proceed_with_diagnostic_task":t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!0,decidedAt:r,operatorNote:k_t(n,e)};case"evidence_only":return{outcome:"evidence_only",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:k_t(n,e)};case"health_only":return{outcome:"health_only",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`provider_signal, score=${e.score}`};case"owner_confirm":return{outcome:"owner_confirm_required",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`requires_confirmation, score=${e.score}`};case"reject":return{outcome:"refused",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`rejected, score=${e.score}`};default:{let i=t.decision;return{outcome:"refused",reason:`Unhandled triage decision: ${String(t.decision)}. Conservative refusal.`,nextAction:"investigate_unknown_triage_decision",sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r}}}}function DX(e){return e.isValid?e.isOwnerManual?GHn(e):qHn(e):jHn(e)}var R_t=[{key:"why",headerRegex:/^##\s+1\.\s*Why\s*$/im,label:"why",header:"## 1. Why"},{key:"desiredOutcome",headerRegex:/^##\s+2\.\s*Desired Outcome\s*$/im,label:"desiredOutcome",header:"## 2. Desired Outcome"},{key:"nonNegotiables",headerRegex:/^##\s+3\.\s*Non-negotiables\s*$/im,label:"nonNegotiables",header:"## 3. Non-negotiables"},{key:"stopEscalation",headerRegex:/^##\s+4\.\s*Stop\s*\/\s*Escalation\s*$/im,label:"stopEscalation",header:"## 4. Stop / Escalation"},{key:"currentStrategicFocus",headerRegex:/^##\s+5\.\s*Current Strategic Focus\s*$/im,label:"currentStrategicFocus",header:"## 5. Current Strategic Focus"}];function PX(e){let t={};for(let n of R_t){let r=n.headerRegex.exec(e);if(r===null)continue;let i=e.slice(r.index+r[0].length),o=/^##\s+/m.exec(i);t[n.key]=i.slice(0,o!==null?o.index:i.length).trim()}return t}function cSe(e){let t=[];for(let n of R_t){let i=Object.hasOwn(e,n.key)?e[n.key]:void 0;if(i===void 0){t.push({code:"missing_section",message:`Section "${n.label}" is missing from INTENT.md.`,section:n.label});continue}if(typeof i!="string"){t.push({code:"parse_failed",message:`Section "${n.label}" has a non-string value.`,section:n.label});continue}if(i.trim().length===0){t.push({code:"empty_section",message:`Section "${n.label}" is empty.`,section:n.label});continue}i.length<10&&t.push({code:"too_vague",message:`Section "${n.label}" is too short.`,section:n.label})}return t}function Hm(e){return`INTENT.${e}.md`}import{createHash as XHn}from"node:crypto";function LX(e){return`sha256:${XHn("sha256").update(e,"utf8").digest("hex")}`}function Du(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var uSe=4e3,lSe=`
|
|
1948
1948
|
...[truncated: intent doc exceeds injection budget]`;function dSe(e){if(e==null)return"";let t=typeof e.rawIntentMd=="string"?e.rawIntentMd:"";if(t.trim().length===0)return"";let n=Du(t);if(n.length>uSe){let a=uSe-lSe.length;n=n.slice(0,Math.max(0,a))+lSe}let r=`<intent_anchor>
|
|
1949
1949
|
This is the Owner-owned project intent.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
|
-
"version": "3.1.
|
|
5
|
+
"version": "3.1.4",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true,
|
|
8
8
|
"onCapabilities": [
|
|
@@ -46,6 +46,10 @@
|
|
|
46
46
|
"type": "string",
|
|
47
47
|
"minLength": 1
|
|
48
48
|
},
|
|
49
|
+
"principleId": {
|
|
50
|
+
"type": "string",
|
|
51
|
+
"minLength": 1
|
|
52
|
+
},
|
|
49
53
|
"expiresAt": {
|
|
50
54
|
"type": "string",
|
|
51
55
|
"format": "date-time"
|
package/openclaw.plugin.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
|
-
"version": "3.1.
|
|
5
|
+
"version": "3.1.4",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true,
|
|
8
8
|
"onCapabilities": [
|
|
@@ -46,6 +46,10 @@
|
|
|
46
46
|
"type": "string",
|
|
47
47
|
"minLength": 1
|
|
48
48
|
},
|
|
49
|
+
"principleId": {
|
|
50
|
+
"type": "string",
|
|
51
|
+
"minLength": 1
|
|
52
|
+
},
|
|
49
53
|
"expiresAt": {
|
|
50
54
|
"type": "string",
|
|
51
55
|
"format": "date-time"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "principles-disciple",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.4",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -76,22 +76,22 @@
|
|
|
76
76
|
"compile-principles": "node scripts/compile-principles.mjs"
|
|
77
77
|
},
|
|
78
78
|
"devDependencies": {
|
|
79
|
-
"@principles/core": "^6.0.
|
|
80
|
-
"@principles/host-runtime": "^3.1.
|
|
79
|
+
"@principles/core": "^6.0.1",
|
|
80
|
+
"@principles/host-runtime": "^3.1.2",
|
|
81
81
|
"@types/better-sqlite3": "^9.6.0",
|
|
82
82
|
"@types/js-yaml": "^4.0.9",
|
|
83
83
|
"@types/micromatch": "^4.0.10",
|
|
84
|
-
"@types/node": "^26.
|
|
84
|
+
"@types/node": "^26.6.6",
|
|
85
85
|
"@types/ws": "^8.18.2",
|
|
86
86
|
"@typescript-eslint/eslint-plugin": "^8.68.0",
|
|
87
87
|
"@typescript-eslint/parser": "^8.70.1",
|
|
88
88
|
"@vitest/coverage-v8": "^5.0.0",
|
|
89
89
|
"esbuild": "^0.28.2",
|
|
90
90
|
"eslint": "^10.8.1",
|
|
91
|
-
"jsdom": "^
|
|
91
|
+
"jsdom": "^31.0.0",
|
|
92
92
|
"typescript": "^7.0.2",
|
|
93
|
-
"vite": "^8.3.
|
|
94
|
-
"vitest": "^5.
|
|
93
|
+
"vite": "^8.3.6",
|
|
94
|
+
"vitest": "^5.1.0",
|
|
95
95
|
"ws": "^8.22.0"
|
|
96
96
|
},
|
|
97
97
|
"peerDependencies": {
|
|
@@ -109,5 +109,5 @@
|
|
|
109
109
|
"js-yaml": "^5.4.3",
|
|
110
110
|
"micromatch": "^4.0.8"
|
|
111
111
|
},
|
|
112
|
-
"gitHead": "
|
|
112
|
+
"gitHead": "4000adc495a7c146f4d9282c114d0d936d8e196a"
|
|
113
113
|
}
|