@sapienx/agentos 0.6.6 → 0.6.7
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/README.md +1 -1
- package/bundle/.next/BUILD_ID +1 -1
- package/bundle/.next/app-path-routes-manifest.json +16 -16
- package/bundle/.next/build-manifest.json +3 -3
- package/bundle/.next/prerender-manifest.json +3 -3
- package/bundle/.next/react-loadable-manifest.json +3 -2
- package/bundle/.next/required-server-files.json +2 -2
- package/bundle/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/bundle/.next/server/app/_global-error.html +1 -1
- package/bundle/.next/server/app/_global-error.rsc +1 -1
- package/bundle/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/bundle/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/bundle/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/bundle/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/bundle/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/bundle/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/bundle/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/bundle/.next/server/app/_not-found.html +2 -2
- package/bundle/.next/server/app/_not-found.rsc +2 -2
- package/bundle/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/bundle/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/bundle/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
- package/bundle/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/bundle/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/bundle/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/bundle/.next/server/app/accounts/page.js +1 -1
- package/bundle/.next/server/app/accounts/page.js.nft.json +1 -1
- package/bundle/.next/server/app/accounts/page_client-reference-manifest.js +1 -1
- package/bundle/.next/server/app/agents/page.js +1 -1
- package/bundle/.next/server/app/agents/page.js.nft.json +1 -1
- package/bundle/.next/server/app/agents/page_client-reference-manifest.js +1 -1
- package/bundle/.next/server/app/api/accounts/access-rules/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/accounts/login-targets/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/agents/[agentId]/chat/route.js +2 -2
- package/bundle/.next/server/app/api/agents/[agentId]/chat/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/agents/route.js +1 -1
- package/bundle/.next/server/app/api/agents/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/diagnostics/route.js +1 -1
- package/bundle/.next/server/app/api/diagnostics/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/gateway/control/route.js +1 -1
- package/bundle/.next/server/app/api/gateway/control/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/mission/route.js +1 -1
- package/bundle/.next/server/app/api/mission/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/models/catalog/route.js +1 -2
- package/bundle/.next/server/app/api/models/catalog/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/models/providers/route.js +1 -2
- package/bundle/.next/server/app/api/models/providers/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/onboarding/models/route.js +8 -9
- package/bundle/.next/server/app/api/onboarding/models/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/onboarding/route.js +8 -8
- package/bundle/.next/server/app/api/onboarding/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/openclaw/compatibility-smoke/route.js +1 -1
- package/bundle/.next/server/app/api/openclaw/compatibility-smoke/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/planner/[planId]/deploy/route.js +1 -1
- package/bundle/.next/server/app/api/planner/[planId]/deploy/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/planner/[planId]/document-rewrite/route.js +1 -1
- package/bundle/.next/server/app/api/planner/[planId]/document-rewrite/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/planner/[planId]/route.js +1 -1
- package/bundle/.next/server/app/api/planner/[planId]/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/planner/[planId]/simulate/route.js +1 -1
- package/bundle/.next/server/app/api/planner/[planId]/simulate/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/planner/[planId]/turn/route.js +1 -1
- package/bundle/.next/server/app/api/planner/[planId]/turn/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/planner/route.js +1 -1
- package/bundle/.next/server/app/api/planner/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/reset/route.js +1 -1
- package/bundle/.next/server/app/api/reset/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/runtimes/[runtimeId]/route.js +1 -1
- package/bundle/.next/server/app/api/runtimes/[runtimeId]/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/settings/gateway/route.js +1 -1
- package/bundle/.next/server/app/api/settings/gateway/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/settings/openclaw-binary/route.js +1 -1
- package/bundle/.next/server/app/api/settings/openclaw-binary/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/settings/workspace-root/route.js +1 -1
- package/bundle/.next/server/app/api/settings/workspace-root/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/snapshot/route.js +1 -1
- package/bundle/.next/server/app/api/snapshot/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/stream/route.js +1 -1
- package/bundle/.next/server/app/api/stream/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/tasks/[taskId]/abort/route.js +1 -1
- package/bundle/.next/server/app/api/tasks/[taskId]/abort/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/tasks/[taskId]/control/route.js +1 -1
- package/bundle/.next/server/app/api/tasks/[taskId]/control/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/tasks/[taskId]/stream/route.js +1 -1
- package/bundle/.next/server/app/api/tasks/[taskId]/stream/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/update/route.js +7 -7
- package/bundle/.next/server/app/api/update/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/channels/discovered-groups/route.js +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/channels/discovered-groups/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/channels/route.js +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/channels/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/edit-draft/route.js +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/edit-draft/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/files/route.js +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/files/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/surfaces/discovery/route.js +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/surfaces/discovery/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/surfaces/reconcile/route.js +1 -1
- package/bundle/.next/server/app/api/workspaces/[workspaceId]/surfaces/reconcile/route.js.nft.json +1 -1
- package/bundle/.next/server/app/api/workspaces/route.js +1 -1
- package/bundle/.next/server/app/api/workspaces/route.js.nft.json +1 -1
- package/bundle/.next/server/app/files/page.js +1 -1
- package/bundle/.next/server/app/files/page.js.nft.json +1 -1
- package/bundle/.next/server/app/files/page_client-reference-manifest.js +1 -1
- package/bundle/.next/server/app/integrations/page.js +1 -1
- package/bundle/.next/server/app/integrations/page.js.nft.json +1 -1
- package/bundle/.next/server/app/integrations/page_client-reference-manifest.js +1 -1
- package/bundle/.next/server/app/models/page.js +1 -1
- package/bundle/.next/server/app/models/page.js.nft.json +1 -1
- package/bundle/.next/server/app/models/page_client-reference-manifest.js +1 -1
- package/bundle/.next/server/app/page.js +1 -1
- package/bundle/.next/server/app/page.js.nft.json +1 -1
- package/bundle/.next/server/app/page_client-reference-manifest.js +1 -1
- package/bundle/.next/server/app/settings/page.js +1 -1
- package/bundle/.next/server/app/settings/page.js.nft.json +1 -1
- package/bundle/.next/server/app/settings/page_client-reference-manifest.js +1 -1
- package/bundle/.next/server/app/tasks/page.js +1 -1
- package/bundle/.next/server/app/tasks/page.js.nft.json +1 -1
- package/bundle/.next/server/app/tasks/page_client-reference-manifest.js +1 -1
- package/bundle/.next/server/app-paths-manifest.json +16 -16
- package/bundle/.next/server/chunks/1718.js +1 -1
- package/bundle/.next/server/chunks/1908.js +12 -0
- package/bundle/.next/server/chunks/{4466.js → 2307.js} +1 -1
- package/bundle/.next/server/chunks/4391.js +36 -36
- package/bundle/.next/server/chunks/4767.js +20 -19
- package/bundle/.next/server/chunks/4983.js +3 -1
- package/bundle/.next/server/chunks/6476.js +5 -5
- package/bundle/.next/server/chunks/{6320.js → 6637.js} +1 -1
- package/bundle/.next/server/chunks/{7396.js → 7085.js} +1 -1
- package/bundle/.next/server/chunks/9494.js +183 -0
- package/bundle/.next/server/middleware-build-manifest.js +1 -1
- package/bundle/.next/server/middleware-react-loadable-manifest.js +1 -1
- package/bundle/.next/server/pages/404.html +2 -2
- package/bundle/.next/server/pages/500.html +1 -1
- package/bundle/.next/server/server-reference-manifest.json +1 -1
- package/bundle/.next/static/chunks/2083-e309043f80c43402.js +1 -0
- package/bundle/.next/static/chunks/2125-162d48301a8f53b4.js +3 -0
- package/bundle/.next/static/chunks/2207-4f66fd1ddff2aba5.js +1 -0
- package/bundle/.next/static/chunks/{6276-fdd5e81abda749e8.js → 2603-769710adda1d633d.js} +1 -1
- package/bundle/.next/static/chunks/4137.19010bab7fabf352.js +1 -0
- package/bundle/.next/static/chunks/{3315-597211dffe007157.js → 4176-f5f581e6cd26d962.js} +4 -4
- package/bundle/.next/static/chunks/7197.866876dffb806516.js +1 -0
- package/bundle/.next/static/chunks/{7442-4cc100ec1115e55d.js → 7442-717620617b49de55.js} +36 -36
- package/bundle/.next/static/chunks/8373-cadb82a39137601c.js +1 -0
- package/bundle/.next/static/chunks/app/accounts/page-2caea77f8a44146b.js +1 -0
- package/bundle/.next/static/chunks/app/agents/page-d4c7bfe64d44b003.js +1 -0
- package/bundle/.next/static/chunks/app/files/page-a16b11d418e6dbe5.js +1 -0
- package/bundle/.next/static/chunks/app/integrations/page-2314a29ba4274466.js +1 -0
- package/bundle/.next/static/chunks/app/models/page-7850176ce8455112.js +1 -0
- package/bundle/.next/static/chunks/app/page-da330bca609cd094.js +1 -0
- package/bundle/.next/static/chunks/app/settings/page-a6c7770571bf5fe1.js +1 -0
- package/bundle/.next/static/chunks/app/tasks/page-af0098a4b77a7e2e.js +1 -0
- package/bundle/.next/static/chunks/webpack-0a8ad3b5f2b4bb1b.js +1 -0
- package/bundle/.next/static/css/39bff2e14c799896.css +3 -0
- package/bundle/server.js +1 -1
- package/package.json +1 -1
- package/bundle/.next/server/chunks/2082.js +0 -183
- package/bundle/.next/server/chunks/707.js +0 -12
- package/bundle/.next/static/chunks/2083-42815fbe60a1bf82.js +0 -1
- package/bundle/.next/static/chunks/2842.b8d0551fd4d397d4.js +0 -1
- package/bundle/.next/static/chunks/6672-f468873ca90420ef.js +0 -1
- package/bundle/.next/static/chunks/6848-bf85a5b7d7c1e82b.js +0 -1
- package/bundle/.next/static/chunks/7197.f130bbf23030eec7.js +0 -1
- package/bundle/.next/static/chunks/app/accounts/page-c9e49f6fc4ec8e1e.js +0 -1
- package/bundle/.next/static/chunks/app/agents/page-6729705e1231670f.js +0 -1
- package/bundle/.next/static/chunks/app/files/page-88c9118871e40c6f.js +0 -1
- package/bundle/.next/static/chunks/app/integrations/page-b0541340ce23ac08.js +0 -1
- package/bundle/.next/static/chunks/app/models/page-d46f533a6ad10e54.js +0 -1
- package/bundle/.next/static/chunks/app/page-78b8c43dceba02d6.js +0 -1
- package/bundle/.next/static/chunks/app/settings/page-dc8c5f99e93317b5.js +0 -1
- package/bundle/.next/static/chunks/app/tasks/page-2d8a967801747f41.js +0 -1
- package/bundle/.next/static/chunks/webpack-6d3da3859b096ce1.js +0 -1
- package/bundle/.next/static/css/2755afb6503b0e79.css +0 -3
- /package/bundle/.next/static/{Pe2Qv8_zpxfA-X03dV603 → Lmp1cZ9_c9K3sYYLpgFsg}/_buildManifest.js +0 -0
- /package/bundle/.next/static/{Pe2Qv8_zpxfA-X03dV603 → Lmp1cZ9_c9K3sYYLpgFsg}/_ssgManifest.js +0 -0
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
exports.id=6476,exports.ids=[6476],exports.modules={3442:()=>{},6491:()=>{},7565:(a,b,c)=>{"use strict";c.d(b,{QL:()=>h,Xz:()=>g});var d=c(38699),e=c(26516);let f=null;function g(){let a;return f||(a=new d.p,f=(0,e.JG)()?a:new e.gH({fallback:a})),f}function h(a="reset"){let b=f;f=null;try{b?.close?.(a)}catch{}}},14805:(a,b,c)=>{"use strict";c.d(b,{Wy:()=>k,eG:()=>i,fh:()=>h,kz:()=>j,lk:()=>l,tj:()=>g});var d=c(51455),e=c(48161),f=c(76760);let g="AGENTOS_RUNTIME_DIR",h="openclaw-gateway-auth.json";function i(a=process.env){return"1"===a.AGENTOS_PACKAGE_RUNTIME}function j(a=process.env){return(0,f.join)(function(a=process.env){var b;let c=a[g]?.trim();return c?(b=c).startsWith("~")?(0,f.join)((0,e.homedir)(),b.slice(1)):b:(0,f.join)((0,e.homedir)(),".agentos")}(a),h)}async function k(a,b=process.env){let c=a.value.trim();if(!c)throw Error("Gateway token/password is required.");let e=j(b);return await (0,d.mkdir)((0,f.dirname)(e),{recursive:!0}),await (0,d.writeFile)(e,`${JSON.stringify({version:1,kind:a.kind,value:c,updatedAt:new Date().toISOString()},null,2)}
|
|
1
|
+
exports.id=6476,exports.ids=[6476],exports.modules={3442:()=>{},6491:()=>{},7565:(a,b,c)=>{"use strict";c.d(b,{QL:()=>h,Xz:()=>g});var d=c(38699),e=c(26516);let f=null;function g(){let a;return f||(a=new d.p,f=(0,e.JG)()?a:new e.gH({fallback:a})),f}function h(a="reset"){let b=f;f=null;try{b?.close?.(a)}catch{}}},11315:(a,b,c)=>{"use strict";c.d(b,{L:()=>d,c:()=>e});let d="2026.6.1",e="2026.6.1"},11782:(a,b,c)=>{"use strict";c.d(b,{AV:()=>g,JC:()=>j,JN:()=>h,Kg:()=>e,gt:()=>i,jw:()=>k});var d=c(65395);function e(a,b,c){if(!b)return null;let e=(0,d.W2)(a),g=Math.max(Array.from(c).filter(b=>f(a,b)).length,(b.allowed??[]).filter(b=>f(a,b)).length),h=n(b.auth?.providers,a),i=n(b.auth?.oauth?.providers,a),j=q(i)?i:null,k=Array.isArray(j?.profiles)?j.profiles:null,l=k?k.filter(a=>{if(!q(a))return!1;let b=o(a.status)?.toLowerCase();return!b||!["expired","missing","invalid","error","disabled","revoked"].includes(b)}).length:0,m=o(i?.status)?.toLowerCase(),r=q(h?.profiles)?h.profiles:{},s=p(r.count)??0,t=p(r.token)??0,u=p(r.apiKey)??0,v=function({provider:a,visibleCount:b,oauthProfiles:c,usableOauthProfileCount:d,oauthStatus:e,profileCount:f,tokenProfileCount:g,apiKeyProfileCount:h,oauthProfileCount:i,effectiveKind:j,syntheticAuthValue:k}){return"ollama"===a?b>0:"openai-codex"===a?!!(c&&d>0||"ok"===e||k||"oauth"===j||"synthetic"===j):"openai"===a?!!(g+h>0||j&&["token","apikey","api-key"].includes(j)||"profiles"===j&&f>0&&0===i):"ok"===e||f>0||!!k||!!(j&&["ok","profiles","token","apikey","api-key","oauth","synthetic"].includes(j))}({provider:a,visibleCount:g,oauthProfiles:k,usableOauthProfileCount:l,oauthStatus:m,profileCount:s,tokenProfileCount:t,apiKeyProfileCount:u,oauthProfileCount:p(r.oauth)??0,effectiveKind:o(h?.effective?.kind)?.toLowerCase(),syntheticAuthValue:o(h?.syntheticAuth?.value)});return{provider:a,connected:v,canConnect:!0,needsTerminal:"oauth"===e.connectKind,detail:function({provider:a,descriptor:b,connected:c,visibleCount:d,profileCount:e,usableOauthProfileCount:f,oauthStatus:g}){return"ollama"===a?d>0?`${d} local model${1===d?"":"s"} detected.`:"Install or pull a local model to unlock this route.":c?f>0||"ok"===g?"OAuth connected":e>0?`${e} auth profile${1===e?"":"s"}`:"openai-codex"===a&&d>0?`Codex app-server connected with ${d} available model${1===d?"":"s"}.`:d>0?`${d} configured model${1===d?"":"s"} in AgentOS.`:`${b.shortLabel} is connected.`:d>0?`${d} configured model${1===d?"":"s"} are already saved in AgentOS. Connect ${b.shortLabel} to use them.`:b.helperText}({provider:a,descriptor:e,connected:v,visibleCount:g,profileCount:s,usableOauthProfileCount:l,oauthStatus:m})}}function f(a,b,c){let d=c||b.split("/",1)[0]||"";return"openai-codex"===a?"codex"===d||"openai-codex"===d||k(b):d===a}function g(a,b,c={}){let d=a.split("/",1)[0]||"unknown",e=c.provider?.trim()||null;return"codex"===e||"openai-codex"===e||"codex"===d||"openai"===d&&l(a,b,c)?"openai-codex":d}function h(a){let b=a.trim(),c=/^(?:codex|openai-codex)\/(.+)$/i.exec(b);return c?`openai/${c[1]}`:b}function i(a,b){let c=h(a);return"openai-codex"===b||/^codex\//i.test(a)||/^openai-codex\//i.test(a)||k(c)?`openai-codex:${c.toLowerCase()}`:`${b}:${c.toLowerCase()}`}function j(a,b,c={}){let d=a.split("/",1)[0]||"",e=c.provider?.trim()||null;return"openai-codex"===e||"openai-codex"===d||"codex"===e||"codex"===d||"openai"===d&&l(a,b,c)}function k(a){return/^openai\/(?:gpt-5\.5|gpt-5\.4-mini)$/i.test(a)||/^openai\/.*codex/i.test(a)}function l(a,b,c={}){if(/^openai\/.*codex/i.test(a)||c.tags?.some(m))return!0;if(!k(a))return!1;if(!b)return!0;let d=e("openai-codex",b,[]),f=e("openai",b,[]);return!!(d?.connected&&!f?.connected)}function m(a){return/^(codex|openai-codex|chatgpt|app-server|codex-app-server)$/i.test(a.trim())}function n(a,b){return a?.find(a=>{var c,d;return c=o(a.provider),d=b,!!c&&("openai-codex"===d?"openai"===c||"codex"===c||"openai-codex"===c:c===d)})}function o(a){return"string"==typeof a&&a.trim()?a.trim():null}function p(a){return"number"==typeof a&&Number.isFinite(a)?a:null}function q(a){return!!a&&"object"==typeof a&&!Array.isArray(a)}},14805:(a,b,c)=>{"use strict";c.d(b,{Wy:()=>k,eG:()=>i,fh:()=>h,kz:()=>j,lk:()=>l,tj:()=>g});var d=c(51455),e=c(48161),f=c(76760);let g="AGENTOS_RUNTIME_DIR",h="openclaw-gateway-auth.json";function i(a=process.env){return"1"===a.AGENTOS_PACKAGE_RUNTIME}function j(a=process.env){return(0,f.join)(function(a=process.env){var b;let c=a[g]?.trim();return c?(b=c).startsWith("~")?(0,f.join)((0,e.homedir)(),b.slice(1)):b:(0,f.join)((0,e.homedir)(),".agentos")}(a),h)}async function k(a,b=process.env){let c=a.value.trim();if(!c)throw Error("Gateway token/password is required.");let e=j(b);return await (0,d.mkdir)((0,f.dirname)(e),{recursive:!0}),await (0,d.writeFile)(e,`${JSON.stringify({version:1,kind:a.kind,value:c,updatedAt:new Date().toISOString()},null,2)}
|
|
2
2
|
`,{encoding:"utf8",mode:384}),await (0,d.chmod)(e,384),e}async function l(a=process.env){let b;try{b=JSON.parse(await (0,d.readFile)(j(a),"utf8"))}catch{return null}let c="token"===b.kind||"password"===b.kind?b.kind:null,e="string"==typeof b.value&&b.value.trim()?b.value.trim():null;return c&&e?{kind:c,value:e}:null}},15292:(a,b,c)=>{"use strict";c.d(b,{Ck:()=>p,Df:()=>t,Fs:()=>r,XV:()=>q,bq:()=>o,g:()=>s,ml:()=>n});var d=c(73024),e=c(51455),f=c(48161),g=c.n(f),h=c(76760),i=c.n(h),j=c(31421),k=c(97411);let l=i().join(g().homedir(),".openclaw"),m=i().join(l,"binary-selection.json");function n(){return{mode:"auto",path:null,resolvedPath:null,label:"Auto",detail:"Use the managed resolution order."}}async function o(){try{let c=await (0,e.readFile)(m,"utf8");var a,b=JSON.parse(c);if(!b||"object"!=typeof b)return n();let d=(a=b.mode,"auto"===a||"local-prefix"===a||"global-path"===a||"custom"===a?a:null);if(!d||"auto"===d)return n();let f="string"==typeof b.path?b.path.trim():"";return f?{mode:d,path:i().normalize(f),resolvedPath:i().normalize(f),label:"local-prefix"===d?"Local prefix":"global-path"===d?"Global PATH":"Custom path",detail:i().normalize(f)}:n()}catch(a){return"object"==typeof a&&a&&"code"in a&&a.code,n()}}async function p(a){await (0,e.mkdir)(l,{recursive:!0}),await (0,e.writeFile)(m,`${JSON.stringify(a,null,2)}
|
|
3
3
|
`,{encoding:"utf8",mode:384}),await (0,e.chmod)(m,384)}async function q(a){await (0,e.access)(a,d.constants.X_OK);let b=i().basename(a).toLowerCase();if("openclaw"!==b&&"openclaw.exe"!==b)throw Error("OpenClaw binary path must point to an executable named openclaw.");let c=(0,j.spawnSync)(a,["--version"],{encoding:"utf8",timeout:5e3,env:{...process.env}});if(c.error||0!==c.status)throw Error("OpenClaw binary did not pass the --version probe.");let f=`${c.stdout||""}
|
|
4
|
-
${c.stderr||""}`.trim();if(!/\bopenclaw\b/i.test(f)&&!/\b\d+(?:\.\d+)+\b/.test(f))throw Error("OpenClaw binary did not return a recognizable version.")}async function r(){let a="win32"===process.platform?"where":"which",b="win32"===process.platform?["openclaw.exe"]:["openclaw"],c=(0,j.spawnSync)(a,b,{encoding:"utf8"});if(0!==c.status||c.error)throw Error("Could not resolve openclaw from PATH.");let d=c.stdout.split(/\r?\n/).map(a=>a.trim()).find(Boolean)||"";if(!d)throw Error("Could not resolve openclaw from PATH.");return d}function s(a){return a&&"auto"!==a.mode?"local-prefix"===a.mode?(0,k.lz)():a.path:null}function t(a,b){return a?{...a,resolvedPath:"auto"===a.mode?b:a.resolvedPath||a.path||b}:{...n(),resolvedPath:b}}},17929:(a,b,c)=>{"use strict";c.d(b,{FZ:()=>function a(b){return"string"==typeof b?o(b):Array.isArray(b)?b.some(b=>a(b)):!!h(b)&&Object.values(b).some(b=>a(b))},LK:()=>h,Pu:()=>k,WW:()=>m,e6:()=>i,g:()=>g,hz:()=>n,nf:()=>j,o0:()=>o,r0:()=>l,r_:()=>f,yK:()=>p});var d=c(24117),e=c(98717);function f(){return`agentos:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`}function g(a){return"string"==typeof a?a.trim():""}function h(a){return!!a&&"object"==typeof a&&!Array.isArray(a)}function i(a,b){if(!b.trim())return a;let c=a;for(let a of j(b)){if(Array.isArray(c)&&"number"==typeof a){c=c[a];continue}if(!h(c)||"string"!=typeof a)return;c=c[a]}return c}function j(a){let b,c=[],d=/([^[.\]]+)|\[(\d+)\]/g;for(;b=d.exec(a);)b[1]?c.push(b[1]):b[2]&&c.push(Number(b[2]));return c}function k(a){return JSON.parse(JSON.stringify(a))}function l(a,b,c){let d=j(b);if(0===d.length)throw new e.pz("Config path is required.","unknown");let f=a;for(let a=0;a<d.length-1;a+=1){let b=d[a],c=d[a+1];if("string"!=typeof b)throw new e.pz("Array root config paths are not supported.","unknown");let g=f[b];if(h(g)||Array.isArray(g)){f=g;continue}let i="number"==typeof c?[]:{};f[b]=i,f=i}let g=d[d.length-1];if("number"==typeof g){if(!Array.isArray(f))throw new e.pz("Config path points to an array index on a non-array parent.","unknown");f[g]=c;return}f[g]=c}function m(a,b){let c=j(b);if(0===c.length)throw new e.pz("Config path is required.","unknown");let d=a;for(let a=0;a<c.length-1;a+=1){let b=c[a];if(void 0===(d=Array.isArray(d)&&"number"==typeof b||h(d)&&"string"==typeof b?d[b]:void 0))return}let f=c[c.length-1];Array.isArray(d)&&"number"==typeof f?d.splice(f,1):h(d)&&"string"==typeof f&&delete d[f]}function n(a,b){return{stdout:JSON.stringify(a??{}),stderr:"",...b?{metadata:b}:{}}}function o(a){return a===d.K$}function p(a){return"string"==typeof a&&a.trim()?a.trim():null}},21916:(a,b,c)=>{"use strict";function d(a,b,c){return"in_progress"===a||b?.endsWith(":main")&&"number"==typeof c&&c<36e5?"running":"completed"===a||"done"===a?"completed":"failed"===a||"error"===a?"stalled":"idle"}function e(a){return a.rpcOk?a.activeRuntime?.status==="running"||a.activeRuntime?.status==="queued"?"engaged":a.heartbeatEnabled?"monitoring":a.lastActiveAt?"ready":"standby":"offline"}function f(a){if(a.runtime)return a.runtime.taskId?"running"===a.runtime.status||"queued"===a.runtime.status?`Tracking task ${a.runtime.taskId.slice(0,8)}`:"completed"===a.runtime.status?`Recent task ${a.runtime.taskId.slice(0,8)} completed`:"cancelled"===a.runtime.status?`Recent task ${a.runtime.taskId.slice(0,8)} cancelled`:"stalled"===a.runtime.status?`Recent task ${a.runtime.taskId.slice(0,8)} waiting for output`:`Recent task ${a.runtime.taskId.slice(0,8)}`:"running"===a.runtime.status||"queued"===a.runtime.status?"Maintaining main session context":"Main session recently updated";return a.heartbeatEvery?`Heartbeat on ${a.heartbeatEvery}`:"standby"===a.status?"Waiting for assignment":"Ready for next turn"}function g(a,b){let c=b.filter(b=>a.includes(b.id));return c.some(a=>"engaged"===a.status)?"engaged":c.some(a=>"monitoring"===a.status)?"monitoring":c.some(a=>"ready"===a.status)?"ready":c.some(a=>"offline"===a.status)?"offline":"standby"}function h(a,b){var c,d,e,f;let g=a.filter(a=>{var b;return!1!==(b=a).available&&!b.missing}),h=t([...a.map(a=>a.key.split("/")[0]||"unknown"),...(b?.auth?.providers??[]).map(a=>a?.provider).filter(u),...(b?.auth?.oauth?.providers??[]).map(a=>a?.provider).filter(u)].filter(u)),m=new Map((b?.auth?.providers??[]).filter(a=>u(a?.provider)).map(a=>[a.provider,a])),n=new Map((b?.auth?.oauth?.providers??[]).filter(a=>u(a?.provider)).map(a=>[a.provider,a])),o=r(b?.resolvedDefault??void 0),p=r(b?.defaultModel??void 0),q=o??p,s=q?k(q):null,v=!!(q&&g.some(a=>a.key===q)&&(c=s,d=a,e=m,f=n,c&&("ollama"===c?d.some(a=>i(c,a.key)&&!0===a.local):j(c).some(a=>{var b,c,d;let g,h;return b=a,c=e,d=f,g=c.get(b),h=d.get(b),(g?.profiles?.count??0)>0||h?.status==="ok"})))),w=v?q:g[0]?.key??null,x=h.map(b=>{var c;let d,e=a.filter(a=>i(b,a.key)),f=e.some(a=>!0!==a.local),g="ollama"!==b&&f,h=m.get(b),j=n.get(b),k="ollama"===b?e.some(a=>a.local):(h?.profiles?.count??0)>0||j?.status==="ok",o=null;return j?.status==="ok"?o="OAuth connected":(h?.profiles?.count??0)>0?o=`${h?.profiles?.count} auth profile${h?.profiles?.count===1?"":"s"}`:"ollama"===b&&k?o="Local Ollama model detected.":"ollama"===b?o="Install or pull a local model to unlock this route.":f&&(o="openai-codex"===(d=(c=b).trim().toLowerCase())?"Use the ChatGPT account-based login flow in terminal to use this route.":"openrouter"===d||"openai"===d||"anthropic"===d||"xai"===d||"google"===d||"gemini"===d||"deepseek"===d||"mistral"===d?`Add your ${l(c)} API key in terminal to use this route.`:`Connect ${l(c)} auth in terminal to use this route.`),{provider:b,connected:k,canLogin:g,detail:o}}),y=(b?.auth?.missingProvidersInUse??[]).filter(u),z=new Set(y),A=b?.auth?.unusableProfiles?.length??0,B=[];0===g.length&&B.push("No available models were detected yet."),g.length>0&&!q&&B.push("Choose a default model to finish setup."),q&&!v&&(s&&z.has(s)?B.push(`Default model is set, but ${l(s)} auth is still missing.`):y.length>0?B.push(`Default model is set, but auth is still missing for: ${y.join(", ")}.`):B.push("The selected default model is not ready yet.")),y.length>0&&!q&&B.push(`Auth is still missing for: ${y.join(", ")}.`),A>0&&B.push("Some stored model auth profiles are not usable.");let C=function(a){let b=a.defaultProvider?j(a.defaultProvider):[];if(b.some(b=>a.authProviders.some(a=>a.provider===b&&a.connected)))return null;for(let c of b){let b=a.authProviders.find(a=>a.provider===c&&!a.connected&&a.canLogin);if(b)return b.provider}let c=a.missingProvidersInUse.find(b=>a.authProviders.some(a=>a.provider===b&&!a.connected&&a.canLogin));return c||(a.authProviders.find(a=>!a.connected&&a.canLogin)?.provider??(a.providerIds.includes("openai-codex")||0===a.readyModels.length?"openai-codex":null))}({defaultProvider:s,authProviders:x,missingProvidersInUse:y,providerIds:h,readyModels:g});return{ready:g.length>0&&v,defaultModel:p??null,resolvedDefaultModel:o??null,defaultModelReady:v,recommendedModelId:w??null,preferredLoginProvider:C,totalModelCount:a.length,availableModelCount:g.length,localModelCount:g.filter(a=>a.local).length,remoteModelCount:g.filter(a=>!0!==a.local).length,missingModelCount:a.filter(a=>a.missing||!1===a.available).length,authProviders:x,issues:t(B)}}function i(a,b){let c=k(b)??"unknown";return"openai-codex"===a?"openai"===c||"openai-codex"===c:c===a}function j(a){return"openai"===a?["openai","openai-codex"]:[a]}function k(a){let[b]=a.split("/",1);return b||null}function l(a){let b=a.trim().toLowerCase();return"openrouter"===b?"OpenRouter":"openai-codex"===b?"ChatGPT":"openai"===b?"OpenAI":"anthropic"===b?"Anthropic":"ollama"===b?"Ollama":"xai"===b?"xAI":"google"===b||"gemini"===b?"Gemini":"deepseek"===b?"DeepSeek":"mistral"===b?"Mistral":a.split("-").map(a=>a?a[0].toUpperCase()+a.slice(1):a).join(" ")}function m(a){return a.rpcOk||a.hasOpenClawSignal?!a.rpcOk||a.warningCount>0||a.runtimeIssueCount>0?"degraded":"healthy":"offline"}function n(a){return Object.entries(a).flatMap(([a,b])=>"rejected"!==b.status?[]:[`${a}: ${b.reason instanceof Error?b.reason.message:String(b.reason)}`])}function o(a){let b=r(a.legacyInfo);if(a.latestVersion&&a.currentVersion){let b=p(a.latestVersion,a.currentVersion);return b>0?`Update available: v${a.latestVersion} is ready. Current version: v${a.currentVersion}.`:0===b?`OpenClaw is up to date on v${a.currentVersion}.`:`Running v${a.currentVersion}. Registry currently reports v${a.latestVersion}.`}return a.latestVersion?`Latest available version: v${a.latestVersion}. Current version could not be determined.`:b||(a.updateError?`Update registry check failed: ${a.updateError}`:a.currentVersion?`Running v${a.currentVersion}. Update registry status is still loading.`:void 0)}function p(a,b){let c=q(a),d=q(b),e=Math.max(c.length,d.length);for(let a=0;a<e;a+=1){let b=c[a]??0,e=d[a]??0;if("number"==typeof b&&"number"==typeof e){if(b!==e)return b-e;continue}let f=String(b),g=String(e);if(f!==g)return f.localeCompare(g)}return 0}function q(a){return a.trim().replace(/^v/i,"").split(/[^0-9a-zA-Z]+/).filter(Boolean).map(a=>/^\d+$/.test(a)?Number(a):a.toLowerCase())}function r(a){return a?.trim()||void 0}function s(a){let b=r(a);if(b)return b.split(/\r?\n/,1)[0]?.trim()||b}function t(a){return Array.from(new Set(a))}function u(a){return!!a}c.d(b,{Am:()=>t,Lp:()=>n,Nk:()=>r,OZ:()=>g,QK:()=>p,QL:()=>h,YO:()=>m,iP:()=>f,mB:()=>o,nn:()=>s,xH:()=>d,yv:()=>e})},24117:(a,b,c)=>{"use strict";c.d(b,{$s:()=>m,Fj:()=>n,Ht:()=>p,JV:()=>h,K$:()=>r,N4:()=>d,OJ:()=>f,Rg:()=>l,Tv:()=>q,ZX:()=>j,aj:()=>k,dK:()=>e,lY:()=>i,mh:()=>g,vO:()=>o});let d="ws://127.0.0.1:18789",e=4e3,f=8e3,g=3e4,h="connect",i=3,j=4,k={min:3,max:4},l="gateway-client",m="backend",n="device-auth.json",o="device.json",p=Buffer.from("302a300506032b6570032100","hex"),q=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing","operator.talk.secrets"],r="__OPENCLAW_REDACTED__"},26516:(a,b,c)=>{"use strict";c.d(b,{gH:()=>al,aj:()=>m.aj,Lo:()=>ak,JG:()=>C});var d=c(38699),e=c(65493),f=c(80500),g=c(77598),h=c(51455),i=c(48161),j=c(76760),k=c(14805),l=c(98717),m=c(24117),n=c(17929),o=c(78446);async function p(a,b,c,d){if(d.readLocalConfigFile){let a=await q(b);if(a.fromConfigFile)return a}for(let d of b){let b=null;try{b=await a.getConfig(d,c)}catch(a){if((0,o.D)(a))return{value:"",invalidConfig:!0};continue}let e=(0,n.g)(b);if((0,n.o0)(e))throw new l.pz(`${d} is configured but OpenClaw returned a redacted secret. Set AGENTOS_OPENCLAW_GATEWAY_TOKEN/PASSWORD or OPENCLAW_GATEWAY_TOKEN/PASSWORD to enable native Gateway WS; using CLI fallback.`,"auth");if(e)return{value:e,invalidConfig:!1}}return{value:"",invalidConfig:!1}}async function q(a){let b,c=await w((b=process.env.OPENCLAW_CONFIG_PATH?.trim())?v(b):(0,j.join)(u(),"openclaw.json"));if(!c)return{value:"",invalidConfig:!1,fromConfigFile:!1};for(let b of a){let a=(0,n.g)((0,n.e6)(c,b));if((0,n.o0)(a))throw new l.pz(`${b} is configured but OpenClaw returned a redacted secret. Set AGENTOS_OPENCLAW_GATEWAY_TOKEN/PASSWORD or OPENCLAW_GATEWAY_TOKEN/PASSWORD to enable native Gateway WS; using CLI fallback.`,"auth");if(a)return{value:a,invalidConfig:!1,fromConfigFile:!0}}return{value:"",invalidConfig:!1,fromConfigFile:!0}}async function r(a,b,c,d){let e=s(c)?["gateway.auth.token","gateway.remote.token"]:["gateway.remote.token","gateway.auth.token"],f=s(c)?["gateway.auth.password","gateway.remote.password"]:["gateway.remote.password","gateway.auth.password"],g=b.token?.trim()||process.env.AGENTOS_OPENCLAW_GATEWAY_TOKEN?.trim()||process.env.OPENCLAW_GATEWAY_TOKEN?.trim();if(g)return{token:g,password:""};let h=b.password?.trim()||process.env.AGENTOS_OPENCLAW_GATEWAY_PASSWORD?.trim()||process.env.OPENCLAW_GATEWAY_PASSWORD?.trim();if(h)return{token:"",password:h};let i=await p(a,e,d,{readLocalConfigFile:!b.webSocketFactory});if(i.value||i.invalidConfig)return{token:i.value,password:""};let j=s(c)?await (0,k.lk)():null;if(j?.kind==="token")return{token:j.value,password:""};let l=await p(a,f,d,{readLocalConfigFile:!b.webSocketFactory}),m=l.invalidConfig?"":l.value;return m||j?.kind!=="password"?{token:"",password:m}:{token:"",password:j.value}}function s(a){try{let{hostname:b}=new URL(a);return"localhost"===b||"127.0.0.1"===b||"::1"===b||"[::1]"===b}catch{return!1}}async function t(a,b){if(!s(a)||b.webSocketFactory)return null;let c=u(),[d,e]=await Promise.all([w((0,j.join)(c,"identity",m.vO)),w((0,j.join)(c,"identity",m.Fj))]),f=(0,n.yK)(d?.deviceId),g=(0,n.yK)(d?.publicKeyPem),h=(0,n.yK)(d?.privateKeyPem),i=(0,n.yK)(e?.tokens?.operator?.token);return f&&g&&h&&i&&e?.deviceId===f?{deviceId:f,publicKeyPem:g,privateKeyPem:h,token:i}:null}function u(){let a=process.env.OPENCLAW_STATE_DIR?.trim();return a?v(a):(0,j.join)((0,i.homedir)(),".openclaw")}function v(a){return a.startsWith("~")?(0,j.join)((0,i.homedir)(),a.slice(1)):a}async function w(a){try{return JSON.parse(await (0,h.readFile)(a,"utf8"))}catch{return null}}function x(a){return a.toString("base64").replaceAll("+","-").replaceAll("/","_").replace(/=+$/g,"")}function y(a){return"string"==typeof a?a.trim().replaceAll("|",""):""}async function z(a,b,c,d,e){var f,h,i,j;let k,l,n=await t(c,b),o=b.scopes??m.Tv,p="",q="";try{let e=await r(a,b,c,d);p=e.token,q=e.password}catch(a){if(!n?.token)throw a}let s=!n||p||q?null:n,u=s?.token??p,v=u?{token:u}:q?{password:q}:void 0,w=Date.now(),z=process.platform,A=s&&e?{id:s.deviceId,publicKey:(j=s.publicKeyPem,(k=Buffer.from((0,g.createPublicKey)(j).export({type:"spki",format:"der"}))).length===m.Ht.length+32&&k.subarray(0,m.Ht.length).equals(m.Ht)?x(k.subarray(m.Ht.length)):x(k)),signature:(h=s.privateKeyPem,i=["v3",(f={deviceId:s.deviceId,clientId:b.clientName??m.Rg,clientMode:m.$s,role:b.role??"operator",scopes:o,signedAtMs:w,token:u??null,nonce:e,platform:z,deviceFamily:null}).deviceId,f.clientId,f.clientMode,f.role,f.scopes.join(","),String(f.signedAtMs),f.token??"",f.nonce,y(f.platform),y(f.deviceFamily)].join("|"),l=(0,g.createPrivateKey)(h),x((0,g.sign)(null,Buffer.from(i,"utf8"),l))),signedAt:w,nonce:e}:void 0;return{deviceAuth:s,params:{minProtocol:m.lY,maxProtocol:m.ZX,client:{id:b.clientName??m.Rg,version:b.clientVersion??"agentos",platform:z,mode:m.$s,instanceId:b.instanceId},role:b.role??"operator",scopes:o,caps:["tool-events"],...v?{auth:v}:{},...A?{device:A}:{},userAgent:"AgentOS",locale:"en"}}}var A=c(79102);function B(a){return a?.trim().toLowerCase()}function C(){let a=B(process.env.AGENTOS_OPENCLAW_GATEWAY_CLIENT??process.env.OPENCLAW_GATEWAY_CLIENT),b=B(process.env.AGENTOS_OPENCLAW_NATIVE_WS);return"cli"===a||"0"===b||"false"===b||"off"===b}function D(a,b){if("number"==typeof a&&Number.isFinite(a)&&a>0)return a;let c=Number(process.env.AGENTOS_OPENCLAW_NATIVE_WS_TIMEOUT_MS);return Number.isFinite(c)&&c>0?c:b&&/^(chat\.send|sessions\.send|sessions\.abort|chat\.abort)$/.test(b)?m.mh:b&&/(^|\.)(list|get|status|authStatus|schema|tail)$/.test(b)?m.OJ:m.dK}function E(a,b={}){var c;let d=(c=a,/(^|\.)(add|assign|cancel|configure|create|delete|invoke|put|remove|setup|update|set|unset|patch|apply|send|abort|resolve|restart|start|stop|logout)$/i.test(c))?"mutation":"read";return{safety:d,timeoutMs:b.timeoutMs,allowCliFallback:!0,allowReadCliFallbackOnNativeFailure:!1,allowMutationFallbackOnUnsupported:"mutation"===d}}function F(a,b,c){if(!1===c.allowCliFallback)return!1;let d=(0,l.$g)(a);return"mutation"!==c.safety?"unsupported"===d.kind||!0===c.allowReadCliFallbackOnNativeFailure:!!c.allowUnsafeMutationCliFallback||(!(a instanceof l.jl)||a.method===b)&&"unsupported"===d.kind&&!1!==c.allowMutationFallbackOnUnsupported}var G=c(99663);function H(a,b,c){if(a.addEventListener&&a.removeEventListener)return a.addEventListener(b,c),()=>a.removeEventListener?.(b,c);if(a.on){let d=(...a)=>{var d;"close"===b?c({code:"number"==typeof a[0]?a[0]:void 0,reason:"string"==typeof(d=a[1])?d:Buffer.isBuffer(d)?d.toString("utf8"):ArrayBuffer.isView(d)?Buffer.from(d.buffer,d.byteOffset,d.byteLength).toString("utf8"):void 0}):c(a[0])};return a.on(b,d),()=>{a.off?a.off(b,d):a.removeListener?.(b,d)}}let d=`on${b}`,e=a[d];return a[d]=c,()=>{a[d]===c&&(a[d]=e??null)}}function I(a){if(!a||"object"!=typeof a)return null;let b="number"==typeof a.code?a.code:null,c="string"==typeof a.reason?a.reason:"";return b?`${b}${c?`: ${c}`:""}`:c||null}function J(a){if("string"!=typeof a)if(a instanceof ArrayBuffer)a=new TextDecoder().decode(a);else{if(!ArrayBuffer.isView(a))return null;a=new TextDecoder().decode(a)}try{return JSON.parse(a)}catch(a){throw new l.As("OpenClaw Gateway returned invalid JSON.",{cause:a})}}function K(a){if(a?.aborted)throw new l.As("OpenClaw Gateway request was aborted.")}async function L(a,b,c){K(c),1!==a.readyState&&await new Promise((d,e)=>{let f=!1,g=[],h=a=>{if(!f){for(let a of(f=!0,globalThis.clearTimeout(i),g))a();c?.removeEventListener("abort",j),a()}},i=globalThis.setTimeout(()=>{h(()=>e(new l.As("Timed out connecting to OpenClaw Gateway.")))},b),j=()=>{h(()=>e(new l.As("OpenClaw Gateway request was aborted.")))};g.push(H(a,"open",()=>h(d)),H(a,"error",a=>h(()=>e(new l.As("Failed to connect to OpenClaw Gateway.",{cause:a})))),H(a,"close",a=>h(()=>e(new l.As(`OpenClaw Gateway closed before the connection was ready${I(a)?` (${I(a)})`:""}.`))))),c?.addEventListener("abort",j,{once:!0})})}async function M(a,b,c){return K(c),await new Promise((d,e)=>{let f=!1,g=[],h=a=>{if(!f){for(let a of(f=!0,globalThis.clearTimeout(i),g))a();c?.removeEventListener("abort",j),a()}},i=globalThis.setTimeout(()=>{h(()=>e(new l.As("OpenClaw Gateway connect challenge timed out.")))},b),j=()=>{h(()=>e(new l.As("OpenClaw Gateway request was aborted.")))};g.push(H(a,"message",a=>{try{let b=a?.data??a,c=J(b);if(c?.type!=="event"||"connect.challenge"!==c.event)return;let f=c.payload?.nonce;if("string"!=typeof f||!f.trim())return void h(()=>e(new l.As("OpenClaw Gateway connect challenge is missing a nonce.")));h(()=>d(f.trim()))}catch(a){h(()=>e(a))}}),H(a,"close",a=>h(()=>e(new l.As(`OpenClaw Gateway closed before the connect challenge${I(a)?` (${I(a)})`:""}.`))))),c?.addEventListener("abort",j,{once:!0})})}function N(a,b,c,d,e,f){K(f);let g=(0,n.r_)();return new Promise((h,i)=>{function j(){globalThis.clearTimeout(n),f?.removeEventListener("abort",m)}function k(a){b.delete(g),j(),i(a)}function m(){k(new l.As("OpenClaw Gateway request was aborted."))}let n=globalThis.setTimeout(()=>{k(new l.jl(`Timed out waiting for OpenClaw Gateway method "${c}".`,c,!0))},e);b.set(g,{resolve:a=>{j(),h(a)},reject:k,timer:n,cleanup:j,method:c,sent:!1}),f?.addEventListener("abort",m,{once:!0});try{a.send(JSON.stringify({type:"req",id:g,method:c,params:d}));let e=b.get(g);e&&(e.sent=!0)}catch(a){k(new l.jl(`Failed to send OpenClaw Gateway method "${c}".`,c,!1,{cause:a}))}})}class O{constructor(a,b){this.fallback=a,this.options=b,this.socket=null,this.pending=new Map,this.cleanupCallbacks=[],this.eventListeners=new Set,this.closeListeners=new Set,this.connectPromise=null,this.hello=null,this.state="idle",this.lastNativeError=null,this.lastConnectedAt=null,this.lastDisconnectedAt=null}getDiagnostics(){return{connectionState:this.state,protocolVersion:"number"==typeof this.hello?.protocol?this.hello.protocol:null,lastNativeError:this.lastNativeError,lastConnectedAt:this.lastConnectedAt,lastDisconnectedAt:this.lastDisconnectedAt}}async request(a,b,c,d){let e=await this.ensureConnected(c,d);(0,A.qi)(e,a);let f=this.socket;if(!f||1!==f.readyState)throw new l.As("OpenClaw Gateway connection is not ready.");return N(f,this.pending,a,b,d,c.signal)}async probe(a,b){return this.ensureConnected(a,b)}async subscribe(a,b,c,d){let e=await this.ensureConnected(c,d),f=(0,A.sq)(a,e);if(0===f.length&&!(0,A.pP)(e,"chat")&&!(0,A.pP)(e,"agent")&&!(0,A.pP)(e,"session.message")&&!(0,A.pP)(e,"session.tool")&&!(0,A.pP)(e,"sessions.changed")&&!(0,A.pP)(e,"task")&&!(0,A.pP)(e,"task.updated")&&!(0,A.pP)(e,"task.completed")&&!(0,A.pP)(e,"artifact")&&!(0,A.pP)(e,"artifact.updated")&&!(0,A.pP)(e,"exec.approval.requested")&&!(0,A.pP)(e,"plugin.approval.requested"))throw new l.As("OpenClaw Gateway does not advertise compatible runtime event streaming.",{kind:"unsupported"});let g=a=>{try{b.onEvent(a)}catch(a){b.onError?.(a)}},h=()=>b.onClose?.();this.eventListeners.add(g),this.closeListeners.add(h);try{for(let a of f)await this.request(a.method,a.params,c,d)}catch(a){throw this.eventListeners.delete(g),this.closeListeners.delete(h),a}let i=!1;return{close:()=>{!i&&(i=!0,this.eventListeners.delete(g),this.closeListeners.delete(h),f.length>0&&this.close("event subscription closed"))}}}close(a="closed"){this.disconnect(new l.As(`OpenClaw Gateway connection closed: ${a}.`),{notify:!0,closeSocket:!0,state:"closed"})}async ensureConnected(a,b){return(K(a.signal),this.socket?.readyState===1&&this.hello)?this.hello:(this.connectPromise||(this.connectPromise=this.connect(a,b).finally(()=>{this.connectPromise=null})),this.connectPromise)}async connect(a,b){var c;this.disconnect(new l.As("Replacing stale OpenClaw Gateway connection."),{notify:!1,closeSocket:!0,state:"connecting"});let d=(c=this.options.url,c?.trim()||process.env.AGENTOS_OPENCLAW_GATEWAY_URL?.trim()||process.env.OPENCLAW_GATEWAY_URL?.trim()||m.N4),e=function(a){let b=a??("u">typeof process&&"1"===process.env.AGENTOS_PACKAGE_RUNTIME&&"function"==typeof globalThis.WebSocket?globalThis.WebSocket:"u">typeof process&&process.versions?.node?G.kb:globalThis.WebSocket);if(!b)throw new l.As("Native WebSocket is not available in this runtime.");return b}(this.options.webSocketFactory),f=await z(this.fallback,this.options,d,a),g=new e(d);this.socket=g,this.state="connecting",this.lastNativeError=null,this.cleanupCallbacks=[H(g,"message",a=>this.handleMessage(a)),H(g,"error",a=>{let b=new l.As("OpenClaw Gateway WebSocket error.",{cause:a});this.lastNativeError=b.message,this.rejectPending(b)}),H(g,"close",a=>{let b=I(a);this.disconnect(new l.As(`OpenClaw Gateway connection closed${b?` (${b})`:""}.`),{notify:!0,closeSocket:!1,state:"closed"})})];try{await L(g,b,a.signal);let c=f.deviceAuth?(await z(this.fallback,this.options,d,a,await M(g,b,a.signal))).params:f.params,e=await N(g,this.pending,m.JV,c,b,a.signal);return(0,A.MK)(e),this.hello=e,this.state="connected",this.lastConnectedAt=new Date().toISOString(),this.lastNativeError=null,e}catch(a){throw this.lastNativeError=a instanceof Error?a.message:String(a),this.disconnect(a,{notify:!0,closeSocket:!0,state:"error"}),a}}handleMessage(a){try{let b=a?.data??a,c=J(b);if(!c)return;if("event"===c.type){for(let a of[...this.eventListeners])a(c);return}if("res"!==c.type||void 0===c.id)return;let d=String(c.id),e=this.pending.get(d);if(!e)return;if(this.pending.delete(d),globalThis.clearTimeout(e.timer),!1===c.ok)return void e.reject(new l.jl(function(a){if("string"==typeof a)return a;if(a&&"object"==typeof a){let b="string"==typeof a.message?a.message:null,c="string"==typeof a.detail?a.detail:null;return["string"==typeof a.code?a.code:null,b,c].filter(Boolean).join(": ")}return""}(c.error)||c.message||c.code||"OpenClaw Gateway request failed.",e.method,e.sent,{cause:c}));e.resolve(c.payload)}catch(a){this.lastNativeError=a instanceof Error?a.message:String(a),this.rejectPending(a)}}rejectPending(a){for(let[b,c]of this.pending)globalThis.clearTimeout(c.timer),this.pending.delete(b),c.reject(a)}disconnect(a,b){let c=!!this.socket,d=this.socket;for(let a of(this.socket=null,this.hello=null,this.state=b.state,"connecting"!==b.state&&c&&(this.lastDisconnectedAt=new Date().toISOString()),this.cleanupCallbacks))a();if(this.cleanupCallbacks=[],this.rejectPending(a),b.notify)for(let a of[...this.closeListeners])a();b.closeSocket&&d&&function(a){if(3===a.readyState)return;let b=H(a,"error",()=>{}),c=globalThis.setTimeout(()=>{b?.(),b=null},5e3);"object"==typeof c&&c&&"unref"in c&&"function"==typeof c.unref&&c.unref();try{if(0===a.readyState&&"function"==typeof a.terminate)return void a.terminate();a.close()}catch{b?.(),b=null,globalThis.clearTimeout(c)}}(d)}}function P(a,b){let c=b?.trim();if(c?.startsWith("agent:"))return c;let d=a?.trim()||"main";return c?`agent:${d}:explicit:${c}`:`agent:${d}:main`}function Q(a={}){let b=a.key?.trim()||a.sessionKey?.trim();if(b)return{key:b};let c=a.sessionId?.trim(),d=a.agentId?.trim();return{agentId:d||void 0,sessionId:c||void 0,key:d||c?P(d,c):void 0}}function R(a,b){return"number"==typeof a.timeoutSeconds&&Number.isFinite(a.timeoutSeconds)&&a.timeoutSeconds>0?Math.floor(1e3*a.timeoutSeconds):"number"==typeof b.timeoutMs&&Number.isFinite(b.timeoutMs)&&b.timeoutMs>0?b.timeoutMs:45e3}function S(a){let b=(0,l.$g)(a).kind,c=a instanceof Error?a.message:String(a||"");return"unsupported"===b||"conflict"===b||"malformed-response"===b||/invalid .*sessions\.(create|patch) params|unexpected property/i.test(c)}var T=c(17661),U=c(21916);let V=T.Ik({runtimeVersion:T.Yj().optional(),version:T.Yj().optional(),updateChannel:T.Yj().optional()}).passthrough(),W=T.Ik({defaultId:T.Yj().optional(),mainKey:T.Yj().optional(),scope:T.Yj().optional(),agents:T.YO(T.Ik({id:T.Yj(),name:T.Yj().optional(),identity:T.Ik({name:T.Yj().optional(),theme:T.Yj().optional(),emoji:T.Yj().optional(),avatar:T.Yj().optional(),avatarUrl:T.Yj().optional()}).passthrough().optional(),workspace:T.Yj().optional(),model:T.Ik({primary:T.Yj().optional(),fallbacks:T.YO(T.Yj()).optional()}).passthrough().optional()}).passthrough())}).passthrough(),X=T.Ik({sessions:T.YO(T.Ik({}).passthrough())}).passthrough(),Y=T.Ik({ts:T.ai().optional(),channelOrder:T.YO(T.Yj()).optional().default([]),channelLabels:T.g1(T.Yj(),T.Yj()).optional().default({}),channelDetailLabels:T.g1(T.Yj(),T.Yj()).optional(),channelSystemImages:T.g1(T.Yj(),T.Yj()).optional(),channelMeta:T.YO(T.Ik({id:T.Yj(),label:T.Yj(),detailLabel:T.Yj(),systemImage:T.Yj().optional()}).passthrough()).optional(),channels:T.g1(T.Yj(),T.L5()),channelAccounts:T.g1(T.Yj(),T.YO(T.Ik({accountId:T.Yj()}).passthrough())),channelDefaultAccountId:T.g1(T.Yj(),T.KC([T.Yj(),T.ch()])).optional().default({})}).passthrough(),Z=T.Ik({models:T.YO(T.Ik({key:T.Yj().optional(),id:T.Yj().optional(),provider:T.Yj().optional(),name:T.Yj(),input:T.KC([T.Yj(),T.YO(T.Yj())]).optional().default("text"),contextWindow:T.ai().nullable().optional().default(null),local:T.zM().nullable().optional().default(null),available:T.zM().nullable().optional().default(null),tags:T.YO(T.Yj()).optional().default([]),missing:T.zM().optional().default(!1)}).passthrough())}).passthrough(),$=T.Ik({skills:T.YO(T.Ik({name:T.Yj(),description:T.Yj().optional(),emoji:T.Yj().optional(),eligible:T.zM().optional(),disabled:T.zM().optional(),blockedByAllowlist:T.zM().optional(),source:T.Yj().optional(),bundled:T.zM().optional()}).passthrough())}).passthrough(),_=T.Ik({plugins:T.YO(T.Ik({id:T.Yj(),name:T.Yj(),status:T.Yj().optional(),toolNames:T.YO(T.Yj()).optional()}).passthrough()).optional(),descriptors:T.YO(T.Ik({}).passthrough()).optional()}).passthrough(),aa=T.Ik({exists:T.zM().optional(),valid:T.zM().optional(),hash:T.Yj().optional(),config:T.g1(T.Yj(),T.L5()).optional(),resolved:T.L5().optional()}).passthrough(),ab=T.Ik({}).passthrough();function ac(a,b,c){let d=b.safeParse(c);if(!d.success)throw new l.pz(`${a}: OpenClaw Gateway returned a malformed response.`,"malformed-response",{cause:d.error});return d.data}function ad(a,b){return ac(a,ab,b)}function ae(a){(a?.latestVersion||a?.error)&&(af={...a})}let af=null;function ag(a){let b=ac("models.list",Z,a);return{...b,models:b.models.map(a=>{let b=(0,n.yK)(a.id),c=(0,n.yK)(a.provider),d=(0,n.yK)(a.key)??(c&&b?`${c}/${b}`:b),e=Array.isArray(a.input)?a.input.filter(a=>"string"==typeof a).join(",")||"text":(0,n.yK)(a.input)??"text",f=Array.isArray(a.tags)?a.tags.filter(a=>"string"==typeof a):[];return!0!==a.default&&!0!==a.isDefault||f.includes("default")||f.push("default"),{key:d??(0,n.yK)(a.name)??"unknown",name:(0,n.yK)(a.name)??d??b??"Unknown model",input:e,contextWindow:"number"==typeof a.contextWindow?a.contextWindow:null,local:"boolean"==typeof a.local?a.local:null,available:"boolean"==typeof a.available?a.available:null,tags:f,missing:!0===a.missing}})}}function ah(a,b){var c,d;let e=(0,n.LK)(a)?a:{},f=b?ag(b).models:[],g=f.map(a=>a.key).filter(Boolean),h=(c=e,d=f,(0,n.yK)(c.defaultModel)??(0,n.yK)(c.default)??d.find(a=>a.tags.some(a=>"default"===a.toLowerCase()))?.key??null),i=(0,n.yK)(e.resolvedDefault)??(0,n.yK)(e.resolvedDefaultModel)??h,j=Array.isArray(e.providers)?e.providers.filter(a=>(0,n.LK)(a)):[];return{defaultModel:h,resolvedDefault:i,allowed:g,auth:{providers:j.map(a=>{let b=ai(a.profiles);return{provider:(0,n.yK)(a.provider)??void 0,effective:{kind:b>0?"ok":(0,n.yK)(a.status)??(0,n.yK)(a.kind)??void 0,detail:(0,n.yK)(a.detail)??void 0},profiles:{count:Array.isArray(a.profiles)?b:void 0}}}),missingProvidersInUse:Array.isArray(e.missingProvidersInUse)?e.missingProvidersInUse.filter(a=>"string"==typeof a):[],unusableProfiles:Array.isArray(e.unusableProfiles)?e.unusableProfiles:[],oauth:{providers:j.map(a=>({provider:(0,n.yK)(a.provider)??void 0,status:ai(a.profiles)>0?"ok":(0,n.yK)(a.status)??void 0,profiles:Array.isArray(a.profiles)?a.profiles:void 0,effectiveProfiles:Array.isArray(a.effectiveProfiles)?a.effectiveProfiles:void 0}))}}}}function ai(a){return Array.isArray(a)?a.filter(a=>(function(a){if(!(0,n.LK)(a))return!1;let b=(0,n.yK)(a.status)?.toLowerCase();return!b||!["expired","missing","invalid","error","disabled","revoked"].includes(b)})(a)).length:0}function aj(a){let b=ac("plugins.uiDescriptors",_,a);return{plugins:(b.plugins??b.descriptors??[]).map(a=>({...a,id:(0,n.yK)(a.id)??(0,n.yK)(a.pluginId)??(0,n.yK)(a.name)??"unknown",name:(0,n.yK)(a.name)??(0,n.yK)(a.label)??(0,n.yK)(a.id)??"Unknown plugin",status:(0,n.yK)(a.status)??void 0,toolNames:Array.isArray(a.toolNames)?a.toolNames.filter(a=>"string"==typeof a):void 0}))}}function ak(){return(0,l.Lo)()}class al{constructor(a={}){this.options=a,this.fallbackCounts={},this.lastNativeFailure=null,this.fallback=a.fallback??new d.p,this.connection=new O(this.fallback,a)}close(a="closed"){this.connection.close(a)}getDiagnostics(){var a,b,c;let d=this.connection.getDiagnostics(),e=this.options.forceCli||C(),f=Object.values(this.fallbackCounts).reduce((a,b)=>Number.isFinite(b)&&b>0?a+b:a,0),g=(0,l.Lo)(),h=(a=g,b=d.lastConnectedAt,0!==a.length&&(!b||a.some(a=>ao(a.at,b))))?f:0,i=ao(this.lastNativeFailure?.at??null,d.lastConnectedAt)?this.lastNativeFailure:null,j=this.lastNativeFailure?.issue||(0,l.mW)(d.lastNativeError),k=i?.issue||(0,l.mW)(d.lastNativeError),n=(c={forceCli:e,connectionState:d.connectionState,fallbackTotal:h,lastNativeError:k}).forceCli?"cli-forced":"error"===c.connectionState?"unreachable":c.fallbackTotal>0?"fallback-active":"closed"===c.connectionState||c.lastNativeError?"degraded":"native-ws";return{mode:e?"cli":"native-ws",gatewayMode:n,statusLabel:function(a){switch(a){case"native-ws":return"Native Gateway: OK";case"cli-forced":return"CLI fallback forced";case"fallback-active":return"CLI fallback used";case"unreachable":return"Native Gateway: Unreachable";default:return"Native Gateway: Degraded"}}(n),recovery:function(a,b){if("native-ws"===a)return null;if(b)return b;switch(a){case"cli-forced":return"Unset CLI-forced Gateway mode and restart AgentOS to use native WebSocket transport.";case"fallback-active":return"Inspect recent fallback diagnostics, update OpenClaw for protocol or method gaps, repair token/device access for auth failures, then restart the Gateway if needed.";case"unreachable":return"Start or restart the OpenClaw Gateway, verify the endpoint and token/password, then retry the native operation.";default:return"Inspect Gateway diagnostics, check token/device access, update OpenClaw for compatibility gaps, then restart the Gateway before retrying."}}(n,i?.recovery??null),connectionState:e?"cli-forced":d.connectionState,protocolVersion:d.protocolVersion,protocolRange:m.aj,fallbackCounts:{...this.fallbackCounts},fallbackTotal:f,recentFallbackDiagnostics:g,lastNativeError:j||null,lastNativeFailureAt:this.lastNativeFailure?.at??null,lastConnectedAt:d.lastConnectedAt,lastDisconnectedAt:d.lastDisconnectedAt}}recordNativeFailure(a,b){let c=(0,l.$g)(b);this.lastNativeFailure={at:new Date().toISOString(),operation:a,issue:(0,l.mW)(c.message),kind:c.kind,recovery:(0,l.fu)(c)}}clearNativeFailure(a){this.lastNativeFailure?.operation===a&&(this.lastNativeFailure=null)}recordGatewayFallback(a,b){this.recordNativeFailure(a,b),this.fallbackCounts[a]=(this.fallbackCounts[a]??0)+1,(0,l.Rd)(a,b)}cliFallbackDisabledError(a,b){this.recordNativeFailure(a,b);let c=(0,l.$g)(b);return new l.pz(`${c.message} Gateway-native operation failed; CLI fallback disabled for this operation. Recovery: ${(0,l.fu)(c)}`,c.kind,{cause:b})}getHealth(a={}){return this.gatewayFirst("health",{},a,a=>(0,n.LK)(a)?a:{},()=>this.fallback.getHealth(a))}getStatus(a={}){return this.options.forceCli||C()?this.fallback.getStatus(a):this.callNative("status",{},a).then(a=>{let b=ac("status",V,a);return((0,l.Z6)("status"),this.clearNativeFailure("status"),b.update?.registry?.latestVersion||b.update?.registry?.error)?(ae(b.update?.registry),b):function(a){let b=a.update??{},c=(void 0)??{},d=function(a){var b;let c=((b=a).runtimeVersion||b.overview?.version||b.version||"").trim().replace(/^v/i,"")||null,d=af?.latestVersion?.trim();if(af){if(c&&d&&(0,U.QK)(c,d)>0){af=null;return}return af??void 0}}(a),e=b.registry??c.registry??d??void 0;if(e&&ae(e),!e)return a;let f={...c,...b};return e&&(f.registry=e),{...a,update:f}}(b)}).catch(b=>{if(this.options.onNativeFailure?.(b,"status"),!F(b,"status",E("status",a)))throw this.cliFallbackDisabledError("status",b);return this.recordGatewayFallback("status",b),this.fallback.getStatus(a)})}getUpdateStatus(a={}){return this.options.forceCli||C()?this.fallback.getUpdateStatus(a):this.callNative("update.status",{},a).then(async b=>{var c,d;let e=ad("update.status",b);return(function(a){let b=[];function c(a){!(0,n.LK)(a)||b.includes(a)||b.push(a)}return c(a),c(a?.update),c(a?.availability),c(ap(a?.update)?.registry),c(a?.registry),c(a?.result),c(ap(a?.result)?.update),c(ap(ap(a?.result)?.update)?.registry),c(ap(a?.result)?.availability),c(a?.sentinel),c(ap(a?.sentinel)?.stats),b})(e).some(a=>"boolean"==typeof a.updateAvailable||"string"==typeof a.latestVersion||"string"==typeof a.targetVersion||"string"==typeof a.availableVersion||"string"==typeof a.recommendedVersion||"boolean"==typeof a.available||"boolean"==typeof a.hasRegistryUpdate)?((0,l.Z6)("update.status"),this.clearNativeFailure("update.status"),e):(this.recordGatewayFallback("update.status",new l.pz("OpenClaw Gateway update.status did not include update availability details.","malformed-response")),c=e,d=await this.fallback.getUpdateStatus(a),{...c,...d})}).catch(b=>{if(this.options.onNativeFailure?.(b,"update.status"),!F(b,"update.status",E("update.status",a)))throw this.cliFallbackDisabledError("update.status",b);return this.recordGatewayFallback("update.status",b),this.fallback.getUpdateStatus(a)})}getGatewayStatus(a={}){return this.gatewayFirst("health",{},a,a=>{let b=(0,n.LK)(a)?a:{};return{service:{label:!1===b.ok?"Runtime degraded":"Runtime ready",loaded:!1!==b.ok},rpc:{ok:!1!==b.ok}}},()=>this.fallback.getGatewayStatus(a))}async getModelStatus(a={}){if(this.options.forceCli||C())return this.fallback.getModelStatus(a);let[b,c]=await Promise.allSettled([this.callNative("models.authStatus",{},a),this.callNative("models.list",{view:"configured"},a)]);for(let d of[{method:"models.authStatus",result:b},{method:"models.list",result:c}].filter(a=>"rejected"===a.result.status))if(this.options.onNativeFailure?.(d.result.reason,d.method),!F(d.result.reason,d.method,E(d.method,a)))throw this.cliFallbackDisabledError(d.method,d.result.reason);if("rejected"===b.status&&"rejected"===c.status){let c=b.reason;return this.recordGatewayFallback("models.authStatus",c),this.fallback.getModelStatus(a)}return(0,l.Z6)("models.authStatus"),(0,l.Z6)("models.list"),this.clearNativeFailure("models.authStatus"),this.clearNativeFailure("models.list"),ah("fulfilled"===b.status?b.value:null,"fulfilled"===c.status?c.value:null)}async getAgentModelStatus(a,b={}){if(this.options.forceCli||C())return this.fallback.getAgentModelStatus(a,b);let c=a.agentId,[d,e]=await Promise.allSettled([this.callNative("models.authStatus",{agentId:c},b),this.callNative("models.list",{view:"configured"},b)]);for(let a of[{method:"models.authStatus",result:d},{method:"models.list",result:e}].filter(a=>"rejected"===a.result.status))if(this.options.onNativeFailure?.(a.result.reason,a.method),!F(a.result.reason,a.method,E(a.method,b)))throw this.cliFallbackDisabledError(a.method,a.result.reason);if("rejected"===d.status&&"rejected"===e.status){let c=d.reason;return this.recordGatewayFallback("models.authStatus",c),this.fallback.getAgentModelStatus(a,b)}(0,l.Z6)("models.authStatus"),(0,l.Z6)("models.list"),this.clearNativeFailure("models.authStatus"),this.clearNativeFailure("models.list");let f="fulfilled"===d.status?d.value:null,g=ah(f,"fulfilled"===e.status?e.value:null);return(0,n.LK)(f)&&(g.agentDir=(0,n.yK)(f.agentDir)??g.agentDir),g}setModelAuthOrder(a,b={}){return this.gatewayFirstCompatible("modelAuthOrder",{provider:a.provider,agentId:a.agentId,profileIds:a.profileIds},b,n.hz,()=>this.fallback.setModelAuthOrder(a,b))}listAgents(a={}){return this.gatewayFirst("agents.list",{},a,a=>ac("agents.list",W,a),()=>this.fallback.listAgents(a))}listSessions(a={},b={}){return this.gatewayFirst("sessions.list",{...a},b,a=>ac("sessions.list",X,a),()=>this.fallback.listSessions(a,b))}describeSession(a={},b={}){return this.gatewayFirst("sessions.describe",{...Q(a),includeMessages:a.includeMessages,limit:a.limit},b,a=>ad("sessions.describe",a),()=>this.fallback.describeSession(a,b))}getSessionHistory(a={},b={}){return this.gatewayFirstSessionHistory(a,b)}exportSession(a={},b={}){return this.gatewayFirstSessionExport(a,b)}listTasks(a={},b={}){return this.gatewayFirst("tasks.list",{...a},b,a=>ad("tasks.list",a),()=>this.fallback.listTasks(a,b))}getTask(a,b={}){return this.gatewayFirst("tasks.get",{...a},b,a=>ad("tasks.get",a),()=>this.fallback.getTask(a,b))}assignTask(a,b={}){let c={...E("tasks.assign",b),allowCliFallback:!1,allowMutationFallbackOnUnsupported:!1};return this.gatewayFirst("tasks.assign",{...a,reason:a.reason??void 0},b,a=>ad("tasks.assign",a),()=>this.fallback.assignTask(a,b),c)}cancelTask(a,b={}){return this.gatewayFirst("tasks.cancel",{taskId:a.taskId,reason:a.reason??void 0},b,a=>ad("tasks.cancel",a),()=>this.fallback.cancelTask(a,b))}listArtifacts(a={},b={}){return this.gatewayFirst("artifacts.list",function(a={}){return{taskId:a.taskId?.trim()||void 0,runId:a.runId?.trim()||void 0,sessionKey:a.sessionKey?.trim()||a.sessionId?.trim()||void 0}}(a),b,a=>ad("artifacts.list",a),()=>this.fallback.listArtifacts(a,b))}getArtifact(a,b={}){return this.gatewayFirst("artifacts.get",{...a},b,a=>ad("artifacts.get",a),()=>this.fallback.getArtifact(a,b))}putArtifact(a,b={}){let c={...E("artifacts.put",b),allowCliFallback:!1,allowMutationFallbackOnUnsupported:!1};return this.gatewayFirst("artifacts.put",{...a},b,a=>ad("artifacts.put",a),()=>this.fallback.putArtifact(a,b),c)}deleteArtifact(a,b={}){let c={...E("artifacts.delete",b),allowCliFallback:!1,allowMutationFallbackOnUnsupported:!1};return this.gatewayFirst("artifacts.delete",{artifactId:a.artifactId,reason:a.reason??void 0},b,a=>ad("artifacts.delete",a),()=>this.fallback.deleteArtifact(a,b),c)}async getRuntimeSnapshot(a={},b={}){if(this.options.forceCli||C())return this.fallback.getRuntimeSnapshot(a,b);let c=!1!==a.includeSessions,d=!1!==a.includeTasks,e=!1!==a.includeArtifacts,f={taskId:a.taskId,runId:a.runId,sessionKey:a.sessionKey,sessionId:a.sessionId},g=e&&function(a={}){return!!(a.taskId?.trim()||a.runId?.trim()||a.sessionKey?.trim()||a.sessionId?.trim())}(f),h=await Promise.allSettled([c?this.listSessions({limit:a.limit,agentId:a.agentId},b):Promise.resolve(null),d?this.listTasks({limit:a.limit,agentId:a.agentId,workspace:a.workspace},b):Promise.resolve(null),g?this.listArtifacts(f,b):Promise.resolve(null)]),i=h.filter((a,b)=>[c,d,g][b]),j=i.filter(a=>"rejected"===a.status);if(i.length>0&&j.length===i.length)throw j[0]?.reason??Error("OpenClaw Gateway runtime snapshot failed.");let[k,l,m]=h,n={sessions:"fulfilled"===k.status?k.value?.sessions??[]:[],tasks:"fulfilled"===l.status?l.value?.tasks??[]:[],artifacts:"fulfilled"===m.status?m.value?.artifacts??[]:[]};return j.length>0&&(n.metadata={runtimeSnapshot:{partial:!0,errors:j.map(a=>{var b;return(b=a.reason)instanceof Error?b.message:String(b||"Unknown OpenClaw Gateway snapshot error.")})}}),n}getToolsCatalog(a={},b={}){return this.gatewayFirst("tools.catalog",{...a},b,a=>ad("tools.catalog",a),()=>this.fallback.getToolsCatalog(a,b))}getEffectiveTools(a={},b={}){return this.gatewayFirst("tools.effective",{...a},b,a=>ad("tools.effective",a),()=>this.fallback.getEffectiveTools(a,b))}invokeTool(a,b={}){return this.gatewayFirst("tools.invoke",{...a},b,a=>ad("tools.invoke",a),()=>this.fallback.invokeTool(a,b))}getChannelStatus(a={},b={}){return this.gatewayFirst("channels.status",{...a},b,a=>ac("channels.status",Y,a),()=>this.fallback.getChannelStatus(a,b))}getChannelLogs(a,b={}){return this.gatewayFirst("channels.logs",{channel:a.channel,lines:a.lines??void 0},b,a=>(0,n.LK)(a)?a:{},()=>this.fallback.getChannelLogs(a,b))}provisionChannelAccount(a,b={}){return this.gatewayFirstCompatible("channelProvisioning",{channel:a.channel,account:a.account?.trim()||void 0,accountId:a.account?.trim()||void 0,name:a.name?.trim()||void 0,token:a.token?.trim()||void 0,botToken:a.botToken?.trim()||void 0,webhookUrl:a.webhookUrl?.trim()||void 0},b,n.hz,()=>this.fallback.provisionChannelAccount(a,b))}removeChannelAccount(a,b={}){return this.gatewayFirstCompatible("channelRemoval",{channel:a.channel,account:a.account,accountId:a.account,delete:a.delete??void 0},b,n.hz,()=>this.fallback.removeChannelAccount(a,b))}setupGmailWebhook(a,b={}){return this.gatewayFirstCompatible("gmailProvisioning",{account:a.account,config:a.config??{}},b,n.hz,()=>this.fallback.setupGmailWebhook(a,b))}listSkills(a={}){return this.gatewayFirst("skills.status",{},a,b=>{let c=ac("skills.status",$,b);return a.eligible?{...c,skills:c.skills.filter(a=>!0===a.eligible)}:c},()=>this.fallback.listSkills(a))}listPlugins(a={}){return this.gatewayFirst("plugins.uiDescriptors",{},a,aj,()=>this.fallback.listPlugins(a))}listModels(a={},b={}){return this.gatewayFirst("models.list",{view:a.all?"all":"configured"},b,b=>{let c=ag(b);return a.provider?{...c,models:c.models.filter(b=>b.key.split("/",1)[0]===a.provider)}:c},()=>this.fallback.listModels(a,b))}scanModels(a={}){return this.fallback.scanModels(a)}probeGateway(a={}){return this.fallback.probeGateway(a)}controlGateway(a,b={}){return this.close(`gateway.${a}`),this.fallback.controlGateway(a,b).finally(()=>{this.close(`gateway.${a}.completed`)})}approveDeviceAccess(a={},b={}){return!1===a.latest||a.requestId?this.gatewayFirstCompatible("deviceApproval",{requestId:a.requestId??void 0,scopes:a.scopes},b,a=>ad("device.pair.approve",a),()=>this.fallback.approveDeviceAccess(a,b)):this.gatewayFirstCompatible("devicePairList",{},b,a=>ad("device.pair.list",a),()=>this.fallback.call("device.pair.list",{},b)).then(c=>{let d=(0,A.$k)(c);if(!d)throw new l.pz("No pending OpenClaw device access request found.","unknown");return this.approveDeviceAccess({...a,latest:!1,requestId:d},b)})}async call(a,b={},c={}){if(this.options.forceCli||C())return this.fallback.call(a,b,c);try{let d=await this.callNative(a,b,c);return(0,l.Z6)(a),this.clearNativeFailure(a),d}catch(e){this.options.onNativeFailure?.(e,a);let d=E(a,c);if(!F(e,a,d))throw this.cliFallbackDisabledError(a,e);return this.recordGatewayFallback(a,e),this.fallback.call(a,b,c)}}getConfig(a,b={}){return this.gatewayFirst("config.get",{},b,b=>{let c=ac("config.get",aa,b),d=(0,n.LK)(c.config)?c.config:{},e=(0,n.LK)(c.resolved)?c.resolved:{},f=(0,n.e6)(d,a)??(0,n.e6)(e,a);return void 0===f?null:f},()=>this.fallback.getConfig(a,b))}getConfigSchema(a={}){return this.gatewayFirst("config.schema",{},a,a=>(0,n.LK)(a)?a:null,()=>this.fallback.getConfigSchema?.(a)??Promise.resolve(null))}lookupConfigSchema(a,b={}){return this.gatewayFirst("config.schema.lookup",{path:a.path},b,a=>(0,n.LK)(a)?a:null,()=>this.fallback.lookupConfigSchema?.(a,b)??Promise.resolve(null))}async hasConfig(a,b={}){return null!=await this.getConfig(a,b)}setConfig(a,b,c={}){return this.gatewayConfigMutationFirst("config.set",a,b,c,c=>(0,n.r0)(c,a,b),()=>this.fallback.setConfig(a,b,c))}unsetConfig(a,b={}){return this.gatewayConfigMutationFirst("config.unset",a,void 0,b,b=>(0,n.WW)(b,a),()=>this.fallback.unsetConfig(a,b))}addAgent(a,b={}){if(a.agentDir?.trim())return this.fallback.addAgent(a,b);let c={name:a.name?.trim()||a.id,workspace:a.workspace};return a.model&&(c.model=a.model),a.emoji&&(c.emoji=a.emoji),a.avatar&&(c.avatar=a.avatar),this.gatewayFirst("agents.create",c,b,n.hz,()=>this.fallback.addAgent(a,b))}updateAgent(a,b={}){let c={agentId:a.id};return void 0!==a.name&&null!==a.name&&a.name.trim()&&(c.name=a.name.trim()),void 0!==a.workspace&&null!==a.workspace&&a.workspace.trim()&&(c.workspace=a.workspace.trim()),void 0!==a.model&&(c.model=a.model?.trim()||null),void 0!==a.emoji&&(c.emoji=a.emoji?.trim()||""),void 0!==a.avatar&&(c.avatar=a.avatar?.trim()||""),this.gatewayFirst("agents.update",c,b,n.hz,()=>this.fallback.updateAgent?.(a,b)??Promise.resolve({stdout:JSON.stringify({ok:!0,fallback:"application-config"}),stderr:""}))}setAgentIdentity(a,b={}){return this.gatewayFirstCompatible("agentIdentity",{agentId:a.agentId,agent:a.agentId,workspace:a.workspace,identityFile:a.identityFile,name:a.name?.trim()||void 0,emoji:a.emoji?.trim()||void 0,theme:a.theme?.trim()||void 0,avatar:a.avatar?.trim()||void 0},b,n.hz,()=>this.fallback.setAgentIdentity(a,b))}deleteAgent(a,b={}){return this.gatewayFirst("agents.delete",{agentId:a},b,n.hz,()=>this.fallback.deleteAgent(a,b))}provisionAutomation(a,b={}){return this.gatewayFirstCompatible("automationProvisioning",{name:a.name,description:a.description||a.name,agentId:a.agentId,agent:a.agentId,message:a.message,thinking:a.thinking||"medium",timeoutSeconds:a.timeoutSeconds??120,schedule:a.schedule,announce:a.announce??void 0},b,n.hz,()=>this.fallback.provisionAutomation(a,b))}async runAgentTurn(a,b={}){if(this.options.forceCli||C())return this.fallback.runAgentTurn(a,b);try{let c=await this.runAgentTurnNative(a,b);return(0,l.Z6)("chat.send"),(0,l.Z6)("sessions.send"),this.clearNativeFailure("chat.send"),this.clearNativeFailure("sessions.send"),c}catch(d){this.options.onNativeFailure?.(d,"chat.send");let c=d instanceof l.jl?d.method:"chat.send";if(!F(d,c,{safety:"mutation"}))throw this.cliFallbackDisabledError(c,d);return this.recordGatewayFallback("chat.send",d),this.fallback.runAgentTurn(a,b)}}abortAgentTurn(a,b={}){let c=a.sessionId||a.agentId?P(a.agentId,a.sessionId):void 0;return this.gatewayFirst("sessions.abort",{key:c,runId:a.runId??void 0},b,a=>a,()=>this.gatewayFirst("chat.abort",{sessionKey:c,runId:a.runId??void 0},b,a=>a,()=>this.fallback.abortAgentTurn?.(a,b)??this.fallback.call("sessions.abort",{key:c,runId:a.runId??void 0},b)))}async steerSession(a,b={}){if(this.options.forceCli||b.forceCli||C())throw new l.pz("Native OpenClaw Gateway is required for sessions.steer.","unsupported");try{let c,d,e=await this.callNative("sessions.steer",(c=a.key?.trim(),d=a.sessionId?.trim(),{key:c||void 0,sessionId:c?void 0:d||void 0,message:a.message}),b,{safety:"mutation",timeoutMs:b.timeoutMs,allowCliFallback:!1,allowMutationFallbackOnUnsupported:!1});return this.clearNativeFailure("sessions.steer"),ad("sessions.steer",e)}catch(a){throw this.options.onNativeFailure?.(a,"sessions.steer"),this.cliFallbackDisabledError("sessions.steer",a)}}async injectChat(a,b={}){if(this.options.forceCli||b.forceCli||C())throw new l.pz("Native OpenClaw Gateway is required for chat.inject.","unsupported");try{let c,d,e=await this.callNative("chat.inject",(c=a.sessionKey?.trim(),d=a.sessionId?.trim(),{sessionKey:c||void 0,sessionId:c?void 0:d||void 0,message:a.message}),b,{safety:"mutation",timeoutMs:b.timeoutMs,allowCliFallback:!1,allowMutationFallbackOnUnsupported:!1});return this.clearNativeFailure("chat.inject"),ad("chat.inject",e)}catch(a){throw this.options.onNativeFailure?.(a,"chat.inject"),this.cliFallbackDisabledError("chat.inject",a)}}async streamAgentTurn(a,b={},c={}){if(c.forceCli||this.options.forceCli||C())return this.fallback.streamAgentTurn(a,b,c);let d=P(a.agentId,a.sessionId),e=null,f=null,g="",h=()=>{},i=new Promise(a=>{h=a});try{e=await this.subscribeNativeEvents({subscribeSessions:!0,sessionKeys:[d]},{onEvent:a=>{let c=function(a,b,c){let d=(0,n.LK)(a.payload)?a.payload:{},e=(0,n.yK)(d.sessionKey)??(0,n.yK)(d.key)??(0,n.yK)(d.sessionId),f=(0,n.yK)(d.runId)??(0,n.yK)(d.run)??(0,n.yK)(d.clientRunId),g=b.includes(":explicit:")?b.split(":explicit:").at(1)??null:null;if(e&&e!==b&&e!==g||c&&f&&f!==c||!e&&!f)return null;let h=function(a){if(!(0,n.LK)(a))return null;let b=(0,n.LK)(a.author)?a.author:null;return(0,n.yK)(a.role)??(0,n.yK)(a.type)??(0,n.yK)(a.speaker)??(0,n.yK)(b?.role)??(0,n.yK)(b?.type)??(0,n.yK)(b?.name)}(d.message)??(0,n.yK)(d.role)??(0,n.yK)(d.authorRole)??(0,n.yK)(d.speaker);if(h&&/^(user|operator|system)$/i.test(h))return null;let i=(0,n.yK)(d.state)??(0,n.yK)(d.status)??(0,n.yK)(a.event),j=function a(b){return"string"==typeof b&&b.trim()?b.trim():Array.isArray(b)?b.flatMap(b=>{if(!(0,n.LK)(b))return[];if(("text"===b.type||"output_text"===b.type)&&"string"==typeof b.text&&b.text.trim())return[b.text.trim()];if("toolResult"===b.type){let c=a(b.content)??(0,n.yK)(b.text);return c?[c]:[]}return[]}).join("\n\n").trim()||null:(0,n.LK)(b)?(0,n.yK)(b.text)??(0,n.yK)(b.content)??a(b.content)??(0,n.yK)(b.summary)??(0,n.yK)(b.message):null}(d.message)??(0,n.yK)(d.text)??(0,n.yK)(d.summary)??(0,n.yK)(d.detail),k=/final|complete|completed|aborted|abort|error|failed|stalled/i.test(i??""),l=/error|failed|stalled/i.test(i??"");return!k||j||l?{text:j,done:k,payload:{runId:f??c??void 0,status:l?"stalled":k?"completed":"running",summary:j??"OpenClaw Gateway stream failed.",payloads:j?[{text:j,mediaUrl:null}]:[]}}:null}(a,d,f);c&&(c.text&&c.text!==g&&(g=c.text,b.onStdout?.(`${JSON.stringify({type:"assistant",text:c.text})}
|
|
4
|
+
${c.stderr||""}`.trim();if(!/\bopenclaw\b/i.test(f)&&!/\b\d+(?:\.\d+)+\b/.test(f))throw Error("OpenClaw binary did not return a recognizable version.")}async function r(){let a="win32"===process.platform?"where":"which",b="win32"===process.platform?["openclaw.exe"]:["openclaw"],c=(0,j.spawnSync)(a,b,{encoding:"utf8"});if(0!==c.status||c.error)throw Error("Could not resolve openclaw from PATH.");let d=c.stdout.split(/\r?\n/).map(a=>a.trim()).find(Boolean)||"";if(!d)throw Error("Could not resolve openclaw from PATH.");return d}function s(a){return a&&"auto"!==a.mode?"local-prefix"===a.mode?(0,k.lz)():a.path:null}function t(a,b){return a?{...a,resolvedPath:"auto"===a.mode?b:a.resolvedPath||a.path||b}:{...n(),resolvedPath:b}}},17929:(a,b,c)=>{"use strict";c.d(b,{FZ:()=>function a(b){return"string"==typeof b?o(b):Array.isArray(b)?b.some(b=>a(b)):!!h(b)&&Object.values(b).some(b=>a(b))},LK:()=>h,Pu:()=>k,WW:()=>m,e6:()=>i,g:()=>g,hz:()=>n,nf:()=>j,o0:()=>o,r0:()=>l,r_:()=>f,yK:()=>p});var d=c(24117),e=c(98717);function f(){return`agentos:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`}function g(a){return"string"==typeof a?a.trim():""}function h(a){return!!a&&"object"==typeof a&&!Array.isArray(a)}function i(a,b){if(!b.trim())return a;let c=a;for(let a of j(b)){if(Array.isArray(c)&&"number"==typeof a){c=c[a];continue}if(!h(c)||"string"!=typeof a)return;c=c[a]}return c}function j(a){let b,c=[],d=/([^[.\]]+)|\[(\d+)\]/g;for(;b=d.exec(a);)b[1]?c.push(b[1]):b[2]&&c.push(Number(b[2]));return c}function k(a){return JSON.parse(JSON.stringify(a))}function l(a,b,c){let d=j(b);if(0===d.length)throw new e.pz("Config path is required.","unknown");let f=a;for(let a=0;a<d.length-1;a+=1){let b=d[a],c=d[a+1];if("string"!=typeof b)throw new e.pz("Array root config paths are not supported.","unknown");let g=f[b];if(h(g)||Array.isArray(g)){f=g;continue}let i="number"==typeof c?[]:{};f[b]=i,f=i}let g=d[d.length-1];if("number"==typeof g){if(!Array.isArray(f))throw new e.pz("Config path points to an array index on a non-array parent.","unknown");f[g]=c;return}f[g]=c}function m(a,b){let c=j(b);if(0===c.length)throw new e.pz("Config path is required.","unknown");let d=a;for(let a=0;a<c.length-1;a+=1){let b=c[a];if(void 0===(d=Array.isArray(d)&&"number"==typeof b||h(d)&&"string"==typeof b?d[b]:void 0))return}let f=c[c.length-1];Array.isArray(d)&&"number"==typeof f?d.splice(f,1):h(d)&&"string"==typeof f&&delete d[f]}function n(a,b){return{stdout:JSON.stringify(a??{}),stderr:"",...b?{metadata:b}:{}}}function o(a){return a===d.K$}function p(a){return"string"==typeof a&&a.trim()?a.trim():null}},21916:(a,b,c)=>{"use strict";c.d(b,{Am:()=>w,Lp:()=>q,Nk:()=>u,OZ:()=>h,QK:()=>s,QL:()=>i,YO:()=>p,iP:()=>g,mB:()=>r,nn:()=>v,xH:()=>e,yv:()=>f});var d=c(11782);function e(a,b,c){return"in_progress"===a||b?.endsWith(":main")&&"number"==typeof c&&c<36e5?"running":"completed"===a||"done"===a?"completed":"failed"===a||"error"===a?"stalled":"idle"}function f(a){return a.rpcOk?a.activeRuntime?.status==="running"||a.activeRuntime?.status==="queued"?"engaged":a.heartbeatEnabled?"monitoring":a.lastActiveAt?"ready":"standby":"offline"}function g(a){if(a.runtime)return a.runtime.taskId?"running"===a.runtime.status||"queued"===a.runtime.status?`Tracking task ${a.runtime.taskId.slice(0,8)}`:"completed"===a.runtime.status?`Recent task ${a.runtime.taskId.slice(0,8)} completed`:"cancelled"===a.runtime.status?`Recent task ${a.runtime.taskId.slice(0,8)} cancelled`:"stalled"===a.runtime.status?`Recent task ${a.runtime.taskId.slice(0,8)} waiting for output`:`Recent task ${a.runtime.taskId.slice(0,8)}`:"running"===a.runtime.status||"queued"===a.runtime.status?"Maintaining main session context":"Main session recently updated";return a.heartbeatEvery?`Heartbeat on ${a.heartbeatEvery}`:"standby"===a.status?"Waiting for assignment":"Ready for next turn"}function h(a,b){let c=b.filter(b=>a.includes(b.id));return c.some(a=>"engaged"===a.status)?"engaged":c.some(a=>"monitoring"===a.status)?"monitoring":c.some(a=>"ready"===a.status)?"ready":c.some(a=>"offline"===a.status)?"offline":"standby"}function i(a,b){var c,e,f,g,h;let i=a.filter(a=>{var b;return!1!==(b=a).available&&!b.missing}),p=w([...a.map(a=>{var b;return b=a.key,(0,d.jw)(b)?"openai-codex":b.split("/")[0]||"unknown"}),...(b?.auth?.providers??[]).map(a=>a?.provider).filter(x),...(b?.auth?.oauth?.providers??[]).map(a=>a?.provider).filter(x)].filter(x)),q=new Map((b?.auth?.providers??[]).filter(a=>x(a?.provider)).map(a=>[a.provider,a])),r=new Map((b?.auth?.oauth?.providers??[]).filter(a=>x(a?.provider)).map(a=>[a.provider,a])),s=u(b?.resolvedDefault??void 0),t=u(b?.defaultModel??void 0),v=s??t,y=v?n(v):null,z=!!(v&&i.some(a=>a.key===v)&&(c=y,e=v,f=a,g=q,h=r,c&&("ollama"===c?f.some(a=>l(c,a.key)&&!0===a.local):m(c,e).some(a=>(function(a,b,c){if("openai"===a)return j(b.get(a));if("openai-codex"===a)return k(b.get(a)??b.get("openai"),c.get(a)??c.get("openai"));let d=b.get(a),e=c.get(a);return(d?.profiles?.count??0)>0||e?.status==="ok"})(a,g,h))))),A=z?v:i[0]?.key??null,B=p.map(b=>{var c;let d,e=a.filter(a=>l(b,a.key)),f=e.some(a=>!0!==a.local),g="ollama"!==b&&f,h=q.get(b),i=r.get(b);h?.effective?.kind?.trim().toLowerCase();let m="ollama"===b?e.some(a=>a.local):"openai"===b?j(h):"openai-codex"===b?k(h??q.get("openai"),i??r.get("openai")):(h?.profiles?.count??0)>0||i?.status==="ok",n=null;return"openai"!==b&&(i?.status==="ok"||"openai-codex"===b&&r.get("openai")?.status==="ok")?n="OAuth connected":h&&(h.profiles?.count??0)>0&&("openai"!==b||j(h))?n=`${h?.profiles?.count} auth profile${h?.profiles?.count===1?"":"s"}`:"ollama"===b&&m?n="Local Ollama model detected.":"ollama"===b?n="Install or pull a local model to unlock this route.":f&&(n="openai-codex"===(d=(c=b).trim().toLowerCase())?"Use the ChatGPT account-based login flow in terminal to use this route.":"openrouter"===d||"openai"===d||"anthropic"===d||"xai"===d||"google"===d||"gemini"===d||"deepseek"===d||"mistral"===d?`Add your ${o(c)} API key in terminal to use this route.`:`Connect ${o(c)} auth in terminal to use this route.`),{provider:b,connected:m,canLogin:g,detail:n}}),C=(b?.auth?.missingProvidersInUse??[]).filter(x),D=new Set(C),E=b?.auth?.unusableProfiles?.length??0,F=[];0===i.length&&F.push("No available models were detected yet."),i.length>0&&!v&&F.push("Choose a default model to finish setup."),v&&!z&&(y&&D.has(y)?F.push(`Default model is set, but ${o(y)} auth is still missing.`):C.length>0?F.push(`Default model is set, but auth is still missing for: ${C.join(", ")}.`):F.push("The selected default model is not ready yet.")),C.length>0&&!v&&F.push(`Auth is still missing for: ${C.join(", ")}.`),E>0&&F.push("Some stored model auth profiles are not usable.");let G=function(a){let b=a.defaultProvider?m(a.defaultProvider,a.defaultModelId):[];if(b.some(b=>a.authProviders.some(a=>a.provider===b&&a.connected)))return null;for(let c of b){let b=a.authProviders.find(a=>a.provider===c&&!a.connected&&a.canLogin);if(b)return b.provider}let c=a.missingProvidersInUse.find(b=>a.authProviders.some(a=>a.provider===b&&!a.connected&&a.canLogin));return c||(a.authProviders.find(a=>!a.connected&&a.canLogin)?.provider??(a.providerIds.includes("openai-codex")||0===a.readyModels.length?"openai-codex":null))}({defaultProvider:y,defaultModelId:v??null,authProviders:B,missingProvidersInUse:C,providerIds:p,readyModels:i});return{ready:i.length>0&&z,defaultModel:t??null,resolvedDefaultModel:s??null,defaultModelReady:z,recommendedModelId:A??null,preferredLoginProvider:G,totalModelCount:a.length,availableModelCount:i.length,localModelCount:i.filter(a=>a.local).length,remoteModelCount:i.filter(a=>!0!==a.local).length,missingModelCount:a.filter(a=>a.missing||!1===a.available).length,authProviders:B,issues:w(F)}}function j(a){let b=a?.effective?.kind?.trim().toLowerCase(),c=a?.profiles?.token??0,d=a?.profiles?.apiKey??0,e=a?.profiles?.oauth??0,f=a?.profiles?.count??0;return!!(c+d>0||b&&["token","apikey","api-key"].includes(b)||"profiles"===b&&f>0&&0===e)}function k(a,b){let c=a?.effective?.kind?.trim().toLowerCase(),d=a?.profiles?.oauth??0,e=a?.syntheticAuth?.value?.trim();return!!(b?.status==="ok"||d>0||e||"oauth"===c||"synthetic"===c)}function l(a,b){let c=n(b)??"unknown";return"openai-codex"===a?"openai-codex"===c||"codex"===c||"openai"===c&&(0,d.jw)(b):c===a}function m(a,b){return"openai"===a&&b&&(0,d.jw)(b)?["openai","openai-codex"]:[a]}function n(a){let[b]=a.split("/",1);return b||null}function o(a){let b=a.trim().toLowerCase();return"openrouter"===b?"OpenRouter":"openai-codex"===b?"ChatGPT":"openai"===b?"OpenAI":"anthropic"===b?"Anthropic":"ollama"===b?"Ollama":"xai"===b?"xAI":"google"===b||"gemini"===b?"Gemini":"deepseek"===b?"DeepSeek":"mistral"===b?"Mistral":a.split("-").map(a=>a?a[0].toUpperCase()+a.slice(1):a).join(" ")}function p(a){return a.rpcOk||a.hasOpenClawSignal?!a.rpcOk||a.warningCount>0||a.runtimeIssueCount>0?"degraded":"healthy":"offline"}function q(a){return Object.entries(a).flatMap(([a,b])=>"rejected"!==b.status?[]:[`${a}: ${b.reason instanceof Error?b.reason.message:String(b.reason)}`])}function r(a){let b=u(a.legacyInfo);if(a.latestVersion&&a.currentVersion){let b=s(a.latestVersion,a.currentVersion);return b>0?`Update available: v${a.latestVersion} is ready. Current version: v${a.currentVersion}.`:0===b?`OpenClaw is up to date on v${a.currentVersion}.`:`Running v${a.currentVersion}. Registry currently reports v${a.latestVersion}.`}return a.latestVersion?`Latest available version: v${a.latestVersion}. Current version could not be determined.`:b||(a.updateError?`Update registry check failed: ${a.updateError}`:a.currentVersion?`Running v${a.currentVersion}. Update registry status is still loading.`:void 0)}function s(a,b){let c=t(a),d=t(b),e=Math.max(c.length,d.length);for(let a=0;a<e;a+=1){let b=c[a]??0,e=d[a]??0;if("number"==typeof b&&"number"==typeof e){if(b!==e)return b-e;continue}let f=String(b),g=String(e);if(f!==g)return f.localeCompare(g)}return 0}function t(a){return a.trim().replace(/^v/i,"").split(/[^0-9a-zA-Z]+/).filter(Boolean).map(a=>/^\d+$/.test(a)?Number(a):a.toLowerCase())}function u(a){return a?.trim()||void 0}function v(a){let b=u(a);if(b)return b.split(/\r?\n/,1)[0]?.trim()||b}function w(a){return Array.from(new Set(a))}function x(a){return!!a}},24117:(a,b,c)=>{"use strict";c.d(b,{$s:()=>m,Fj:()=>n,Ht:()=>p,JV:()=>h,K$:()=>r,N4:()=>d,OJ:()=>f,Rg:()=>l,Tv:()=>q,ZX:()=>j,aj:()=>k,dK:()=>e,lY:()=>i,mh:()=>g,vO:()=>o});let d="ws://127.0.0.1:18789",e=4e3,f=8e3,g=3e4,h="connect",i=3,j=4,k={min:3,max:4},l="gateway-client",m="backend",n="device-auth.json",o="device.json",p=Buffer.from("302a300506032b6570032100","hex"),q=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing","operator.talk.secrets"],r="__OPENCLAW_REDACTED__"},26516:(a,b,c)=>{"use strict";c.d(b,{gH:()=>al,aj:()=>m.aj,Lo:()=>ak,JG:()=>C});var d=c(38699),e=c(65493),f=c(80500),g=c(77598),h=c(51455),i=c(48161),j=c(76760),k=c(14805),l=c(98717),m=c(24117),n=c(17929),o=c(78446);async function p(a,b,c,d){if(d.readLocalConfigFile){let a=await q(b);if(a.fromConfigFile)return a}for(let d of b){let b=null;try{b=await a.getConfig(d,c)}catch(a){if((0,o.D)(a))return{value:"",invalidConfig:!0};continue}let e=(0,n.g)(b);if((0,n.o0)(e))throw new l.pz(`${d} is configured but OpenClaw returned a redacted secret. Set AGENTOS_OPENCLAW_GATEWAY_TOKEN/PASSWORD or OPENCLAW_GATEWAY_TOKEN/PASSWORD to enable native Gateway WS; using CLI fallback.`,"auth");if(e)return{value:e,invalidConfig:!1}}return{value:"",invalidConfig:!1}}async function q(a){let b,c=await w((b=process.env.OPENCLAW_CONFIG_PATH?.trim())?v(b):(0,j.join)(u(),"openclaw.json"));if(!c)return{value:"",invalidConfig:!1,fromConfigFile:!1};for(let b of a){let a=(0,n.g)((0,n.e6)(c,b));if((0,n.o0)(a))throw new l.pz(`${b} is configured but OpenClaw returned a redacted secret. Set AGENTOS_OPENCLAW_GATEWAY_TOKEN/PASSWORD or OPENCLAW_GATEWAY_TOKEN/PASSWORD to enable native Gateway WS; using CLI fallback.`,"auth");if(a)return{value:a,invalidConfig:!1,fromConfigFile:!0}}return{value:"",invalidConfig:!1,fromConfigFile:!0}}async function r(a,b,c,d){let e=s(c)?["gateway.auth.token","gateway.remote.token"]:["gateway.remote.token","gateway.auth.token"],f=s(c)?["gateway.auth.password","gateway.remote.password"]:["gateway.remote.password","gateway.auth.password"],g=b.token?.trim()||process.env.AGENTOS_OPENCLAW_GATEWAY_TOKEN?.trim()||process.env.OPENCLAW_GATEWAY_TOKEN?.trim();if(g)return{token:g,password:""};let h=b.password?.trim()||process.env.AGENTOS_OPENCLAW_GATEWAY_PASSWORD?.trim()||process.env.OPENCLAW_GATEWAY_PASSWORD?.trim();if(h)return{token:"",password:h};let i=await p(a,e,d,{readLocalConfigFile:!b.webSocketFactory});if(i.value||i.invalidConfig)return{token:i.value,password:""};let j=s(c)?await (0,k.lk)():null;if(j?.kind==="token")return{token:j.value,password:""};let l=await p(a,f,d,{readLocalConfigFile:!b.webSocketFactory}),m=l.invalidConfig?"":l.value;return m||j?.kind!=="password"?{token:"",password:m}:{token:"",password:j.value}}function s(a){try{let{hostname:b}=new URL(a);return"localhost"===b||"127.0.0.1"===b||"::1"===b||"[::1]"===b}catch{return!1}}async function t(a,b){if(!s(a)||b.webSocketFactory)return null;let c=u(),[d,e]=await Promise.all([w((0,j.join)(c,"identity",m.vO)),w((0,j.join)(c,"identity",m.Fj))]),f=(0,n.yK)(d?.deviceId),g=(0,n.yK)(d?.publicKeyPem),h=(0,n.yK)(d?.privateKeyPem),i=(0,n.yK)(e?.tokens?.operator?.token);return f&&g&&h&&i&&e?.deviceId===f?{deviceId:f,publicKeyPem:g,privateKeyPem:h,token:i}:null}function u(){let a=process.env.OPENCLAW_STATE_DIR?.trim();return a?v(a):(0,j.join)((0,i.homedir)(),".openclaw")}function v(a){return a.startsWith("~")?(0,j.join)((0,i.homedir)(),a.slice(1)):a}async function w(a){try{return JSON.parse(await (0,h.readFile)(a,"utf8"))}catch{return null}}function x(a){return a.toString("base64").replaceAll("+","-").replaceAll("/","_").replace(/=+$/g,"")}function y(a){return"string"==typeof a?a.trim().replaceAll("|",""):""}async function z(a,b,c,d,e){var f,h,i,j;let k,l,n=await t(c,b),o=b.scopes??m.Tv,p="",q="";try{let e=await r(a,b,c,d);p=e.token,q=e.password}catch(a){if(!n?.token)throw a}let s=!n||p||q?null:n,u=s?.token??p,v=u?{token:u}:q?{password:q}:void 0,w=Date.now(),z=process.platform,A=s&&e?{id:s.deviceId,publicKey:(j=s.publicKeyPem,(k=Buffer.from((0,g.createPublicKey)(j).export({type:"spki",format:"der"}))).length===m.Ht.length+32&&k.subarray(0,m.Ht.length).equals(m.Ht)?x(k.subarray(m.Ht.length)):x(k)),signature:(h=s.privateKeyPem,i=["v3",(f={deviceId:s.deviceId,clientId:b.clientName??m.Rg,clientMode:m.$s,role:b.role??"operator",scopes:o,signedAtMs:w,token:u??null,nonce:e,platform:z,deviceFamily:null}).deviceId,f.clientId,f.clientMode,f.role,f.scopes.join(","),String(f.signedAtMs),f.token??"",f.nonce,y(f.platform),y(f.deviceFamily)].join("|"),l=(0,g.createPrivateKey)(h),x((0,g.sign)(null,Buffer.from(i,"utf8"),l))),signedAt:w,nonce:e}:void 0;return{deviceAuth:s,params:{minProtocol:m.lY,maxProtocol:m.ZX,client:{id:b.clientName??m.Rg,version:b.clientVersion??"agentos",platform:z,mode:m.$s,instanceId:b.instanceId},role:b.role??"operator",scopes:o,caps:["tool-events"],...v?{auth:v}:{},...A?{device:A}:{},userAgent:"AgentOS",locale:"en"}}}var A=c(79102);function B(a){return a?.trim().toLowerCase()}function C(){let a=B(process.env.AGENTOS_OPENCLAW_GATEWAY_CLIENT??process.env.OPENCLAW_GATEWAY_CLIENT),b=B(process.env.AGENTOS_OPENCLAW_NATIVE_WS);return"cli"===a||"0"===b||"false"===b||"off"===b}function D(a,b){if("number"==typeof a&&Number.isFinite(a)&&a>0)return a;let c=Number(process.env.AGENTOS_OPENCLAW_NATIVE_WS_TIMEOUT_MS);return Number.isFinite(c)&&c>0?c:b&&/^(chat\.send|sessions\.send|sessions\.abort|chat\.abort)$/.test(b)?m.mh:b&&/(^|\.)(list|get|status|authStatus|schema|tail)$/.test(b)?m.OJ:m.dK}function E(a,b={}){var c;let d=(c=a,/(^|\.)(add|assign|cancel|configure|create|delete|invoke|put|remove|setup|update|set|unset|patch|apply|send|abort|resolve|restart|start|stop|logout)$/i.test(c))?"mutation":"read";return{safety:d,timeoutMs:b.timeoutMs,allowCliFallback:!0,allowReadCliFallbackOnNativeFailure:!1,allowMutationFallbackOnUnsupported:"mutation"===d}}function F(a,b,c){if(!1===c.allowCliFallback)return!1;let d=(0,l.$g)(a);return"mutation"!==c.safety?"unsupported"===d.kind||!0===c.allowReadCliFallbackOnNativeFailure:!!c.allowUnsafeMutationCliFallback||(!(a instanceof l.jl)||a.method===b)&&"unsupported"===d.kind&&!1!==c.allowMutationFallbackOnUnsupported}var G=c(99663);function H(a,b,c){if(a.addEventListener&&a.removeEventListener)return a.addEventListener(b,c),()=>a.removeEventListener?.(b,c);if(a.on){let d=(...a)=>{var d;"close"===b?c({code:"number"==typeof a[0]?a[0]:void 0,reason:"string"==typeof(d=a[1])?d:Buffer.isBuffer(d)?d.toString("utf8"):ArrayBuffer.isView(d)?Buffer.from(d.buffer,d.byteOffset,d.byteLength).toString("utf8"):void 0}):c(a[0])};return a.on(b,d),()=>{a.off?a.off(b,d):a.removeListener?.(b,d)}}let d=`on${b}`,e=a[d];return a[d]=c,()=>{a[d]===c&&(a[d]=e??null)}}function I(a){if(!a||"object"!=typeof a)return null;let b="number"==typeof a.code?a.code:null,c="string"==typeof a.reason?a.reason:"";return b?`${b}${c?`: ${c}`:""}`:c||null}function J(a){if("string"!=typeof a)if(a instanceof ArrayBuffer)a=new TextDecoder().decode(a);else{if(!ArrayBuffer.isView(a))return null;a=new TextDecoder().decode(a)}try{return JSON.parse(a)}catch(a){throw new l.As("OpenClaw Gateway returned invalid JSON.",{cause:a})}}function K(a){if(a?.aborted)throw new l.As("OpenClaw Gateway request was aborted.")}async function L(a,b,c){K(c),1!==a.readyState&&await new Promise((d,e)=>{let f=!1,g=[],h=a=>{if(!f){for(let a of(f=!0,globalThis.clearTimeout(i),g))a();c?.removeEventListener("abort",j),a()}},i=globalThis.setTimeout(()=>{h(()=>e(new l.As("Timed out connecting to OpenClaw Gateway.")))},b),j=()=>{h(()=>e(new l.As("OpenClaw Gateway request was aborted.")))};g.push(H(a,"open",()=>h(d)),H(a,"error",a=>h(()=>e(new l.As("Failed to connect to OpenClaw Gateway.",{cause:a})))),H(a,"close",a=>h(()=>e(new l.As(`OpenClaw Gateway closed before the connection was ready${I(a)?` (${I(a)})`:""}.`))))),c?.addEventListener("abort",j,{once:!0})})}async function M(a,b,c){return K(c),await new Promise((d,e)=>{let f=!1,g=[],h=a=>{if(!f){for(let a of(f=!0,globalThis.clearTimeout(i),g))a();c?.removeEventListener("abort",j),a()}},i=globalThis.setTimeout(()=>{h(()=>e(new l.As("OpenClaw Gateway connect challenge timed out.")))},b),j=()=>{h(()=>e(new l.As("OpenClaw Gateway request was aborted.")))};g.push(H(a,"message",a=>{try{let b=a?.data??a,c=J(b);if(c?.type!=="event"||"connect.challenge"!==c.event)return;let f=c.payload?.nonce;if("string"!=typeof f||!f.trim())return void h(()=>e(new l.As("OpenClaw Gateway connect challenge is missing a nonce.")));h(()=>d(f.trim()))}catch(a){h(()=>e(a))}}),H(a,"close",a=>h(()=>e(new l.As(`OpenClaw Gateway closed before the connect challenge${I(a)?` (${I(a)})`:""}.`))))),c?.addEventListener("abort",j,{once:!0})})}function N(a,b,c,d,e,f){K(f);let g=(0,n.r_)();return new Promise((h,i)=>{function j(){globalThis.clearTimeout(n),f?.removeEventListener("abort",m)}function k(a){b.delete(g),j(),i(a)}function m(){k(new l.As("OpenClaw Gateway request was aborted."))}let n=globalThis.setTimeout(()=>{k(new l.jl(`Timed out waiting for OpenClaw Gateway method "${c}".`,c,!0))},e);b.set(g,{resolve:a=>{j(),h(a)},reject:k,timer:n,cleanup:j,method:c,sent:!1}),f?.addEventListener("abort",m,{once:!0});try{a.send(JSON.stringify({type:"req",id:g,method:c,params:d}));let e=b.get(g);e&&(e.sent=!0)}catch(a){k(new l.jl(`Failed to send OpenClaw Gateway method "${c}".`,c,!1,{cause:a}))}})}class O{constructor(a,b){this.fallback=a,this.options=b,this.socket=null,this.pending=new Map,this.cleanupCallbacks=[],this.eventListeners=new Set,this.closeListeners=new Set,this.connectPromise=null,this.hello=null,this.state="idle",this.lastNativeError=null,this.lastConnectedAt=null,this.lastDisconnectedAt=null}getDiagnostics(){return{connectionState:this.state,protocolVersion:"number"==typeof this.hello?.protocol?this.hello.protocol:null,lastNativeError:this.lastNativeError,lastConnectedAt:this.lastConnectedAt,lastDisconnectedAt:this.lastDisconnectedAt}}async request(a,b,c,d){let e=await this.ensureConnected(c,d);(0,A.qi)(e,a);let f=this.socket;if(!f||1!==f.readyState)throw new l.As("OpenClaw Gateway connection is not ready.");return N(f,this.pending,a,b,d,c.signal)}async probe(a,b){return this.ensureConnected(a,b)}async subscribe(a,b,c,d){let e=await this.ensureConnected(c,d),f=(0,A.sq)(a,e);if(0===f.length&&!(0,A.pP)(e,"chat")&&!(0,A.pP)(e,"agent")&&!(0,A.pP)(e,"session.message")&&!(0,A.pP)(e,"session.tool")&&!(0,A.pP)(e,"sessions.changed")&&!(0,A.pP)(e,"task")&&!(0,A.pP)(e,"task.updated")&&!(0,A.pP)(e,"task.completed")&&!(0,A.pP)(e,"artifact")&&!(0,A.pP)(e,"artifact.updated")&&!(0,A.pP)(e,"exec.approval.requested")&&!(0,A.pP)(e,"plugin.approval.requested"))throw new l.As("OpenClaw Gateway does not advertise compatible runtime event streaming.",{kind:"unsupported"});let g=a=>{try{b.onEvent(a)}catch(a){b.onError?.(a)}},h=()=>b.onClose?.();this.eventListeners.add(g),this.closeListeners.add(h);try{for(let a of f)await this.request(a.method,a.params,c,d)}catch(a){throw this.eventListeners.delete(g),this.closeListeners.delete(h),a}let i=!1;return{close:()=>{!i&&(i=!0,this.eventListeners.delete(g),this.closeListeners.delete(h),f.length>0&&this.close("event subscription closed"))}}}close(a="closed"){this.disconnect(new l.As(`OpenClaw Gateway connection closed: ${a}.`),{notify:!0,closeSocket:!0,state:"closed"})}async ensureConnected(a,b){return(K(a.signal),this.socket?.readyState===1&&this.hello)?this.hello:(this.connectPromise||(this.connectPromise=this.connect(a,b).finally(()=>{this.connectPromise=null})),this.connectPromise)}async connect(a,b){var c;this.disconnect(new l.As("Replacing stale OpenClaw Gateway connection."),{notify:!1,closeSocket:!0,state:"connecting"});let d=(c=this.options.url,c?.trim()||process.env.AGENTOS_OPENCLAW_GATEWAY_URL?.trim()||process.env.OPENCLAW_GATEWAY_URL?.trim()||m.N4),e=function(a){let b=a??("u">typeof process&&"1"===process.env.AGENTOS_PACKAGE_RUNTIME&&"function"==typeof globalThis.WebSocket?globalThis.WebSocket:"u">typeof process&&process.versions?.node?G.kb:globalThis.WebSocket);if(!b)throw new l.As("Native WebSocket is not available in this runtime.");return b}(this.options.webSocketFactory),f=await z(this.fallback,this.options,d,a),g=new e(d);this.socket=g,this.state="connecting",this.lastNativeError=null,this.cleanupCallbacks=[H(g,"message",a=>this.handleMessage(a)),H(g,"error",a=>{let b=new l.As("OpenClaw Gateway WebSocket error.",{cause:a});this.lastNativeError=b.message,this.rejectPending(b)}),H(g,"close",a=>{let b=I(a);this.disconnect(new l.As(`OpenClaw Gateway connection closed${b?` (${b})`:""}.`),{notify:!0,closeSocket:!1,state:"closed"})})];try{await L(g,b,a.signal);let c=f.deviceAuth?(await z(this.fallback,this.options,d,a,await M(g,b,a.signal))).params:f.params,e=await N(g,this.pending,m.JV,c,b,a.signal);return(0,A.MK)(e),this.hello=e,this.state="connected",this.lastConnectedAt=new Date().toISOString(),this.lastNativeError=null,e}catch(a){throw this.lastNativeError=a instanceof Error?a.message:String(a),this.disconnect(a,{notify:!0,closeSocket:!0,state:"error"}),a}}handleMessage(a){try{let b=a?.data??a,c=J(b);if(!c)return;if("event"===c.type){for(let a of[...this.eventListeners])a(c);return}if("res"!==c.type||void 0===c.id)return;let d=String(c.id),e=this.pending.get(d);if(!e)return;if(this.pending.delete(d),globalThis.clearTimeout(e.timer),!1===c.ok)return void e.reject(new l.jl(function(a){if("string"==typeof a)return a;if(a&&"object"==typeof a){let b="string"==typeof a.message?a.message:null,c="string"==typeof a.detail?a.detail:null;return["string"==typeof a.code?a.code:null,b,c].filter(Boolean).join(": ")}return""}(c.error)||c.message||c.code||"OpenClaw Gateway request failed.",e.method,e.sent,{cause:c}));e.resolve(c.payload)}catch(a){this.lastNativeError=a instanceof Error?a.message:String(a),this.rejectPending(a)}}rejectPending(a){for(let[b,c]of this.pending)globalThis.clearTimeout(c.timer),this.pending.delete(b),c.reject(a)}disconnect(a,b){let c=!!this.socket,d=this.socket;for(let a of(this.socket=null,this.hello=null,this.state=b.state,"connecting"!==b.state&&c&&(this.lastDisconnectedAt=new Date().toISOString()),this.cleanupCallbacks))a();if(this.cleanupCallbacks=[],this.rejectPending(a),b.notify)for(let a of[...this.closeListeners])a();b.closeSocket&&d&&function(a){if(3===a.readyState)return;let b=H(a,"error",()=>{}),c=globalThis.setTimeout(()=>{b?.(),b=null},5e3);"object"==typeof c&&c&&"unref"in c&&"function"==typeof c.unref&&c.unref();try{if(0===a.readyState&&"function"==typeof a.terminate)return void a.terminate();a.close()}catch{b?.(),b=null,globalThis.clearTimeout(c)}}(d)}}function P(a,b){let c=b?.trim();if(c?.startsWith("agent:"))return c;let d=a?.trim()||"main";return c?`agent:${d}:explicit:${c}`:`agent:${d}:main`}function Q(a={}){let b=a.key?.trim()||a.sessionKey?.trim();if(b)return{key:b};let c=a.sessionId?.trim(),d=a.agentId?.trim();return{agentId:d||void 0,sessionId:c||void 0,key:d||c?P(d,c):void 0}}function R(a,b){return"number"==typeof a.timeoutSeconds&&Number.isFinite(a.timeoutSeconds)&&a.timeoutSeconds>0?Math.floor(1e3*a.timeoutSeconds):"number"==typeof b.timeoutMs&&Number.isFinite(b.timeoutMs)&&b.timeoutMs>0?b.timeoutMs:45e3}function S(a){let b=(0,l.$g)(a).kind,c=a instanceof Error?a.message:String(a||"");return"unsupported"===b||"conflict"===b||"malformed-response"===b||/invalid .*sessions\.(create|patch) params|unexpected property/i.test(c)}var T=c(17661),U=c(21916);let V=T.Ik({runtimeVersion:T.Yj().optional(),version:T.Yj().optional(),updateChannel:T.Yj().optional()}).passthrough(),W=T.Ik({defaultId:T.Yj().optional(),mainKey:T.Yj().optional(),scope:T.Yj().optional(),agents:T.YO(T.Ik({id:T.Yj(),name:T.Yj().optional(),identity:T.Ik({name:T.Yj().optional(),theme:T.Yj().optional(),emoji:T.Yj().optional(),avatar:T.Yj().optional(),avatarUrl:T.Yj().optional()}).passthrough().optional(),workspace:T.Yj().optional(),model:T.Ik({primary:T.Yj().optional(),fallbacks:T.YO(T.Yj()).optional()}).passthrough().optional()}).passthrough())}).passthrough(),X=T.Ik({sessions:T.YO(T.Ik({}).passthrough())}).passthrough(),Y=T.Ik({ts:T.ai().optional(),channelOrder:T.YO(T.Yj()).optional().default([]),channelLabels:T.g1(T.Yj(),T.Yj()).optional().default({}),channelDetailLabels:T.g1(T.Yj(),T.Yj()).optional(),channelSystemImages:T.g1(T.Yj(),T.Yj()).optional(),channelMeta:T.YO(T.Ik({id:T.Yj(),label:T.Yj(),detailLabel:T.Yj(),systemImage:T.Yj().optional()}).passthrough()).optional(),channels:T.g1(T.Yj(),T.L5()),channelAccounts:T.g1(T.Yj(),T.YO(T.Ik({accountId:T.Yj()}).passthrough())),channelDefaultAccountId:T.g1(T.Yj(),T.KC([T.Yj(),T.ch()])).optional().default({})}).passthrough(),Z=T.Ik({models:T.YO(T.Ik({key:T.Yj().optional(),id:T.Yj().optional(),provider:T.Yj().optional(),name:T.Yj(),input:T.KC([T.Yj(),T.YO(T.Yj())]).optional().default("text"),contextWindow:T.ai().nullable().optional().default(null),local:T.zM().nullable().optional().default(null),available:T.zM().nullable().optional().default(null),tags:T.YO(T.Yj()).optional().default([]),missing:T.zM().optional().default(!1)}).passthrough())}).passthrough(),$=T.Ik({skills:T.YO(T.Ik({name:T.Yj(),description:T.Yj().optional(),emoji:T.Yj().optional(),eligible:T.zM().optional(),disabled:T.zM().optional(),blockedByAllowlist:T.zM().optional(),source:T.Yj().optional(),bundled:T.zM().optional()}).passthrough())}).passthrough(),_=T.Ik({plugins:T.YO(T.Ik({id:T.Yj(),name:T.Yj(),status:T.Yj().optional(),toolNames:T.YO(T.Yj()).optional()}).passthrough()).optional(),descriptors:T.YO(T.Ik({}).passthrough()).optional()}).passthrough(),aa=T.Ik({exists:T.zM().optional(),valid:T.zM().optional(),hash:T.Yj().optional(),config:T.g1(T.Yj(),T.L5()).optional(),resolved:T.L5().optional()}).passthrough(),ab=T.Ik({}).passthrough();function ac(a,b,c){let d=b.safeParse(c);if(!d.success)throw new l.pz(`${a}: OpenClaw Gateway returned a malformed response.`,"malformed-response",{cause:d.error});return d.data}function ad(a,b){return ac(a,ab,b)}function ae(a){(a?.latestVersion||a?.error)&&(af={...a})}let af=null;function ag(a){let b=ac("models.list",Z,a);return{...b,models:b.models.map(a=>{let b=(0,n.yK)(a.id),c=(0,n.yK)(a.provider),d=(0,n.yK)(a.key)??(c&&b?`${c}/${b}`:b),e=Array.isArray(a.input)?a.input.filter(a=>"string"==typeof a).join(",")||"text":(0,n.yK)(a.input)??"text",f=Array.isArray(a.tags)?a.tags.filter(a=>"string"==typeof a):[];return!0!==a.default&&!0!==a.isDefault||f.includes("default")||f.push("default"),{key:d??(0,n.yK)(a.name)??"unknown",name:(0,n.yK)(a.name)??d??b??"Unknown model",input:e,contextWindow:"number"==typeof a.contextWindow?a.contextWindow:null,local:"boolean"==typeof a.local?a.local:null,available:"boolean"==typeof a.available?a.available:null,tags:f,missing:!0===a.missing}})}}function ah(a,b){var c,d;let e=(0,n.LK)(a)?a:{},f=b?ag(b).models:[],g=f.map(a=>a.key).filter(Boolean),h=(c=e,d=f,(0,n.yK)(c.defaultModel)??(0,n.yK)(c.default)??d.find(a=>a.tags.some(a=>"default"===a.toLowerCase()))?.key??null),i=(0,n.yK)(e.resolvedDefault)??(0,n.yK)(e.resolvedDefaultModel)??h,j=Array.isArray(e.providers)?e.providers.filter(a=>(0,n.LK)(a)):[];return{defaultModel:h,resolvedDefault:i,allowed:g,auth:{providers:j.map(a=>{let b=ai(a.profiles);return{provider:(0,n.yK)(a.provider)??void 0,effective:{kind:b>0?"ok":(0,n.yK)(a.status)??(0,n.yK)(a.kind)??void 0,detail:(0,n.yK)(a.detail)??void 0},profiles:{count:Array.isArray(a.profiles)?b:void 0}}}),missingProvidersInUse:Array.isArray(e.missingProvidersInUse)?e.missingProvidersInUse.filter(a=>"string"==typeof a):[],unusableProfiles:Array.isArray(e.unusableProfiles)?e.unusableProfiles:[],oauth:{providers:j.map(a=>({provider:(0,n.yK)(a.provider)??void 0,status:ai(a.profiles)>0?"ok":(0,n.yK)(a.status)??void 0,profiles:Array.isArray(a.profiles)?a.profiles:void 0,effectiveProfiles:Array.isArray(a.effectiveProfiles)?a.effectiveProfiles:void 0}))}}}}function ai(a){return Array.isArray(a)?a.filter(a=>(function(a){if(!(0,n.LK)(a))return!1;let b=(0,n.yK)(a.status)?.toLowerCase();return!b||!["expired","missing","invalid","error","disabled","revoked"].includes(b)})(a)).length:0}function aj(a){let b=ac("plugins.uiDescriptors",_,a);return{plugins:(b.plugins??b.descriptors??[]).map(a=>({...a,id:(0,n.yK)(a.id)??(0,n.yK)(a.pluginId)??(0,n.yK)(a.name)??"unknown",name:(0,n.yK)(a.name)??(0,n.yK)(a.label)??(0,n.yK)(a.id)??"Unknown plugin",status:(0,n.yK)(a.status)??void 0,toolNames:Array.isArray(a.toolNames)?a.toolNames.filter(a=>"string"==typeof a):void 0}))}}function ak(){return(0,l.Lo)()}class al{constructor(a={}){this.options=a,this.fallbackCounts={},this.lastNativeFailure=null,this.fallback=a.fallback??new d.p,this.connection=new O(this.fallback,a)}close(a="closed"){this.connection.close(a)}getDiagnostics(){var a,b,c;let d=this.connection.getDiagnostics(),e=this.options.forceCli||C(),f=Object.values(this.fallbackCounts).reduce((a,b)=>Number.isFinite(b)&&b>0?a+b:a,0),g=(0,l.Lo)(),h=(a=g,b=d.lastConnectedAt,0!==a.length&&(!b||a.some(a=>ap(a.at,b))))?f:0,i=ap(this.lastNativeFailure?.at??null,d.lastConnectedAt)?this.lastNativeFailure:null,j=this.lastNativeFailure?.issue||(0,l.mW)(d.lastNativeError),k=i?.issue||(0,l.mW)(d.lastNativeError),n=(c={forceCli:e,connectionState:d.connectionState,fallbackTotal:h,lastNativeError:k}).forceCli?"cli-forced":"error"===c.connectionState?"unreachable":c.fallbackTotal>0?"fallback-active":"closed"===c.connectionState||c.lastNativeError?"degraded":"native-ws";return{mode:e?"cli":"native-ws",gatewayMode:n,statusLabel:function(a){switch(a){case"native-ws":return"Native Gateway: OK";case"cli-forced":return"CLI fallback forced";case"fallback-active":return"CLI fallback used";case"unreachable":return"Native Gateway: Unreachable";default:return"Native Gateway: Degraded"}}(n),recovery:function(a,b){if("native-ws"===a)return null;if(b)return b;switch(a){case"cli-forced":return"Unset CLI-forced Gateway mode and restart AgentOS to use native WebSocket transport.";case"fallback-active":return"Inspect recent fallback diagnostics, update OpenClaw for protocol or method gaps, repair token/device access for auth failures, then restart the Gateway if needed.";case"unreachable":return"Start or restart the OpenClaw Gateway, verify the endpoint and token/password, then retry the native operation.";default:return"Inspect Gateway diagnostics, check token/device access, update OpenClaw for compatibility gaps, then restart the Gateway before retrying."}}(n,i?.recovery??null),connectionState:e?"cli-forced":d.connectionState,protocolVersion:d.protocolVersion,protocolRange:m.aj,fallbackCounts:{...this.fallbackCounts},fallbackTotal:f,recentFallbackDiagnostics:g,lastNativeError:j||null,lastNativeFailureAt:this.lastNativeFailure?.at??null,lastConnectedAt:d.lastConnectedAt,lastDisconnectedAt:d.lastDisconnectedAt}}recordNativeFailure(a,b){let c=(0,l.$g)(b);this.lastNativeFailure={at:new Date().toISOString(),operation:a,issue:(0,l.mW)(c.message),kind:c.kind,recovery:(0,l.fu)(c)}}clearNativeFailure(a){this.lastNativeFailure?.operation===a&&(this.lastNativeFailure=null)}recordGatewayFallback(a,b){this.recordNativeFailure(a,b),this.fallbackCounts[a]=(this.fallbackCounts[a]??0)+1,(0,l.Rd)(a,b)}cliFallbackDisabledError(a,b){this.recordNativeFailure(a,b);let c=(0,l.$g)(b);return new l.pz(`${c.message} Gateway-native operation failed; CLI fallback disabled for this operation. Recovery: ${(0,l.fu)(c)}`,c.kind,{cause:b})}getHealth(a={}){return this.gatewayFirst("health",{},a,a=>(0,n.LK)(a)?a:{},()=>this.fallback.getHealth(a))}getStatus(a={}){return this.options.forceCli||C()?this.fallback.getStatus(a):this.callNative("status",{},a).then(a=>{let b=ac("status",V,a);return((0,l.Z6)("status"),this.clearNativeFailure("status"),b.update?.registry?.latestVersion||b.update?.registry?.error)?(ae(b.update?.registry),b):function(a){let b=a.update??{},c=(void 0)??{},d=function(a){var b;let c=((b=a).runtimeVersion||b.overview?.version||b.version||"").trim().replace(/^v/i,"")||null,d=af?.latestVersion?.trim();if(af){if(c&&d&&(0,U.QK)(c,d)>0){af=null;return}return af??void 0}}(a),e=b.registry??c.registry??d??void 0;if(e&&ae(e),!e)return a;let f={...c,...b};return e&&(f.registry=e),{...a,update:f}}(b)}).catch(b=>{if(this.options.onNativeFailure?.(b,"status"),!F(b,"status",E("status",a)))throw this.cliFallbackDisabledError("status",b);return this.recordGatewayFallback("status",b),this.fallback.getStatus(a)})}getUpdateStatus(a={}){return this.options.forceCli||C()?this.fallback.getUpdateStatus(a):this.callNative("update.status",{},a).then(async b=>{var c,d;let e=ad("update.status",b);return(function(a){let b=[];function c(a){!(0,n.LK)(a)||b.includes(a)||b.push(a)}return c(a),c(a?.update),c(a?.availability),c(aq(a?.update)?.registry),c(a?.registry),c(a?.result),c(aq(a?.result)?.update),c(aq(aq(a?.result)?.update)?.registry),c(aq(a?.result)?.availability),c(a?.sentinel),c(aq(a?.sentinel)?.stats),b})(e).some(a=>"boolean"==typeof a.updateAvailable||"string"==typeof a.latestVersion||"string"==typeof a.targetVersion||"string"==typeof a.availableVersion||"string"==typeof a.recommendedVersion||"boolean"==typeof a.available||"boolean"==typeof a.hasRegistryUpdate)?((0,l.Z6)("update.status"),this.clearNativeFailure("update.status"),e):(this.recordGatewayFallback("update.status",new l.pz("OpenClaw Gateway update.status did not include update availability details.","malformed-response")),c=e,d=await this.fallback.getUpdateStatus(a),{...c,...d})}).catch(b=>{if(this.options.onNativeFailure?.(b,"update.status"),!F(b,"update.status",E("update.status",a)))throw this.cliFallbackDisabledError("update.status",b);return this.recordGatewayFallback("update.status",b),this.fallback.getUpdateStatus(a)})}getGatewayStatus(a={}){return this.gatewayFirst("health",{},a,a=>{let b=(0,n.LK)(a)?a:{};return{service:{label:!1===b.ok?"Runtime degraded":"Runtime ready",loaded:!1!==b.ok},rpc:{ok:!1!==b.ok}}},()=>this.fallback.getGatewayStatus(a))}async getModelStatus(a={}){if(this.options.forceCli||C())return this.fallback.getModelStatus(a);let[b,c]=await Promise.allSettled([this.callNative("models.authStatus",{},a),this.callNative("models.list",{view:"configured"},a)]);for(let d of[{method:"models.authStatus",result:b},{method:"models.list",result:c}].filter(a=>"rejected"===a.result.status))if(this.options.onNativeFailure?.(d.result.reason,d.method),!F(d.result.reason,d.method,E(d.method,a)))throw this.cliFallbackDisabledError(d.method,d.result.reason);if("rejected"===b.status&&"rejected"===c.status){let c=b.reason;return this.recordGatewayFallback("models.authStatus",c),this.fallback.getModelStatus(a)}return(0,l.Z6)("models.authStatus"),(0,l.Z6)("models.list"),this.clearNativeFailure("models.authStatus"),this.clearNativeFailure("models.list"),ah("fulfilled"===b.status?b.value:null,"fulfilled"===c.status?c.value:null)}async getAgentModelStatus(a,b={}){if(this.options.forceCli||C())return this.fallback.getAgentModelStatus(a,b);let c=a.agentId,[d,e]=await Promise.allSettled([this.callNative("models.authStatus",{agentId:c},b),this.callNative("models.list",{view:"configured"},b)]);for(let a of[{method:"models.authStatus",result:d},{method:"models.list",result:e}].filter(a=>"rejected"===a.result.status))if(this.options.onNativeFailure?.(a.result.reason,a.method),!F(a.result.reason,a.method,E(a.method,b)))throw this.cliFallbackDisabledError(a.method,a.result.reason);if("rejected"===d.status&&"rejected"===e.status){let c=d.reason;return this.recordGatewayFallback("models.authStatus",c),this.fallback.getAgentModelStatus(a,b)}(0,l.Z6)("models.authStatus"),(0,l.Z6)("models.list"),this.clearNativeFailure("models.authStatus"),this.clearNativeFailure("models.list");let f="fulfilled"===d.status?d.value:null,g=ah(f,"fulfilled"===e.status?e.value:null);return(0,n.LK)(f)&&(g.agentDir=(0,n.yK)(f.agentDir)??g.agentDir),g}setModelAuthOrder(a,b={}){return this.gatewayFirstCompatible("modelAuthOrder",{provider:a.provider,agentId:a.agentId,profileIds:a.profileIds},b,n.hz,()=>this.fallback.setModelAuthOrder(a,b))}listAgents(a={}){return this.gatewayFirst("agents.list",{},a,a=>ac("agents.list",W,a),()=>this.fallback.listAgents(a))}listSessions(a={},b={}){return this.gatewayFirst("sessions.list",{...a},b,a=>ac("sessions.list",X,a),()=>this.fallback.listSessions(a,b))}describeSession(a={},b={}){return this.gatewayFirst("sessions.describe",{...Q(a),includeMessages:a.includeMessages,limit:a.limit},b,a=>ad("sessions.describe",a),()=>this.fallback.describeSession(a,b))}getSessionHistory(a={},b={}){return this.gatewayFirstSessionHistory(a,b)}exportSession(a={},b={}){return this.gatewayFirstSessionExport(a,b)}listTasks(a={},b={}){return this.gatewayFirst("tasks.list",{...a},b,a=>ad("tasks.list",a),()=>this.fallback.listTasks(a,b))}getTask(a,b={}){return this.gatewayFirst("tasks.get",{...a},b,a=>ad("tasks.get",a),()=>this.fallback.getTask(a,b))}assignTask(a,b={}){return this.gatewayFirstCompatible("taskAssign",{...a,reason:a.reason??void 0},b,a=>ad("tasks.assign",a),()=>this.fallback.assignTask(a,b))}cancelTask(a,b={}){return this.gatewayFirst("tasks.cancel",{taskId:a.taskId,reason:a.reason??void 0},b,a=>ad("tasks.cancel",a),()=>this.fallback.cancelTask(a,b))}listArtifacts(a={},b={}){return this.gatewayFirst("artifacts.list",function(a={}){return{taskId:a.taskId?.trim()||void 0,runId:a.runId?.trim()||void 0,sessionKey:a.sessionKey?.trim()||a.sessionId?.trim()||void 0}}(a),b,a=>ad("artifacts.list",a),()=>this.fallback.listArtifacts(a,b))}getArtifact(a,b={}){return this.gatewayFirst("artifacts.get",{...a},b,a=>ad("artifacts.get",a),()=>this.fallback.getArtifact(a,b))}putArtifact(a,b={}){let c={...E("artifacts.put",b),allowCliFallback:!1,allowMutationFallbackOnUnsupported:!1};return this.gatewayFirst("artifacts.put",{...a},b,a=>ad("artifacts.put",a),()=>this.fallback.putArtifact(a,b),c)}deleteArtifact(a,b={}){let c={...E("artifacts.delete",b),allowCliFallback:!1,allowMutationFallbackOnUnsupported:!1};return this.gatewayFirst("artifacts.delete",{artifactId:a.artifactId,reason:a.reason??void 0},b,a=>ad("artifacts.delete",a),()=>this.fallback.deleteArtifact(a,b),c)}async getRuntimeSnapshot(a={},b={}){if(this.options.forceCli||C())return this.fallback.getRuntimeSnapshot(a,b);let c=!1!==a.includeSessions,d=!1!==a.includeTasks,e=!1!==a.includeArtifacts,f={taskId:a.taskId,runId:a.runId,sessionKey:a.sessionKey,sessionId:a.sessionId},g=e&&function(a={}){return!!(a.taskId?.trim()||a.runId?.trim()||a.sessionKey?.trim()||a.sessionId?.trim())}(f),h=await Promise.allSettled([c?this.listSessions({limit:a.limit,agentId:a.agentId},b):Promise.resolve(null),d?this.listTasks({limit:a.limit,agentId:a.agentId,workspace:a.workspace},b):Promise.resolve(null),g?this.listArtifacts(f,b):Promise.resolve(null)]),i=h.filter((a,b)=>[c,d,g][b]),j=i.filter(a=>"rejected"===a.status);if(i.length>0&&j.length===i.length)throw j[0]?.reason??Error("OpenClaw Gateway runtime snapshot failed.");let[k,l,m]=h,n={sessions:"fulfilled"===k.status?k.value?.sessions??[]:[],tasks:"fulfilled"===l.status?l.value?.tasks??[]:[],artifacts:"fulfilled"===m.status?m.value?.artifacts??[]:[]};return j.length>0&&(n.metadata={runtimeSnapshot:{partial:!0,errors:j.map(a=>{var b;return(b=a.reason)instanceof Error?b.message:String(b||"Unknown OpenClaw Gateway snapshot error.")})}}),n}getToolsCatalog(a={},b={}){return this.gatewayFirst("tools.catalog",{...a},b,a=>ad("tools.catalog",a),()=>this.fallback.getToolsCatalog(a,b))}getEffectiveTools(a={},b={}){return this.gatewayFirst("tools.effective",{...a},b,a=>ad("tools.effective",a),()=>this.fallback.getEffectiveTools(a,b))}invokeTool(a,b={}){return this.gatewayFirst("tools.invoke",{...a},b,a=>ad("tools.invoke",a),()=>this.fallback.invokeTool(a,b))}getChannelStatus(a={},b={}){return this.gatewayFirst("channels.status",{...a},b,a=>ac("channels.status",Y,a),()=>this.fallback.getChannelStatus(a,b))}getChannelLogs(a,b={}){return this.gatewayFirst("channels.logs",{channel:a.channel,lines:a.lines??void 0},b,a=>(0,n.LK)(a)?a:{},()=>this.fallback.getChannelLogs(a,b))}provisionChannelAccount(a,b={}){return this.gatewayFirstCompatible("channelProvisioning",{channel:a.channel,account:a.account?.trim()||void 0,accountId:a.account?.trim()||void 0,name:a.name?.trim()||void 0,token:a.token?.trim()||void 0,botToken:a.botToken?.trim()||void 0,webhookUrl:a.webhookUrl?.trim()||void 0},b,n.hz,()=>this.fallback.provisionChannelAccount(a,b))}removeChannelAccount(a,b={}){return this.gatewayFirstCompatible("channelRemoval",{channel:a.channel,account:a.account,accountId:a.account,delete:a.delete??void 0},b,n.hz,()=>this.fallback.removeChannelAccount(a,b))}setupGmailWebhook(a,b={}){return this.gatewayFirstCompatible("gmailProvisioning",{account:a.account,config:a.config??{}},b,n.hz,()=>this.fallback.setupGmailWebhook(a,b))}listSkills(a={}){return this.gatewayFirst("skills.status",{},a,b=>{let c=ac("skills.status",$,b);return a.eligible?{...c,skills:c.skills.filter(a=>!0===a.eligible)}:c},()=>this.fallback.listSkills(a))}listPlugins(a={}){return this.gatewayFirstCompatible("plugins",{},a,aj,()=>this.fallback.listPlugins(a))}listModels(a={},b={}){return this.gatewayFirst("models.list",{view:a.all?"all":"configured"},b,b=>{let c=ag(b);return a.provider?{...c,models:c.models.filter(b=>b.key.split("/",1)[0]===a.provider)}:c},()=>this.fallback.listModels(a,b))}scanModels(a={}){return this.gatewayFirstCompatible("modelScan",{yes:!0===a.yes||void 0,noInput:!0===a.noInput||void 0,noProbe:!0===a.noProbe||void 0},a,a=>Array.isArray(a)?a:Array.isArray(a?.models)?a.models:[],()=>this.fallback.scanModels(a))}probeGateway(a={}){return this.fallback.probeGateway(a)}controlGateway(a,b={}){return this.close(`gateway.${a}`),this.fallback.controlGateway(a,b).finally(()=>{this.close(`gateway.${a}.completed`)})}approveDeviceAccess(a={},b={}){return!1===a.latest||a.requestId?this.gatewayFirstCompatible("deviceApproval",{requestId:a.requestId??void 0,scopes:a.scopes},b,a=>ad("device.pair.approve",a),()=>this.fallback.approveDeviceAccess(a,b)):this.gatewayFirstCompatible("devicePairList",{},b,a=>ad("device.pair.list",a),()=>this.fallback.call("device.pair.list",{},b)).then(c=>{let d=(0,A.$k)(c);if(!d)throw new l.pz("No pending OpenClaw device access request found.","unknown");return this.approveDeviceAccess({...a,latest:!1,requestId:d},b)})}async call(a,b={},c={}){if(this.options.forceCli||C())return this.fallback.call(a,b,c);try{let d=await this.callNative(a,b,c);return(0,l.Z6)(a),this.clearNativeFailure(a),d}catch(e){this.options.onNativeFailure?.(e,a);let d=E(a,c);if(!F(e,a,d))throw this.cliFallbackDisabledError(a,e);return this.recordGatewayFallback(a,e),this.fallback.call(a,b,c)}}getConfig(a,b={}){return this.gatewayFirst("config.get",{},b,b=>{let c=ac("config.get",aa,b),d=(0,n.LK)(c.config)?c.config:{},e=(0,n.LK)(c.resolved)?c.resolved:{},f=(0,n.e6)(d,a)??(0,n.e6)(e,a);return void 0===f?null:f},()=>this.fallback.getConfig(a,b))}getConfigSchema(a={}){return this.gatewayFirst("config.schema",{},a,a=>(0,n.LK)(a)?a:null,()=>this.fallback.getConfigSchema?.(a)??Promise.resolve(null))}lookupConfigSchema(a,b={}){return this.gatewayFirst("config.schema.lookup",{path:a.path},b,a=>(0,n.LK)(a)?a:null,()=>this.fallback.lookupConfigSchema?.(a,b)??Promise.resolve(null))}async hasConfig(a,b={}){return null!=await this.getConfig(a,b)}setConfig(a,b,c={}){return this.gatewayConfigMutationFirst("config.set",a,b,c,c=>(0,n.r0)(c,a,b),()=>this.fallback.setConfig(a,b,c))}unsetConfig(a,b={}){return this.gatewayConfigMutationFirst("config.unset",a,void 0,b,b=>(0,n.WW)(b,a),()=>this.fallback.unsetConfig(a,b))}addAgent(a,b={}){if(a.agentDir?.trim())return this.fallback.addAgent(a,b);let c={name:a.name?.trim()||a.id,workspace:a.workspace};return a.model&&(c.model=a.model),a.emoji&&(c.emoji=a.emoji),a.avatar&&(c.avatar=a.avatar),this.gatewayFirst("agents.create",c,b,n.hz,()=>this.fallback.addAgent(a,b))}updateAgent(a,b={}){let c={agentId:a.id};return void 0!==a.name&&null!==a.name&&a.name.trim()&&(c.name=a.name.trim()),void 0!==a.workspace&&null!==a.workspace&&a.workspace.trim()&&(c.workspace=a.workspace.trim()),void 0!==a.model&&(c.model=a.model?.trim()||null),void 0!==a.emoji&&(c.emoji=a.emoji?.trim()||""),void 0!==a.avatar&&(c.avatar=a.avatar?.trim()||""),this.gatewayFirst("agents.update",c,b,n.hz,()=>this.fallback.updateAgent?.(a,b)??Promise.resolve({stdout:JSON.stringify({ok:!0,fallback:"application-config"}),stderr:""}))}setAgentIdentity(a,b={}){return this.gatewayFirstCompatible("agentIdentity",{agentId:a.agentId,agent:a.agentId,workspace:a.workspace,identityFile:a.identityFile,name:a.name?.trim()||void 0,emoji:a.emoji?.trim()||void 0,theme:a.theme?.trim()||void 0,avatar:a.avatar?.trim()||void 0},b,n.hz,()=>this.fallback.setAgentIdentity(a,b))}deleteAgent(a,b={}){return this.gatewayFirst("agents.delete",{agentId:a},b,n.hz,()=>this.fallback.deleteAgent(a,b))}provisionAutomation(a,b={}){return this.gatewayFirstCompatible("automationProvisioning",{name:a.name,description:a.description||a.name,agentId:a.agentId,agent:a.agentId,message:a.message,thinking:a.thinking||"medium",timeoutSeconds:a.timeoutSeconds??120,schedule:a.schedule,announce:a.announce??void 0},b,n.hz,()=>this.fallback.provisionAutomation(a,b))}async runAgentTurn(a,b={}){if(this.options.forceCli||C())return this.fallback.runAgentTurn(a,b);try{let c=await this.runAgentTurnNative(a,b);if((0,l.Z6)("chat.send"),(0,l.Z6)("sessions.send"),this.clearNativeFailure("chat.send"),this.clearNativeFailure("sessions.send"),!function(a,b){if(!b.runId||"number"!=typeof a.timeoutSeconds||!Number.isFinite(a.timeoutSeconds)||a.timeoutSeconds<=0)return!1;let c=b.status?.trim().toLowerCase();return!c||"started"===c||"running"===c||"queued"===c}(a,c))return c;return await this.waitForAgentTurnNative(a,c,b)??c}catch(d){this.options.onNativeFailure?.(d,"chat.send");let c=d instanceof l.jl?d.method:"chat.send";if(!F(d,c,{safety:"mutation"}))throw this.cliFallbackDisabledError(c,d);return this.recordGatewayFallback("chat.send",d),this.fallback.runAgentTurn(a,b)}}abortAgentTurn(a,b={}){let c=a.sessionId||a.agentId?P(a.agentId,a.sessionId):void 0;return this.gatewayFirst("sessions.abort",{key:c,runId:a.runId??void 0},b,a=>a,()=>this.gatewayFirst("chat.abort",{sessionKey:c,runId:a.runId??void 0},b,a=>a,()=>this.fallback.abortAgentTurn?.(a,b)??this.fallback.call("sessions.abort",{key:c,runId:a.runId??void 0},b)))}async steerSession(a,b={}){if(this.options.forceCli||b.forceCli||C())throw new l.pz("Native OpenClaw Gateway is required for sessions.steer.","unsupported");try{let c,d,e=await this.callNative("sessions.steer",(c=a.key?.trim(),d=a.sessionId?.trim(),{key:c||void 0,sessionId:c?void 0:d||void 0,message:a.message}),b,{safety:"mutation",timeoutMs:b.timeoutMs,allowCliFallback:!1,allowMutationFallbackOnUnsupported:!1});return this.clearNativeFailure("sessions.steer"),ad("sessions.steer",e)}catch(a){throw this.options.onNativeFailure?.(a,"sessions.steer"),this.cliFallbackDisabledError("sessions.steer",a)}}async injectChat(a,b={}){if(this.options.forceCli||b.forceCli||C())throw new l.pz("Native OpenClaw Gateway is required for chat.inject.","unsupported");try{let c,d,e=await this.callNative("chat.inject",(c=a.sessionKey?.trim(),d=a.sessionId?.trim(),{sessionKey:c||void 0,sessionId:c?void 0:d||void 0,message:a.message}),b,{safety:"mutation",timeoutMs:b.timeoutMs,allowCliFallback:!1,allowMutationFallbackOnUnsupported:!1});return this.clearNativeFailure("chat.inject"),ad("chat.inject",e)}catch(a){throw this.options.onNativeFailure?.(a,"chat.inject"),this.cliFallbackDisabledError("chat.inject",a)}}async streamAgentTurn(a,b={},c={}){if(c.forceCli||this.options.forceCli||C())return this.fallback.streamAgentTurn(a,b,c);let d=P(a.agentId,a.sessionId),e=null,f=null,g="",h=()=>{},i=new Promise(a=>{h=a});try{e=await this.subscribeNativeEvents({subscribeSessions:!0,sessionKeys:[d]},{onEvent:a=>{let c=function(a,b,c){let d=(0,n.LK)(a.payload)?a.payload:{},e=(0,n.yK)(d.sessionKey)??(0,n.yK)(d.key)??(0,n.yK)(d.sessionId),f=(0,n.yK)(d.runId)??(0,n.yK)(d.run)??(0,n.yK)(d.clientRunId),g=b.includes(":explicit:")?b.split(":explicit:").at(1)??null:null;if(e&&e!==b&&e!==g||c&&f&&f!==c||!e&&!f)return null;let h=function(a){if(!(0,n.LK)(a))return null;let b=(0,n.LK)(a.author)?a.author:null;return(0,n.yK)(a.role)??(0,n.yK)(a.type)??(0,n.yK)(a.speaker)??(0,n.yK)(b?.role)??(0,n.yK)(b?.type)??(0,n.yK)(b?.name)}(d.message)??(0,n.yK)(d.role)??(0,n.yK)(d.authorRole)??(0,n.yK)(d.speaker);if(h&&/^(user|operator|system)$/i.test(h))return null;let i=(0,n.yK)(d.state)??(0,n.yK)(d.status)??(0,n.yK)(a.event),j=function a(b){return"string"==typeof b&&b.trim()?b.trim():Array.isArray(b)?b.flatMap(b=>{if(!(0,n.LK)(b))return[];if(("text"===b.type||"output_text"===b.type)&&"string"==typeof b.text&&b.text.trim())return[b.text.trim()];if("toolResult"===b.type){let c=a(b.content)??(0,n.yK)(b.text);return c?[c]:[]}return[]}).join("\n\n").trim()||null:(0,n.LK)(b)?(0,n.yK)(b.text)??(0,n.yK)(b.content)??a(b.content)??(0,n.yK)(b.summary)??(0,n.yK)(b.message):null}(d.message)??(0,n.yK)(d.text)??(0,n.yK)(d.summary)??(0,n.yK)(d.detail),k=/final|complete|completed|aborted|abort|error|failed|stalled/i.test(i??""),l=/error|failed|stalled/i.test(i??"");return!k||j||l?{text:j,done:k,payload:{runId:f??c??void 0,status:l?"stalled":k?"completed":"running",summary:j??"OpenClaw Gateway stream failed.",payloads:j?[{text:j,mediaUrl:null}]:[]}}:null}(a,d,f);c&&(c.text&&c.text!==g&&(g=c.text,b.onStdout?.(`${JSON.stringify({type:"assistant",text:c.text})}
|
|
5
5
|
`)),c.done&&h?.(c.payload))},onError:a=>{b.onStderr?.(a instanceof Error?`${a.message}
|
|
6
6
|
`:`${String(a)}
|
|
7
|
-
`)}},c);let j=await this.runAgentTurnNative(a,c);f=j.runId??null,(0,l.Z6)("streamAgentTurn"),this.clearNativeFailure("streamAgentTurn");let k=R(a,c),m=await Promise.race([i,new Promise(a=>globalThis.setTimeout(()=>a(null),k))]);if(m)return m;return await this.waitForAgentTurnNative(a,j,c)??j}catch(e){this.options.onNativeFailure?.(e,"streamAgentTurn");let d=e instanceof l.jl?e.method:"streamAgentTurn";if(!F(e,d,{safety:"mutation"}))throw this.cliFallbackDisabledError(d,e);return this.recordGatewayFallback("streamAgentTurn",e),this.fallback.streamAgentTurn(a,b,c)}finally{e?.close(),h(null)}}async runAgentTurnNative(a,b={}){let c=P(a.agentId,a.sessionId),d="number"==typeof a.timeoutSeconds&&Number.isFinite(a.timeoutSeconds)?Math.max(0,Math.floor(1e3*a.timeoutSeconds)):void 0,e=a.idempotencyKey?.trim()||a.dispatchId||(0,n.r_)();await this.prepareNativeSession(a,c,b);let f={sessionKey:c,sessionId:a.sessionId,message:a.message,thinking:a.thinking,timeoutMs:d,idempotencyKey:e};try{return await this.callNative("chat.send",f,b)}catch(d){if(!(0,A.lH)(d)){if(am(d,a.agentId)){let e=await this.checkGatewayAgentRegistry(a.agentId,b);if("present"===e)try{return await this.prepareNativeSession(a,c,b),await this.callNative("chat.send",f,b)}catch(b){if(am(b,a.agentId))throw an(a.agentId,b);throw b}if("missing"===e)throw an(a.agentId,d)}throw d}}return this.callNative("sessions.send",{agentId:a.agentId,key:c,message:a.message,thinking:a.thinking,timeoutMs:d,idempotencyKey:e},b)}async checkGatewayAgentRegistry(a,b){try{var c;let d,e=ac("agents.list",W,await this.callNative("agents.list",{},{...b,timeoutMs:5e3},{safety:"read",timeoutMs:5e3}));return(0,l.Z6)("agents.list"),this.clearNativeFailure("agents.list"),(c=e,(d=a.trim())&&(c.defaultId===d||c.mainKey===d||c.agents.some(a=>a.id===d)))?"present":"missing"}catch{return"unknown"}}async prepareNativeSession(a,b,c){if(a.sessionId||a.dispatchId){try{await this.callNative("sessions.create",{key:b,agentId:a.agentId},c,{safety:"mutation"}),(0,l.Z6)("sessions.create")}catch(a){if(!S(a))throw a}try{await this.callNative("sessions.patch",{key:b,metadata:{agentId:a.agentId,sessionId:a.sessionId??void 0,workspace:a.workspace??void 0,dispatchId:a.dispatchId??void 0,local:a.local??void 0,origin:a.dispatchId?"agentos-mission-dispatch":"agentos-direct-chat"}},c,{safety:"mutation"}),(0,l.Z6)("sessions.patch")}catch(a){if(!S(a))throw a}}}async waitForAgentTurnNative(a,b,c){if(!b.runId)return null;let d=R(a,c),e=P(a.agentId,a.sessionId);try{let f=await this.callNative("agent.wait",{runId:b.runId,sessionKey:e,sessionId:a.sessionId??void 0,timeoutMs:d},{...c,timeoutMs:d},{safety:"read",timeoutMs:d});return(0,l.Z6)("agent.wait"),f}catch(b){let a;if("unsupported"!==(a=(0,l.$g)(b).kind)&&"timeout"!==a&&"malformed-response"!==a)throw b;return null}}tailLogs(a={},b={}){return this.gatewayFirst("logs.tail",{...a},b,a=>(0,n.LK)(a)?a:{},()=>this.fallback.tailLogs?.(a,b)??this.fallback.call("logs.tail",{...a},b))}listExecApprovals(a={},b={}){return this.gatewayFirst("exec.approval.list",{...a},b,a=>(0,n.LK)(a)?a:{},()=>this.fallback.listExecApprovals?.(a,b)??this.fallback.call("exec.approval.list",{...a},b))}resolveExecApproval(a,b={}){return this.gatewayFirst("exec.approval.resolve",{approvalId:a.approvalId,decision:a.decision,reason:a.reason??void 0},b,a=>(0,n.LK)(a)?a:{},()=>this.fallback.resolveExecApproval?.(a,b)??this.fallback.call("exec.approval.resolve",{approvalId:a.approvalId,decision:a.decision,reason:a.reason??void 0},b))}getCronStatus(a={}){return this.gatewayFirst("cron.status",{},a,a=>(0,n.LK)(a)?a:{},()=>this.fallback.getCronStatus?.(a)??this.fallback.call("cron.status",{},a))}listCronJobs(a={},b={}){return this.gatewayFirst("cron.list",{...a},b,a=>(0,n.LK)(a)?a:{},()=>this.fallback.listCronJobs?.(a,b)??this.fallback.call("cron.list",{...a},b))}async subscribeRuntimeEvents(a,b,c={}){if(c.forceCli||this.options.forceCli||C())return this.fallback.subscribeRuntimeEvents(a,b,c);let d=[a.includeSessions,a.includeTasks,a.includeArtifacts,a.includeApprovals].some(a=>void 0!==a);try{let e=await this.subscribeNativeEvents({subscribeSessions:a.includeSessions??!d,subscribeTasks:a.includeTasks??(!!a.taskIds?.length||void 0),subscribeArtifacts:a.includeArtifacts,subscribeApprovals:a.includeApprovals,sessionKeys:a.sessionKeys,taskIds:a.taskIds,artifactIds:a.artifactIds},b,c);return(0,l.Z6)("runtime.subscribe"),this.clearNativeFailure("runtime.subscribe"),e}catch(d){if(this.options.onNativeFailure?.(d,"runtime.subscribe"),!F(d,"runtime.subscribe",{safety:"read",timeoutMs:c.timeoutMs}))throw this.cliFallbackDisabledError("runtime.subscribe",d);return this.recordGatewayFallback("runtime.subscribe",d),this.fallback.subscribeRuntimeEvents(a,b,c)}}async callNative(a,b={},c={},d=E(a,c)){let e=D(d.timeoutMs??c.timeoutMs??this.options.timeoutMs,a);return this.connection.request(a,b,c,e)}async probeNativeHandshake(a={}){let b=D(a.timeoutMs??this.options.timeoutMs,m.JV);return this.connection.probe(a,b)}async subscribeNativeEvents(a,b,c={}){let d=D(c.timeoutMs??this.options.timeoutMs,"sessions.subscribe");return this.connection.subscribe(a,b,c,d)}async gatewayFirstSessionHistory(a,b){if(this.options.forceCli||C())return this.fallback.getSessionHistory(a,b);let c=[["chat.history",function(a={}){return{sessionKey:Q(a).key,limit:a.limit,cursor:a.cursor??void 0}}(a)],["sessions.preview",function(a={}){let b=Q(a).key;return{key:b,sessionKey:b,sessionKeys:b?[b]:void 0,limit:a.limit,cursor:a.cursor??void 0}}(a)],["sessions.history",function(a={}){return{...Q(a),limit:a.limit,cursor:a.cursor??void 0}}(a)]],d=null;for(let[e,f]of c){let g=E(e,b);try{let a=ad(e,await this.callNative(e,f,b,g));for(let[a]of c)(0,l.Z6)(a),this.clearNativeFailure(a);return a}catch(c){if(this.options.onNativeFailure?.(c,e),(0,A.lH)(c)){d=c;continue}if(!F(c,e,g))throw this.cliFallbackDisabledError(e,c);return this.recordGatewayFallback(e,c),this.fallback.getSessionHistory(a,b)}}return this.recordGatewayFallback("chat.history",d??new l.As("OpenClaw Gateway does not advertise a compatible session history method.",{kind:"unsupported"})),this.fallback.getSessionHistory(a,b)}async gatewayFirstSessionExport(a,b){if(this.options.forceCli||C())return this.fallback.exportSession(a,b);let c=Q(a),d=[["sessions.get",c],["sessions.describe",c],["sessions.export",{...c,format:a.format}]],e=null;for(let[c,f]of d){let g=E(c,b);try{let e=ad(c,await this.callNative(c,f,b,g));for(let[a]of d)(0,l.Z6)(a),this.clearNativeFailure(a);return function(a,b){if("string"==typeof b.content)return{...b,format:a.format??("string"==typeof b.format?b.format:"json")};let c=a.format??"json";return{...b,format:c,session:b.session??b,content:"json"===c?JSON.stringify(b):void 0}}(a,e)}catch(d){if(this.options.onNativeFailure?.(d,c),(0,A.lH)(d)){e=d;continue}if(!F(d,c,g))throw this.cliFallbackDisabledError(c,d);return this.recordGatewayFallback(c,d),this.fallback.exportSession(a,b)}}return this.recordGatewayFallback("sessions.get",e??new l.As("OpenClaw Gateway does not advertise a compatible session export method.",{kind:"unsupported"})),this.fallback.exportSession(a,b)}async gatewayFirst(a,b,c,d,e,f=E(a,c)){if(this.options.forceCli||C())return e();try{let e=d(await this.callNative(a,b,c,f));return(0,l.Z6)(a),this.clearNativeFailure(a),e}catch(b){if(this.options.onNativeFailure?.(b,a),!F(b,a,f))throw this.cliFallbackDisabledError(a,b);return this.recordGatewayFallback(a,b),e()}}async gatewayFirstCompatible(a,b,c,d,f){if(this.options.forceCli||C())return f();let g=(0,e.P5)(a),h=null;for(let a of g){let e=E(a,c);try{let f=d(await this.callNative(a,b,c,e));for(let a of g)(0,l.Z6)(a),this.clearNativeFailure(a);return f}catch(b){if(this.options.onNativeFailure?.(b,a),(0,A.lH)(b)){h=b;continue}if(!F(b,a,e))throw this.cliFallbackDisabledError(a,b);return this.recordGatewayFallback(a,b),f()}}let i=g[0]??a;return this.recordGatewayFallback(i,h??new l.As(`OpenClaw Gateway does not advertise a compatible method for ${a}.`,{kind:"unsupported"})),f()}async gatewayConfigMutationFirst(a,b,c,d,e,g){if(this.options.forceCli||C())return g();if((0,n.FZ)(c))throw new l.pz("Refusing to write a redacted OpenClaw secret back to config.","auth");let h=(0,f.vC)(b);try{let g,h=ac("config.get",aa,await this.callNative("config.get",{},d,{safety:"read"})),i=(0,n.Pu)((0,n.LK)(h.config)?h.config:{});e(i);let j=await this.callNative("config.schema.lookup",{path:b},d,{safety:"read"}).catch(()=>this.callNative("config.schema",{},d,{safety:"read"})).catch(()=>null),k=(0,f.RE)(j),m="string"==typeof h.hash&&h.hash.trim()?h.hash:void 0,o=(0,f.LF)(b,"config.unset"===a?null:c),p={raw:JSON.stringify(o)};m&&(p.baseHash=m);let q="config.patch";try{g=await this.callNative("config.patch",p,d,{safety:"mutation"})}catch(a){if(!(0,A.lH)(a))throw a;try{let a={raw:JSON.stringify(i)};m&&(a.baseHash=m),g=await this.callNative("config.apply",a,d,{safety:"mutation"}),q="config.apply"}catch(c){if(!(0,A.lH)(c))throw c;if((0,n.FZ)(h.config))throw new l.pz("OpenClaw returned redacted secrets in the config snapshot; refusing full Gateway config overwrite.","auth",{cause:c});let b={raw:JSON.stringify(i)};m&&(b.baseHash=m);try{g=await this.callNative("config.set",b,d,{safety:"mutation"}),q="config.set"}catch(b){if(!(0,A.lH)(b))throw b;throw a}}}(0,l.Z6)(a),this.clearNativeFailure(a);let r={path:b,reloadKind:k,restartRequired:"restart"===k,hotReloaded:"hot"===k,appliedVia:q,...m?{baseHash:m}:{}};return(0,n.hz)((0,n.LK)(g)?{...g,configMutation:r}:{ok:!0,configMutation:r},{openClawConfig:r})}catch(d){this.options.onNativeFailure?.(d,a);let c=d instanceof l.jl?d.method:a;if(!(F(d,c,{safety:"mutation"})||(0,f.c0)(d,b)))throw this.cliFallbackDisabledError(c,d);return this.recordGatewayFallback(a,d),g()}finally{h&&this.close(`${a}:${b}`)}}}function am(a,b){let c=(0,l.$g)(a).message.replace(/\s+/g," ").trim();if(!c||!/\bagent\b/i.test(c)||!/\bnot found\b/i.test(c))return!1;let d=b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return RegExp(`\\bagent\\s+["'\`]?${d}["'\`]?\\s+not\\s+found\\b`,"i").test(c)}function an(a,b){return new l.pz(`OpenClaw Gateway has not loaded agent "${a}" yet. Restart the Gateway or refresh AgentOS after OpenClaw finishes loading agents, then retry chat.`,"conflict",{cause:b})}function ao(a,b){if(!a)return!1;if(!b)return!0;let c=Date.parse(a),d=Date.parse(b);return!(Number.isFinite(c)&&Number.isFinite(d))||c>=d}function ap(a){return(0,n.LK)(a)?a:void 0}},38699:(a,b,c)=>{"use strict";c.d(b,{p:()=>l});var d=c(88366),e=c(78446),f=c(17929),g=c(24117);function h(a){let b=["agent","--agent",a.agentId];return a.sessionId&&b.push("--session-id",a.sessionId),a.local&&b.push("--local"),b.push("--message",a.message,"--thinking",a.thinking??"medium","--timeout",String(a.timeoutSeconds??45),"--json"),b}function i(a={}){let b,c,d=a.key?.trim()||a.sessionKey?.trim();if(d)return{key:d};let e=a.sessionId?.trim(),f=a.agentId?.trim();return{agentId:f||void 0,sessionId:e||void 0,key:f||e?(b=e?.trim(),c=f?.trim()||"main",b?`agent:${c}:explicit:${b}`:`agent:${c}:main`):void 0}}function j(a,b,c){var d;let e="number"==typeof(d=c)&&Number.isFinite(d)?String(d):"boolean"==typeof d?d?"true":"false":"string"==typeof d&&d.trim().length>0?d.trim():null;null!==e&&a.push(b,e)}function k(a){return"object"==typeof a&&null!==a}class l{getDiagnostics(){return{mode:"cli",gatewayMode:"cli-forced",statusLabel:"CLI fallback forced",recovery:"Unset the CLI-forced Gateway mode and restart AgentOS to use the native OpenClaw Gateway.",connectionState:"cli-forced",protocolVersion:null,protocolRange:g.aj,fallbackCounts:{},fallbackTotal:0,recentFallbackDiagnostics:[],lastNativeError:null,lastNativeFailureAt:null,lastConnectedAt:null,lastDisconnectedAt:null}}getHealth(a={}){return this.call("health",{},a)}getStatus(a={}){return(0,d.VP)(["status","--json"],a)}getUpdateStatus(a={}){return(0,d.VP)(["update","status","--json"],a)}getGatewayStatus(a={}){return(0,d.VP)(["gateway","status","--json"],a)}getModelStatus(a={}){return(0,d.VP)(["models","status","--json"],a)}getAgentModelStatus(a,b={}){return(0,d.VP)(["models","status","--agent",a.agentId,"--json"],b)}setModelAuthOrder(a,b={}){return(0,d.zB)(["models","auth","order","set","--provider",a.provider,"--agent",a.agentId,...a.profileIds],b)}async listAgents(a={}){return{agents:(await (0,d.VP)(["agents","list","--json"],a)).map(a=>({id:a.id,name:a.name,identity:{name:a.identityName,emoji:a.identityEmoji},workspace:a.workspace,model:a.model?{primary:a.model}:void 0}))}}listSessions(a={},b={}){return this.call("sessions.list",{...a},b)}describeSession(a={},b={}){return this.call("sessions.describe",{...i(a),includeMessages:a.includeMessages,limit:a.limit},b)}async getSessionHistory(a={},b={}){let c=null;for(let[d,e]of[["chat.history",function(a={}){return{sessionKey:i(a).key,limit:a.limit,cursor:a.cursor??void 0}}(a)],["sessions.preview",function(a={}){let b=i(a).key;return{key:b,sessionKey:b,sessionKeys:b?[b]:void 0,limit:a.limit,cursor:a.cursor??void 0}}(a)],["sessions.history",function(a={}){return{...i(a),limit:a.limit,cursor:a.cursor??void 0}}(a)]])try{return await this.call(d,e,b)}catch(a){c=a}throw c}async exportSession(a={},b={}){let c=null,d=i(a);for(let e of["sessions.get","sessions.describe","sessions.export"])try{let c=await this.call(e,"sessions.export"===e?{...d,format:a.format}:d,b);return function(a,b){if("string"==typeof b.content)return{...b,format:a.format??("string"==typeof b.format?b.format:"json")};let c=a.format??"json";return{...b,format:c,session:b.session??b,content:"json"===c?JSON.stringify(b):void 0}}(a,c)}catch(a){c=a}throw c}listTasks(a={},b={}){return this.call("tasks.list",{...a},b)}getTask(a,b={}){return this.call("tasks.get",{...a},b)}assignTask(a,b={}){return this.call("tasks.assign",{...a,reason:a.reason??void 0},b)}cancelTask(a,b={}){return this.call("tasks.cancel",{taskId:a.taskId,reason:a.reason??void 0},b)}listArtifacts(a={},b={}){return this.call("artifacts.list",function(a={}){return{taskId:a.taskId?.trim()||void 0,runId:a.runId?.trim()||void 0,sessionKey:a.sessionKey?.trim()||a.sessionId?.trim()||void 0}}(a),b)}getArtifact(a,b={}){return this.call("artifacts.get",{...a},b)}async putArtifact(a,b={}){throw Error("Artifact writes are not part of the OpenClaw 2026.5.28 Gateway baseline; native Gateway support must be explicitly advertised before AgentOS can use artifacts.put.")}async deleteArtifact(a,b={}){throw Error("Artifact deletion is not part of the OpenClaw 2026.5.28 Gateway baseline; native Gateway support must be explicitly advertised before AgentOS can use artifacts.delete.")}async getRuntimeSnapshot(a={},b={}){let c=!1!==a.includeSessions,d=!1!==a.includeTasks,e=!1!==a.includeArtifacts,f={taskId:a.taskId,runId:a.runId,sessionKey:a.sessionKey,sessionId:a.sessionId},g=e&&function(a={}){return!!(a.taskId?.trim()||a.runId?.trim()||a.sessionKey?.trim()||a.sessionId?.trim())}(f),h=await Promise.allSettled([c?this.listSessions({limit:a.limit,agentId:a.agentId},b):Promise.resolve(null),d?this.listTasks({limit:a.limit,agentId:a.agentId,workspace:a.workspace},b):Promise.resolve(null),g?this.listArtifacts(f,b):Promise.resolve(null)]),i=h.filter((a,b)=>[c,d,g][b]),j=i.filter(a=>"rejected"===a.status);if(i.length>0&&j.length===i.length)throw j[0]?.reason??Error("OpenClaw Gateway runtime snapshot failed.");let[k,l,m]=h,n={sessions:"fulfilled"===k.status?k.value?.sessions??[]:[],tasks:"fulfilled"===l.status?l.value?.tasks??[]:[],artifacts:"fulfilled"===m.status?m.value?.artifacts??[]:[]};return j.length>0&&(n.metadata={runtimeSnapshot:{partial:!0,errors:j.map(a=>{var b;return(b=a.reason)instanceof Error?b.message:String(b||"Unknown OpenClaw Gateway snapshot error.")})}}),n}getToolsCatalog(a={},b={}){return this.call("tools.catalog",{...a},b)}getEffectiveTools(a={},b={}){return this.call("tools.effective",{...a},b)}invokeTool(a,b={}){return this.call("tools.invoke",{...a},b)}async subscribeRuntimeEvents(a,b,c={}){throw Error("OpenClaw runtime event subscriptions require the native Gateway transport.")}getChannelStatus(a={},b={}){return this.call("channels.status",{...a},b)}getChannelLogs(a,b={}){let c=["channels","logs","--channel",a.channel,"--json"];return"number"==typeof a.lines&&Number.isFinite(a.lines)&&a.lines>0&&c.push("--lines",String(a.lines)),(0,d.VP)(c,b)}provisionChannelAccount(a,b={}){let c=["channels","add","--channel",a.channel];return j(c,"--account",a.account),j(c,"--token",a.token),j(c,"--bot-token",a.botToken),j(c,"--webhook-url",a.webhookUrl),j(c,"--name",a.name),(0,d.zB)(c,b)}removeChannelAccount(a,b={}){let c=["channels","remove","--channel",a.channel,"--account",a.account];return a.delete&&c.push("--delete"),(0,d.zB)(c,b)}setupGmailWebhook(a,b={}){var c,e,f;let g,h,i,l;return(0,d.zB)((g=a.config??{},h=["webhooks","gmail","setup","--account",a.account],i=k(g.serve)?g.serve:{},l=k(g.tailscale)?g.tailscale:{},j(h,"--project",g.project),j(h,"--topic",g.topic),j(h,"--subscription",g.subscription),j(h,"--label",g.label),j(h,"--hook-url",g.hookUrl),j(h,"--hook-token",g.hookToken),j(h,"--push-token",g.pushToken),j(h,"--bind",i.bind),j(h,"--port",i.port),j(h,"--path",i.path),c=h,e="--include-body",(!0===(f=g.includeBody)||"true"===f)&&c.push(e),j(h,"--max-bytes",g.maxBytes),j(h,"--renew-minutes",g.renewEveryMinutes),j(h,"--tailscale",l.mode),j(h,"--tailscale-path",l.path),j(h,"--tailscale-target",l.target),j(h,"--push-endpoint",g.pushEndpoint),h),b)}listSkills(a={}){let b=["skills","list"];return a.eligible&&b.push("--eligible"),b.push("--json"),(0,d.VP)(b,a)}listPlugins(a={}){return(0,d.VP)(["plugins","list","--json"],a)}listModels(a={},b={}){let c=["models","list"];return a.all&&c.push("--all"),c.push("--json"),a.provider&&c.push("--provider",a.provider),(0,d.VP)(c,b)}scanModels(a={}){let b=["models","scan","--json"];return a.yes&&b.push("--yes"),a.noInput&&b.push("--no-input"),a.noProbe&&b.push("--no-probe"),(0,d.VP)(b,a)}probeGateway(a={}){return(0,d.VP)(["gateway","probe","--json"],a)}controlGateway(a,b={}){let c=["gateway",a];return"restart"===a&&b.force&&c.push("--force"),c.push("--json"),(0,d.VP)(c,b)}async approveDeviceAccess(a={},b={}){if(!1!==a.latest&&!a.requestId){let c=function(a){let b=Array.isArray(a.pending)?a.pending:[],c=null;for(let a of b){if(!a||"object"!=typeof a)continue;let b="string"==typeof a.requestId&&a.requestId.trim()?a.requestId.trim():null;if(!b)continue;let d="number"==typeof a.ts&&Number.isFinite(a.ts)?a.ts:0;(!c||d>c.ts)&&(c={requestId:b,ts:d})}return c?.requestId??null}(await (0,d.VP)(["devices","list","--json"],b));if(!c)throw Error("No pending OpenClaw device access request found.");return this.approveDeviceAccess({...a,latest:!1,requestId:c},b)}let c=["devices","approve"];for(let b of(a.requestId&&c.push(a.requestId),a.scopes??[]))j(c,"--scope",b);return c.push("--json"),(0,d.VP)(c,b)}call(a,b={},c={}){return(0,d.VP)(["gateway","call",a,"--params",JSON.stringify(b),"--json"],c)}async getConfig(a,b={}){return(0,d.VP)(["config","get",a,"--json"],b).catch(()=>null)}async getConfigSchema(a={}){return this.call("config.schema",{},a).catch(()=>null)}async lookupConfigSchema(a,b={}){return this.call("config.schema.lookup",{path:a.path},b).catch(()=>null)}async hasConfig(a,b={}){try{return await (0,d.zB)(["config","get",a,"--json"],b),!0}catch(a){if((0,e.t)(a).includes("Config path not found"))return!1;throw a}}setConfig(a,b,c={}){if((0,f.FZ)(b))throw Error("Refusing to write a redacted OpenClaw secret back to config.");let e=["config","set",a,"string"==typeof b?b:JSON.stringify(b)];return c.strictJson&&e.push("--strict-json"),(0,d.zB)(e,c)}unsetConfig(a,b={}){return(0,d.zB)(["config","unset",a],b)}addAgent(a,b={}){let c=["agents","add",a.id,"--workspace",a.workspace,"--agent-dir",a.agentDir,"--non-interactive","--json"];return a.model&&c.push("--model",a.model),(0,d.zB)(c,b)}async updateAgent(a,b={}){return{stdout:JSON.stringify({ok:!0,fallback:"application-config"}),stderr:""}}setAgentIdentity(a,b={}){let c;return(0,d.zB)((j(c=["agents","set-identity","--agent",a.agentId,"--workspace",a.workspace,"--identity-file",a.identityFile,"--json"],"--name",a.name),j(c,"--emoji",a.emoji),j(c,"--theme",a.theme),j(c,"--avatar",a.avatar),c),b)}deleteAgent(a,b={}){return(0,d.zB)(["agents","delete",a,"--force","--json"],b)}provisionAutomation(a,b={}){let c;return(0,d.zB)((c=["cron","add","--name",a.name,"--description",a.description||a.name,"--agent",a.agentId,"--message",a.message,"--thinking",a.thinking||"medium","--timeout-seconds",String(a.timeoutSeconds??120),"--json"],"every"===a.schedule.kind?c.push("--every",a.schedule.value):c.push("--cron",a.schedule.value),a.announce?.channel&&(c.push("--announce","--channel",a.announce.channel),j(c,"--to",a.announce.target)),c),b)}runAgentTurn(a,b={}){return(0,d.VP)(h(a),b)}abortAgentTurn(a,b={}){return this.call("chat.abort",{runId:a.runId??void 0,sessionId:a.sessionId??void 0,agentId:a.agentId??void 0,reason:a.reason??void 0},b)}async steerSession(a,b={}){throw Error("Native OpenClaw Gateway is required for sessions.steer.")}async injectChat(a,b={}){throw Error("Native OpenClaw Gateway is required for chat.inject.")}streamAgentTurn(a,b={},c={}){return(0,d.JZ)(h(a),{...c,...b})}tailLogs(a={},b={}){return this.call("logs.tail",{...a},b)}listExecApprovals(a={},b={}){return this.call("exec.approval.list",{...a},b)}resolveExecApproval(a,b={}){return this.call("exec.approval.resolve",{approvalId:a.approvalId,decision:a.decision,reason:a.reason??void 0},b)}getCronStatus(a={}){return this.call("cron.status",{},a)}listCronJobs(a={},b={}){return this.call("cron.list",{...a},b)}}},39503:(a,b,c)=>{"use strict";c.d(b,{rw:()=>g});var d=c(7565);class e{constructor(a=d.Xz){this.getClient=a}getHealth(a={}){return this.getClient().getHealth(a)}getStatus(a={}){return this.getClient().getStatus(a)}getUpdateStatus(a={}){return this.getClient().getUpdateStatus(a)}getGatewayStatus(a={}){return this.getClient().getGatewayStatus(a)}getModelStatus(a={}){return this.getClient().getModelStatus(a)}getAgentModelStatus(a,b={}){return this.getClient().getAgentModelStatus(a,b)}setModelAuthOrder(a,b={}){return this.getClient().setModelAuthOrder(a,b)}listAgents(a={}){return this.getClient().listAgents(a)}listSessions(a={},b={}){return this.getClient().listSessions(a,b)}describeSession(a={},b={}){return this.getClient().describeSession(a,b)}getSessionHistory(a={},b={}){return this.getClient().getSessionHistory(a,b)}exportSession(a={},b={}){return this.getClient().exportSession(a,b)}listTasks(a={},b={}){return this.getClient().listTasks(a,b)}getTask(a,b={}){return this.getClient().getTask(a,b)}assignTask(a,b={}){return this.getClient().assignTask(a,b)}cancelTask(a,b={}){return this.getClient().cancelTask(a,b)}listArtifacts(a={},b={}){return this.getClient().listArtifacts(a,b)}getArtifact(a,b={}){return this.getClient().getArtifact(a,b)}putArtifact(a,b={}){return this.getClient().putArtifact(a,b)}deleteArtifact(a,b={}){return this.getClient().deleteArtifact(a,b)}getRuntimeSnapshot(a={},b={}){return this.getClient().getRuntimeSnapshot(a,b)}getToolsCatalog(a={},b={}){return this.getClient().getToolsCatalog(a,b)}getEffectiveTools(a={},b={}){return this.getClient().getEffectiveTools(a,b)}invokeTool(a,b={}){return this.getClient().invokeTool(a,b)}subscribeRuntimeEvents(a,b,c={}){return this.getClient().subscribeRuntimeEvents(a,b,c)}getChannelStatus(a={},b={}){return this.getClient().getChannelStatus(a,b)}getChannelLogs(a,b={}){return this.getClient().getChannelLogs(a,b)}provisionChannelAccount(a,b={}){return this.getClient().provisionChannelAccount(a,b)}removeChannelAccount(a,b={}){return this.getClient().removeChannelAccount(a,b)}setupGmailWebhook(a,b={}){return this.getClient().setupGmailWebhook(a,b)}listModels(a={},b={}){return this.getClient().listModels(a,b)}listSkills(a={}){return this.getClient().listSkills(a)}listPlugins(a={}){return this.getClient().listPlugins(a)}scanModels(a={}){return this.getClient().scanModels(a)}getConfig(a,b={}){return this.getClient().getConfig(a,b)}getConfigSchema(a={}){return this.getClient().getConfigSchema?.(a)??Promise.resolve(null)}lookupConfigSchema(a,b={}){return this.getClient().lookupConfigSchema?.(a,b)??Promise.resolve(null)}hasConfig(a,b={}){return this.getClient().hasConfig(a,b)}setConfig(a,b,c={}){return this.getClient().setConfig(a,b,c)}unsetConfig(a,b={}){return this.getClient().unsetConfig(a,b)}addAgent(a,b={}){return this.getClient().addAgent(a,b)}updateAgent(a,b={}){return this.getClient().updateAgent?.(a,b)??Promise.resolve({stdout:JSON.stringify({ok:!0,fallback:"application-config"}),stderr:""})}setAgentIdentity(a,b={}){return this.getClient().setAgentIdentity(a,b)}deleteAgent(a,b={}){return this.getClient().deleteAgent(a,b)}provisionAutomation(a,b={}){return this.getClient().provisionAutomation(a,b)}runAgentTurn(a,b={}){return this.getClient().runAgentTurn(a,b)}abortAgentTurn(a,b={}){let c=this.getClient();return c.abortAgentTurn?c.abortAgentTurn(a,b):c.call("chat.abort",{...a},b)}steerSession(a,b={}){let c=this.getClient();if(!c.steerSession)throw Error("Native OpenClaw Gateway is required for sessions.steer.");return c.steerSession(a,b)}injectChat(a,b={}){let c=this.getClient();if(!c.injectChat)throw Error("Native OpenClaw Gateway is required for chat.inject.");return c.injectChat(a,b)}streamAgentTurn(a,b={},c={}){return this.getClient().streamAgentTurn(a,b,c)}probeGateway(a={}){return this.getClient().probeGateway(a)}controlGateway(a,b={}){return this.getClient().controlGateway(a,b)}approveDeviceAccess(a={},b={}){return this.getClient().approveDeviceAccess(a,b)}call(a,b={},c={}){return this.getClient().call(a,b,c)}tailLogs(a={},b={}){let c=this.getClient();return c.tailLogs?.(a,b)??c.call("logs.tail",{...a},b)}listExecApprovals(a={},b={}){let c=this.getClient();return c.listExecApprovals?.(a,b)??c.call("exec.approval.list",{...a},b)}resolveExecApproval(a,b={}){let c=this.getClient();return c.resolveExecApproval?.(a,b)??c.call("exec.approval.resolve",{approvalId:a.approvalId,decision:a.decision,reason:a.reason??void 0},b)}getCronStatus(a={}){let b=this.getClient();return b.getCronStatus?.(a)??b.call("cron.status",{},a)}listCronJobs(a={},b={}){let c=this.getClient();return c.listCronJobs?.(a,b)??c.call("cron.list",{...a},b)}}let f=null;function g(){return f||(f=new e),f}},40218:()=>{},65493:(a,b,c)=>{"use strict";c.d(b,{Av:()=>j,Dq:()=>l,Hi:()=>q,P5:()=>p,iG:()=>e,jW:()=>o,rp:()=>k,zS:()=>d});let d=[{id:"health",label:"Gateway health",methods:["health","status"],baseline:"required"},{id:"modelAuthOrder",label:"Model auth order",methods:["models.authOrder.set","models.auth.order.set"],baseline:"experimental"},{id:"logsTail",label:"Gateway logs",methods:["logs.tail"],baseline:"required"},{id:"configSchemaLookup",label:"Config schema lookup",methods:["config.schema.lookup","config.schema"],baseline:"required"},{id:"configPatch",label:"Config patch",methods:["config.patch","config.apply","config.set"],baseline:"required"},{id:"sessionLifecycle",label:"Session lifecycle",methods:["sessions.create","sessions.patch","sessions.steer"],baseline:"optional"},{id:"agentCreate",label:"Agent creation",methods:["agents.create"],baseline:"required"},{id:"agentUpdate",label:"Agent update",methods:["agents.update"],baseline:"required"},{id:"agentIdentity",label:"Agent identity sync",methods:["agents.identity.set","agents.setIdentity","agents.set-identity"],baseline:"experimental"},{id:"agentDelete",label:"Agent removal",methods:["agents.delete"],baseline:"required"},{id:"missionDispatch",label:"Mission dispatch",methods:["chat.send","sessions.send"],baseline:"required"},{id:"missionStream",label:"Mission event stream",methods:["sessions.subscribe","sessions.messages.subscribe"],events:["chat","agent","session.message","session.tool"],baseline:"optional"},{id:"chatControl",label:"Chat control",methods:["chat.abort","chat.inject"],baseline:"optional"},{id:"agentWait",label:"Agent wait",methods:["agent.wait"],baseline:"optional"},{id:"sessionHistory",label:"Session history",methods:["chat.history","sessions.preview","sessions.get","sessions.describe"],baseline:"optional"},{id:"taskEvents",label:"Task events",methods:["tasks.subscribe","tasks.get","tasks.list"],events:["task","task.updated","task.completed"],baseline:"optional"},{id:"taskCancel",label:"Task cancellation",methods:["tasks.cancel"],baseline:"optional"},{id:"artifacts",label:"Artifact sync",methods:["artifacts.list","artifacts.get","artifacts.download"],events:["artifact","artifact.updated"],baseline:"optional"},{id:"runtimeSnapshot",label:"Runtime snapshot",methods:["sessions.list","tasks.list"],baseline:"required"},{id:"tools",label:"Tool catalog",methods:["tools.catalog","tools.effective","tools.invoke"],fallbackAllowed:!1,baseline:"optional"},{id:"execApprovals",label:"Execution approvals",methods:["exec.approval.list","exec.approval.get","exec.approval.resolve","exec.approvals.get","exec.approvals.set"],baseline:"optional"},{id:"devicePairList",label:"Device pairing list",methods:["device.pair.list","devices.list","gateway.devices.list"],baseline:"optional"},{id:"deviceApproval",label:"Device access repair",methods:["device.pair.approve","devices.approve","gateway.devices.approve"],baseline:"optional"},{id:"cronRead",label:"Automation status",methods:["cron.list","cron.status"],baseline:"optional"},{id:"channels",label:"Channel status",methods:["channels.status"],baseline:"required"},{id:"channelLogs",label:"Channel logs",methods:["channels.logs"],baseline:"optional"},{id:"channelProvisioning",label:"Channel provisioning",methods:["channels.add","channels.create","channels.configure"],baseline:"experimental"},{id:"channelRemoval",label:"Channel removal",methods:["channels.remove","channels.delete"],baseline:"experimental"},{id:"gmailProvisioning",label:"Gmail webhook setup",methods:["webhooks.gmail.setup","gmail.setup"],baseline:"experimental"},{id:"automationProvisioning",label:"Automation provisioning",methods:["cron.add","cron.create"],baseline:"experimental"},{id:"skills",label:"Skill status",methods:["skills.status"],baseline:"optional"},{id:"updates",label:"Update status",methods:["update.status","update.run","status"],baseline:"optional"}],e="2026.5.28",f=["health","status","models.list","models.authStatus","agents.list","agents.create","agents.update","agents.delete","sessions.list","chat.send","config.get","config.schema","config.schema.lookup","config.patch","config.apply","channels.status","logs.tail"],g=["agent.identity.get","agent.wait","artifacts.download","artifacts.get","artifacts.list","chat.abort","chat.history","chat.inject","channels.logout","channels.start","channels.stop","cron.list","cron.status","devices.list","exec.approval.get","exec.approval.list","exec.approval.request","exec.approval.resolve","exec.approval.waitDecision","plugins.uiDescriptors","sessions.abort","sessions.create","sessions.describe","sessions.get","sessions.messages.subscribe","sessions.patch","sessions.preview","sessions.resolve","sessions.steer","sessions.subscribe","skills.detail","skills.install","skills.search","skills.status","skills.update","tasks.cancel","tasks.get","tasks.list","tasks.subscribe","tools.catalog","tools.effective","tools.invoke","update.run","update.status"],h=["diagnostics.stability","agents.files.list","agents.files.get","agents.files.set","plugin.approval.list","plugin.approval.resolve","environment.list","environment.get","environment.create","environment.update","environment.delete","gateway.restart.preflight","gateway.restart.request","models.authOrder.set","models.auth.order.set","agents.identity.set","agents.setIdentity","agents.set-identity","channels.logs","channels.add","channels.create","channels.configure","channels.remove","channels.delete","webhooks.gmail.setup","gmail.setup","cron.add","cron.create"],i=[...f,...g,...h];Array.from(new Set([...d.flatMap(a=>a.methods),...i])).sort(),Array.from(new Set([...f,...g])).sort();let j=Array.from(new Set(f)).sort(),k=Array.from(new Set(g)).sort(),l=Array.from(new Set(h)).sort(),m=new Map(d.map(a=>[a.id,a])),n=new Map(d.flatMap(a=>a.methods.map(b=>[b,a])));function o(a){let b=m.get(a);if(!b)throw Error(`Unknown OpenClaw Gateway compatibility operation: ${a}`);return b}function p(a){return o(a).methods}function q(a){return m.get(a)?.label??n.get(a)?.label??(a.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,a=>a.toUpperCase())||"Gateway operation")}},78446:(a,b,c)=>{"use strict";c.d(b,{D:()=>f,t:()=>e});var d=c(96972);function e(a){if(!a||"object"!=typeof a)return"";let b="stdout"in a?g(a.stdout):"",c="stderr"in a?g(a.stderr):"",e="message"in a&&"string"==typeof a.message?a.message:"";return(0,d.bS)(`${e}
|
|
7
|
+
`)}},c);let j=await this.runAgentTurnNative(a,c);f=j.runId??null,(0,l.Z6)("streamAgentTurn"),this.clearNativeFailure("streamAgentTurn");let k=R(a,c),m=await Promise.race([i,new Promise(a=>globalThis.setTimeout(()=>a(null),k))]);if(m)return m;return await this.waitForAgentTurnNative(a,j,c)??j}catch(e){this.options.onNativeFailure?.(e,"streamAgentTurn");let d=e instanceof l.jl?e.method:"streamAgentTurn";if(!F(e,d,{safety:"mutation"}))throw this.cliFallbackDisabledError(d,e);return this.recordGatewayFallback("streamAgentTurn",e),this.fallback.streamAgentTurn(a,b,c)}finally{e?.close(),h(null)}}async runAgentTurnNative(a,b={}){let c=P(a.agentId,a.sessionId),d="number"==typeof a.timeoutSeconds&&Number.isFinite(a.timeoutSeconds)?Math.max(0,Math.floor(1e3*a.timeoutSeconds)):void 0,e=a.idempotencyKey?.trim()||a.dispatchId||(0,n.r_)();await this.prepareNativeSession(a,c,b);let f={sessionKey:c,sessionId:a.sessionId,message:a.message,thinking:a.thinking,timeoutMs:d,idempotencyKey:e};try{return await this.callNative("chat.send",f,b)}catch(d){if(!(0,A.lH)(d)){if(am(d,a.agentId)){let e=await this.checkGatewayAgentRegistry(a.agentId,b);if("present"===e)try{return await this.prepareNativeSession(a,c,b),await this.callNative("chat.send",f,b)}catch(b){if(am(b,a.agentId))throw ao(a.agentId,b);throw b}if("missing"===e)throw ao(a.agentId,d)}throw d}}return this.callNative("sessions.send",{agentId:a.agentId,key:c,message:a.message,thinking:a.thinking,timeoutMs:d,idempotencyKey:e},b)}async checkGatewayAgentRegistry(a,b){try{var c;let d,e=ac("agents.list",W,await this.callNative("agents.list",{},{...b,timeoutMs:5e3},{safety:"read",timeoutMs:5e3}));return(0,l.Z6)("agents.list"),this.clearNativeFailure("agents.list"),(c=e,(d=a.trim())&&(c.defaultId===d||c.mainKey===d||c.agents.some(a=>a.id===d)))?"present":"missing"}catch{return"unknown"}}async prepareNativeSession(a,b,c){if(a.sessionId||a.dispatchId){try{await this.callNative("sessions.create",{key:b,agentId:a.agentId},c,{safety:"mutation"}),(0,l.Z6)("sessions.create")}catch(a){if(!S(a))throw a}try{await this.callNative("sessions.patch",{key:b,metadata:{agentId:a.agentId,sessionId:a.sessionId??void 0,workspace:a.workspace??void 0,dispatchId:a.dispatchId??void 0,local:a.local??void 0,origin:a.dispatchId?"agentos-mission-dispatch":"agentos-direct-chat"}},c,{safety:"mutation"}),(0,l.Z6)("sessions.patch")}catch(a){if(!S(a))throw a}}}async waitForAgentTurnNative(a,b,c){if(!b.runId)return null;let d=R(a,c),e=Math.max(d+5e3,5e3);try{let f=await this.callNative("agent.wait",an(a,b.runId,d),{...c,timeoutMs:e},{safety:"read",timeoutMs:e});return(0,l.Z6)("agent.wait"),f}catch(i){var f;let g,h;if(h=(f=i)instanceof Error?f.message:String(f||""),/agent\.wait/i.test(h)&&/must have required property ['"]?(sessionKey|sessionId|key)['"]?/i.test(h)){let f=await this.callNative("agent.wait",an(a,b.runId,d,{includeSession:!0}),{...c,timeoutMs:e},{safety:"read",timeoutMs:e});return(0,l.Z6)("agent.wait"),f}if("unsupported"!==(g=(0,l.$g)(i).kind)&&"timeout"!==g&&"malformed-response"!==g)throw i;return null}}tailLogs(a={},b={}){return this.gatewayFirst("logs.tail",{...a},b,a=>(0,n.LK)(a)?a:{},()=>this.fallback.tailLogs?.(a,b)??this.fallback.call("logs.tail",{...a},b))}listExecApprovals(a={},b={}){return this.gatewayFirst("exec.approval.list",{...a},b,a=>(0,n.LK)(a)?a:{},()=>this.fallback.listExecApprovals?.(a,b)??this.fallback.call("exec.approval.list",{...a},b))}resolveExecApproval(a,b={}){return this.gatewayFirst("exec.approval.resolve",{approvalId:a.approvalId,decision:a.decision,reason:a.reason??void 0},b,a=>(0,n.LK)(a)?a:{},()=>this.fallback.resolveExecApproval?.(a,b)??this.fallback.call("exec.approval.resolve",{approvalId:a.approvalId,decision:a.decision,reason:a.reason??void 0},b))}getCronStatus(a={}){return this.gatewayFirst("cron.status",{},a,a=>(0,n.LK)(a)?a:{},()=>this.fallback.getCronStatus?.(a)??this.fallback.call("cron.status",{},a))}listCronJobs(a={},b={}){return this.gatewayFirst("cron.list",{...a},b,a=>(0,n.LK)(a)?a:{},()=>this.fallback.listCronJobs?.(a,b)??this.fallback.call("cron.list",{...a},b))}async subscribeRuntimeEvents(a,b,c={}){if(c.forceCli||this.options.forceCli||C())return this.fallback.subscribeRuntimeEvents(a,b,c);let d=[a.includeSessions,a.includeTasks,a.includeArtifacts,a.includeApprovals].some(a=>void 0!==a);try{let e=await this.subscribeNativeEvents({subscribeSessions:a.includeSessions??!d,subscribeTasks:a.includeTasks??(!!a.taskIds?.length||void 0),subscribeArtifacts:a.includeArtifacts,subscribeApprovals:a.includeApprovals,sessionKeys:a.sessionKeys,taskIds:a.taskIds,artifactIds:a.artifactIds},b,c);return(0,l.Z6)("runtime.subscribe"),this.clearNativeFailure("runtime.subscribe"),e}catch(d){if(this.options.onNativeFailure?.(d,"runtime.subscribe"),!F(d,"runtime.subscribe",{safety:"read",timeoutMs:c.timeoutMs}))throw this.cliFallbackDisabledError("runtime.subscribe",d);return this.recordGatewayFallback("runtime.subscribe",d),this.fallback.subscribeRuntimeEvents(a,b,c)}}async callNative(a,b={},c={},d=E(a,c)){let e=D(d.timeoutMs??c.timeoutMs??this.options.timeoutMs,a);return this.connection.request(a,b,c,e)}async probeNativeHandshake(a={}){let b=D(a.timeoutMs??this.options.timeoutMs,m.JV);return this.connection.probe(a,b)}async subscribeNativeEvents(a,b,c={}){let d=D(c.timeoutMs??this.options.timeoutMs,"sessions.subscribe");return this.connection.subscribe(a,b,c,d)}async gatewayFirstSessionHistory(a,b){if(this.options.forceCli||C())return this.fallback.getSessionHistory(a,b);let c=[["chat.history",function(a={}){return{sessionKey:Q(a).key,limit:a.limit,cursor:a.cursor??void 0}}(a)],["sessions.preview",function(a={}){let b=Q(a).key;return{key:b,sessionKey:b,sessionKeys:b?[b]:void 0,limit:a.limit,cursor:a.cursor??void 0}}(a)],["sessions.history",function(a={}){return{...Q(a),limit:a.limit,cursor:a.cursor??void 0}}(a)]],d=null;for(let[e,f]of c){let g=E(e,b);try{let a=ad(e,await this.callNative(e,f,b,g));for(let[a]of c)(0,l.Z6)(a),this.clearNativeFailure(a);return a}catch(c){if(this.options.onNativeFailure?.(c,e),(0,A.lH)(c)){d=c;continue}if(!F(c,e,g))throw this.cliFallbackDisabledError(e,c);return this.recordGatewayFallback(e,c),this.fallback.getSessionHistory(a,b)}}return this.recordGatewayFallback("chat.history",d??new l.As("OpenClaw Gateway does not advertise a compatible session history method.",{kind:"unsupported"})),this.fallback.getSessionHistory(a,b)}async gatewayFirstSessionExport(a,b){if(this.options.forceCli||C())return this.fallback.exportSession(a,b);let c=Q(a),d=[["sessions.get",c],["sessions.describe",c],["sessions.export",{...c,format:a.format}]],e=null;for(let[c,f]of d){let g=E(c,b);try{let e=ad(c,await this.callNative(c,f,b,g));for(let[a]of d)(0,l.Z6)(a),this.clearNativeFailure(a);return function(a,b){if("string"==typeof b.content)return{...b,format:a.format??("string"==typeof b.format?b.format:"json")};let c=a.format??"json";return{...b,format:c,session:b.session??b,content:"json"===c?JSON.stringify(b):void 0}}(a,e)}catch(d){if(this.options.onNativeFailure?.(d,c),(0,A.lH)(d)){e=d;continue}if(!F(d,c,g))throw this.cliFallbackDisabledError(c,d);return this.recordGatewayFallback(c,d),this.fallback.exportSession(a,b)}}return this.recordGatewayFallback("sessions.get",e??new l.As("OpenClaw Gateway does not advertise a compatible session export method.",{kind:"unsupported"})),this.fallback.exportSession(a,b)}async gatewayFirst(a,b,c,d,e,f=E(a,c)){if(this.options.forceCli||C())return e();try{let e=d(await this.callNative(a,b,c,f));return(0,l.Z6)(a),this.clearNativeFailure(a),e}catch(b){if(this.options.onNativeFailure?.(b,a),!F(b,a,f))throw this.cliFallbackDisabledError(a,b);return this.recordGatewayFallback(a,b),e()}}async gatewayFirstCompatible(a,b,c,d,f){let g=(0,e.jW)(a);if(this.options.forceCli||C()){if(!1===g.fallbackAllowed)throw new l.pz(`${g.label} requires native OpenClaw Gateway support; CLI fallback is disabled for this operation.`,"unsupported");return f()}let h=(0,e.P5)(a),i=null;for(let a of h){let e=E(a,c);try{let f=d(await this.callNative(a,b,c,e));for(let a of h)(0,l.Z6)(a),this.clearNativeFailure(a);return f}catch(b){if(this.options.onNativeFailure?.(b,a),(0,A.lH)(b)){i=b;continue}if(!1===g.fallbackAllowed||!F(b,a,e))throw this.cliFallbackDisabledError(a,b);return this.recordGatewayFallback(a,b),f()}}let j=h[0]??a;if(!1===g.fallbackAllowed)throw this.cliFallbackDisabledError(j,i??new l.As(`OpenClaw Gateway does not advertise a compatible method for ${a}.`,{kind:"unsupported"}));return this.recordGatewayFallback(j,i??new l.As(`OpenClaw Gateway does not advertise a compatible method for ${a}.`,{kind:"unsupported"})),f()}async gatewayConfigMutationFirst(a,b,c,d,e,g){if(this.options.forceCli||C())return g();if((0,n.FZ)(c))throw new l.pz("Refusing to write a redacted OpenClaw secret back to config.","auth");let h=(0,f.vC)(b);try{let g,h=ac("config.get",aa,await this.callNative("config.get",{},d,{safety:"read"})),i=(0,n.Pu)((0,n.LK)(h.config)?h.config:{});e(i);let j=await this.callNative("config.schema.lookup",{path:b},d,{safety:"read"}).catch(()=>this.callNative("config.schema",{},d,{safety:"read"})).catch(()=>null),k=(0,f.RE)(j),m="string"==typeof h.hash&&h.hash.trim()?h.hash:void 0,o=(0,f.LF)(b,"config.unset"===a?null:c),p={raw:JSON.stringify(o)};m&&(p.baseHash=m);let q="config.patch";try{g=await this.callNative("config.patch",p,d,{safety:"mutation"})}catch(a){if(!(0,A.lH)(a))throw a;try{let a={raw:JSON.stringify(i)};m&&(a.baseHash=m),g=await this.callNative("config.apply",a,d,{safety:"mutation"}),q="config.apply"}catch(c){if(!(0,A.lH)(c))throw c;if((0,n.FZ)(h.config))throw new l.pz("OpenClaw returned redacted secrets in the config snapshot; refusing full Gateway config overwrite.","auth",{cause:c});let b={raw:JSON.stringify(i)};m&&(b.baseHash=m);try{g=await this.callNative("config.set",b,d,{safety:"mutation"}),q="config.set"}catch(b){if(!(0,A.lH)(b))throw b;throw a}}}(0,l.Z6)(a),this.clearNativeFailure(a);let r={path:b,reloadKind:k,restartRequired:"restart"===k,hotReloaded:"hot"===k,appliedVia:q,...m?{baseHash:m}:{}};return(0,n.hz)((0,n.LK)(g)?{...g,configMutation:r}:{ok:!0,configMutation:r},{openClawConfig:r})}catch(d){this.options.onNativeFailure?.(d,a);let c=d instanceof l.jl?d.method:a;if(!(F(d,c,{safety:"mutation"})||(0,f.c0)(d,b)))throw this.cliFallbackDisabledError(c,d);return this.recordGatewayFallback(a,d),g()}finally{h&&this.close(`${a}:${b}`)}}}function am(a,b){let c=(0,l.$g)(a).message.replace(/\s+/g," ").trim();if(!c||!/\bagent\b/i.test(c)||!/\bnot found\b/i.test(c))return!1;let d=b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return RegExp(`\\bagent\\s+["'\`]?${d}["'\`]?\\s+not\\s+found\\b`,"i").test(c)}function an(a,b,c,d={}){return d.includeSession?{runId:b,sessionKey:P(a.agentId,a.sessionId),sessionId:a.sessionId??void 0,timeoutMs:c}:{runId:b,timeoutMs:c}}function ao(a,b){return new l.pz(`OpenClaw Gateway has not loaded agent "${a}" yet. Restart the Gateway or refresh AgentOS after OpenClaw finishes loading agents, then retry chat.`,"conflict",{cause:b})}function ap(a,b){if(!a)return!1;if(!b)return!0;let c=Date.parse(a),d=Date.parse(b);return!(Number.isFinite(c)&&Number.isFinite(d))||c>=d}function aq(a){return(0,n.LK)(a)?a:void 0}},38699:(a,b,c)=>{"use strict";c.d(b,{p:()=>m});var d=c(88366),e=c(78446),f=c(17929),g=c(24117),h=c(11315);function i(a){let b=["agent","--agent",a.agentId];return a.sessionId&&b.push("--session-id",a.sessionId),a.local&&b.push("--local"),b.push("--message",a.message,"--thinking",a.thinking??"medium","--timeout",String(a.timeoutSeconds??45),"--json"),b}function j(a={}){let b,c,d=a.key?.trim()||a.sessionKey?.trim();if(d)return{key:d};let e=a.sessionId?.trim(),f=a.agentId?.trim();return{agentId:f||void 0,sessionId:e||void 0,key:f||e?(b=e?.trim(),c=f?.trim()||"main",b?`agent:${c}:explicit:${b}`:`agent:${c}:main`):void 0}}function k(a,b,c){var d;let e="number"==typeof(d=c)&&Number.isFinite(d)?String(d):"boolean"==typeof d?d?"true":"false":"string"==typeof d&&d.trim().length>0?d.trim():null;null!==e&&a.push(b,e)}function l(a){return"object"==typeof a&&null!==a}class m{getDiagnostics(){return{mode:"cli",gatewayMode:"cli-forced",statusLabel:"CLI fallback forced",recovery:"Unset the CLI-forced Gateway mode and restart AgentOS to use the native OpenClaw Gateway.",connectionState:"cli-forced",protocolVersion:null,protocolRange:g.aj,fallbackCounts:{},fallbackTotal:0,recentFallbackDiagnostics:[],lastNativeError:null,lastNativeFailureAt:null,lastConnectedAt:null,lastDisconnectedAt:null}}getHealth(a={}){return this.call("health",{},a)}getStatus(a={}){return(0,d.VP)(["status","--json"],a)}getUpdateStatus(a={}){return(0,d.VP)(["update","status","--json"],a)}getGatewayStatus(a={}){return(0,d.VP)(["gateway","status","--json"],a)}getModelStatus(a={}){return(0,d.VP)(["models","status","--json"],a)}getAgentModelStatus(a,b={}){return(0,d.VP)(["models","status","--agent",a.agentId,"--json"],b)}setModelAuthOrder(a,b={}){return(0,d.zB)(["models","auth","order","set","--provider",a.provider,"--agent",a.agentId,...a.profileIds],b)}async listAgents(a={}){return{agents:(await (0,d.VP)(["agents","list","--json"],a)).map(a=>({id:a.id,name:a.name,identity:{name:a.identityName,emoji:a.identityEmoji},workspace:a.workspace,model:a.model?{primary:a.model}:void 0}))}}listSessions(a={},b={}){return this.call("sessions.list",{...a},b)}describeSession(a={},b={}){return this.call("sessions.describe",{...j(a),includeMessages:a.includeMessages,limit:a.limit},b)}async getSessionHistory(a={},b={}){let c=null;for(let[d,e]of[["chat.history",function(a={}){return{sessionKey:j(a).key,limit:a.limit,cursor:a.cursor??void 0}}(a)],["sessions.preview",function(a={}){let b=j(a).key;return{key:b,sessionKey:b,sessionKeys:b?[b]:void 0,limit:a.limit,cursor:a.cursor??void 0}}(a)],["sessions.history",function(a={}){return{...j(a),limit:a.limit,cursor:a.cursor??void 0}}(a)]])try{return await this.call(d,e,b)}catch(a){c=a}throw c}async exportSession(a={},b={}){let c=null,d=j(a);for(let e of["sessions.get","sessions.describe","sessions.export"])try{let c=await this.call(e,"sessions.export"===e?{...d,format:a.format}:d,b);return function(a,b){if("string"==typeof b.content)return{...b,format:a.format??("string"==typeof b.format?b.format:"json")};let c=a.format??"json";return{...b,format:c,session:b.session??b,content:"json"===c?JSON.stringify(b):void 0}}(a,c)}catch(a){c=a}throw c}listTasks(a={},b={}){return this.call("tasks.list",{...a},b)}getTask(a,b={}){return this.call("tasks.get",{...a},b)}assignTask(a,b={}){return this.call("tasks.assign",{...a,reason:a.reason??void 0},b)}cancelTask(a,b={}){return this.call("tasks.cancel",{taskId:a.taskId,reason:a.reason??void 0},b)}listArtifacts(a={},b={}){return this.call("artifacts.list",function(a={}){return{taskId:a.taskId?.trim()||void 0,runId:a.runId?.trim()||void 0,sessionKey:a.sessionKey?.trim()||a.sessionId?.trim()||void 0}}(a),b)}getArtifact(a,b={}){return this.call("artifacts.get",{...a},b)}async putArtifact(a,b={}){throw Error(`Artifact writes are not part of the OpenClaw ${h.c} Gateway baseline; native Gateway support must be explicitly advertised before AgentOS can use artifacts.put.`)}async deleteArtifact(a,b={}){throw Error(`Artifact deletion is not part of the OpenClaw ${h.c} Gateway baseline; native Gateway support must be explicitly advertised before AgentOS can use artifacts.delete.`)}async getRuntimeSnapshot(a={},b={}){let c=!1!==a.includeSessions,d=!1!==a.includeTasks,e=!1!==a.includeArtifacts,f={taskId:a.taskId,runId:a.runId,sessionKey:a.sessionKey,sessionId:a.sessionId},g=e&&function(a={}){return!!(a.taskId?.trim()||a.runId?.trim()||a.sessionKey?.trim()||a.sessionId?.trim())}(f),h=await Promise.allSettled([c?this.listSessions({limit:a.limit,agentId:a.agentId},b):Promise.resolve(null),d?this.listTasks({limit:a.limit,agentId:a.agentId,workspace:a.workspace},b):Promise.resolve(null),g?this.listArtifacts(f,b):Promise.resolve(null)]),i=h.filter((a,b)=>[c,d,g][b]),j=i.filter(a=>"rejected"===a.status);if(i.length>0&&j.length===i.length)throw j[0]?.reason??Error("OpenClaw Gateway runtime snapshot failed.");let[k,l,m]=h,n={sessions:"fulfilled"===k.status?k.value?.sessions??[]:[],tasks:"fulfilled"===l.status?l.value?.tasks??[]:[],artifacts:"fulfilled"===m.status?m.value?.artifacts??[]:[]};return j.length>0&&(n.metadata={runtimeSnapshot:{partial:!0,errors:j.map(a=>{var b;return(b=a.reason)instanceof Error?b.message:String(b||"Unknown OpenClaw Gateway snapshot error.")})}}),n}getToolsCatalog(a={},b={}){return this.call("tools.catalog",{...a},b)}getEffectiveTools(a={},b={}){return this.call("tools.effective",{...a},b)}invokeTool(a,b={}){return this.call("tools.invoke",{...a},b)}async subscribeRuntimeEvents(a,b,c={}){throw Error("OpenClaw runtime event subscriptions require the native Gateway transport.")}getChannelStatus(a={},b={}){return this.call("channels.status",{...a},b)}getChannelLogs(a,b={}){let c=["channels","logs","--channel",a.channel,"--json"];return"number"==typeof a.lines&&Number.isFinite(a.lines)&&a.lines>0&&c.push("--lines",String(a.lines)),(0,d.VP)(c,b)}provisionChannelAccount(a,b={}){let c=["channels","add","--channel",a.channel];return k(c,"--account",a.account),k(c,"--token",a.token),k(c,"--bot-token",a.botToken),k(c,"--webhook-url",a.webhookUrl),k(c,"--name",a.name),(0,d.zB)(c,b)}removeChannelAccount(a,b={}){let c=["channels","remove","--channel",a.channel,"--account",a.account];return a.delete&&c.push("--delete"),(0,d.zB)(c,b)}setupGmailWebhook(a,b={}){var c,e,f;let g,h,i,j;return(0,d.zB)((g=a.config??{},h=["webhooks","gmail","setup","--account",a.account],i=l(g.serve)?g.serve:{},j=l(g.tailscale)?g.tailscale:{},k(h,"--project",g.project),k(h,"--topic",g.topic),k(h,"--subscription",g.subscription),k(h,"--label",g.label),k(h,"--hook-url",g.hookUrl),k(h,"--hook-token",g.hookToken),k(h,"--push-token",g.pushToken),k(h,"--bind",i.bind),k(h,"--port",i.port),k(h,"--path",i.path),c=h,e="--include-body",(!0===(f=g.includeBody)||"true"===f)&&c.push(e),k(h,"--max-bytes",g.maxBytes),k(h,"--renew-minutes",g.renewEveryMinutes),k(h,"--tailscale",j.mode),k(h,"--tailscale-path",j.path),k(h,"--tailscale-target",j.target),k(h,"--push-endpoint",g.pushEndpoint),h),b)}listSkills(a={}){let b=["skills","list"];return a.eligible&&b.push("--eligible"),b.push("--json"),(0,d.VP)(b,a)}listPlugins(a={}){return(0,d.VP)(["plugins","list","--json"],a)}listModels(a={},b={}){let c=["models","list"];return a.all&&c.push("--all"),c.push("--json"),a.provider&&c.push("--provider",a.provider),(0,d.VP)(c,b)}scanModels(a={}){let b=["models","scan","--json"];return a.yes&&b.push("--yes"),a.noInput&&b.push("--no-input"),a.noProbe&&b.push("--no-probe"),(0,d.VP)(b,a)}probeGateway(a={}){return(0,d.VP)(["gateway","probe","--json"],a)}controlGateway(a,b={}){let c=["gateway",a];return"restart"===a&&b.force&&c.push("--force"),c.push("--json"),(0,d.VP)(c,b)}async approveDeviceAccess(a={},b={}){if(!1!==a.latest&&!a.requestId){let c=function(a){let b=Array.isArray(a.pending)?a.pending:[],c=null;for(let a of b){if(!a||"object"!=typeof a)continue;let b="string"==typeof a.requestId&&a.requestId.trim()?a.requestId.trim():null;if(!b)continue;let d="number"==typeof a.ts&&Number.isFinite(a.ts)?a.ts:0;(!c||d>c.ts)&&(c={requestId:b,ts:d})}return c?.requestId??null}(await (0,d.VP)(["devices","list","--json"],b));if(!c)throw Error("No pending OpenClaw device access request found.");return this.approveDeviceAccess({...a,latest:!1,requestId:c},b)}let c=["devices","approve"];for(let b of(a.requestId&&c.push(a.requestId),a.scopes??[]))k(c,"--scope",b);return c.push("--json"),(0,d.VP)(c,b)}call(a,b={},c={}){return(0,d.VP)(["gateway","call",a,"--params",JSON.stringify(b),"--json"],c)}async getConfig(a,b={}){return(0,d.VP)(["config","get",a,"--json"],b).catch(()=>null)}async getConfigSchema(a={}){return this.call("config.schema",{},a).catch(()=>null)}async lookupConfigSchema(a,b={}){return this.call("config.schema.lookup",{path:a.path},b).catch(()=>null)}async hasConfig(a,b={}){try{return await (0,d.zB)(["config","get",a,"--json"],b),!0}catch(a){if((0,e.t)(a).includes("Config path not found"))return!1;throw a}}setConfig(a,b,c={}){if((0,f.FZ)(b))throw Error("Refusing to write a redacted OpenClaw secret back to config.");let e=["config","set",a,"string"==typeof b?b:JSON.stringify(b)];return c.strictJson&&e.push("--strict-json"),(0,d.zB)(e,c)}unsetConfig(a,b={}){return(0,d.zB)(["config","unset",a],b)}addAgent(a,b={}){let c=["agents","add",a.id,"--workspace",a.workspace,"--agent-dir",a.agentDir,"--non-interactive","--json"];return a.model&&c.push("--model",a.model),(0,d.zB)(c,b)}async updateAgent(a,b={}){return{stdout:JSON.stringify({ok:!0,fallback:"application-config"}),stderr:""}}setAgentIdentity(a,b={}){let c;return(0,d.zB)((k(c=["agents","set-identity","--agent",a.agentId,"--workspace",a.workspace,"--identity-file",a.identityFile,"--json"],"--name",a.name),k(c,"--emoji",a.emoji),k(c,"--theme",a.theme),k(c,"--avatar",a.avatar),c),b)}deleteAgent(a,b={}){return(0,d.zB)(["agents","delete",a,"--force","--json"],b)}provisionAutomation(a,b={}){let c;return(0,d.zB)((c=["cron","add","--name",a.name,"--description",a.description||a.name,"--agent",a.agentId,"--message",a.message,"--thinking",a.thinking||"medium","--timeout-seconds",String(a.timeoutSeconds??120),"--json"],"every"===a.schedule.kind?c.push("--every",a.schedule.value):c.push("--cron",a.schedule.value),a.announce?.channel&&(c.push("--announce","--channel",a.announce.channel),k(c,"--to",a.announce.target)),c),b)}runAgentTurn(a,b={}){return(0,d.VP)(i(a),b)}abortAgentTurn(a,b={}){return this.call("chat.abort",{runId:a.runId??void 0,sessionId:a.sessionId??void 0,agentId:a.agentId??void 0,reason:a.reason??void 0},b)}async steerSession(a,b={}){throw Error("Native OpenClaw Gateway is required for sessions.steer.")}async injectChat(a,b={}){throw Error("Native OpenClaw Gateway is required for chat.inject.")}streamAgentTurn(a,b={},c={}){return(0,d.JZ)(i(a),{...c,...b})}tailLogs(a={},b={}){return this.call("logs.tail",{...a},b)}listExecApprovals(a={},b={}){return this.call("exec.approval.list",{...a},b)}resolveExecApproval(a,b={}){return this.call("exec.approval.resolve",{approvalId:a.approvalId,decision:a.decision,reason:a.reason??void 0},b)}getCronStatus(a={}){return this.call("cron.status",{},a)}listCronJobs(a={},b={}){return this.call("cron.list",{...a},b)}}},39503:(a,b,c)=>{"use strict";c.d(b,{rw:()=>g});var d=c(7565);class e{constructor(a=d.Xz){this.getClient=a}getHealth(a={}){return this.getClient().getHealth(a)}getStatus(a={}){return this.getClient().getStatus(a)}getUpdateStatus(a={}){return this.getClient().getUpdateStatus(a)}getGatewayStatus(a={}){return this.getClient().getGatewayStatus(a)}getModelStatus(a={}){return this.getClient().getModelStatus(a)}getAgentModelStatus(a,b={}){return this.getClient().getAgentModelStatus(a,b)}setModelAuthOrder(a,b={}){return this.getClient().setModelAuthOrder(a,b)}listAgents(a={}){return this.getClient().listAgents(a)}listSessions(a={},b={}){return this.getClient().listSessions(a,b)}describeSession(a={},b={}){return this.getClient().describeSession(a,b)}getSessionHistory(a={},b={}){return this.getClient().getSessionHistory(a,b)}exportSession(a={},b={}){return this.getClient().exportSession(a,b)}listTasks(a={},b={}){return this.getClient().listTasks(a,b)}getTask(a,b={}){return this.getClient().getTask(a,b)}assignTask(a,b={}){return this.getClient().assignTask(a,b)}cancelTask(a,b={}){return this.getClient().cancelTask(a,b)}listArtifacts(a={},b={}){return this.getClient().listArtifacts(a,b)}getArtifact(a,b={}){return this.getClient().getArtifact(a,b)}putArtifact(a,b={}){return this.getClient().putArtifact(a,b)}deleteArtifact(a,b={}){return this.getClient().deleteArtifact(a,b)}getRuntimeSnapshot(a={},b={}){return this.getClient().getRuntimeSnapshot(a,b)}getToolsCatalog(a={},b={}){return this.getClient().getToolsCatalog(a,b)}getEffectiveTools(a={},b={}){return this.getClient().getEffectiveTools(a,b)}invokeTool(a,b={}){return this.getClient().invokeTool(a,b)}subscribeRuntimeEvents(a,b,c={}){return this.getClient().subscribeRuntimeEvents(a,b,c)}getChannelStatus(a={},b={}){return this.getClient().getChannelStatus(a,b)}getChannelLogs(a,b={}){return this.getClient().getChannelLogs(a,b)}provisionChannelAccount(a,b={}){return this.getClient().provisionChannelAccount(a,b)}removeChannelAccount(a,b={}){return this.getClient().removeChannelAccount(a,b)}setupGmailWebhook(a,b={}){return this.getClient().setupGmailWebhook(a,b)}listModels(a={},b={}){return this.getClient().listModels(a,b)}listSkills(a={}){return this.getClient().listSkills(a)}listPlugins(a={}){return this.getClient().listPlugins(a)}scanModels(a={}){return this.getClient().scanModels(a)}getConfig(a,b={}){return this.getClient().getConfig(a,b)}getConfigSchema(a={}){return this.getClient().getConfigSchema?.(a)??Promise.resolve(null)}lookupConfigSchema(a,b={}){return this.getClient().lookupConfigSchema?.(a,b)??Promise.resolve(null)}hasConfig(a,b={}){return this.getClient().hasConfig(a,b)}setConfig(a,b,c={}){return this.getClient().setConfig(a,b,c)}unsetConfig(a,b={}){return this.getClient().unsetConfig(a,b)}addAgent(a,b={}){return this.getClient().addAgent(a,b)}updateAgent(a,b={}){return this.getClient().updateAgent?.(a,b)??Promise.resolve({stdout:JSON.stringify({ok:!0,fallback:"application-config"}),stderr:""})}setAgentIdentity(a,b={}){return this.getClient().setAgentIdentity(a,b)}deleteAgent(a,b={}){return this.getClient().deleteAgent(a,b)}provisionAutomation(a,b={}){return this.getClient().provisionAutomation(a,b)}runAgentTurn(a,b={}){return this.getClient().runAgentTurn(a,b)}abortAgentTurn(a,b={}){let c=this.getClient();return c.abortAgentTurn?c.abortAgentTurn(a,b):c.call("chat.abort",{...a},b)}steerSession(a,b={}){let c=this.getClient();if(!c.steerSession)throw Error("Native OpenClaw Gateway is required for sessions.steer.");return c.steerSession(a,b)}injectChat(a,b={}){let c=this.getClient();if(!c.injectChat)throw Error("Native OpenClaw Gateway is required for chat.inject.");return c.injectChat(a,b)}streamAgentTurn(a,b={},c={}){return this.getClient().streamAgentTurn(a,b,c)}probeGateway(a={}){return this.getClient().probeGateway(a)}controlGateway(a,b={}){return this.getClient().controlGateway(a,b)}approveDeviceAccess(a={},b={}){return this.getClient().approveDeviceAccess(a,b)}call(a,b={},c={}){return this.getClient().call(a,b,c)}tailLogs(a={},b={}){let c=this.getClient();return c.tailLogs?.(a,b)??c.call("logs.tail",{...a},b)}listExecApprovals(a={},b={}){let c=this.getClient();return c.listExecApprovals?.(a,b)??c.call("exec.approval.list",{...a},b)}resolveExecApproval(a,b={}){let c=this.getClient();return c.resolveExecApproval?.(a,b)??c.call("exec.approval.resolve",{approvalId:a.approvalId,decision:a.decision,reason:a.reason??void 0},b)}getCronStatus(a={}){let b=this.getClient();return b.getCronStatus?.(a)??b.call("cron.status",{},a)}listCronJobs(a={},b={}){let c=this.getClient();return c.listCronJobs?.(a,b)??c.call("cron.list",{...a},b)}}let f=null;function g(){return f||(f=new e),f}},40218:()=>{},65395:(a,b,c)=>{"use strict";c.d(b,{W2:()=>f,a3:()=>g});var d=c(11315);let e=[{id:"openai-codex",label:"ChatGPT",shortLabel:"ChatGPT",description:"Use OpenClaw's Codex app-server provider and pull in Codex-ready models.",category:"primary",connectKind:"oauth",accent:"from-[#d8f5eb] via-[#ebfbf5] to-white",helperText:`OpenClaw ${d.L} uses the Codex app-server plugin for this route.`},{id:"openrouter",label:"OpenRouter",shortLabel:"OpenRouter",description:"Add an API key, discover the full catalog, and curate the models you want.",category:"primary",connectKind:"apiKey",accent:"from-[#fff2d7] via-[#fff7ea] to-white",helperText:"Best for broad model access and curated remote routes.",searchPlaceholder:"Search OpenRouter models"},{id:"ollama",label:"Ollama Local",shortLabel:"Ollama",description:"Discover models already available on this machine and add them instantly.",category:"primary",connectKind:"local",accent:"from-[#deefff] via-[#f2f8ff] to-white",helperText:"Local-first discovery with helpful pull commands when empty."},{id:"anthropic",label:"Anthropic",shortLabel:"Anthropic",description:"Paste an API key and add Claude models through the same flow.",category:"other",connectKind:"apiKey",accent:"from-[#efe9ff] via-[#f7f3ff] to-white",helperText:"Simple API key connection."},{id:"openai",label:"OpenAI API",shortLabel:"OpenAI",description:"Connect a standard OpenAI API key for direct GPT model access.",category:"other",connectKind:"apiKey",accent:"from-[#e8f8e8] via-[#f4fbf4] to-white",helperText:"Use this for API-key-based OpenAI routing."},{id:"google",label:"Gemini",shortLabel:"Gemini",description:"Add a Gemini API key, discover Google models, and pick the routes you want.",category:"other",connectKind:"apiKey",accent:"from-[#e6f7ff] via-[#f4fbff] to-white",helperText:"Simple API key connection.",searchPlaceholder:"Search Gemini models"},{id:"deepseek",label:"DeepSeek",shortLabel:"DeepSeek",description:"Add a DeepSeek API key, discover the catalog, and add the models you need.",category:"other",connectKind:"apiKey",accent:"from-[#e7eeff] via-[#f4f7ff] to-white",helperText:"Simple API key connection.",searchPlaceholder:"Search DeepSeek models"},{id:"mistral",label:"Mistral",shortLabel:"Mistral",description:"Add a Mistral API key, discover Mistral and Codestral models, and curate your routes.",category:"other",connectKind:"apiKey",accent:"from-[#f2e8ff] via-[#fbf7ff] to-white",helperText:"Simple API key connection.",searchPlaceholder:"Search Mistral models"},{id:"xai",label:"xAI",shortLabel:"xAI",description:"Use an xAI API key to bring Grok models into AgentOS.",category:"other",connectKind:"apiKey",accent:"from-[#ffe6ea] via-[#fff3f5] to-white",helperText:"Simple API key connection."}];function f(a){let b=e.find(b=>b.id===a);if(!b)throw Error(`Unknown model provider: ${a}`);return b}function g(a){return"string"==typeof a&&e.some(b=>b.id===a)}e.filter(a=>"primary"===a.category),e.filter(a=>"other"===a.category)},65493:(a,b,c)=>{"use strict";c.d(b,{Av:()=>k,Dq:()=>m,Hi:()=>r,P5:()=>q,iG:()=>f,jW:()=>p,rp:()=>l,zS:()=>e});var d=c(11315);let e=[{id:"health",label:"Gateway health",methods:["health","status"],baseline:"required"},{id:"modelAuthOrder",label:"Model auth order",methods:["models.authOrder.set","models.auth.order.set"],baseline:"experimental"},{id:"modelScan",label:"Model scan",methods:["models.scan"],baseline:"optional"},{id:"logsTail",label:"Gateway logs",methods:["logs.tail"],baseline:"required"},{id:"configSchemaLookup",label:"Config schema lookup",methods:["config.schema.lookup","config.schema"],baseline:"required"},{id:"configPatch",label:"Config patch",methods:["config.patch","config.apply","config.set"],baseline:"required"},{id:"sessionLifecycle",label:"Session lifecycle",methods:["sessions.create","sessions.patch","sessions.steer"],baseline:"optional"},{id:"agentCreate",label:"Agent creation",methods:["agents.create"],baseline:"required"},{id:"agentUpdate",label:"Agent update",methods:["agents.update"],baseline:"required"},{id:"agentIdentity",label:"Agent identity sync",methods:["agents.identity.set","agents.setIdentity","agents.set-identity"],baseline:"experimental"},{id:"agentDelete",label:"Agent removal",methods:["agents.delete"],baseline:"required"},{id:"missionDispatch",label:"Mission dispatch",methods:["chat.send","sessions.send"],baseline:"required"},{id:"missionStream",label:"Mission event stream",methods:["sessions.subscribe","sessions.messages.subscribe"],events:["chat","agent","session.message","session.tool"],baseline:"optional"},{id:"chatControl",label:"Chat control",methods:["chat.abort","chat.inject"],baseline:"optional"},{id:"agentWait",label:"Agent wait",methods:["agent.wait"],baseline:"optional"},{id:"sessionHistory",label:"Session history",methods:["chat.history","sessions.preview","sessions.get","sessions.describe"],baseline:"optional"},{id:"taskEvents",label:"Task events",methods:["tasks.subscribe","tasks.get","tasks.list"],events:["task","task.updated","task.completed"],baseline:"optional"},{id:"taskAssign",label:"Task assignment",methods:["tasks.assign"],fallbackAllowed:!1,baseline:"experimental"},{id:"taskCancel",label:"Task cancellation",methods:["tasks.cancel"],baseline:"optional"},{id:"artifacts",label:"Artifact sync",methods:["artifacts.list","artifacts.get","artifacts.download"],events:["artifact","artifact.updated"],baseline:"optional"},{id:"runtimeSnapshot",label:"Runtime snapshot",methods:["sessions.list","tasks.list"],baseline:"required"},{id:"tools",label:"Tool catalog",methods:["tools.catalog","tools.effective","tools.invoke"],fallbackAllowed:!1,baseline:"optional"},{id:"plugins",label:"Plugin catalog",methods:["plugins.uiDescriptors","plugins.list"],baseline:"optional"},{id:"execApprovals",label:"Execution approvals",methods:["exec.approval.list","exec.approval.get","exec.approval.resolve","exec.approvals.get","exec.approvals.set"],baseline:"optional"},{id:"devicePairList",label:"Device pairing list",methods:["device.pair.list","devices.list","gateway.devices.list"],baseline:"optional"},{id:"deviceApproval",label:"Device access repair",methods:["device.pair.approve","devices.approve","gateway.devices.approve"],baseline:"optional"},{id:"cronRead",label:"Automation status",methods:["cron.list","cron.status"],baseline:"optional"},{id:"channels",label:"Channel status",methods:["channels.status"],baseline:"required"},{id:"channelList",label:"Channel list",methods:["channels.list","channels.status"],baseline:"optional"},{id:"channelLogs",label:"Channel logs",methods:["channels.logs"],baseline:"optional"},{id:"channelProvisioning",label:"Channel provisioning",methods:["channels.add","channels.create","channels.configure"],baseline:"experimental"},{id:"channelRemoval",label:"Channel removal",methods:["channels.remove","channels.delete"],baseline:"experimental"},{id:"gmailProvisioning",label:"Gmail webhook setup",methods:["webhooks.gmail.setup","gmail.setup"],baseline:"experimental"},{id:"automationProvisioning",label:"Automation provisioning",methods:["cron.add","cron.create"],baseline:"experimental"},{id:"skills",label:"Skill status",methods:["skills.status"],baseline:"optional"},{id:"updates",label:"Update status",methods:["update.status","update.run","status"],baseline:"optional"}],f=d.c,g=["health","status","update.status","models.list","models.authStatus","agents.list","agents.create","agents.update","agents.delete","sessions.list","sessions.preview","chat.send","config.get","config.set","config.schema","config.schema.lookup","config.patch","config.apply","channels.status","logs.tail"],h=["agent.identity.get","agent.wait","artifacts.download","artifacts.get","artifacts.list","chat.abort","chat.history","chat.inject","channels.logout","channels.list","channels.start","channels.stop","cron.list","cron.status","devices.list","device.pair.list","device.pair.approve","device.pair.reject","device.pair.remove","exec.approval.get","exec.approval.list","exec.approval.request","exec.approval.resolve","exec.approval.waitDecision","plugins.uiDescriptors","plugins.list","models.scan","sessions.abort","sessions.create","sessions.describe","sessions.get","sessions.messages.subscribe","sessions.patch","sessions.resolve","sessions.steer","sessions.subscribe","skills.detail","skills.install","skills.search","skills.status","skills.update","tasks.cancel","tasks.get","tasks.list","tasks.subscribe","tools.catalog","tools.effective","tools.invoke","update.run"],i=["diagnostics.stability","agents.files.list","agents.files.get","agents.files.set","plugin.approval.list","plugin.approval.resolve","environment.list","environment.get","environment.create","environment.update","environment.delete","gateway.restart.preflight","gateway.restart.request","tasks.assign","models.authOrder.set","models.auth.order.set","agents.identity.set","agents.setIdentity","agents.set-identity","channels.logs","channels.add","channels.create","channels.configure","channels.remove","channels.delete","webhooks.gmail.setup","gmail.setup","cron.add","cron.create"],j=[...g,...h,...i];Array.from(new Set([...e.flatMap(a=>a.methods),...j])).sort(),Array.from(new Set([...g,...h])).sort();let k=Array.from(new Set(g)).sort(),l=Array.from(new Set(h)).sort(),m=Array.from(new Set(i)).sort(),n=new Map(e.map(a=>[a.id,a])),o=new Map(e.flatMap(a=>a.methods.map(b=>[b,a])));function p(a){let b=n.get(a);if(!b)throw Error(`Unknown OpenClaw Gateway compatibility operation: ${a}`);return b}function q(a){return p(a).methods}function r(a){return n.get(a)?.label??o.get(a)?.label??(a.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,a=>a.toUpperCase())||"Gateway operation")}},78446:(a,b,c)=>{"use strict";c.d(b,{D:()=>f,t:()=>e});var d=c(96972);function e(a){if(!a||"object"!=typeof a)return"";let b="stdout"in a?g(a.stdout):"",c="stderr"in a?g(a.stderr):"",e="message"in a&&"string"==typeof a.message?a.message:"";return(0,d.bS)(`${e}
|
|
8
8
|
${b}
|
|
9
9
|
${c}`)}function f(a){let b=e(a),c=a instanceof Error?a.message:"",d=`${b}
|
|
10
10
|
${c}`;return/OpenClaw config is invalid/i.test(d)||/Invalid config at .*openclaw\.json/i.test(d)||/Status, health, logs, and doctor commands still run with invalid config/i.test(d)}function g(a){return"string"==typeof a?a:a instanceof Uint8Array?Buffer.from(a).toString():""}},79102:(a,b,c)=>{"use strict";c.d(b,{$k:()=>m,MK:()=>j,lH:()=>l,pP:()=>i,qi:()=>k,sq:()=>g});var d=c(24117),e=c(98717),f=c(17929);function g(a,b){let c=[];for(let d of(!1!==a.subscribeSessions&&h(b,"sessions.subscribe")&&c.push({method:"sessions.subscribe",params:{}}),Array.isArray(a.sessionKeys)?a.sessionKeys.filter(a=>"string"==typeof a&&a.trim().length>0):[]))h(b,"sessions.messages.subscribe")&&c.push({method:"sessions.messages.subscribe",params:{key:d.trim()}});let d=Array.isArray(a.taskIds)?a.taskIds.filter(a=>"string"==typeof a&&a.trim().length>0):[];return(!0===a.subscribeTasks||d.length>0)&&h(b,"tasks.subscribe")&&c.push({method:"tasks.subscribe",params:d.length>0?{taskIds:d.map(a=>a.trim())}:{}}),c}function h(a,b){if(b===d.JV)return!0;let c=Array.isArray(a?.features?.methods)?a.features.methods.filter(a=>"string"==typeof a&&a.trim().length>0):[];return 0===c.length||c.includes(b)}function i(a,b){let c=Array.isArray(a?.features?.events)?a.features.events.filter(a=>"string"==typeof a&&a.trim().length>0):[];return 0===c.length||c.includes(b)}function j(a){if(!a||"object"!=typeof a)throw new e.As("OpenClaw Gateway connect response was malformed.",{kind:"malformed-response"});let b=a.protocol;if("number"==typeof b&&Number.isFinite(b)&&(b<d.lY||b>d.ZX))throw new e.As(`OpenClaw Gateway protocol ${b} is outside AgentOS' supported range ${d.lY}-${d.ZX}.`,{kind:"protocol-mismatch"})}function k(a,b){if(!h(a,b))throw new e.As(`OpenClaw Gateway does not advertise method "${b}".`,{kind:"unsupported"})}function l(a){return"unsupported"===(0,e.$g)(a).kind}function m(a){let b=Array.isArray(a.pending)?a.pending:[],c=null;for(let a of b){if(!(0,f.LK)(a))continue;let b=(0,f.yK)(a.requestId);if(!b)continue;let d="number"==typeof a.ts&&Number.isFinite(a.ts)?a.ts:0;(!c||d>c.ts)&&(c={requestId:b,ts:d})}return c?.requestId??null}},80500:(a,b,c)=>{"use strict";c.d(b,{LF:()=>f,RE:()=>g,S4:()=>k,_v:()=>j,c0:()=>i,vC:()=>h});var d=c(98717),e=c(17929);function f(a,b){let c=(0,e.nf)(a);if(0===c.length)throw new d.pz("Config path is required.","unknown");if(c.some(a=>"number"==typeof a))throw new d.pz("Gateway config.patch merge updates do not support array-index paths; using CLI config fallback.","unsupported");let f={},g=f;for(let a=0;a<c.length;a+=1){let d=c[a];if(a===c.length-1){g[d]=b;break}let e={};g[d]=e,g=e}return f}function g(a){let b=new Set,c=[a];for(;c.length>0;){let a=c.shift();if(!(!a||b.has(a))){if(b.add(a),(0,e.LK)(a)){let b=function(a){if("string"!=typeof a)return"unknown";let b=a.trim().toLowerCase();return"restart"===b||"hot"===b||"none"===b?b:"unknown"}(a.reloadKind??a.reload??a.reload_kind??a.reloadPolicy??a.reloadRequirement);if("unknown"!==b)return b;c.push(a.schema,a.hint,a.node,a.config);continue}Array.isArray(a)&&c.push(...a)}}return"unknown"}function h(a){return/^(gateway\.(remote\.(url|token|password)|auth\.(mode|token|password))|gateway\.mode)$/.test(a)}function i(a,b){let c=(0,d.$g)(a).kind;return!!h(b)&&("auth"===c||"timeout"===c||"unreachable"===c)&&(!(a instanceof d.jl)||!/^config\.(patch|apply|set|unset)$/i.test(a.method))}function j(a){let b=a instanceof Error?a.message:String(a??"");return/(^|[^a-z])rate limit(?:ed)?\b|retry after|too many requests|HTTP\s*429/i.test(b)&&(!(a instanceof d.jl)||/^config\.(get|schema|patch|apply|set|unset)$/i.test(a.method))}function k(a){if(!j(a))return null;let b=(a instanceof Error?a.message:String(a??"")).match(/retry after\s+(\d+(?:\.\d+)?)\s*(ms|msec|millisecond(?:s)?|s|sec|second(?:s)?|m|min|minute(?:s)?)?/i);if(!b)return null;let c=Number(b[1]);if(!Number.isFinite(c)||c<0)return null;let d=b[2]?.toLowerCase()??"s";return"ms"===d||"msec"===d||d.startsWith("millisecond")?Math.round(c):"m"===d||"min"===d||d.startsWith("minute")?Math.round(6e4*c):Math.round(1e3*c)}},88366:(a,b,c)=>{"use strict";c.d(b,{JZ:()=>s,T5:()=>y,VP:()=>p,Vg:()=>u,XP:()=>w,YP:()=>t,gg:()=>v,ik:()=>r,o_:()=>x,zB:()=>o});var d=c(31421),e=c(97411),f=c(15292),g=c(96972);process.env.OPENCLAW_BIN;let h=process.env.OPENCLAW_BIN?.trim()||"",i="",j=null,k=null,l=/^[A-Za-z0-9_./:@=+%-]+$/,m=0,n=[];async function o(a,b={}){return q(a,b)}async function p(a,b={}){try{let c=await o(a,b);return z(c.stdout||c.stderr)}catch(b){let a=A(b);if(a)try{return z(a.stdout||a.stderr)}catch{}throw b}}async function q(a,b={}){let c=await w();return new Promise((e,f)=>{let g=Date.now(),h=new Date(g).toISOString(),i=`openclaw:${g}:${m++}`,j=(0,d.spawn)(c,a,{detached:!0,env:{...process.env}}),k="",l="",n=!1,o=!1,p=!1,q=Promise.resolve(),r=null,s=(a,b)=>{a&&b&&(q=q.then(()=>a(b)).catch(()=>{}))},t=a=>{n||(n=!0,q.finally(a))},u=a=>{if(j.pid)try{process.kill(-j.pid,a)}catch{j.kill(a)}else j.kill(a);"SIGTERM"!==a||r||(r=setTimeout(()=>{if(!n)if(j.pid)try{process.kill(-j.pid,"SIGKILL")}catch{j.kill("SIGKILL")}else j.kill("SIGKILL")},2e3))},v=setTimeout(()=>{o=!0,u("SIGTERM")},b.timeoutMs??45e3),w=()=>{p=!0,u("SIGTERM")};b.signal&&(b.signal.aborted?w():b.signal.addEventListener("abort",w));let x=()=>{clearTimeout(v),r&&(clearTimeout(r),r=null),b.signal&&b.signal.removeEventListener("abort",w)};j.stdout.on("data",a=>{let c=a.toString();k+=c,s(b.onStdout,c)}),j.stderr.on("data",a=>{let c=a.toString();l+=c,s(b.onStderr,c)}),j.on("error",b=>{x(),t(()=>{D({id:i,command:c,args:a,startedAt:h,startedAtMs:g,status:"start-error",exitCode:null,stdout:k,stderr:l?`${l}
|
|
11
11
|
${b.message}`:b.message}),f(B(`OpenClaw command failed to start: ${b.message}`,k,l?`${l}
|
|
12
12
|
${b.message}`:b.message,null))})}),j.on("close",d=>{x(),t(()=>{if(p){D({id:i,command:c,args:a,startedAt:h,startedAtMs:g,status:"aborted",exitCode:d,stdout:k,stderr:l||"The command was aborted."}),f(B("OpenClaw command was aborted.",k,l||"The command was aborted.",d));return}if(o){D({id:i,command:c,args:a,startedAt:h,startedAtMs:g,status:"timeout",exitCode:d,stdout:k,stderr:l||"The command exceeded its timeout window."}),f(B(`OpenClaw command timed out after ${Math.round((b.timeoutMs??45e3)/1e3)} seconds.`,k,l||"The command exceeded its timeout window.",d));return}if(0!==d){D({id:i,command:c,args:a,startedAt:h,startedAtMs:g,status:"failed",exitCode:d,stdout:k,stderr:l}),f(B(`OpenClaw command failed with exit code ${d}.`,k,l,d));return}D({id:i,command:c,args:a,startedAt:h,startedAtMs:g,status:"ok",exitCode:d,stdout:k,stderr:l}),e({stdout:k,stderr:l})})})})}function r(){return n.map(a=>({...a,args:E(a.args),stdoutPreview:a.stdoutPreview?(0,g.bS)(a.stdoutPreview):null,stderrPreview:a.stderrPreview?(0,g.bS)(a.stderrPreview):null})).reverse()}async function s(a,b={}){try{let c=await q(a,b);return z(c.stdout||c.stderr)}catch(b){let a=A(b);if(a)try{return z(a.stdout||a.stderr)}catch{}throw b}}async function t(){let a=Date.now();if(k&&k.expiresAt>a)return k.value;try{let b=await o(["--version"],{timeoutMs:5e3}),c=function(a){let b=a.trim();if(!b)return null;let c=b.match(/\b(\d+(?:\.\d+)+)\b/);return c?.[1]??null}(b.stdout||b.stderr);return k={value:c,expiresAt:a+3e5},c}catch{return k={value:null,expiresAt:a+3e4},null}}async function u(){try{return await w(),!0}catch{return!1}}function v(a,b){return[a,...b].map(H).join(" ")}async function w(){if(j)return j;j=(async()=>{let a,b;if(i)return i;let c=await (0,f.bq)().catch(()=>(0,f.ml)()),d=(0,f.g)(c),g=h||"",j="auto"===c.mode?(a=(0,e.eB)(),b=(0,e.lz)(),Array.from(new Set([h&&h!==b?h:"",a,b,(0,e.u_)(),"openclaw"].filter(a=>!!a)))):[d||""];for(let a of("auto"===c.mode&&g&&j.unshift(g),j))if(await I(a))return i=a,process.env.OPENCLAW_BIN=a,a;throw Error("OpenClaw CLI is not installed or could not be resolved.")})();try{return await j}finally{j=null}}function x(){h||process.env.OPENCLAW_BIN!==i||delete process.env.OPENCLAW_BIN,i="",j=null,k=null}function y(){return i||null}function z(a){let b=a.trim();if(!b)throw Error("OpenClaw returned no JSON output.");try{return JSON.parse(b)}catch{}let c=b.split(/\r?\n/);for(let a=0;a<c.length;a+=1){let b=c[a].trim();if(b.startsWith("{")||b.startsWith("["))for(let b=c.length;b>a;b-=1){let d=c.slice(a,b).join("\n").trim();try{return JSON.parse(d)}catch{}}}throw Error(`Unable to parse OpenClaw JSON output:
|
|
13
|
-
${(0,g.bS)(b.slice(0,800))}`)}function A(a){if(!a||"object"!=typeof a)return null;let b="stdout"in a?C(a.stdout):"",c="stderr"in a?C(a.stderr):"";return b||c?{stdout:b,stderr:c}:null}function B(a,b,c,d){let e=(0,g.bS)(function(a){let b=a.split(/\r?\n/).map(a=>a.trim()).filter(Boolean);if(0===b.length)return"";for(let a of[/Config path not found/i,/cannot find module/i,/command not found/i,/no such file or directory/i,/permission denied/i,/not writable/i,/failed/i,/\berror\b/i]){let c=b.find(b=>a.test(b));if(c)return c}return b.at(-1)??""}(c||b)),f=Error(null!==d&&/^OpenClaw command failed with exit code \d+\.$/.test(a)&&e?`${a.slice(0,-1)}: ${e}.`:a);return f.stdout=b,f.stderr=c,f.code=d,f}function C(a){return"string"==typeof a?a:a instanceof Uint8Array?Buffer.from(a).toString():""}function D(a){let b=Date.now();n.push({id:a.id,command:a.command,args:E(a.args),startedAt:a.startedAt,finishedAt:new Date(b).toISOString(),durationMs:Math.max(b-a.startedAtMs,0),status:a.status,exitCode:a.exitCode,stdoutPreview:G(a.stdout),stderrPreview:G(a.stderr)}),n.length>25&&n.splice(0,n.length-25)}function E(a){let b=new Set(["--message","--api-key","--bot-token","--hook-token","--push-token","--token","--password","--secret","--webhook-url","--key"]),c=[],d=!1,e=!1;for(let h=0;h<a.length;h+=1){var f,g;let i=a[h];if(d||e){c.push("[redacted]"),d=!1,e=!1;continue}if("config"===(f=a)[(g=h)-2]&&"set"===f[g-1]){let a=function(a){let b=a.indexOf("=");return b<=0?null:{path:a.slice(0,b),value:a.slice(b+1)}}(i);if(a&&F(a.path)){c.push(`${a.path}=[redacted]`);continue}if(F(i)){c.push(i),e=!0;continue}}let[j]=i.split("=",1);if(b.has(j)){c.push(i.includes("=")?`${j}=[redacted]`:i),d=!i.includes("=");continue}c.push(i.length>160?`${i.slice(0,157)}...`:i)}return c}function F(a){return/(^|[._-])(?:api[-_]?key|token|password|secret|private[-_]?key|credential|client[-_]?secret|webhook[-_]?token)s?($|[._-])/i.test(a)}function G(a){let b=a.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).join("\n").trim();if(!b)return null;let c=(0,g.bS)(b);return c.length>800?`${c.slice(0,797)}...`:c}function H(a){return l.test(a)?a:`'${a.replace(/'/g,"'\\''")}'`}async function I(a){return await new Promise(b=>{let c=(0,d.spawn)(a,["--version"],{stdio:"ignore"});c.once("error",()=>{b(!1)}),c.once("exit",a=>{b(0===a)})})}},92826:()=>{},96972:(a,b,c)=>{"use strict";c.d(b,{bS:()=>m,fp:()=>l,n3:()=>n});let d="[redacted]",e=new Set(["apikey","apitoken","authorization","authtoken","authpassword","clientsecret","credential","credentials","openclawgatewaytoken","openclawgatewaypassword","password","passwd","privatekey","pushtoken","refreshtoken","secret","token","tokens","webhooktoken"]),f=["apikey","apitoken","authtoken","authpassword","clientsecret","credential","credentials","password","privatekey","pushtoken","refreshtoken","secret","token","webhooktoken"],g=/\b([A-Z0-9_]*(?:API_KEY|TOKEN|PASSWORD|SECRET|PRIVATE_KEY|CREDENTIAL)[A-Z0-9_]*|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|auth[-_ ]?token|password|private[-_ ]?key|secret|credential)s?\s*([:=])\s*("([^"]*)"|'([^']*)'|[^\s,;&]+)/gi,h=/\b(authorization\s*:\s*bearer\s+)([^\s"',;]+)/gi,i=/\b(?:xox[baprs]-|sk-[A-Za-z0-9]|ghp_|github_pat_)[^\s"',;]*/g,j=/(["'])(api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|auth[-_ ]?token|token|password|private[-_ ]?key|secret|credential|client[-_ ]?secret|webhook[-_ ]?token)\1\s*:\s*(["'])(?:(?!\3).)*\3/gi,k=/([?&](?:api[-_]?key|access[-_]?token|refresh[-_]?token|auth[-_]?token|token|password|private[-_]?key|secret|credential|client[-_]?secret|webhook[-_]?token)=)([^&#\s]+)/gi;function l(a){return function a(b,c,g){if("string"==typeof b)return c?d:m(b);if("number"==typeof b||"bigint"==typeof b)return c?d:b;if(null==b||"boolean"==typeof b||b instanceof Date)return b;if(Array.isArray(b))return g.has(b)?[]:(g.add(b),b.map(b=>a(b,c,g)));if("object"!=typeof b)return b;if(g.has(b))return{};g.add(b);let h={};for(let[d,i]of Object.entries(b)){let b=function(a){let b=a.replace(/[^A-Za-z0-9]/g,"").toLowerCase();return!!b&&"tokenusage"!==b&&(!!e.has(b)||f.some(a=>b.endsWith(a)))}(d);h[d]=a(i,c||b,g)}return h}(a,!1,new WeakSet)}function m(a){return a.replace(h,(a,b)=>`${b}${d}`).replace(k,(a,b)=>`${b}${d}`).replace(i,d).replace(j,(a,b,c,e)=>`${b}${c}${b}:${e}${d}${e}`).replace(g,(a,b,c)=>`${b}${c}${d}`)}function n(a,b){return m((a instanceof Error?a.message:"string"==typeof a?a:b)||b)}},97411:(a,b,c)=>{"use strict";c.d(b,{CS:()=>
|
|
14
|
-
`,d=RegExp(`${
|
|
13
|
+
${(0,g.bS)(b.slice(0,800))}`)}function A(a){if(!a||"object"!=typeof a)return null;let b="stdout"in a?C(a.stdout):"",c="stderr"in a?C(a.stderr):"";return b||c?{stdout:b,stderr:c}:null}function B(a,b,c,d){let e=(0,g.bS)(function(a){let b=a.split(/\r?\n/).map(a=>a.trim()).filter(Boolean);if(0===b.length)return"";for(let a of[/Config path not found/i,/cannot find module/i,/command not found/i,/no such file or directory/i,/permission denied/i,/not writable/i,/failed/i,/\berror\b/i]){let c=b.find(b=>a.test(b));if(c)return c}return b.at(-1)??""}(c||b)),f=Error(null!==d&&/^OpenClaw command failed with exit code \d+\.$/.test(a)&&e?`${a.slice(0,-1)}: ${e}.`:a);return f.stdout=b,f.stderr=c,f.code=d,f}function C(a){return"string"==typeof a?a:a instanceof Uint8Array?Buffer.from(a).toString():""}function D(a){let b=Date.now();n.push({id:a.id,command:a.command,args:E(a.args),startedAt:a.startedAt,finishedAt:new Date(b).toISOString(),durationMs:Math.max(b-a.startedAtMs,0),status:a.status,exitCode:a.exitCode,stdoutPreview:G(a.stdout),stderrPreview:G(a.stderr)}),n.length>25&&n.splice(0,n.length-25)}function E(a){let b=new Set(["--message","--api-key","--bot-token","--hook-token","--push-token","--token","--password","--secret","--webhook-url","--key"]),c=[],d=!1,e=!1;for(let h=0;h<a.length;h+=1){var f,g;let i=a[h];if(d||e){c.push("[redacted]"),d=!1,e=!1;continue}if("config"===(f=a)[(g=h)-2]&&"set"===f[g-1]){let a=function(a){let b=a.indexOf("=");return b<=0?null:{path:a.slice(0,b),value:a.slice(b+1)}}(i);if(a&&F(a.path)){c.push(`${a.path}=[redacted]`);continue}if(F(i)){c.push(i),e=!0;continue}}let[j]=i.split("=",1);if(b.has(j)){c.push(i.includes("=")?`${j}=[redacted]`:i),d=!i.includes("=");continue}c.push(i.length>160?`${i.slice(0,157)}...`:i)}return c}function F(a){return/(^|[._-])(?:api[-_]?key|token|password|secret|private[-_]?key|credential|client[-_]?secret|webhook[-_]?token)s?($|[._-])/i.test(a)}function G(a){let b=a.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).join("\n").trim();if(!b)return null;let c=(0,g.bS)(b);return c.length>800?`${c.slice(0,797)}...`:c}function H(a){return l.test(a)?a:`'${a.replace(/'/g,"'\\''")}'`}async function I(a){return await new Promise(b=>{let c=(0,d.spawn)(a,["--version"],{stdio:"ignore"});c.once("error",()=>{b(!1)}),c.once("exit",a=>{b(0===a)})})}},92826:()=>{},96972:(a,b,c)=>{"use strict";c.d(b,{bS:()=>m,fp:()=>l,n3:()=>n});let d="[redacted]",e=new Set(["apikey","apitoken","authorization","authtoken","authpassword","clientsecret","credential","credentials","openclawgatewaytoken","openclawgatewaypassword","password","passwd","privatekey","pushtoken","refreshtoken","secret","token","tokens","webhooktoken"]),f=["apikey","apitoken","authtoken","authpassword","clientsecret","credential","credentials","password","privatekey","pushtoken","refreshtoken","secret","token","webhooktoken"],g=/\b([A-Z0-9_]*(?:API_KEY|TOKEN|PASSWORD|SECRET|PRIVATE_KEY|CREDENTIAL)[A-Z0-9_]*|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|auth[-_ ]?token|password|private[-_ ]?key|secret|credential)s?\s*([:=])\s*("([^"]*)"|'([^']*)'|[^\s,;&]+)/gi,h=/\b(authorization\s*:\s*bearer\s+)([^\s"',;]+)/gi,i=/\b(?:xox[baprs]-|sk-[A-Za-z0-9]|ghp_|github_pat_)[^\s"',;]*/g,j=/(["'])(api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|auth[-_ ]?token|token|password|private[-_ ]?key|secret|credential|client[-_ ]?secret|webhook[-_ ]?token)\1\s*:\s*(["'])(?:(?!\3).)*\3/gi,k=/([?&](?:api[-_]?key|access[-_]?token|refresh[-_]?token|auth[-_]?token|token|password|private[-_]?key|secret|credential|client[-_]?secret|webhook[-_]?token)=)([^&#\s]+)/gi;function l(a){return function a(b,c,g){if("string"==typeof b)return c?d:m(b);if("number"==typeof b||"bigint"==typeof b)return c?d:b;if(null==b||"boolean"==typeof b||b instanceof Date)return b;if(Array.isArray(b))return g.has(b)?[]:(g.add(b),b.map(b=>a(b,c,g)));if("object"!=typeof b)return b;if(g.has(b))return{};g.add(b);let h={};for(let[d,i]of Object.entries(b)){let b=function(a){let b=a.replace(/[^A-Za-z0-9]/g,"").toLowerCase();return!!b&&"tokenusage"!==b&&(!!e.has(b)||f.some(a=>b.endsWith(a)))}(d);h[d]=a(i,c||b,g)}return h}(a,!1,new WeakSet)}function m(a){return a.replace(h,(a,b)=>`${b}${d}`).replace(k,(a,b)=>`${b}${d}`).replace(i,d).replace(j,(a,b,c,e)=>`${b}${c}${b}:${e}${d}${e}`).replace(g,(a,b,c)=>`${b}${c}${d}`)}function n(a,b){return m((a instanceof Error?a.message:"string"==typeof a?a:b)||b)}},97411:(a,b,c)=>{"use strict";c.d(b,{CS:()=>u,J$:()=>o,Oj:()=>t,Yf:()=>s,eB:()=>q,lz:()=>p,u_:()=>r,yt:()=>k});var d=c(31421),e=c(48161),f=c.n(e),g=c(76760),h=c.n(g),i=c(51455),j=c(11315);let k="https://docs.openclaw.ai/install",l="# >>> OpenClaw PATH >>>",m="# <<< OpenClaw PATH <<<",n="agentos-env.sh";function o(){return h().join(f().homedir(),".openclaw")}function p(){return h().join(o(),"bin","win32"===process.platform?"openclaw.cmd":"openclaw")}function q(){return h().join(o(),"tools","node","bin","win32"===process.platform?"openclaw.cmd":"openclaw")}function r(){return h().join(f().homedir(),".local","bin","win32"===process.platform?"openclaw.cmd":"openclaw")}function s(){return"win32"===process.platform?`& ([scriptblock]::Create((iwr -useb https://openclaw.ai/install.ps1))) -Tag ${j.L} -NoOnboard`:`set -euo pipefail; curl -fsSL --proto '=https' --tlsv1.2 https://openclaw.ai/install-cli.sh | bash -s -- --prefix "$HOME/.openclaw" --version ${j.L} --no-onboard`}async function t(a={}){var b,c,d,e;let g,h,i,j=a.platform??process.platform,k=a.homeDir??f().homedir(),l=a.env??process.env,m=B(j).join(k,".openclaw","bin"),n=v((b=l)[z(b,j)],m,j),o=(c=l,d=m,g=z(c,e=j),(i=w(h=c[g],d,e))!==(h??"")&&(c[g]=i,!0));if("win32"===j){let b=await y(m,{currentUserPath:a.windowsUserPath,runPowerShellScript:a.runPowerShellScript});return{binDir:m,alreadyOnPath:n,updatedCurrentProcess:o,updatedFiles:[],createdFiles:[],updatedWindowsUserPath:b.updated,warnings:b.warnings}}let p=await x({binDir:m,homeDir:k,platform:j,shell:a.shell??l.SHELL??""});return{binDir:m,alreadyOnPath:n,updatedCurrentProcess:o,updatedFiles:p.updatedFiles,createdFiles:p.createdFiles,updatedWindowsUserPath:!1,warnings:p.warnings}}function u(a){let b=a.binDir;return a.updatedWindowsUserPath?`Added ${b} to the Windows user PATH. Open a new terminal to use openclaw directly.`:Array.from(new Set([...a.updatedFiles,...a.createdFiles])).length>0?`Added ${b} to shell startup files. Open a new terminal to use openclaw directly.`:a.alreadyOnPath&&!a.updatedCurrentProcess?`${b} is already on PATH.`:`Prepared ${b} for the current AgentOS process. Open a new terminal after adding it to PATH if openclaw is not found.`}function v(a,b,c=process.platform){var d,e;let f=A(b,c);return(d=a,e=c,(d??"").split("win32"===e?";":":").map(a=>a.trim()).filter(Boolean)).some(a=>A(a,c)===f)}function w(a,b,c=process.platform){if(v(a,b,c))return a??"";let d="win32"===c?";":":";return a?.trim()?`${b}${d}${a}`:b}async function x(a){let b=h().join(a.homeDir,".openclaw"),c=h().join(b,n),d=[],e=[],f=[],g=await F(c,'# Managed by AgentOS. Adds the OpenClaw local-prefix binary directory.\ncase ":$PATH:" in\n *":$HOME/.openclaw/bin:"*) ;;\n *) export PATH="$HOME/.openclaw/bin:$PATH" ;;\nesac\n');for(let b of("created"===g?e.push(c):"updated"===g&&d.push(c),await C(a.homeDir,a.shell,a.platform)))try{let a="fish"===b.kind?[l,'if test -d "$HOME/.openclaw/bin"\n fish_add_path "$HOME/.openclaw/bin"\nend',m].join("\n"):[l,`[ -f "$HOME/.openclaw/${n}" ] && . "$HOME/.openclaw/${n}"`,m].join("\n"),c=await E(b.filePath,a);"created"===c?e.push(b.filePath):"updated"===c&&d.push(b.filePath)}catch(a){f.push(`Could not update ${b.filePath}: ${a instanceof Error?a.message:String(a)}`)}return{updatedFiles:d,createdFiles:e,warnings:f}}async function y(a,b){let c=b.runPowerShellScript??J,d=[],e=b.currentUserPath;try{var f;if(void 0===e&&(e=await c("[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetEnvironmentVariable('Path', 'User')")),v(e,a,"win32"))return{updated:!1,warnings:d};let b=w(e,a,"win32");return await c(`[Environment]::SetEnvironmentVariable('Path', ${(f=b,`'${f.replaceAll("'","''")}'`)}, 'User')`),{updated:!0,warnings:d}}catch(a){return d.push(`Could not update the Windows user PATH: ${a instanceof Error?a.message:String(a)}`),{updated:!1,warnings:d}}}function z(a,b){return"win32"!==b?"PATH":Object.keys(a).find(a=>"path"===a.toLowerCase())??"Path"}function A(a,b){let c=B(b).normalize(a.replace(/^["']|["']$/g,"")).replace(/[\\/]+$/,"");return"win32"===b?c.toLowerCase():c}function B(a){return"win32"===a?h().win32:h().posix}async function C(a,b,c){var d,e,f;let g=h().basename(b||""),i=await D([h().join(a,".zshrc"),h().join(a,".bashrc"),h().join(a,".bash_profile"),h().join(a,".profile")]),j=(d=a,e=g,f=c,"fish"===e?[h().join(d,".config","fish","conf.d","openclaw.fish")]:"zsh"===e?[h().join(d,".zshrc")]:"bash"===e?"darwin"===f?[h().join(d,".bash_profile"),h().join(d,".bashrc")]:[h().join(d,".bashrc"),h().join(d,".profile")]:[h().join(d,".profile")]).map(a=>({filePath:a,kind:"fish"===g&&a.endsWith(".fish")?"fish":"posix"}));for(let a of i)j.some(b=>b.filePath===a)||j.push({filePath:a,kind:"posix"});return j}async function D(a){let b=[];for(let c of a)await H(c)&&b.push(c);return b}async function E(a,b){let c=await H(a),d=c?await (0,i.readFile)(a,"utf8"):"",e=function(a,b){let c=b.endsWith("\n")?b:`${b}
|
|
14
|
+
`,d=RegExp(`${I(l)}[\\s\\S]*?${I(m)}\\n?`,"m");if(d.test(a))return a.replace(d,c);let e=a&&!a.endsWith("\n")?"\n":"",f=a.trim()?"\n":"";return`${a}${e}${f}${c}`}(d,b);return e===d?"unchanged":(await G(a,e),c?"updated":"created")}async function F(a,b){let c=await H(a);return(c?await (0,i.readFile)(a,"utf8"):"")===b?"unchanged":(await G(a,b),c?"updated":"created")}async function G(a,b){await (0,i.mkdir)(h().dirname(a),{recursive:!0}),await (0,i.writeFile)(a,b,"utf8")}async function H(a){try{return await (0,i.access)(a),!0}catch{return!1}}function I(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J(a){return new Promise((b,c)=>{let e=process.env.SystemRoot?h().join(process.env.SystemRoot,"System32","WindowsPowerShell","v1.0","powershell.exe"):"powershell.exe",f=Buffer.from(a,"utf16le").toString("base64"),g=(0,d.spawn)(e,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",f],{windowsHide:!0}),i="",j="";g.stdout.on("data",a=>{i+=a.toString()}),g.stderr.on("data",a=>{j+=a.toString()}),g.on("error",c),g.on("close",a=>{0===a?b(i.trim()):c(Error(j.trim()||`PowerShell exited with code ${a??"unknown"}.`))})})}},98717:(a,b,c)=>{"use strict";c.d(b,{$g:()=>m,As:()=>f,Lo:()=>j,Rd:()=>k,Z6:()=>l,fu:()=>o,jl:()=>g,mW:()=>p,pz:()=>h});var d=c(24117),e=c(96972);class f extends Error{constructor(a,b={}){super(a),this.name="NativeGatewayError",this.kind=b.kind??n(a),this.cause=b.cause}}class g extends f{constructor(a,b,c,d={}){super(a,d),this.method=b,this.sent=c,this.name="NativeGatewayRequestError"}}class h extends Error{constructor(a,b,c={}){super(a),this.kind=b,this.name="OpenClawGatewayClientError",this.cause=c.cause}}let i=[];function j(){return[...i]}function k(a,b){let c=m(b);l(a),i.unshift({at:new Date().toISOString(),operation:a,issue:p(c.message),kind:c.kind,recovery:o(c)}),i.splice(20)}function l(a){for(let b=i.length-1;b>=0;b-=1)i[b]?.operation===a&&i.splice(b,1)}function m(a){if(a instanceof h||a instanceof f)return new h(p(a.message),a.kind,{cause:a.cause??a});let b=a instanceof Error?a.message:String(a||"OpenClaw Gateway request failed.");return new h(p(b),n(b),{cause:a})}function n(a){return/protocol|version|hello|handshake/i.test(a)?"protocol-mismatch":/unknown method|method not found|unsupported method/i.test(a)?"unsupported":/auth|token|password|unauthorized|forbidden/i.test(a)?"auth":/scope|permission|not allowed/i.test(a)?"scope-limited":/base\s*hash|basehash|conflict|stale|precondition|version mismatch|already changed/i.test(a)?"conflict":/(^|[^a-z])rate limit(?:ed)?\b|retry after|too many requests/i.test(a)?"rate-limited":/invalid[_\s-]?request|invalid .*params|invalid json|malformed|schema|payload/i.test(a)?"malformed-response":/timed out|timeout/i.test(a)?"timeout":/connect|closed|unreachable|websocket/i.test(a)?"unreachable":"unknown"}function o(a){switch(a.kind){case"auth":return"Check the OpenClaw Gateway token/password, then repair local device access in Settings if the operator scope is missing.";case"conflict":return"Refresh the Gateway config snapshot, then retry the action.";case"scope-limited":return"Approve AgentOS as an OpenClaw operator with the required read/write/admin scopes.";case"protocol-mismatch":return`Update OpenClaw or AgentOS so the Gateway protocol overlaps AgentOS' supported range ${d.lY}-${d.ZX}.`;case"rate-limited":return"Wait for the OpenClaw Gateway config cooldown to expire, then retry the action.";case"unsupported":return"OpenClaw does not advertise this Gateway method; AgentOS will use the compatibility fallback when available.";case"timeout":return"Restart the OpenClaw Gateway, inspect diagnostics for slow handlers, then retry the action.";case"unreachable":return"Start or restart the OpenClaw Gateway, verify the endpoint, or keep using CLI fallback only for recovery.";case"malformed-response":return"Update OpenClaw or report the incompatible Gateway response shape.";default:return"Inspect OpenClaw diagnostics for the underlying Gateway failure."}}function p(a){let b=a?.trim();return b?(0,e.bS)(b).replace(/\b(authorization|bearer|token|password|secret|api[_-]?key)\b(\s*[:=]\s*)(["']?)[^\s"',;}{]+/gi,(a,b,c,d)=>`${b}${c}${d}[redacted]`).replace(/\b(AGENTOS_OPENCLAW_GATEWAY_TOKEN|OPENCLAW_GATEWAY_TOKEN|AGENTOS_OPENCLAW_GATEWAY_PASSWORD|OPENCLAW_GATEWAY_PASSWORD)=["']?[^"'\s]+/g,(a,b)=>`${b}=[redacted]`).replace(/__OPENCLAW_REDACTED__/g,"[redacted]"):""}}};
|