principles-disciple 3.1.2 → 3.1.3

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 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===`
@@ -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.2",
5
+ "version": "3.1.3",
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"
@@ -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.2",
5
+ "version": "3.1.3",
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.2",
3
+ "version": "3.1.3",
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",
@@ -81,17 +81,17 @@
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.4.1",
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": "^30.1.1",
91
+ "jsdom": "^31.0.0",
92
92
  "typescript": "^7.0.2",
93
- "vite": "^8.3.4",
94
- "vitest": "^5.0.0",
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": "8a791cfcfb34ec1a70dcdf392f4afc86c1a278c8"
112
+ "gitHead": "e7c7e6bba35aa7d691496cf126b195ea3a70fef9"
113
113
  }