agentroam 0.2.0-preview.5 → 0.2.0-preview.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/cli.js +1 -1
- package/dist/cloudflared/bundled-asset.test.js +1 -1
- package/dist/cloudflared/manifest.js +1 -1
- package/dist/tunnel/public-readiness.js +1 -1
- package/package.json +2 -2
- package/runtime/.next/BUILD_ID +1 -1
- package/runtime/.next/app-build-manifest.json +4 -4
- package/runtime/.next/app-path-routes-manifest.json +1 -1
- package/runtime/.next/build-manifest.json +5 -5
- package/runtime/.next/prerender-manifest.json +1 -1
- package/runtime/.next/react-loadable-manifest.json +2 -2
- package/runtime/.next/server/app/_not-found/page_client-reference-manifest.js +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/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/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 +2 -2
- package/runtime/.next/server/app/api/agent/stream/route.js.nft.json +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]/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/web/page.js +1 -1
- package/runtime/.next/server/app/web/page_client-reference-manifest.js +1 -1
- package/runtime/.next/server/app/web.html +1 -1
- package/runtime/.next/server/app/web.rsc +2 -2
- package/runtime/.next/server/app-paths-manifest.json +15 -15
- package/runtime/.next/server/chunks/{809.js → 988.js} +10 -10
- package/runtime/.next/server/middleware-build-manifest.js +1 -1
- package/runtime/.next/server/middleware-react-loadable-manifest.js +1 -1
- 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/static/chunks/404.829f96e7395dbd79.js +1 -0
- package/runtime/.next/static/chunks/app/web/page-8747e21600303a2a.js +1 -0
- package/runtime/.next/static/chunks/{webpack-8bcef6486c3ddc96.js → webpack-96381cef391af02d.js} +1 -1
- package/runtime/node_modules/@agent/core/dist/domain/web-console/WebArtifactBridge.d.ts +9 -0
- package/runtime/node_modules/@agent/core/dist/domain/web-console/WebArtifactBridge.d.ts.map +1 -0
- package/runtime/node_modules/@agent/core/dist/domain/web-console/WebArtifactBridge.test.d.ts +2 -0
- package/runtime/node_modules/@agent/core/dist/domain/web-console/WebArtifactBridge.test.d.ts.map +1 -0
- package/runtime/node_modules/@agent/core/dist/domain/web-console/index.d.ts +1 -0
- package/runtime/node_modules/@agent/core/dist/domain/web-console/index.d.ts.map +1 -1
- package/runtime/node_modules/@agent/core/dist/index.js +24 -1
- package/runtime/node_modules/@agent/core/dist/index.js.map +4 -3
- package/runtime/webapp/dist/assets/{App-XUxeDI8P.js → App-C4wiUXZC.js} +62 -62
- package/runtime/webapp/dist/assets/index-D7slQOD-.css +1 -0
- package/runtime/webapp/dist/assets/{index-BdHtZjnb.js → index-DhS2YvqH.js} +1 -1
- package/runtime/webapp/dist/index.html +2 -2
- package/runtime/.next/static/chunks/604.749f141c00996f2f.js +0 -1
- package/runtime/.next/static/chunks/app/web/page-7d24c8b46d41da35.js +0 -1
- package/runtime/webapp/dist/assets/index-DeGogWCH.css +0 -1
- /package/runtime/.next/static/{mZZGSYMLIZnVm0gc5PXky → HvOq-7Qqu9K-QSMSBbbdj}/_buildManifest.js +0 -0
- /package/runtime/.next/static/{mZZGSYMLIZnVm0gc5PXky → HvOq-7Qqu9K-QSMSBbbdj}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";(()=>{var e={};e.id=820,e.ids=[820],e.modules={7728:e=>{e.exports=require("@anthropic-ai/claude-agent-sdk")},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")},7503:e=>{e.exports=require("node:net")},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")},5881:e=>{e.exports=require("node:util")},2592:(e,t,s)=>{s.r(t),s.d(t,{originalPathname:()=>g,patchFetch:()=>v,requestAsyncStorage:()=>h,routeModule:()=>d,serverHooks:()=>m,staticGenerationAsyncStorage:()=>p});var r={};s.r(r),s.d(r,{GET:()=>u});var o=s(7786),i=s(5042),n=s(2184),a=s(7186),l=s(
|
|
1
|
+
"use strict";(()=>{var e={};e.id=820,e.ids=[820],e.modules={7728:e=>{e.exports=require("@anthropic-ai/claude-agent-sdk")},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")},7503:e=>{e.exports=require("node:net")},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")},5881:e=>{e.exports=require("node:util")},2592:(e,t,s)=>{s.r(t),s.d(t,{originalPathname:()=>g,patchFetch:()=>v,requestAsyncStorage:()=>h,routeModule:()=>d,serverHooks:()=>m,staticGenerationAsyncStorage:()=>p});var r={};s.r(r),s.d(r,{GET:()=>u});var o=s(7786),i=s(5042),n=s(2184),a=s(7186),l=s(3988);async function u(e){let t=new URL(e.url).searchParams.get("sessionId");if(!t)return new Response("sessionId is required",{status:400});if((0,l.V_)(t))return c(e,t);let s=!1,r=null,o=null;return new Response(new ReadableStream({start(i){let n=new TextEncoder,l=()=>{if(!s){s=!0,r?.(),r=null,o&&e.signal.removeEventListener("abort",o);try{i.close()}catch{}}},u=e=>{if(s)return!1;try{return i.enqueue(n.encode(e)),!0}catch{return l(),!1}};if(!u(": connected\n\n"))return;let c=Number.parseInt(e.headers.get("last-event-id")??"",10),d=Number.isSafeInteger(c)?c:a.f.getLatestEventId(t);r=a.f.subscribe(t,(e,t)=>{u(`id: ${t}
|
|
2
2
|
data: ${JSON.stringify(e)}
|
|
3
3
|
|
|
4
4
|
`)&&("done"===e.type||"error"===e.type)&&l()},d),o=l,e.signal.aborted?l():e.signal.addEventListener("abort",o,{once:!0})},cancel(){s=!0,r?.(),r=null,o&&e.signal.removeEventListener("abort",o)}}),{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}async function c(e,t){let s=!1,r=null,o=null,i=(0,l.NL)(),n=new URL(e.url),a=Number.parseInt(n.searchParams.get("afterSequence")??"",10),u=n.searchParams.get("afterRunId"),c=e.headers.get("last-event-id");return new Response(new ReadableStream({async start(n){let l=new TextEncoder,d=()=>{if(!s){s=!0,r?.(),r=null,o&&e.signal.removeEventListener("abort",o);try{n.close()}catch{}}},h=e=>{if(s)return!1;try{return n.enqueue(l.encode(e)),!0}catch{return d(),!1}};if(h(": connected\n\n"))try{let s=await i.snapshot(t),n=function(e){if(!e)return null;let t=e.lastIndexOf(":");if(t<0){let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?{runId:null,sequence:t}:null}let s=e.slice(0,t),r=Number.parseInt(e.slice(t+1),10);return s&&Number.isSafeInteger(r)?{runId:s,sequence:r}:null}(c),l=Number.isSafeInteger(a)?{runId:u,sequence:a}:null,p=n??l,m=p?p.runId&&p.runId!==s.runId?0:p.sequence:s.snapshotRevision;r=await i.subscribe(t,m,({runId:e,sequence:t,event:s})=>{let r={...s,_nativeRunId:e,_nativeSequence:t};h(`id: ${e}:${t}
|
|
@@ -9,4 +9,4 @@ data: ${JSON.stringify({type:"error",message:e instanceof Error?e.message:"Nativ
|
|
|
9
9
|
|
|
10
10
|
`),d()}},cancel(){s=!0,r?.(),r=null,o&&e.signal.removeEventListener("abort",o)}}),{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let d=new o.AppRouteRouteModule({definition:{kind:i.x.APP_ROUTE,page:"/api/agent/stream/route",pathname:"/api/agent/stream",filename:"route",bundlePath:"app/api/agent/stream/route"},resolvedPagePath:"/Users/caoqu/team-agent/customer-agent/packages/server/app/api/agent/stream/route.ts",nextConfigOutput:"standalone",userland:r}),{requestAsyncStorage:h,staticGenerationAsyncStorage:p,serverHooks:m}=d,g="/api/agent/stream/route";function v(){return(0,n.patchFetch)({serverHooks:m,staticGenerationAsyncStorage:p})}},7786:(e,t,s)=>{e.exports=s(517)},7186:(e,t,s)=>{s.d(t,{B:()=>n,f:()=>u});var r=s(1322),o=s(612),i=s(785);class n extends Error{constructor(e,t,s){super(e),this.code=t,this.status=s,this.name="ProjectWorkingDirectoryError"}}class a{constructor(){this.baseDir=(0,i.kO)(),this.workingDirectory=(0,i.sr)(),this.builder=null,this.sessionStore=new r.m6(this.baseDir),this.projectStore=new r.XW(this.baseDir),this.remoteToolStore=new r.rt((0,r.N8)(this.baseDir).db),this.defaultRemoteToolsProjectId=process.env.AGENT_PROJECT_ID??"default",this.activeRun=null,this.activeAgent=null,this.activeRunSessionId=null,this.subscribers=new Map,this.recentEvents=new Map,this.eventCounters=new Map,this.pendingQuestions=new Map,this.toolPermissionGate=new r.XP({resolveMode:async e=>{let t=await this.sessionStore.get(e);return(0,r.Ny)(t?.metadata.permissionMode)},requestApproval:async e=>{let t=await this.createQuestion({question:`Customer Agent 请求权限
|
|
11
11
|
${e.summary}
|
|
12
|
-
原因:${e.reason}`,options:[...r.Sf],toolCallId:""},e.sessionId);return(0,r.wM)(t.answer,t.selectedIndices)}});let e=process.env.AGENT_API_KEY,t=process.env.AGENT_MODEL_PROVIDER||"openai",s=process.env.AGENT_MODEL_ID||"gpt-4o",o=process.env.AGENT_BASE_URL||void 0,n=new r.Y4().withSessionStore(this.sessionStore).withWorkingDirectory(this.workingDirectory).withToolPermissionGate(this.toolPermissionGate);n.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e&&n.withModel(t,{apiKey:e,modelId:s,baseUrl:o}),this.builder=n}getBuilder(){return this.builder||(this.builder=new r.Y4().withToolPermissionGate(this.toolPermissionGate)),this.builder}setBuilder(e){e.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e.withWorkingDirectory(this.workingDirectory),e.withToolPermissionGate(this.toolPermissionGate),this.builder=e}getSessionStore(){return this.sessionStore}getProjectStore(){return this.projectStore}async resolveProjectWorkingDirectory(e,t=!1){if(!e)return this.workingDirectory;let s=await this.projectStore.get(e);if(!s)throw new n("项目不存在","PROJECT_NOT_FOUND",404);if(!s.description?.trim()){if(!t)return this.workingDirectory;throw new n("该项目没有宿主机目录","PROJECT_PATH_REQUIRED",400)}try{return r.Tp.fromEnvironment(process.env.AGENT_WEB_ROOTS,(0,o.homedir)()).assertDirectory(s.description)}catch(e){throw new n(e instanceof Error?e.message:"项目目录不可用","PROJECT_PATH_INVALID",400)}}getModelConfig(){return{provider:process.env.AGENT_MODEL_PROVIDER||"openai",modelId:process.env.AGENT_MODEL_ID||"gpt-4o",baseUrl:process.env.AGENT_BASE_URL||""}}getWebAppBuildId(){return globalThis.__webAppBuildId??""}registerRemoteTools(e,t){return this.remoteToolStore.upsertTools(e,t)}getRemoteToolStore(){return this.remoteToolStore}async createSession(e,t=""){let s=new Date().toISOString();return t&&!await this.projectStore.get(t)&&await this.projectStore.create({id:t,name:t,description:"",created:s,updated:s}),this.sessionStore.create({id:crypto.randomUUID(),projectId:t,title:e,status:"idle",messages:[],events:[],created:s,updated:s,metadata:{permissionMode:"full-access"}})}async setSessionPermissionMode(e,t){if(!(0,r.ue)(t))throw Error(`Invalid permission mode: ${String(t)}`);let s=await this.sessionStore.get(e);if(!s)throw Error(`Session not found: ${e}`);return this.toolPermissionGate.clearSession(e),this.sessionStore.update(e,{metadata:{...s.metadata,permissionMode:t}})}getLatestEventId(e){return this.eventCounters.get(e)??0}subscribe(e,t,s=-1){for(let r of this.recentEvents.get(e)??[])if(!(r.id<=s))try{t(r.event,r.id)}catch{}let r=this.subscribers.get(e)??new Set;return r.add(t),this.subscribers.set(e,r),()=>{r.delete(t),0===r.size&&this.subscribers.delete(e)}}emit(e,t){let s=(this.eventCounters.get(e)??0)+1;this.eventCounters.set(e,s);let r=this.recentEvents.get(e);for(let o of(r&&(r.push({id:s,event:t}),r.length>500&&r.splice(0,r.length-500)),this.subscribers.get(e)??[]))try{o(t,s)}catch{}}publishExternal(e,t){this.emit(e,t)}resetExternalStream(e){this.eventCounters.set(e,0),this.recentEvents.set(e,[])}projectMessagesFromEvents(e){let t=[],s=null;for(let r of e){if("text_chunk"===r.type){s||(s={role:"assistant",content:""},t.push(s)),s.content+=r.text;continue}if("tool_call"===r.type){s&&!s.toolCalls?s.toolCalls=[r.toolCall]:t.push({role:"assistant",content:"",toolCalls:[r.toolCall]}),s=null;continue}if("tool_result"===r.type){t.push({role:"tool",content:r.result.content,toolCallId:r.result.toolCallId});continue}if("ask_user"===r.type){t.push({role:"assistant",content:""}),s=null;continue}"done"===r.type&&(s?s.content=r.finalText||s.content:r.finalText?.trim()&&t.push({role:"assistant",content:r.finalText}),s=null)}return t}async run(e,t,s){let o;let i=await this.sessionStore.get(t),n=await this.resolveProjectWorkingDirectory(i?.projectId);await this.sessionStore.addMessage(t,{role:"user",content:e}),this.eventCounters.set(t,0),this.recentEvents.set(t,[]);let a=i?.projectId||this.defaultRemoteToolsProjectId;try{o=await this.getBuilder().withWorkingDirectory(n).withRemoteToolStore(this.remoteToolStore,a).withTool(new r.as(async e=>this.createQuestion(e,t))).build()}catch(s){let e={type:"error",message:s instanceof Error?s.message:"Failed to build agent"};try{await this.sessionStore.addEvent(t,e)}catch{}throw this.emit(t,e),s}finally{this.builder?.withWorkingDirectory(this.workingDirectory).withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId)}this.activeAgent=o,this.activeRunSessionId=t,this.activeRun=o.run(e,t,s);let l=!1;try{for await(let e of this.activeRun)await this.sessionStore.addEvent(t,e),"error"===e.type?(l=!0,await this.sessionStore.update(t,{status:"failed"})):"done"!==e.type||l||(e.finalText.trim()&&await this.sessionStore.addMessage(t,{role:"assistant",content:e.finalText}),await this.sessionStore.update(t,{status:"completed"})),this.emit(t,e)}catch(s){l=!0;let e={type:"error",message:s instanceof Error?s.message:"Agent run failed"};try{await this.sessionStore.addEvent(t,e),await this.sessionStore.update(t,{status:"failed"})}catch{}this.emit(t,e)}finally{this.activeRunSessionId===t&&(this.activeAgent=null,this.activeRunSessionId=null),this.activeRun=null}try{let e=await this.sessionStore.get(t),s=(e?.messages??[]).filter(e=>"user"===e.role),r=this.projectMessagesFromEvents(e?.events??[]);await this.sessionStore.replaceMessages(t,[...s,...r])}catch{}}createQuestion(e,t){let s=crypto.randomUUID();return this.emit(t,{type:"ask_user",questionId:s,question:e.question,options:e.options,multiSelect:e.multiSelect}),new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingQuestions.has(s)&&(this.pendingQuestions.delete(s),t(Error("Question timed out after 5 minutes")))},3e5);this.pendingQuestions.set(s,{resolve:e,reject:t,timer:r})})}answerQuestion(e,t,s){let r=this.pendingQuestions.get(e);return!!r&&(clearTimeout(r.timer),this.pendingQuestions.delete(e),r.resolve({answer:t,selectedIndices:s}),!0)}async steer(e,t){return await this.sessionStore.addMessage(t,{role:"user",content:e,name:"__steer__"}),this.activeRunSessionId===t&&!!this.activeAgent&&(this.emit(t,{type:"thinking",message:`User added: ${e.slice(0,60)}`}),!0)}abort(){for(let[e,t]of(this.activeAgent?.abort(),this.pendingQuestions))clearTimeout(t.timer),t.reject(Error("Agent aborted")),this.pendingQuestions.delete(e)}}let l=globalThis,u=l.__agentHost??new a;l.__agentHost=u}};var t=require("../../../../webpack-runtime.js");t.C(e);var s=e=>t(t.s=e),r=t.X(0,[375,322,
|
|
12
|
+
原因:${e.reason}`,options:[...r.Sf],toolCallId:""},e.sessionId);return(0,r.wM)(t.answer,t.selectedIndices)}});let e=process.env.AGENT_API_KEY,t=process.env.AGENT_MODEL_PROVIDER||"openai",s=process.env.AGENT_MODEL_ID||"gpt-4o",o=process.env.AGENT_BASE_URL||void 0,n=new r.Y4().withSessionStore(this.sessionStore).withWorkingDirectory(this.workingDirectory).withToolPermissionGate(this.toolPermissionGate);n.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e&&n.withModel(t,{apiKey:e,modelId:s,baseUrl:o}),this.builder=n}getBuilder(){return this.builder||(this.builder=new r.Y4().withToolPermissionGate(this.toolPermissionGate)),this.builder}setBuilder(e){e.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e.withWorkingDirectory(this.workingDirectory),e.withToolPermissionGate(this.toolPermissionGate),this.builder=e}getSessionStore(){return this.sessionStore}getProjectStore(){return this.projectStore}async resolveProjectWorkingDirectory(e,t=!1){if(!e)return this.workingDirectory;let s=await this.projectStore.get(e);if(!s)throw new n("项目不存在","PROJECT_NOT_FOUND",404);if(!s.description?.trim()){if(!t)return this.workingDirectory;throw new n("该项目没有宿主机目录","PROJECT_PATH_REQUIRED",400)}try{return r.Tp.fromEnvironment(process.env.AGENT_WEB_ROOTS,(0,o.homedir)()).assertDirectory(s.description)}catch(e){throw new n(e instanceof Error?e.message:"项目目录不可用","PROJECT_PATH_INVALID",400)}}getModelConfig(){return{provider:process.env.AGENT_MODEL_PROVIDER||"openai",modelId:process.env.AGENT_MODEL_ID||"gpt-4o",baseUrl:process.env.AGENT_BASE_URL||""}}getWebAppBuildId(){return globalThis.__webAppBuildId??""}registerRemoteTools(e,t){return this.remoteToolStore.upsertTools(e,t)}getRemoteToolStore(){return this.remoteToolStore}async createSession(e,t=""){let s=new Date().toISOString();return t&&!await this.projectStore.get(t)&&await this.projectStore.create({id:t,name:t,description:"",created:s,updated:s}),this.sessionStore.create({id:crypto.randomUUID(),projectId:t,title:e,status:"idle",messages:[],events:[],created:s,updated:s,metadata:{permissionMode:"full-access"}})}async setSessionPermissionMode(e,t){if(!(0,r.ue)(t))throw Error(`Invalid permission mode: ${String(t)}`);let s=await this.sessionStore.get(e);if(!s)throw Error(`Session not found: ${e}`);return this.toolPermissionGate.clearSession(e),this.sessionStore.update(e,{metadata:{...s.metadata,permissionMode:t}})}getLatestEventId(e){return this.eventCounters.get(e)??0}subscribe(e,t,s=-1){for(let r of this.recentEvents.get(e)??[])if(!(r.id<=s))try{t(r.event,r.id)}catch{}let r=this.subscribers.get(e)??new Set;return r.add(t),this.subscribers.set(e,r),()=>{r.delete(t),0===r.size&&this.subscribers.delete(e)}}emit(e,t){let s=(this.eventCounters.get(e)??0)+1;this.eventCounters.set(e,s);let r=this.recentEvents.get(e);for(let o of(r&&(r.push({id:s,event:t}),r.length>500&&r.splice(0,r.length-500)),this.subscribers.get(e)??[]))try{o(t,s)}catch{}}publishExternal(e,t){this.emit(e,t)}resetExternalStream(e){this.eventCounters.set(e,0),this.recentEvents.set(e,[])}projectMessagesFromEvents(e){let t=[],s=null;for(let r of e){if("text_chunk"===r.type){s||(s={role:"assistant",content:""},t.push(s)),s.content+=r.text;continue}if("tool_call"===r.type){s&&!s.toolCalls?s.toolCalls=[r.toolCall]:t.push({role:"assistant",content:"",toolCalls:[r.toolCall]}),s=null;continue}if("tool_result"===r.type){t.push({role:"tool",content:r.result.content,toolCallId:r.result.toolCallId});continue}if("ask_user"===r.type){t.push({role:"assistant",content:""}),s=null;continue}"done"===r.type&&(s?s.content=r.finalText||s.content:r.finalText?.trim()&&t.push({role:"assistant",content:r.finalText}),s=null)}return t}async run(e,t,s){let o;let i=await this.sessionStore.get(t),n=await this.resolveProjectWorkingDirectory(i?.projectId);await this.sessionStore.addMessage(t,{role:"user",content:e}),this.eventCounters.set(t,0),this.recentEvents.set(t,[]);let a=i?.projectId||this.defaultRemoteToolsProjectId;try{o=await this.getBuilder().withWorkingDirectory(n).withRemoteToolStore(this.remoteToolStore,a).withTool(new r.as(async e=>this.createQuestion(e,t))).build()}catch(s){let e={type:"error",message:s instanceof Error?s.message:"Failed to build agent"};try{await this.sessionStore.addEvent(t,e)}catch{}throw this.emit(t,e),s}finally{this.builder?.withWorkingDirectory(this.workingDirectory).withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId)}this.activeAgent=o,this.activeRunSessionId=t,this.activeRun=o.run(e,t,s);let l=!1;try{for await(let e of this.activeRun)await this.sessionStore.addEvent(t,e),"error"===e.type?(l=!0,await this.sessionStore.update(t,{status:"failed"})):"done"!==e.type||l||(e.finalText.trim()&&await this.sessionStore.addMessage(t,{role:"assistant",content:e.finalText}),await this.sessionStore.update(t,{status:"completed"})),this.emit(t,e)}catch(s){l=!0;let e={type:"error",message:s instanceof Error?s.message:"Agent run failed"};try{await this.sessionStore.addEvent(t,e),await this.sessionStore.update(t,{status:"failed"})}catch{}this.emit(t,e)}finally{this.activeRunSessionId===t&&(this.activeAgent=null,this.activeRunSessionId=null),this.activeRun=null}try{let e=await this.sessionStore.get(t),s=(e?.messages??[]).filter(e=>"user"===e.role),r=this.projectMessagesFromEvents(e?.events??[]);await this.sessionStore.replaceMessages(t,[...s,...r])}catch{}}createQuestion(e,t){let s=crypto.randomUUID();return this.emit(t,{type:"ask_user",questionId:s,question:e.question,options:e.options,multiSelect:e.multiSelect}),new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingQuestions.has(s)&&(this.pendingQuestions.delete(s),t(Error("Question timed out after 5 minutes")))},3e5);this.pendingQuestions.set(s,{resolve:e,reject:t,timer:r})})}answerQuestion(e,t,s){let r=this.pendingQuestions.get(e);return!!r&&(clearTimeout(r.timer),this.pendingQuestions.delete(e),r.resolve({answer:t,selectedIndices:s}),!0)}async steer(e,t){return await this.sessionStore.addMessage(t,{role:"user",content:e,name:"__steer__"}),this.activeRunSessionId===t&&!!this.activeAgent&&(this.emit(t,{type:"thinking",message:`User added: ${e.slice(0,60)}`}),!0)}abort(){for(let[e,t]of(this.activeAgent?.abort(),this.pendingQuestions))clearTimeout(t.timer),t.reject(Error("Agent aborted")),this.pendingQuestions.delete(e)}}let l=globalThis,u=l.__agentHost??new a;l.__agentHost=u}};var t=require("../../../../webpack-runtime.js");t.C(e);var s=e=>t(t.s=e),r=t.X(0,[375,322,988],()=>s(2592));module.exports=r})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":1,"files":["../../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../../node_modules/better-sqlite3","../../../../../../node_modules/next","../../../../../../package.json","../../../../../package.json","../../../../chunks/322.js","../../../../chunks/375.js","../../../../chunks/
|
|
1
|
+
{"version":1,"files":["../../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../../node_modules/better-sqlite3","../../../../../../node_modules/next","../../../../../../package.json","../../../../../package.json","../../../../chunks/322.js","../../../../chunks/375.js","../../../../chunks/988.js","../../../../webpack-runtime.js"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";(()=>{var t={};t.id=917,t.ids=[917],t.modules={7728:t=>{t.exports=require("@anthropic-ai/claude-agent-sdk")},5890:t=>{t.exports=require("better-sqlite3")},399:t=>{t.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},517:t=>{t.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},9801:t=>{t.exports=require("os")},7718:t=>{t.exports=require("node:child_process")},6005:t=>{t.exports=require("node:crypto")},5673:t=>{t.exports=require("node:events")},7561:t=>{t.exports=require("node:fs")},3977:t=>{t.exports=require("node:fs/promises")},8849:t=>{t.exports=require("node:http")},2286:t=>{t.exports=require("node:https")},7503:t=>{t.exports=require("node:net")},612:t=>{t.exports=require("node:os")},9411:t=>{t.exports=require("node:path")},1747:t=>{t.exports=require("node:readline")},1041:t=>{t.exports=require("node:url")},5881:t=>{t.exports=require("node:util")},7428:(t,e,i)=>{i.r(e),i.d(e,{originalPathname:()=>tx,patchFetch:()=>tI,requestAsyncStorage:()=>tP,routeModule:()=>tb,serverHooks:()=>tR,staticGenerationAsyncStorage:()=>tD});var s={};i.r(s),i.d(s,{GET:()=>tv,dynamic:()=>tg,runtime:()=>ty});var r=i(7786),n=i(5042),a=i(2184),o=i(4809),h=i(5673),l=i(7561),d=i(3977),c=i(9411);let p=require("node:stream"),u={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},f={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:u.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(f);let _="READDIRP_RECURSIVE_ERROR",m=new Set(["ENOENT","EPERM","EACCES","ELOOP",_]),w=[u.DIR_TYPE,u.EVERYTHING_TYPE,u.FILE_DIR_TYPE,u.FILE_TYPE],g=new Set([u.DIR_TYPE,u.EVERYTHING_TYPE,u.FILE_DIR_TYPE]),y=new Set([u.EVERYTHING_TYPE,u.FILE_DIR_TYPE,u.FILE_TYPE]),E=t=>m.has(t.code),v="win32"===process.platform,b=t=>!0,P=t=>{if(void 0===t)return b;if("function"==typeof t)return t;if("string"==typeof t){let e=t.trim();return t=>t.basename===e}if(Array.isArray(t)){let e=t.map(t=>t.trim());return t=>e.some(e=>t.basename===e)}return b};class D extends p.Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark??f.highWaterMark});let e={...f,...t},i=e.root??f.root,s=e.type??f.type;this._fileFilter=P(e.fileFilter),this._directoryFilter=P(e.directoryFilter);let r=e.lstat?d.lstat:d.stat;v?this._stat=t=>r(t,{bigint:!0}):this._stat=r,this._maxDepth=null!=e.depth&&Number.isSafeInteger(e.depth)?e.depth:f.depth,this._wantsDir=g.has(s),this._wantsFile=y.has(s),this._wantsEverything=s===u.EVERYTHING_TYPE,this._root=(0,c.resolve)(i),this._relStart=this._root.endsWith(c.sep)?this._root.length:this._root.length+1,this._isDirent=!e.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let n={path:this._root,depth:1};n.pending=this._exploreDir(this._root,1),this.parents=[n],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let e=this.parent,i=e&&e.files;if(i&&i.length>0){let{path:s,depth:r}=e,n=i.splice(0,t).map(t=>this._formatEntry(t,s));for(let e of this._isDirent?n:await Promise.all(n)){if(!e)continue;if(this.destroyed)return;let i=this._getEntryType(e);"string"!=typeof i&&(i=await i),"directory"===i&&this._directoryFilter(e)?(r<=this._maxDepth&&this.parents.push({path:e.fullPath,depth:r+1}),this._wantsDir&&(this.push(e),t--)):("file"===i||this._includeAsFile(e))&&this._fileFilter(e)&&this._wantsFile&&(this.push(e),t--)}}else{let t=this.parents.pop();if(!t){this.push(null);break}let e=t.pending??this._exploreDir(t.path,t.depth),i=this.parents[this.parents.length-1];if(i&&!i.pending&&(i.pending=this._exploreDir(i.path,i.depth)),this.parent=await e,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(t,e){let i;try{i=await (0,d.readdir)(t,this._rdOptions)}catch(t){this._onError(t)}return{files:i,depth:e,path:t}}_formatEntry(t,e){let i=this._isDirent?t.name:t,s=(0,c.join)(e,i),r={path:s.slice(this._relStart),fullPath:s,basename:i};return this._isDirent?(r.dirent=t,r):this._stat(s).then(t=>(r.stats=t,r),t=>{this._onError(t)})}_onError(t){E(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}_getEntryType(t){if(!t||!(this._statsProp in t))return"";let e=t[this._statsProp];return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?this._getSymlinkEntryType(t):""}async _getSymlinkEntryType(t){let e=t.fullPath;try{let t=await (0,d.realpath)(e),i=await (0,d.lstat)(t);if(i.isFile())return"file";if(i.isDirectory()){let i=t.length;if(e.startsWith(t)&&e[i]===c.sep){let i=Error(`Circular symlink detected: "${e}" points to "${t}"`);return i.code=_,this._onError(i),""}return"directory"}}catch(t){this._onError(t)}return""}_includeAsFile(t){let e=t&&t[this._statsProp];return e&&this._wantsEverything&&!e.isDirectory()}}var R=i(612);let x=()=>{},I=process.platform,T="win32"===I,k="darwin"===I,F="linux"===I,W="freebsd"===I,A="OS400"===(0,R.type)(),S={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},C={lstat:d.lstat,stat:d.stat},N="listeners",j="errHandlers",z="rawEmitters",M=[N,j,z],L=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),O=t=>L.has(c.extname(t).slice(1).toLowerCase()),H=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},q=(t,e,i)=>{let s=t[e];s instanceof Set||(t[e]=s=new Set([s])),s.add(i)},Y=t=>e=>{let i=t[e];i instanceof Set?i.clear():delete t[e]},U=(t,e,i)=>{let s=t[e];s instanceof Set?s.delete(i):s===i&&delete t[e]},G=t=>t instanceof Set?0===t.size:!t,$=new Map;function V(t,e,i,s,r){try{return(0,l.watch)(t,{persistent:e.persistent},(e,s)=>{i(t),r(e,s,{watchedPath:t}),s&&t!==s&&K(c.resolve(t,s),N,c.join(t,s))})}catch(t){s(t);return}}let K=(t,e,i,s,r)=>{let n=$.get(t);n&&H(n[e],t=>{t(i,s,r)})},X=(t,e,i,s)=>{let r;let{listener:n,errHandler:a,rawEmitter:o}=s,h=$.get(e);if(!i.persistent){if(!(r=V(t,i,n,a,o)))return;return r.close.bind(r)}if(h)q(h,N,n),q(h,j,a),q(h,z,o);else{if(!(r=V(t,i,K.bind(null,e,N),a,K.bind(null,e,z))))return;r.on(S.ERROR,async i=>{let s=K.bind(null,e,j);if(h&&(h.watcherUnusable=!0),T&&"EPERM"===i.code)try{let e=await (0,d.open)(t,"r");await e.close(),s(i)}catch(t){}else s(i)}),h={listeners:n,errHandlers:a,rawEmitters:o,watcher:r},$.set(e,h)}return()=>{U(h,N,n),U(h,j,a),U(h,z,o),G(h.listeners)&&(h.watcher.close(),$.delete(e),M.forEach(Y(h)),h.watcher=void 0,Object.freeze(h))}},B=new Map,J=(t,e,i,s)=>{let{listener:r,rawEmitter:n}=s,a=B.get(e),o=a&&a.options;return o&&(o.persistent<i.persistent||o.interval>i.interval)&&((0,l.unwatchFile)(e),a=void 0),a?(q(a,N,r),q(a,z,n)):(a={listeners:r,rawEmitters:n,options:i,watcher:(0,l.watchFile)(e,i,(i,s)=>{H(a.rawEmitters,t=>{t(S.CHANGE,e,{curr:i,prev:s})});let r=i.mtimeMs;(i.size!==s.size||r>s.mtimeMs||0===r)&&H(a.listeners,e=>e(t,i))})},B.set(e,a)),()=>{U(a,N,r),U(a,z,n),G(a.listeners)&&(B.delete(e),(0,l.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}};class Q{fsw;_boundHandleError;constructor(t){this.fsw=t,this._boundHandleError=e=>t._handleError(e)}_watchWithNodeFs(t,e){let i;let s=this.fsw.options,r=c.dirname(t),n=c.basename(t);this.fsw._getWatchedDir(r).add(n);let a=c.resolve(t),o={persistent:s.persistent};if(e||(e=x),s.usePolling){let r=s.interval!==s.binaryInterval;o.interval=r&&O(n)?s.binaryInterval:s.interval,i=J(t,a,o,{listener:e,rawEmitter:this.fsw._emitRaw})}else i=X(t,a,o,{listener:e,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return i}_handleFile(t,e,i){if(this.fsw.closed)return;let s=c.dirname(t),r=c.basename(t),n=this.fsw._getWatchedDir(s),a=e;if(n.has(r))return;let o=async(e,i)=>{if(this.fsw._throttle("watch",t,5)){if(i&&0!==i.mtimeMs){if(n.has(r)){let e=i.atimeMs,s=i.mtimeMs;(!e||e<=s||s!==a.mtimeMs)&&this.fsw._emit(S.CHANGE,t,i),a=i}}else try{let i=await (0,d.stat)(t);if(this.fsw.closed)return;let s=i.atimeMs,r=i.mtimeMs;if((!s||s<=r||r!==a.mtimeMs)&&this.fsw._emit(S.CHANGE,t,i),(k||F||W)&&a.ino!==i.ino){this.fsw._closeFile(e),a=i;let s=this._watchWithNodeFs(t,o);s&&this.fsw._addPathCloser(e,s)}else a=i}catch(t){this.fsw._remove(s,r)}}},h=this._watchWithNodeFs(t,o);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(S.ADD,t,0))return;this.fsw._emit(S.ADD,t,e)}return h}async _handleSymlink(t,e,i,s){if(this.fsw.closed)return;let r=t.fullPath,n=this.fsw._getWatchedDir(e);if(!this.fsw.options.followSymlinks){let e;this.fsw._incrReadyCount();try{e=await (0,d.realpath)(i)}catch(t){return this.fsw._emitReady(),!0}if(this.fsw.closed)return;return n.has(s)?this.fsw._symlinkPaths.get(r)!==e&&(this.fsw._symlinkPaths.set(r,e),this.fsw._emit(S.CHANGE,i,t.stats)):(n.add(s),this.fsw._symlinkPaths.set(r,e),this.fsw._emit(S.ADD,i,t.stats)),this.fsw._emitReady(),!0}if(this.fsw._symlinkPaths.has(r))return!0;this.fsw._symlinkPaths.set(r,!0)}_handleRead(t,e,i,s,r,n,a){t=c.join(t,"");let o=s?`${t}:${s}`:t;if(!(a=this.fsw._throttle("readdir",o,1e3)))return;let h=this.fsw._getWatchedDir(i.path),l=new Set,d=this.fsw._readdirp(t,{fileFilter:t=>i.filterPath(t),directoryFilter:t=>i.filterDir(t)});if(d)return d.on("data",async a=>{if(this.fsw.closed){d=void 0;return}let o=a.path,p=c.join(t,o);if(l.add(o),!(a.stats.isSymbolicLink()&&await this._handleSymlink(a,t,p,o))){if(this.fsw.closed){d=void 0;return}o!==s&&(s||h.has(o))||(this.fsw._incrReadyCount(),p=c.join(r,c.relative(r,p)),this._addToNodeFs(p,e,i,n+1))}}).on(S.ERROR,this._boundHandleError),new Promise((e,o)=>{if(!d)return o();d.once("end",()=>{if(this.fsw.closed){d=void 0;return}let o=!!a&&a.clear();e(void 0),h.getChildren().filter(e=>e!==t&&!l.has(e)).forEach(e=>{this.fsw._remove(t,e)}),d=void 0,o&&this._handleRead(t,!1,i,s,r,n,a)})})}async _handleDir(t,e,i,s,r,n,a){let o,h;let l=this.fsw._getWatchedDir(c.dirname(t)),d=l.has(c.basename(t));i&&this.fsw.options.ignoreInitial||r||d||this.fsw._emit(S.ADD_DIR,t,e),l.add(c.basename(t)),this.fsw._getWatchedDir(t);let p=this.fsw.options.depth;if((null==p||s<=p)&&!this.fsw._symlinkPaths.has(a)){if(!r&&(await this._handleRead(t,i,n,r,t,s,o),this.fsw.closed))return;h=this._watchWithNodeFs(t,(e,i)=>{i&&0===i.mtimeMs||this._handleRead(e,!1,n,r,t,s,o)})}return h}async _addToNodeFs(t,e,i,s,r){let n=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return n(),!1;let a=this.fsw._getWatchHelpers(t);i&&(a.filterPath=t=>i.filterPath(t),a.filterDir=t=>i.filterDir(t));try{let i;let o=await C[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,o))return n(),!1;let h=this.fsw.options.followSymlinks;if(o.isDirectory()){let n=c.resolve(t),l=h?await (0,d.realpath)(t):t;if(this.fsw.closed||(i=await this._handleDir(a.watchPath,o,e,s,r,a,l),this.fsw.closed))return;n!==l&&void 0!==l&&this.fsw._symlinkPaths.set(n,l)}else if(o.isSymbolicLink()){let r=h?await (0,d.realpath)(t):t;if(this.fsw.closed)return;let n=c.dirname(a.watchPath);if(this.fsw._getWatchedDir(n).add(a.watchPath),this.fsw._emit(S.ADD,a.watchPath,o),i=await this._handleDir(n,o,e,s,t,a,r),this.fsw.closed)return;void 0!==r&&this.fsw._symlinkPaths.set(c.resolve(t),r)}else i=this._handleFile(a.watchPath,o,e);return n(),i&&this.fsw._addPathCloser(t,i),!1}catch(e){if(this.fsw._handleError(e))return n(),t}}}let Z=/\\/g,tt=/\/\//g,te=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,ti=/^\.[/\\]/;function ts(t){return Array.isArray(t)?t:[t]}let tr=t=>"object"==typeof t&&null!==t&&!(t instanceof RegExp);function tn(t,e,i){let s=function(t){if("string"!=typeof t)throw Error("string expected");t=(t=c.normalize(t)).replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(tt,"/"),e&&(t="/"+t),t}(e);for(let e=0;e<t.length;e++)if((0,t[e])(s,i))return!0;return!1}let ta=t=>{let e=ts(t).flat();if(!e.every(t=>"string"==typeof t))throw TypeError(`Non-string provided as watch path: ${e}`);return e.map(th)},to=t=>{let e=t.replace(Z,"/"),i=!1;return e.startsWith("//")&&(i=!0),e=e.replace(tt,"/"),i&&(e="/"+e),e},th=t=>to(c.normalize(to(t))),tl=(t="")=>e=>"string"==typeof e?th(c.isAbsolute(e)?e:c.join(t,e)):e,td=(t,e)=>c.isAbsolute(t)?t:c.join(e,t),tc=Object.freeze(new Set);class tp{path;_removeWatcher;items;constructor(t,e){this.path=t,this._removeWatcher=e,this.items=new Set}add(t){let{items:e}=this;e&&"."!==t&&".."!==t&&e.add(t)}async remove(t){let{items:e}=this;if(!e||(e.delete(t),e.size>0))return;let i=this.path;try{await (0,d.readdir)(i)}catch(t){this._removeWatcher&&this._removeWatcher(c.dirname(i),c.basename(i))}}has(t){let{items:e}=this;if(e)return e.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=x,this.items=tc,Object.freeze(this)}}class tu{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(t,e,i){this.fsw=i;let s=t;this.path=t=t.replace(ti,""),this.watchPath=s,this.fullWatchPath=c.resolve(s),this.dirParts=[],this.dirParts.forEach(t=>{t.length>1&&t.pop()}),this.followSymlinks=e,this.statMethod=e?"stat":"lstat"}entryPath(t){return c.join(this.watchPath,c.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:e}=t;if(e&&e.isSymbolicLink())return this.filterDir(t);let i=this.entryPath(t);return this.fsw._isntIgnored(i,e)&&this.fsw._hasReadPermissions(e)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}}class tf extends h.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let e=t.awaitWriteFinish,i={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?ts(t.ignored):ts([]),awaitWriteFinish:!0===e?i:"object"==typeof e&&{...i,...e}};A&&(s.usePolling=!0),void 0===s.atomic&&(s.atomic=!s.usePolling);let r=process.env.CHOKIDAR_USEPOLLING;if(void 0!==r){let t=r.toLowerCase();"false"===t||"0"===t?s.usePolling=!1:"true"===t||"1"===t?s.usePolling=!0:s.usePolling=!!t}let n=process.env.CHOKIDAR_INTERVAL;n&&(s.interval=Number.parseInt(n,10));let a=0;this._emitReady=()=>{++a>=this._readyCount&&(this._emitReady=x,this._readyEmitted=!0,process.nextTick(()=>this.emit(S.READY)))},this._emitRaw=(...t)=>this.emit(S.RAW,...t),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new Q(this),Object.freeze(s)}_addIgnoredPath(t){if(tr(t)){for(let e of this._ignoredPaths)if(tr(e)&&e.path===t.path&&e.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),"string"==typeof t)for(let e of this._ignoredPaths)tr(e)&&e.path===t&&this._ignoredPaths.delete(e)}add(t,e,i){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let r=ta(t);return s&&(r=r.map(t=>td(t,s))),r.forEach(t=>{this._removeIgnoredPath(t)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=r.length,Promise.all(r.map(async t=>{let s=await this._nodeFsHandler._addToNodeFs(t,!i,void 0,0,e);return s&&this._emitReady(),s})).then(t=>{this.closed||t.forEach(t=>{t&&this.add(c.dirname(t),c.basename(e||t))})}),this}unwatch(t){if(this.closed)return this;let e=ta(t),{cwd:i}=this.options;return e.forEach(t=>{c.isAbsolute(t)||this._closers.has(t)||(i&&(t=c.join(i,t)),t=c.resolve(t)),this._closePath(t),this._addIgnoredPath(t),this._watched.has(t)&&this._addIgnoredPath({path:t,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(e=>e.forEach(e=>{let i=e();i instanceof Promise&&t.push(i)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((e,i)=>{t[(this.options.cwd?c.relative(this.options.cwd,i):i)||"."]=e.getChildren().sort()}),t}emitWithAll(t,e){this.emit(t,...e),t!==S.ERROR&&this.emit(S.ALL,t,...e)}async _emit(t,e,i){let s;if(this.closed)return;let r=this.options;T&&(e=c.normalize(e)),r.cwd&&(e=c.relative(r.cwd,e));let n=[e];null!=i&&n.push(i);let a=r.awaitWriteFinish;if(a&&(s=this._pendingWrites.get(e)))return s.lastChange=new Date,this;if(r.atomic){if(t===S.UNLINK)return this._pendingUnlinks.set(e,[t,...n]),setTimeout(()=>{this._pendingUnlinks.forEach((t,e)=>{this.emit(...t),this.emit(S.ALL,...t),this._pendingUnlinks.delete(e)})},"number"==typeof r.atomic?r.atomic:100),this;t===S.ADD&&this._pendingUnlinks.has(e)&&(t=S.CHANGE,this._pendingUnlinks.delete(e))}if(a&&(t===S.ADD||t===S.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(e,a.stabilityThreshold,t,(e,i)=>{e?(t=S.ERROR,n[0]=e,this.emitWithAll(t,n)):i&&(n.length>1?n[1]=i:n.push(i),this.emitWithAll(t,n))}),this;if(t===S.CHANGE&&!this._throttle(S.CHANGE,e,50))return this;if(r.alwaysStat&&void 0===i&&(t===S.ADD||t===S.ADD_DIR||t===S.CHANGE)){let t;let i=r.cwd?c.join(r.cwd,e):e;try{t=await (0,d.stat)(i)}catch(t){}if(!t||this.closed)return;n.push(t)}return this.emitWithAll(t,n),this}_handleError(t){let e=t&&t.code;return t&&"ENOENT"!==e&&"ENOTDIR"!==e&&(!this.options.ignorePermissionErrors||"EPERM"!==e&&"EACCES"!==e)&&this.emit(S.ERROR,t),t||this.closed}_throttle(t,e,i){let s;this._throttled.has(t)||this._throttled.set(t,new Map);let r=this._throttled.get(t);if(!r)throw Error("invalid throttle");let n=r.get(e);if(n)return n.count++,!1;let a=()=>{let t=r.get(e),i=t?t.count:0;return r.delete(e),clearTimeout(s),t&&clearTimeout(t.timeoutObject),i},o={timeoutObject:s=setTimeout(a,i),clear:a,count:0};return r.set(e,o),o}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,e,i,s){let r;let n=this.options.awaitWriteFinish;if("object"!=typeof n)return;let a=n.pollInterval,o=t;this.options.cwd&&!c.isAbsolute(t)&&(o=c.join(this.options.cwd,t));let h=new Date,d=this._pendingWrites;d.has(t)||(d.set(t,{lastChange:h,cancelWait:()=>(d.delete(t),clearTimeout(r),i)}),r=setTimeout(function i(n){(0,l.stat)(o,(o,h)=>{if(o||!d.has(t)){o&&"ENOENT"!==o.code&&s(o);return}let l=Number(new Date);n&&h.size!==n.size&&(d.get(t).lastChange=l),l-d.get(t).lastChange>=e?(d.delete(t),s(void 0,h)):r=setTimeout(i,a,h)})},a))}_isIgnored(t,e){if(this.options.atomic&&te.test(t))return!0;if(!this._userIgnored){let{cwd:t}=this.options,e=(this.options.ignored||[]).map(tl(t)),i=[...[...this._ignoredPaths].map(tl(t)),...e];this._userIgnored=function(t,e){if(null==t)throw TypeError("anymatch: specify first argument");let i=ts(t).map(t=>"function"==typeof t?t:"string"==typeof t?e=>t===e:t instanceof RegExp?e=>t.test(e):"object"==typeof t&&null!==t?e=>{if(t.path===e)return!0;if(t.recursive){let i=c.relative(t.path,e);return!!i&&!i.startsWith("..")&&!c.isAbsolute(i)}return!1}:()=>!1);return null==e?(t,e)=>tn(i,t,e):tn(i,e)}(i,void 0)}return this._userIgnored(t,e)}_isntIgnored(t,e){return!this._isIgnored(t,e)}_getWatchHelpers(t){return new tu(t,this.options.followSymlinks,this)}_getWatchedDir(t){let e=c.resolve(t);return this._watched.has(e)||this._watched.set(e,new tp(e,this._boundRemove)),this._watched.get(e)}_hasReadPermissions(t){return!!this.options.ignorePermissionErrors||!!(256&Number(t.mode))}_remove(t,e,i){let s=c.join(t,e),r=c.resolve(s);if(i=null!=i?i:this._watched.has(s)||this._watched.has(r),!this._throttle("remove",s,100))return;i||1!==this._watched.size||this.add(t,e,!0),this._getWatchedDir(s).getChildren().forEach(t=>this._remove(s,t));let n=this._getWatchedDir(t),a=n.has(e);n.remove(e),this._symlinkPaths.has(r)&&this._symlinkPaths.delete(r);let o=s;if(this.options.cwd&&(o=c.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(o)&&this._pendingWrites.get(o).cancelWait()===S.ADD)return;this._watched.delete(s),this._watched.delete(r);let h=i?S.UNLINK_DIR:S.UNLINK;a&&!this._isIgnored(s)&&this._emit(h,s),this._closePath(s)}_closePath(t){this._closeFile(t);let e=c.dirname(t);this._getWatchedDir(e).remove(c.basename(t))}_closeFile(t){let e=this._closers.get(t);e&&(e.forEach(t=>t()),this._closers.delete(t))}_addPathCloser(t,e){if(!e)return;let i=this._closers.get(t);i||(i=[],this._closers.set(t,i)),i.push(e)}_readdirp(t,e){if(this.closed)return;let i=function(t,e={}){let i=e.entryType||e.type;if("both"===i&&(i=u.FILE_DIR_TYPE),t){if("string"!=typeof t)throw TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(i&&!w.includes(i))throw Error(`readdirp: Invalid type passed. Use one of ${w.join(", ")}`)}else throw Error("readdirp: root argument is required. Usage: readdirp(root, options)");let s={...e,root:t};return i&&(s.type=i),new D(s)}(t,{type:S.ALL,alwaysStat:!0,lstat:!0,...e,depth:0});return this._streams.add(i),i.once("close",()=>{i=void 0}),i.once("end",()=>{i&&(this._streams.delete(i),i=void 0)}),i}}let t_=t=>(function(t,e={}){let i=new tf(e);return i.add(t),i})(t,{ignoreInitial:!0,persistent:!0});class tm{constructor(t=t_,e=150){this.watchFile=t,this.debounceMs=e,this.entries=new Map}subscribe(t,e,i){let s=`${t}\0${e}`,r=this.entries.get(s);if(!r){let t=this.watchFile(e);r={watcher:t,subscribers:new Set,revision:0,debounceTimer:null},t.on("add",()=>this.schedule(r)),t.on("change",()=>this.schedule(r)),this.entries.set(s,r)}r.subscribers.add(i);let n=!0;return()=>{if(!n)return;n=!1;let t=this.entries.get(s);t&&(t.subscribers.delete(i),0===t.subscribers.size&&this.releaseEntry(s,t))}}async dispose(){let t=[...this.entries.entries()];this.entries.clear(),await Promise.all(t.map(async([,t])=>{t.debounceTimer&&clearTimeout(t.debounceTimer),await t.watcher.close()}))}schedule(t){t.debounceTimer&&clearTimeout(t.debounceTimer),t.debounceTimer=setTimeout(()=>{t.debounceTimer=null,t.revision+=1;let e={type:"session_history_changed",revision:t.revision};for(let i of t.subscribers)try{i(e)}catch{}},this.debounceMs)}releaseEntry(t,e){this.entries.get(t)===e&&this.entries.delete(t),e.debounceTimer&&clearTimeout(e.debounceTimer),e.debounceTimer=null,e.watcher.close()}}let tw=globalThis,tg="force-dynamic",ty="nodejs",tE=new TextEncoder;async function tv(t,{params:e}){if(!(0,o.V_)(e.id))return Response.json({error:"Native session not found"},{status:404});try{let i=await (0,o.NL)().getSessionWatchPath(e.id);if(!i)return Response.json({error:"Native session transcript is unavailable"},{status:404});let s=()=>void 0,r=new ReadableStream({start(r){let n=!1,a=(tw.__nativeSessionChangeMonitor||(tw.__nativeSessionChangeMonitor=new tm),tw.__nativeSessionChangeMonitor).subscribe(e.id,i,t=>{n||r.enqueue(tE.encode(`data: ${JSON.stringify(t)}
|
|
1
|
+
"use strict";(()=>{var t={};t.id=917,t.ids=[917],t.modules={7728:t=>{t.exports=require("@anthropic-ai/claude-agent-sdk")},5890:t=>{t.exports=require("better-sqlite3")},399:t=>{t.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},517:t=>{t.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},9801:t=>{t.exports=require("os")},7718:t=>{t.exports=require("node:child_process")},6005:t=>{t.exports=require("node:crypto")},5673:t=>{t.exports=require("node:events")},7561:t=>{t.exports=require("node:fs")},3977:t=>{t.exports=require("node:fs/promises")},8849:t=>{t.exports=require("node:http")},2286:t=>{t.exports=require("node:https")},7503:t=>{t.exports=require("node:net")},612:t=>{t.exports=require("node:os")},9411:t=>{t.exports=require("node:path")},1747:t=>{t.exports=require("node:readline")},1041:t=>{t.exports=require("node:url")},5881:t=>{t.exports=require("node:util")},7428:(t,e,i)=>{i.r(e),i.d(e,{originalPathname:()=>tx,patchFetch:()=>tI,requestAsyncStorage:()=>tP,routeModule:()=>tb,serverHooks:()=>tR,staticGenerationAsyncStorage:()=>tD});var s={};i.r(s),i.d(s,{GET:()=>tv,dynamic:()=>tg,runtime:()=>ty});var r=i(7786),n=i(5042),a=i(2184),o=i(3988),h=i(5673),l=i(7561),d=i(3977),c=i(9411);let p=require("node:stream"),u={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},f={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:u.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(f);let _="READDIRP_RECURSIVE_ERROR",m=new Set(["ENOENT","EPERM","EACCES","ELOOP",_]),w=[u.DIR_TYPE,u.EVERYTHING_TYPE,u.FILE_DIR_TYPE,u.FILE_TYPE],g=new Set([u.DIR_TYPE,u.EVERYTHING_TYPE,u.FILE_DIR_TYPE]),y=new Set([u.EVERYTHING_TYPE,u.FILE_DIR_TYPE,u.FILE_TYPE]),E=t=>m.has(t.code),v="win32"===process.platform,b=t=>!0,P=t=>{if(void 0===t)return b;if("function"==typeof t)return t;if("string"==typeof t){let e=t.trim();return t=>t.basename===e}if(Array.isArray(t)){let e=t.map(t=>t.trim());return t=>e.some(e=>t.basename===e)}return b};class D extends p.Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark??f.highWaterMark});let e={...f,...t},i=e.root??f.root,s=e.type??f.type;this._fileFilter=P(e.fileFilter),this._directoryFilter=P(e.directoryFilter);let r=e.lstat?d.lstat:d.stat;v?this._stat=t=>r(t,{bigint:!0}):this._stat=r,this._maxDepth=null!=e.depth&&Number.isSafeInteger(e.depth)?e.depth:f.depth,this._wantsDir=g.has(s),this._wantsFile=y.has(s),this._wantsEverything=s===u.EVERYTHING_TYPE,this._root=(0,c.resolve)(i),this._relStart=this._root.endsWith(c.sep)?this._root.length:this._root.length+1,this._isDirent=!e.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let n={path:this._root,depth:1};n.pending=this._exploreDir(this._root,1),this.parents=[n],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let e=this.parent,i=e&&e.files;if(i&&i.length>0){let{path:s,depth:r}=e,n=i.splice(0,t).map(t=>this._formatEntry(t,s));for(let e of this._isDirent?n:await Promise.all(n)){if(!e)continue;if(this.destroyed)return;let i=this._getEntryType(e);"string"!=typeof i&&(i=await i),"directory"===i&&this._directoryFilter(e)?(r<=this._maxDepth&&this.parents.push({path:e.fullPath,depth:r+1}),this._wantsDir&&(this.push(e),t--)):("file"===i||this._includeAsFile(e))&&this._fileFilter(e)&&this._wantsFile&&(this.push(e),t--)}}else{let t=this.parents.pop();if(!t){this.push(null);break}let e=t.pending??this._exploreDir(t.path,t.depth),i=this.parents[this.parents.length-1];if(i&&!i.pending&&(i.pending=this._exploreDir(i.path,i.depth)),this.parent=await e,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(t,e){let i;try{i=await (0,d.readdir)(t,this._rdOptions)}catch(t){this._onError(t)}return{files:i,depth:e,path:t}}_formatEntry(t,e){let i=this._isDirent?t.name:t,s=(0,c.join)(e,i),r={path:s.slice(this._relStart),fullPath:s,basename:i};return this._isDirent?(r.dirent=t,r):this._stat(s).then(t=>(r.stats=t,r),t=>{this._onError(t)})}_onError(t){E(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}_getEntryType(t){if(!t||!(this._statsProp in t))return"";let e=t[this._statsProp];return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?this._getSymlinkEntryType(t):""}async _getSymlinkEntryType(t){let e=t.fullPath;try{let t=await (0,d.realpath)(e),i=await (0,d.lstat)(t);if(i.isFile())return"file";if(i.isDirectory()){let i=t.length;if(e.startsWith(t)&&e[i]===c.sep){let i=Error(`Circular symlink detected: "${e}" points to "${t}"`);return i.code=_,this._onError(i),""}return"directory"}}catch(t){this._onError(t)}return""}_includeAsFile(t){let e=t&&t[this._statsProp];return e&&this._wantsEverything&&!e.isDirectory()}}var R=i(612);let x=()=>{},I=process.platform,T="win32"===I,k="darwin"===I,F="linux"===I,W="freebsd"===I,A="OS400"===(0,R.type)(),S={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},C={lstat:d.lstat,stat:d.stat},N="listeners",j="errHandlers",z="rawEmitters",M=[N,j,z],L=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),O=t=>L.has(c.extname(t).slice(1).toLowerCase()),H=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},q=(t,e,i)=>{let s=t[e];s instanceof Set||(t[e]=s=new Set([s])),s.add(i)},Y=t=>e=>{let i=t[e];i instanceof Set?i.clear():delete t[e]},U=(t,e,i)=>{let s=t[e];s instanceof Set?s.delete(i):s===i&&delete t[e]},G=t=>t instanceof Set?0===t.size:!t,$=new Map;function V(t,e,i,s,r){try{return(0,l.watch)(t,{persistent:e.persistent},(e,s)=>{i(t),r(e,s,{watchedPath:t}),s&&t!==s&&K(c.resolve(t,s),N,c.join(t,s))})}catch(t){s(t);return}}let K=(t,e,i,s,r)=>{let n=$.get(t);n&&H(n[e],t=>{t(i,s,r)})},X=(t,e,i,s)=>{let r;let{listener:n,errHandler:a,rawEmitter:o}=s,h=$.get(e);if(!i.persistent){if(!(r=V(t,i,n,a,o)))return;return r.close.bind(r)}if(h)q(h,N,n),q(h,j,a),q(h,z,o);else{if(!(r=V(t,i,K.bind(null,e,N),a,K.bind(null,e,z))))return;r.on(S.ERROR,async i=>{let s=K.bind(null,e,j);if(h&&(h.watcherUnusable=!0),T&&"EPERM"===i.code)try{let e=await (0,d.open)(t,"r");await e.close(),s(i)}catch(t){}else s(i)}),h={listeners:n,errHandlers:a,rawEmitters:o,watcher:r},$.set(e,h)}return()=>{U(h,N,n),U(h,j,a),U(h,z,o),G(h.listeners)&&(h.watcher.close(),$.delete(e),M.forEach(Y(h)),h.watcher=void 0,Object.freeze(h))}},B=new Map,J=(t,e,i,s)=>{let{listener:r,rawEmitter:n}=s,a=B.get(e),o=a&&a.options;return o&&(o.persistent<i.persistent||o.interval>i.interval)&&((0,l.unwatchFile)(e),a=void 0),a?(q(a,N,r),q(a,z,n)):(a={listeners:r,rawEmitters:n,options:i,watcher:(0,l.watchFile)(e,i,(i,s)=>{H(a.rawEmitters,t=>{t(S.CHANGE,e,{curr:i,prev:s})});let r=i.mtimeMs;(i.size!==s.size||r>s.mtimeMs||0===r)&&H(a.listeners,e=>e(t,i))})},B.set(e,a)),()=>{U(a,N,r),U(a,z,n),G(a.listeners)&&(B.delete(e),(0,l.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}};class Q{fsw;_boundHandleError;constructor(t){this.fsw=t,this._boundHandleError=e=>t._handleError(e)}_watchWithNodeFs(t,e){let i;let s=this.fsw.options,r=c.dirname(t),n=c.basename(t);this.fsw._getWatchedDir(r).add(n);let a=c.resolve(t),o={persistent:s.persistent};if(e||(e=x),s.usePolling){let r=s.interval!==s.binaryInterval;o.interval=r&&O(n)?s.binaryInterval:s.interval,i=J(t,a,o,{listener:e,rawEmitter:this.fsw._emitRaw})}else i=X(t,a,o,{listener:e,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return i}_handleFile(t,e,i){if(this.fsw.closed)return;let s=c.dirname(t),r=c.basename(t),n=this.fsw._getWatchedDir(s),a=e;if(n.has(r))return;let o=async(e,i)=>{if(this.fsw._throttle("watch",t,5)){if(i&&0!==i.mtimeMs){if(n.has(r)){let e=i.atimeMs,s=i.mtimeMs;(!e||e<=s||s!==a.mtimeMs)&&this.fsw._emit(S.CHANGE,t,i),a=i}}else try{let i=await (0,d.stat)(t);if(this.fsw.closed)return;let s=i.atimeMs,r=i.mtimeMs;if((!s||s<=r||r!==a.mtimeMs)&&this.fsw._emit(S.CHANGE,t,i),(k||F||W)&&a.ino!==i.ino){this.fsw._closeFile(e),a=i;let s=this._watchWithNodeFs(t,o);s&&this.fsw._addPathCloser(e,s)}else a=i}catch(t){this.fsw._remove(s,r)}}},h=this._watchWithNodeFs(t,o);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(S.ADD,t,0))return;this.fsw._emit(S.ADD,t,e)}return h}async _handleSymlink(t,e,i,s){if(this.fsw.closed)return;let r=t.fullPath,n=this.fsw._getWatchedDir(e);if(!this.fsw.options.followSymlinks){let e;this.fsw._incrReadyCount();try{e=await (0,d.realpath)(i)}catch(t){return this.fsw._emitReady(),!0}if(this.fsw.closed)return;return n.has(s)?this.fsw._symlinkPaths.get(r)!==e&&(this.fsw._symlinkPaths.set(r,e),this.fsw._emit(S.CHANGE,i,t.stats)):(n.add(s),this.fsw._symlinkPaths.set(r,e),this.fsw._emit(S.ADD,i,t.stats)),this.fsw._emitReady(),!0}if(this.fsw._symlinkPaths.has(r))return!0;this.fsw._symlinkPaths.set(r,!0)}_handleRead(t,e,i,s,r,n,a){t=c.join(t,"");let o=s?`${t}:${s}`:t;if(!(a=this.fsw._throttle("readdir",o,1e3)))return;let h=this.fsw._getWatchedDir(i.path),l=new Set,d=this.fsw._readdirp(t,{fileFilter:t=>i.filterPath(t),directoryFilter:t=>i.filterDir(t)});if(d)return d.on("data",async a=>{if(this.fsw.closed){d=void 0;return}let o=a.path,p=c.join(t,o);if(l.add(o),!(a.stats.isSymbolicLink()&&await this._handleSymlink(a,t,p,o))){if(this.fsw.closed){d=void 0;return}o!==s&&(s||h.has(o))||(this.fsw._incrReadyCount(),p=c.join(r,c.relative(r,p)),this._addToNodeFs(p,e,i,n+1))}}).on(S.ERROR,this._boundHandleError),new Promise((e,o)=>{if(!d)return o();d.once("end",()=>{if(this.fsw.closed){d=void 0;return}let o=!!a&&a.clear();e(void 0),h.getChildren().filter(e=>e!==t&&!l.has(e)).forEach(e=>{this.fsw._remove(t,e)}),d=void 0,o&&this._handleRead(t,!1,i,s,r,n,a)})})}async _handleDir(t,e,i,s,r,n,a){let o,h;let l=this.fsw._getWatchedDir(c.dirname(t)),d=l.has(c.basename(t));i&&this.fsw.options.ignoreInitial||r||d||this.fsw._emit(S.ADD_DIR,t,e),l.add(c.basename(t)),this.fsw._getWatchedDir(t);let p=this.fsw.options.depth;if((null==p||s<=p)&&!this.fsw._symlinkPaths.has(a)){if(!r&&(await this._handleRead(t,i,n,r,t,s,o),this.fsw.closed))return;h=this._watchWithNodeFs(t,(e,i)=>{i&&0===i.mtimeMs||this._handleRead(e,!1,n,r,t,s,o)})}return h}async _addToNodeFs(t,e,i,s,r){let n=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return n(),!1;let a=this.fsw._getWatchHelpers(t);i&&(a.filterPath=t=>i.filterPath(t),a.filterDir=t=>i.filterDir(t));try{let i;let o=await C[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,o))return n(),!1;let h=this.fsw.options.followSymlinks;if(o.isDirectory()){let n=c.resolve(t),l=h?await (0,d.realpath)(t):t;if(this.fsw.closed||(i=await this._handleDir(a.watchPath,o,e,s,r,a,l),this.fsw.closed))return;n!==l&&void 0!==l&&this.fsw._symlinkPaths.set(n,l)}else if(o.isSymbolicLink()){let r=h?await (0,d.realpath)(t):t;if(this.fsw.closed)return;let n=c.dirname(a.watchPath);if(this.fsw._getWatchedDir(n).add(a.watchPath),this.fsw._emit(S.ADD,a.watchPath,o),i=await this._handleDir(n,o,e,s,t,a,r),this.fsw.closed)return;void 0!==r&&this.fsw._symlinkPaths.set(c.resolve(t),r)}else i=this._handleFile(a.watchPath,o,e);return n(),i&&this.fsw._addPathCloser(t,i),!1}catch(e){if(this.fsw._handleError(e))return n(),t}}}let Z=/\\/g,tt=/\/\//g,te=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,ti=/^\.[/\\]/;function ts(t){return Array.isArray(t)?t:[t]}let tr=t=>"object"==typeof t&&null!==t&&!(t instanceof RegExp);function tn(t,e,i){let s=function(t){if("string"!=typeof t)throw Error("string expected");t=(t=c.normalize(t)).replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(tt,"/"),e&&(t="/"+t),t}(e);for(let e=0;e<t.length;e++)if((0,t[e])(s,i))return!0;return!1}let ta=t=>{let e=ts(t).flat();if(!e.every(t=>"string"==typeof t))throw TypeError(`Non-string provided as watch path: ${e}`);return e.map(th)},to=t=>{let e=t.replace(Z,"/"),i=!1;return e.startsWith("//")&&(i=!0),e=e.replace(tt,"/"),i&&(e="/"+e),e},th=t=>to(c.normalize(to(t))),tl=(t="")=>e=>"string"==typeof e?th(c.isAbsolute(e)?e:c.join(t,e)):e,td=(t,e)=>c.isAbsolute(t)?t:c.join(e,t),tc=Object.freeze(new Set);class tp{path;_removeWatcher;items;constructor(t,e){this.path=t,this._removeWatcher=e,this.items=new Set}add(t){let{items:e}=this;e&&"."!==t&&".."!==t&&e.add(t)}async remove(t){let{items:e}=this;if(!e||(e.delete(t),e.size>0))return;let i=this.path;try{await (0,d.readdir)(i)}catch(t){this._removeWatcher&&this._removeWatcher(c.dirname(i),c.basename(i))}}has(t){let{items:e}=this;if(e)return e.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=x,this.items=tc,Object.freeze(this)}}class tu{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(t,e,i){this.fsw=i;let s=t;this.path=t=t.replace(ti,""),this.watchPath=s,this.fullWatchPath=c.resolve(s),this.dirParts=[],this.dirParts.forEach(t=>{t.length>1&&t.pop()}),this.followSymlinks=e,this.statMethod=e?"stat":"lstat"}entryPath(t){return c.join(this.watchPath,c.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:e}=t;if(e&&e.isSymbolicLink())return this.filterDir(t);let i=this.entryPath(t);return this.fsw._isntIgnored(i,e)&&this.fsw._hasReadPermissions(e)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}}class tf extends h.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let e=t.awaitWriteFinish,i={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?ts(t.ignored):ts([]),awaitWriteFinish:!0===e?i:"object"==typeof e&&{...i,...e}};A&&(s.usePolling=!0),void 0===s.atomic&&(s.atomic=!s.usePolling);let r=process.env.CHOKIDAR_USEPOLLING;if(void 0!==r){let t=r.toLowerCase();"false"===t||"0"===t?s.usePolling=!1:"true"===t||"1"===t?s.usePolling=!0:s.usePolling=!!t}let n=process.env.CHOKIDAR_INTERVAL;n&&(s.interval=Number.parseInt(n,10));let a=0;this._emitReady=()=>{++a>=this._readyCount&&(this._emitReady=x,this._readyEmitted=!0,process.nextTick(()=>this.emit(S.READY)))},this._emitRaw=(...t)=>this.emit(S.RAW,...t),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new Q(this),Object.freeze(s)}_addIgnoredPath(t){if(tr(t)){for(let e of this._ignoredPaths)if(tr(e)&&e.path===t.path&&e.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),"string"==typeof t)for(let e of this._ignoredPaths)tr(e)&&e.path===t&&this._ignoredPaths.delete(e)}add(t,e,i){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let r=ta(t);return s&&(r=r.map(t=>td(t,s))),r.forEach(t=>{this._removeIgnoredPath(t)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=r.length,Promise.all(r.map(async t=>{let s=await this._nodeFsHandler._addToNodeFs(t,!i,void 0,0,e);return s&&this._emitReady(),s})).then(t=>{this.closed||t.forEach(t=>{t&&this.add(c.dirname(t),c.basename(e||t))})}),this}unwatch(t){if(this.closed)return this;let e=ta(t),{cwd:i}=this.options;return e.forEach(t=>{c.isAbsolute(t)||this._closers.has(t)||(i&&(t=c.join(i,t)),t=c.resolve(t)),this._closePath(t),this._addIgnoredPath(t),this._watched.has(t)&&this._addIgnoredPath({path:t,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(e=>e.forEach(e=>{let i=e();i instanceof Promise&&t.push(i)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((e,i)=>{t[(this.options.cwd?c.relative(this.options.cwd,i):i)||"."]=e.getChildren().sort()}),t}emitWithAll(t,e){this.emit(t,...e),t!==S.ERROR&&this.emit(S.ALL,t,...e)}async _emit(t,e,i){let s;if(this.closed)return;let r=this.options;T&&(e=c.normalize(e)),r.cwd&&(e=c.relative(r.cwd,e));let n=[e];null!=i&&n.push(i);let a=r.awaitWriteFinish;if(a&&(s=this._pendingWrites.get(e)))return s.lastChange=new Date,this;if(r.atomic){if(t===S.UNLINK)return this._pendingUnlinks.set(e,[t,...n]),setTimeout(()=>{this._pendingUnlinks.forEach((t,e)=>{this.emit(...t),this.emit(S.ALL,...t),this._pendingUnlinks.delete(e)})},"number"==typeof r.atomic?r.atomic:100),this;t===S.ADD&&this._pendingUnlinks.has(e)&&(t=S.CHANGE,this._pendingUnlinks.delete(e))}if(a&&(t===S.ADD||t===S.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(e,a.stabilityThreshold,t,(e,i)=>{e?(t=S.ERROR,n[0]=e,this.emitWithAll(t,n)):i&&(n.length>1?n[1]=i:n.push(i),this.emitWithAll(t,n))}),this;if(t===S.CHANGE&&!this._throttle(S.CHANGE,e,50))return this;if(r.alwaysStat&&void 0===i&&(t===S.ADD||t===S.ADD_DIR||t===S.CHANGE)){let t;let i=r.cwd?c.join(r.cwd,e):e;try{t=await (0,d.stat)(i)}catch(t){}if(!t||this.closed)return;n.push(t)}return this.emitWithAll(t,n),this}_handleError(t){let e=t&&t.code;return t&&"ENOENT"!==e&&"ENOTDIR"!==e&&(!this.options.ignorePermissionErrors||"EPERM"!==e&&"EACCES"!==e)&&this.emit(S.ERROR,t),t||this.closed}_throttle(t,e,i){let s;this._throttled.has(t)||this._throttled.set(t,new Map);let r=this._throttled.get(t);if(!r)throw Error("invalid throttle");let n=r.get(e);if(n)return n.count++,!1;let a=()=>{let t=r.get(e),i=t?t.count:0;return r.delete(e),clearTimeout(s),t&&clearTimeout(t.timeoutObject),i},o={timeoutObject:s=setTimeout(a,i),clear:a,count:0};return r.set(e,o),o}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,e,i,s){let r;let n=this.options.awaitWriteFinish;if("object"!=typeof n)return;let a=n.pollInterval,o=t;this.options.cwd&&!c.isAbsolute(t)&&(o=c.join(this.options.cwd,t));let h=new Date,d=this._pendingWrites;d.has(t)||(d.set(t,{lastChange:h,cancelWait:()=>(d.delete(t),clearTimeout(r),i)}),r=setTimeout(function i(n){(0,l.stat)(o,(o,h)=>{if(o||!d.has(t)){o&&"ENOENT"!==o.code&&s(o);return}let l=Number(new Date);n&&h.size!==n.size&&(d.get(t).lastChange=l),l-d.get(t).lastChange>=e?(d.delete(t),s(void 0,h)):r=setTimeout(i,a,h)})},a))}_isIgnored(t,e){if(this.options.atomic&&te.test(t))return!0;if(!this._userIgnored){let{cwd:t}=this.options,e=(this.options.ignored||[]).map(tl(t)),i=[...[...this._ignoredPaths].map(tl(t)),...e];this._userIgnored=function(t,e){if(null==t)throw TypeError("anymatch: specify first argument");let i=ts(t).map(t=>"function"==typeof t?t:"string"==typeof t?e=>t===e:t instanceof RegExp?e=>t.test(e):"object"==typeof t&&null!==t?e=>{if(t.path===e)return!0;if(t.recursive){let i=c.relative(t.path,e);return!!i&&!i.startsWith("..")&&!c.isAbsolute(i)}return!1}:()=>!1);return null==e?(t,e)=>tn(i,t,e):tn(i,e)}(i,void 0)}return this._userIgnored(t,e)}_isntIgnored(t,e){return!this._isIgnored(t,e)}_getWatchHelpers(t){return new tu(t,this.options.followSymlinks,this)}_getWatchedDir(t){let e=c.resolve(t);return this._watched.has(e)||this._watched.set(e,new tp(e,this._boundRemove)),this._watched.get(e)}_hasReadPermissions(t){return!!this.options.ignorePermissionErrors||!!(256&Number(t.mode))}_remove(t,e,i){let s=c.join(t,e),r=c.resolve(s);if(i=null!=i?i:this._watched.has(s)||this._watched.has(r),!this._throttle("remove",s,100))return;i||1!==this._watched.size||this.add(t,e,!0),this._getWatchedDir(s).getChildren().forEach(t=>this._remove(s,t));let n=this._getWatchedDir(t),a=n.has(e);n.remove(e),this._symlinkPaths.has(r)&&this._symlinkPaths.delete(r);let o=s;if(this.options.cwd&&(o=c.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(o)&&this._pendingWrites.get(o).cancelWait()===S.ADD)return;this._watched.delete(s),this._watched.delete(r);let h=i?S.UNLINK_DIR:S.UNLINK;a&&!this._isIgnored(s)&&this._emit(h,s),this._closePath(s)}_closePath(t){this._closeFile(t);let e=c.dirname(t);this._getWatchedDir(e).remove(c.basename(t))}_closeFile(t){let e=this._closers.get(t);e&&(e.forEach(t=>t()),this._closers.delete(t))}_addPathCloser(t,e){if(!e)return;let i=this._closers.get(t);i||(i=[],this._closers.set(t,i)),i.push(e)}_readdirp(t,e){if(this.closed)return;let i=function(t,e={}){let i=e.entryType||e.type;if("both"===i&&(i=u.FILE_DIR_TYPE),t){if("string"!=typeof t)throw TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(i&&!w.includes(i))throw Error(`readdirp: Invalid type passed. Use one of ${w.join(", ")}`)}else throw Error("readdirp: root argument is required. Usage: readdirp(root, options)");let s={...e,root:t};return i&&(s.type=i),new D(s)}(t,{type:S.ALL,alwaysStat:!0,lstat:!0,...e,depth:0});return this._streams.add(i),i.once("close",()=>{i=void 0}),i.once("end",()=>{i&&(this._streams.delete(i),i=void 0)}),i}}let t_=t=>(function(t,e={}){let i=new tf(e);return i.add(t),i})(t,{ignoreInitial:!0,persistent:!0});class tm{constructor(t=t_,e=150){this.watchFile=t,this.debounceMs=e,this.entries=new Map}subscribe(t,e,i){let s=`${t}\0${e}`,r=this.entries.get(s);if(!r){let t=this.watchFile(e);r={watcher:t,subscribers:new Set,revision:0,debounceTimer:null},t.on("add",()=>this.schedule(r)),t.on("change",()=>this.schedule(r)),this.entries.set(s,r)}r.subscribers.add(i);let n=!0;return()=>{if(!n)return;n=!1;let t=this.entries.get(s);t&&(t.subscribers.delete(i),0===t.subscribers.size&&this.releaseEntry(s,t))}}async dispose(){let t=[...this.entries.entries()];this.entries.clear(),await Promise.all(t.map(async([,t])=>{t.debounceTimer&&clearTimeout(t.debounceTimer),await t.watcher.close()}))}schedule(t){t.debounceTimer&&clearTimeout(t.debounceTimer),t.debounceTimer=setTimeout(()=>{t.debounceTimer=null,t.revision+=1;let e={type:"session_history_changed",revision:t.revision};for(let i of t.subscribers)try{i(e)}catch{}},this.debounceMs)}releaseEntry(t,e){this.entries.get(t)===e&&this.entries.delete(t),e.debounceTimer&&clearTimeout(e.debounceTimer),e.debounceTimer=null,e.watcher.close()}}let tw=globalThis,tg="force-dynamic",ty="nodejs",tE=new TextEncoder;async function tv(t,{params:e}){if(!(0,o.V_)(e.id))return Response.json({error:"Native session not found"},{status:404});try{let i=await (0,o.NL)().getSessionWatchPath(e.id);if(!i)return Response.json({error:"Native session transcript is unavailable"},{status:404});let s=()=>void 0,r=new ReadableStream({start(r){let n=!1,a=(tw.__nativeSessionChangeMonitor||(tw.__nativeSessionChangeMonitor=new tm),tw.__nativeSessionChangeMonitor).subscribe(e.id,i,t=>{n||r.enqueue(tE.encode(`data: ${JSON.stringify(t)}
|
|
2
2
|
|
|
3
|
-
`))}),o=setInterval(()=>{n||r.enqueue(tE.encode(": keep-alive\n\n"))},15e3);s=()=>{n||(n=!0,clearInterval(o),a(),t.signal.removeEventListener("abort",s))},t.signal.addEventListener("abort",s,{once:!0}),r.enqueue(tE.encode(": connected\n\n"))},cancel(){s()}});return new Response(r,{headers:{"Cache-Control":"no-cache, no-transform",Connection:"keep-alive","Content-Type":"text/event-stream; charset=utf-8","X-Accel-Buffering":"no"}})}catch(t){return Response.json({error:t instanceof Error?t.message:"Internal error"},{status:(0,o.WW)(t)})}}let tb=new r.AppRouteRouteModule({definition:{kind:n.x.APP_ROUTE,page:"/api/sessions/[id]/changes/route",pathname:"/api/sessions/[id]/changes",filename:"route",bundlePath:"app/api/sessions/[id]/changes/route"},resolvedPagePath:"/Users/caoqu/team-agent/customer-agent/packages/server/app/api/sessions/[id]/changes/route.ts",nextConfigOutput:"standalone",userland:s}),{requestAsyncStorage:tP,staticGenerationAsyncStorage:tD,serverHooks:tR}=tb,tx="/api/sessions/[id]/changes/route";function tI(){return(0,a.patchFetch)({serverHooks:tR,staticGenerationAsyncStorage:tD})}},7786:(t,e,i)=>{t.exports=i(517)}};var e=require("../../../../../webpack-runtime.js");e.C(t);var i=t=>e(e.s=t),s=e.X(0,[375,322,
|
|
3
|
+
`))}),o=setInterval(()=>{n||r.enqueue(tE.encode(": keep-alive\n\n"))},15e3);s=()=>{n||(n=!0,clearInterval(o),a(),t.signal.removeEventListener("abort",s))},t.signal.addEventListener("abort",s,{once:!0}),r.enqueue(tE.encode(": connected\n\n"))},cancel(){s()}});return new Response(r,{headers:{"Cache-Control":"no-cache, no-transform",Connection:"keep-alive","Content-Type":"text/event-stream; charset=utf-8","X-Accel-Buffering":"no"}})}catch(t){return Response.json({error:t instanceof Error?t.message:"Internal error"},{status:(0,o.WW)(t)})}}let tb=new r.AppRouteRouteModule({definition:{kind:n.x.APP_ROUTE,page:"/api/sessions/[id]/changes/route",pathname:"/api/sessions/[id]/changes",filename:"route",bundlePath:"app/api/sessions/[id]/changes/route"},resolvedPagePath:"/Users/caoqu/team-agent/customer-agent/packages/server/app/api/sessions/[id]/changes/route.ts",nextConfigOutput:"standalone",userland:s}),{requestAsyncStorage:tP,staticGenerationAsyncStorage:tD,serverHooks:tR}=tb,tx="/api/sessions/[id]/changes/route";function tI(){return(0,a.patchFetch)({serverHooks:tR,staticGenerationAsyncStorage:tD})}},7786:(t,e,i)=>{t.exports=i(517)}};var e=require("../../../../../webpack-runtime.js");e.C(t);var i=t=>e(e.s=t),s=e.X(0,[375,322,988],()=>i(7428));module.exports=s})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":1,"files":["../../../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../../../node_modules/better-sqlite3","../../../../../../../node_modules/next","../../../../../../../package.json","../../../../../../package.json","../../../../../chunks/322.js","../../../../../chunks/375.js","../../../../../chunks/
|
|
1
|
+
{"version":1,"files":["../../../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../../../node_modules/better-sqlite3","../../../../../../../node_modules/next","../../../../../../../package.json","../../../../../../package.json","../../../../../chunks/322.js","../../../../../chunks/375.js","../../../../../chunks/988.js","../../../../../webpack-runtime.js"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var e={};e.id=939,e.ids=[939],e.modules={7728:e=>{e.exports=require("@anthropic-ai/claude-agent-sdk")},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")},7503:e=>{e.exports=require("node:net")},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")},5881:e=>{e.exports=require("node:util")},8207:(e,r,t)=>{t.r(r),t.d(r,{originalPathname:()=>l,patchFetch:()=>f,requestAsyncStorage:()=>x,routeModule:()=>d,serverHooks:()=>q,staticGenerationAsyncStorage:()=>c});var s={};t.r(s),t.d(s,{POST:()=>u});var o=t(7786),i=t(5042),n=t(2184),a=t(1890),p=t(
|
|
1
|
+
"use strict";(()=>{var e={};e.id=939,e.ids=[939],e.modules={7728:e=>{e.exports=require("@anthropic-ai/claude-agent-sdk")},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")},7503:e=>{e.exports=require("node:net")},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")},5881:e=>{e.exports=require("node:util")},8207:(e,r,t)=>{t.r(r),t.d(r,{originalPathname:()=>l,patchFetch:()=>f,requestAsyncStorage:()=>x,routeModule:()=>d,serverHooks:()=>q,staticGenerationAsyncStorage:()=>c});var s={};t.r(s),t.d(s,{POST:()=>u});var o=t(7786),i=t(5042),n=t(2184),a=t(1890),p=t(3988);async function u(e,{params:r}){try{let e=await (0,p.NL)().fork(r.id);return a.NextResponse.json(e,{status:201})}catch(e){return a.NextResponse.json({error:e instanceof Error?e.message:"Internal error"},{status:(0,p.WW)(e)})}}let d=new o.AppRouteRouteModule({definition:{kind:i.x.APP_ROUTE,page:"/api/sessions/[id]/fork/route",pathname:"/api/sessions/[id]/fork",filename:"route",bundlePath:"app/api/sessions/[id]/fork/route"},resolvedPagePath:"/Users/caoqu/team-agent/customer-agent/packages/server/app/api/sessions/[id]/fork/route.ts",nextConfigOutput:"standalone",userland:s}),{requestAsyncStorage:x,staticGenerationAsyncStorage:c,serverHooks:q}=d,l="/api/sessions/[id]/fork/route";function f(){return(0,n.patchFetch)({serverHooks:q,staticGenerationAsyncStorage:c})}}};var r=require("../../../../../webpack-runtime.js");r.C(e);var t=e=>r(r.s=e),s=r.X(0,[375,703,322,988],()=>t(8207));module.exports=s})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":1,"files":["../../../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../../../node_modules/better-sqlite3","../../../../../../../node_modules/next","../../../../../../../package.json","../../../../../../package.json","../../../../../chunks/322.js","../../../../../chunks/375.js","../../../../../chunks/703.js","../../../../../chunks/
|
|
1
|
+
{"version":1,"files":["../../../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../../../node_modules/better-sqlite3","../../../../../../../node_modules/next","../../../../../../../package.json","../../../../../../package.json","../../../../../chunks/322.js","../../../../../chunks/375.js","../../../../../chunks/703.js","../../../../../chunks/988.js","../../../../../webpack-runtime.js"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var e={};e.id=719,e.ids=[719],e.modules={7728:e=>{e.exports=require("@anthropic-ai/claude-agent-sdk")},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")},7503:e=>{e.exports=require("node:net")},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")},5881:e=>{e.exports=require("node:util")},6466:(e,r,s)=>{s.r(r),s.d(r,{originalPathname:()=>h,patchFetch:()=>l,requestAsyncStorage:()=>x,routeModule:()=>u,serverHooks:()=>f,staticGenerationAsyncStorage:()=>c});var t={};s.r(t),s.d(t,{POST:()=>d});var o=s(7786),n=s(5042),i=s(2184),a=s(1890),p=s(
|
|
1
|
+
"use strict";(()=>{var e={};e.id=719,e.ids=[719],e.modules={7728:e=>{e.exports=require("@anthropic-ai/claude-agent-sdk")},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")},7503:e=>{e.exports=require("node:net")},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")},5881:e=>{e.exports=require("node:util")},6466:(e,r,s)=>{s.r(r),s.d(r,{originalPathname:()=>h,patchFetch:()=>l,requestAsyncStorage:()=>x,routeModule:()=>u,serverHooks:()=>f,staticGenerationAsyncStorage:()=>c});var t={};s.r(t),s.d(t,{POST:()=>d});var o=s(7786),n=s(5042),i=s(2184),a=s(1890),p=s(3988);async function d(e,{params:r}){if(!(0,p.V_)(r.id))return a.NextResponse.json({error:"Only native sessions can be handed off"},{status:405});try{let e=await (0,p.NL)().handoff(r.id,"desktop");return a.NextResponse.json(e)}catch(e){return a.NextResponse.json({error:e instanceof Error?e.message:"Native handoff failed"},{status:(0,p.WW)(e)})}}let u=new o.AppRouteRouteModule({definition:{kind:n.x.APP_ROUTE,page:"/api/sessions/[id]/handoff/route",pathname:"/api/sessions/[id]/handoff",filename:"route",bundlePath:"app/api/sessions/[id]/handoff/route"},resolvedPagePath:"/Users/caoqu/team-agent/customer-agent/packages/server/app/api/sessions/[id]/handoff/route.ts",nextConfigOutput:"standalone",userland:t}),{requestAsyncStorage:x,staticGenerationAsyncStorage:c,serverHooks:f}=u,h="/api/sessions/[id]/handoff/route";function l(){return(0,i.patchFetch)({serverHooks:f,staticGenerationAsyncStorage:c})}}};var r=require("../../../../../webpack-runtime.js");r.C(e);var s=e=>r(r.s=e),t=r.X(0,[375,703,322,988],()=>s(6466));module.exports=t})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":1,"files":["../../../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../../../node_modules/better-sqlite3","../../../../../../../node_modules/next","../../../../../../../package.json","../../../../../../package.json","../../../../../chunks/322.js","../../../../../chunks/375.js","../../../../../chunks/703.js","../../../../../chunks/
|
|
1
|
+
{"version":1,"files":["../../../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../../../node_modules/better-sqlite3","../../../../../../../node_modules/next","../../../../../../../package.json","../../../../../../package.json","../../../../../chunks/322.js","../../../../../chunks/375.js","../../../../../chunks/703.js","../../../../../chunks/988.js","../../../../../webpack-runtime.js"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";(()=>{var e={};e.id=241,e.ids=[241],e.modules={7728:e=>{e.exports=require("@anthropic-ai/claude-agent-sdk")},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")},7503:e=>{e.exports=require("node:net")},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")},5881:e=>{e.exports=require("node:util")},9564:(e,t,s)=>{s.r(t),s.d(t,{originalPathname:()=>S,patchFetch:()=>v,requestAsyncStorage:()=>g,routeModule:()=>m,serverHooks:()=>w,staticGenerationAsyncStorage:()=>f});var o={};s.r(o),s.d(o,{DELETE:()=>p,GET:()=>c,PATCH:()=>h});var r=s(7786),i=s(5042),n=s(2184),a=s(1890),l=s(1322),u=s(7186),d=s(
|
|
1
|
+
"use strict";(()=>{var e={};e.id=241,e.ids=[241],e.modules={7728:e=>{e.exports=require("@anthropic-ai/claude-agent-sdk")},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")},7503:e=>{e.exports=require("node:net")},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")},5881:e=>{e.exports=require("node:util")},9564:(e,t,s)=>{s.r(t),s.d(t,{originalPathname:()=>S,patchFetch:()=>v,requestAsyncStorage:()=>g,routeModule:()=>m,serverHooks:()=>w,staticGenerationAsyncStorage:()=>f});var o={};s.r(o),s.d(o,{DELETE:()=>p,GET:()=>c,PATCH:()=>h});var r=s(7786),i=s(5042),n=s(2184),a=s(1890),l=s(1322),u=s(7186),d=s(3988);async function c(e,{params:t}){let s=new URL(e.url),o=s.searchParams.get("before"),r=s.searchParams.get("limit"),i=null!==o||null!==r?{before:o||void 0,limit:function(e){if(null===e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}(r)}:void 0;if((0,d.V_)(t.id))try{let e=await (0,d.NL)().get(t.id,i);return a.NextResponse.json(e)}catch(e){return a.NextResponse.json({error:e instanceof Error?e.message:"Internal error"},{status:(0,d.WW)(e)})}let n=await u.f.getSessionStore().get(t.id);if(!n)return a.NextResponse.json({error:"Session not found"},{status:404});let c=!n.messages?.length&&Array.isArray(n.events)&&n.events.length>0?function(e){let t=[],s=null;for(let o of e){let e=o.type;if("text_chunk"===e){s||(s={id:crypto.randomUUID(),role:"assistant",content:"",isStreaming:!0,timestamp:Date.now()},t.push(s)),s.content=`${s.content??""}${o.text??""}`;continue}if("tool_call"===e&&o.toolCall){s={id:crypto.randomUUID(),role:"assistant",content:s?.content??"",toolCalls:[o.toolCall],isStreaming:!1,timestamp:Date.now()},t.push(s),s=null;continue}if("tool_result"===e&&o.result){let e=o.result;t.push({id:crypto.randomUUID(),role:"tool",content:e.content??"",toolCallId:e.toolCallId,timestamp:Date.now()});continue}if("ask_user"===e){t.push({id:crypto.randomUUID(),role:"assistant",content:"",askUser:{questionId:o.questionId,question:o.question??"",options:o.options,multiSelect:o.multiSelect},timestamp:Date.now()});continue}"done"===e&&"string"==typeof o.finalText&&(s?(s.content=o.finalText,s.isStreaming=!1):o.finalText.trim()&&t.push({id:crypto.randomUUID(),role:"assistant",content:o.finalText,timestamp:Date.now()}),s=null)}return t}(n.events):n.messages,h=i?{...n,permissionMode:(0,l.Ny)(n.metadata.permissionMode),...(0,l.MO)(c??[],n.events??[],i)}:{...n,messages:c,permissionMode:(0,l.Ny)(n.metadata.permissionMode)};return a.NextResponse.json(h)}async function h(e,{params:t}){let s=await e.json();if(!(0,l.ue)(s.permissionMode))return a.NextResponse.json({error:"Invalid permission mode"},{status:400});if((0,d.V_)(t.id))try{let e=await (0,d.NL)().setPermissionMode(t.id,s.permissionMode);return a.NextResponse.json(e)}catch(e){return a.NextResponse.json({error:e instanceof Error?e.message:"Unable to update permission mode"},{status:(0,d.WW)(e)})}try{let e=await u.f.setSessionPermissionMode(t.id,s.permissionMode);return a.NextResponse.json({...e,permissionMode:(0,l.Ny)(e.metadata.permissionMode)})}catch(s){let e=s instanceof Error?s.message:"Unable to update permission mode",t=e.startsWith("Session not found")?404:500;return a.NextResponse.json({error:e},{status:t})}}async function p(e,{params:t}){return(0,d.V_)(t.id)?a.NextResponse.json({error:"External runtime sessions cannot be deleted"},{status:405}):(await u.f.getSessionStore().delete(t.id),a.NextResponse.json({status:"deleted"}))}let m=new r.AppRouteRouteModule({definition:{kind:i.x.APP_ROUTE,page:"/api/sessions/[id]/route",pathname:"/api/sessions/[id]",filename:"route",bundlePath:"app/api/sessions/[id]/route"},resolvedPagePath:"/Users/caoqu/team-agent/customer-agent/packages/server/app/api/sessions/[id]/route.ts",nextConfigOutput:"standalone",userland:o}),{requestAsyncStorage:g,staticGenerationAsyncStorage:f,serverHooks:w}=m,S="/api/sessions/[id]/route";function v(){return(0,n.patchFetch)({serverHooks:w,staticGenerationAsyncStorage:f})}},7186:(e,t,s)=>{s.d(t,{B:()=>n,f:()=>u});var o=s(1322),r=s(612),i=s(785);class n extends Error{constructor(e,t,s){super(e),this.code=t,this.status=s,this.name="ProjectWorkingDirectoryError"}}class a{constructor(){this.baseDir=(0,i.kO)(),this.workingDirectory=(0,i.sr)(),this.builder=null,this.sessionStore=new o.m6(this.baseDir),this.projectStore=new o.XW(this.baseDir),this.remoteToolStore=new o.rt((0,o.N8)(this.baseDir).db),this.defaultRemoteToolsProjectId=process.env.AGENT_PROJECT_ID??"default",this.activeRun=null,this.activeAgent=null,this.activeRunSessionId=null,this.subscribers=new Map,this.recentEvents=new Map,this.eventCounters=new Map,this.pendingQuestions=new Map,this.toolPermissionGate=new o.XP({resolveMode:async e=>{let t=await this.sessionStore.get(e);return(0,o.Ny)(t?.metadata.permissionMode)},requestApproval:async e=>{let t=await this.createQuestion({question:`Customer Agent 请求权限
|
|
2
2
|
${e.summary}
|
|
3
|
-
原因:${e.reason}`,options:[...o.Sf],toolCallId:""},e.sessionId);return(0,o.wM)(t.answer,t.selectedIndices)}});let e=process.env.AGENT_API_KEY,t=process.env.AGENT_MODEL_PROVIDER||"openai",s=process.env.AGENT_MODEL_ID||"gpt-4o",r=process.env.AGENT_BASE_URL||void 0,n=new o.Y4().withSessionStore(this.sessionStore).withWorkingDirectory(this.workingDirectory).withToolPermissionGate(this.toolPermissionGate);n.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e&&n.withModel(t,{apiKey:e,modelId:s,baseUrl:r}),this.builder=n}getBuilder(){return this.builder||(this.builder=new o.Y4().withToolPermissionGate(this.toolPermissionGate)),this.builder}setBuilder(e){e.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e.withWorkingDirectory(this.workingDirectory),e.withToolPermissionGate(this.toolPermissionGate),this.builder=e}getSessionStore(){return this.sessionStore}getProjectStore(){return this.projectStore}async resolveProjectWorkingDirectory(e,t=!1){if(!e)return this.workingDirectory;let s=await this.projectStore.get(e);if(!s)throw new n("项目不存在","PROJECT_NOT_FOUND",404);if(!s.description?.trim()){if(!t)return this.workingDirectory;throw new n("该项目没有宿主机目录","PROJECT_PATH_REQUIRED",400)}try{return o.Tp.fromEnvironment(process.env.AGENT_WEB_ROOTS,(0,r.homedir)()).assertDirectory(s.description)}catch(e){throw new n(e instanceof Error?e.message:"项目目录不可用","PROJECT_PATH_INVALID",400)}}getModelConfig(){return{provider:process.env.AGENT_MODEL_PROVIDER||"openai",modelId:process.env.AGENT_MODEL_ID||"gpt-4o",baseUrl:process.env.AGENT_BASE_URL||""}}getWebAppBuildId(){return globalThis.__webAppBuildId??""}registerRemoteTools(e,t){return this.remoteToolStore.upsertTools(e,t)}getRemoteToolStore(){return this.remoteToolStore}async createSession(e,t=""){let s=new Date().toISOString();return t&&!await this.projectStore.get(t)&&await this.projectStore.create({id:t,name:t,description:"",created:s,updated:s}),this.sessionStore.create({id:crypto.randomUUID(),projectId:t,title:e,status:"idle",messages:[],events:[],created:s,updated:s,metadata:{permissionMode:"full-access"}})}async setSessionPermissionMode(e,t){if(!(0,o.ue)(t))throw Error(`Invalid permission mode: ${String(t)}`);let s=await this.sessionStore.get(e);if(!s)throw Error(`Session not found: ${e}`);return this.toolPermissionGate.clearSession(e),this.sessionStore.update(e,{metadata:{...s.metadata,permissionMode:t}})}getLatestEventId(e){return this.eventCounters.get(e)??0}subscribe(e,t,s=-1){for(let o of this.recentEvents.get(e)??[])if(!(o.id<=s))try{t(o.event,o.id)}catch{}let o=this.subscribers.get(e)??new Set;return o.add(t),this.subscribers.set(e,o),()=>{o.delete(t),0===o.size&&this.subscribers.delete(e)}}emit(e,t){let s=(this.eventCounters.get(e)??0)+1;this.eventCounters.set(e,s);let o=this.recentEvents.get(e);for(let r of(o&&(o.push({id:s,event:t}),o.length>500&&o.splice(0,o.length-500)),this.subscribers.get(e)??[]))try{r(t,s)}catch{}}publishExternal(e,t){this.emit(e,t)}resetExternalStream(e){this.eventCounters.set(e,0),this.recentEvents.set(e,[])}projectMessagesFromEvents(e){let t=[],s=null;for(let o of e){if("text_chunk"===o.type){s||(s={role:"assistant",content:""},t.push(s)),s.content+=o.text;continue}if("tool_call"===o.type){s&&!s.toolCalls?s.toolCalls=[o.toolCall]:t.push({role:"assistant",content:"",toolCalls:[o.toolCall]}),s=null;continue}if("tool_result"===o.type){t.push({role:"tool",content:o.result.content,toolCallId:o.result.toolCallId});continue}if("ask_user"===o.type){t.push({role:"assistant",content:""}),s=null;continue}"done"===o.type&&(s?s.content=o.finalText||s.content:o.finalText?.trim()&&t.push({role:"assistant",content:o.finalText}),s=null)}return t}async run(e,t,s){let r;let i=await this.sessionStore.get(t),n=await this.resolveProjectWorkingDirectory(i?.projectId);await this.sessionStore.addMessage(t,{role:"user",content:e}),this.eventCounters.set(t,0),this.recentEvents.set(t,[]);let a=i?.projectId||this.defaultRemoteToolsProjectId;try{r=await this.getBuilder().withWorkingDirectory(n).withRemoteToolStore(this.remoteToolStore,a).withTool(new o.as(async e=>this.createQuestion(e,t))).build()}catch(s){let e={type:"error",message:s instanceof Error?s.message:"Failed to build agent"};try{await this.sessionStore.addEvent(t,e)}catch{}throw this.emit(t,e),s}finally{this.builder?.withWorkingDirectory(this.workingDirectory).withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId)}this.activeAgent=r,this.activeRunSessionId=t,this.activeRun=r.run(e,t,s);let l=!1;try{for await(let e of this.activeRun)await this.sessionStore.addEvent(t,e),"error"===e.type?(l=!0,await this.sessionStore.update(t,{status:"failed"})):"done"!==e.type||l||(e.finalText.trim()&&await this.sessionStore.addMessage(t,{role:"assistant",content:e.finalText}),await this.sessionStore.update(t,{status:"completed"})),this.emit(t,e)}catch(s){l=!0;let e={type:"error",message:s instanceof Error?s.message:"Agent run failed"};try{await this.sessionStore.addEvent(t,e),await this.sessionStore.update(t,{status:"failed"})}catch{}this.emit(t,e)}finally{this.activeRunSessionId===t&&(this.activeAgent=null,this.activeRunSessionId=null),this.activeRun=null}try{let e=await this.sessionStore.get(t),s=(e?.messages??[]).filter(e=>"user"===e.role),o=this.projectMessagesFromEvents(e?.events??[]);await this.sessionStore.replaceMessages(t,[...s,...o])}catch{}}createQuestion(e,t){let s=crypto.randomUUID();return this.emit(t,{type:"ask_user",questionId:s,question:e.question,options:e.options,multiSelect:e.multiSelect}),new Promise((e,t)=>{let o=setTimeout(()=>{this.pendingQuestions.has(s)&&(this.pendingQuestions.delete(s),t(Error("Question timed out after 5 minutes")))},3e5);this.pendingQuestions.set(s,{resolve:e,reject:t,timer:o})})}answerQuestion(e,t,s){let o=this.pendingQuestions.get(e);return!!o&&(clearTimeout(o.timer),this.pendingQuestions.delete(e),o.resolve({answer:t,selectedIndices:s}),!0)}async steer(e,t){return await this.sessionStore.addMessage(t,{role:"user",content:e,name:"__steer__"}),this.activeRunSessionId===t&&!!this.activeAgent&&(this.emit(t,{type:"thinking",message:`User added: ${e.slice(0,60)}`}),!0)}abort(){for(let[e,t]of(this.activeAgent?.abort(),this.pendingQuestions))clearTimeout(t.timer),t.reject(Error("Agent aborted")),this.pendingQuestions.delete(e)}}let l=globalThis,u=l.__agentHost??new a;l.__agentHost=u}};var t=require("../../../../webpack-runtime.js");t.C(e);var s=e=>t(t.s=e),o=t.X(0,[375,703,322,
|
|
3
|
+
原因:${e.reason}`,options:[...o.Sf],toolCallId:""},e.sessionId);return(0,o.wM)(t.answer,t.selectedIndices)}});let e=process.env.AGENT_API_KEY,t=process.env.AGENT_MODEL_PROVIDER||"openai",s=process.env.AGENT_MODEL_ID||"gpt-4o",r=process.env.AGENT_BASE_URL||void 0,n=new o.Y4().withSessionStore(this.sessionStore).withWorkingDirectory(this.workingDirectory).withToolPermissionGate(this.toolPermissionGate);n.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e&&n.withModel(t,{apiKey:e,modelId:s,baseUrl:r}),this.builder=n}getBuilder(){return this.builder||(this.builder=new o.Y4().withToolPermissionGate(this.toolPermissionGate)),this.builder}setBuilder(e){e.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e.withWorkingDirectory(this.workingDirectory),e.withToolPermissionGate(this.toolPermissionGate),this.builder=e}getSessionStore(){return this.sessionStore}getProjectStore(){return this.projectStore}async resolveProjectWorkingDirectory(e,t=!1){if(!e)return this.workingDirectory;let s=await this.projectStore.get(e);if(!s)throw new n("项目不存在","PROJECT_NOT_FOUND",404);if(!s.description?.trim()){if(!t)return this.workingDirectory;throw new n("该项目没有宿主机目录","PROJECT_PATH_REQUIRED",400)}try{return o.Tp.fromEnvironment(process.env.AGENT_WEB_ROOTS,(0,r.homedir)()).assertDirectory(s.description)}catch(e){throw new n(e instanceof Error?e.message:"项目目录不可用","PROJECT_PATH_INVALID",400)}}getModelConfig(){return{provider:process.env.AGENT_MODEL_PROVIDER||"openai",modelId:process.env.AGENT_MODEL_ID||"gpt-4o",baseUrl:process.env.AGENT_BASE_URL||""}}getWebAppBuildId(){return globalThis.__webAppBuildId??""}registerRemoteTools(e,t){return this.remoteToolStore.upsertTools(e,t)}getRemoteToolStore(){return this.remoteToolStore}async createSession(e,t=""){let s=new Date().toISOString();return t&&!await this.projectStore.get(t)&&await this.projectStore.create({id:t,name:t,description:"",created:s,updated:s}),this.sessionStore.create({id:crypto.randomUUID(),projectId:t,title:e,status:"idle",messages:[],events:[],created:s,updated:s,metadata:{permissionMode:"full-access"}})}async setSessionPermissionMode(e,t){if(!(0,o.ue)(t))throw Error(`Invalid permission mode: ${String(t)}`);let s=await this.sessionStore.get(e);if(!s)throw Error(`Session not found: ${e}`);return this.toolPermissionGate.clearSession(e),this.sessionStore.update(e,{metadata:{...s.metadata,permissionMode:t}})}getLatestEventId(e){return this.eventCounters.get(e)??0}subscribe(e,t,s=-1){for(let o of this.recentEvents.get(e)??[])if(!(o.id<=s))try{t(o.event,o.id)}catch{}let o=this.subscribers.get(e)??new Set;return o.add(t),this.subscribers.set(e,o),()=>{o.delete(t),0===o.size&&this.subscribers.delete(e)}}emit(e,t){let s=(this.eventCounters.get(e)??0)+1;this.eventCounters.set(e,s);let o=this.recentEvents.get(e);for(let r of(o&&(o.push({id:s,event:t}),o.length>500&&o.splice(0,o.length-500)),this.subscribers.get(e)??[]))try{r(t,s)}catch{}}publishExternal(e,t){this.emit(e,t)}resetExternalStream(e){this.eventCounters.set(e,0),this.recentEvents.set(e,[])}projectMessagesFromEvents(e){let t=[],s=null;for(let o of e){if("text_chunk"===o.type){s||(s={role:"assistant",content:""},t.push(s)),s.content+=o.text;continue}if("tool_call"===o.type){s&&!s.toolCalls?s.toolCalls=[o.toolCall]:t.push({role:"assistant",content:"",toolCalls:[o.toolCall]}),s=null;continue}if("tool_result"===o.type){t.push({role:"tool",content:o.result.content,toolCallId:o.result.toolCallId});continue}if("ask_user"===o.type){t.push({role:"assistant",content:""}),s=null;continue}"done"===o.type&&(s?s.content=o.finalText||s.content:o.finalText?.trim()&&t.push({role:"assistant",content:o.finalText}),s=null)}return t}async run(e,t,s){let r;let i=await this.sessionStore.get(t),n=await this.resolveProjectWorkingDirectory(i?.projectId);await this.sessionStore.addMessage(t,{role:"user",content:e}),this.eventCounters.set(t,0),this.recentEvents.set(t,[]);let a=i?.projectId||this.defaultRemoteToolsProjectId;try{r=await this.getBuilder().withWorkingDirectory(n).withRemoteToolStore(this.remoteToolStore,a).withTool(new o.as(async e=>this.createQuestion(e,t))).build()}catch(s){let e={type:"error",message:s instanceof Error?s.message:"Failed to build agent"};try{await this.sessionStore.addEvent(t,e)}catch{}throw this.emit(t,e),s}finally{this.builder?.withWorkingDirectory(this.workingDirectory).withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId)}this.activeAgent=r,this.activeRunSessionId=t,this.activeRun=r.run(e,t,s);let l=!1;try{for await(let e of this.activeRun)await this.sessionStore.addEvent(t,e),"error"===e.type?(l=!0,await this.sessionStore.update(t,{status:"failed"})):"done"!==e.type||l||(e.finalText.trim()&&await this.sessionStore.addMessage(t,{role:"assistant",content:e.finalText}),await this.sessionStore.update(t,{status:"completed"})),this.emit(t,e)}catch(s){l=!0;let e={type:"error",message:s instanceof Error?s.message:"Agent run failed"};try{await this.sessionStore.addEvent(t,e),await this.sessionStore.update(t,{status:"failed"})}catch{}this.emit(t,e)}finally{this.activeRunSessionId===t&&(this.activeAgent=null,this.activeRunSessionId=null),this.activeRun=null}try{let e=await this.sessionStore.get(t),s=(e?.messages??[]).filter(e=>"user"===e.role),o=this.projectMessagesFromEvents(e?.events??[]);await this.sessionStore.replaceMessages(t,[...s,...o])}catch{}}createQuestion(e,t){let s=crypto.randomUUID();return this.emit(t,{type:"ask_user",questionId:s,question:e.question,options:e.options,multiSelect:e.multiSelect}),new Promise((e,t)=>{let o=setTimeout(()=>{this.pendingQuestions.has(s)&&(this.pendingQuestions.delete(s),t(Error("Question timed out after 5 minutes")))},3e5);this.pendingQuestions.set(s,{resolve:e,reject:t,timer:o})})}answerQuestion(e,t,s){let o=this.pendingQuestions.get(e);return!!o&&(clearTimeout(o.timer),this.pendingQuestions.delete(e),o.resolve({answer:t,selectedIndices:s}),!0)}async steer(e,t){return await this.sessionStore.addMessage(t,{role:"user",content:e,name:"__steer__"}),this.activeRunSessionId===t&&!!this.activeAgent&&(this.emit(t,{type:"thinking",message:`User added: ${e.slice(0,60)}`}),!0)}abort(){for(let[e,t]of(this.activeAgent?.abort(),this.pendingQuestions))clearTimeout(t.timer),t.reject(Error("Agent aborted")),this.pendingQuestions.delete(e)}}let l=globalThis,u=l.__agentHost??new a;l.__agentHost=u}};var t=require("../../../../webpack-runtime.js");t.C(e);var s=e=>t(t.s=e),o=t.X(0,[375,703,322,988],()=>s(9564));module.exports=o})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":1,"files":["../../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../../node_modules/better-sqlite3","../../../../../../node_modules/next","../../../../../../package.json","../../../../../package.json","../../../../chunks/322.js","../../../../chunks/375.js","../../../../chunks/703.js","../../../../chunks/
|
|
1
|
+
{"version":1,"files":["../../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../../node_modules/better-sqlite3","../../../../../../node_modules/next","../../../../../../package.json","../../../../../package.json","../../../../chunks/322.js","../../../../chunks/375.js","../../../../chunks/703.js","../../../../chunks/988.js","../../../../webpack-runtime.js"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";(()=>{var e={};e.id=772,e.ids=[772],e.modules={7728:e=>{e.exports=require("@anthropic-ai/claude-agent-sdk")},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")},7503:e=>{e.exports=require("node:net")},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")},5881:e=>{e.exports=require("node:util")},1880:(e,t,s)=>{s.r(t),s.d(t,{originalPathname:()=>v,patchFetch:()=>f,requestAsyncStorage:()=>m,routeModule:()=>p,serverHooks:()=>w,staticGenerationAsyncStorage:()=>g});var r={};s.r(r),s.d(r,{GET:()=>d,POST:()=>h});var o=s(7786),i=s(5042),n=s(2184),a=s(1890),l=s(1322),u=s(7186),c=s(
|
|
1
|
+
"use strict";(()=>{var e={};e.id=772,e.ids=[772],e.modules={7728:e=>{e.exports=require("@anthropic-ai/claude-agent-sdk")},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")},7503:e=>{e.exports=require("node:net")},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")},5881:e=>{e.exports=require("node:util")},1880:(e,t,s)=>{s.r(t),s.d(t,{originalPathname:()=>v,patchFetch:()=>f,requestAsyncStorage:()=>m,routeModule:()=>p,serverHooks:()=>w,staticGenerationAsyncStorage:()=>g});var r={};s.r(r),s.d(r,{GET:()=>d,POST:()=>h});var o=s(7786),i=s(5042),n=s(2184),a=s(1890),l=s(1322),u=s(7186),c=s(3988);async function d(e){let t=new URL(e.url),s=t.searchParams.get("projectId")||void 0,r="1"===t.searchParams.get("refresh"),o=await u.f.getSessionStore().list(s),i=(0,c.NL)(),n=o.map(({messages:e,events:t,...s})=>({...s,agentType:"customer-agent",canDelete:!0,permissionMode:(0,l.Ny)(s.metadata.permissionMode)}));try{let e=r?await i.refresh(s):await i.list(s);return a.NextResponse.json([...n,...e])}catch(e){return console.error("Native session discovery failed:",e),a.NextResponse.json(n)}}async function h(e){let t=await e.json(),s=t.agentType??"customer-agent";if("customer-agent"!==s)try{if(!t.projectId)throw new u.B("请选择宿主机项目","PROJECT_PATH_REQUIRED",400);let e=await u.f.resolveProjectWorkingDirectory(t.projectId,!0),r=await (0,c.NL)().create({agentType:s,title:t.title??"新会话",cwd:e});return a.NextResponse.json(r,{status:201})}catch(e){if(e instanceof u.B)return a.NextResponse.json({error:{code:e.code,message:e.message}},{status:e.status});return a.NextResponse.json({error:e instanceof Error?e.message:"Internal error"},{status:(0,c.WW)(e)})}let r=await u.f.createSession(t.title??"Untitled",t.projectId??"");return a.NextResponse.json(r,{status:201})}let p=new o.AppRouteRouteModule({definition:{kind:i.x.APP_ROUTE,page:"/api/sessions/route",pathname:"/api/sessions",filename:"route",bundlePath:"app/api/sessions/route"},resolvedPagePath:"/Users/caoqu/team-agent/customer-agent/packages/server/app/api/sessions/route.ts",nextConfigOutput:"standalone",userland:r}),{requestAsyncStorage:m,staticGenerationAsyncStorage:g,serverHooks:w}=p,v="/api/sessions/route";function f(){return(0,n.patchFetch)({serverHooks:w,staticGenerationAsyncStorage:g})}},7186:(e,t,s)=>{s.d(t,{B:()=>n,f:()=>u});var r=s(1322),o=s(612),i=s(785);class n extends Error{constructor(e,t,s){super(e),this.code=t,this.status=s,this.name="ProjectWorkingDirectoryError"}}class a{constructor(){this.baseDir=(0,i.kO)(),this.workingDirectory=(0,i.sr)(),this.builder=null,this.sessionStore=new r.m6(this.baseDir),this.projectStore=new r.XW(this.baseDir),this.remoteToolStore=new r.rt((0,r.N8)(this.baseDir).db),this.defaultRemoteToolsProjectId=process.env.AGENT_PROJECT_ID??"default",this.activeRun=null,this.activeAgent=null,this.activeRunSessionId=null,this.subscribers=new Map,this.recentEvents=new Map,this.eventCounters=new Map,this.pendingQuestions=new Map,this.toolPermissionGate=new r.XP({resolveMode:async e=>{let t=await this.sessionStore.get(e);return(0,r.Ny)(t?.metadata.permissionMode)},requestApproval:async e=>{let t=await this.createQuestion({question:`Customer Agent 请求权限
|
|
2
2
|
${e.summary}
|
|
3
|
-
原因:${e.reason}`,options:[...r.Sf],toolCallId:""},e.sessionId);return(0,r.wM)(t.answer,t.selectedIndices)}});let e=process.env.AGENT_API_KEY,t=process.env.AGENT_MODEL_PROVIDER||"openai",s=process.env.AGENT_MODEL_ID||"gpt-4o",o=process.env.AGENT_BASE_URL||void 0,n=new r.Y4().withSessionStore(this.sessionStore).withWorkingDirectory(this.workingDirectory).withToolPermissionGate(this.toolPermissionGate);n.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e&&n.withModel(t,{apiKey:e,modelId:s,baseUrl:o}),this.builder=n}getBuilder(){return this.builder||(this.builder=new r.Y4().withToolPermissionGate(this.toolPermissionGate)),this.builder}setBuilder(e){e.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e.withWorkingDirectory(this.workingDirectory),e.withToolPermissionGate(this.toolPermissionGate),this.builder=e}getSessionStore(){return this.sessionStore}getProjectStore(){return this.projectStore}async resolveProjectWorkingDirectory(e,t=!1){if(!e)return this.workingDirectory;let s=await this.projectStore.get(e);if(!s)throw new n("项目不存在","PROJECT_NOT_FOUND",404);if(!s.description?.trim()){if(!t)return this.workingDirectory;throw new n("该项目没有宿主机目录","PROJECT_PATH_REQUIRED",400)}try{return r.Tp.fromEnvironment(process.env.AGENT_WEB_ROOTS,(0,o.homedir)()).assertDirectory(s.description)}catch(e){throw new n(e instanceof Error?e.message:"项目目录不可用","PROJECT_PATH_INVALID",400)}}getModelConfig(){return{provider:process.env.AGENT_MODEL_PROVIDER||"openai",modelId:process.env.AGENT_MODEL_ID||"gpt-4o",baseUrl:process.env.AGENT_BASE_URL||""}}getWebAppBuildId(){return globalThis.__webAppBuildId??""}registerRemoteTools(e,t){return this.remoteToolStore.upsertTools(e,t)}getRemoteToolStore(){return this.remoteToolStore}async createSession(e,t=""){let s=new Date().toISOString();return t&&!await this.projectStore.get(t)&&await this.projectStore.create({id:t,name:t,description:"",created:s,updated:s}),this.sessionStore.create({id:crypto.randomUUID(),projectId:t,title:e,status:"idle",messages:[],events:[],created:s,updated:s,metadata:{permissionMode:"full-access"}})}async setSessionPermissionMode(e,t){if(!(0,r.ue)(t))throw Error(`Invalid permission mode: ${String(t)}`);let s=await this.sessionStore.get(e);if(!s)throw Error(`Session not found: ${e}`);return this.toolPermissionGate.clearSession(e),this.sessionStore.update(e,{metadata:{...s.metadata,permissionMode:t}})}getLatestEventId(e){return this.eventCounters.get(e)??0}subscribe(e,t,s=-1){for(let r of this.recentEvents.get(e)??[])if(!(r.id<=s))try{t(r.event,r.id)}catch{}let r=this.subscribers.get(e)??new Set;return r.add(t),this.subscribers.set(e,r),()=>{r.delete(t),0===r.size&&this.subscribers.delete(e)}}emit(e,t){let s=(this.eventCounters.get(e)??0)+1;this.eventCounters.set(e,s);let r=this.recentEvents.get(e);for(let o of(r&&(r.push({id:s,event:t}),r.length>500&&r.splice(0,r.length-500)),this.subscribers.get(e)??[]))try{o(t,s)}catch{}}publishExternal(e,t){this.emit(e,t)}resetExternalStream(e){this.eventCounters.set(e,0),this.recentEvents.set(e,[])}projectMessagesFromEvents(e){let t=[],s=null;for(let r of e){if("text_chunk"===r.type){s||(s={role:"assistant",content:""},t.push(s)),s.content+=r.text;continue}if("tool_call"===r.type){s&&!s.toolCalls?s.toolCalls=[r.toolCall]:t.push({role:"assistant",content:"",toolCalls:[r.toolCall]}),s=null;continue}if("tool_result"===r.type){t.push({role:"tool",content:r.result.content,toolCallId:r.result.toolCallId});continue}if("ask_user"===r.type){t.push({role:"assistant",content:""}),s=null;continue}"done"===r.type&&(s?s.content=r.finalText||s.content:r.finalText?.trim()&&t.push({role:"assistant",content:r.finalText}),s=null)}return t}async run(e,t,s){let o;let i=await this.sessionStore.get(t),n=await this.resolveProjectWorkingDirectory(i?.projectId);await this.sessionStore.addMessage(t,{role:"user",content:e}),this.eventCounters.set(t,0),this.recentEvents.set(t,[]);let a=i?.projectId||this.defaultRemoteToolsProjectId;try{o=await this.getBuilder().withWorkingDirectory(n).withRemoteToolStore(this.remoteToolStore,a).withTool(new r.as(async e=>this.createQuestion(e,t))).build()}catch(s){let e={type:"error",message:s instanceof Error?s.message:"Failed to build agent"};try{await this.sessionStore.addEvent(t,e)}catch{}throw this.emit(t,e),s}finally{this.builder?.withWorkingDirectory(this.workingDirectory).withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId)}this.activeAgent=o,this.activeRunSessionId=t,this.activeRun=o.run(e,t,s);let l=!1;try{for await(let e of this.activeRun)await this.sessionStore.addEvent(t,e),"error"===e.type?(l=!0,await this.sessionStore.update(t,{status:"failed"})):"done"!==e.type||l||(e.finalText.trim()&&await this.sessionStore.addMessage(t,{role:"assistant",content:e.finalText}),await this.sessionStore.update(t,{status:"completed"})),this.emit(t,e)}catch(s){l=!0;let e={type:"error",message:s instanceof Error?s.message:"Agent run failed"};try{await this.sessionStore.addEvent(t,e),await this.sessionStore.update(t,{status:"failed"})}catch{}this.emit(t,e)}finally{this.activeRunSessionId===t&&(this.activeAgent=null,this.activeRunSessionId=null),this.activeRun=null}try{let e=await this.sessionStore.get(t),s=(e?.messages??[]).filter(e=>"user"===e.role),r=this.projectMessagesFromEvents(e?.events??[]);await this.sessionStore.replaceMessages(t,[...s,...r])}catch{}}createQuestion(e,t){let s=crypto.randomUUID();return this.emit(t,{type:"ask_user",questionId:s,question:e.question,options:e.options,multiSelect:e.multiSelect}),new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingQuestions.has(s)&&(this.pendingQuestions.delete(s),t(Error("Question timed out after 5 minutes")))},3e5);this.pendingQuestions.set(s,{resolve:e,reject:t,timer:r})})}answerQuestion(e,t,s){let r=this.pendingQuestions.get(e);return!!r&&(clearTimeout(r.timer),this.pendingQuestions.delete(e),r.resolve({answer:t,selectedIndices:s}),!0)}async steer(e,t){return await this.sessionStore.addMessage(t,{role:"user",content:e,name:"__steer__"}),this.activeRunSessionId===t&&!!this.activeAgent&&(this.emit(t,{type:"thinking",message:`User added: ${e.slice(0,60)}`}),!0)}abort(){for(let[e,t]of(this.activeAgent?.abort(),this.pendingQuestions))clearTimeout(t.timer),t.reject(Error("Agent aborted")),this.pendingQuestions.delete(e)}}let l=globalThis,u=l.__agentHost??new a;l.__agentHost=u}};var t=require("../../../webpack-runtime.js");t.C(e);var s=e=>t(t.s=e),r=t.X(0,[375,703,322,
|
|
3
|
+
原因:${e.reason}`,options:[...r.Sf],toolCallId:""},e.sessionId);return(0,r.wM)(t.answer,t.selectedIndices)}});let e=process.env.AGENT_API_KEY,t=process.env.AGENT_MODEL_PROVIDER||"openai",s=process.env.AGENT_MODEL_ID||"gpt-4o",o=process.env.AGENT_BASE_URL||void 0,n=new r.Y4().withSessionStore(this.sessionStore).withWorkingDirectory(this.workingDirectory).withToolPermissionGate(this.toolPermissionGate);n.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e&&n.withModel(t,{apiKey:e,modelId:s,baseUrl:o}),this.builder=n}getBuilder(){return this.builder||(this.builder=new r.Y4().withToolPermissionGate(this.toolPermissionGate)),this.builder}setBuilder(e){e.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e.withWorkingDirectory(this.workingDirectory),e.withToolPermissionGate(this.toolPermissionGate),this.builder=e}getSessionStore(){return this.sessionStore}getProjectStore(){return this.projectStore}async resolveProjectWorkingDirectory(e,t=!1){if(!e)return this.workingDirectory;let s=await this.projectStore.get(e);if(!s)throw new n("项目不存在","PROJECT_NOT_FOUND",404);if(!s.description?.trim()){if(!t)return this.workingDirectory;throw new n("该项目没有宿主机目录","PROJECT_PATH_REQUIRED",400)}try{return r.Tp.fromEnvironment(process.env.AGENT_WEB_ROOTS,(0,o.homedir)()).assertDirectory(s.description)}catch(e){throw new n(e instanceof Error?e.message:"项目目录不可用","PROJECT_PATH_INVALID",400)}}getModelConfig(){return{provider:process.env.AGENT_MODEL_PROVIDER||"openai",modelId:process.env.AGENT_MODEL_ID||"gpt-4o",baseUrl:process.env.AGENT_BASE_URL||""}}getWebAppBuildId(){return globalThis.__webAppBuildId??""}registerRemoteTools(e,t){return this.remoteToolStore.upsertTools(e,t)}getRemoteToolStore(){return this.remoteToolStore}async createSession(e,t=""){let s=new Date().toISOString();return t&&!await this.projectStore.get(t)&&await this.projectStore.create({id:t,name:t,description:"",created:s,updated:s}),this.sessionStore.create({id:crypto.randomUUID(),projectId:t,title:e,status:"idle",messages:[],events:[],created:s,updated:s,metadata:{permissionMode:"full-access"}})}async setSessionPermissionMode(e,t){if(!(0,r.ue)(t))throw Error(`Invalid permission mode: ${String(t)}`);let s=await this.sessionStore.get(e);if(!s)throw Error(`Session not found: ${e}`);return this.toolPermissionGate.clearSession(e),this.sessionStore.update(e,{metadata:{...s.metadata,permissionMode:t}})}getLatestEventId(e){return this.eventCounters.get(e)??0}subscribe(e,t,s=-1){for(let r of this.recentEvents.get(e)??[])if(!(r.id<=s))try{t(r.event,r.id)}catch{}let r=this.subscribers.get(e)??new Set;return r.add(t),this.subscribers.set(e,r),()=>{r.delete(t),0===r.size&&this.subscribers.delete(e)}}emit(e,t){let s=(this.eventCounters.get(e)??0)+1;this.eventCounters.set(e,s);let r=this.recentEvents.get(e);for(let o of(r&&(r.push({id:s,event:t}),r.length>500&&r.splice(0,r.length-500)),this.subscribers.get(e)??[]))try{o(t,s)}catch{}}publishExternal(e,t){this.emit(e,t)}resetExternalStream(e){this.eventCounters.set(e,0),this.recentEvents.set(e,[])}projectMessagesFromEvents(e){let t=[],s=null;for(let r of e){if("text_chunk"===r.type){s||(s={role:"assistant",content:""},t.push(s)),s.content+=r.text;continue}if("tool_call"===r.type){s&&!s.toolCalls?s.toolCalls=[r.toolCall]:t.push({role:"assistant",content:"",toolCalls:[r.toolCall]}),s=null;continue}if("tool_result"===r.type){t.push({role:"tool",content:r.result.content,toolCallId:r.result.toolCallId});continue}if("ask_user"===r.type){t.push({role:"assistant",content:""}),s=null;continue}"done"===r.type&&(s?s.content=r.finalText||s.content:r.finalText?.trim()&&t.push({role:"assistant",content:r.finalText}),s=null)}return t}async run(e,t,s){let o;let i=await this.sessionStore.get(t),n=await this.resolveProjectWorkingDirectory(i?.projectId);await this.sessionStore.addMessage(t,{role:"user",content:e}),this.eventCounters.set(t,0),this.recentEvents.set(t,[]);let a=i?.projectId||this.defaultRemoteToolsProjectId;try{o=await this.getBuilder().withWorkingDirectory(n).withRemoteToolStore(this.remoteToolStore,a).withTool(new r.as(async e=>this.createQuestion(e,t))).build()}catch(s){let e={type:"error",message:s instanceof Error?s.message:"Failed to build agent"};try{await this.sessionStore.addEvent(t,e)}catch{}throw this.emit(t,e),s}finally{this.builder?.withWorkingDirectory(this.workingDirectory).withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId)}this.activeAgent=o,this.activeRunSessionId=t,this.activeRun=o.run(e,t,s);let l=!1;try{for await(let e of this.activeRun)await this.sessionStore.addEvent(t,e),"error"===e.type?(l=!0,await this.sessionStore.update(t,{status:"failed"})):"done"!==e.type||l||(e.finalText.trim()&&await this.sessionStore.addMessage(t,{role:"assistant",content:e.finalText}),await this.sessionStore.update(t,{status:"completed"})),this.emit(t,e)}catch(s){l=!0;let e={type:"error",message:s instanceof Error?s.message:"Agent run failed"};try{await this.sessionStore.addEvent(t,e),await this.sessionStore.update(t,{status:"failed"})}catch{}this.emit(t,e)}finally{this.activeRunSessionId===t&&(this.activeAgent=null,this.activeRunSessionId=null),this.activeRun=null}try{let e=await this.sessionStore.get(t),s=(e?.messages??[]).filter(e=>"user"===e.role),r=this.projectMessagesFromEvents(e?.events??[]);await this.sessionStore.replaceMessages(t,[...s,...r])}catch{}}createQuestion(e,t){let s=crypto.randomUUID();return this.emit(t,{type:"ask_user",questionId:s,question:e.question,options:e.options,multiSelect:e.multiSelect}),new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingQuestions.has(s)&&(this.pendingQuestions.delete(s),t(Error("Question timed out after 5 minutes")))},3e5);this.pendingQuestions.set(s,{resolve:e,reject:t,timer:r})})}answerQuestion(e,t,s){let r=this.pendingQuestions.get(e);return!!r&&(clearTimeout(r.timer),this.pendingQuestions.delete(e),r.resolve({answer:t,selectedIndices:s}),!0)}async steer(e,t){return await this.sessionStore.addMessage(t,{role:"user",content:e,name:"__steer__"}),this.activeRunSessionId===t&&!!this.activeAgent&&(this.emit(t,{type:"thinking",message:`User added: ${e.slice(0,60)}`}),!0)}abort(){for(let[e,t]of(this.activeAgent?.abort(),this.pendingQuestions))clearTimeout(t.timer),t.reject(Error("Agent aborted")),this.pendingQuestions.delete(e)}}let l=globalThis,u=l.__agentHost??new a;l.__agentHost=u}};var t=require("../../../webpack-runtime.js");t.C(e);var s=e=>t(t.s=e),r=t.X(0,[375,703,322,988],()=>s(1880));module.exports=r})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":1,"files":["../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../node_modules/better-sqlite3","../../../../../node_modules/next","../../../../../package.json","../../../../package.json","../../../chunks/322.js","../../../chunks/375.js","../../../chunks/703.js","../../../chunks/
|
|
1
|
+
{"version":1,"files":["../../../../../node_modules/@anthropic-ai/claude-agent-sdk","../../../../../node_modules/better-sqlite3","../../../../../node_modules/next","../../../../../package.json","../../../../package.json","../../../chunks/322.js","../../../chunks/375.js","../../../chunks/703.js","../../../chunks/988.js","../../../webpack-runtime.js"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(()=>{var e={};e.id=541,e.ids=[541],e.modules={2934:e=>{"use strict";e.exports=require("next/dist/client/components/action-async-storage.external.js")},4580:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external.js")},5869:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external.js")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},8664:(e,t,r)=>{"use strict";r.r(t),r.d(t,{GlobalError:()=>o.a,__next_app__:()=>p,originalPathname:()=>u,pages:()=>d,routeModule:()=>b,tree:()=>c}),r(6742),r(4972),r(3028);var a=r(1772),i=r(5042),n=r(5663),o=r.n(n),l=r(4812),s={};for(let e in l)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(s[e]=()=>l[e]);r.d(t,s);let c=["",{children:["web",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(r.bind(r,6742)),"/Users/caoqu/team-agent/customer-agent/packages/server/app/web/page.tsx"]}]},{}]},{layout:[()=>Promise.resolve().then(r.bind(r,4972)),"/Users/caoqu/team-agent/customer-agent/packages/server/app/layout.tsx"],"not-found":[()=>Promise.resolve().then(r.t.bind(r,3028,23)),"next/dist/client/components/not-found-error"]}],d=["/Users/caoqu/team-agent/customer-agent/packages/server/app/web/page.tsx"],u="/web/page",p={require:r,loadChunk:()=>Promise.resolve()},b=new a.AppPageRouteModule({definition:{kind:i.x.APP_PAGE,page:"/web/page",pathname:"/web",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:c}})},8490:(e,t,r)=>{Promise.resolve().then(r.t.bind(r,1782,23)),Promise.resolve().then(r.t.bind(r,8949,23)),Promise.resolve().then(r.t.bind(r,6569,23)),Promise.resolve().then(r.t.bind(r,8718,23)),Promise.resolve().then(r.t.bind(r,7415,23)),Promise.resolve().then(r.t.bind(r,8781,23))},3703:(e,t,r)=>{Promise.resolve().then(r.bind(r,5023))},2027:()=>{},1166:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n}});let a=r(7094);r(3517),r(5921);let i=a._(r(4079));function n(e,t){var r;let a={loading:e=>{let{error:t,isLoading:r,pastDelay:a}=e;return null}};"function"==typeof e&&(a.loader=e);let n={...a,...t};return(0,i.default)({...n,modules:null==(r=n.loadableGenerated)?void 0:r.modules})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1803:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"BailoutToCSR",{enumerable:!0,get:function(){return i}});let a=r(93);function i(e){let{reason:t,children:r}=e;throw new a.BailoutToCSRError(t)}},4079:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return c}});let a=r(3517),i=r(5921),n=r(1803),o=r(5259);function l(e){return{default:e&&"default"in e?e.default:e}}let s={loader:()=>Promise.resolve(l(()=>null)),loading:null,ssr:!0},c=function(e){let t={...s,...e},r=(0,i.lazy)(()=>t.loader().then(l)),c=t.loading;function d(e){let l=c?(0,a.jsx)(c,{isLoading:!0,pastDelay:!0,error:null}):null,s=t.ssr?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(o.PreloadCss,{moduleIds:t.modules}),(0,a.jsx)(r,{...e})]}):(0,a.jsx)(n.BailoutToCSR,{reason:"next/dynamic",children:(0,a.jsx)(r,{...e})});return(0,a.jsx)(i.Suspense,{fallback:l,children:s})}return d.displayName="LoadableComponent",d}},5259:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"PreloadCss",{enumerable:!0,get:function(){return n}});let a=r(3517),i=r(4580);function n(e){let{moduleIds:t}=e,r=(0,i.getExpectedRequestStore)("next/dynamic css"),n=[];if(r.reactLoadableManifest&&t){let e=r.reactLoadableManifest;for(let r of t){if(!e[r])continue;let t=e[r].files.filter(e=>e.endsWith(".css"));n.push(...t)}}return 0===n.length?null:(0,a.jsx)(a.Fragment,{children:n.map(e=>(0,a.jsx)("link",{precedence:"dynamic",rel:"stylesheet",href:r.assetPrefix+"/_next/"+encodeURI(e),as:"style"},e))})}},5023:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>P});var a=r(3517),i=r(1166),n=r.n(i),o=r(5921);let l=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),s=(...e)=>e.filter((e,t,r)=>!!e&&""!==e.trim()&&r.indexOf(e)===t).join(" ").trim();var c={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};let d=(0,o.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:a,className:i="",children:n,iconNode:l,...d},u)=>(0,o.createElement)("svg",{ref:u,...c,width:t,height:t,stroke:e,strokeWidth:a?24*Number(r)/Number(t):r,className:s("lucide",i),...d},[...l.map(([e,t])=>(0,o.createElement)(e,t)),...Array.isArray(n)?n:[n]])),u=(e,t)=>{let r=(0,o.forwardRef)(({className:r,...a},i)=>(0,o.createElement)(d,{ref:i,iconNode:t,className:s(`lucide-${l(e)}`,r),...a}));return r.displayName=`${e}`,r},p=u("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),b=u("FolderTree",[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]]);function f({children:e}){let t=function(){let[e,t]=(0,o.useState)("loading"),[r,a]=(0,o.useState)(null),[i]=(0,o.useState)(""),[n,l]=(0,o.useState)(null),s=(0,o.useCallback)(async()=>{t("loading"),l(null);try{let e=await fetch("/api/web-console/bootstrap",{credentials:"same-origin",cache:"no-store"});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=await e.json();a(r.user),t("authenticated")}catch{l("无法连接远程控制台"),t("needsLogin")}},[]),c=(0,o.useCallback)(async()=>{let e=await fetch("/api/web-console/bootstrap",{credentials:"same-origin",cache:"no-store"});if(!e.ok)throw Error("bootstrap failed");let r=await e.json();return a(r.user),t("authenticated"),r.wsNonce},[]),d=(0,o.useCallback)(async()=>!0,[]);return{status:e,user:r,error:n,csrfToken:i,setup:d,login:d,logout:s,refresh:s,getWsNonce:c}}();return"authenticated"===t.status?a.jsx(a.Fragment,{children:e(t)}):a.jsx("main",{style:h.page,children:a.jsx("div",{style:h.card,children:t.error||"正在连接远程控制台…"})})}let h={page:{minHeight:"100dvh",display:"grid",placeItems:"center",background:"#0b0b10",color:"#e8e8ee",fontFamily:'-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif'},card:{color:"#858999",fontSize:13}};function x({csrfToken:e,terminalId:t,onFill:r}){let[i,n]=(0,o.useState)([]),[l,s]=(0,o.useState)(""),c=(0,o.useCallback)(async()=>{let e=new URLSearchParams({q:l,limit:"200"}),t=await fetch(`/api/web-console/history?${e}`,{credentials:"same-origin"});t.ok&&n((await t.json()).history)},[l]),d=async t=>{await fetch("/api/web-console/history",{method:"DELETE",credentials:"same-origin",headers:{"content-type":"application/json","x-csrf-token":e},body:JSON.stringify({id:t})}),c()},u=e=>{t&&r(e)};return(0,a.jsxs)("div",{className:"history-panel",children:[(0,a.jsxs)("div",{className:"history-search",children:[a.jsx("input",{value:l,onChange:e=>s(e.target.value),placeholder:"搜索命令"}),a.jsx("button",{onClick:c,children:"刷新"})]}),i.map(e=>(0,a.jsxs)("div",{className:`history-item${t?"":" history-item-disabled"}`,role:"button",tabIndex:t?0:-1,onClick:()=>u(e.command),onKeyDown:r=>{("Enter"===r.key||" "===r.key)&&t&&(r.preventDefault(),u(e.command))},children:[a.jsx("code",{children:e.command}),(0,a.jsxs)("small",{children:[e.cwd," \xb7 ",new Date(e.executedAt).toLocaleString()]}),(0,a.jsxs)("div",{className:"history-item-actions",onClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),children:[a.jsx("button",{onClick:()=>navigator.clipboard.writeText(e.command),children:"复制"}),a.jsx("button",{disabled:!t,onClick:()=>u(e.command),children:"填入"}),a.jsx("button",{onClick:()=>d(e.id),children:"删除"})]})]},e.id)),!i.length&&a.jsx("div",{className:"history-empty",children:"暂无 Shell 命令历史"}),!t&&!!i.length&&a.jsx("div",{className:"history-empty",children:"请先打开一个终端页签"})]})}var g=r(5878);let m=[{id:"pearl",label:"珍珠白",swatch:"#f5f6fa",preview:["#f5f6fa","#4f6ef7"],cssVars:{"--ui-root-bg":"#f5f6fa","--ui-text":"#111827","--ui-tabbar-bg":"#eef0f6","--ui-tabbar-border":"#dfe3ee","--ui-tab-bg":"#e6e9f4","--ui-tab-text":"#5b6472","--ui-tab-active-bg":"#ffffff","--ui-tab-active-text":"#111827","--ui-tab-accent":"#4f6ef7","--ui-connection-bg":"#eef0f6","--ui-connection-text":"#9ca3af","--ui-tree-bg":"#fbfcfe","--ui-tree-border":"#e5e8f0","--ui-term-col-bg":"#f5f6fa","--ui-fab-bg":"#ffffff","--ui-fab-border":"#d8dcea","--ui-muted-surface":"#eef0f6","--ui-muted-border":"#d8dcea","--ui-muted-text":"#6b7280","--ui-panel-input-bg":"#ffffff","--ui-panel-input-text":"#111827","--ui-panel-input-border":"#d8dcea","--ui-drawer-tab-text":"#6b7280","--ui-drawer-tab-active":"#111827","--ui-history-item-text":"#1f2937","--ui-history-meta":"#9ca3af","--ui-success":"#059669","--ui-error":"#dc2626"},termHostBg:"#ffffff",keybar:{bg:"#eef0f6",border:"#dfe3ee",keyBg:"#ffffff",keyBorder:"#d8dcea",keyText:"#4b5563",accent:"#4f6ef7",accentText:"#ffffff",drag:"#a5b4fc"},xterm:{background:"#ffffff",foreground:"#1f2937",cursor:"#4f6ef7",selectionBackground:"#c7d2fe",black:"#24292e",red:"#d73a49",green:"#22863a",yellow:"#b08800",blue:"#005cc5",magenta:"#6f42c1",cyan:"#1b7c83",white:"#6a737d",brightBlack:"#959da5",brightWhite:"#fafbfc"}},{id:"scifi",label:"科幻霓虹",swatch:"#050a14",preview:["#050a14","#22d3ee"],cssVars:{"--ui-root-bg":"#050a14","--ui-text":"#e2f3ff","--ui-tabbar-bg":"#0a1220","--ui-tabbar-border":"#10263c","--ui-tab-bg":"#0d1626","--ui-tab-text":"#5c7893","--ui-tab-active-bg":"#122036","--ui-tab-active-text":"#e2f3ff","--ui-tab-accent":"#22d3ee","--ui-connection-bg":"#0a1220","--ui-connection-text":"#5c7893","--ui-tree-bg":"#0d1626","--ui-tree-border":"#10263c","--ui-term-col-bg":"#050a14","--ui-fab-bg":"#122036","--ui-fab-border":"#155e75","--ui-muted-surface":"#0d1626","--ui-muted-border":"#164e63","--ui-muted-text":"#9fb8d0","--ui-panel-input-bg":"#0a1220","--ui-panel-input-text":"#e2f3ff","--ui-panel-input-border":"#164e63","--ui-drawer-tab-text":"#5c7893","--ui-drawer-tab-active":"#e2f3ff","--ui-history-item-text":"#d5ecfb","--ui-history-meta":"#5c7893","--ui-success":"#34d399","--ui-error":"#fb7185"},termHostBg:"#0a1220",keybar:{bg:"#0a1220",border:"#10263c",keyBg:"#0d1626",keyBorder:"#164e63",keyText:"#9fb8d0",accent:"#22d3ee",accentText:"#04121a",drag:"#155e75"},xterm:{background:"#0a1220",foreground:"#e2f3ff",cursor:"#22d3ee",selectionBackground:"#164e63",black:"#0d1626",red:"#fb7185",green:"#34d399",yellow:"#fbbf24",blue:"#38bdf8",magenta:"#e879f9",cyan:"#22d3ee",white:"#e2f3ff",brightBlack:"#5c7893",brightWhite:"#ffffff"}},{id:"noir",label:"暗夜黑",swatch:"#0f1115",preview:["#0f1115","#a78bfa"],cssVars:{"--ui-root-bg":"#0f1115","--ui-text":"#eceff4","--ui-tabbar-bg":"#14171d","--ui-tabbar-border":"#232833","--ui-tab-bg":"#191d24","--ui-tab-text":"#6b7280","--ui-tab-active-bg":"#1f242d","--ui-tab-active-text":"#eceff4","--ui-tab-accent":"#a78bfa","--ui-connection-bg":"#14171d","--ui-connection-text":"#6b7280","--ui-tree-bg":"#191d24","--ui-tree-border":"#232833","--ui-term-col-bg":"#0f1115","--ui-fab-bg":"#1f242d","--ui-fab-border":"#2a3040","--ui-muted-surface":"#191d24","--ui-muted-border":"#2a3040","--ui-muted-text":"#aab2bf","--ui-panel-input-bg":"#14171d","--ui-panel-input-text":"#eceff4","--ui-panel-input-border":"#2a3040","--ui-drawer-tab-text":"#6b7280","--ui-drawer-tab-active":"#eceff4","--ui-history-item-text":"#d7dce4","--ui-history-meta":"#6b7280","--ui-success":"#4ade80","--ui-error":"#f87171"},termHostBg:"#14171d",keybar:{bg:"#14171d",border:"#232833",keyBg:"#191d24",keyBorder:"#2a3040",keyText:"#aab2bf",accent:"#a78bfa",accentText:"#0f1115",drag:"#4b4470"},xterm:{background:"#14171d",foreground:"#eceff4",cursor:"#a78bfa",selectionBackground:"#3b3654",black:"#191d24",red:"#f87171",green:"#4ade80",yellow:"#fbbf24",blue:"#60a5fa",magenta:"#c084fc",cyan:"#67e8f9",white:"#eceff4",brightBlack:"#6b7280",brightWhite:"#ffffff"}}],v="pearl",w=Object.fromEntries(m.map(e=>[e.id,e])),y={dark:"noir",black:"noir",gray:"noir",blue:"noir",red:"noir",yellow:"noir",green:"noir",white:"pearl"};function k({username:e,themeId:t,onThemeChange:r,accent:i,accentText:n}){let[l,s]=(0,o.useState)(!1),c=(0,o.useRef)(null),d=(0,o.useRef)(null),u=(0,o.useRef)(null),[p,b]=(0,o.useState)(null),[f,h]=(0,o.useState)(null),x=(e.trim()[0]??"?").toUpperCase();return(0,a.jsxs)("div",{ref:c,className:"theme-picker",children:[a.jsx("button",{ref:d,type:"button",className:"theme-avatar","aria-label":`换肤(${e})`,title:e,"aria-expanded":l,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.preventDefault(),e.stopPropagation(),s(e=>!e)},style:{border:`1px solid ${i}`,background:i,color:n},children:x}),l&&p&&f&&(0,g.createPortal)((0,a.jsxs)("div",{ref:u,className:"theme-popover",role:"dialog","aria-label":"选择皮肤",style:{position:"fixed",top:p.top,left:p.left,zIndex:200,width:176,padding:8,borderRadius:10,border:"1px solid var(--ui-tabbar-border, #282b36)",background:"var(--ui-tab-active-bg, #262b38)",boxShadow:"0 10px 28px rgba(0,0,0,.45)"},children:[a.jsx("div",{style:{fontSize:10,color:"var(--ui-connection-text, #777b8c)",margin:"2px 4px 6px",letterSpacing:.5},children:"皮肤"}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:2},children:m.map(e=>{let i=e.id===t;return(0,a.jsxs)("button",{type:"button",className:"theme-popover-item","aria-label":e.label,"aria-pressed":i,onPointerDown:e=>e.stopPropagation(),onClick:()=>{r(e.id),s(!1)},style:{background:i?"color-mix(in srgb, var(--ui-tab-accent, #7aa2f7) 14%, transparent)":"transparent"},children:[a.jsx("span",{style:{width:18,height:18,borderRadius:5,flexShrink:0,background:`linear-gradient(135deg, ${e.preview[0]} 55%, ${e.preview[1]} 55%)`,boxShadow:"inset 0 0 0 1px rgba(128,128,160,.25)"}}),a.jsx("span",{style:{flex:1,textAlign:"left",fontSize:12,fontWeight:i?600:400,color:i?"var(--ui-tab-active-text, #edf0f7)":"var(--ui-tab-text, #8f93a4)"},children:e.label}),i&&a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"var(--ui-tab-accent, #7aa2f7)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m5 12 4 4L19 6"})})]},e.id)})})]}),f)]})}let j=n()(async()=>{},{loadableGenerated:{modules:["app/web/page.tsx -> ./TerminalPane"]},ssr:!1}),S=n()(async()=>{},{loadableGenerated:{modules:["app/web/page.tsx -> ./FileTree"]},ssr:!1}),C=n()(async()=>{},{loadableGenerated:{modules:["app/web/page.tsx -> ./FilePreview"]},ssr:!1});function P(){return a.jsx(f,{children:e=>a.jsx(R,{auth:e})})}let T={id:"webapp-agent",title:"智能助手",kind:"webapp"};function R({auth:e}){let{state:t,epoch:r,rpc:i,onEvent:n,onTerminalData:l,onTerminalReset:s,sendTerminalInput:c}=function(e,t,r){let[a,i]=(0,o.useState)({connected:!1,error:null}),[n,l]=(0,o.useState)(0),s=(0,o.useRef)(null),c=(0,o.useRef)(0),d=(0,o.useRef)(new Map),u=(0,o.useRef)([]),p=(0,o.useRef)(0),b=(0,o.useRef)(new Map),f=(0,o.useRef)(new Map),h=(0,o.useRef)(new Map),x=(0,o.useRef)(1e3),g=(0,o.useRef)(!1),m=(0,o.useRef)(null),v=(0,o.useRef)(e),w=(0,o.useRef)(t),y=(0,o.useRef)(r);v.current=e,w.current=t,y.current=r;let k=(0,o.useCallback)((e,t)=>{let r=b.current.get(e);return r||b.current.set(e,r=new Set),r.add(t),()=>r.delete(t)},[]),j=(0,o.useCallback)((e,t)=>{let r=f.current.get(e);return r||f.current.set(e,r=new Set),r.add(t),()=>r.delete(t)},[]),S=(0,o.useCallback)((e,t)=>{let r=h.current.get(e);return r||h.current.set(e,r=new Set),r.add(t),()=>r.delete(t)},[]),C=(0,o.useCallback)((e,t)=>{let r=s.current;if(!r||r.readyState!==WebSocket.OPEN)return!1;let a=new TextEncoder().encode(t),i=new Uint8Array(6+a.byteLength),n=new DataView(i.buffer);return i[0]=1,i[1]=1,n.setUint32(2,e),i.set(a,6),r.send(i),!0},[]),P=(0,o.useCallback)(e=>{let t=s.current;t?.readyState===WebSocket.OPEN?t.send(e):u.current.push(e)},[]),T=(0,o.useCallback)((e,t={},r=15e3)=>new Promise((a,i)=>{let n=++p.current,o=setTimeout(()=>{d.current.delete(n),i(Error(`${e} timeout`))},r);d.current.set(n,{resolve:a,reject:i,timer:o}),P(JSON.stringify({type:e,_req:n,...t}))}),[P]),R=(0,o.useCallback)(async()=>{let e,t;g.current=!1;let r=++c.current;m.current&&(clearInterval(m.current),m.current=null);let a=s.current;if(a){a.onopen=a.onmessage=a.onerror=a.onclose=null;try{a.close()}catch{}}try{e=await w.current()}catch{r===c.current&&y.current();return}if(r===c.current&&!g.current){try{t=new WebSocket(`${"https:"===location.protocol?"wss:":"ws:"}//${location.host}/ws?nonce=${encodeURIComponent(e)}`)}catch(e){i({connected:!1,error:String(e)});return}t.binaryType="arraybuffer",s.current=t,t.onopen=()=>{if(r!==c.current||s.current!==t)return;for(let e of(x.current=1e3,i({connected:!0,error:null}),l(e=>e+1),u.current.splice(0)))t.send(e);let e=Date.now();m.current=setInterval(()=>{if(s.current!==t||t.readyState!==WebSocket.OPEN){clearInterval(m.current),m.current=null;return}if(Date.now()-e>25e3){try{t.close()}catch{}return}try{t.send(JSON.stringify({type:"ping"}))}catch{}},1e4);let a=()=>{e=Date.now()};t.addEventListener("message",a),t.addEventListener("close",()=>t.removeEventListener("message",a),{once:!0})},t.onmessage=e=>{let a;if(r===c.current&&s.current===t){if("string"!=typeof e.data){let t=new Uint8Array(e.data);if(t.byteLength>=6&&1===t[0]&&2===t[1]){let e=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(2);f.current.get(e)?.forEach(e=>e(t.subarray(6)))}else if(t.byteLength>=6&&1===t[0]&&3===t[1]){let e=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(2);h.current.get(e)?.forEach(e=>e())}else v.current(t);return}try{a=JSON.parse(e.data)}catch{return}if("error"===a.type&&null!=a.id){let e=d.current.get(a.id);if(e){d.current.delete(a.id),clearTimeout(e.timer);let t=Object.assign(Error(a.error||"gateway error"),{code:a.code});e.reject(t)}return}if(null!=a.id&&"string"==typeof a.type&&a.type.endsWith(":result")){let e=d.current.get(a.id);e&&(d.current.delete(a.id),clearTimeout(e.timer),e.resolve(a));return}b.current.get(a.type)?.forEach(e=>e(a))}},t.onclose=e=>{if(r!==c.current||s.current!==t)return;if(m.current&&(clearInterval(m.current),m.current=null),s.current=null,i({connected:!1,error:null}),4001===e.code||4003===e.code){y.current();return}if(g.current)return;let a=x.current;x.current=Math.min(2*a,8e3),setTimeout(()=>{g.current||r!==c.current||R()},a)},t.onerror=()=>{}}},[]);return{state:a,epoch:n,rpc:T,onEvent:k,onTerminalData:j,onTerminalReset:S,sendTerminalInput:C,reconnect:R}}(()=>{},e.getWsNonce,e.refresh),[d,u]=(0,o.useState)([{...T}]),[f,h]=(0,o.useState)(T.id),[g,m]=(0,o.useState)({});(0,o.useRef)(!1),(0,o.useRef)(null);let P=(0,o.useRef)(new Map),R=(0,o.useCallback)((e,t)=>(P.current.set(e,t),()=>P.current.delete(e)),[]),N=(0,o.useCallback)(e=>{if(!f)return;let t=P.current.get(f);t?t(e):i("term:input",{id:f,data:`\x15${e}`}).catch(()=>{}),B(!1)},[f,i]),[D,E]=(0,o.useState)(!1),[_,L]=(0,o.useState)({}),[O,I]=(0,o.useState)(null),[$,B]=(0,o.useState)(!1),[W,F]=(0,o.useState)("files"),[H,U]=(0,o.useState)(null),[q,A]=(0,o.useState)(!0),[X,V]=(0,o.useState)({xRatio:.94,yRatio:.65,anchor:"right"}),[G,Y]=(0,o.useState)(!1),[J,K]=(0,o.useState)([]),[Z,Q]=(0,o.useState)(v),[ee,et]=(0,o.useState)(!1),er=function(e){if(e&&e in w)return w[e];let t=e?y[e]:void 0;return t?w[t]:w[v]}(Z),ea=(0,o.useRef)(null),ei=(0,o.useRef)(null),[en,eo]=(0,o.useState)(0),[el,es]=(0,o.useState)(!1),ec=(0,o.useRef)(null),ed=(0,o.useRef)(null),eu=(0,o.useRef)(null),ep=(0,o.useCallback)(e=>{eu.current?.contentWindow?.postMessage({type:"agent-web-shell:skin:v1",skin:e},window.location.origin)},[]);(0,o.useRef)(0);let eb=f?g[f]??null:null;(0,o.useCallback)(t=>{fetch("/api/web-console/preferences",{method:"PATCH",credentials:"same-origin",headers:{"content-type":"application/json","x-csrf-token":e.csrfToken},body:JSON.stringify(t)}).catch(()=>{})},[e.csrfToken]),(0,o.useCallback)(t=>{e.csrfToken&&fetch("/api/web-console/device-state",{method:"PUT",credentials:"same-origin",headers:{"content-type":"application/json","x-csrf-token":e.csrfToken},body:JSON.stringify(t)}).catch(()=>{})},[e.csrfToken]);let ef=(0,o.useCallback)(e=>{I(e),B(!1)},[]),eh=(0,o.useCallback)(()=>{let e=null;u(t=>t.length>=8?t:[...t,{id:e=`t-web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,title:`Terminal ${t.length+1}`}]),e&&h(e)},[]),ex=e=>{e!==T.id&&window.confirm("关闭页签会终止该终端进程,确认关闭?")&&(u(t=>{let r=t.filter(t=>t.id!==e);return f===e&&h(r[0]?.id??null),r}),i("term:kill",{id:e}).catch(()=>{}))},eg=(0,o.useCallback)(e=>{if(!f||d.length<2)return;let t=(d.findIndex(e=>e.id===f)+e+d.length)%d.length;h(d[t].id)},[f,d]),em=Math.max(0,d.findIndex(e=>e.id===f)),ev=d[em]?.kind==="webapp"?er.cssVars["--ui-term-col-bg"]:er.termHostBg,ew={...z.root,...er.cssVars,"--ui-active-content-bg":ev,"--ui-terminal-bg":er.termHostBg,background:"var(--ui-root-bg)",color:"var(--ui-text)"},ey=(0,o.useCallback)(()=>{ei.current=null,eo(0),es(!1)},[]),ek=(0,o.useCallback)(e=>{Math.abs(e)>=64&&d.length>1&&eg(e<0?1:-1),ey()},[d.length,eg,ey]),ej=e=>e instanceof Element&&!!e.closest(".terminal-screen");return(0,o.useCallback)((e="smooth")=>{let t=ed.current;if(!t||!f)return;let r=t.querySelector(`[data-terminal-id="${f}"]`);if(!r)return;if(r===t.querySelector("[data-terminal-id]")){t&&(t.scrollLeft=0);return}let a=t.querySelector(".terminal-connection"),i=a?.offsetWidth??0,n=r.offsetLeft,o=n+r.offsetWidth,l=t.scrollLeft,s=l+t.clientWidth-i;n<l+8?t.scrollTo({left:Math.max(0,n-8),behavior:e}):o>s-8&&t.scrollTo({left:o-t.clientWidth+i+8,behavior:e})},[f]),(0,a.jsxs)("div",{className:"web-root",style:ew,children:[a.jsx("style",{dangerouslySetInnerHTML:{__html:M}}),(0,a.jsxs)("div",{className:"terminal-tabs",ref:ed,children:[d.map(e=>(0,a.jsxs)("div",{"data-terminal-id":e.id,draggable:!0,className:`terminal-tab ${e.id===f?"active":""}`,onDragStart:()=>{ec.current=e.id},onDragOver:e=>e.preventDefault(),onDrop:t=>{t.preventDefault();let r=ec.current;ec.current=null,r&&r!==e.id&&u(t=>{let a=t.findIndex(e=>e.id===r),n=t.findIndex(t=>t.id===e.id);if(a<0||n<0)return t;let o=[...t],[l]=o.splice(a,1);return o.splice(n,0,l),i("term:reorder",{ids:o.map(e=>e.id).filter(e=>e!==T.id)}).catch(()=>{}),o})},onClick:()=>h(e.id),onDoubleClick:()=>{if("webapp"===e.kind)return;let t=window.prompt("页签名称",e.title)?.trim();t&&i("term:rename",{id:e.id,title:t}).then(()=>u(r=>r.map(r=>r.id===e.id?{...r,title:t}:r))).catch(()=>{})},children:[a.jsx("span",{children:e.title}),"webapp"!==e.kind&&a.jsx("button",{tabIndex:-1,onClick:t=>{t.stopPropagation(),ex(e.id)},children:"\xd7"})]},e.id)),a.jsx("button",{className:"terminal-add",disabled:d.length>=8,onClick:eh,children:"+"}),(0,a.jsxs)("div",{className:"terminal-connection",children:[a.jsx("span",{style:{width:8,height:8,borderRadius:99,background:t.connected?"var(--ui-success)":"var(--ui-error)"}}),a.jsx(k,{username:e.user?.username??"?",themeId:Z,onThemeChange:Q,accent:er.keybar.accent,accentText:er.keybar.accentText})]})]}),(0,a.jsxs)("main",{className:`workspace ${$?"show-tree":""} ${O?"has-preview":""}`,style:z.workspace,children:[a.jsx("section",{className:"term-col",style:z.termCol,onPointerDownCapture:e=>{"touch"===e.pointerType&&ej(e.target)&&(ei.current={x:e.clientX,y:e.clientY,axis:"pending"})},onPointerMoveCapture:e=>{let t=ei.current;if(!t||"touch"!==e.pointerType)return;let r=e.clientX-t.x,a=e.clientY-t.y;if("pending"===t.axis){if(8>=Math.max(Math.abs(r),Math.abs(a)))return;if(Math.abs(a)>=1.2*Math.abs(r)){ei.current=null;return}t.axis="horizontal",es(!0)}"horizontal"===t.axis&&(e.preventDefault(),eo(r))},onPointerUpCapture:e=>{let t=ei.current;if(!t||"touch"!==e.pointerType)return;let r=e.clientX-t.x;"horizontal"===t.axis&&Math.abs(r)>=64?ek(r):ey()},onPointerCancelCapture:ey,children:a.jsx("div",{className:"terminal-track",style:{transform:`translate3d(calc(${-(100*em)}% + ${en}px),0,0)`,transition:el?"none":"transform 260ms cubic-bezier(.22,.8,.32,1)"},children:d.map(e=>a.jsx("div",{className:"terminal-slide",children:"webapp"===e.kind?a.jsx("iframe",{ref:eu,src:"/app/",title:e.title,onLoad:()=>ep(Z),style:{width:"100%",height:"100%",border:"0",background:"var(--ui-term-col-bg, #101014)"}}):a.jsx(j,{terminalId:e.id,title:e.title,visible:e.id===f,state:t,rpc:i,onEvent:n,onTerminalData:l,onTerminalReset:s,sendTerminalInput:c,keyOrder:J,keybarHidden:G,onKeyOrderChange:K,onKeybarHiddenChange:Y,terminalTheme:er,initialScrollLine:_[e.id]??null,onScrollLineChange:t=>L(r=>r[e.id]===t?r:{...r,[e.id]:t}),onRegisterFill:t=>R(e.id,t),onCwdChange:t=>t&&m(r=>({...r,[e.id]:t}))})},e.id))})}),$&&a.jsx("div",{className:"drawer-mask",onClick:()=>B(!1)}),(0,a.jsxs)("aside",{className:`tree-col ${$?"tree-col-open":""}`,style:z.treeCol,children:[(0,a.jsxs)("div",{className:"tree-head",style:z.treeHead,children:[a.jsx("button",{className:"files"===W?"drawer-tab-active":"",onClick:()=>F("files"),children:"文件"}),a.jsx("button",{className:"history"===W?"drawer-tab-active":"",onClick:()=>F("history"),children:"历史"}),a.jsx("span",{className:"tree-cwd",style:z.treeCwd,children:eb??""}),a.jsx("button",{style:{...z.iconBtn,marginLeft:"auto",flexShrink:0},onClick:()=>B(!1),"aria-label":"close drawer",children:a.jsx(p,{size:15,"aria-hidden":"true"})})]}),"files"===W?a.jsx(S,{ready:r>0,followCwd:!0,cwd:eb,rpc:i,onEvent:n,onOpenFile:ef,selectedPath:O,initialRoot:H,initialFollow:q,onTreeStateChange:(e,t)=>{U(e),A(t)}}):a.jsx(x,{csrfToken:e.csrfToken,terminalId:f,onFill:N}),(0,a.jsxs)("div",{style:z.treeFoot,children:[a.jsx("span",{style:z.treeFootDot}),a.jsx("span",{children:"实时同步"})]})]}),O&&a.jsx("section",{className:"preview-col",style:z.previewCol,children:a.jsx(C,{path:O,rpc:i,onClose:()=>I(null)})})]}),!$&&a.jsx("button",{className:"fab-files",style:{...z.fabFiles,left:`${100*X.xRatio}%`,top:`${100*X.yRatio}%`,right:"auto",bottom:"auto",transform:"translate(-50%,-50%)"},onPointerDown:e=>{ea.current={moved:!1,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:e=>{let t=ea.current;if(!t||!t.moved&&4>Math.hypot(e.clientX-t.startX,e.clientY-t.startY))return;t.moved=!0;let r=window.visualViewport;V({xRatio:Math.max(.05,Math.min(.95,e.clientX/(r?.width||innerWidth))),yRatio:Math.max(.08,Math.min(.92,(e.clientY-(r?.offsetTop||0))/(r?.height||innerHeight))),anchor:e.clientX<(r?.width||innerWidth)/2?"left":"right"})},onPointerUp:e=>{e.currentTarget.releasePointerCapture(e.pointerId),ea.current?.moved||B(!0),ea.current=null},"aria-label":"files",children:a.jsx(b,{size:20,"aria-hidden":"true"})})]})}let M=`
|
|
1
|
+
(()=>{var e={};e.id=541,e.ids=[541],e.modules={2934:e=>{"use strict";e.exports=require("next/dist/client/components/action-async-storage.external.js")},4580:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external.js")},5869:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external.js")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},8664:(e,t,r)=>{"use strict";r.r(t),r.d(t,{GlobalError:()=>o.a,__next_app__:()=>p,originalPathname:()=>u,pages:()=>d,routeModule:()=>b,tree:()=>c}),r(6742),r(4972),r(3028);var a=r(1772),i=r(5042),n=r(5663),o=r.n(n),l=r(4812),s={};for(let e in l)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(s[e]=()=>l[e]);r.d(t,s);let c=["",{children:["web",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(r.bind(r,6742)),"/Users/caoqu/team-agent/customer-agent/packages/server/app/web/page.tsx"]}]},{}]},{layout:[()=>Promise.resolve().then(r.bind(r,4972)),"/Users/caoqu/team-agent/customer-agent/packages/server/app/layout.tsx"],"not-found":[()=>Promise.resolve().then(r.t.bind(r,3028,23)),"next/dist/client/components/not-found-error"]}],d=["/Users/caoqu/team-agent/customer-agent/packages/server/app/web/page.tsx"],u="/web/page",p={require:r,loadChunk:()=>Promise.resolve()},b=new a.AppPageRouteModule({definition:{kind:i.x.APP_PAGE,page:"/web/page",pathname:"/web",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:c}})},8490:(e,t,r)=>{Promise.resolve().then(r.t.bind(r,1782,23)),Promise.resolve().then(r.t.bind(r,8949,23)),Promise.resolve().then(r.t.bind(r,6569,23)),Promise.resolve().then(r.t.bind(r,8718,23)),Promise.resolve().then(r.t.bind(r,7415,23)),Promise.resolve().then(r.t.bind(r,8781,23))},3703:(e,t,r)=>{Promise.resolve().then(r.bind(r,5023))},2027:()=>{},1166:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n}});let a=r(7094);r(3517),r(5921);let i=a._(r(4079));function n(e,t){var r;let a={loading:e=>{let{error:t,isLoading:r,pastDelay:a}=e;return null}};"function"==typeof e&&(a.loader=e);let n={...a,...t};return(0,i.default)({...n,modules:null==(r=n.loadableGenerated)?void 0:r.modules})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1803:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"BailoutToCSR",{enumerable:!0,get:function(){return i}});let a=r(93);function i(e){let{reason:t,children:r}=e;throw new a.BailoutToCSRError(t)}},4079:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return c}});let a=r(3517),i=r(5921),n=r(1803),o=r(5259);function l(e){return{default:e&&"default"in e?e.default:e}}let s={loader:()=>Promise.resolve(l(()=>null)),loading:null,ssr:!0},c=function(e){let t={...s,...e},r=(0,i.lazy)(()=>t.loader().then(l)),c=t.loading;function d(e){let l=c?(0,a.jsx)(c,{isLoading:!0,pastDelay:!0,error:null}):null,s=t.ssr?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(o.PreloadCss,{moduleIds:t.modules}),(0,a.jsx)(r,{...e})]}):(0,a.jsx)(n.BailoutToCSR,{reason:"next/dynamic",children:(0,a.jsx)(r,{...e})});return(0,a.jsx)(i.Suspense,{fallback:l,children:s})}return d.displayName="LoadableComponent",d}},5259:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"PreloadCss",{enumerable:!0,get:function(){return n}});let a=r(3517),i=r(4580);function n(e){let{moduleIds:t}=e,r=(0,i.getExpectedRequestStore)("next/dynamic css"),n=[];if(r.reactLoadableManifest&&t){let e=r.reactLoadableManifest;for(let r of t){if(!e[r])continue;let t=e[r].files.filter(e=>e.endsWith(".css"));n.push(...t)}}return 0===n.length?null:(0,a.jsx)(a.Fragment,{children:n.map(e=>(0,a.jsx)("link",{precedence:"dynamic",rel:"stylesheet",href:r.assetPrefix+"/_next/"+encodeURI(e),as:"style"},e))})}},5023:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>P});var a=r(3517),i=r(1166),n=r.n(i),o=r(5921);let l=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),s=(...e)=>e.filter((e,t,r)=>!!e&&""!==e.trim()&&r.indexOf(e)===t).join(" ").trim();var c={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};let d=(0,o.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:a,className:i="",children:n,iconNode:l,...d},u)=>(0,o.createElement)("svg",{ref:u,...c,width:t,height:t,stroke:e,strokeWidth:a?24*Number(r)/Number(t):r,className:s("lucide",i),...d},[...l.map(([e,t])=>(0,o.createElement)(e,t)),...Array.isArray(n)?n:[n]])),u=(e,t)=>{let r=(0,o.forwardRef)(({className:r,...a},i)=>(0,o.createElement)(d,{ref:i,iconNode:t,className:s(`lucide-${l(e)}`,r),...a}));return r.displayName=`${e}`,r},p=u("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),b=u("FolderTree",[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]]);function f({children:e}){let t=function(){let[e,t]=(0,o.useState)("loading"),[r,a]=(0,o.useState)(null),[i]=(0,o.useState)(""),[n,l]=(0,o.useState)(null),s=(0,o.useCallback)(async()=>{t("loading"),l(null);try{let e=await fetch("/api/web-console/bootstrap",{credentials:"same-origin",cache:"no-store"});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=await e.json();a(r.user),t("authenticated")}catch{l("无法连接远程控制台"),t("needsLogin")}},[]),c=(0,o.useCallback)(async()=>{let e=await fetch("/api/web-console/bootstrap",{credentials:"same-origin",cache:"no-store"});if(!e.ok)throw Error("bootstrap failed");let r=await e.json();return a(r.user),t("authenticated"),r.wsNonce},[]),d=(0,o.useCallback)(async()=>!0,[]);return{status:e,user:r,error:n,csrfToken:i,setup:d,login:d,logout:s,refresh:s,getWsNonce:c}}();return"authenticated"===t.status?a.jsx(a.Fragment,{children:e(t)}):a.jsx("main",{style:h.page,children:a.jsx("div",{style:h.card,children:t.error||"正在连接远程控制台…"})})}let h={page:{minHeight:"100dvh",display:"grid",placeItems:"center",background:"#0b0b10",color:"#e8e8ee",fontFamily:'-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif'},card:{color:"#858999",fontSize:13}};function x({csrfToken:e,terminalId:t,onFill:r}){let[i,n]=(0,o.useState)([]),[l,s]=(0,o.useState)(""),c=(0,o.useCallback)(async()=>{let e=new URLSearchParams({q:l,limit:"200"}),t=await fetch(`/api/web-console/history?${e}`,{credentials:"same-origin"});t.ok&&n((await t.json()).history)},[l]),d=async t=>{await fetch("/api/web-console/history",{method:"DELETE",credentials:"same-origin",headers:{"content-type":"application/json","x-csrf-token":e},body:JSON.stringify({id:t})}),c()},u=e=>{t&&r(e)};return(0,a.jsxs)("div",{className:"history-panel",children:[(0,a.jsxs)("div",{className:"history-search",children:[a.jsx("input",{value:l,onChange:e=>s(e.target.value),placeholder:"搜索命令"}),a.jsx("button",{onClick:c,children:"刷新"})]}),i.map(e=>(0,a.jsxs)("div",{className:`history-item${t?"":" history-item-disabled"}`,role:"button",tabIndex:t?0:-1,onClick:()=>u(e.command),onKeyDown:r=>{("Enter"===r.key||" "===r.key)&&t&&(r.preventDefault(),u(e.command))},children:[a.jsx("code",{children:e.command}),(0,a.jsxs)("small",{children:[e.cwd," \xb7 ",new Date(e.executedAt).toLocaleString()]}),(0,a.jsxs)("div",{className:"history-item-actions",onClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),children:[a.jsx("button",{onClick:()=>navigator.clipboard.writeText(e.command),children:"复制"}),a.jsx("button",{disabled:!t,onClick:()=>u(e.command),children:"填入"}),a.jsx("button",{onClick:()=>d(e.id),children:"删除"})]})]},e.id)),!i.length&&a.jsx("div",{className:"history-empty",children:"暂无 Shell 命令历史"}),!t&&!!i.length&&a.jsx("div",{className:"history-empty",children:"请先打开一个终端页签"})]})}var g=r(5878);let m=[{id:"pearl",label:"珍珠白",swatch:"#f5f6fa",preview:["#f5f6fa","#4f6ef7"],cssVars:{"--ui-root-bg":"#f5f6fa","--ui-text":"#111827","--ui-tabbar-bg":"#eef0f6","--ui-tabbar-border":"#dfe3ee","--ui-tab-bg":"#e6e9f4","--ui-tab-text":"#5b6472","--ui-tab-active-bg":"#ffffff","--ui-tab-active-text":"#111827","--ui-tab-accent":"#4f6ef7","--ui-connection-bg":"#eef0f6","--ui-connection-text":"#9ca3af","--ui-tree-bg":"#fbfcfe","--ui-tree-border":"#e5e8f0","--ui-term-col-bg":"#f5f6fa","--ui-fab-bg":"#ffffff","--ui-fab-border":"#d8dcea","--ui-muted-surface":"#eef0f6","--ui-muted-border":"#d8dcea","--ui-muted-text":"#6b7280","--ui-panel-input-bg":"#ffffff","--ui-panel-input-text":"#111827","--ui-panel-input-border":"#d8dcea","--ui-drawer-tab-text":"#6b7280","--ui-drawer-tab-active":"#111827","--ui-history-item-text":"#1f2937","--ui-history-meta":"#9ca3af","--ui-success":"#059669","--ui-error":"#dc2626"},termHostBg:"#ffffff",keybar:{bg:"#eef0f6",border:"#dfe3ee",keyBg:"#ffffff",keyBorder:"#d8dcea",keyText:"#4b5563",accent:"#4f6ef7",accentText:"#ffffff",drag:"#a5b4fc"},xterm:{background:"#ffffff",foreground:"#1f2937",cursor:"#4f6ef7",selectionBackground:"#c7d2fe",black:"#24292e",red:"#d73a49",green:"#22863a",yellow:"#b08800",blue:"#005cc5",magenta:"#6f42c1",cyan:"#1b7c83",white:"#6a737d",brightBlack:"#959da5",brightWhite:"#fafbfc"}},{id:"scifi",label:"科幻霓虹",swatch:"#050a14",preview:["#050a14","#22d3ee"],cssVars:{"--ui-root-bg":"#050a14","--ui-text":"#e2f3ff","--ui-tabbar-bg":"#0a1220","--ui-tabbar-border":"#10263c","--ui-tab-bg":"#0d1626","--ui-tab-text":"#5c7893","--ui-tab-active-bg":"#122036","--ui-tab-active-text":"#e2f3ff","--ui-tab-accent":"#22d3ee","--ui-connection-bg":"#0a1220","--ui-connection-text":"#5c7893","--ui-tree-bg":"#0d1626","--ui-tree-border":"#10263c","--ui-term-col-bg":"#050a14","--ui-fab-bg":"#122036","--ui-fab-border":"#155e75","--ui-muted-surface":"#0d1626","--ui-muted-border":"#164e63","--ui-muted-text":"#9fb8d0","--ui-panel-input-bg":"#0a1220","--ui-panel-input-text":"#e2f3ff","--ui-panel-input-border":"#164e63","--ui-drawer-tab-text":"#5c7893","--ui-drawer-tab-active":"#e2f3ff","--ui-history-item-text":"#d5ecfb","--ui-history-meta":"#5c7893","--ui-success":"#34d399","--ui-error":"#fb7185"},termHostBg:"#0a1220",keybar:{bg:"#0a1220",border:"#10263c",keyBg:"#0d1626",keyBorder:"#164e63",keyText:"#9fb8d0",accent:"#22d3ee",accentText:"#04121a",drag:"#155e75"},xterm:{background:"#0a1220",foreground:"#e2f3ff",cursor:"#22d3ee",selectionBackground:"#164e63",black:"#0d1626",red:"#fb7185",green:"#34d399",yellow:"#fbbf24",blue:"#38bdf8",magenta:"#e879f9",cyan:"#22d3ee",white:"#e2f3ff",brightBlack:"#5c7893",brightWhite:"#ffffff"}},{id:"noir",label:"暗夜黑",swatch:"#0f1115",preview:["#0f1115","#a78bfa"],cssVars:{"--ui-root-bg":"#0f1115","--ui-text":"#eceff4","--ui-tabbar-bg":"#14171d","--ui-tabbar-border":"#232833","--ui-tab-bg":"#191d24","--ui-tab-text":"#6b7280","--ui-tab-active-bg":"#1f242d","--ui-tab-active-text":"#eceff4","--ui-tab-accent":"#a78bfa","--ui-connection-bg":"#14171d","--ui-connection-text":"#6b7280","--ui-tree-bg":"#191d24","--ui-tree-border":"#232833","--ui-term-col-bg":"#0f1115","--ui-fab-bg":"#1f242d","--ui-fab-border":"#2a3040","--ui-muted-surface":"#191d24","--ui-muted-border":"#2a3040","--ui-muted-text":"#aab2bf","--ui-panel-input-bg":"#14171d","--ui-panel-input-text":"#eceff4","--ui-panel-input-border":"#2a3040","--ui-drawer-tab-text":"#6b7280","--ui-drawer-tab-active":"#eceff4","--ui-history-item-text":"#d7dce4","--ui-history-meta":"#6b7280","--ui-success":"#4ade80","--ui-error":"#f87171"},termHostBg:"#14171d",keybar:{bg:"#14171d",border:"#232833",keyBg:"#191d24",keyBorder:"#2a3040",keyText:"#aab2bf",accent:"#a78bfa",accentText:"#0f1115",drag:"#4b4470"},xterm:{background:"#14171d",foreground:"#eceff4",cursor:"#a78bfa",selectionBackground:"#3b3654",black:"#191d24",red:"#f87171",green:"#4ade80",yellow:"#fbbf24",blue:"#60a5fa",magenta:"#c084fc",cyan:"#67e8f9",white:"#eceff4",brightBlack:"#6b7280",brightWhite:"#ffffff"}}],v="pearl",w=Object.fromEntries(m.map(e=>[e.id,e])),y={dark:"noir",black:"noir",gray:"noir",blue:"noir",red:"noir",yellow:"noir",green:"noir",white:"pearl"};function k({username:e,themeId:t,onThemeChange:r,accent:i,accentText:n}){let[l,s]=(0,o.useState)(!1),c=(0,o.useRef)(null),d=(0,o.useRef)(null),u=(0,o.useRef)(null),[p,b]=(0,o.useState)(null),[f,h]=(0,o.useState)(null),x=(e.trim()[0]??"?").toUpperCase();return(0,a.jsxs)("div",{ref:c,className:"theme-picker",children:[a.jsx("button",{ref:d,type:"button",className:"theme-avatar","aria-label":`换肤(${e})`,title:e,"aria-expanded":l,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.preventDefault(),e.stopPropagation(),s(e=>!e)},style:{border:`1px solid ${i}`,background:i,color:n},children:x}),l&&p&&f&&(0,g.createPortal)((0,a.jsxs)("div",{ref:u,className:"theme-popover",role:"dialog","aria-label":"选择皮肤",style:{position:"fixed",top:p.top,left:p.left,zIndex:200,width:176,padding:8,borderRadius:10,border:"1px solid var(--ui-tabbar-border, #282b36)",background:"var(--ui-tab-active-bg, #262b38)",boxShadow:"0 10px 28px rgba(0,0,0,.45)"},children:[a.jsx("div",{style:{fontSize:10,color:"var(--ui-connection-text, #777b8c)",margin:"2px 4px 6px",letterSpacing:.5},children:"皮肤"}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:2},children:m.map(e=>{let i=e.id===t;return(0,a.jsxs)("button",{type:"button",className:"theme-popover-item","aria-label":e.label,"aria-pressed":i,onPointerDown:e=>e.stopPropagation(),onClick:()=>{r(e.id),s(!1)},style:{background:i?"color-mix(in srgb, var(--ui-tab-accent, #7aa2f7) 14%, transparent)":"transparent"},children:[a.jsx("span",{style:{width:18,height:18,borderRadius:5,flexShrink:0,background:`linear-gradient(135deg, ${e.preview[0]} 55%, ${e.preview[1]} 55%)`,boxShadow:"inset 0 0 0 1px rgba(128,128,160,.25)"}}),a.jsx("span",{style:{flex:1,textAlign:"left",fontSize:12,fontWeight:i?600:400,color:i?"var(--ui-tab-active-text, #edf0f7)":"var(--ui-tab-text, #8f93a4)"},children:e.label}),i&&a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"var(--ui-tab-accent, #7aa2f7)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m5 12 4 4L19 6"})})]},e.id)})})]}),f)]})}let j=n()(async()=>{},{loadableGenerated:{modules:["app/web/page.tsx -> ./TerminalPane"]},ssr:!1}),S=n()(async()=>{},{loadableGenerated:{modules:["app/web/page.tsx -> ./FileTree"]},ssr:!1}),C=n()(async()=>{},{loadableGenerated:{modules:["app/web/page.tsx -> ./FilePreview"]},ssr:!1});function P(){return a.jsx(f,{children:e=>a.jsx(R,{auth:e})})}let T={id:"webapp-agent",title:"智能助手",kind:"webapp"};function R({auth:e}){let{state:t,epoch:r,rpc:i,onEvent:n,onTerminalData:l,onTerminalReset:s,sendTerminalInput:c}=function(e,t,r){let[a,i]=(0,o.useState)({connected:!1,error:null}),[n,l]=(0,o.useState)(0),s=(0,o.useRef)(null),c=(0,o.useRef)(0),d=(0,o.useRef)(new Map),u=(0,o.useRef)([]),p=(0,o.useRef)(0),b=(0,o.useRef)(new Map),f=(0,o.useRef)(new Map),h=(0,o.useRef)(new Map),x=(0,o.useRef)(1e3),g=(0,o.useRef)(!1),m=(0,o.useRef)(null),v=(0,o.useRef)(e),w=(0,o.useRef)(t),y=(0,o.useRef)(r);v.current=e,w.current=t,y.current=r;let k=(0,o.useCallback)((e,t)=>{let r=b.current.get(e);return r||b.current.set(e,r=new Set),r.add(t),()=>r.delete(t)},[]),j=(0,o.useCallback)((e,t)=>{let r=f.current.get(e);return r||f.current.set(e,r=new Set),r.add(t),()=>r.delete(t)},[]),S=(0,o.useCallback)((e,t)=>{let r=h.current.get(e);return r||h.current.set(e,r=new Set),r.add(t),()=>r.delete(t)},[]),C=(0,o.useCallback)((e,t)=>{let r=s.current;if(!r||r.readyState!==WebSocket.OPEN)return!1;let a=new TextEncoder().encode(t),i=new Uint8Array(6+a.byteLength),n=new DataView(i.buffer);return i[0]=1,i[1]=1,n.setUint32(2,e),i.set(a,6),r.send(i),!0},[]),P=(0,o.useCallback)(e=>{let t=s.current;t?.readyState===WebSocket.OPEN?t.send(e):u.current.push(e)},[]),T=(0,o.useCallback)((e,t={},r=15e3)=>new Promise((a,i)=>{let n=++p.current,o=setTimeout(()=>{d.current.delete(n),i(Error(`${e} timeout`))},r);d.current.set(n,{resolve:a,reject:i,timer:o}),P(JSON.stringify({type:e,_req:n,...t}))}),[P]),R=(0,o.useCallback)(async()=>{let e,t;g.current=!1;let r=++c.current;m.current&&(clearInterval(m.current),m.current=null);let a=s.current;if(a){a.onopen=a.onmessage=a.onerror=a.onclose=null;try{a.close()}catch{}}try{e=await w.current()}catch{r===c.current&&y.current();return}if(r===c.current&&!g.current){try{t=new WebSocket(`${"https:"===location.protocol?"wss:":"ws:"}//${location.host}/ws?nonce=${encodeURIComponent(e)}`)}catch(e){i({connected:!1,error:String(e)});return}t.binaryType="arraybuffer",s.current=t,t.onopen=()=>{if(r!==c.current||s.current!==t)return;for(let e of(x.current=1e3,i({connected:!0,error:null}),l(e=>e+1),u.current.splice(0)))t.send(e);let e=Date.now();m.current=setInterval(()=>{if(s.current!==t||t.readyState!==WebSocket.OPEN){clearInterval(m.current),m.current=null;return}if(Date.now()-e>25e3){try{t.close()}catch{}return}try{t.send(JSON.stringify({type:"ping"}))}catch{}},1e4);let a=()=>{e=Date.now()};t.addEventListener("message",a),t.addEventListener("close",()=>t.removeEventListener("message",a),{once:!0})},t.onmessage=e=>{let a;if(r===c.current&&s.current===t){if("string"!=typeof e.data){let t=new Uint8Array(e.data);if(t.byteLength>=6&&1===t[0]&&2===t[1]){let e=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(2);f.current.get(e)?.forEach(e=>e(t.subarray(6)))}else if(t.byteLength>=6&&1===t[0]&&3===t[1]){let e=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(2);h.current.get(e)?.forEach(e=>e())}else v.current(t);return}try{a=JSON.parse(e.data)}catch{return}if("error"===a.type&&null!=a.id){let e=d.current.get(a.id);if(e){d.current.delete(a.id),clearTimeout(e.timer);let t=Object.assign(Error(a.error||"gateway error"),{code:a.code});e.reject(t)}return}if(null!=a.id&&"string"==typeof a.type&&a.type.endsWith(":result")){let e=d.current.get(a.id);e&&(d.current.delete(a.id),clearTimeout(e.timer),e.resolve(a));return}b.current.get(a.type)?.forEach(e=>e(a))}},t.onclose=e=>{if(r!==c.current||s.current!==t)return;if(m.current&&(clearInterval(m.current),m.current=null),s.current=null,i({connected:!1,error:null}),4001===e.code||4003===e.code){y.current();return}if(g.current)return;let a=x.current;x.current=Math.min(2*a,8e3),setTimeout(()=>{g.current||r!==c.current||R()},a)},t.onerror=()=>{}}},[]);return{state:a,epoch:n,rpc:T,onEvent:k,onTerminalData:j,onTerminalReset:S,sendTerminalInput:C,reconnect:R}}(()=>{},e.getWsNonce,e.refresh),[d,u]=(0,o.useState)([{...T}]),[f,h]=(0,o.useState)(T.id),[g,m]=(0,o.useState)({});(0,o.useRef)(!1),(0,o.useRef)(null);let P=(0,o.useRef)(new Map),R=(0,o.useCallback)((e,t)=>(P.current.set(e,t),()=>P.current.delete(e)),[]),N=(0,o.useCallback)(e=>{if(!f)return;let t=P.current.get(f);t?t(e):i("term:input",{id:f,data:`\x15${e}`}).catch(()=>{}),B(!1)},[f,i]),[D,E]=(0,o.useState)(!1),[_,L]=(0,o.useState)({}),[O,I]=(0,o.useState)(null),[$,B]=(0,o.useState)(!1),[W,F]=(0,o.useState)("files"),[H,q]=(0,o.useState)(null),[U,A]=(0,o.useState)(!0),[X,V]=(0,o.useState)(null),[G,Y]=(0,o.useState)({xRatio:.94,yRatio:.65,anchor:"right"}),[J,K]=(0,o.useState)(!1),[Z,Q]=(0,o.useState)([]),[ee,et]=(0,o.useState)(v),[er,ea]=(0,o.useState)(!1),ei=function(e){if(e&&e in w)return w[e];let t=e?y[e]:void 0;return t?w[t]:w[v]}(ee),en=(0,o.useRef)(null),eo=(0,o.useRef)(null),[el,es]=(0,o.useState)(0),[ec,ed]=(0,o.useState)(!1),eu=(0,o.useRef)(null),ep=(0,o.useRef)(null),eb=(0,o.useRef)(null),ef=(0,o.useCallback)(e=>{eb.current?.contentWindow?.postMessage({type:"agent-web-shell:skin:v1",skin:e},window.location.origin)},[]);(0,o.useRef)(0);let eh=f?g[f]??null:null;(0,o.useCallback)(t=>{fetch("/api/web-console/preferences",{method:"PATCH",credentials:"same-origin",headers:{"content-type":"application/json","x-csrf-token":e.csrfToken},body:JSON.stringify(t)}).catch(()=>{})},[e.csrfToken]),(0,o.useCallback)(t=>{e.csrfToken&&fetch("/api/web-console/device-state",{method:"PUT",credentials:"same-origin",headers:{"content-type":"application/json","x-csrf-token":e.csrfToken},body:JSON.stringify(t)}).catch(()=>{})},[e.csrfToken]);let ex=(0,o.useCallback)(e=>{I(e),B(!1)},[]),eg=(0,o.useCallback)(()=>{let e=null;u(t=>t.length>=8?t:[...t,{id:e=`t-web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,title:`Terminal ${t.length+1}`}]),e&&h(e)},[]),em=e=>{e!==T.id&&window.confirm("关闭页签会终止该终端进程,确认关闭?")&&(u(t=>{let r=t.filter(t=>t.id!==e);return f===e&&h(r[0]?.id??null),r}),i("term:kill",{id:e}).catch(()=>{}))},ev=(0,o.useCallback)(e=>{if(!f||d.length<2)return;let t=(d.findIndex(e=>e.id===f)+e+d.length)%d.length;h(d[t].id)},[f,d]),ew=Math.max(0,d.findIndex(e=>e.id===f)),ey=d[ew]?.kind==="webapp"?ei.cssVars["--ui-term-col-bg"]:ei.termHostBg,ek={...z.root,...ei.cssVars,"--ui-active-content-bg":ey,"--ui-terminal-bg":ei.termHostBg,background:"var(--ui-root-bg)",color:"var(--ui-text)"},ej=(0,o.useCallback)(()=>{eo.current=null,es(0),ed(!1)},[]),eS=(0,o.useCallback)(e=>{Math.abs(e)>=64&&d.length>1&&ev(e<0?1:-1),ej()},[d.length,ev,ej]),eC=e=>e instanceof Element&&!!e.closest(".terminal-screen");return(0,o.useCallback)((e="smooth")=>{let t=ep.current;if(!t||!f)return;let r=t.querySelector(`[data-terminal-id="${f}"]`);if(!r)return;if(r===t.querySelector("[data-terminal-id]")){t&&(t.scrollLeft=0);return}let a=t.querySelector(".terminal-connection"),i=a?.offsetWidth??0,n=r.offsetLeft,o=n+r.offsetWidth,l=t.scrollLeft,s=l+t.clientWidth-i;n<l+8?t.scrollTo({left:Math.max(0,n-8),behavior:e}):o>s-8&&t.scrollTo({left:o-t.clientWidth+i+8,behavior:e})},[f]),(0,a.jsxs)("div",{className:"web-root",style:ek,children:[a.jsx("style",{dangerouslySetInnerHTML:{__html:M}}),(0,a.jsxs)("div",{className:"terminal-tabs",ref:ep,children:[d.map(e=>(0,a.jsxs)("div",{"data-terminal-id":e.id,draggable:!0,className:`terminal-tab ${e.id===f?"active":""}`,onDragStart:()=>{eu.current=e.id},onDragOver:e=>e.preventDefault(),onDrop:t=>{t.preventDefault();let r=eu.current;eu.current=null,r&&r!==e.id&&u(t=>{let a=t.findIndex(e=>e.id===r),n=t.findIndex(t=>t.id===e.id);if(a<0||n<0)return t;let o=[...t],[l]=o.splice(a,1);return o.splice(n,0,l),i("term:reorder",{ids:o.map(e=>e.id).filter(e=>e!==T.id)}).catch(()=>{}),o})},onClick:()=>h(e.id),onDoubleClick:()=>{if("webapp"===e.kind)return;let t=window.prompt("页签名称",e.title)?.trim();t&&i("term:rename",{id:e.id,title:t}).then(()=>u(r=>r.map(r=>r.id===e.id?{...r,title:t}:r))).catch(()=>{})},children:[a.jsx("span",{children:e.title}),"webapp"!==e.kind&&a.jsx("button",{tabIndex:-1,onClick:t=>{t.stopPropagation(),em(e.id)},children:"\xd7"})]},e.id)),a.jsx("button",{className:"terminal-add",disabled:d.length>=8,onClick:eg,children:"+"}),(0,a.jsxs)("div",{className:"terminal-connection",children:[a.jsx("span",{style:{width:8,height:8,borderRadius:99,background:t.connected?"var(--ui-success)":"var(--ui-error)"}}),a.jsx(k,{username:e.user?.username??"?",themeId:ee,onThemeChange:et,accent:ei.keybar.accent,accentText:ei.keybar.accentText})]})]}),(0,a.jsxs)("main",{className:`workspace ${$?"show-tree":""} ${O?"has-preview":""}`,style:z.workspace,children:[a.jsx("section",{className:"term-col",style:z.termCol,onPointerDownCapture:e=>{"touch"===e.pointerType&&eC(e.target)&&(eo.current={x:e.clientX,y:e.clientY,axis:"pending"})},onPointerMoveCapture:e=>{let t=eo.current;if(!t||"touch"!==e.pointerType)return;let r=e.clientX-t.x,a=e.clientY-t.y;if("pending"===t.axis){if(8>=Math.max(Math.abs(r),Math.abs(a)))return;if(Math.abs(a)>=1.2*Math.abs(r)){eo.current=null;return}t.axis="horizontal",ed(!0)}"horizontal"===t.axis&&(e.preventDefault(),es(r))},onPointerUpCapture:e=>{let t=eo.current;if(!t||"touch"!==e.pointerType)return;let r=e.clientX-t.x;"horizontal"===t.axis&&Math.abs(r)>=64?eS(r):ej()},onPointerCancelCapture:ej,children:a.jsx("div",{className:"terminal-track",style:{transform:`translate3d(calc(${-(100*ew)}% + ${el}px),0,0)`,transition:ec?"none":"transform 260ms cubic-bezier(.22,.8,.32,1)"},children:d.map(e=>a.jsx("div",{className:"terminal-slide",children:"webapp"===e.kind?a.jsx("iframe",{ref:eb,src:"/app/",title:e.title,onLoad:()=>ef(ee),style:{width:"100%",height:"100%",border:"0",background:"var(--ui-term-col-bg, #101014)"}}):a.jsx(j,{terminalId:e.id,title:e.title,visible:e.id===f,state:t,rpc:i,onEvent:n,onTerminalData:l,onTerminalReset:s,sendTerminalInput:c,keyOrder:Z,keybarHidden:J,onKeyOrderChange:Q,onKeybarHiddenChange:K,terminalTheme:ei,initialScrollLine:_[e.id]??null,onScrollLineChange:t=>L(r=>r[e.id]===t?r:{...r,[e.id]:t}),onRegisterFill:t=>R(e.id,t),onCwdChange:t=>t&&m(r=>({...r,[e.id]:t}))})},e.id))})}),$&&a.jsx("div",{className:"drawer-mask",onClick:()=>B(!1)}),(0,a.jsxs)("aside",{className:`tree-col ${$?"tree-col-open":""}`,style:z.treeCol,children:[(0,a.jsxs)("div",{className:"tree-head",style:z.treeHead,children:[a.jsx("button",{className:"files"===W?"drawer-tab-active":"",onClick:()=>F("files"),children:"文件"}),a.jsx("button",{className:"history"===W?"drawer-tab-active":"",onClick:()=>F("history"),children:"历史"}),a.jsx("span",{className:"tree-cwd",style:z.treeCwd,children:eh??""}),a.jsx("button",{style:{...z.iconBtn,marginLeft:"auto",flexShrink:0},onClick:()=>B(!1),"aria-label":"close drawer",children:a.jsx(p,{size:15,"aria-hidden":"true"})})]}),"files"===W?a.jsx(S,{ready:r>0,followCwd:!0,cwd:eh,rpc:i,onEvent:n,onOpenFile:ex,selectedPath:O,initialRoot:H,initialFollow:U,revealRequest:X,onTreeStateChange:(e,t)=>{q(e),A(t)}}):a.jsx(x,{csrfToken:e.csrfToken,terminalId:f,onFill:N}),(0,a.jsxs)("div",{style:z.treeFoot,children:[a.jsx("span",{style:z.treeFootDot}),a.jsx("span",{children:"实时同步"})]})]}),O&&a.jsx("section",{className:"preview-col",style:z.previewCol,children:a.jsx(C,{path:O,rpc:i,onClose:()=>I(null)})})]}),!$&&a.jsx("button",{className:"fab-files",style:{...z.fabFiles,left:`${100*G.xRatio}%`,top:`${100*G.yRatio}%`,right:"auto",bottom:"auto",transform:"translate(-50%,-50%)"},onPointerDown:e=>{en.current={moved:!1,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:e=>{let t=en.current;if(!t||!t.moved&&4>Math.hypot(e.clientX-t.startX,e.clientY-t.startY))return;t.moved=!0;let r=window.visualViewport;Y({xRatio:Math.max(.05,Math.min(.95,e.clientX/(r?.width||innerWidth))),yRatio:Math.max(.08,Math.min(.92,(e.clientY-(r?.offsetTop||0))/(r?.height||innerHeight))),anchor:e.clientX<(r?.width||innerWidth)/2?"left":"right"})},onPointerUp:e=>{e.currentTarget.releasePointerCapture(e.pointerId),en.current?.moved||B(!0),en.current=null},"aria-label":"files",children:a.jsx(b,{size:20,"aria-hidden":"true"})})]})}let M=`
|
|
2
2
|
html, body { width:100%; height:100%; margin:0; overflow:hidden; background:var(--ui-root-bg, #0b0b10); overscroll-behavior:none; color:var(--ui-text, #e8e8ee); }
|
|
3
3
|
* { -webkit-tap-highlight-color: transparent; }
|
|
4
4
|
.terminal-tabs { display:flex; align-items:end; gap:4px; min-height:38px; padding:0 8px; overflow-x:auto; overflow-y:hidden; touch-action:pan-x; overscroll-behavior-x:contain; -webkit-overflow-scrolling:touch; scroll-behavior:smooth; background:var(--ui-tabbar-bg, #12141b); border-bottom:0; scrollbar-width:none; flex-shrink:0; }
|