agentroam-runtime-darwin-arm64 0.2.0-preview.7 → 0.2.0-preview.8
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/manifest.json +1 -1
- package/package.json +1 -1
- package/runtime/.next/BUILD_ID +1 -1
- package/runtime/.next/app-path-routes-manifest.json +1 -1
- package/runtime/.next/build-manifest.json +2 -2
- package/runtime/.next/prerender-manifest.json +1 -1
- package/runtime/.next/server/app/_not-found.html +1 -1
- package/runtime/.next/server/app/_not-found.rsc +1 -1
- package/runtime/.next/server/app/api/agent/abort/route.js +2 -2
- package/runtime/.next/server/app/api/agent/abort/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/answer/route.js +2 -2
- package/runtime/.next/server/app/api/agent/answer/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/model/route.js +1 -1
- package/runtime/.next/server/app/api/agent/run/route.js +2 -2
- package/runtime/.next/server/app/api/agent/run/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/runtime-health/route.js +1 -1
- package/runtime/.next/server/app/api/agent/runtime-health/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/runtime-health.body +1 -1
- package/runtime/.next/server/app/api/agent/steer/route.js +2 -2
- package/runtime/.next/server/app/api/agent/steer/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/agent/stream/route.js +6 -6
- package/runtime/.next/server/app/api/agent/stream/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/mcp/connect/route.js +1 -1
- package/runtime/.next/server/app/api/plugins/load/route.js +2 -2
- package/runtime/.next/server/app/api/projects/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/projects/check/route.js +1 -1
- package/runtime/.next/server/app/api/projects/directories/route.js +1 -1
- package/runtime/.next/server/app/api/projects/roots/route.js +1 -1
- package/runtime/.next/server/app/api/projects/route.js +1 -1
- package/runtime/.next/server/app/api/remote-tools/register/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/changes/route.js +2 -2
- package/runtime/.next/server/app/api/sessions/[id]/changes/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/fork/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/fork/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/goals/route.js +2 -2
- package/runtime/.next/server/app/api/sessions/[id]/goals/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/handoff/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/handoff/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/route.js +2 -2
- package/runtime/.next/server/app/api/sessions/[id]/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/sessions/route.js +2 -2
- package/runtime/.next/server/app/api/sessions/route.js.nft.json +1 -1
- package/runtime/.next/server/app/api/skills/route.js +2 -2
- package/runtime/.next/server/app/api/tools/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/login/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/logout/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/revoke-all/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/setup/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/status/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/status.body +1 -0
- package/runtime/.next/server/app/api/web-auth/status.meta +1 -0
- package/runtime/.next/server/app/api/web-console/bootstrap/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/device-state/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/history/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/preferences/route.js +1 -1
- package/runtime/.next/server/app/web.html +1 -1
- package/runtime/.next/server/app/web.rsc +1 -1
- package/runtime/.next/server/app-paths-manifest.json +16 -16
- package/runtime/.next/server/chunks/83.js +119 -0
- package/runtime/.next/server/pages/404.html +1 -1
- package/runtime/.next/server/pages/500.html +1 -1
- package/runtime/.next/server/server-reference-manifest.json +1 -1
- package/runtime/.next/server/webpack-runtime.js +1 -1
- package/runtime/package-lock.json +1 -1
- package/runtime/package.json +1 -1
- package/runtime/webapp/dist/assets/{App-D8mcRu-Q.js → App-BipEZAhs.js} +54 -54
- package/runtime/webapp/dist/assets/{index-BjCuCFYF.js → index-1C7w3q4Y.js} +1 -1
- package/runtime/webapp/dist/index.html +1 -1
- package/runtime/.next/server/chunks/988.js +0 -119
- /package/runtime/.next/static/{WbNomgtKBalC4rAWPGRjU → 9pvPG6rD0pKUnx50jLZOe}/_buildManifest.js +0 -0
- /package/runtime/.next/static/{WbNomgtKBalC4rAWPGRjU → 9pvPG6rD0pKUnx50jLZOe}/_ssgManifest.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var e={};e.id=289,e.ids=[289],e.modules={5890:e=>{e.exports=require("better-sqlite3")},399:e=>{e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},517:e=>{e.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},9801:e=>{e.exports=require("os")},7718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},5673:e=>{e.exports=require("node:events")},7561:e=>{e.exports=require("node:fs")},3977:e=>{e.exports=require("node:fs/promises")},8849:e=>{e.exports=require("node:http")},2286:e=>{e.exports=require("node:https")},612:e=>{e.exports=require("node:os")},9411:e=>{e.exports=require("node:path")},1747:e=>{e.exports=require("node:readline")},1041:e=>{e.exports=require("node:url")},1851:(e,r,t)=>{t.r(r),t.d(r,{originalPathname:()=>h,patchFetch:()=>
|
|
1
|
+
"use strict";(()=>{var e={};e.id=289,e.ids=[289],e.modules={5890:e=>{e.exports=require("better-sqlite3")},399:e=>{e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},517:e=>{e.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},9801:e=>{e.exports=require("os")},7718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},5673:e=>{e.exports=require("node:events")},7561:e=>{e.exports=require("node:fs")},3977:e=>{e.exports=require("node:fs/promises")},8849:e=>{e.exports=require("node:http")},2286:e=>{e.exports=require("node:https")},612:e=>{e.exports=require("node:os")},9411:e=>{e.exports=require("node:path")},1747:e=>{e.exports=require("node:readline")},1041:e=>{e.exports=require("node:url")},1851:(e,r,t)=>{t.r(r),t.d(r,{originalPathname:()=>h,patchFetch:()=>v,requestAsyncStorage:()=>p,routeModule:()=>c,serverHooks:()=>m,staticGenerationAsyncStorage:()=>l});var s={};t.r(s),t.d(s,{DELETE:()=>d,GET:()=>u});var n=t(7786),o=t(5042),i=t(2184),a=t(2110);async function u(e){let{userId:r}=(0,a.nQ)(),t=new URL(e.url);return Response.json({history:a.hw.listHistory(r,t.searchParams.get("q")||"",Math.min(200,Number(t.searchParams.get("limit")||100)),t.searchParams.get("terminalId")||void 0)})}async function d(e){let{userId:r}=(0,a.nQ)(),t=await e.json();return t.id?a.hw.deleteHistory(r,Number(t.id)):a.hw.clearHistory(r,t.terminalId||void 0),new Response(null,{status:204})}let c=new n.AppRouteRouteModule({definition:{kind:o.x.APP_ROUTE,page:"/api/web-console/history/route",pathname:"/api/web-console/history",filename:"route",bundlePath:"app/api/web-console/history/route"},resolvedPagePath:"/Users/caoqu/team-agent/customer-agent/packages/server/app/api/web-console/history/route.ts",nextConfigOutput:"standalone",userland:s}),{requestAsyncStorage:p,staticGenerationAsyncStorage:l,serverHooks:m}=c,h="/api/web-console/history/route";function v(){return(0,i.patchFetch)({serverHooks:m,staticGenerationAsyncStorage:l})}},7786:(e,r,t)=>{e.exports=t(517)},785:(e,r,t)=>{t.d(r,{kO:()=>o,sr:()=>i});var s=t(9411);let n=function(){let e=process.argv[1];if(e){let r=(0,s.dirname)((0,s.resolve)(e)),t=`${s.sep}node_modules${s.sep}.bin`;return r.endsWith(t)?(0,s.resolve)(r,"..",".."):r}return(0,s.resolve)(process.cwd())}();function o(){return function(e=process.env,r=n){return(0,s.resolve)(e.AGENT_DATA_DIR?.trim()||r)}()}function i(){return function(e=process.env,r=n){return(0,s.resolve)(e.AGENT_WORKING_DIRECTORY?.trim()||r)}(process.env,o())}},2110:(e,r,t)=>{t.d(r,{Qx:()=>d,hw:()=>i.hw,nQ:()=>u});var s=t(6005),n=t(1322),o=t(785),i=t(3710);let a=new n.T3((0,o.kO)());function u(){return{userId:a.getOrCreatePrincipal().userId,username:"local",deviceId:"browser"}}function d(){let e=Date.now(),r=(0,s.randomBytes)(24).toString("base64url"),t=e+6e4,n=u();return a.issueWsNonce(r,n.userId,t,e),{nonce:r,expiresAt:t,principal:n}}},3710:(e,r,t)=>{t.d(r,{$U:()=>p,Ci:()=>m,VP:()=>o,Xd:()=>c,ZA:()=>a,ap:()=>l,hw:()=>u,ki:()=>i,yN:()=>h});var s=t(1322),n=t(785);let o="customer_agent_session",i="customer_agent_device",a=new s.E0(new s.S3((0,n.kO)())),u=new s.XU((0,n.kO)());function d(e){let r={};for(let t of(e.headers.get("cookie")||"").split(";")){let e=t.indexOf("=");e>0&&(r[t.slice(0,e).trim()]=decodeURIComponent(t.slice(e+1).trim()))}return r}function c(e){return d(e)[o]||null}function p(e){let r=d(e);return{ip:e.headers.get("x-forwarded-for")?.split(",")[0].trim()||"unknown",userAgent:e.headers.get("user-agent")||"",deviceId:r[i],deviceName:e.headers.get("x-device-name")||""}}function l(e){let r=a.authenticateToken(c(e));return a.validateCsrf(r,e.headers.get("x-csrf-token")),r}function m(e,r,t){return{httpOnly:t,sameSite:"strict",secure:"https"===("1"===process.env.AGENT_TRUST_TUNNEL_PROXY?e.headers.get("x-forwarded-proto"):null)||"https:"===new URL(e.url).protocol,path:"/",maxAge:r}}function h(e){let r=e instanceof s.CT?e:new s.CT("UNAUTHENTICATED","认证失败",401);return Response.json({error:{code:r.code,message:r.message}},{status:r.status})}}};var r=require("../../../../webpack-runtime.js");r.C(e);var t=e=>r(r.s=e),s=r.X(0,[375,322],()=>t(1851));module.exports=s})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var e={};e.id=792,e.ids=[792],e.modules={5890:e=>{e.exports=require("better-sqlite3")},399:e=>{e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},517:e=>{e.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},9801:e=>{e.exports=require("os")},7718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},5673:e=>{e.exports=require("node:events")},7561:e=>{e.exports=require("node:fs")},3977:e=>{e.exports=require("node:fs/promises")},8849:e=>{e.exports=require("node:http")},2286:e=>{e.exports=require("node:https")},612:e=>{e.exports=require("node:os")},9411:e=>{e.exports=require("node:path")},1747:e=>{e.exports=require("node:readline")},1041:e=>{e.exports=require("node:url")},5402:(e,r,t)=>{t.r(r),t.d(r,{originalPathname:()=>
|
|
1
|
+
"use strict";(()=>{var e={};e.id=792,e.ids=[792],e.modules={5890:e=>{e.exports=require("better-sqlite3")},399:e=>{e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},517:e=>{e.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},9801:e=>{e.exports=require("os")},7718:e=>{e.exports=require("node:child_process")},6005:e=>{e.exports=require("node:crypto")},5673:e=>{e.exports=require("node:events")},7561:e=>{e.exports=require("node:fs")},3977:e=>{e.exports=require("node:fs/promises")},8849:e=>{e.exports=require("node:http")},2286:e=>{e.exports=require("node:https")},612:e=>{e.exports=require("node:os")},9411:e=>{e.exports=require("node:path")},1747:e=>{e.exports=require("node:readline")},1041:e=>{e.exports=require("node:url")},5402:(e,r,t)=>{t.r(r),t.d(r,{originalPathname:()=>v,patchFetch:()=>x,requestAsyncStorage:()=>m,routeModule:()=>f,serverHooks:()=>g,staticGenerationAsyncStorage:()=>h});var n={};t.r(n),t.d(n,{GET:()=>d,PATCH:()=>l});var s=t(7786),o=t(5042),i=t(2184),a=t(1890),u=t(1322),c=t(2110);let p=e=>({userId:e,revision:1,theme:"black",terminalFontSize:11,fileButtonPosition:{xRatio:.94,yRatio:.65,anchor:"right"},keybarPosition:{xRatio:.5,yRatio:.95,anchor:"bottom"},keybarHidden:!1,keyOrder:[],pinnedCommands:(0,u._O)(),updatedAt:new Date().toISOString()});async function d(){let{userId:e}=(0,c.nQ)();return a.NextResponse.json({preferences:c.hw.getPreferences(e)??p(e)})}async function l(e){let{userId:r}=(0,c.nQ)(),t=c.hw.getPreferences(r)??p(r),n=await e.json(),s=t.pinnedCommands;if(Object.prototype.hasOwnProperty.call(n,"pinnedCommands"))try{s=(0,u.l7)(n.pinnedCommands)}catch(e){return a.NextResponse.json({error:{code:"INVALID_PINNED_COMMANDS",message:e instanceof Error?e.message:"置顶命令无效"}},{status:400})}let o={...t,...n,pinnedCommands:s,userId:r,revision:t.revision+1,updatedAt:new Date().toISOString()},i=c.hw.getPreferences(r);return c.hw.savePreferences(o,i?t.revision:null)?a.NextResponse.json({preferences:o}):a.NextResponse.json({error:{code:"REVISION_CONFLICT",message:"偏好已在其他设备更新"}},{status:409})}let f=new s.AppRouteRouteModule({definition:{kind:o.x.APP_ROUTE,page:"/api/web-console/preferences/route",pathname:"/api/web-console/preferences",filename:"route",bundlePath:"app/api/web-console/preferences/route"},resolvedPagePath:"/Users/caoqu/team-agent/customer-agent/packages/server/app/api/web-console/preferences/route.ts",nextConfigOutput:"standalone",userland:n}),{requestAsyncStorage:m,staticGenerationAsyncStorage:h,serverHooks:g}=f,v="/api/web-console/preferences/route";function x(){return(0,i.patchFetch)({serverHooks:g,staticGenerationAsyncStorage:h})}},785:(e,r,t)=>{t.d(r,{kO:()=>o,sr:()=>i});var n=t(9411);let s=function(){let e=process.argv[1];if(e){let r=(0,n.dirname)((0,n.resolve)(e)),t=`${n.sep}node_modules${n.sep}.bin`;return r.endsWith(t)?(0,n.resolve)(r,"..",".."):r}return(0,n.resolve)(process.cwd())}();function o(){return function(e=process.env,r=s){return(0,n.resolve)(e.AGENT_DATA_DIR?.trim()||r)}()}function i(){return function(e=process.env,r=s){return(0,n.resolve)(e.AGENT_WORKING_DIRECTORY?.trim()||r)}(process.env,o())}},2110:(e,r,t)=>{t.d(r,{Qx:()=>c,hw:()=>i.hw,nQ:()=>u});var n=t(6005),s=t(1322),o=t(785),i=t(3710);let a=new s.T3((0,o.kO)());function u(){return{userId:a.getOrCreatePrincipal().userId,username:"local",deviceId:"browser"}}function c(){let e=Date.now(),r=(0,n.randomBytes)(24).toString("base64url"),t=e+6e4,s=u();return a.issueWsNonce(r,s.userId,t,e),{nonce:r,expiresAt:t,principal:s}}},3710:(e,r,t)=>{t.d(r,{$U:()=>d,Ci:()=>f,VP:()=>o,Xd:()=>p,ZA:()=>a,ap:()=>l,hw:()=>u,ki:()=>i,yN:()=>m});var n=t(1322),s=t(785);let o="customer_agent_session",i="customer_agent_device",a=new n.E0(new n.S3((0,s.kO)())),u=new n.XU((0,s.kO)());function c(e){let r={};for(let t of(e.headers.get("cookie")||"").split(";")){let e=t.indexOf("=");e>0&&(r[t.slice(0,e).trim()]=decodeURIComponent(t.slice(e+1).trim()))}return r}function p(e){return c(e)[o]||null}function d(e){let r=c(e);return{ip:e.headers.get("x-forwarded-for")?.split(",")[0].trim()||"unknown",userAgent:e.headers.get("user-agent")||"",deviceId:r[i],deviceName:e.headers.get("x-device-name")||""}}function l(e){let r=a.authenticateToken(p(e));return a.validateCsrf(r,e.headers.get("x-csrf-token")),r}function f(e,r,t){return{httpOnly:t,sameSite:"strict",secure:"https"===("1"===process.env.AGENT_TRUST_TUNNEL_PROXY?e.headers.get("x-forwarded-proto"):null)||"https:"===new URL(e.url).protocol,path:"/",maxAge:r}}function m(e){let r=e instanceof n.CT?e:new n.CT("UNAUTHENTICATED","认证失败",401);return Response.json({error:{code:r.code,message:r.message}},{status:r.status})}}};var r=require("../../../../webpack-runtime.js");r.C(e);var t=e=>r(r.s=e),n=r.X(0,[375,703,322],()=>t(5402));module.exports=n})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/webpack-22b57460ff31be13.js"/><script src="/_next/static/chunks/3cc391f0-6377b9b71382a170.js" async=""></script><script src="/_next/static/chunks/183-ffe4acb07968be9e.js" async=""></script><script src="/_next/static/chunks/main-app-07d67f2d4e96ecb8.js" async=""></script><script src="/_next/static/chunks/108-5a2df9f74c5fd4ea.js" async=""></script><script src="/_next/static/chunks/app/web/page-c8af455b0fde4d74.js" async=""></script><title>AgentRoam</title><meta name="description" content="General-purpose AI agent API server"/><script src="/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><main class="jsx-3fdfcb7d409f1983 remote-gate is-connecting"><div aria-hidden="true" class="jsx-3fdfcb7d409f1983 remote-grid"></div><div aria-hidden="true" class="jsx-3fdfcb7d409f1983 remote-stream remote-stream-left"></div><div aria-hidden="true" class="jsx-3fdfcb7d409f1983 remote-stream remote-stream-right"></div><div class="jsx-3fdfcb7d409f1983 remote-content"><div aria-hidden="true" class="jsx-3fdfcb7d409f1983 remote-scene"><div class="jsx-3fdfcb7d409f1983 remote-beam"></div><div class="jsx-3fdfcb7d409f1983 remote-pulse remote-pulse-one"></div><div class="jsx-3fdfcb7d409f1983 remote-pulse remote-pulse-two"></div><div class="jsx-3fdfcb7d409f1983 remote-device"><div class="jsx-3fdfcb7d409f1983 remote-device-back"></div><div class="jsx-3fdfcb7d409f1983 remote-screen"><div class="jsx-3fdfcb7d409f1983 remote-screen-scan"></div><svg xmlns="http://www.w3.org/2000/svg" width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-monitor"><rect width="20" height="14" x="2" y="3" rx="2"></rect><line x1="8" x2="16" y1="21" y2="21"></line><line x1="12" x2="12" y1="17" y2="21"></line></svg></div><div class="jsx-3fdfcb7d409f1983 remote-device-stand"></div></div></div><div role="status" aria-label="正在连接远程控制台" class="jsx-3fdfcb7d409f1983 remote-status"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-monitor" aria-hidden="true"><rect width="20" height="14" x="2" y="3" rx="2"></rect><line x1="8" x2="16" y1="21" y2="21"></line><line x1="12" x2="12" y1="17" y2="21"></line></svg><span class="jsx-3fdfcb7d409f1983">远程连接中</span><span aria-hidden="true" class="jsx-3fdfcb7d409f1983 remote-elapsed">· 已持续 <!-- -->0<!-- --> 秒</span></div></div></main><script src="/_next/static/chunks/webpack-22b57460ff31be13.js" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0]);self.__next_f.push([2,null])</script><script>self.__next_f.push([1,"1:I[7709,[],\"\"]\n3:I[5613,[],\"ClientPageRoot\"]\n4:I[5431,[\"108\",\"static/chunks/108-5a2df9f74c5fd4ea.js\",\"541\",\"static/chunks/app/web/page-c8af455b0fde4d74.js\"],\"default\",1]\n5:I[1338,[],\"\"]\n6:I[1573,[],\"\"]\n8:I[6554,[],\"\"]\n9:[]\n"])</script><script>self.__next_f.push([1,"0:[\"$\",\"$L1\",null,{\"buildId\":\"
|
|
1
|
+
<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/webpack-22b57460ff31be13.js"/><script src="/_next/static/chunks/3cc391f0-6377b9b71382a170.js" async=""></script><script src="/_next/static/chunks/183-ffe4acb07968be9e.js" async=""></script><script src="/_next/static/chunks/main-app-07d67f2d4e96ecb8.js" async=""></script><script src="/_next/static/chunks/108-5a2df9f74c5fd4ea.js" async=""></script><script src="/_next/static/chunks/app/web/page-c8af455b0fde4d74.js" async=""></script><title>AgentRoam</title><meta name="description" content="General-purpose AI agent API server"/><script src="/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><main class="jsx-3fdfcb7d409f1983 remote-gate is-connecting"><div aria-hidden="true" class="jsx-3fdfcb7d409f1983 remote-grid"></div><div aria-hidden="true" class="jsx-3fdfcb7d409f1983 remote-stream remote-stream-left"></div><div aria-hidden="true" class="jsx-3fdfcb7d409f1983 remote-stream remote-stream-right"></div><div class="jsx-3fdfcb7d409f1983 remote-content"><div aria-hidden="true" class="jsx-3fdfcb7d409f1983 remote-scene"><div class="jsx-3fdfcb7d409f1983 remote-beam"></div><div class="jsx-3fdfcb7d409f1983 remote-pulse remote-pulse-one"></div><div class="jsx-3fdfcb7d409f1983 remote-pulse remote-pulse-two"></div><div class="jsx-3fdfcb7d409f1983 remote-device"><div class="jsx-3fdfcb7d409f1983 remote-device-back"></div><div class="jsx-3fdfcb7d409f1983 remote-screen"><div class="jsx-3fdfcb7d409f1983 remote-screen-scan"></div><svg xmlns="http://www.w3.org/2000/svg" width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-monitor"><rect width="20" height="14" x="2" y="3" rx="2"></rect><line x1="8" x2="16" y1="21" y2="21"></line><line x1="12" x2="12" y1="17" y2="21"></line></svg></div><div class="jsx-3fdfcb7d409f1983 remote-device-stand"></div></div></div><div role="status" aria-label="正在连接远程控制台" class="jsx-3fdfcb7d409f1983 remote-status"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-monitor" aria-hidden="true"><rect width="20" height="14" x="2" y="3" rx="2"></rect><line x1="8" x2="16" y1="21" y2="21"></line><line x1="12" x2="12" y1="17" y2="21"></line></svg><span class="jsx-3fdfcb7d409f1983">远程连接中</span><span aria-hidden="true" class="jsx-3fdfcb7d409f1983 remote-elapsed">· 已持续 <!-- -->0<!-- --> 秒</span></div></div></main><script src="/_next/static/chunks/webpack-22b57460ff31be13.js" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0]);self.__next_f.push([2,null])</script><script>self.__next_f.push([1,"1:I[7709,[],\"\"]\n3:I[5613,[],\"ClientPageRoot\"]\n4:I[5431,[\"108\",\"static/chunks/108-5a2df9f74c5fd4ea.js\",\"541\",\"static/chunks/app/web/page-c8af455b0fde4d74.js\"],\"default\",1]\n5:I[1338,[],\"\"]\n6:I[1573,[],\"\"]\n8:I[6554,[],\"\"]\n9:[]\n"])</script><script>self.__next_f.push([1,"0:[\"$\",\"$L1\",null,{\"buildId\":\"9pvPG6rD0pKUnx50jLZOe\",\"assetPrefix\":\"\",\"urlParts\":[\"\",\"web\"],\"initialTree\":[\"\",{\"children\":[\"web\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",true],\"initialSeedData\":[\"\",{\"children\":[\"web\",{\"children\":[\"__PAGE__\",{},[[\"$L2\",[\"$\",\"$L3\",null,{\"props\":{\"params\":{},\"searchParams\":{}},\"Component\":\"$4\"}],null],null],null]},[null,[\"$\",\"$L5\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\",\"web\",\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L6\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"notFoundStyles\":\"$undefined\"}]],null]},[[null,[\"$\",\"html\",null,{\"lang\":\"en\",\"children\":[\"$\",\"body\",null,{\"children\":[\"$\",\"$L5\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L6\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":\"404\"}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],\"notFoundStyles\":[]}]}]}]],null],null],\"couldBeIntercepted\":false,\"initialHead\":[null,\"$L7\"],\"globalErrorComponent\":\"$8\",\"missingSlots\":\"$W9\"}]\n"])</script><script>self.__next_f.push([1,"7:[[\"$\",\"meta\",\"0\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}],[\"$\",\"meta\",\"1\",{\"charSet\":\"utf-8\"}],[\"$\",\"title\",\"2\",{\"children\":\"AgentRoam\"}],[\"$\",\"meta\",\"3\",{\"name\":\"description\",\"content\":\"General-purpose AI agent API server\"}]]\n2:null\n"])</script></body></html>
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
3:I[5431,["108","static/chunks/108-5a2df9f74c5fd4ea.js","541","static/chunks/app/web/page-c8af455b0fde4d74.js"],"default",1]
|
|
3
3
|
4:I[1338,[],""]
|
|
4
4
|
5:I[1573,[],""]
|
|
5
|
-
0:["
|
|
5
|
+
0:["9pvPG6rD0pKUnx50jLZOe",[[["",{"children":["web",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["web",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","web","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[null,["$","html",null,{"lang":"en","children":["$","body",null,{"children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]]
|
|
6
6
|
6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"AgentRoam"}],["$","meta","3",{"name":"description","content":"General-purpose AI agent API server"}]]
|
|
7
7
|
1:null
|
|
@@ -1,40 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"/_not-found/page": "app/_not-found/page.js",
|
|
3
3
|
"/api/agent/model/route": "app/api/agent/model/route.js",
|
|
4
|
-
"/api/mcp/disconnect/route": "app/api/mcp/disconnect/route.js",
|
|
5
4
|
"/api/mcp/connect/route": "app/api/mcp/connect/route.js",
|
|
6
|
-
"/api/mcp/servers/route": "app/api/mcp/servers/route.js",
|
|
7
|
-
"/api/plugins/load/route": "app/api/plugins/load/route.js",
|
|
8
5
|
"/api/auth/verify/route": "app/api/auth/verify/route.js",
|
|
9
|
-
"/api/
|
|
6
|
+
"/api/mcp/disconnect/route": "app/api/mcp/disconnect/route.js",
|
|
7
|
+
"/api/mcp/servers/route": "app/api/mcp/servers/route.js",
|
|
10
8
|
"/api/memory/route": "app/api/memory/route.js",
|
|
9
|
+
"/api/memory/[key]/route": "app/api/memory/[key]/route.js",
|
|
10
|
+
"/api/plugins/load/route": "app/api/plugins/load/route.js",
|
|
11
11
|
"/api/projects/[id]/route": "app/api/projects/[id]/route.js",
|
|
12
|
-
"/api/projects/check/route": "app/api/projects/check/route.js",
|
|
13
12
|
"/api/projects/directories/route": "app/api/projects/directories/route.js",
|
|
14
|
-
"/api/projects/
|
|
13
|
+
"/api/projects/check/route": "app/api/projects/check/route.js",
|
|
15
14
|
"/api/projects/route": "app/api/projects/route.js",
|
|
16
15
|
"/api/remote-tools/register/route": "app/api/remote-tools/register/route.js",
|
|
17
|
-
"/api/
|
|
16
|
+
"/api/projects/roots/route": "app/api/projects/roots/route.js",
|
|
18
17
|
"/api/skills/route": "app/api/skills/route.js",
|
|
19
|
-
"/api/
|
|
20
|
-
"/api/web-auth/revoke-all/route": "app/api/web-auth/revoke-all/route.js",
|
|
18
|
+
"/api/tools/route": "app/api/tools/route.js",
|
|
21
19
|
"/api/web-auth/logout/route": "app/api/web-auth/logout/route.js",
|
|
22
|
-
"/api/web-auth/
|
|
20
|
+
"/api/web-auth/revoke-all/route": "app/api/web-auth/revoke-all/route.js",
|
|
23
21
|
"/api/web-auth/setup/route": "app/api/web-auth/setup/route.js",
|
|
22
|
+
"/api/web-auth/status/route": "app/api/web-auth/status/route.js",
|
|
24
23
|
"/api/web-console/history/route": "app/api/web-console/history/route.js",
|
|
24
|
+
"/api/web-auth/login/route": "app/api/web-auth/login/route.js",
|
|
25
25
|
"/api/web-console/preferences/route": "app/api/web-console/preferences/route.js",
|
|
26
26
|
"/web/page": "app/web/page.js",
|
|
27
|
-
"/api/agent/
|
|
27
|
+
"/api/agent/runtime-health/route": "app/api/agent/runtime-health/route.js",
|
|
28
|
+
"/api/agent/abort/route": "app/api/agent/abort/route.js",
|
|
28
29
|
"/api/agent/answer/route": "app/api/agent/answer/route.js",
|
|
30
|
+
"/api/agent/steer/route": "app/api/agent/steer/route.js",
|
|
29
31
|
"/api/agent/run/route": "app/api/agent/run/route.js",
|
|
30
|
-
"/api/agent/
|
|
31
|
-
"/api/agent/runtime-health/route": "app/api/agent/runtime-health/route.js",
|
|
32
|
+
"/api/agent/stream/route": "app/api/agent/stream/route.js",
|
|
32
33
|
"/api/sessions/[id]/fork/route": "app/api/sessions/[id]/fork/route.js",
|
|
33
|
-
"/api/sessions/[id]/handoff/route": "app/api/sessions/[id]/handoff/route.js",
|
|
34
|
-
"/api/sessions/route": "app/api/sessions/route.js",
|
|
35
34
|
"/api/sessions/[id]/changes/route": "app/api/sessions/[id]/changes/route.js",
|
|
36
|
-
"/api/
|
|
35
|
+
"/api/sessions/[id]/handoff/route": "app/api/sessions/[id]/handoff/route.js",
|
|
37
36
|
"/api/sessions/[id]/goals/route": "app/api/sessions/[id]/goals/route.js",
|
|
37
|
+
"/api/sessions/route": "app/api/sessions/route.js",
|
|
38
38
|
"/api/web-console/bootstrap/route": "app/api/web-console/bootstrap/route.js",
|
|
39
39
|
"/api/web-console/device-state/route": "app/api/web-console/device-state/route.js",
|
|
40
40
|
"/api/sessions/[id]/route": "app/api/sessions/[id]/route.js"
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"use strict";exports.id=83,exports.ids=[83],exports.modules={8224:(e,t,s)=>{s.d(t,{K:()=>i});class i{push(e){if(this.closed)return;let t=this.waiters.shift();t?t({value:e,done:!1}):this.values.push(e)}close(){if(!this.closed)for(let e of(this.closed=!0,this.waiters.splice(0)))e({value:void 0,done:!0})}[Symbol.asyncIterator](){return{next:async()=>{let e=this.values.shift();return void 0!==e?{value:e,done:!1}:this.closed?{value:void 0,done:!0}:new Promise(e=>this.waiters.push(e))}}}constructor(){this.values=[],this.waiters=[],this.closed=!1}}},3088:(e,t,s)=>{s.a(e,async(e,i)=>{try{s.d(t,{IW:()=>x});var r=s(7718),n=s(3977),a=s(612),o=s(9411),l=s(5881),u=s(2728),d=s(1322),c=s(8224),p=s(9956),h=s(5300),m=s(5779),f=s(132),y=e([u]);u=(y.then?(await y)():y)[0];let N=(0,l.promisify)(r.execFile),O=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;class A{consume(e){var t,s,i,r,n;if("system"===e.type&&"task_started"===e.subtype){if(!0===e.ambient||!0===e.skip_transcript||"local_agent"!==e.task_type&&!e.subagent_type||"string"!=typeof e.tool_use_id)return[];let t={ambient:!1,settled:!1,streamedText:!1,activity:{taskId:e.task_id,parentToolCallId:e.tool_use_id,agentName:e.subagent_type,description:e.description.trim(),status:"running",isBackgrounded:e.is_backgrounded,spawnDepth:e.spawn_depth,messages:[]}};return this.tasks.set(e.task_id,t),[this.update(t)]}if("system"===e.type&&"task_progress"===e.subtype){let t=this.tasks.get(e.task_id);return!t||t.ambient?[]:(t.activity={...t.activity,description:e.description.trim()||t.activity.description,agentName:e.subagent_type??t.activity.agentName,summary:e.summary?.trim()||t.activity.summary,lastToolName:e.last_tool_name??t.activity.lastToolName,elapsedSeconds:I(e.usage.duration_ms),toolUses:S(e.usage.tool_uses)},[this.update(t)])}if("system"===e.type&&"task_updated"===e.subtype){let s=this.tasks.get(e.task_id);return!s||s.ambient?[]:(s.activity={...s.activity,status:e.patch.status?(t=e.patch.status,"completed"===t||"failed"===t?t:"killed"===t?"stopped":"running"):s.activity.status,description:e.patch.description?.trim()||s.activity.description,isBackgrounded:e.patch.is_backgrounded??s.activity.isBackgrounded,summary:e.patch.error?.trim()||s.activity.summary},[this.update(s)])}if("system"===e.type&&"task_notification"===e.subtype){let t=this.tasks.get(e.task_id);return!t||t.ambient||!0===e.ambient||!0===e.skip_transcript?[]:(t.activity={...t.activity,status:e.status,summary:e.summary?.trim()||t.activity.summary,elapsedSeconds:e.usage?I(e.usage.duration_ms):t.activity.elapsedSeconds,toolUses:e.usage?S(e.usage.tool_uses):t.activity.toolUses},t.settled=!0,[this.update(t)])}let a=w(e);if(!a)return[];let o=[...this.tasks.values()].find(e=>e.activity.parentToolCallId===a&&!e.ambient);if(!o)return[];if("stream_event"===e.type){let t=e.event;if("content_block_delta"!==t.type)return[];let s=R(t.delta);return"text_delta"===s.type&&"string"==typeof s.text&&s.text?(o.activity={...o.activity,messages:b(o.activity.messages,s.text)},o.streamedText=!0,[this.update(o)]):[]}if("assistant"===e.type){let t=o.activity.messages,s=Array.isArray(e.message.content)?e.message.content:[],i=T(s);for(let e of(i&&!o.streamedText&&(t=b(t,i)),s)){let s=E(e);s&&(t=function(e,t){let s=e[e.length-1];return s?.role==="assistant"?[...e.slice(0,-1),{...s,toolCalls:[...s.toolCalls??[],t]}]:[...e,{role:"assistant",content:"",toolCalls:[t]}]}(t,s))}return(o.streamedText=!1,t===o.activity.messages)?[]:(o.activity={...o.activity,messages:t},[this.update(o)])}if("user"===e.type){let t=e.message.content;if(!Array.isArray(t))return[];let a=o.activity.messages;for(let e of t){let t=R(e);"tool_result"===t.type&&"string"==typeof t.tool_use_id&&(s=a,i=t.tool_use_id,r=T(t.content),n=!0===t.is_error,a=[...s,{role:"tool",content:r,toolCallId:i,...n?{name:"error"}:{}}])}return a===o.activity.messages?[]:(o.activity={...o.activity,messages:a},[this.update(o)])}return[]}hasActiveBackgroundTasks(){return[...this.tasks.values()].some(({activity:e,ambient:t,settled:s})=>!t&&!s&&!0===e.isBackgrounded)}stopActive(){let e=[];for(let t of this.tasks.values())t.ambient||t.settled||(t.activity={...t.activity,status:"stopped"},e.push(this.update(t)));return e}update(e){return{type:"native_subagent_update",activity:{...e.activity,messages:e.activity.messages.map(e=>({...e,...e.toolCalls?{toolCalls:e.toolCalls.map(e=>({...e}))}:{}}))}}}constructor(){this.tasks=new Map}}class x{constructor(e={}){this.agentType="claude-code",this.drafts=new Map,this.ownedSessions=new Set,this.activeQueries=new Map,this.activeInputs=new Map,this.pendingPermissions=new Map,this.abortedSessions=new Set,this.permissionEvents=new Map,this.sessionRoot=e.sessionRoot??(0,o.join)((0,a.homedir)(),".claude","projects")}async health(){try{let{stdout:e}=await N("claude",["--version"],{encoding:"utf8",timeout:5e3});return{agentType:this.agentType,available:!0,label:"Claude Code",version:e.trim()}}catch(e){return{agentType:this.agentType,available:!1,label:"Claude Code",error:e instanceof Error?e.message:String(e)}}}async discoverSessions(){let[e,t]=await Promise.all([this.listAllSessions(),this.externalOccupancy()]),s=e.map(e=>this.toSummary(e,t)),i=new Set(s.map(e=>e.nativeSessionId));for(let e of this.drafts.values())i.has(e.nativeSessionId)||s.push(e);return s}async getSession(e){let t=this.drafts.get(e),[s,i,r]=await Promise.all([this.findSession(e),(0,u.getSessionMessages)(e).catch(()=>[]),this.externalOccupancy()]);if(!s&&!t)throw new f.n(`Claude Code session not found: ${e}`,"SESSION_NOT_FOUND");let n=s?this.toSummary(s,r):t,a=_(i),o=await this.recoverSubagentActivities(e,n.cwd,a);return{...n,messages:a,events:o}}async getSessionWatchPath(e){return this.findSessionPath(e)}async create(e){let t=crypto.randomUUID(),s=new Date().toISOString(),i={id:(0,m.F)(this.agentType,t),agentType:this.agentType,nativeSessionId:t,title:e.title,cwd:e.cwd,projectId:e.projectId,created:s,updated:s,status:"idle",occupancy:"available",sourceLabel:"Claude Code SDK",canResume:!0,canDelete:!1};return this.drafts.set(t,i),i}async *run(e,t,s,i,r,n){if(this.activeQueries.has(e))throw new f.n("Claude Code session is already running","SESSION_OCCUPIED");let a=await this.getSession(e);if("owned-externally"===a.occupancy)throw new f.n("Claude Code session is open in another client","SESSION_OCCUPIED");let o=n?.goal?`/goal ${n.goal.objective}`:t,l=g(o,void 0,s),p=this.drafts.has(e),h=(0,d.Ny)(n?.permissionMode),m="full-access"===h?void 0:(t,s,i)=>this.requestPermission(e,t,s,i,h,a.cwd,n?.brokerRunId),y=new c.K;y.push(l);let v=(0,u.query)({prompt:y,options:{cwd:a.cwd,...p?{sessionId:e}:{resume:e},includePartialMessages:!0,forwardSubagentText:!0,agentProgressSummaries:!0,permissionMode:"full-access"===h?"bypassPermissions":"default",..."full-access"===h?{allowDangerouslySkipPermissions:!0}:{canUseTool:m},tools:{type:"preset",preset:"claude_code"},skills:"all"}});this.activeQueries.set(e,v),this.activeInputs.set(e,y),this.ownedSessions.add(e);let _=new c.K;this.permissionEvents.set(e,e=>_.push(e));let I="",S=new A,b=null;try{let t=v[Symbol.asyncIterator](),s=_[Symbol.asyncIterator](),i=t.next(),r=s.next();for(;;){let n=await Promise.race([i.then(e=>({source:"sdk",result:e})),r.then(e=>({source:"permission",result:e}))]);if("permission"===n.source){n.result.done||(yield n.result.value),r=s.next();continue}if(n.result.done){let t=this.abortedSessions.delete(e);if(S.hasActiveBackgroundTasks()){for(let e of S.stopActive())yield e;yield t?{type:"turn_aborted"}:{type:"error",message:"Claude Code ended before a background subagent completed",code:"NATIVE_PROTOCOL_ERROR"},b=null}else t&&(yield{type:"turn_aborted"});break}let a=n.result.value;for(let e of(i=t.next(),S.consume(a)))yield e;for(let e of function(e,t){if("active_goal"===e.type)return e.value?[{type:"runtime_progress",progressId:"claude:goal",phase:"status",label:"正在推进目标",current:e.value.iterations,detail:e.value.last_reason||e.value.condition}]:[];if(w(e))return[];if("stream_event"===e.type){let t=e.event;if("content_block_delta"===t.type){let e=R(t.delta);if("text_delta"===e.type&&"string"==typeof e.text)return[{type:"text_chunk",text:e.text}]}return[]}if("tool_progress"===e.type)return"string"==typeof e.tool_use_id&&"number"==typeof e.elapsed_time_seconds&&Number.isFinite(e.elapsed_time_seconds)?[{type:"runtime_progress",progressId:`claude:tool:${e.tool_use_id}`,phase:"tool",label:"string"==typeof e.tool_name&&e.tool_name?`正在使用 ${e.tool_name}`:"正在使用工具",toolCallId:e.tool_use_id,elapsedSeconds:Math.max(0,e.elapsed_time_seconds),detail:`${Math.max(0,Math.round(e.elapsed_time_seconds))} 秒`}]:[];if("system"===e.type&&"thinking_tokens"===e.subtype){if("number"!=typeof e.estimated_tokens||!Number.isFinite(e.estimated_tokens))return[];let t=Math.max(0,Math.round(e.estimated_tokens));return[{type:"runtime_progress",progressId:"claude:thinking",phase:"thinking",label:"正在思考",current:t,detail:`${t.toLocaleString("en-US")} tokens`}]}if("system"===e.type&&"api_retry"===e.subtype){if("number"!=typeof e.attempt||"number"!=typeof e.max_retries||!Number.isFinite(e.attempt)||!Number.isFinite(e.max_retries))return[];let t=Math.max(0,Math.round(e.attempt)),s=Math.max(0,Math.round(e.max_retries));return[{type:"runtime_progress",progressId:"claude:api-retry",phase:"retry",label:"请求重试",current:t,total:s,detail:`${t}/${s}`}]}if("system"===e.type&&"status"===e.subtype&&e.status){let t="compacting"===e.status?"正在压缩上下文":"正在请求模型";return[{type:"runtime_progress",progressId:"claude:status",phase:"status",label:t}]}if("system"===e.type&&"informational"===e.subtype)return"string"==typeof e.content&&e.content.trim()?[{type:"runtime_progress",progressId:e.tool_use_id?`claude:info:${e.tool_use_id}`:"claude:info",phase:"status",label:e.content.trim(),...e.tool_use_id?{toolCallId:e.tool_use_id}:{}}]:[];if("system"===e.type&&"hook_progress"===e.subtype)return"string"==typeof e.hook_name&&e.hook_name.trim()?[{type:"runtime_progress",progressId:`claude:hook:${e.hook_id}`,phase:"status",label:`正在运行 ${e.hook_name.trim()}`,detail:"string"==typeof e.hook_event&&e.hook_event.trim()?e.hook_event.trim():void 0}]:[];if("system"===e.type&&"task_progress"===e.subtype){if("string"!=typeof e.task_id||"string"!=typeof e.description||!e.description.trim())return[];let t="number"==typeof e.usage?.duration_ms&&Number.isFinite(e.usage.duration_ms)?Math.max(0,Math.round(e.usage.duration_ms/1e3)):void 0;return[{type:"runtime_progress",progressId:`claude:task:${e.task_id}`,phase:"status",label:e.description.trim(),...e.tool_use_id?{toolCallId:e.tool_use_id}:{},...void 0===t?{}:{elapsedSeconds:t,detail:`${t} 秒`}}]}if("assistant"===e.type){let s=[],i=Array.isArray(e.message.content)?e.message.content:[];if(!t){let e=T(i);e&&s.push({type:"text_chunk",text:e})}for(let e of i){let t=E(e);t&&s.push({type:"tool_call",toolCall:t})}return s}if("user"===e.type){let t=e.message.content;return Array.isArray(t)?t.flatMap(e=>{let t=R(e);return"tool_result"!==t.type||"string"!=typeof t.tool_use_id?[]:[{type:"tool_result",result:{toolCallId:t.tool_use_id,content:T(t.content),isError:!0===t.is_error}}]}):[]}return[]}(a,I.length>0))"text_chunk"===e.type&&(I+=e.text),yield e;if("system"===a.type&&"init"===a.subtype&&a.session_id!==e)throw new f.n(`Claude Code returned unexpected session ID ${a.session_id}`,"NATIVE_PROTOCOL_ERROR");if("result"===a.type&&(b=a),b&&!S.hasActiveBackgroundTasks()){yield function(e,t){if("success"===e.subtype&&!e.is_error)return{type:"done",finalText:e.result||t};let s="result"in e&&"string"==typeof e.result?e.result:"errors"in e&&Array.isArray(e.errors)?e.errors.join("\n"):"Claude Code run failed";return{type:"error",message:s||"Claude Code run failed"}}(b,I),b=null;break}}this.drafts.delete(e)}catch(e){yield{type:"error",message:e instanceof Error?e.message:String(e),code:e instanceof f.n?e.code:"NATIVE_PROTOCOL_ERROR"}}finally{this.rejectPermissionsForSession(e,"Claude Code run ended"),_.close(),y.close(),this.permissionEvents.delete(e),this.activeQueries.delete(e),this.activeInputs.delete(e),this.ownedSessions.delete(e),this.abortedSessions.delete(e),v.close()}}async steer(e,t){let s=this.activeInputs.get(e);return!!s&&(s.push(g(t,"now")),!0)}async abort(e){let t=this.activeQueries.get(e);t&&(this.abortedSessions.add(e),await t.interrupt().catch(()=>void 0),t.close())}async answerQuestion(e,t){let s=this.pendingPermissions.get(e);return!!s&&(this.pendingPermissions.delete(e),"允许一次"===t.answer||"本会话允许"===t.answer?s.resolve({behavior:"allow",updatedInput:s.input,..."本会话允许"===t.answer&&s.suggestions?.length?{updatedPermissions:s.suggestions}:{}}):s.resolve({behavior:"deny",message:"取消"===t.answer?"User cancelled the operation":"User declined the operation",interrupt:"取消"===t.answer}),!0)}async dispose(){for(let e of this.activeInputs.values())e.close();for(let e of(this.activeInputs.clear(),this.activeQueries.values()))e.close();for(let[e,t]of(this.activeQueries.clear(),this.ownedSessions.clear(),this.pendingPermissions))t.resolve({behavior:"deny",message:"Customer Agent is shutting down",interrupt:!0}),this.pendingPermissions.delete(e)}async listAllSessions(){let e=[];for(let t=0;;t+=200){let s=await (0,u.listSessions)({limit:200,offset:t});if(e.push(...s),s.length<200)return e}}async findSession(e){let t=0;for(;;){let s=await (0,u.listSessions)({limit:200,offset:t}),i=s.find(t=>t.sessionId===e);if(i)return i;if(s.length<200)return;t+=200}}async externalOccupancy(){let e=new Set,[t,s]=await Promise.all([(0,h.g)("claude",this.sessionRoot),v()]);for(let s of t){let t=(0,o.basename)(s);t.endsWith(".jsonl")&&e.add(t.slice(0,-6))}for(let t of s)t.sessionId&&("done"!==t.state||"active"===t.status||"running"===t.status)&&e.add(t.sessionId);for(let t of this.ownedSessions)e.delete(t);return e}async recoverSubagentActivities(e,t,s){let i=new Set(s.flatMap(e=>(e.toolCalls??[]).filter(e=>"Agent"===e.name).map(e=>e.id)));if(0===i.size)return[];let r=await this.findSessionPath(e);if(!r)return[];let a=(0,o.join)((0,o.dirname)(r),e,"subagents"),l=await (0,u.listSubagents)(e,t?{dir:t}:void 0).catch(()=>[]);return(await Promise.all(l.map(async s=>{if(!/^[a-z0-9_-]+$/i.test(s))return null;try{let r=JSON.parse(await (0,n.readFile)((0,o.join)(a,`agent-${s}.meta.json`),"utf8"));if("string"!=typeof r.toolUseId||!i.has(r.toolUseId)||"string"!=typeof r.description||!r.description.trim())return null;let l=await (0,u.getSubagentMessages)(e,s,t?{dir:t}:void 0),d=_(l);if(0===d.length)return null;let c=[...d].reverse().find(e=>"assistant"===e.role&&e.content.trim())?.content.trim();return{type:"native_subagent_update",activity:{taskId:s,parentToolCallId:r.toolUseId,agentName:"string"==typeof r.agentType?r.agentType:void 0,description:r.description.trim(),status:c?"completed":"stopped",spawnDepth:"number"==typeof r.spawnDepth?r.spawnDepth:void 0,summary:c,messages:d}}}catch{return null}}))).filter(e=>null!==e)}async findSessionPath(e){let t;if((0,o.basename)(e)!==e||!O.test(e))return null;try{t=await (0,n.readdir)(this.sessionRoot,{withFileTypes:!0})}catch{return null}for(let s of t){if(!s.isDirectory())continue;let t=(0,o.join)(this.sessionRoot,s.name,`${e}.jsonl`);try{if((await (0,n.stat)(t)).isFile())return t}catch{}}return null}toSummary(e,t){let s=this.ownedSessions.has(e.sessionId),i=t.has(e.sessionId),r=s?"owned-by-customer-agent":i?"owned-externally":"available",n=new Date(e.lastModified).toISOString();return{id:(0,m.F)(this.agentType,e.sessionId),agentType:this.agentType,nativeSessionId:e.sessionId,title:(e.customTitle||e.summary||e.firstPrompt||"Claude Code session").trim(),cwd:e.cwd||"",created:new Date(e.createdAt??e.lastModified).toISOString(),updated:n,status:"available"===r?"idle":"running",occupancy:r,sourceLabel:"Claude Code CLI",canResume:"owned-externally"!==r,canDelete:!1}}requestPermission(e,t,s,i,r,n,a){let o=function(e,t,s){let i=function(e){let t=e.replace(/[^a-z]/gi,"").toLowerCase();return({read:"read_file",glob:"glob",grep:"grep",write:"write_file",edit:"str_replace",multiedit:"str_replace",bash:"bash",webfetch:"web_fetch",websearch:"web_search"})[t]??`claude_${t||"unknown"}`}(e),r=("write_file"===i||"str_replace"===i)&&"string"!=typeof t.file_path&&"string"==typeof t.path?{...t,file_path:t.path}:t;return(0,d.Cr)(i,r,s)}(t,s,n);if(!("full-access"!==r&&("request-approval"===r?"safe"!==o.kind:o.risky||["shell","network","external-write","remote","risky-local","unknown"].includes(o.kind))))return Promise.resolve({behavior:"allow",updatedInput:s});let l=a?`native:${a}:${i.requestId}`:`claude:${e}:${i.requestId}`;return new Promise(r=>{let n=()=>{this.pendingPermissions.delete(l),r({behavior:"deny",message:"Operation aborted",interrupt:!0})};if(i.signal.aborted){n();return}i.signal.addEventListener("abort",n,{once:!0}),this.pendingPermissions.set(l,{nativeSessionId:e,input:s,suggestions:i.suggestions,resolve:e=>{i.signal.removeEventListener("abort",n),r(e)}});let a={type:"ask_user",questionId:l,question:i.title||i.decisionReason||o.summary||`Claude Code requests permission to use ${t}`,options:[{label:"允许一次",description:i.description||"Allow this operation once"},{label:"本会话允许",description:"Allow the suggested operation for this session"},{label:"拒绝",description:"Decline this operation"},{label:"取消",description:"Cancel the current operation"}]};this.permissionEvents.get(e)?.(a)})}rejectPermissionsForSession(e,t){for(let[s,i]of this.pendingPermissions)i.nativeSessionId===e&&(i.resolve({behavior:"deny",message:t,interrupt:!0}),this.pendingPermissions.delete(s))}}function g(e,t,s){let i=(0,p.u)(s),r=i.length>0?[{type:"text",text:e},...i.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.base64}}))]:e;return{type:"user",message:{role:"user",content:r},parent_tool_use_id:null,...t?{priority:t}:{}}}async function v(){try{let{stdout:e}=await N("claude",["agents","--json","--all"],{encoding:"utf8",timeout:5e3,maxBuffer:4194304}),t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function _(e){let t=[];for(let s of e){if("user"!==s.type&&"assistant"!==s.type)continue;let e=R(s.message).content;if("assistant"===s.type){let s=Array.isArray(e)?e:[],i=T(e),r=s.map(E).filter(e=>null!==e);(i||r.length)&&t.push({role:"assistant",content:i,...r.length?{toolCalls:r}:{}});continue}let i=Array.isArray(e)?e:[],r=T(e),n=function(e){let t=[];for(let s of e){let e=R(s);if("image"!==e.type)continue;let i=R(e.source),r=i.media_type,n=i.data;if("base64"!==i.type||"string"!=typeof r||"string"!=typeof n)continue;let a="image/jpeg"===r?"jpg":"image/png"===r?"png":"image/gif"===r?"gif":"image/webp"===r?"webp":null;a&&t.push({type:"image",name:`image-${t.length+1}.${a}`,dataUrl:`data:${r};base64,${n}`})}return t}(i);for(let e of((r||n.length>0)&&t.push({role:"user",content:r,...n.length>0?{presentation:{attachments:n}}:{}}),i)){let s=R(e);"tool_result"===s.type&&"string"==typeof s.tool_use_id&&t.push({role:"tool",content:T(s.content),toolCallId:s.tool_use_id})}}return t}function w(e){return"parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id&&e.parent_tool_use_id?e.parent_tool_use_id:null}function I(e){return Number.isFinite(e)?Math.max(0,Math.round(e/1e3)):void 0}function S(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):void 0}function b(e,t){if(!t)return e;let s=e[e.length-1];return s?.role!=="assistant"||s.toolCalls?.length?[...e,{role:"assistant",content:t}]:[...e.slice(0,-1),{...s,content:s.content+t}]}function E(e){let t=R(e);return"tool_use"!==t.type||"string"!=typeof t.id||"string"!=typeof t.name?null:{id:t.id,name:t.name,arguments:R(t.input)}}function T(e){return"string"==typeof e?e:Array.isArray(e)?e.flatMap(e=>{if("string"==typeof e)return[e];let t=R(e);return"text"===t.type&&"string"==typeof t.text?[t.text]:[]}).join("\n").trim():""}function R(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}i()}catch(e){i(e)}})},9529:(e,t,s)=>{s.d(t,{b:()=>n});var i=s(7718),r=s(132);class n{constructor(e={}){this.process=null,this.startPromise=null,this.buffer="",this.nextId=1,this.disposed=!1,this.pending=new Map,this.notificationListeners=new Set,this.exitListeners=new Set,this.serverRequestHandler=null,this.executable=e.executable??"codex",this.requestTimeoutMs=e.requestTimeoutMs??12e4,this.spawnProcess=e.spawnProcess??i.spawn}get pid(){return this.process?.pid}onNotification(e){return this.notificationListeners.add(e),()=>this.notificationListeners.delete(e)}onExit(e){return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}setServerRequestHandler(e){this.serverRequestHandler=e}async request(e,t){return await this.ensureStarted(),this.sendRequest(e,t)}respond(e,t){this.write({id:e,result:t})}respondError(e,t,s){this.write({id:e,error:{code:t,message:s}})}async restart(){await this.stop(),this.disposed=!1,await this.ensureStarted()}async dispose(){this.disposed=!0,await this.stop()}async ensureStarted(){if(!this.process||this.process.killed){if(this.disposed)throw new r.n("Codex App Server is disposed","RUNTIME_UNAVAILABLE");this.startPromise||(this.startPromise=this.start().finally(()=>{this.startPromise=null})),await this.startPromise}}async start(){let e=this.spawnProcess(this.executable,["app-server","--stdio"],{stdio:["pipe","pipe","pipe"]});this.process=e,this.buffer="",e.stdout.setEncoding("utf8"),e.stdout.on("data",e=>this.handleStdout(e)),e.stderr.setEncoding("utf8"),e.stderr.on("data",e=>{let t=e.trim();t&&console.warn(`[codex-app-server] ${t}`)}),e.once("error",e=>this.handleExit(e)),e.once("exit",(e,t)=>{this.handleExit(Error(`Codex App Server exited (${e??t??"unknown"})`))}),await this.sendRequest("initialize",{clientInfo:{name:"customer-agent",title:"Customer Agent",version:"0.1.0"},capabilities:{experimentalApi:!0}}),this.write({method:"initialized",params:{}})}sendRequest(e,t){let s=this.nextId++;return new Promise((i,n)=>{let a=setTimeout(()=>{this.pending.delete(s),n(new r.n(`Codex request timed out: ${e}`,"NATIVE_PROTOCOL_ERROR"))},this.requestTimeoutMs);this.pending.set(s,{resolve:i,reject:n,timer:a});try{this.write({method:e,id:s,params:t})}catch(e){clearTimeout(a),this.pending.delete(s),n(e instanceof Error?e:Error(String(e)))}})}write(e){if(!this.process||this.process.killed||!this.process.stdin.writable)throw new r.n("Codex App Server is unavailable","RUNTIME_UNAVAILABLE");this.process.stdin.write(`${JSON.stringify(e)}
|
|
2
|
+
`)}handleStdout(e){this.buffer+=e;let t=this.buffer.indexOf("\n");for(;t>=0;){let e=this.buffer.slice(0,t).trim();this.buffer=this.buffer.slice(t+1),e&&this.handleLine(e),t=this.buffer.indexOf("\n")}}handleLine(e){let t;try{t=JSON.parse(e)}catch{console.warn("[codex-app-server] Ignoring malformed JSON-RPC line");return}if("string"==typeof t.method&&void 0!==t.id){let e=t;this.serverRequestHandler?this.serverRequestHandler(e):this.respondError(e.id,-32601,`Unsupported server request: ${e.method}`);return}if(void 0!==t.id){let e=this.pending.get(t.id);if(!e)return;if(clearTimeout(e.timer),this.pending.delete(t.id),t.error){let s=t.error;e.reject(new r.n(s.message??`Codex request failed (${s.code??"unknown"})`,/active writer|already.*loaded|in use/i.test(s.message??"")?"SESSION_OCCUPIED":"NATIVE_PROTOCOL_ERROR"))}else e.resolve(t.result);return}if("string"==typeof t.method){let e=t;for(let t of this.notificationListeners)t(e)}}handleExit(e){if(this.process){for(let t of(this.process=null,this.pending.values()))clearTimeout(t.timer),t.reject(new r.n(e.message,"RUNTIME_UNAVAILABLE"));for(let t of(this.pending.clear(),this.exitListeners))t(e)}}async stop(){let e=this.process;this.process=null,e&&!e.killed&&(e.kill("SIGTERM"),await new Promise(t=>{let s=setTimeout(t,1e3);e.once("exit",()=>{clearTimeout(s),t()})}))}}},3053:(e,t,s)=>{s.d(t,{tX:()=>x});var i=s(7718),r=s(3977),n=s(612),a=s(9411),o=s(5881),l=s(1322),u=s(8224),d=s(9529);let c=new Set(["task_started","turn_started"]),p=new Set(["task_complete","turn_complete","turn_aborted"]);function h(e){let t="string"==typeof e?e:e.toString("utf8");if(!t.trim())return"unknown";try{let e=JSON.parse(t);if("event_msg"!==e.type||"string"!=typeof e.payload?.type)return"unknown";if(c.has(e.payload.type))return"running";if(p.has(e.payload.type))return"idle"}catch{}return"unknown"}class m{constructor(e=65536){if(this.chunkSize=e,this.cache=new Map,!Number.isInteger(e)||e<=0)throw Error("Codex rollout activity chunk size must be a positive integer")}async read(e){let t=null;try{t=await (0,r.open)(e,"r");let s=await t.stat();if(!s.isFile())return this.cache.delete(e),"unknown";let i=`${s.dev}:${s.ino}`,n=this.cache.get(e),a=n&&n.identity===i&&s.size>=n.size&&(s.size>n.size||s.mtimeMs===n.mtimeMs)?await this.readAppended(t,n,s.size,s.mtimeMs):await this.bootstrap(t,i,s.size,s.mtimeMs);return this.cache.set(e,a),a.activity}catch{return this.cache.delete(e),"unknown"}finally{await t?.close().catch(()=>void 0)}}async readMany(e){let t=[...new Set(e)],s=new Set(t);for(let e of this.cache.keys())s.has(e)||this.cache.delete(e);return new Map(await Promise.all(t.map(async e=>[e,await this.read(e)])))}async bootstrap(e,t,s,i){let r=s,n=Buffer.alloc(0),a="unknown",o=Buffer.alloc(0),l=!1,u=!1;for(;r>0&&"unknown"===a;){let t=Math.min(this.chunkSize,r);r-=t;let s=Buffer.allocUnsafe(t),{bytesRead:i}=await e.read(s,0,t,r),d=s.subarray(0,i),c=f(d);if(0===c.length)n=y(d,n);else{let e=d.length;for(let t=c.length-1;t>=0;t-=1){let s=c[t],i=y(v(d.subarray(s+1,e)),n);if(u||(o=i??Buffer.alloc(0),l=null===i,u=!0),i&&(a=h(i)),"unknown"!==a)break;n=Buffer.alloc(0),e=s}"unknown"===a&&(n=Buffer.from(d.subarray(0,e)))}}return"unknown"===a&&0===r&&n&&(u||(o=n,u=!0),a=h(n)),u||(l=null===n),{identity:t,size:s,mtimeMs:i,trailing:o,trailingOverflow:l,activity:a}}async readAppended(e,t,s,i){if(s===t.size)return{...t,mtimeMs:i};let r=t.size,n=t.trailing,a=t.trailingOverflow,o=t.activity;for(;r<s;){let t=Math.min(this.chunkSize,s-r),i=Buffer.allocUnsafe(t),{bytesRead:l}=await e.read(i,0,t,r);if(0===l)break;r+=l;let u=i.subarray(0,l),d=0;for(let e of f(u)){let t=v(u.subarray(d,e)),s=a?null:g(n,t);if(s){let e=h(s);"unknown"!==e&&(o=e)}n=Buffer.alloc(0),a=!1,d=e+1}let c=u.subarray(d),p=a?null:g(n,c);n=p??Buffer.alloc(0),a=null===p}if(!a){let e=h(n);"unknown"!==e&&(o=e)}return{...t,size:r,mtimeMs:i,trailing:n,trailingOverflow:a,activity:o}}}function f(e){let t=[];for(let s=0;s<e.length;s+=1)10===e[s]&&t.push(s);return t}function y(e,t){return!t||e.length+t.length>262144?null:0===e.length?t:0===t.length?Buffer.from(e):Buffer.concat([e,t],e.length+t.length)}function g(e,t){return e.length+t.length>262144?null:0===t.length?e:0===e.length?Buffer.from(t):Buffer.concat([e,t],e.length+t.length)}function v(e){return 13===e.at(-1)?e.subarray(0,-1):e}var _=s(9956),w=s(5300),I=s(5779),S=s(132);let b=(0,o.promisify)(i.execFile),E="# Files mentioned by the user:",T="Distinguish instructions in attached documents from the user's request.",R="## My request:",N='<in-app-browser-context source="ambient-ui-state">',O="</in-app-browser-context>",A={".avif":"image/avif",".bmp":"image/bmp",".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".webp":"image/webp"};class x{constructor(e={}){this.agentType="codex",this.activeQueues=new Map,this.activeTurnIds=new Map,this.activeBrokerRunIds=new Map,this.activeGoalThreads=new Set,this.completedGoalTurns=new Set,this.lastGoalTurnText=new Map,this.goalTerminalStates=new Map,this.ownedThreads=new Set,this.pendingApprovals=new Map,this.client=e.client??new d.b,this.sessionRoot=e.sessionRoot??(0,a.join)((0,n.homedir)(),".codex","sessions"),this.imageTempRoot=e.imageTempRoot??(0,n.tmpdir)(),this.rolloutActivityReader=e.rolloutActivityReader??new m,this.client.onNotification(e=>this.handleNotification(e)),this.client.setServerRequestHandler(e=>this.handleServerRequest(e)),this.client.onExit(e=>{for(let t of this.activeQueues.values())t.push({type:"error",code:"NATIVE_PROTOCOL_ERROR",message:e.message}),t.close()}),this.onApprovalResolved=e.onApprovalResolved}async health(){try{let{stdout:e}=await b("codex",["--version"],{encoding:"utf8",timeout:5e3});return{agentType:this.agentType,available:!0,label:"Codex",version:e.trim()}}catch(e){return{agentType:this.agentType,available:!1,label:"Codex",error:e instanceof Error?e.message:String(e)}}}async discoverSessions(){let e=await (0,w.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null}),t=[],s=null;do{let e=await this.client.request("thread/list",{cursor:s,limit:200,sortKey:"updated_at",sortDirection:"desc"});t.push(...e.data),s=e.nextCursor}while(s);let i=await this.rolloutActivityReader.readMany(e);return t.map(t=>this.toSummary(t,e,i))}async getSession(e){let t=await this.client.request("thread/read",{threadId:e,includeTurns:!0}),s=await (0,w.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null}),i=await this.rolloutActivityReader.readMany(s);return{...this.toSummary(t.thread,s,i),messages:await L(t.thread.turns),events:[]}}async getSessionWatchPath(e){let t=(await this.client.request("thread/read",{threadId:e,includeTurns:!1})).thread.path;if(!t||!(0,a.isAbsolute)(t))return null;try{let[e,s,i]=await Promise.all([(0,r.realpath)(this.sessionRoot),(0,r.realpath)(t),(0,r.stat)(t)]),n=(0,a.relative)((0,a.resolve)(e),(0,a.resolve)(s));if(i.isFile()&&""!==n&&!n.startsWith(`..${a.sep}`)&&".."!==n&&!(0,a.isAbsolute)(n))return s}catch{}return null}async create(e){let t=await this.client.request("thread/start",{cwd:e.cwd,threadSource:"customer-agent"});return await this.client.request("thread/name/set",{threadId:t.thread.id,name:e.title}).catch(()=>void 0),await this.client.request("thread/unsubscribe",{threadId:t.thread.id}).catch(()=>void 0),this.toSummary({...t.thread,name:e.title},new Set)}async fork(e){let t=await this.client.request("thread/read",{threadId:e,includeTurns:!1}),s=await this.client.request("thread/fork",{threadId:e}),i=(t.thread.name||t.thread.preview||"Codex session").trim(),r=`${i}(副本)`;return await this.client.request("thread/name/set",{threadId:s.thread.id,name:r}),this.toSummary({...s.thread,name:r},new Set)}async *run(e,t,s,i,n,a){var o,d;if(this.activeQueues.has(e))throw new S.n("Codex session is already running","SESSION_OCCUPIED");let c=await this.getSession(e);if("owned-externally"===c.occupancy)throw new S.n("Codex session is open in another client","SESSION_OCCUPIED");let p=(0,_.u)(s),h=new u.K,m=null;this.activeQueues.set(e,h),this.ownedThreads.add(e),a?.brokerRunId&&this.activeBrokerRunIds.set(e,a.brokerRunId),a?.goal&&this.activeGoalThreads.add(e);try{await this.client.request("thread/resume",{threadId:e,excludeTurns:!0}),a?.goal&&await this.client.request("thread/goal/set",{threadId:e,objective:a.goal.objective,status:"active"});let s=p.length>0?await P(p,this.imageTempRoot).then(e=>(m=e.directory,e.inputs)):[],i=function(e){let t=e.trim().match(/^\/([\w-]+)(?:\s+([\s\S]*))?$/);return!t||["goal","compact","loop"].includes(t[1].toLowerCase())?null:{name:t[1],rest:t[2]?.trim()??""}}(t),r=i?await this.resolveSkillPath(c.cwd,i.name):null,n=i?`$${i.name}${i.rest?` ${i.rest}`:""}`:t,u=await this.client.request("turn/start",{threadId:e,input:[{type:"text",text:n,text_elements:[]},...i&&r?[{type:"skill",name:i.name,path:r}]:[],...s],...(o=(0,l.Ny)(a?.permissionMode),d=c.cwd,"request-approval"===o?{approvalPolicy:"onRequest",sandboxPolicy:{type:"readOnly"}}:"auto-approval"===o?{approvalPolicy:"onRequest",sandboxPolicy:{type:"workspaceWrite",writableRoots:d?[d]:[],networkAccess:!1}}:{approvalPolicy:"never",sandboxPolicy:{type:"dangerFullAccess"}})});for await(let t of(this.activeTurnIds.set(e,u.turn.id),h))yield t}catch(t){let e=t instanceof S.n?t:new S.n(t instanceof Error?t.message:String(t),"NATIVE_PROTOCOL_ERROR");yield{type:"error",message:e.message,code:e.code}}finally{this.activeTurnIds.delete(e),this.activeQueues.delete(e),this.ownedThreads.delete(e),this.activeBrokerRunIds.delete(e),this.activeGoalThreads.delete(e),this.completedGoalTurns.delete(e),this.lastGoalTurnText.delete(e),this.goalTerminalStates.delete(e),await this.client.request("thread/unsubscribe",{threadId:e}).catch(()=>void 0),m&&await (0,r.rm)(m,{recursive:!0,force:!0}).catch(()=>void 0)}}async abort(e){let t=this.activeTurnIds.get(e),s=[];t&&s.push(this.client.request("turn/interrupt",{threadId:e,turnId:t})),this.activeGoalThreads.has(e)&&s.push(this.client.request("thread/goal/clear",{threadId:e}));let i=(await Promise.allSettled(s)).find(e=>"rejected"===e.status);if(i)throw i.reason}async answerQuestion(e,t){let s=this.pendingApprovals.get(e);if(!s)return!1;this.pendingApprovals.delete(e);let i=t.answer.trim();if("item/tool/requestUserInput"===s.method){let e=s.params.questions;return this.client.respond(s.requestId,{answers:Object.fromEntries((e??[]).map(e=>[e.id,{answers:[i]}]))}),!0}return this.client.respond(s.requestId,function(e,t){let s="本会话允许"===t?"acceptForSession":"允许一次"===t?"accept":"取消"===t?"cancel":"decline";return"item/permissions/requestApproval"!==e.method?{decision:s}:{permissions:"accept"===s||"acceptForSession"===s?C(e.params):Array.isArray(C(e.params))?[]:{},scope:"acceptForSession"===s?"session":"turn"}}(s,i)),!0}async dispose(){await this.client.dispose()}async resolveSkillPath(e,t){for(let s of[(0,a.join)((0,n.homedir)(),".codex","skills",t,"SKILL.md"),(0,a.join)((0,n.homedir)(),".agent","skills",t,"SKILL.md"),...e?[(0,a.join)(e,".codex","skills",t,"SKILL.md"),(0,a.join)(e,".agent","skills",t,"SKILL.md")]:[]])try{if((await (0,r.stat)(s)).isFile())return s}catch{}try{let s=await this.client.request("skills/list",{cwds:e?[e]:[],forceReload:!1});return function e(t,s){if(!t||"object"!=typeof t)return null;if(Array.isArray(t)){for(let i of t){let t=e(i,s);if(t)return t}return null}if(t.name===s&&"string"==typeof t.path)return t.path;for(let i of Object.values(t)){let t=e(i,s);if(t)return t}return null}(s,t)}catch{return null}}toSummary(e,t,s=new Map){var i;let r=this.ownedThreads.has(e.id),n=!!(e.path&&t.has(e.path)),a=r?"owned-by-customer-agent":n?"owned-externally":"available";return{id:(0,I.F)(this.agentType,e.id),agentType:this.agentType,nativeSessionId:e.id,title:(e.name||e.preview||"Codex session").trim(),cwd:e.cwd,parentSessionId:e.parentThreadId?(0,I.F)(this.agentType,e.parentThreadId):void 0,created:new Date(1e3*e.createdAt).toISOString(),updated:new Date(1e3*e.updatedAt).toISOString(),status:function(e,t=!1,s=!1){return t||s||"active"===e?"running":"systemError"===e?"failed":"idle"}(e.status?.type,r,n&&!!(e.path&&"running"===s.get(e.path))),occupancy:a,sourceLabel:"vscode"===(i=e.source)?"Codex Desktop":"cli"===i?"Codex CLI":"exec"===i?"Codex Exec":"appServer"===i?"Customer Agent / Codex":i&&"object"==typeof i&&"custom"in i?String(i.custom):"Codex",canResume:"owned-externally"!==a,canDelete:!1}}handleNotification(e){let t=e.params??{};if("serverRequest/resolved"===e.method){let e=t.requestId??t.id;for(let[t,s]of this.pendingApprovals)if(String(s.requestId)===String(e)){this.pendingApprovals.delete(t),this.onApprovalResolved?.(t);break}return}let s="string"==typeof t.threadId?t.threadId:void 0;if(!s)return;let i=this.activeQueues.get(s);if(!i)return;if("thread/goal/updated"===e.method&&this.activeGoalThreads.has(s)){let e=function(e){let t=U(e).status;return"active"===t||"paused"===t||"blocked"===t||"usageLimited"===t||"budgetLimited"===t||"complete"===t?t:null}(t.goal);e&&"active"!==e&&(this.goalTerminalStates.set(s,{status:e}),this.activeTurnIds.has(s)||this.completedGoalTurns.add(s),this.finishGoalQueueIfReady(s,i));return}if("thread/goal/cleared"===e.method&&this.activeGoalThreads.has(s)){this.goalTerminalStates.set(s,{status:"cleared"}),this.activeTurnIds.has(s)||this.completedGoalTurns.add(s),this.finishGoalQueueIfReady(s,i);return}if("turn/started"===e.method){let e=t.turn;"string"==typeof e?.id&&this.activeTurnIds.set(s,e.id),this.completedGoalTurns.delete(s)}let r=function(e){if("turn/started"===e.method)return{type:"runtime_progress",progressId:"codex:status",phase:"status",label:"正在开始处理"};if("item/started"!==e.method)return null;let t=U(U(e.params).item);return"reasoning"===t.type&&"string"==typeof t.id&&t.id?{type:"runtime_progress",progressId:`codex:reasoning:${t.id}`,phase:"thinking",label:"正在思考"}:null}(e);r&&i.push(r);let n=function(e){if("item/reasoning/summaryTextDelta"!==e.method&&"item/reasoning/summaryPartAdded"!==e.method)return null;let t=U(e.params),s=t.itemId,i=t.summaryIndex;if("string"!=typeof s||!s||"number"!=typeof i||!Number.isSafeInteger(i)||i<0)return null;let r="item/reasoning/summaryPartAdded"===e.method?"":t.delta;return"string"!=typeof r?null:{type:"reasoning_summary_delta",itemId:s,sectionIndex:i,delta:r}}(e);if(n){i.push(n);return}if("item/reasoning/textDelta"!==e.method){if("item/agentMessage/delta"===e.method&&"string"==typeof t.delta){i.push({type:"text_chunk",text:t.delta});return}if("item/started"===e.method){let e=q(t.item);e&&i.push({type:"tool_call",toolCall:e});return}if("item/completed"===e.method){let e=M(t.item);e&&i.push({type:"tool_result",result:e});return}if("turn/completed"===e.method){let e=t.turn;if(this.activeTurnIds.delete(s),this.activeGoalThreads.has(s)){e?.status==="failed"?(i.push({type:"error",message:e.error?.message??"Codex turn failed"}),i.close()):e?.status==="interrupted"?(i.push({type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Codex turn was interrupted."}),i.close()):(this.lastGoalTurnText.set(s,D(e?.items??[])),this.completedGoalTurns.add(s),this.finishGoalQueueIfReady(s,i));return}if(e?.status==="failed")i.push({type:"error",message:e.error?.message??"Codex turn failed"});else if(e?.status==="interrupted")i.push({type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Codex turn was interrupted."});else{let t=D(e?.items??[]);i.push({type:"done",finalText:t})}i.close();return}if("turn/interrupt"===e.method){i.push({type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Codex turn was interrupted."}),i.close();return}"error"===e.method&&(i.push({type:"error",message:String(t.message??"Codex runtime error")}),i.close())}}finishGoalQueueIfReady(e,t){if(!this.completedGoalTurns.has(e))return;let s=this.goalTerminalStates.get(e);s&&("complete"===s.status?t.push({type:"done",finalText:this.lastGoalTurnText.get(e)??""}):t.push({type:"error",code:"NATIVE_PROTOCOL_ERROR",message:function(e){switch(e){case"paused":return"Codex goal was paused.";case"blocked":return"Codex goal is blocked.";case"usageLimited":return"Codex goal stopped because the usage limit was reached.";case"budgetLimited":return"Codex goal stopped because the token budget was reached.";case"cleared":return"Codex goal was cleared."}}(s.status)}),t.close())}handleServerRequest(e){let t=e.params??{};if("currentTime/read"===e.method){this.client.respond(e.id,{currentTime:new Date().toISOString()});return}let s="string"==typeof t.threadId?t.threadId:"string"==typeof t.conversationId?t.conversationId:void 0,i=s?this.activeQueues.get(s):void 0;if(!i){this.client.respondError(e.id,-32601,`Unsupported server request: ${e.method}`);return}let r=s?this.activeBrokerRunIds.get(s):void 0,n=r?`native:${r}:${String(e.id)}`:`codex:${String(e.id)}`;if(this.pendingApprovals.set(n,{requestId:e.id,method:e.method,params:t,questionId:n}),"item/tool/requestUserInput"===e.method){let e=t.questions,s=e?.[0];i.push({type:"ask_user",questionId:n,question:s?.question??"Codex needs additional input",options:s?.options?.map(e=>({label:e.label,description:e.description??""}))});return}if(!new Set(["item/commandExecution/requestApproval","item/fileChange/requestApproval","item/permissions/requestApproval","applyPatchApproval","execCommandApproval"]).has(e.method)){this.pendingApprovals.delete(n),this.client.respondError(e.id,-32601,`Unsupported server request: ${e.method}`);return}let a="string"==typeof t.command?t.command:Array.isArray(t.command)?t.command.join(" "):void 0,o="string"==typeof t.reason?t.reason:void 0,l="item/permissions/requestApproval"===e.method?function(e){let t=JSON.stringify(C(e));return t&&"{}"!==t?`Codex requests permission: ${t.slice(0,500)}`:"Codex requests expanded filesystem or network permission"}(t):void 0;i.push({type:"ask_user",questionId:n,question:o||l||(a?`Codex requests permission to run: ${a}`:"Codex requests permission to modify files"),options:[{label:"允许一次",description:"Allow this operation once"},{label:"本会话允许",description:"Allow equivalent operations for this session"},{label:"拒绝",description:"Decline this operation"},{label:"取消",description:"Cancel the current operation"}]})}}function C(e){if("permissions"in e)return e.permissions;if("requestedPermissions"in e)return e.requestedPermissions;let t={};for(let s of["filesystem","network","filesystemPermissions","networkPermissions"])s in e&&(t[s]=e[s]);return t}async function P(e,t){let s=await (0,r.mkdtemp)((0,a.join)(t,"customer-agent-codex-images-"));try{let t=[];for(let[i,n]of e.entries()){let e=(0,a.join)(s,`image-${i+1}.${n.extension}`);await (0,r.writeFile)(e,n.bytes,{mode:384}),t.push({type:"localImage",path:e})}return{directory:s,inputs:t}}catch(e){throw await (0,r.rm)(s,{recursive:!0,force:!0}).catch(()=>void 0),e}}async function k(e){let t=(0,a.basename)(e)||"image",s=A[(0,a.extname)(e).toLowerCase()];if(!s)return{type:"image",name:t,unavailable:!0};try{let i=await (0,r.stat)(e);if(!i.isFile()||i.size>20971520)return{type:"image",name:t,unavailable:!0};let n=await (0,r.readFile)(e);if(n.byteLength>20971520)return{type:"image",name:t,unavailable:!0};return{type:"image",name:t,dataUrl:`data:${s};base64,${n.toString("base64")}`}}catch{return{type:"image",name:t,unavailable:!0}}}async function L(e){let t=[];for(let s of e)for(let e of s.items??[])if("userMessage"===e.type){let s=e.content,i=s?.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>String(e.text)).join("\n").trim();if(i){let e=function(e){let t=e.trim(),s=-1;if(t.startsWith(E)){let e=t.indexOf(T,E.length);if(e<0)return{content:t};s=e+T.length}else{if(!t.startsWith(N))return{content:t};let e=t.indexOf(O,N.length);if(e<0)return{content:t};s=e+O.length}let i=t.indexOf(R,s);if(i<0)return{content:t};let r=t.slice(i+R.length).trim();return r?{content:r,rawContent:t}:{content:t}}(i),r=(s??[]).filter(e=>("local_image"===e.type||"localImage"===e.type)&&"string"==typeof e.path).map(e=>String(e.path)),n=await Promise.all(r.map(k)),a=e.rawContent||n.length>0?{...e.rawContent?{rawContent:e.rawContent}:{},...n.length>0?{attachments:n}:{}}:void 0;t.push({role:"user",content:e.content,...a?{presentation:a}:{}})}}else if("agentMessage"===e.type&&"string"==typeof e.text&&e.text.trim())t.push({role:"assistant",content:e.text});else if("reasoning"===e.type&&Array.isArray(e.summary)){let s=e.summary.flatMap((t,s)=>"string"==typeof t&&t.trim()?[{itemId:e.id??`reasoning-${s}`,sectionIndex:s,text:t}]:[]);s.length>0&&t.push({role:"assistant",content:"",presentation:{reasoning:s}})}else{let s=q(e);s&&t.push({role:"assistant",content:"",toolCalls:[s]});let i=M(e);i&&t.push({role:"tool",content:i.content,toolCallId:i.toolCallId,name:s?.name})}return t}function q(e){return e?.id?"commandExecution"===e.type?{id:e.id,name:"shell",arguments:{command:e.command,cwd:e.cwd}}:"fileChange"===e.type?{id:e.id,name:"apply_patch",arguments:{changes:e.changes}}:"mcpToolCall"===e.type?{id:e.id,name:`${String(e.server)}:${String(e.tool)}`,arguments:U(e.arguments)}:"dynamicToolCall"===e.type?{id:e.id,name:String(e.tool),arguments:U(e.arguments)}:null:null}function M(e){return e?.id?"commandExecution"===e.type?{toolCallId:e.id,content:"string"==typeof e.aggregatedOutput?e.aggregatedOutput:"",isError:"number"==typeof e.exitCode&&0!==e.exitCode}:"fileChange"===e.type?{toolCallId:e.id,content:JSON.stringify(e.changes??[],null,2),isError:"failed"===e.status}:"mcpToolCall"===e.type||"dynamicToolCall"===e.type?{toolCallId:e.id,content:JSON.stringify(e.result??e.contentItems??e.error??{},null,2),isError:!!e.error||!1===e.success}:null:null}function D(e){for(let t=e.length-1;t>=0;t--){let s=e[t];if("agentMessage"===s.type&&"string"==typeof s.text)return s.text}return""}function U(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{value:e}}},9956:(e,t,s)=>{s.d(t,{u:()=>a});var i=s(132);let r=4*Math.ceil(6990506.666666667),n={"image/jpeg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp"};function a(e){return(e??[]).map((e,t)=>(function(e,t){let s=`Image ${t+1}`,i=/^data:(image\/(?:jpeg|png|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec(e);if(!i)throw o(`${s} must be a base64 JPEG, PNG, GIF, or WebP data URL`);let a=i[1],l=i[2];if(l.length%4!=0||l.length>r)throw o(`${s} is malformed or exceeds the 20 MB limit`);let u=Buffer.from(l,"base64");if(u.toString("base64").replace(/=+$/,"")!==l.replace(/=+$/,"")||!function(e,t){if("image/jpeg"===e)return t.length>=3&&255===t[0]&&216===t[1]&&255===t[2];if("image/png"===e)return t.length>=8&&t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]));if("image/gif"===e){let e=t.subarray(0,6).toString("ascii");return"GIF87a"===e||"GIF89a"===e}return t.length>=12&&"RIFF"===t.subarray(0,4).toString("ascii")&&"WEBP"===t.subarray(8,12).toString("ascii")}(a,u))throw o(`${s} content does not match its declared media type`);if(u.byteLength>20971520)throw o(`${s} exceeds the 20 MB limit`);return{mimeType:a,extension:n[a],base64:l,bytes:u}})(e,t))}function o(e){return new i.n(e,"NATIVE_PROTOCOL_ERROR")}},5300:(e,t,s)=>{s.d(t,{g:()=>a});var i=s(7718),r=s(7561);let n=(0,s(5881).promisify)(i.execFile);async function a(e,t,s={}){try{let{stdout:i}=await n("lsof",["+c","0","-a","-c",e,"-FpFn"],{encoding:"utf8",timeout:5e3,maxBuffer:4194304});return function(e,t,s={}){let i=t.endsWith("/")?t:`${t}/`,n=new Set(s.excludePids??[]),a=void 0===s.idleAfterMs?12e4:s.idleAfterMs,o=s.nowMs??Date.now(),l=s.getMtimeMs??(e=>(0,r.statSync)(e).mtimeMs),u=new Set,d=null;for(let t of e.split("\n"))if(t.startsWith("p"))d=Number(t.slice(1));else if(t.startsWith(`n${i}`)&&(null===d||!n.has(d))){let e=t.slice(1);try{let t=l(e);if(null!==a&&o-t>a)continue}catch{continue}u.add(e)}return u}(i,t,s)}catch{return new Set}}},7578:(e,t,s)=>{s.a(e,async(e,i)=>{try{s.d(t,{WH:()=>_,v6:()=>v});var r=s(6005),n=s(7561),a=s(7503),o=s(612),l=s(9411),u=s(1322),d=s(8224),c=s(3088),p=s(9529),h=s(3053),m=s(5779),f=s(132),y=s(2428),g=e([c]);c=(g.then?(await g)():g)[0];let x="native-runtime.sock";class C{constructor(e,t){this.now=t,(0,n.mkdirSync)(e,{recursive:!0,mode:448});try{(0,n.chmodSync)(e,448)}catch{}this.database=new u.G1(e),this.database.db.exec(`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS native_runtime_policy (
|
|
4
|
+
session_id TEXT PRIMARY KEY,
|
|
5
|
+
permission_mode TEXT NOT NULL,
|
|
6
|
+
updated_at INTEGER NOT NULL
|
|
7
|
+
);
|
|
8
|
+
CREATE TABLE IF NOT EXISTS native_runtime_run (
|
|
9
|
+
run_id TEXT PRIMARY KEY,
|
|
10
|
+
session_id TEXT NOT NULL,
|
|
11
|
+
agent_type TEXT NOT NULL,
|
|
12
|
+
native_session_id TEXT NOT NULL,
|
|
13
|
+
input TEXT NOT NULL,
|
|
14
|
+
permission_mode TEXT NOT NULL,
|
|
15
|
+
controller TEXT NOT NULL,
|
|
16
|
+
status TEXT NOT NULL,
|
|
17
|
+
next_sequence INTEGER NOT NULL DEFAULT 0,
|
|
18
|
+
created_at INTEGER NOT NULL,
|
|
19
|
+
terminal_at INTEGER,
|
|
20
|
+
goal_id TEXT
|
|
21
|
+
);
|
|
22
|
+
CREATE UNIQUE INDEX IF NOT EXISTS native_runtime_active_run_per_session
|
|
23
|
+
ON native_runtime_run(session_id) WHERE status = 'active';
|
|
24
|
+
CREATE INDEX IF NOT EXISTS native_runtime_runs_by_session
|
|
25
|
+
ON native_runtime_run(session_id, created_at DESC);
|
|
26
|
+
CREATE TABLE IF NOT EXISTS native_runtime_event (
|
|
27
|
+
run_id TEXT NOT NULL,
|
|
28
|
+
sequence INTEGER NOT NULL,
|
|
29
|
+
payload TEXT NOT NULL,
|
|
30
|
+
created_at INTEGER NOT NULL,
|
|
31
|
+
PRIMARY KEY(run_id, sequence)
|
|
32
|
+
);
|
|
33
|
+
CREATE TABLE IF NOT EXISTS native_runtime_approval (
|
|
34
|
+
question_id TEXT PRIMARY KEY,
|
|
35
|
+
run_id TEXT NOT NULL,
|
|
36
|
+
state TEXT NOT NULL,
|
|
37
|
+
created_at INTEGER NOT NULL,
|
|
38
|
+
resolved_at INTEGER
|
|
39
|
+
);
|
|
40
|
+
CREATE INDEX IF NOT EXISTS native_runtime_approval_by_run
|
|
41
|
+
ON native_runtime_approval(run_id, state);
|
|
42
|
+
CREATE TABLE IF NOT EXISTS native_runtime_lock (
|
|
43
|
+
session_id TEXT PRIMARY KEY,
|
|
44
|
+
occupancy TEXT NOT NULL,
|
|
45
|
+
revision INTEGER NOT NULL,
|
|
46
|
+
sample_state TEXT,
|
|
47
|
+
sample_at INTEGER,
|
|
48
|
+
updated_at INTEGER NOT NULL
|
|
49
|
+
);
|
|
50
|
+
CREATE TABLE IF NOT EXISTS native_runtime_goal_state (
|
|
51
|
+
session_id TEXT PRIMARY KEY,
|
|
52
|
+
payload TEXT NOT NULL,
|
|
53
|
+
updated_at INTEGER NOT NULL
|
|
54
|
+
);
|
|
55
|
+
`),this.database.db.prepare("PRAGMA table_info(native_runtime_run)").all().some(e=>"goal_id"===e.name)||this.database.db.exec("ALTER TABLE native_runtime_run ADD COLUMN goal_id TEXT")}recoverInterruptedRuns(){for(let e of this.database.db.prepare("SELECT * FROM native_runtime_run WHERE status = 'active'").all())this.appendTerminal(e.run_id,{type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Native runtime restarted; this turn was interrupted. You can send again."});this.pruneExpiredTerminals()}getPermissionMode(e){let t=this.database.db.prepare("SELECT permission_mode FROM native_runtime_policy WHERE session_id = ?").get(e);return(0,u.Ny)(t?.permission_mode)}setPermissionMode(e,t){let s=(0,u.Ny)(t);return this.database.db.prepare(`
|
|
56
|
+
INSERT INTO native_runtime_policy(session_id, permission_mode, updated_at)
|
|
57
|
+
VALUES (?, ?, ?)
|
|
58
|
+
ON CONFLICT(session_id) DO UPDATE SET permission_mode=excluded.permission_mode, updated_at=excluded.updated_at
|
|
59
|
+
`).run(e,s,this.now()),s}getGoalState(e){let t=this.database.db.prepare("SELECT payload FROM native_runtime_goal_state WHERE session_id = ?").get(e);if(!t?.payload)return(0,u.uA)(void 0);try{return(0,u.uA)({goalState:JSON.parse(t.payload)})}catch{return(0,u.uA)(void 0)}}enqueueGoal(e,t,s){return this.updateGoalState(e,i=>(0,u.Wf)(i,{id:(0,r.randomUUID)(),sessionId:e,objective:t,sourceMessageId:s,now:this.now()}))}reorderGoals(e,t){return this.updateGoalState(e,e=>(0,u.ZC)(e,t))}cancelGoal(e,t){return this.updateGoalState(e,e=>(0,u.LJ)(e,t,this.now()))}finishGoal(e,t,s,i){return this.updateGoalState(e,e=>e.active?.id===t?(0,u.JX)(e,s,this.now(),i):e)}listActiveGoals(){return this.database.db.prepare("SELECT payload FROM native_runtime_goal_state").all().flatMap(e=>{try{let t=(0,u.uA)({goalState:JSON.parse(e.payload)});return t.active?[t.active]:[]}catch{return[]}})}updateGoalState(e,t){return this.database.db.transaction(()=>{let s=t(this.getGoalState(e));return this.database.db.prepare(`
|
|
60
|
+
INSERT INTO native_runtime_goal_state(session_id, payload, updated_at)
|
|
61
|
+
VALUES (?, ?, ?)
|
|
62
|
+
ON CONFLICT(session_id) DO UPDATE SET payload=excluded.payload, updated_at=excluded.updated_at
|
|
63
|
+
`).run(e,JSON.stringify(s),this.now()),s})()}admit(e){return this.database.db.transaction(()=>{let t=this.database.db.prepare("SELECT run_id FROM native_runtime_run WHERE session_id = ? AND status = 'active'").get(e.sessionId);if(t?.run_id)throw new f.n("Session is already running","SESSION_OCCUPIED");let s=this.now(),i={sessionId:e.sessionId,runId:(0,r.randomUUID)(),agentType:e.agentType,nativeSessionId:e.nativeSessionId,input:e.message,permissionMode:this.getPermissionMode(e.sessionId),controller:e.controller,status:"active",nextSequence:0,createdAt:s,terminalAt:null,goalId:e.goalId??null};return this.database.db.prepare(`
|
|
64
|
+
INSERT INTO native_runtime_run(
|
|
65
|
+
run_id, session_id, agent_type, native_session_id, input, permission_mode,
|
|
66
|
+
controller, status, next_sequence, created_at, terminal_at, goal_id
|
|
67
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
68
|
+
`).run(i.runId,i.sessionId,i.agentType,i.nativeSessionId,i.input,i.permissionMode,i.controller,i.status,i.nextSequence,i.createdAt,i.terminalAt,i.goalId),this.transitionLock(e.sessionId,"owned-by-customer-agent",null,null),i})()}appendEvent(e,t){return this.database.db.transaction(()=>{let s=this.getRunById(e);if(!s||"active"!==s.status)return null;let i=s.nextSequence+1;return this.database.db.prepare("INSERT INTO native_runtime_event(run_id, sequence, payload, created_at) VALUES (?, ?, ?, ?)").run(e,i,JSON.stringify(t),this.now()),this.database.db.prepare("UPDATE native_runtime_run SET next_sequence = ? WHERE run_id = ?").run(i,e),"ask_user"===t.type&&this.database.db.prepare(`
|
|
69
|
+
INSERT INTO native_runtime_approval(question_id, run_id, state, created_at, resolved_at)
|
|
70
|
+
VALUES (?, ?, 'pending', ?, NULL)
|
|
71
|
+
ON CONFLICT(question_id) DO NOTHING
|
|
72
|
+
`).run(t.questionId,e,this.now()),S(t)&&this.finalizeRun(e,"error"===t.type?t.message:null),{runId:e,sequence:i,event:t}})()}appendTerminal(e,t){let s=this.getRunById(e);return s&&"active"===s.status?this.appendEvent(e,t):null}getSnapshot(e,t=0){let s=this.projection(e,t);return{sessionId:e,runId:s.run?.runId??null,snapshotRevision:s.run?.nextSequence??0,events:s.events,controller:s.run?.status==="active"?s.run.controller:null}}projection(e,t=0){let s=this.getLatestRetainedRun(e);if(!s)return{run:null,events:[]};let i=this.database.db.prepare(`
|
|
73
|
+
SELECT run_id, sequence, payload FROM native_runtime_event
|
|
74
|
+
WHERE run_id = ? AND sequence > ? ORDER BY sequence ASC
|
|
75
|
+
`).all(s.runId,t).flatMap(e=>{let t=function(e){try{let t=JSON.parse(e);return t&&"object"==typeof t&&"string"==typeof t.type?t:null}catch{return null}}(e.payload);return t&&("ask_user"!==t.type||this.isApprovalVisible(t.questionId))?[{runId:e.run_id,sequence:e.sequence,event:t}]:[]});return{run:s,events:i}}claimApproval(e){return this.database.db.transaction(()=>{let t=this.database.db.prepare(`
|
|
76
|
+
SELECT approval.run_id
|
|
77
|
+
FROM native_runtime_approval approval
|
|
78
|
+
JOIN native_runtime_run run ON run.run_id = approval.run_id
|
|
79
|
+
WHERE approval.question_id = ? AND approval.state = 'pending' AND run.status = 'active'
|
|
80
|
+
`).get(e);if(!t?.run_id)return null;let s=this.database.db.prepare(`
|
|
81
|
+
UPDATE native_runtime_approval SET state = 'claimed'
|
|
82
|
+
WHERE question_id = ? AND state = 'pending'
|
|
83
|
+
`).run(e).changes;return 1===s?this.getRunById(t.run_id):null})()}resolveApproval(e){let t=this.database.db.transaction(()=>{let t=this.database.db.prepare(`
|
|
84
|
+
SELECT run_id FROM native_runtime_approval
|
|
85
|
+
WHERE question_id = ? AND state IN ('pending', 'claimed')
|
|
86
|
+
`).get(e);if(!t?.run_id)return null;let s=this.database.db.prepare(`
|
|
87
|
+
UPDATE native_runtime_approval SET state = 'resolved', resolved_at = ?
|
|
88
|
+
WHERE question_id = ? AND state IN ('pending', 'claimed')
|
|
89
|
+
`).run(this.now(),e).changes;return 1===s?t.run_id:null})();return t?this.appendEvent(t,{type:"approval_resolved",questionId:e}):null}restoreApproval(e){this.database.db.prepare(`
|
|
90
|
+
UPDATE native_runtime_approval SET state = 'pending', resolved_at = NULL
|
|
91
|
+
WHERE question_id = ? AND state = 'claimed'
|
|
92
|
+
`).run(e)}changeController(e,t){return this.database.db.prepare(`
|
|
93
|
+
UPDATE native_runtime_run SET controller = ? WHERE session_id = ? AND status = 'active'
|
|
94
|
+
`).run(t,e),this.getSnapshot(e)}activeRun(e){let t=this.database.db.prepare("SELECT * FROM native_runtime_run WHERE session_id = ? AND status = 'active'").get(e);return t?I(t):null}hasActiveRuns(){let e=this.database.db.prepare("SELECT 1 AS active FROM native_runtime_run WHERE status = 'active' LIMIT 1").get();return e?.active===1}sessionIdForRun(e){return this.getRunById(e)?.sessionId??null}recordExplicitExternalOwnership(e){this.activeRun(e)||this.transitionLock(e,"owned-externally","occupied",this.now())}observeDiscovery(e,t){if(this.activeRun(e))return this.transitionLock(e,"owned-by-customer-agent",null,null);let s=this.getLock(e),i=t?"occupied":"clean",r=this.now();return s.sampleState===i&&null!==s.sampleAt&&r-s.sampleAt>=5e3?this.transitionLock(e,t?"owned-externally":"available",i,r):(this.database.db.prepare(`
|
|
95
|
+
INSERT INTO native_runtime_lock(session_id, occupancy, revision, sample_state, sample_at, updated_at)
|
|
96
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
97
|
+
ON CONFLICT(session_id) DO UPDATE SET sample_state=excluded.sample_state, sample_at=excluded.sample_at, updated_at=excluded.updated_at
|
|
98
|
+
`).run(e,s.occupancy,s.revision,i,r,r),{...s,sampleState:i,sampleAt:r})}applySummary(e){let t="owned-externally"===e.occupancy,s=this.observeDiscovery(e.id,t),i=this.getPermissionMode(e.id),r=this.activeRun(e.id),n=r?"owned-by-customer-agent":s.occupancy;return{...e,occupancy:n,status:r?"running":e.status,canResume:"owned-externally"!==n,permissionMode:i,occupancyRevision:s.revision,controller:r?.controller??null,goalState:this.getGoalState(e.id)}}applyDetail(e){let t=this.applySummary(e),s=this.projection(e.id),i=function(e,t,s){if(!t)return e;let i=[...e],r=[...i].reverse().find(e=>"user"===e.role);r&&r.content===t.input||i.push({role:"user",content:t.input,name:`__native_run:${t.runId}`});let n=[],a=null;for(let{event:e}of s){if("reasoning_summary_delta"===e.type){let s=`__native_reasoning:${t.runId}:${e.itemId}`,i=n.findIndex(e=>e.name===s);i<0&&(i=n.length,n.push({role:"assistant",content:"",name:s,presentation:{reasoning:[]}}));let r=n[i];n[i]={...r,presentation:{...r.presentation,reasoning:(0,u.bX)(r.presentation?.reasoning,e)}},a=null;continue}if("text_chunk"!==e.type&&"tool_call"!==e.type)continue;null===a&&(a=n.length,n.push({role:"assistant",content:"",name:`__native_run:${t.runId}`}));let s=n[a];n[a]="text_chunk"===e.type?{...s,content:s.content+e.text}:{...s,toolCalls:[...s.toolCalls??[],e.toolCall]}}for(let e of n){let t=e.presentation?.reasoning;if(t?.length){let s=i.findIndex(e=>e.presentation?.reasoning?.some(e=>t.some(t=>t.itemId===e.itemId)));if(s<0)i.push(e);else{let e=i[s],r=[...e.presentation?.reasoning??[]];for(let e of t){let t=r.findIndex(t=>t.itemId===e.itemId&&t.sectionIndex===e.sectionIndex);t<0?r.push(e):e.text.startsWith(r[t].text)&&(r[t]=e)}i[s]={...e,presentation:{...e.presentation,reasoning:r.sort((e,t)=>e.sectionIndex-t.sectionIndex)}}}continue}let s=function(e,t){let s=e.filter(e=>"assistant"===e.role),i=t.content&&s.some(e=>e.content===t.content)?"":t.content,r=new Set(s.flatMap(e=>e.toolCalls?.map(e=>e.id)??[])),n=t.toolCalls?.filter(e=>!r.has(e.id));return i||n?.length?{...t,content:i,toolCalls:n?.length?n:void 0}:null}(i,e);s&&i.push(s)}return i}(e.messages,s.run,s.events);return{...e,...t,messages:i,events:s.events.map(({event:e})=>e),snapshotRevision:s.run?.nextSequence??0,snapshotRunId:s.run?.runId??null}}getRunById(e){let t=this.database.db.prepare("SELECT * FROM native_runtime_run WHERE run_id = ?").get(e);return t?I(t):null}getLatestRetainedRun(e){let t=this.database.db.prepare(`
|
|
99
|
+
SELECT * FROM native_runtime_run
|
|
100
|
+
WHERE session_id = ? AND (status = 'active' OR terminal_at >= ?)
|
|
101
|
+
ORDER BY CASE status WHEN 'active' THEN 0 ELSE 1 END, created_at DESC LIMIT 1
|
|
102
|
+
`).get(e,this.now()-6e5);return t?I(t):null}isApprovalVisible(e){let t=this.database.db.prepare("SELECT state FROM native_runtime_approval WHERE question_id = ?").get(e);return t?.state==="pending"||t?.state==="claimed"}finalizeRun(e,t){let s=this.getRunById(e);if(!s||"active"!==s.status)return;let i=this.now();this.database.db.prepare(`
|
|
103
|
+
UPDATE native_runtime_run SET status = 'terminal', terminal_at = ? WHERE run_id = ?
|
|
104
|
+
`).run(i,e),this.database.db.prepare(`
|
|
105
|
+
UPDATE native_runtime_approval SET state = 'resolved', resolved_at = ?
|
|
106
|
+
WHERE run_id = ? AND state IN ('pending', 'claimed')
|
|
107
|
+
`).run(i,e),this.transitionLock(s.sessionId,"available",null,null)}getLock(e){let t=this.database.db.prepare("SELECT * FROM native_runtime_lock WHERE session_id = ?").get(e);return t?{sessionId:t.session_id,occupancy:t.occupancy,revision:t.revision,sampleState:t.sample_state,sampleAt:t.sample_at}:{sessionId:e,occupancy:"available",revision:0,sampleState:null,sampleAt:null}}transitionLock(e,t,s,i){let r=this.getLock(e),n=r.occupancy===t?r.revision:r.revision+1,a=this.now();return this.database.db.prepare(`
|
|
108
|
+
INSERT INTO native_runtime_lock(session_id, occupancy, revision, sample_state, sample_at, updated_at)
|
|
109
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
110
|
+
ON CONFLICT(session_id) DO UPDATE SET
|
|
111
|
+
occupancy=excluded.occupancy,
|
|
112
|
+
revision=excluded.revision,
|
|
113
|
+
sample_state=excluded.sample_state,
|
|
114
|
+
sample_at=excluded.sample_at,
|
|
115
|
+
updated_at=excluded.updated_at
|
|
116
|
+
`).run(e,t,n,s,i,a),{sessionId:e,occupancy:t,revision:n,sampleState:s,sampleAt:i}}pruneExpiredTerminals(){let e=this.now()-6e5,t=this.database.db.prepare("SELECT run_id FROM native_runtime_run WHERE status = 'terminal' AND terminal_at < ?").all(e);this.database.db.transaction(()=>{for(let e of t)this.database.db.prepare("DELETE FROM native_runtime_event WHERE run_id = ?").run(e.run_id),this.database.db.prepare("DELETE FROM native_runtime_approval WHERE run_id = ?").run(e.run_id),this.database.db.prepare("DELETE FROM native_runtime_run WHERE run_id = ?").run(e.run_id)})()}}class P{constructor(e,t,s=Date.now){this.directory=e,this.subscribers=new Map,this.localSubscribers=new Set,this.pendingCreations=new Map,this.server=null,this.ownsSocket=!1,this.state=new C(e,s),this.runtime="function"==typeof t?t({onApprovalResolved:e=>this.handleApprovalResolved(e)}):t}get socketPath(){return(0,l.join)(this.directory,x)}async start(){if(this.server)return;(0,n.mkdirSync)(this.directory,{recursive:!0,mode:448});try{(0,n.chmodSync)(this.directory,448)}catch{}if((0,n.existsSync)(this.socketPath)){let e=Error(`Native runtime broker socket is already in use: ${this.socketPath}`);throw e.code="EADDRINUSE",e}let e=(0,a.createServer)(e=>this.handleSocket(e));await new Promise((t,s)=>{let i=t=>{e.removeListener("listening",r),s(t)},r=()=>{e.removeListener("error",i),t()};e.once("error",i),e.once("listening",r),e.listen(this.socketPath)});try{(0,n.chmodSync)(this.socketPath,384)}catch{}for(let t of(this.server=e,this.ownsSocket=!0,this.state.recoverInterruptedRuns(),this.state.listActiveGoals()))this.startGoal(t,"web")}async stop(){let e=this.server;for(let e of(this.server=null,this.subscribers.keys()))e.destroy();this.subscribers.clear(),this.localSubscribers.clear(),e&&await new Promise(t=>e.close(()=>t())),this.ownsSocket&&(0,n.existsSync)(this.socketPath)&&(0,n.rmSync)(this.socketPath,{force:!0}),this.ownsSocket=!1,await this.runtime.dispose()}async health(){return this.runtime.health()}async list(e){return this.mergePending(await this.runtime.list(e),e).map(e=>this.state.applySummary(e))}async refresh(e){return this.mergePending(await this.runtime.refresh(e),e).map(e=>this.state.applySummary(e))}async create(e){let t=await this.runtime.create(e);return this.pendingCreations.set(t.id,t),this.state.applySummary(t)}async fork(e){let t=await this.runtime.fork(e);return this.pendingCreations.set(t.id,t),this.state.applySummary(t)}async get(e,t){try{return this.state.applyDetail(await this.runtime.get(e,t))}catch(s){let t=this.pendingCreations.get(e);if(!t)throw s;return this.state.applyDetail({...t,messages:[],events:[]})}}getSessionWatchPath(e){return this.runtime.getSessionWatchPath(e)}async startRun(e,t,s,i="web",r){let n=w(e);try{let t=await this.runtime.get(e);if(!t.canResume||"owned-externally"===t.occupancy)throw this.state.recordExplicitExternalOwnership(e),new f.n("Session is currently owned by another client","SESSION_OCCUPIED")}catch(t){throw t instanceof f.n&&"SESSION_OCCUPIED"===t.code&&this.state.recordExplicitExternalOwnership(e),t}let a=this.state.admit({sessionId:e,agentType:n.agentType,nativeSessionId:n.nativeSessionId,message:t,controller:i,goalId:r});return this.executeRun(a,s),{runId:a.runId,snapshotRevision:a.nextSequence,permissionMode:a.permissionMode}}async getGoals(e,t="web"){let s=this.state.getGoalState(e);return s.active&&!this.state.activeRun(e)&&await this.startGoal(s.active,t),this.state.getGoalState(e)}async enqueueGoal(e,t,s,i="web"){w(e);let r=!!this.state.getGoalState(e).active,n=this.state.enqueueGoal(e,t,s);if(r||!n.active)return{state:n};let a=await this.startGoal(n.active,i);return{state:this.state.getGoalState(e),...a?{started:a}:{}}}reorderGoals(e,t){return w(e),this.state.reorderGoals(e,t)}async cancelGoal(e,t,s="web"){w(e);let i=this.state.getGoalState(e).active?.id===t,r=this.state.activeRun(e),n=this.state.cancelGoal(e,t);return i&&r?.goalId===t?(await this.runtime.abort(e).catch(()=>void 0),!this.state.activeRun(e)&&n.active&&this.startGoal(n.active,s)):i&&!r&&n.active&&this.startGoal(n.active,s),n}subscribe(e,t,s){let i=this.state.getSnapshot(e,t);for(let e of i.events)s(e);let r={sessionId:e,runId:i.runId,afterSequence:i.snapshotRevision,listener:s};return this.localSubscribers.add(r),()=>this.localSubscribers.delete(r)}snapshot(e,t=0){return this.state.getSnapshot(e,t)}async answerQuestion(e,t){let s=this.state.claimApproval(e);if(!s)return!1;try{if(await this.runtime.answerQuestion(e,t))return this.handleApprovalResolved(e),!0}catch{}let i=this.state.appendTerminal(s.runId,{type:"error",code:"APPROVAL_EXPIRED",message:"This approval request is no longer active; the native turn was interrupted. You can send again."});throw i&&this.broadcast(i),new f.n("This approval request is no longer active; the native turn was interrupted.","APPROVAL_EXPIRED")}async abort(e){if(!e)return;let t=this.state.activeRun(e);await this.runtime.abort(e),t&&setTimeout(()=>{let e=this.state.appendTerminal(t.runId,{type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Native turn was interrupted before the runtime confirmed completion."});e&&this.broadcast(e)},3e3).unref?.()}steer(e,t){return this.runtime.steer(e,t)}setPermissionMode(e,t){let s=this.state.activeRun(e),i=this.state.setPermissionMode(e,t),r={id:e,agentType:w(e).agentType,nativeSessionId:w(e).nativeSessionId,title:"Native session",cwd:"",created:new Date().toISOString(),updated:new Date().toISOString(),status:s?"running":"idle",occupancy:s?"owned-by-customer-agent":"available",sourceLabel:"Native runtime broker",canResume:!0,canDelete:!1,permissionMode:i};return this.state.applySummary(r)}handoff(e,t){return this.state.changeController(e,t)}async executeRun(e,t){let s=!1;try{let i={permissionMode:e.permissionMode,brokerRunId:e.runId,...e.goalId?{goal:{id:e.goalId,objective:this.state.getGoalState(e.sessionId).active?.objective??e.input}}:{}};for await(let r of this.runtime.run(e.sessionId,e.input,t,void 0,void 0,i)){let t=this.state.appendEvent(e.runId,r);t&&this.broadcast(t),"error"===r.type&&"SESSION_OCCUPIED"===r.code&&this.state.recordExplicitExternalOwnership(e.sessionId),s||=S(r)}if(!s){let t=this.state.appendTerminal(e.runId,{type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Native runtime stopped without a terminal event."});t&&this.broadcast(t)}}catch(i){let t=i instanceof f.n&&"SESSION_OCCUPIED"===i.code,s=this.state.appendTerminal(e.runId,{type:"error",code:i instanceof f.n?i.code:"NATIVE_PROTOCOL_ERROR",message:i instanceof Error?i.message:"Native runtime failed"});s&&this.broadcast(s),t&&this.state.recordExplicitExternalOwnership(e.sessionId)}finally{if(e.goalId){let t=this.state.getSnapshot(e.sessionId).events,s=[...t].reverse().find(({event:e})=>S(e))?.event,i=s?.type==="done"?"completed":"failed",r=s?.type==="error"?s.message:void 0,n=this.state.finishGoal(e.sessionId,e.goalId,i,r).active;n&&!this.state.activeRun(e.sessionId)&&this.startGoal(n,e.controller)}else{let t=this.state.getGoalState(e.sessionId).active;t&&!this.state.activeRun(e.sessionId)&&this.startGoal(t,e.controller)}}}async startGoal(e,t){if(!this.state.activeRun(e.sessionId))try{return await this.startRun(e.sessionId,e.objective,void 0,t,e.id)}catch(i){let s=this.state.finishGoal(e.sessionId,e.id,"failed",i instanceof Error?i.message:String(i));s.active&&this.startGoal(s.active,t);return}}handleApprovalResolved(e){let t=this.state.resolveApproval(e);t&&this.broadcast(t)}mergePending(e,t){if(void 0!==t)return e;let s=new Set(e.map(e=>e.id));for(let t of e)this.pendingCreations.delete(t.id);return[...e,...[...this.pendingCreations.values()].filter(e=>!s.has(e.id))].sort((e,t)=>t.updated.localeCompare(e.updated))}handleSocket(e){let t="";e.setEncoding("utf8"),e.on("data",s=>{let i=(t+=s).indexOf("\n");for(;i>=0;){let s=t.slice(0,i).trim();t=t.slice(i+1),s&&this.handleSocketLine(e,s),i=t.indexOf("\n")}}),e.on("close",()=>this.subscribers.delete(e)),e.on("error",()=>this.subscribers.delete(e))}handleSocketLine(e,t){let s;try{s=JSON.parse(t)}catch{e.end();return}if(!s.id||!s.method||!s.params||"object"!=typeof s.params){this.write(e,{id:s.id||"",ok:!1,error:{message:"Invalid broker request"}}),e.end();return}if("subscribe"===s.method){let t=T(s.params,"sessionId"),i=R(s.params,"afterSequence")??0;if(!t){this.write(e,{id:s.id,ok:!1,error:{message:"sessionId is required"}}),e.end();return}let r=this.state.getSnapshot(t,i);for(let i of(this.subscribers.set(e,{sessionId:t,runId:r.runId,afterSequence:r.snapshotRevision}),this.write(e,{id:s.id,ok:!0,result:{snapshotRevision:r.snapshotRevision}}),r.events))this.write(e,{type:"event",event:i});return}this.handleRequest(s).then(t=>{this.write(e,{id:s.id,ok:!0,result:t}),e.end()},t=>{this.write(e,{id:s.id,ok:!1,error:{message:t instanceof Error?t.message:String(t),...t instanceof f.n?{code:t.code}:{}}}),e.end()})}async handleRequest(e){let t=T(e.params,"sessionId");switch(e.method){case"ping":return{ok:!0};case"health":return this.health();case"list":return this.list(T(e.params,"projectId")||void 0);case"refresh":return this.refresh(T(e.params,"projectId")||void 0);case"create":return this.create({agentType:function(e,t){let s=T(e,t);if("codex"===s||"claude-code"===s)return s;throw new f.n("A native agent type is required","INVALID_SESSION_ID")}(e.params,"agentType"),title:T(e.params,"title")||"New session",cwd:T(e.params,"cwd")||"",...T(e.params,"projectId")?{projectId:T(e.params,"projectId")}:{}});case"fork":return this.fork(E(t));case"get":return this.get(E(t),function(e){let t=T(e,"before")||void 0,s=R(e,"limit")??void 0;return t||void 0!==s?{before:t,limit:s}:void 0}(e.params));case"watchPath":return this.getSessionWatchPath(E(t));case"startRun":return this.startRun(E(t),T(e.params,"input")||"",N(e.params.images),O(e.params.controller));case"snapshot":return this.snapshot(E(t),R(e.params,"afterSequence")??0);case"getGoals":return this.getGoals(E(t),O(e.params.controller));case"enqueueGoal":return this.enqueueGoal(E(t),T(e.params,"objective")||"",T(e.params,"sourceMessageId")||void 0,O(e.params.controller));case"reorderGoals":return this.reorderGoals(E(t),N(e.params.orderedIds)??[]);case"cancelGoal":return this.cancelGoal(E(t),T(e.params,"goalId")||"",O(e.params.controller));case"answer":var s;return this.answerQuestion(T(e.params,"questionId")||"",{answer:T(e.params,"answer")||"",selectedIndices:(s=e.params.selectedIndices,Array.isArray(s)&&s.every(e=>"number"==typeof e)?s:void 0)});case"abort":return this.abort(t||void 0);case"steer":return this.steer(E(t),T(e.params,"input")||"");case"setPermissionMode":return this.setPermissionMode(E(t),(0,u.Ny)(e.params.permissionMode));case"handoff":return this.handoff(E(t),O(e.params.controller));default:throw new f.n(`Unsupported broker method: ${e.method}`,"OPERATION_NOT_SUPPORTED")}}broadcast(e){let t=this.state.sessionIdForRun(e.runId);if(t){for(let[s,i]of this.subscribers)i.sessionId===t&&(i.runId!==e.runId&&(i.runId=e.runId,i.afterSequence=0),e.sequence<=i.afterSequence||(i.afterSequence=e.sequence,this.write(s,{type:"event",event:e})));for(let s of this.localSubscribers)s.sessionId===t&&(s.runId!==e.runId&&(s.runId=e.runId,s.afterSequence=0),e.sequence<=s.afterSequence||(s.afterSequence=e.sequence,s.listener(e)))}}write(e,t){!e.destroyed&&e.writable&&e.write(`${JSON.stringify(t)}
|
|
117
|
+
`)}}class k{constructor(e={}){this.options=e,this.ensurePromise=null}get directory(){return this.options.directory||process.env.AGENT_NATIVE_RUNTIME_DIR?.trim()||(0,l.join)((0,o.homedir)(),".agentroam","native-runtime")}async health(){return this.request("health",{})}async list(e){return this.request("list",e?{projectId:e}:{})}async refresh(e){return this.request("refresh",e?{projectId:e}:{})}async create(e){return this.request("create",{...e})}async fork(e){return this.request("fork",{sessionId:e})}async get(e,t){return this.request("get",{sessionId:e,...t??{}})}async getSessionWatchPath(e){return this.request("watchPath",{sessionId:e})}async startRun(e,t,s,i="web"){return this.request("startRun",{sessionId:e,input:t,images:s,controller:i})}async *run(e,t,s,i,r,n="desktop"){let a=await this.startRun(e,t,s,n);yield{type:"run_admitted",_nativeRunId:a.runId,_nativeSequence:0};let o=new d.K,l=await this.subscribe(e,0,e=>{e.runId===a.runId&&(o.push({...e.event,_nativeRunId:e.runId,_nativeSequence:e.sequence}),S(e.event)&&o.close())});try{for await(let e of o)yield e}finally{l()}}async subscribe(e,t,s){await this.ensureHost();let i=await A((0,l.join)(this.directory,x)),n=(0,r.randomUUID)(),a=!1,o="",u=new Promise((e,t)=>{let r=s=>{a||(a=!0,s?t(s):e())};i.setEncoding("utf8"),i.on("data",e=>{let t=(o+=e).indexOf("\n");for(;t>=0;){let e=o.slice(0,t).trim();if(o=o.slice(t+1),e)try{let t=JSON.parse(e);"id"in t&&t.id===n?t.ok?r():r(b(t.error)):"type"in t&&"event"===t.type&&t.event&&s(t.event)}catch{r(new f.n("Malformed broker response","NATIVE_PROTOCOL_ERROR"))}t=o.indexOf("\n")}}),i.once("error",e=>r(e)),i.once("close",()=>{a||r(new f.n("Native runtime broker disconnected","RUNTIME_UNAVAILABLE"))})});return i.write(`${JSON.stringify({id:n,method:"subscribe",params:{sessionId:e,afterSequence:t}})}
|
|
118
|
+
`),await u,()=>i.end()}async snapshot(e,t=0){return this.request("snapshot",{sessionId:e,afterSequence:t})}async getGoals(e,t="web"){return this.request("getGoals",{sessionId:e,controller:t})}async enqueueGoal(e,t,s,i="web"){return this.request("enqueueGoal",{sessionId:e,objective:t,sourceMessageId:s,controller:i})}async reorderGoals(e,t){return this.request("reorderGoals",{sessionId:e,orderedIds:[...t]})}async cancelGoal(e,t,s="web"){return this.request("cancelGoal",{sessionId:e,goalId:t,controller:s})}async answerQuestion(e,t){return this.request("answer",{questionId:e,answer:t.answer,selectedIndices:t.selectedIndices})}async abort(e){await this.request("abort",e?{sessionId:e}:{})}async steer(e,t){return this.request("steer",{sessionId:e,input:t})}async setPermissionMode(e,t){return this.request("setPermissionMode",{sessionId:e,permissionMode:t})}async handoff(e,t){return this.request("handoff",{sessionId:e,controller:t})}async request(e,t){return await this.ensureHost(),this.requestRaw(e,t)}async ensureHost(){return this.ensurePromise||(this.ensurePromise=(async()=>{try{await this.requestRaw("ping",{});return}catch{let e=this.options.runtimeFactory;if(!e)throw new f.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");let t=this.directory,s=(0,l.join)(t,x);if((0,n.existsSync)(s))try{await this.requestRaw("ping",{});return}catch{(0,n.rmSync)(s,{force:!0})}let i=function(){let e=globalThis;return e.__agentroamNativeRuntimeBrokerHosts||(e.__agentroamNativeRuntimeBrokerHosts=new Map),e.__agentroamNativeRuntimeBrokerHosts}(),r=i.get(t);if(!r){r=new P(t,e,this.options.now);try{await r.start(),i.set(t,r)}catch(e){if(await r.stop().catch(()=>void 0),!(e&&"object"==typeof e&&"EADDRINUSE"===e.code))throw e}}await this.requestRaw("ping",{})}})().finally(()=>{this.ensurePromise=null})),this.ensurePromise}async requestRaw(e,t){let s=await A((0,l.join)(this.directory,x)),i=(0,r.randomUUID)();return new Promise((r,n)=>{let a="",o=!1,l=(e,t)=>{o||(o=!0,s.destroy(),e?n(e):r(t))};s.setEncoding("utf8"),s.on("data",e=>{let t=(a+=e).indexOf("\n");if(t<0)return;let s=a.slice(0,t).trim();if(s)try{let e=JSON.parse(s);if(e.id!==i)return;e.ok?l(void 0,e.result):l(b(e.error))}catch{l(new f.n("Malformed broker response","NATIVE_PROTOCOL_ERROR"))}}),s.once("error",e=>l(e)),s.once("close",()=>{o||l(new f.n("Native runtime broker disconnected","RUNTIME_UNAVAILABLE"))}),s.write(`${JSON.stringify({id:i,method:e,params:t})}
|
|
119
|
+
`)})}}function v(e={}){return new k(e)}function _(e,t){let s=new p.b({executable:e||"codex"});return new y.V([new h.tX({client:s,onApprovalResolved:t?.onApprovalResolved}),new c.IW],()=>Promise.resolve([]))}function w(e){let t;try{t=(0,m.V)(e)}catch(t){if(t instanceof f.n)throw t;throw new f.n(`Invalid native session id: ${e}`,"INVALID_SESSION_ID")}if("customer-agent"===t.agentType)throw new f.n("Customer Agent sessions are not handled by the native broker","INVALID_SESSION_ID");return t}function I(e){return{sessionId:e.session_id,runId:e.run_id,agentType:e.agent_type,nativeSessionId:e.native_session_id,input:e.input,permissionMode:(0,u.Ny)(e.permission_mode),controller:e.controller,status:e.status,nextSequence:e.next_sequence,createdAt:e.created_at,terminalAt:e.terminal_at,goalId:e.goal_id??null}}function S(e){return"done"===e.type||"error"===e.type}function b(e){let t=e?.code;return t&&["INVALID_SESSION_ID","SESSION_NOT_FOUND","SESSION_OCCUPIED","RUNTIME_UNAVAILABLE","OPERATION_NOT_SUPPORTED","APPROVAL_EXPIRED","NATIVE_PROTOCOL_ERROR"].includes(t)?new f.n(e?.message||"Native runtime broker failed",t):new f.n(e?.message||"Native runtime broker failed","NATIVE_PROTOCOL_ERROR")}function E(e){if(!e)throw new f.n("sessionId is required","INVALID_SESSION_ID");return e}function T(e,t){return"string"==typeof e[t]?e[t]:null}function R(e,t){return"number"==typeof e[t]&&Number.isSafeInteger(e[t])?e[t]:null}function N(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)?e:void 0}function O(e){return"desktop"===e||"web"===e?e:"web"}function A(e){return new Promise((t,s)=>{let i=(0,a.createConnection)(e),r=setTimeout(()=>{i.destroy(),s(new f.n("Timed out connecting to native runtime broker","RUNTIME_UNAVAILABLE"))},2e3);i.once("connect",()=>{clearTimeout(r),i.removeListener("error",n),t(i)});let n=e=>{clearTimeout(r),s(e)};i.once("error",n)})}i()}catch(e){i(e)}})},5779:(e,t,s)=>{s.d(t,{F:()=>a,V:()=>o});var i=s(132);let r="runtime:",n=new Set(["customer-agent","codex","claude-code"]);function a(e,t){if(!t)throw new i.n("Native session ID is required","INVALID_SESSION_ID");let s=Buffer.from(t,"utf8").toString("base64url");return`${r}${e}:${s}`}function o(e){if(!e)throw new i.n("Session ID is required","INVALID_SESSION_ID");if(!e.startsWith(r))return{agentType:"customer-agent",nativeSessionId:e};let t=/^runtime:([^:]+):([A-Za-z0-9_-]+)$/.exec(e);if(!t||!n.has(t[1]))throw new i.n(`Invalid unified session ID: ${e}`,"INVALID_SESSION_ID");let s=t[2],a=Buffer.from(s,"base64url").toString("utf8");if(!a||Buffer.from(a,"utf8").toString("base64url")!==s)throw new i.n(`Invalid unified session ID: ${e}`,"INVALID_SESSION_ID");return{agentType:t[1],nativeSessionId:a}}},132:(e,t,s)=>{s.d(t,{n:()=>i});class i extends Error{constructor(e,t){super(e),this.code=t,this.name="RuntimeSessionError"}}},2428:(e,t,s)=>{s.d(t,{V:()=>o});var i=s(9411),r=s(1322),n=s(5779),a=s(132);class o{constructor(e,t){for(let s of(this.listProjects=t,this.adapters=new Map,this.activeSessionIds=new Set,this.healthCache=[],this.discoveryPromise=null,this.detailCache=new Map,e))this.adapters.set(s.agentType,s)}async health(){let e=await Promise.all([...this.adapters.values()].map(async e=>{try{return await e.health()}catch(t){return{agentType:e.agentType,available:!1,label:e.agentType,error:t instanceof Error?t.message:String(t)}}}));return this.healthCache=e,e}getCachedHealth(){return this.healthCache}async list(e){return(await this.discoverAll()).filter(t=>void 0===e||t.projectId===e)}async refresh(e){return this.discoveryPromise=null,this.detailCache.clear(),this.list(e)}invalidate(e){this.detailCache.delete(e),this.discoveryPromise=null}async discoverAll(){return this.discoveryPromise||(this.discoveryPromise=this.performDiscovery().catch(e=>{throw this.discoveryPromise=null,e})),this.discoveryPromise}async performDiscovery(){let e=await this.listProjects();return(await Promise.all([...this.adapters.values()].map(async t=>{try{return(await t.discoverSessions()).map(t=>l(t,e))}catch(e){return this.recordFailure(t.agentType,e),[]}}))).flat().sort((e,t)=>t.updated.localeCompare(e.updated))}async listChildren(e){return(await this.list()).filter(t=>t.parentSessionId===e)}async get(e,t){let{adapter:s,nativeSessionId:i}=this.resolveAdapter(e),n=(t?.before?this.detailCache.get(e):void 0)??await s.getSession(i);this.cacheDetail(e,n);let a=l(n,await this.listProjects());return t?{...a,...(0,r.MO)(a.messages,a.events,t)}:a}async getSessionWatchPath(e){let{adapter:t,nativeSessionId:s}=this.resolveAdapter(e);return t.getSessionWatchPath?.(s)??null}async create(e){let t=this.adapters.get(e.agentType);if(!t)throw new a.n(`Runtime is unavailable: ${e.agentType}`,"RUNTIME_UNAVAILABLE");if("customer-agent"!==e.agentType&&!e.cwd)throw new a.n("A project working directory is required","INVALID_SESSION_ID");let s=await t.create(e);return this.discoveryPromise=null,s}async fork(e){let{adapter:t,nativeSessionId:s}=this.resolveAdapter(e);if(!t.fork)throw new a.n("This runtime does not support session forks","OPERATION_NOT_SUPPORTED");let i=await t.fork(s);return this.discoveryPromise=null,i}async *run(e,t,s,i,r,n){let{adapter:o,nativeSessionId:l}=this.resolveAdapter(e),u=await o.getSession(l);if(!u.canResume||"owned-externally"===u.occupancy)throw new a.n("Session is currently owned by another client","SESSION_OCCUPIED");if(this.activeSessionIds.has(e))throw new a.n("Session is already running","SESSION_OCCUPIED");this.activeSessionIds.add(e),this.detailCache.delete(e);try{yield*void 0===n?o.run(l,t,s,i,r):o.run(l,t,s,i,r,n)}finally{this.activeSessionIds.delete(e),this.detailCache.delete(e),this.discoveryPromise=null}}async abort(e){if(e){let{adapter:t,nativeSessionId:s}=this.resolveAdapter(e);await t.abort(s);return}await Promise.allSettled([...this.adapters.values()].map(e=>e.abort("")))}async steer(e,t){let{adapter:s,nativeSessionId:i}=this.resolveAdapter(e);if(!s.steer)throw new a.n("This runtime does not support mid-turn steering","OPERATION_NOT_SUPPORTED");return!!this.activeSessionIds.has(e)&&s.steer(i,t)}async answerQuestion(e,t){for(let s of this.adapters.values())if(await s.answerQuestion(e,t))return!0;return!1}async delete(e){let{adapter:t,nativeSessionId:s}=this.resolveAdapter(e);if(!t.delete||"customer-agent"!==t.agentType)throw new a.n("External runtime sessions cannot be deleted","OPERATION_NOT_SUPPORTED");await t.delete(s),this.detailCache.delete(e),this.discoveryPromise=null}async dispose(){await Promise.allSettled([...this.adapters.values()].map(e=>e.dispose?.()))}agentTypeFor(e){return(0,n.V)(e).agentType}resolveAdapter(e){let t=(0,n.V)(e),s=this.adapters.get(t.agentType);if(!s)throw new a.n(`Runtime is unavailable: ${t.agentType}`,"RUNTIME_UNAVAILABLE");return{adapter:s,nativeSessionId:t.nativeSessionId}}recordFailure(e,t){let s=this.healthCache.find(t=>t.agentType===e),i={agentType:e,available:!1,label:s?.label??e,error:t instanceof Error?t.message:String(t)};this.healthCache=[...this.healthCache.filter(t=>t.agentType!==e),i]}cacheDetail(e,t){for(this.detailCache.delete(e),this.detailCache.set(e,t);this.detailCache.size>3;){let e=this.detailCache.keys().next().value;if(!e)break;this.detailCache.delete(e)}}}function l(e,t){if(e.projectId||!e.cwd)return e;let s=(0,i.resolve)(e.cwd),r=t.filter(e=>e.description).map(e=>({project:e,path:(0,i.resolve)(e.description)})).filter(({path:e})=>s===e||s.startsWith(`${e}${i.sep}`)).sort((e,t)=>t.path.length-e.path.length)[0];return r?{...e,projectId:r.project.id}:e}},2083:(e,t,s)=>{s.a(e,async(e,i)=>{try{s.d(t,{NL:()=>h,V_:()=>y,WW:()=>g});var r=s(7561),n=s(612),a=s(9411),o=s(1322),l=s(7578),u=s(5779),d=s(132),c=s(785),p=e([l]);l=(p.then?(await p)():p)[0];let v=globalThis;class _{constructor(e,t=async()=>[]){this.runtime=e,this.listProjects=t,this.pendingCreations=new Map}health(){return this.runtime.health()}async list(e){let[t,s]=await Promise.all([this.runtime.list(),this.listProjects()]);return f(this.withPendingCreations(t.map(e=>m(e,s))),e)}async refresh(e){let[t,s]=await Promise.all([this.runtime.refresh(),this.listProjects()]);return f(this.withPendingCreations(t.map(e=>m(e,s))),e)}async create(e){let t=m(await this.runtime.create(e),await this.listProjects());return this.pendingCreations.set(t.id,t),t}async fork(e){if(!y(e))throw new d.n("Customer Agent sessions do not support native forks","OPERATION_NOT_SUPPORTED");let t=m(await this.runtime.fork(e),await this.listProjects());return this.pendingCreations.set(t.id,t),t}async get(e,t){let s;try{s=await this.runtime.get(e,t)}catch(i){let s=this.pendingCreations.get(e);if(!s)throw i;return t?{...s,messages:[],events:[],history:{nextCursor:null,hasMore:!1,pageSize:0,totalItems:0}}:{...s,messages:[],events:[]}}return m(s,await this.listProjects())}getSessionWatchPath(e){return this.runtime.getSessionWatchPath(e)}run(e,t,s,i,r){return this.runtime.run(e,t,s,i,r)}steer(e,t){return this.runtime.steer(e,t)}abort(e){return this.runtime.abort(e)}answerQuestion(e,t){return this.runtime.answerQuestion(e,t)}async startRun(e,t,s,i="web"){if(!this.runtime.startRun)throw new d.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.startRun(e,t,s,i)}async subscribe(e,t,s){if(!this.runtime.subscribe)throw new d.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.subscribe(e,t,s)}async snapshot(e,t=0){if(!this.runtime.snapshot)throw new d.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.snapshot(e,t)}async setPermissionMode(e,t){if(!this.runtime.setPermissionMode)throw new d.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.setPermissionMode(e,t)}async handoff(e,t){if(!this.runtime.handoff)throw new d.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.handoff(e,t)}async getGoals(e,t="web"){if(!this.runtime.getGoals)throw new d.n("Goal mode is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.getGoals(e,t)}async enqueueGoal(e,t,s,i="web"){if(!this.runtime.enqueueGoal)throw new d.n("Goal mode is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.enqueueGoal(e,t,s,i)}async reorderGoals(e,t){if(!this.runtime.reorderGoals)throw new d.n("Goal mode is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.reorderGoals(e,t)}async cancelGoal(e,t){if(!this.runtime.cancelGoal)throw new d.n("Goal mode is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.cancelGoal(e,t,"web")}withPendingCreations(e){let t=new Set;for(let s of e)t.add(s.id),this.pendingCreations.delete(s.id);let s=[...e];for(let e of this.pendingCreations.values())t.has(e.id)||s.push(e);return s.sort((e,t)=>t.updated.localeCompare(e.updated))}}function h(){if(!v.__nativeRuntimeService){!function(){let e=[(0,a.join)((0,n.homedir)(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],t=(process.env.PATH??"").split(a.delimiter),s=e.filter(e=>(0,r.existsSync)(e)&&!t.includes(e));s.length>0&&(process.env.PATH=[...t,...s].join(a.delimiter))}();let e=new o.XW((0,c.kO)());v.__nativeRuntimeService=new _((0,l.v6)({runtimeFactory:e=>(0,l.WH)(process.env.AGENT_CODEX_BIN?.trim()||"codex",e)}),()=>e.list())}return v.__nativeRuntimeService}function m(e,t){let{projectId:s,...i}=e;if(!e.cwd)return i;let r=(0,a.resolve)(e.cwd),n=t.filter(e=>e.description).map(e=>({project:e,path:(0,a.resolve)(e.description)})).filter(({path:e})=>r===e||r.startsWith(`${e}${a.sep}`)).sort((e,t)=>t.path.length-e.path.length)[0];return n?{...i,projectId:n.project.id}:i}function f(e,t){return void 0===t?e:e.filter(e=>e.projectId===t)}function y(e){try{return"customer-agent"!==(0,u.V)(e).agentType}catch{return!1}}function g(e){if(e instanceof d.n)switch(e.code){case"SESSION_NOT_FOUND":return 404;case"SESSION_OCCUPIED":case"APPROVAL_EXPIRED":return 409;case"RUNTIME_UNAVAILABLE":return 503;case"OPERATION_NOT_SUPPORTED":return 405;default:return 400}return 500}i()}catch(e){i(e)}})},785:(e,t,s)=>{s.d(t,{kO:()=>n,sr:()=>a});var i=s(9411);let r=function(){let e=process.argv[1];if(e){let t=(0,i.dirname)((0,i.resolve)(e)),s=`${i.sep}node_modules${i.sep}.bin`;return t.endsWith(s)?(0,i.resolve)(t,"..",".."):t}return(0,i.resolve)(process.cwd())}();function n(){return function(e=process.env,t=r){return(0,i.resolve)(e.AGENT_DATA_DIR?.trim()||t)}()}function a(){return function(e=process.env,t=r){return(0,i.resolve)(e.AGENT_WORKING_DIRECTORY?.trim()||t)}(process.env,n())}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/webpack-22b57460ff31be13.js"/><script src="/_next/static/chunks/3cc391f0-6377b9b71382a170.js" async=""></script><script src="/_next/static/chunks/183-ffe4acb07968be9e.js" async=""></script><script src="/_next/static/chunks/main-app-07d67f2d4e96ecb8.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>AgentRoam</title><meta name="description" content="General-purpose AI agent API server"/><script src="/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><script src="/_next/static/chunks/webpack-22b57460ff31be13.js" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0]);self.__next_f.push([2,null])</script><script>self.__next_f.push([1,"1:I[7709,[],\"\"]\n3:I[1338,[],\"\"]\n4:I[1573,[],\"\"]\na:I[6554,[],\"\"]\n5:{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"}\n6:{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"}\n7:{\"display\":\"inline-block\"}\n8:{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0}\nb:[]\n"])</script><script>self.__next_f.push([1,"0:[\"$\",\"$L1\",null,{\"buildId\":\"
|
|
1
|
+
<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/webpack-22b57460ff31be13.js"/><script src="/_next/static/chunks/3cc391f0-6377b9b71382a170.js" async=""></script><script src="/_next/static/chunks/183-ffe4acb07968be9e.js" async=""></script><script src="/_next/static/chunks/main-app-07d67f2d4e96ecb8.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>AgentRoam</title><meta name="description" content="General-purpose AI agent API server"/><script src="/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><script src="/_next/static/chunks/webpack-22b57460ff31be13.js" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0]);self.__next_f.push([2,null])</script><script>self.__next_f.push([1,"1:I[7709,[],\"\"]\n3:I[1338,[],\"\"]\n4:I[1573,[],\"\"]\na:I[6554,[],\"\"]\n5:{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"}\n6:{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"}\n7:{\"display\":\"inline-block\"}\n8:{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0}\nb:[]\n"])</script><script>self.__next_f.push([1,"0:[\"$\",\"$L1\",null,{\"buildId\":\"9pvPG6rD0pKUnx50jLZOe\",\"assetPrefix\":\"\",\"urlParts\":[\"\",\"_not-found\"],\"initialTree\":[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",true],\"initialSeedData\":[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{},[[\"$L2\",[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":\"404\"}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],null],null],null]},[null,[\"$\",\"$L3\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\",\"/_not-found\",\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L4\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"notFoundStyles\":\"$undefined\"}]],null]},[[null,[\"$\",\"html\",null,{\"lang\":\"en\",\"children\":[\"$\",\"body\",null,{\"children\":[\"$\",\"$L3\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L4\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$5\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$6\",\"children\":\"404\"}],[\"$\",\"div\",null,{\"style\":\"$7\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$8\",\"children\":\"This page could not be found.\"}]}]]}]}]],\"notFoundStyles\":[]}]}]}]],null],null],\"couldBeIntercepted\":false,\"initialHead\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],\"$L9\"],\"globalErrorComponent\":\"$a\",\"missingSlots\":\"$Wb\"}]\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}],[\"$\",\"meta\",\"1\",{\"charSet\":\"utf-8\"}],[\"$\",\"title\",\"2\",{\"children\":\"AgentRoam\"}],[\"$\",\"meta\",\"3\",{\"name\":\"description\",\"content\":\"General-purpose AI agent API server\"}]]\n2:null\n"])</script></body></html>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<!DOCTYPE html><html><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width"/><title>500: Internal Server Error</title><meta name="next-head-count" content="3"/><noscript data-n-css=""></noscript><script defer="" nomodule="" src="/_next/static/chunks/polyfills-42372ed130431b0a.js"></script><script src="/_next/static/chunks/webpack-22b57460ff31be13.js" defer=""></script><script src="/_next/static/chunks/framework-7bac12ed8564755e.js" defer=""></script><script src="/_next/static/chunks/main-a03d29ab49823387.js" defer=""></script><script src="/_next/static/chunks/pages/_app-389e6eb8abb0af2d.js" defer=""></script><script src="/_next/static/chunks/pages/_error-7cee5565b5ef9bcb.js" defer=""></script><script src="/_next/static/
|
|
1
|
+
<!DOCTYPE html><html><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width"/><title>500: Internal Server Error</title><meta name="next-head-count" content="3"/><noscript data-n-css=""></noscript><script defer="" nomodule="" src="/_next/static/chunks/polyfills-42372ed130431b0a.js"></script><script src="/_next/static/chunks/webpack-22b57460ff31be13.js" defer=""></script><script src="/_next/static/chunks/framework-7bac12ed8564755e.js" defer=""></script><script src="/_next/static/chunks/main-a03d29ab49823387.js" defer=""></script><script src="/_next/static/chunks/pages/_app-389e6eb8abb0af2d.js" defer=""></script><script src="/_next/static/chunks/pages/_error-7cee5565b5ef9bcb.js" defer=""></script><script src="/_next/static/9pvPG6rD0pKUnx50jLZOe/_buildManifest.js" defer=""></script><script src="/_next/static/9pvPG6rD0pKUnx50jLZOe/_ssgManifest.js" defer=""></script></head><body><div id="__next"><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div style="line-height:48px"><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding-right:23px;font-size:24px;font-weight:500;vertical-align:top">500</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:28px">Internal Server Error<!-- -->.</h2></div></div></div></div><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"statusCode":500}},"page":"/_error","query":{},"buildId":"9pvPG6rD0pKUnx50jLZOe","nextExport":true,"isFallback":false,"gip":true,"scriptLoader":[]}</script></body></html>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"node":{},"edge":{},"encryptionKey":"
|
|
1
|
+
{"node":{},"edge":{},"encryptionKey":"xE6sF6Z3mIdel0akbZRfHChOtCs571SFpXuinTgdpsk="}
|