aws-runtime-bridge 1.9.98 → 1.9.100

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.
Files changed (120) hide show
  1. package/dist/adapter/AcodeSdkAdapter.d.ts +7 -1
  2. package/dist/adapter/AcodeSdkAdapter.js +5 -5
  3. package/dist/adapter/ClaudeSdkAdapter.d.ts +4 -0
  4. package/dist/adapter/ClaudeSdkAdapter.js +2 -2
  5. package/dist/adapter/CodexSdkAdapter.d.ts +2 -0
  6. package/dist/adapter/CodexSdkAdapter.js +3 -3
  7. package/dist/adapter/OpencodeSdkAdapter.d.ts +2 -0
  8. package/dist/adapter/OpencodeSdkAdapter.js +2 -2
  9. package/dist/adapter/idle-poll-loop.d.ts +4 -1
  10. package/dist/adapter/idle-poll-loop.js +1 -1
  11. package/dist/adapter/types.d.ts +4 -2
  12. package/dist/browser/browser-pool.d.ts +73 -0
  13. package/dist/browser/browser-pool.js +2 -0
  14. package/dist/browser/browser-profile-store.d.ts +28 -0
  15. package/dist/browser/browser-profile-store.js +2 -0
  16. package/dist/browser/built-in-browser-tools.d.ts +27 -0
  17. package/dist/browser/built-in-browser-tools.js +2 -0
  18. package/dist/browser/element-locator.d.ts +24 -0
  19. package/dist/browser/element-locator.js +2 -0
  20. package/dist/browser/element-picker.d.ts +17 -0
  21. package/dist/browser/element-picker.js +2 -0
  22. package/dist/browser/input-dispatcher.d.ts +34 -0
  23. package/dist/browser/input-dispatcher.js +2 -0
  24. package/dist/browser/listener-store.d.ts +32 -0
  25. package/dist/browser/listener-store.js +2 -0
  26. package/dist/browser/page-listener-manager.d.ts +106 -0
  27. package/dist/browser/page-listener-manager.js +307 -0
  28. package/dist/browser/page-listener-types.d.ts +90 -0
  29. package/dist/browser/page-listener-types.js +1 -0
  30. package/dist/browser/screencast-manager.d.ts +42 -0
  31. package/dist/browser/screencast-manager.js +2 -0
  32. package/dist/browser/snapshot-serializer.d.ts +15 -0
  33. package/dist/browser/snapshot-serializer.js +5 -0
  34. package/dist/browser/ssrf-guard.d.ts +15 -0
  35. package/dist/browser/ssrf-guard.js +2 -0
  36. package/dist/browser/stealth.d.ts +7 -0
  37. package/dist/browser/stealth.js +173 -0
  38. package/dist/browser/step-archive.d.ts +52 -0
  39. package/dist/browser/step-archive.js +2 -0
  40. package/dist/browser/types.d.ts +192 -0
  41. package/dist/browser/types.js +2 -0
  42. package/dist/browser/ws-server.d.ts +67 -0
  43. package/dist/browser/ws-server.js +2 -0
  44. package/dist/index.js +1 -1
  45. package/dist/middleware/auth.d.ts +2 -0
  46. package/dist/middleware/auth.js +1 -1
  47. package/dist/remote-desktop/computer-control.d.ts +30 -0
  48. package/dist/remote-desktop/computer-control.js +2 -0
  49. package/dist/remote-desktop/coords.d.ts +13 -0
  50. package/dist/remote-desktop/coords.js +2 -0
  51. package/dist/remote-desktop/frame-backpressure.d.ts +7 -0
  52. package/dist/remote-desktop/frame-backpressure.js +2 -0
  53. package/dist/remote-desktop/index.d.ts +7 -0
  54. package/dist/remote-desktop/index.js +4 -0
  55. package/dist/remote-desktop/input-backends/interface.d.ts +17 -0
  56. package/dist/remote-desktop/input-backends/interface.js +1 -0
  57. package/dist/remote-desktop/input-backends/key-map.d.ts +2 -0
  58. package/dist/remote-desktop/input-backends/key-map.js +2 -0
  59. package/dist/remote-desktop/input-dispatcher.d.ts +11 -0
  60. package/dist/remote-desktop/input-dispatcher.js +2 -0
  61. package/dist/remote-desktop/permission-manager.d.ts +7 -0
  62. package/dist/remote-desktop/permission-manager.js +2 -0
  63. package/dist/remote-desktop/screen-capture.d.ts +27 -0
  64. package/dist/remote-desktop/screen-capture.js +2 -0
  65. package/dist/remote-desktop/session-manager.d.ts +59 -0
  66. package/dist/remote-desktop/session-manager.js +2 -0
  67. package/dist/remote-desktop/system-backend.d.ts +65 -0
  68. package/dist/remote-desktop/system-backend.js +5 -0
  69. package/dist/remote-desktop/types.d.ts +68 -0
  70. package/dist/remote-desktop/types.js +1 -0
  71. package/dist/remote-desktop/ui-automation.d.ts +48 -0
  72. package/dist/remote-desktop/ui-automation.js +31 -0
  73. package/dist/remote-desktop/win32-api.d.ts +29 -0
  74. package/dist/remote-desktop/win32-api.js +2 -0
  75. package/dist/routes/background-tasks.d.ts +2 -0
  76. package/dist/routes/background-tasks.js +2 -0
  77. package/dist/routes/browser-listeners.d.ts +2 -0
  78. package/dist/routes/browser-listeners.js +2 -0
  79. package/dist/routes/browser-sessions.d.ts +2 -0
  80. package/dist/routes/browser-sessions.js +2 -0
  81. package/dist/routes/pty.js +3 -3
  82. package/dist/routes/terminal.js +30 -30
  83. package/dist/services/agent-pty-manager.d.ts +22 -0
  84. package/dist/services/agent-pty-manager.js +5 -0
  85. package/dist/services/browser-session-manager.d.ts +55 -0
  86. package/dist/services/browser-session-manager.js +12 -0
  87. package/dist/services/cli-commands.d.ts +4 -0
  88. package/dist/services/cli-commands.js +5 -5
  89. package/package/acode/dist/await-complete-tool.d.ts +17 -0
  90. package/package/acode/dist/await-complete-tool.js +21 -0
  91. package/package/acode/dist/background-command-manager.d.ts +148 -0
  92. package/package/acode/dist/background-command-manager.js +8 -0
  93. package/package/acode/dist/background-command-store.d.ts +46 -0
  94. package/package/acode/dist/background-command-store.js +2 -0
  95. package/package/acode/dist/background-command-tools.d.ts +5 -0
  96. package/package/acode/dist/background-command-tools.js +18 -0
  97. package/package/acode/dist/background-output-ringbuffer.d.ts +23 -0
  98. package/package/acode/dist/background-output-ringbuffer.js +3 -0
  99. package/package/acode/dist/built-in-file-tools.d.ts +8 -1
  100. package/package/acode/dist/built-in-file-tools.js +2 -2
  101. package/package/acode/dist/compaction.js +6 -6
  102. package/package/acode/dist/index.d.ts +1 -0
  103. package/package/acode/dist/index.js +1 -1
  104. package/package/acode/dist/runtime.d.ts +6 -0
  105. package/package/acode/dist/runtime.js +27 -27
  106. package/package/acode/dist/sub-agent-tools.d.ts +0 -1
  107. package/package/acode/dist/sub-agent-tools.js +11 -28
  108. package/package/acode/dist/terminal-tool.d.ts +7 -0
  109. package/package/acode/dist/terminal-tool.js +2 -0
  110. package/package/acode/dist/terminal-types.d.ts +38 -0
  111. package/package/acode/dist/terminal-types.js +1 -0
  112. package/package/acode/dist/types.d.ts +10 -1
  113. package/package/aws-client-agent-mcp/dist/agent-client.d.ts +3 -1
  114. package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
  115. package/package/aws-client-agent-mcp/dist/logger.d.ts +2 -0
  116. package/package/aws-client-agent-mcp/dist/logger.js +1 -1
  117. package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +8 -0
  118. package/package/aws-client-agent-mcp/dist/mcp-server.js +30 -19
  119. package/package/aws-client-agent-mcp/dist/types.d.ts +25 -0
  120. package/package.json +6 -2
@@ -1,6 +1,6 @@
1
- import O from"node:crypto";import I from"node:fs";import l from"node:path";import{Router as L}from"express";import*as D from"node-pty";import{v4 as M}from"uuid";import U,{WebSocketServer as z}from"ws";import{isRuntimeTokenValid as _,validateToken as h}from"../middleware/auth.js";import{createLogger as R}from"../utils/logger.js";const p=R("pty"),j=80,W=24,x=2e5,$=30*60*1e3,v=5*60*1e3,E=60*1e3,b=8,B=new Set(["false","halt","nologin","reboot","shutdown","sync","true"]),a=new Map,w=new Map;function F(e=process.env){const t=String(e.AWS_PTY_IDLE_TTL_MS||"").trim();if(!t)return $;const r=Number(t);return!Number.isFinite(r)||r<1e3?$:r}function Y(e=process.platform,t=process.env,r=I.existsSync){return e==="win32"?{shell:String(t.ComSpec||t.COMSPEC||"").trim()||"powershell.exe",args:[]}:{shell:[String(t.SHELL||"").trim(),"/bin/bash","/bin/sh"].find(s=>X(s,r))||"/bin/sh",args:[]}}function X(e,t){const r=e.trim();if(!r)return!1;const n=l.basename(r).toLowerCase();return B.has(n)?!1:!l.isAbsolute(r)||t(r)}function H(e,t=process.platform,r=process.env){const n=String(e||"auto").trim();if(!n||n==="auto")return Y(t,r);const i=new Set(["bash","sh","zsh","fish","pwsh","pwsh.exe","powershell","powershell.exe","cmd","cmd.exe"]),s=l.basename(n).toLowerCase();if(!i.has(s))throw new Error(`shell is not allowed: ${n}`);return{shell:n,args:[]}}function J(e,t){const r=l.relative(l.resolve(t),l.resolve(e));return r===""||!r.startsWith("..")&&!l.isAbsolute(r)}function V(e=process.env){return String(e.AWS_PTY_ALLOWED_ROOTS||"").split(l.delimiter).map(t=>t.trim()).filter(Boolean).map(t=>l.resolve(t))}function K(e,t=process.env){const r=String(e||"").trim();if(!r)throw new Error("workspacePath is required");if(!l.isAbsolute(r))throw new Error("workspacePath must be absolute");const n=l.resolve(r);if(!I.statSync(n).isDirectory())throw new Error("workspacePath must be an existing directory");const s=V(t);if(s.length>0&&!s.some(c=>J(n,c)))throw new Error("workspacePath is outside allowed roots");return n}function T(e,t){const r=Number(e);return!Number.isInteger(r)||r<=0?t:Math.min(r,500)}function q(e){return{...e,TERM:e.TERM||"xterm-256color",COLORTERM:e.COLORTERM||"truecolor"}}function G(e,t){e.outputBuffer=`${e.outputBuffer}${t}`,e.outputBuffer.length>x&&(e.outputBuffer=e.outputBuffer.slice(-x))}function g(e){return{id:e.id,title:e.title,workspacePath:e.workspacePath,shell:e.shell,cols:e.cols,rows:e.rows,status:e.status,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,exitCode:e.exitCode,signal:e.signal,attachedClients:e.sockets.size,ownerUserId:e.ownerUserId,tenantId:e.tenantId,projectName:e.projectName}}function k(e,t){e.readyState===U.OPEN&&e.send(JSON.stringify(t))}function P(e,t){for(const r of e.sockets)k(r,t)}function A(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{e.sockets.size===0&&S(e.id,"idle-timeout")},F())}function C(e){e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=null)}function Q(e){if(a.size>=re())throw new Error("maximum PTY sessions reached");const t=K(e.workspacePath),r=H(e.shell),n=T(e.cols,j),i=T(e.rows,W),s=`pty_${M()}`,c=new Date().toISOString(),m=String(e.title||"").trim()||`Terminal ${a.size+1}`,u=D.spawn(r.shell,r.args,{name:"xterm-256color",cols:n,rows:i,cwd:t,env:q(process.env)}),o={id:s,title:m,workspacePath:t,shell:r.shell,cols:n,rows:i,status:"running",createdAt:c,lastActiveAt:c,attachedClients:0,ptyProcess:u,sockets:new Set,outputBuffer:"",idleTimer:null,persistent:e.persistent===!0,ownerUserId:String(e.ownerUserId||"").trim()||void 0,tenantId:String(e.tenantId||"").trim()||void 0,projectName:String(e.projectName||"").trim()||void 0};return u.onData(f=>{o.lastActiveAt=new Date().toISOString(),G(o,f),P(o,{type:"output",data:f})}),u.onExit(({exitCode:f,signal:d})=>{o.status="exited",o.exitCode=f,o.signal=d,o.lastActiveAt=new Date().toISOString(),P(o,{type:"exit",exitCode:f,signal:d}),o.sockets.size===0&&!o.persistent?A(o):o.persistent&&(o.idleTimer&&clearTimeout(o.idleTimer),o.idleTimer=setTimeout(()=>{S(o.id,"exited-timeout")},te()))}),a.set(s,o),o.persistent||A(o),Z(o,e.preCommand),p.info(`created pty session id=${s}, cwd=${t}, shell=${r.shell}`),g(o)}function Z(e,t){const r=typeof t=="string"?t:"";if(!r.trim())return;const n=`${r.replace(/\n/g,"\r").replace(/\r+$/g,"")}\r`;try{e.ptyProcess.write(n)}catch(i){const s=i;p.warn(`failed to inject pty pre-command sessionId=${e.id}: ${s.message}`)}}function ee(e=process.env){const t=String(e.AWS_PTY_CONNECT_TOKEN_TTL_MS||"").trim();if(!t)return E;const r=Number(t);return!Number.isFinite(r)||r<5e3||r>10*60*1e3?E:r}function te(e=process.env){const t=String(e.AWS_PTY_EXITED_TTL_MS||"").trim();if(!t)return v;const r=Number(t);return!Number.isFinite(r)||r<1e3?v:r}function re(e=process.env){const t=String(e.AWS_PTY_MAX_SESSIONS||"").trim();if(!t)return b;const r=Number(t);return!Number.isInteger(r)||r<1||r>100?b:r}function ne(e){if(!e||typeof e!="object")return{workspacePath:void 0};const t=e;return{workspacePath:t.workspacePath,title:t.title,shell:t.shell,cols:t.cols,rows:t.rows,persistent:t.persistent,preCommand:t.preCommand,ownerUserId:t.ownerUserId,tenantId:t.tenantId,projectName:t.projectName}}function oe(){return Array.from(a.values()).map(g)}function se(e){const t=a.get(e);return t?g(t):void 0}function ie(e){if(!a.has(e))return;const t=`ptyws_${O.randomBytes(32).toString("base64url")}`,r=Date.now()+ee();return w.set(t,{sessionId:e,expiresAt:r}),{token:t,expiresAt:new Date(r).toISOString()}}function ae(e,t){const r=w.get(t);return r?r.expiresAt<Date.now()?(w.delete(t),p.warn(`[pty-ws] consumePtyConnectToken: token \u5DF2\u8FC7\u671F, sessionId=${e}, expiredAt=${new Date(r.expiresAt).toISOString()}`),!1):r.sessionId!==e?(p.warn(`[pty-ws] consumePtyConnectToken: sessionId \u4E0D\u5339\u914D, expected=${r.sessionId}, actual=${e}`),!1):(w.delete(t),p.info(`[pty-ws] consumePtyConnectToken: \u6210\u529F, sessionId=${e}`),!0):(p.warn(`[pty-ws] consumePtyConnectToken: token \u4E0D\u5B58\u5728, sessionId=${e}, ptyConnectTokens.size=${w.size}`),!1)}function ce(e){for(const[t,r]of w.entries())r.sessionId===e&&w.delete(t)}function S(e,t="closed"){const r=a.get(e);if(!r)return!1;C(r),ce(e),P(r,{type:"status",status:"closing",reason:t});for(const n of r.sockets)n.close(1e3,t);return r.sockets.clear(),r.status==="running"&&r.ptyProcess.kill(),a.delete(e),p.info(`closed pty session id=${e}, reason=${t}`),!0}function ge(e="shutdown"){for(const t of Array.from(a.keys()))S(t,e)}const y=L();y.get("/sessions",h,(e,t)=>{t.json({ok:!0,sessions:oe()})}),y.post("/sessions",h,(e,t)=>{try{const r=Q(ne(e.body));t.status(201).json({ok:!0,session:r})}catch(r){const n=r;t.status(400).json({error:n.message})}}),y.get("/sessions/:sessionId",h,(e,t)=>{const r=se(e.params.sessionId);if(!r){t.status(404).json({error:"pty session not found"});return}t.json({ok:!0,session:r})}),y.delete("/sessions/:sessionId",h,(e,t)=>{if(!S(e.params.sessionId,"explicit-close")){t.status(404).json({error:"pty session not found"});return}t.json({ok:!0})}),y.post("/sessions/:sessionId/connect-token",h,(e,t)=>{const r=ie(e.params.sessionId);if(!r){t.status(404).json({error:"pty session not found"});return}t.json({ok:!0,...r})});function ue(e){const t=e.toString();try{return JSON.parse(t)}catch{return{type:"input",data:t}}}function le(e,t){C(e),e.sockets.add(t),e.lastActiveAt=new Date().toISOString(),k(t,{type:"status",status:e.status,session:g(e)}),e.outputBuffer&&k(t,{type:"output",data:e.outputBuffer,replay:!0}),t.on("message",r=>{const n=ue(r);if(!n||typeof n!="object")return;const i=n,s=String(i.type||"");if(e.lastActiveAt=new Date().toISOString(),s==="input"){e.ptyProcess.write(String(i.data||""));return}if(s==="resize"){const c=T(i.cols,e.cols),m=T(i.rows,e.rows);e.cols=c,e.rows=m,e.ptyProcess.resize(c,m);return}if(s==="close"){S(e.id,"client-close");return}s==="ping"&&k(t,{type:"pong"})}),t.on("close",()=>{e.sockets.delete(t),e.lastActiveAt=new Date().toISOString(),e.sockets.size===0&&e.status==="running"&&!e.persistent&&A(e)})}function pe(e,t){const r=t.searchParams.get("token")||"";if(r.trim())return r.trim();const n=e.headers["x-runtime-token"];return Array.isArray(n)?n[0]?.trim()||"":typeof n=="string"?n.trim():String(e.headers.authorization||"").match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||""}function ke(e){const t=new z({noServer:!0});e.on("upgrade",(r,n,i)=>{const s=r.headers.host||"localhost",c=new URL(r.url||"/",`http://${s}`),m=c.pathname.match(/^\/pty\/sessions\/([^/]+)\/stream$/);if(!m)return;const u=pe(r,c),o=decodeURIComponent(m[1]||""),f=u?u.length>12?u.substring(0,12)+"...":u:"empty";if(p.info(`[pty-ws] upgrade \u8BF7\u6C42: sessionId=${o}, token=${f}, pathname=${c.pathname}`),!_(u)&&!ae(o,u)){p.warn(`[pty-ws] token \u6821\u9A8C\u5931\u8D25: sessionId=${o}, token=${f}, runtimeTokenValid=${_(u)}, ptySessions.size=${a.size}`),n.write(`HTTP/1.1 401 Unauthorized\r
1
+ import O from"node:crypto";import I from"node:fs";import l from"node:path";import{Router as L}from"express";import*as D from"node-pty";import{v4 as M}from"uuid";import U,{WebSocketServer as z}from"ws";import{isRuntimeTokenValid as x,validateToken as h}from"../middleware/auth.js";import{createLogger as R}from"../utils/logger.js";const p=R("pty"),j=80,W=24,_=2e5,E=30*60*1e3,$=5*60*1e3,v=60*1e3,b=8,F=new Set(["false","halt","nologin","reboot","shutdown","sync","true"]),a=new Map,w=new Map;function B(e=process.env){const t=String(e.AWS_PTY_IDLE_TTL_MS||"").trim();if(!t)return E;const r=Number(t);return!Number.isFinite(r)||r<1e3?E:r}function Y(e=process.platform,t=process.env,r=I.existsSync){return e==="win32"?{shell:String(t.ComSpec||t.COMSPEC||"").trim()||"powershell.exe",args:[]}:{shell:[String(t.SHELL||"").trim(),"/bin/bash","/bin/sh"].find(o=>X(o,r))||"/bin/sh",args:[]}}function X(e,t){const r=e.trim();if(!r)return!1;const n=l.basename(r).toLowerCase();return F.has(n)?!1:!l.isAbsolute(r)||t(r)}function H(e,t=process.platform,r=process.env){const n=String(e||"auto").trim();if(!n||n==="auto")return Y(t,r);const i=new Set(["bash","sh","zsh","fish","pwsh","pwsh.exe","powershell","powershell.exe","cmd","cmd.exe"]),o=(t==="win32"?l.win32.basename(n):l.basename(n)).toLowerCase();if(!i.has(o))throw new Error(`shell is not allowed: ${n}`);return{shell:/^[A-Za-z]:[\\/]/.test(n)||n.startsWith("\\")||n.startsWith("/")?n:t==="win32"?{cmd:"cmd.exe",powershell:"powershell.exe",pwsh:"pwsh.exe"}[o]??n:n,args:[]}}function J(e,t){const r=l.relative(l.resolve(t),l.resolve(e));return r===""||!r.startsWith("..")&&!l.isAbsolute(r)}function V(e=process.env){return String(e.AWS_PTY_ALLOWED_ROOTS||"").split(l.delimiter).map(t=>t.trim()).filter(Boolean).map(t=>l.resolve(t))}function K(e,t=process.env){const r=String(e||"").trim();if(!r)throw new Error("workspacePath is required");if(!l.isAbsolute(r))throw new Error("workspacePath must be absolute");const n=l.resolve(r);if(!I.statSync(n).isDirectory())throw new Error("workspacePath must be an existing directory");const o=V(t);if(o.length>0&&!o.some(c=>J(n,c)))throw new Error("workspacePath is outside allowed roots");return n}function T(e,t){const r=Number(e);return!Number.isInteger(r)||r<=0?t:Math.min(r,500)}function q(e){return{...e,TERM:e.TERM||"xterm-256color",COLORTERM:e.COLORTERM||"truecolor"}}function Z(e,t){e.outputBuffer=`${e.outputBuffer}${t}`,e.outputBuffer.length>_&&(e.outputBuffer=e.outputBuffer.slice(-_))}function g(e){return{id:e.id,title:e.title,workspacePath:e.workspacePath,shell:e.shell,cols:e.cols,rows:e.rows,status:e.status,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,exitCode:e.exitCode,signal:e.signal,attachedClients:e.sockets.size,ownerUserId:e.ownerUserId,tenantId:e.tenantId,projectName:e.projectName}}function k(e,t){e.readyState===U.OPEN&&e.send(JSON.stringify(t))}function P(e,t){for(const r of e.sockets)k(r,t)}function A(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{e.sockets.size===0&&S(e.id,"idle-timeout")},B())}function C(e){e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=null)}function G(e){if(a.size>=re())throw new Error("maximum PTY sessions reached");const t=K(e.workspacePath),r=H(e.shell),n=T(e.cols,j),i=T(e.rows,W),o=`pty_${M()}`,c=new Date().toISOString(),d=String(e.title||"").trim()||`Terminal ${a.size+1}`,u=D.spawn(r.shell,r.args,{name:"xterm-256color",cols:n,rows:i,cwd:t,env:q(process.env)}),s={id:o,title:d,workspacePath:t,shell:r.shell,cols:n,rows:i,status:"running",createdAt:c,lastActiveAt:c,attachedClients:0,ptyProcess:u,sockets:new Set,outputBuffer:"",idleTimer:null,persistent:e.persistent===!0,ownerUserId:String(e.ownerUserId||"").trim()||void 0,tenantId:String(e.tenantId||"").trim()||void 0,projectName:String(e.projectName||"").trim()||void 0};return u.onData(f=>{s.lastActiveAt=new Date().toISOString(),Z(s,f),P(s,{type:"output",data:f})}),u.onExit(({exitCode:f,signal:m})=>{s.status="exited",s.exitCode=f,s.signal=m,s.lastActiveAt=new Date().toISOString(),P(s,{type:"exit",exitCode:f,signal:m}),s.sockets.size===0&&!s.persistent?A(s):s.persistent&&(s.idleTimer&&clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{S(s.id,"exited-timeout")},te()))}),a.set(o,s),s.persistent||A(s),Q(s,e.preCommand),p.info(`created pty session id=${o}, cwd=${t}, shell=${r.shell}`),g(s)}function Q(e,t){const r=typeof t=="string"?t:"";if(!r.trim())return;const n=`${r.replace(/\n/g,"\r").replace(/\r+$/g,"")}\r`;try{e.ptyProcess.write(n)}catch(i){const o=i;p.warn(`failed to inject pty pre-command sessionId=${e.id}: ${o.message}`)}}function ee(e=process.env){const t=String(e.AWS_PTY_CONNECT_TOKEN_TTL_MS||"").trim();if(!t)return v;const r=Number(t);return!Number.isFinite(r)||r<5e3||r>10*60*1e3?v:r}function te(e=process.env){const t=String(e.AWS_PTY_EXITED_TTL_MS||"").trim();if(!t)return $;const r=Number(t);return!Number.isFinite(r)||r<1e3?$:r}function re(e=process.env){const t=String(e.AWS_PTY_MAX_SESSIONS||"").trim();if(!t)return b;const r=Number(t);return!Number.isInteger(r)||r<1||r>100?b:r}function ne(e){if(!e||typeof e!="object")return{workspacePath:void 0};const t=e;return{workspacePath:t.workspacePath,title:t.title,shell:t.shell,cols:t.cols,rows:t.rows,persistent:t.persistent,preCommand:t.preCommand,ownerUserId:t.ownerUserId,tenantId:t.tenantId,projectName:t.projectName}}function se(){return Array.from(a.values()).map(g)}function oe(e){const t=a.get(e);return t?g(t):void 0}function ie(e){if(!a.has(e))return;const t=`ptyws_${O.randomBytes(32).toString("base64url")}`,r=Date.now()+ee();return w.set(t,{sessionId:e,expiresAt:r}),{token:t,expiresAt:new Date(r).toISOString()}}function ae(e,t){const r=w.get(t);return r?r.expiresAt<Date.now()?(w.delete(t),p.warn(`[pty-ws] consumePtyConnectToken: token \u5DF2\u8FC7\u671F, sessionId=${e}, expiredAt=${new Date(r.expiresAt).toISOString()}`),!1):r.sessionId!==e?(p.warn(`[pty-ws] consumePtyConnectToken: sessionId \u4E0D\u5339\u914D, expected=${r.sessionId}, actual=${e}`),!1):(w.delete(t),p.info(`[pty-ws] consumePtyConnectToken: \u6210\u529F, sessionId=${e}`),!0):(p.warn(`[pty-ws] consumePtyConnectToken: token \u4E0D\u5B58\u5728, sessionId=${e}, ptyConnectTokens.size=${w.size}`),!1)}function ce(e){for(const[t,r]of w.entries())r.sessionId===e&&w.delete(t)}function S(e,t="closed"){const r=a.get(e);if(!r)return!1;C(r),ce(e),P(r,{type:"status",status:"closing",reason:t});for(const n of r.sockets)n.close(1e3,t);return r.sockets.clear(),r.status==="running"&&r.ptyProcess.kill(),a.delete(e),p.info(`closed pty session id=${e}, reason=${t}`),!0}function ge(e="shutdown"){for(const t of Array.from(a.keys()))S(t,e)}const y=L();y.get("/sessions",h,(e,t)=>{t.json({ok:!0,sessions:se()})}),y.post("/sessions",h,(e,t)=>{try{const r=G(ne(e.body));t.status(201).json({ok:!0,session:r})}catch(r){const n=r;t.status(400).json({error:n.message})}}),y.get("/sessions/:sessionId",h,(e,t)=>{const r=oe(e.params.sessionId);if(!r){t.status(404).json({error:"pty session not found"});return}t.json({ok:!0,session:r})}),y.delete("/sessions/:sessionId",h,(e,t)=>{if(!S(e.params.sessionId,"explicit-close")){t.status(404).json({error:"pty session not found"});return}t.json({ok:!0})}),y.post("/sessions/:sessionId/connect-token",h,(e,t)=>{const r=ie(e.params.sessionId);if(!r){t.status(404).json({error:"pty session not found"});return}t.json({ok:!0,...r})});function ue(e){const t=e.toString();try{return JSON.parse(t)}catch{return{type:"input",data:t}}}function le(e,t){C(e),e.sockets.add(t),e.lastActiveAt=new Date().toISOString(),k(t,{type:"status",status:e.status,session:g(e)}),e.outputBuffer&&k(t,{type:"output",data:e.outputBuffer,replay:!0}),t.on("message",r=>{const n=ue(r);if(!n||typeof n!="object")return;const i=n,o=String(i.type||"");if(e.lastActiveAt=new Date().toISOString(),o==="input"){e.ptyProcess.write(String(i.data||""));return}if(o==="resize"){const c=T(i.cols,e.cols),d=T(i.rows,e.rows);e.cols=c,e.rows=d,e.ptyProcess.resize(c,d);return}if(o==="close"){S(e.id,"client-close");return}o==="ping"&&k(t,{type:"pong"})}),t.on("close",()=>{e.sockets.delete(t),e.lastActiveAt=new Date().toISOString(),e.sockets.size===0&&e.status==="running"&&!e.persistent&&A(e)})}function pe(e,t){const r=t.searchParams.get("token")||"";if(r.trim())return r.trim();const n=e.headers["x-runtime-token"];return Array.isArray(n)?n[0]?.trim()||"":typeof n=="string"?n.trim():String(e.headers.authorization||"").match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||""}function ke(e){const t=new z({noServer:!0});e.on("upgrade",(r,n,i)=>{const o=r.headers.host||"localhost",c=new URL(r.url||"/",`http://${o}`),d=c.pathname.match(/^\/pty\/sessions\/([^/]+)\/stream$/);if(!d)return;const u=pe(r,c),s=decodeURIComponent(d[1]||""),f=u?u.length>12?u.substring(0,12)+"...":u:"empty";if(p.info(`[pty-ws] upgrade \u8BF7\u6C42: sessionId=${s}, token=${f}, pathname=${c.pathname}`),!x(u)&&!ae(s,u)){p.warn(`[pty-ws] token \u6821\u9A8C\u5931\u8D25: sessionId=${s}, token=${f}, runtimeTokenValid=${x(u)}, ptySessions.size=${a.size}`),n.write(`HTTP/1.1 401 Unauthorized\r
2
2
  \r
3
- `),n.destroy();return}const d=a.get(o);if(!d){p.warn(`[pty-ws] session \u4E0D\u5B58\u5728: sessionId=${o}, ptySessions.size=${a.size}, keys=${Array.from(a.keys()).join(",")}`),n.write(`HTTP/1.1 404 Not Found\r
3
+ `),n.destroy();return}const m=a.get(s);if(!m){p.warn(`[pty-ws] session \u4E0D\u5B58\u5728: sessionId=${s}, ptySessions.size=${a.size}, keys=${Array.from(a.keys()).join(",")}`),n.write(`HTTP/1.1 404 Not Found\r
4
4
  \r
5
- `),n.destroy();return}p.info(`[pty-ws] handleUpgrade: sessionId=${o}, status=${d.status}, persistent=${d.persistent}, sockets=${d.sockets.size}`),t.handleUpgrade(r,n,i,N=>{le(d,N)})})}export{ke as attachPtyWebSocketServer,ge as closeAllPtySessions,S as closePtySession,ie as createPtyConnectToken,Q as createPtySession,se as getPtySessionSummary,J as isPathInsideRoot,oe as listPtySessions,y as ptyRouter,a as ptySessions,Y as resolveDefaultShell,re as resolveMaxPtySessions,te as resolvePtyExitedTtlMs,F as resolvePtyIdleTtlMs,K as resolvePtyWorkspacePath,H as resolveRequestedShell};
5
+ `),n.destroy();return}p.info(`[pty-ws] handleUpgrade: sessionId=${s}, status=${m.status}, persistent=${m.persistent}, sockets=${m.sockets.size}`),t.handleUpgrade(r,n,i,N=>{le(m,N)})})}export{ke as attachPtyWebSocketServer,ge as closeAllPtySessions,S as closePtySession,ie as createPtyConnectToken,G as createPtySession,oe as getPtySessionSummary,J as isPathInsideRoot,se as listPtySessions,y as ptyRouter,a as ptySessions,Y as resolveDefaultShell,re as resolveMaxPtySessions,te as resolvePtyExitedTtlMs,B as resolvePtyIdleTtlMs,K as resolvePtyWorkspacePath,H as resolveRequestedShell};
6
6
 
@@ -1,54 +1,54 @@
1
- import{spawn as Fe}from"node:child_process";import{promises as N}from"node:fs";import Te from"node:os";import U from"node:path";import{TextDecoder as Z}from"node:util";import{Router as ze}from"express";import{v4 as We}from"uuid";import ke from"axios";import{adapterRegistry as C,getToolActionInfo as ge,isTransientClipboardPasteFilePath as Ce,redactTransientClipboardPastePaths as q,registerSdkProviders as He,resolveSdkProviderIdByCommand as Qe}from"../adapter/index.js";import{validateToken as S}from"../middleware/auth.js";import{getAgentProcessManager as ye}from"../services/agent-process-manager.js";import{getAiConfigService as Xe}from"../services/cc-switch-sdk.js";import{prepareAcodeInstanceConfig as Ge,redactForLog as ee}from"../services/instance-ai-config-service.js";import{enqueueMcpLaunchBinding as Ve}from"../services/mcp-launch-binding-queue.js";import{resolveSchedulerBaseUrlFromToken as we}from"../services/auto-register.js";import{findClaudeCodeProcesses as Je,isProcessRunning as Ye}from"../services/process-detector.js";import{bridgeEventBuffer as be,sendOutput as H,sendQuestionRequest as Ze,sendStatus as D}from"../services/session-output.js";import{getAllPushStats as et,startHeartbeatScheduler as tt}from"../services/event-delta-pusher.js";import{findPersistedSessionByAgentId as nt,removePersistedSession as v,savePersistedSessions as rt,updatePersistedSessionAutoCommands as ot,updatePersistedSessionRuntimeState as st,upsertPersistedSession as it}from"../services/terminal-persistence.js";import{getInstanceAiConfigDebugLogger as at}from"../utils/instance-ai-config-debug-logger.js";import{logger as h}from"../utils/logger.js";const A=ze();function $e(e){const t=e.header("X-Runtime-Token");return t&&t.trim()?t.trim():(e.header("Authorization")||"").match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||void 0}const f=new Map,ct=45e3,te=new Map;function ut(e){if(te.has(e))return;const t=setInterval(()=>{const n=f.get(e);if(!n){E(e);return}const r=n.currentRuntimeStatus;if(r!=="thinking"&&r!=="tool_using"&&r!=="compacting"){E(e);return}D(n.agentId,e,r,void 0,void 0,{runtimeAccessToken:n.runtimeAccessToken,schedulerBaseUrl:n.schedulerBaseUrl}).catch(()=>{})},ct);te.set(e,t)}function E(e){const t=te.get(e);t&&(clearInterval(t),te.delete(e))}const De=4e3,dt=`
1
+ import{spawn as ze}from"node:child_process";import{promises as N}from"node:fs";import ke from"node:os";import U from"node:path";import{TextDecoder as Z}from"node:util";import{Router as We}from"express";import{v4 as He}from"uuid";import we from"axios";import{adapterRegistry as w,getToolActionInfo as ge,isTransientClipboardPasteFilePath as Ce,redactTransientClipboardPastePaths as q,registerSdkProviders as Qe,resolveSdkProviderIdByCommand as Xe}from"../adapter/index.js";import{validateToken as S}from"../middleware/auth.js";import{getAgentProcessManager as ye}from"../services/agent-process-manager.js";import{getAiConfigService as Ge}from"../services/cc-switch-sdk.js";import{prepareAcodeInstanceConfig as Ve,redactForLog as ee}from"../services/instance-ai-config-service.js";import{enqueueMcpLaunchBinding as Je}from"../services/mcp-launch-binding-queue.js";import{resolveSchedulerBaseUrlFromToken as be}from"../services/auto-register.js";import{findClaudeCodeProcesses as Ye,isProcessRunning as Ze}from"../services/process-detector.js";import{bridgeEventBuffer as $e,sendOutput as H,sendQuestionRequest as et,sendStatus as _}from"../services/session-output.js";import{getAllPushStats as tt,startHeartbeatScheduler as nt}from"../services/event-delta-pusher.js";import{findPersistedSessionByAgentId as rt,removePersistedSession as v,savePersistedSessions as ot,updatePersistedSessionAutoCommands as st,updatePersistedSessionRuntimeState as it,upsertPersistedSession as at}from"../services/terminal-persistence.js";import{getInstanceAiConfigDebugLogger as ct}from"../utils/instance-ai-config-debug-logger.js";import{logger as h}from"../utils/logger.js";const A=We();function _e(e){const t=e.header("X-Runtime-Token");return t&&t.trim()?t.trim():(e.header("Authorization")||"").match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||void 0}const f=new Map,ut=45e3,te=new Map;function dt(e){if(te.has(e))return;const t=setInterval(()=>{const n=f.get(e);if(!n){M(e);return}const r=n.currentRuntimeStatus;if(r!=="thinking"&&r!=="tool_using"&&r!=="compacting"){M(e);return}_(n.agentId,e,r,void 0,void 0,{runtimeAccessToken:n.runtimeAccessToken,schedulerBaseUrl:n.schedulerBaseUrl}).catch(()=>{})},ut);te.set(e,t)}function M(e){const t=te.get(e);t&&(clearInterval(t),te.delete(e))}const De=4e3,lt=`
2
2
 
3
3
  \u8BF7\u6C42\u4F53:
4
- `;function he(e){if(e==null||typeof e!="object"||Array.isArray(e))return;const t=e,n={};return typeof t.model=="string"&&t.model.trim()&&(n.model=t.model.trim()),typeof t.baseURL=="string"&&t.baseURL.trim()&&(n.baseURL=t.baseURL.trim()),typeof t.apiKey=="string"&&t.apiKey.trim()&&(n.apiKey=t.apiKey.trim()),typeof t.effort=="string"&&t.effort.trim()&&(n.effort=t.effort.trim()),n}const lt=`
4
+ `;function he(e){if(e==null||typeof e!="object"||Array.isArray(e))return;const t=e,n={};return typeof t.model=="string"&&t.model.trim()&&(n.model=t.model.trim()),typeof t.baseURL=="string"&&t.baseURL.trim()&&(n.baseURL=t.baseURL.trim()),typeof t.apiKey=="string"&&t.apiKey.trim()&&(n.apiKey=t.apiKey.trim()),typeof t.effort=="string"&&t.effort.trim()&&(n.effort=t.effort.trim()),n}const mt=`
5
5
 
6
6
  \u8BF7\u6C42\u5934:
7
- `,K=new Set;async function mt(e,t){const n=[],r=[],s=U.join(e,".agentswork","memory");try{const c=(await N.readdir(s)).filter(d=>d.endsWith(".json")),u=await Promise.all(c.map(async d=>{try{const l=await N.readFile(U.join(s,d),"utf-8");return JSON.parse(l)}catch{return h.warn("[loadAgentStartupMemories] Failed to parse memory file: %s",U.join(s,d)),null}}));for(const d of u)if(d?.by_uri)for(const l of Object.values(d.by_uri)){const m=l.memory_type||"memory",p=(l.content||"").trim();p&&(m==="recently_memory"?n.push({title:l.title,content:p,uri:l.uri||""}):m==="agent_memory"&&r.push({title:l.title,content:p,uri:l.uri||""}))}}catch{h.debug("[loadAgentStartupMemories] \u65E0\u6CD5\u8BFB\u53D6\u8BB0\u5FC6\u76EE\u5F55: %s",s)}if(n.length===0&&r.length===0&&t?.schedulerBaseUrl&&t?.runtimeAccessToken&&t?.agentId){const a=`${t.schedulerBaseUrl.replace(/\/+$/,"")}/mcp/call`,c={"Content-Type":"application/json","X-Runtime-Token":t.runtimeAccessToken,Authorization:`Bearer ${t.runtimeAccessToken}`},u=["recently_memory","agent_memory"],d=await Promise.allSettled(u.map(l=>fetch(a,{method:"POST",headers:c,body:JSON.stringify({tool:"list_memories",arguments:{agentId:t.agentId,memory_type:l}})}).then(m=>{if(!m.ok)throw new Error(`Server returned ${m.status}`);return m.json()})));for(let l=0;l<d.length;l++){const m=d[l];if(m.status!=="fulfilled")continue;const p=m.value;if(!Array.isArray(p))continue;const T=u[l]==="recently_memory"?n:r;for(const y of p){const g=(y.content||"").trim();g&&T.push({title:y.title,content:g,uri:y.uri||""})}}(n.length>0||r.length>0)&&h.info(`[loadAgentStartupMemories] Loaded ${n.length} task(s) and ${r.length} memory(s) from server for ${t.agentId}`)}const o=10;n.sort((a,c)=>c.uri.localeCompare(a.uri)),r.sort((a,c)=>c.uri.localeCompare(a.uri));const i=[];if(n.length>0){const c=n.slice(0,o).map((u,d)=>`${u.title?`\u3010${u.title}\u3011`:`\u6761\u76EE ${d+1}`}
8
- ${u.content}`);i.push(`\u3010\u77ED\u671F\u8BB0\u5FC6\u3011
7
+ `,K=new Set;async function ft(e,t){const n=[],r=[],s=U.join(e,".agentswork","memory");try{const c=(await N.readdir(s)).filter(u=>u.endsWith(".json")),d=await Promise.all(c.map(async u=>{try{const l=await N.readFile(U.join(s,u),"utf-8");return JSON.parse(l)}catch{return h.warn("[loadAgentStartupMemories] Failed to parse memory file: %s",U.join(s,u)),null}}));for(const u of d)if(u?.by_uri)for(const l of Object.values(u.by_uri)){const m=l.memory_type||"memory",p=(l.content||"").trim();p&&(m==="recently_memory"?n.push({title:l.title,content:p,uri:l.uri||""}):m==="agent_memory"&&r.push({title:l.title,content:p,uri:l.uri||""}))}}catch{h.debug("[loadAgentStartupMemories] \u65E0\u6CD5\u8BFB\u53D6\u8BB0\u5FC6\u76EE\u5F55: %s",s)}if(n.length===0&&r.length===0&&t?.schedulerBaseUrl&&t?.runtimeAccessToken&&t?.agentId){const a=`${t.schedulerBaseUrl.replace(/\/+$/,"")}/mcp/call`,c={"Content-Type":"application/json","X-Runtime-Token":t.runtimeAccessToken,Authorization:`Bearer ${t.runtimeAccessToken}`},d=["recently_memory","agent_memory"],u=await Promise.allSettled(d.map(l=>fetch(a,{method:"POST",headers:c,body:JSON.stringify({tool:"list_memories",arguments:{agentId:t.agentId,memory_type:l}})}).then(m=>{if(!m.ok)throw new Error(`Server returned ${m.status}`);return m.json()})));for(let l=0;l<u.length;l++){const m=u[l];if(m.status!=="fulfilled")continue;const p=m.value;if(!Array.isArray(p))continue;const T=d[l]==="recently_memory"?n:r;for(const y of p){const g=(y.content||"").trim();g&&T.push({title:y.title,content:g,uri:y.uri||""})}}(n.length>0||r.length>0)&&h.info(`[loadAgentStartupMemories] Loaded ${n.length} task(s) and ${r.length} memory(s) from server for ${t.agentId}`)}const o=10;n.sort((a,c)=>c.uri.localeCompare(a.uri)),r.sort((a,c)=>c.uri.localeCompare(a.uri));const i=[];if(n.length>0){const c=n.slice(0,o).map((d,u)=>`${d.title?`\u3010${d.title}\u3011`:`\u6761\u76EE ${u+1}`}
8
+ ${d.content}`);i.push(`\u3010\u77ED\u671F\u8BB0\u5FC6\u3011
9
9
  ${c.join(`
10
10
 
11
- `)}`),n.length>o&&i.push(`... \u53CA\u53E6\u5916 ${n.length-o} \u6761\u77ED\u671F\u8BB0\u5FC6`)}if(r.length>0){const c=r.slice(0,o).map(u=>{const d=u.title?`\u3010${u.title}\u3011`:"";return d?`${d}
12
- ${u.content}`:u.content});i.push(`\u3010agent\u8BA4\u77E5\u3011
11
+ `)}`),n.length>o&&i.push(`... \u53CA\u53E6\u5916 ${n.length-o} \u6761\u77ED\u671F\u8BB0\u5FC6`)}if(r.length>0){const c=r.slice(0,o).map(d=>{const u=d.title?`\u3010${d.title}\u3011`:"";return u?`${u}
12
+ ${d.content}`:d.content});i.push(`\u3010agent\u8BA4\u77E5\u3011
13
13
  ${c.join(`
14
14
 
15
15
  `)}`),r.length>o&&i.push(`... \u53CA\u53E6\u5916 ${r.length-o} \u6761 agent \u8BA4\u77E5`)}if(i.length!==0)return i.join(`
16
16
 
17
- `)}function ft(e,t){return e!=="acode"?{supported:!1,statusCode:400,error:"context reset without restart is only supported by ACode"}:t?{supported:!0}:{supported:!1,statusCode:500,error:"ACode adapter does not expose resetContext"}}function pt(e){return e!=="acode"}function gt(e){const t=typeof e=="object"&&e!==null&&"suppressStatus"in e&&e.suppressStatus===!0,n=typeof e=="object"&&e!==null&&"reason"in e&&typeof e.reason=="string"&&e.reason.trim()?e.reason.trim():void 0;return{statusNotified:!t,reason:n}}function ne(e){const t=e?.usage;if(!t)return;const n=Number.isFinite(t.inputTokens)?t.inputTokens:0,r=Number.isFinite(t.outputTokens)?t.outputTokens:0;return n<=0&&r<=0&&!t.contextLimit&&!t.maxOutput&&!t.inputLimit&&!t.compactionThreshold?void 0:{inputTokens:n,outputTokens:r,...t.contextLimit?{contextLimit:t.contextLimit}:{},...t.maxOutput?{maxOutput:t.maxOutput}:{},...t.inputLimit?{inputLimit:t.inputLimit}:{},...t.compactionThreshold?{compactionThreshold:t.compactionThreshold}:{}}}function yt(e,t){const n=String(e||"").trim().toLowerCase(),r=String(t?.actionType||"").trim().toLowerCase();return n==="tool_using"&&r==="idle"?t?{status:"waiting_input",actionInfo:t}:{status:"waiting_input"}:t?{status:e,actionInfo:t}:{status:e}}const Q=new Map,ht="utf-8",_e="utf-8",Pe=300,Re=6e4;function X(e){return String(e).padStart(2,"0")}function It(e,t=new Date){const n=t.getFullYear(),r=X(t.getMonth()+1),s=X(t.getDate()),o=X(t.getHours()),i=X(t.getMinutes()),a=`${n}${r}${s}-${o}${i}${X(t.getSeconds())}-${String(t.getMilliseconds()).padStart(3,"0")}`;return U.join(Te.homedir(),".acode","cmd-dist",e,`${n}-${r}-${s}`,o,i,`${a}-cmd.out`)}function St(e){if(!e)return 0;const t=e.replace(/\r\n/g,`
17
+ `)}function pt(e,t){return e!=="acode"?{supported:!1,statusCode:400,error:"context reset without restart is only supported by ACode"}:t?{supported:!0}:{supported:!1,statusCode:500,error:"ACode adapter does not expose resetContext"}}function gt(e){return e!=="acode"}function yt(e){const t=typeof e=="object"&&e!==null&&"suppressStatus"in e&&e.suppressStatus===!0,n=typeof e=="object"&&e!==null&&"reason"in e&&typeof e.reason=="string"&&e.reason.trim()?e.reason.trim():void 0;return{statusNotified:!t,reason:n}}function ne(e){const t=e?.usage;if(!t)return;const n=Number.isFinite(t.inputTokens)?t.inputTokens:0,r=Number.isFinite(t.outputTokens)?t.outputTokens:0;return n<=0&&r<=0&&!t.contextLimit&&!t.maxOutput&&!t.inputLimit&&!t.compactionThreshold?void 0:{inputTokens:n,outputTokens:r,...t.contextLimit?{contextLimit:t.contextLimit}:{},...t.maxOutput?{maxOutput:t.maxOutput}:{},...t.inputLimit?{inputLimit:t.inputLimit}:{},...t.compactionThreshold?{compactionThreshold:t.compactionThreshold}:{}}}function ht(e,t){const n=String(e||"").trim().toLowerCase(),r=String(t?.actionType||"").trim().toLowerCase();return n==="tool_using"&&r==="idle"?t?{status:"waiting_input",actionInfo:t}:{status:"waiting_input"}:t?{status:e,actionInfo:t}:{status:e}}const Q=new Map,It="utf-8",Pe="utf-8",Re=300,xe=6e4;function X(e){return String(e).padStart(2,"0")}function St(e,t=new Date){const n=t.getFullYear(),r=X(t.getMonth()+1),s=X(t.getDate()),o=X(t.getHours()),i=X(t.getMinutes()),a=`${n}${r}${s}-${o}${i}${X(t.getSeconds())}-${String(t.getMilliseconds()).padStart(3,"0")}`;return U.join(ke.homedir(),".acode","cmd-dist",e,`${n}-${r}-${s}`,o,i,`${a}-cmd.out`)}function At(e){if(!e)return 0;const t=e.replace(/\r\n/g,`
18
18
  `).replace(/\r/g,`
19
19
  `),n=t.endsWith(`
20
20
  `)?t.slice(0,-1):t;return n?n.split(`
21
- `).length:1}function At(e,t=Pe){return`\r
21
+ `).length:1}function Tt(e,t=Re){return`\r
22
22
  [ACode] \u547D\u4EE4\u8F93\u51FA\u8D85\u8FC7 ${t} \u884C\uFF0C\u5B8C\u6574\u8F93\u51FA\u5DF2\u5199\u5165: ${e}\r
23
23
  [ACode] Agent \u53EF\u81EA\u884C\u8BFB\u53D6\u8BE5\u6587\u4EF6\uFF0C\u6216\u5728\u8BE5\u6587\u4EF6\u4E2D\u641C\u7D22\u9700\u8981\u7684\u5185\u5BB9\u3002\r
24
- `}function Tt(e=Re){return`\r
24
+ `}function kt(e=xe){return`\r
25
25
  [ACode] \u547D\u4EE4\u8D85\u8FC7 ${Math.round(e/1e3)} \u79D2\u6CA1\u6709\u65B0\u7684\u8F93\u51FA\uFF0C\u5DF2\u505C\u6B62\u6267\u884C\u5E76\u4FDD\u7559\u6B64\u524D\u8F93\u51FA\u3002\r
26
- `}async function xe(e){const t=e.outputPath||It(e.agentId,e.startedAt);return e.outputPath=t,await N.mkdir(U.dirname(t),{recursive:!0}),await N.writeFile(t,e.chunks.join(""),"utf-8"),t}function kt(e){return String(e??"").replace(/\r/g,`
27
- `).trim()}function Ct(e=process.platform,t=process.env){const n=t.AWS_TERMINAL_OUTPUT_ENCODING?.trim();return n||(e==="win32"?ht:_e)}function Me(e=Ct()){if(e!=="utf-8")try{return new Z(e,{fatal:!1})}catch{return new Z(_e,{fatal:!1})}return wt()}function wt(){let e=null,t=null,n=null;const r=[];function s(o){try{return new Z(o,{fatal:!1})}catch{return new Z("utf-8",{fatal:!1})}}return{decode(o,i){if(o!=null&&r.push(o instanceof ArrayBuffer?Buffer.from(o):Buffer.isBuffer(o)?o:Buffer.from(o.buffer,o.byteOffset,o.byteLength)),n==="gb18030")return t||(t=s("gb18030")),t.decode(o,i);e||(e=s("utf-8"));const a=e.decode(o,i);if(n===null&&a.includes("\uFFFD")){n="gb18030",t=s("gb18030");const c=Buffer.concat(r);return t.decode(c)}return n===null&&!i?.stream&&(n="utf-8"),a}}}function re(e,t,n=!1){return n?e.decode():!t||t.length===0?"":e.decode(t,{stream:!0})}function bt(e){const t=e.trim().match(/^cd(?:\s+(.*))?$/i);if(!t)return;const n=t[1]?.trim();if(!n)return null;const r=n.replace(/^\/d\s+/i,"").trim();return r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}function $t(e){const t=Q.get(e.sessionId);if(t)return t;const n={currentDirectory:e.workspacePath,runningProcess:null};return Q.set(e.sessionId,n),n}function Ee(e){for(const t of f.values())if(t.agentId===e)return t}async function Dt(e){const t=C.get(e.providerId||"claude-code"),n=oe(t.getSessionStatus(e.sessionId),e.currentRuntimeStatus,e.currentRuntimeActionType);return{sessionId:e.sessionId,status:n,runtimeStatus:n,runtimeActionType:e.currentRuntimeActionType,runtimeActionLabel:e.currentRuntimeActionLabel,runtimeActionDetail:e.currentRuntimeActionDetail,agentId:e.agentId,workspacePath:e.workspacePath,command:e.config.command,mode:"sdk",providerSessionId:t.getProviderSessionId(e.sessionId),reused:!0}}function oe(e,t,n){const r=String(e||"").trim();if(r){const o=String(t||"").trim(),i=String(n||"").trim().toLowerCase();return r.toLowerCase()==="tool_using"&&o.toLowerCase()==="waiting_input"&&i==="idle"?o:r}return String(t||"").trim()||"running"}function _t(e,t=Ye){return e.pid?t(e.pid)?Ne(e.command)==="acode"?{reusable:!1,reason:"in-process-provider"}:{reusable:!0,reason:"active-pid"}:{reusable:!1,reason:"dead-pid"}:{reusable:!1,reason:"missing-pid"}}function En(e){const t=Ee(e);if(!t)h.info(`[cleanupSdkSessionByAgentId] No active SDK session found for agentId=${e}, cleaning residual state anyway`);else{const n=t.sessionId;return h.info(`[cleanupSdkSessionByAgentId] Cleaning up SDK session for agentId=${e}, sessionId=${n}`),E(n),f.delete(n),se(n),v(n).catch(r=>{h.warn(`[cleanupSdkSessionByAgentId] Failed to remove persisted session for agentId=${e}: ${r}`)}),n}K.has(e)&&(K.delete(e),h.info(`[cleanupSdkSessionByAgentId] Released startingAgents lock for agentId=${e}`))}function se(e){const t=Q.get(e);if(!t?.runningProcess){Q.delete(e);return}try{t.runningProcess.kill()}catch{}finally{t.runningProcess=null,Q.delete(e)}}function w(e,t){t&&(e.seq+=1,H(e.agentId,t,e.sessionId,e.seq,void 0,{runtimeAccessToken:e.runtimeAccessToken,schedulerBaseUrl:e.schedulerBaseUrl}).catch(()=>{}))}function Ie(e){return`\x1B[36m${e}>\x1B[0m `}function Pt(e,t){return t==="~"?Te.homedir():U.resolve(e,t)}async function Rt(e,t,n){const r=bt(n);if(r===void 0)return!1;if(r===null)return w(e,`${t.currentDirectory}\r
28
- `),!0;const s=Pt(t.currentDirectory,r);try{return(await N.stat(s)).isDirectory()?(t.currentDirectory=s,w(e,`${t.currentDirectory}\r
29
- `),!0):(w(e,`cd: not a directory: ${s}\r
30
- `),!0)}catch(o){const i=o instanceof Error?o.message:String(o);return w(e,`cd: ${i}\r
31
- `),!0}}async function xt(e,t){const n=f.get(e);if(!n)throw new Error("SDK session not found");const r=kt(t),s=$t(n);if(!r)return{started:!1,cwd:s.currentDirectory};if(s.runningProcess)throw new Error("A terminal command is already running for this session");const o=q(r);if(w(n,`${Ie(s.currentDirectory)}${o}\r
32
- `),Ce(r))return w(n,`[Terminal Warning] \u68C0\u6D4B\u5230\u526A\u8D34\u677F\u4E34\u65F6 paste \u6587\u4EF6\u8DEF\u5F84\uFF0C\u5DF2\u8DF3\u8FC7\u6267\u884C\u3002\u8BF7\u7C98\u8D34\u6587\u4EF6\u5185\u5BB9\u6216\u4F7F\u7528\u663E\u5F0F\u8BFB\u53D6\u547D\u4EE4\u3002\r
33
- `),w(n,Ie(s.currentDirectory)),{started:!1,cwd:s.currentDirectory};if(await Rt(n,s,r))return{started:!1,cwd:s.currentDirectory};await D(n.agentId,e,"tool_using",{actionType:"bash",actionLabel:"\u7EC8\u7AEF\u547D\u4EE4",actionDetail:o},void 0,{runtimeAccessToken:n.runtimeAccessToken,schedulerBaseUrl:n.schedulerBaseUrl});const a=Fe(r,{cwd:s.currentDirectory,shell:!0,env:Le(n.agentId,n.workspacePath,process.env,n.config.envOverrides)});s.runningProcess=a;const c=Me(),u=Me(),d=n.providerId==="acode",l={agentId:n.agentId,startedAt:new Date,chunks:[],spilled:!1};let m;const p=()=>{m&&(clearTimeout(m),m=void 0)},T=()=>{p(),m=setTimeout(()=>{s.runningProcess===a&&(w(n,Tt()),a.kill())},Re)},y=(g,b=!0)=>{if(g&&(d&&l.chunks.push(g),d&&b&&T(),!(d&&l.spilled))){if(d&&St(l.chunks.join(""))>Pe){l.spilled=!0,xe(l).then($=>{w(n,At($))}).catch($=>{const M=$ instanceof Error?$.message:String($);w(n,`\r
34
- [ACode] \u547D\u4EE4\u8F93\u51FA\u843D\u76D8\u5931\u8D25: ${M}\r
35
- `)});return}w(n,g)}};return d&&T(),a.stdout.on("data",g=>{y(re(c,g))}),a.stderr.on("data",g=>{y(re(u,g))}),a.on("error",g=>{w(n,`\r
26
+ `}async function Ee(e){const t=e.outputPath||St(e.agentId,e.startedAt);return e.outputPath=t,await N.mkdir(U.dirname(t),{recursive:!0}),await N.writeFile(t,e.chunks.join(""),"utf-8"),t}function wt(e){return String(e??"").replace(/\r/g,`
27
+ `).trim()}function Ct(e=process.platform,t=process.env){const n=t.AWS_TERMINAL_OUTPUT_ENCODING?.trim();return n||(e==="win32"?It:Pe)}function Me(e=Ct()){if(e!=="utf-8")try{return new Z(e,{fatal:!1})}catch{return new Z(Pe,{fatal:!1})}return bt()}function bt(){let e=null,t=null,n=null;const r=[];function s(o){try{return new Z(o,{fatal:!1})}catch{return new Z("utf-8",{fatal:!1})}}return{decode(o,i){if(o!=null&&r.push(o instanceof ArrayBuffer?Buffer.from(o):Buffer.isBuffer(o)?o:Buffer.from(o.buffer,o.byteOffset,o.byteLength)),n==="gb18030")return t||(t=s("gb18030")),t.decode(o,i);e||(e=s("utf-8"));const a=e.decode(o,i);if(n===null&&a.includes("\uFFFD")){n="gb18030",t=s("gb18030");const c=Buffer.concat(r);return t.decode(c)}return n===null&&!i?.stream&&(n="utf-8"),a}}}function re(e,t,n=!1){return n?e.decode():!t||t.length===0?"":e.decode(t,{stream:!0})}function $t(e){const t=e.trim().match(/^cd(?:\s+(.*))?$/i);if(!t)return;const n=t[1]?.trim();if(!n)return null;const r=n.replace(/^\/d\s+/i,"").trim();return r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}function _t(e){const t=Q.get(e.sessionId);if(t)return t;const n={currentDirectory:e.workspacePath,runningProcess:null};return Q.set(e.sessionId,n),n}function Le(e){for(const t of f.values())if(t.agentId===e)return t}async function Dt(e){const t=w.get(e.providerId||"claude-code"),n=oe(t.getSessionStatus(e.sessionId),e.currentRuntimeStatus,e.currentRuntimeActionType);return{sessionId:e.sessionId,status:n,runtimeStatus:n,runtimeActionType:e.currentRuntimeActionType,runtimeActionLabel:e.currentRuntimeActionLabel,runtimeActionDetail:e.currentRuntimeActionDetail,agentId:e.agentId,workspacePath:e.workspacePath,command:e.config.command,mode:"sdk",providerSessionId:t.getProviderSessionId(e.sessionId),reused:!0}}function oe(e,t,n){const r=String(e||"").trim();if(r){const o=String(t||"").trim(),i=String(n||"").trim().toLowerCase();return r.toLowerCase()==="tool_using"&&o.toLowerCase()==="waiting_input"&&i==="idle"?o:r}return String(t||"").trim()||"running"}function Pt(e,t=Ze){return e.pid?t(e.pid)?qe(e.command)==="acode"?{reusable:!1,reason:"in-process-provider"}:{reusable:!0,reason:"active-pid"}:{reusable:!1,reason:"dead-pid"}:{reusable:!1,reason:"missing-pid"}}function Ln(e){const t=Le(e);if(!t)h.info(`[cleanupSdkSessionByAgentId] No active SDK session found for agentId=${e}, cleaning residual state anyway`);else{const n=t.sessionId;return h.info(`[cleanupSdkSessionByAgentId] Cleaning up SDK session for agentId=${e}, sessionId=${n}`),M(n),f.delete(n),se(n),v(n).catch(r=>{h.warn(`[cleanupSdkSessionByAgentId] Failed to remove persisted session for agentId=${e}: ${r}`)}),n}K.has(e)&&(K.delete(e),h.info(`[cleanupSdkSessionByAgentId] Released startingAgents lock for agentId=${e}`))}function se(e){const t=Q.get(e);if(!t?.runningProcess){Q.delete(e);return}try{t.runningProcess.kill()}catch{}finally{t.runningProcess=null,Q.delete(e)}}function C(e,t){t&&(e.seq+=1,H(e.agentId,t,e.sessionId,e.seq,void 0,{runtimeAccessToken:e.runtimeAccessToken,schedulerBaseUrl:e.schedulerBaseUrl}).catch(()=>{}))}function Ie(e){return`\x1B[36m${e}>\x1B[0m `}function Rt(e,t){return t==="~"?ke.homedir():U.resolve(e,t)}async function xt(e,t,n){const r=$t(n);if(r===void 0)return!1;if(r===null)return C(e,`${t.currentDirectory}\r
28
+ `),!0;const s=Rt(t.currentDirectory,r);try{return(await N.stat(s)).isDirectory()?(t.currentDirectory=s,C(e,`${t.currentDirectory}\r
29
+ `),!0):(C(e,`cd: not a directory: ${s}\r
30
+ `),!0)}catch(o){const i=o instanceof Error?o.message:String(o);return C(e,`cd: ${i}\r
31
+ `),!0}}async function Et(e,t){const n=f.get(e);if(!n)throw new Error("SDK session not found");const r=wt(t),s=_t(n);if(!r)return{started:!1,cwd:s.currentDirectory};if(s.runningProcess)throw new Error("A terminal command is already running for this session");const o=q(r);if(C(n,`${Ie(s.currentDirectory)}${o}\r
32
+ `),Ce(r))return C(n,`[Terminal Warning] \u68C0\u6D4B\u5230\u526A\u8D34\u677F\u4E34\u65F6 paste \u6587\u4EF6\u8DEF\u5F84\uFF0C\u5DF2\u8DF3\u8FC7\u6267\u884C\u3002\u8BF7\u7C98\u8D34\u6587\u4EF6\u5185\u5BB9\u6216\u4F7F\u7528\u663E\u5F0F\u8BFB\u53D6\u547D\u4EE4\u3002\r
33
+ `),C(n,Ie(s.currentDirectory)),{started:!1,cwd:s.currentDirectory};if(await xt(n,s,r))return{started:!1,cwd:s.currentDirectory};await _(n.agentId,e,"tool_using",{actionType:"bash",actionLabel:"\u7EC8\u7AEF\u547D\u4EE4",actionDetail:o},void 0,{runtimeAccessToken:n.runtimeAccessToken,schedulerBaseUrl:n.schedulerBaseUrl});const a=ze(r,{cwd:s.currentDirectory,shell:!0,env:je(n.agentId,n.workspacePath,process.env,n.config.envOverrides)});s.runningProcess=a;const c=Me(),d=Me(),u=n.providerId==="acode",l={agentId:n.agentId,startedAt:new Date,chunks:[],spilled:!1};let m;const p=()=>{m&&(clearTimeout(m),m=void 0)},T=()=>{p(),m=setTimeout(()=>{s.runningProcess===a&&(C(n,kt()),a.kill())},xe)},y=(g,b=!0)=>{if(g&&(u&&l.chunks.push(g),u&&b&&T(),!(u&&l.spilled))){if(u&&At(l.chunks.join(""))>Re){l.spilled=!0,Ee(l).then($=>{C(n,Tt($))}).catch($=>{const E=$ instanceof Error?$.message:String($);C(n,`\r
34
+ [ACode] \u547D\u4EE4\u8F93\u51FA\u843D\u76D8\u5931\u8D25: ${E}\r
35
+ `)});return}C(n,g)}};return u&&T(),a.stdout.on("data",g=>{y(re(c,g))}),a.stderr.on("data",g=>{y(re(d,g))}),a.on("error",g=>{C(n,`\r
36
36
  [Terminal Error] ${g.message}\r
37
- `)}),a.on("close",(g,b)=>{p(),s.runningProcess=null,y(re(c,void 0,!0),!1),y(re(u,void 0,!0),!1),l.spilled&&xe(l).catch($=>{const M=$ instanceof Error?$.message:String($);w(n,`\r
38
- [ACode] \u547D\u4EE4\u8F93\u51FA\u6700\u7EC8\u843D\u76D8\u5931\u8D25: ${M}\r
39
- `)}),g&&g!==0?w(n,`\r
37
+ `)}),a.on("close",(g,b)=>{p(),s.runningProcess=null,y(re(c,void 0,!0),!1),y(re(d,void 0,!0),!1),l.spilled&&Ee(l).catch($=>{const E=$ instanceof Error?$.message:String($);C(n,`\r
38
+ [ACode] \u547D\u4EE4\u8F93\u51FA\u6700\u7EC8\u843D\u76D8\u5931\u8D25: ${E}\r
39
+ `)}),g&&g!==0?C(n,`\r
40
40
  [exit ${g}]\r
41
- `):b&&w(n,`\r
41
+ `):b&&C(n,`\r
42
42
  [signal ${b}]\r
43
- `),w(n,Ie(s.currentDirectory)),D(n.agentId,e,"waiting_input",void 0,void 0,{runtimeAccessToken:n.runtimeAccessToken,schedulerBaseUrl:n.schedulerBaseUrl})}),{started:!0,cwd:s.currentDirectory}}function Le(e,t,n,r){const s={};for(const[o,i]of Object.entries(n))i!==void 0&&(s[o]=i);if(t&&(s.AWS_WORKSPACE_PATH=String(t)),r)for(const[o,i]of Object.entries(r)){const a=o.trim();if(!a||i===void 0||i===null)continue;const c=String(i).trim();c&&(s[a]=c)}return s.AWS_AGENT_ID=String(e),s.AWS_MCP_CLAIM_LAUNCH_BINDING="true",s}function Mt(e){const t=e.trim(),n=t[0],r=t[t.length-1];return(n==='"'||n==="'")&&n===r?t.slice(1,-1):t}async function Et(e){const t=String(e);if(!Ce(t))return t;const n=Mt(t);return U.isAbsolute(n)?N.readFile(n,"utf-8"):t}function je(e,t){const n={};for(const s of[e?.env,t])if(s)for(const[o,i]of Object.entries(s)){const a=o.trim();if(!a||i===void 0||i===null)continue;const c=String(i).trim();c&&(n[a]=c)}const r=n.ANTHROPIC_MODEL?.trim()||n.CODEX_MODEL?.trim()||void 0;return{envOverrides:n,model:r}}async function Lt(){try{return await Xe().readClaudeCodeConfig()}catch(e){return console.warn(`[Runtime] Failed to read saved ClaudeCode AI config: ${e.message}`),{}}}function jt(e){if(e==null)return;const n=(typeof e=="string"?e:JSON.stringify(e,null,2)).trim();if(n)return n.length<=De?n:`${n.slice(0,De)}
44
- ...\uFF08\u7ED3\u679C\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD\uFF09`}function Ut(e){if(e.data.actionType==="mcp")return!0;const n=String(e.data.toolName||"").toLowerCase();return n.startsWith("mcp__")||n.includes("-mcp__")||n.includes("mcp_")}function Bt(e){if(e.type!=="tool_use_end")return;const t=jt(e.data.toolResult??e.data.actionResult);if(!t)return;const n=ge(e.data.toolName,e.data.toolInput),r=e.data.actionType||n.actionType;if(r!=="idle")return r==="mcp"&&Ut(e)?{actionType:"mcp",actionLabel:"MCP\u8FD4\u56DE",actionDetail:e.data.actionDetail||e.data.toolName,actionId:e.data.actionId||e.data.toolUseId,actionResult:t}:{actionType:r,actionLabel:e.data.actionLabel||n.actionLabel,actionDetail:e.data.actionDetail||n.actionDetail||e.data.toolName,actionId:e.data.actionId||e.data.toolUseId,actionResult:t}}function Ot(e){if(e.type==="ai_request"){const t=e.data.model?` ${e.data.model}`:"",n=e.data.lastUserMessagePreview?`\uFF1A${e.data.lastUserMessagePreview}`:"";return`\r
43
+ `),C(n,Ie(s.currentDirectory)),_(n.agentId,e,"waiting_input",void 0,void 0,{runtimeAccessToken:n.runtimeAccessToken,schedulerBaseUrl:n.schedulerBaseUrl})}),{started:!0,cwd:s.currentDirectory}}function je(e,t,n,r){const s={};for(const[o,i]of Object.entries(n))i!==void 0&&(s[o]=i);if(t&&(s.AWS_WORKSPACE_PATH=String(t)),r)for(const[o,i]of Object.entries(r)){const a=o.trim();if(!a||i===void 0||i===null)continue;const c=String(i).trim();c&&(s[a]=c)}return s.AWS_AGENT_ID=String(e),s.AWS_MCP_CLAIM_LAUNCH_BINDING="true",s}function Mt(e){const t=e.trim(),n=t[0],r=t[t.length-1];return(n==='"'||n==="'")&&n===r?t.slice(1,-1):t}async function Lt(e){const t=String(e);if(!Ce(t))return t;const n=Mt(t);return U.isAbsolute(n)?N.readFile(n,"utf-8"):t}function Ue(e,t){const n={};for(const s of[e?.env,t])if(s)for(const[o,i]of Object.entries(s)){const a=o.trim();if(!a||i===void 0||i===null)continue;const c=String(i).trim();c&&(n[a]=c)}const r=n.ANTHROPIC_MODEL?.trim()||n.CODEX_MODEL?.trim()||void 0;return{envOverrides:n,model:r}}async function jt(){try{return await Ge().readClaudeCodeConfig()}catch(e){return console.warn(`[Runtime] Failed to read saved ClaudeCode AI config: ${e.message}`),{}}}function Ut(e){if(e==null)return;const n=(typeof e=="string"?e:JSON.stringify(e,null,2)).trim();if(n)return n.length<=De?n:`${n.slice(0,De)}
44
+ ...\uFF08\u7ED3\u679C\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD\uFF09`}function Bt(e){if(e.data.actionType==="mcp")return!0;const n=String(e.data.toolName||"").toLowerCase();return n.startsWith("mcp__")||n.includes("-mcp__")||n.includes("mcp_")}function Ot(e){if(e.type!=="tool_use_end")return;const t=Ut(e.data.toolResult??e.data.actionResult);if(!t)return;const n=ge(e.data.toolName,e.data.toolInput),r=e.data.actionType||n.actionType;if(r!=="idle")return r==="mcp"&&Bt(e)?{actionType:"mcp",actionLabel:"MCP\u8FD4\u56DE",actionDetail:e.data.actionDetail||e.data.toolName,actionId:e.data.actionId||e.data.toolUseId,actionResult:t}:{actionType:r,actionLabel:e.data.actionLabel||n.actionLabel,actionDetail:e.data.actionDetail||n.actionDetail||e.data.toolName,actionId:e.data.actionId||e.data.toolUseId,actionResult:t}}function Nt(e){if(e.type==="ai_request"){const t=e.data.model?` ${e.data.model}`:"",n=e.data.lastUserMessagePreview?`\uFF1A${e.data.lastUserMessagePreview}`:"";return`\r
45
45
  [ACode] \u6B63\u5728\u8BF7\u6C42\u6A21\u578B${t}${n}\r
46
46
  `}if(e.type==="text_delta"||e.type==="thinking"||e.type==="command_output")return e.data.text||void 0;if(e.type==="error")return e.data.text?`\r
47
47
  [SDK Error] ${e.data.text}\r
48
- `:void 0}function Nt(e){const t=Kt(e);return{sourceEventType:e.type,logCategory:"acode",...vt(e),...t?{logLevel:qt(e),logMessage:t}:{}}}function qt(e){return e.type==="error"?"error":e.type==="command_output"&&e.data.stream==="stderr"?"warn":"info"}function vt(e){return e.type!=="command_output"?{}:{...typeof e.data.stream=="string"?{stream:e.data.stream}:{},...typeof e.data.sequence=="number"?{sequence:e.data.sequence}:{},...typeof e.data.cwd=="string"?{cwd:e.data.cwd}:{},...typeof e.data.commandFilePath=="string"?{commandFilePath:e.data.commandFilePath}:{},...typeof e.data.commandLineCount=="number"?{commandLineCount:e.data.commandLineCount}:{}}}function Kt(e){if(e.type==="ai_request"){const t=e.data.model||"unknown-model",n=e.data.endpoint?` @ ${e.data.endpoint}`:"",r=typeof e.data.toolCount=="number"?`, tools=${e.data.toolCount}`:"";return`AI request started: ${t}${n}${r}`}if(e.type==="tool_use_start")return Ue(e,"\u5F00\u59CB");if(e.type==="tool_use_end")return Ue(e,"\u5B8C\u6210");if(e.type==="command_output")return Wt(e);if(e.type==="turn_complete")return`Turn completed${e.data.finishReason?`, finish=${e.data.finishReason}`:""}`;if(e.type==="session_complete")return`Session completed: exitCode=${e.data.exitCode??0}`;if(e.type==="error")return e.data.text||"ACode runtime error"}const Ft=/\x1b\[[0-9;?]*[a-zA-Z]/g;function zt(e){return e.replace(Ft,"")}function Wt(e){const t=typeof e.data.stream=="string"?e.data.stream:"mixed",n=typeof e.data.sequence=="number"?` #${e.data.sequence}`:"",r=zt(String(e.data.text||"")).replace(/\s+/g," ").trim(),s=r.length>240?`${r.slice(0,240)}...`:r;return`\u547D\u4EE4\u8F93\u51FA(${t}${n}): ${s||"(empty)"}`}function Ue(e,t){const n=ge(e.data.toolName,e.data.toolInput),r=e.data.actionLabel||n.actionLabel||"\u8C03\u7528\u5DE5\u5177",s=Be(e,n);return s?`${t}${r}: ${s}`:`${t}${r}: ${e.data.actionDetail||e.data.toolName||"tool"}`}function Be(e,t){const n=e.data.toolInput;return t.actionType==="bash"?Ht(n)||e.data.actionDetail||t.actionDetail:t.actionType==="read_file"||t.actionType==="edit_file"||t.actionType==="write_file"?Qt(n)||e.data.actionDetail||t.actionDetail:e.data.actionDetail||t.actionDetail}function Ht(e){const t=Se(e?.command,e?.cmd);if(t)return t;if(Array.isArray(e?.argv)){const n=e.argv.map(r=>String(r??"").trim()).filter(Boolean).join(" ");return n?q(n):void 0}return Se(e?.args)}function Qt(e){const t=Oe(e?.paths);return t.length>0?t.length===1?t[0]:`${t.length}\u4E2A\u6587\u4EF6: ${t.join(", ")}`:Se(e?.file_path,e?.filePath,e?.path,e?.target_file,e?.targetFile)}function Se(...e){for(const t of e){if(typeof t=="string"&&t.trim())return q(t.trim());if(Array.isArray(t)){const n=Oe(t)[0];if(n)return n}}}function Oe(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean).map(t=>q(t)):[]}function Xt(e){if(!(!e||Object.keys(e).length===0))try{const t=q(JSON.stringify(e,null,2));return t.length>8e3?`${t.slice(0,8e3)}
49
- ...\uFF08\u8F93\u5165\u53C2\u6570\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD\uFF09`:t}catch{return}}function Gt(e){const t=[e.model?`\u6A21\u578B: ${e.model}`:void 0,e.endpoint||e.requestUrl?`\u63A5\u53E3: ${e.endpoint||e.requestUrl}`:void 0,e.requestMethod?`\u65B9\u6CD5: ${e.requestMethod}`:void 0,typeof e.stream=="boolean"?`\u6D41\u5F0F: ${e.stream?"\u662F":"\u5426"}`:void 0,typeof e.messageCount=="number"?`\u4E0A\u4E0B\u6587\u6D88\u606F: ${e.messageCount}`:void 0,typeof e.toolCount=="number"?`\u53EF\u7528\u5DE5\u5177: ${e.toolCount}`:void 0,e.lastUserMessagePreview?`\u6700\u540E\u8BF7\u6C42: ${e.lastUserMessagePreview}`:void 0].filter(i=>!!i),n=Vt(e.requestHeaders),r=t.join(`
50
- `)||"ACode \u6B63\u5728\u53D1\u9001 AI \u8BF7\u6C42",s=n.length>0?`${lt}${n.join(`
51
- `)}`:"",o=e.requestBody?`${dt}${e.requestBody}`:"";return`${r}${s}${o}`}function Vt(e){return e?Object.entries(e).map(([t,n])=>`${t}: ${n}`).filter(t=>t.trim().length>0):[]}function Jt(e,t){return String(t||"").trim().toLowerCase()!=="waiting_input"?!1:e.type==="thinking"||e.type==="text_delta"}function Yt(e){for(const t of["estimatedContextTokens","contextTokens","context_tokens","contextUsedTokens","context_used_tokens"]){const n=e[t],r=Number(n);if(Number.isFinite(r)&&r>0)return r}}function Zt(e,t){if(!Jt(e,t)){if(e.type==="ai_request"){const n=Yt(e.data);return{status:"thinking",actionInfo:{actionType:"ai_request",actionLabel:"AI\u8BF7\u6C42",actionDetail:Gt(e.data),...n!==void 0?{usage:{inputTokens:n,outputTokens:0}}:{}}}}if(e.type==="thinking"||e.type==="text_delta")return{status:"thinking"};if(e.type==="tool_use_start"){const n=ge(e.data.toolName,e.data.toolInput),r=Be(e,n),s=Xt(e.data.toolInput);return e.data.actionType==="idle"||n.actionType==="idle"?{status:"waiting_input",actionInfo:{actionType:e.data.actionType||n.actionType,actionLabel:e.data.actionLabel||n.actionLabel,actionDetail:r||e.data.actionDetail||n.actionDetail||e.data.toolName,actionInput:s,actionId:e.data.actionId||e.data.toolUseId}}:{status:"tool_using",actionInfo:{actionType:e.data.actionType||n.actionType,actionLabel:e.data.actionLabel||n.actionLabel,actionDetail:r||e.data.actionDetail||n.actionDetail||e.data.toolName,actionInput:s,actionId:e.data.actionId||e.data.toolUseId}}}if(e.type==="turn_complete")return{status:"waiting_input",actionInfo:e.data.usage?{usage:e.data.usage}:void 0};if(e.type==="error")return{status:"error"};if(e.type==="context_compaction")return{status:"compacting",actionInfo:{actionType:"context_compaction",actionLabel:e.data.actionLabel,actionDetail:e.data.actionDetail,...e.data.actionId?{actionId:e.data.actionId}:{},...e.data.parentId?{parentId:e.data.parentId}:{}}};if(e.type==="runtime_capabilities")return{status:t||"waiting_input",actionInfo:{actionType:"runtime_capabilities",actionLabel:e.data.actionLabel||"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:e.data.actionDetail}}}}const L=new Map,ie=new Map,ae=new Map,G=new Map,en=20,tn=500,nn=3e4;async function ce(e,t=nn,n=2){for(let r=0;r<=n;r++){const s=new AbortController;let o;try{const i=e(s.signal);i.catch(()=>{}),await Promise.race([i,new Promise((a,c)=>{o=setTimeout(()=>{s.abort(),c(new Error(`sendOutput timeout after ${t}ms`))},t)})]),o&&clearTimeout(o);return}catch(i){o&&clearTimeout(o);const a=i instanceof Error?i.message:String(i);if(r<n){const c=1e3*(r+1);h.warn(`sendOutput attempt ${r+1}/${n+1} failed (${a}), retrying in ${c}ms...`),await new Promise(u=>setTimeout(u,c));continue}h.warn(`sendOutput failed after ${n+1} attempts (${a}), giving up to unblock serial queue`)}}}function ue(e,t){const n=t?`${e}:${t}`:void 0;let r,s;if(n)r=G.get(n),s=n;else{const p=[];for(const[T,y]of G)T.startsWith(e+":")&&y.buffer&&p.push(y.sourceEventType);for(const T of p)ue(e,T);return}if(!r||!r.buffer)return;r.timer=null;const o=r.buffer,i=r.seq,a=r.entry,c=r.sourceEventType;r.buffer="",s&&G.delete(s);const u={sourceEventType:c,logCategory:"acode"},d={runtimeAccessToken:a.runtimeAccessToken,schedulerBaseUrl:a.schedulerBaseUrl},m=(L.get(e)??Promise.resolve()).then(()=>ce(p=>H(a.agentId,o,e,i,u,d,p)),()=>ce(p=>H(a.agentId,o,e,i,u,d,p)));L.set(e,m),m.finally(()=>{L.get(e)===m&&L.delete(e)})}function rn(e,t){const n=Ot(e);if(!n)return;t.seq+=1;const r=t.seq,s=Nt(e),o={runtimeAccessToken:t.runtimeAccessToken,schedulerBaseUrl:t.schedulerBaseUrl};if((e.type==="command_output"||e.type==="text_delta"||e.type==="thinking")&&n.length<en){const c=`${e.sessionId}:${e.type}`;let u=G.get(c);if(u||(u={buffer:"",seq:0,timer:null,entry:t,sourceEventType:e.type}),u.buffer+=n,u.seq=r,u.entry=t,!u.timer){const d=e.sessionId,l=e.type;u.timer=setTimeout(()=>ue(d,l),tn)}G.set(c,u);return}ue(e.sessionId);const a=(L.get(e.sessionId)??Promise.resolve()).then(()=>ce(c=>H(t.agentId,n,e.sessionId,r,s,o,c)),()=>ce(c=>H(t.agentId,n,e.sessionId,r,s,o,c)));L.set(e.sessionId,a),a.finally(()=>{L.get(e.sessionId)===a&&L.delete(e.sessionId)})}function Ne(e){return Qe(e)}let qe=!1;function on(){qe||(He(C,sn),tt(),qe=!0)}function sn(e,t){e.on("event",n=>{const r=f.get(n.sessionId);if(r){if(console.log(`[${t.displayName} Adapter] Event: ${n.type} for session ${n.sessionId}`),!(n.type==="thinking"||n.type==="text_delta"||n.type==="tool_use_start"||n.type==="context_compaction"||n.type==="ai_request")){n.type==="runtime_capabilities"&&n.data.actionDetail&&(r.cachedCapabilitiesActionDetail=n.data.actionDetail);const i=Zt(n,r.currentRuntimeStatus);i&&D(r.agentId,n.sessionId,i.status,i.actionInfo,ne(i.actionInfo),{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},n.timestamp?new Date(n.timestamp).getTime():void 0,n.type)}rn(n,r);const o=Bt(n);o&&D(r.agentId,n.sessionId,"tool_result",o,void 0,{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},n.timestamp?new Date(n.timestamp).getTime():void 0,n.type)}}),e.on("status-change",(n,r,s)=>{const o=f.get(n);if(o){ue(n),r==="thinking"||r==="tool_using"||r==="compacting"?ut(n):E(n);const i=yt(r,s);o.currentRuntimeStatus=i.status;const a=o.currentRuntimeActionDetail??"",c=a.includes("poll_message")||a.includes("get_message"),d=!(i.actionInfo?.actionType==="ai_request")&&(i.status==="thinking"||i.status==="waiting_input")&&(o.currentRuntimeActionType==="idle"||o.currentRuntimeActionType==="mcp")&&c;(i.actionInfo?.actionType||!d)&&(o.currentRuntimeActionType=i.actionInfo?.actionType,o.currentRuntimeActionLabel=i.actionInfo?.actionLabel,o.currentRuntimeActionDetail=i.actionInfo?.actionDetail,o.currentRuntimeActionInput=i.actionInfo?.actionInput),console.log(`[${t.displayName} Adapter] Status changed: ${i.status} for agent ${o.agentId}`,i.actionInfo||""),st(n,{runtimeStatus:i.status,runtimeActionType:o.currentRuntimeActionType,runtimeActionLabel:o.currentRuntimeActionLabel,runtimeActionDetail:o.currentRuntimeActionDetail});const l=i.actionInfo?.actionType?i.actionInfo:o.currentRuntimeActionType?{actionType:o.currentRuntimeActionType,actionLabel:o.currentRuntimeActionLabel??"",actionDetail:o.currentRuntimeActionDetail,actionInput:o.currentRuntimeActionInput}:void 0;if(i.status==="compacting"){const p=(ie.get(n)??Promise.resolve()).then(async()=>{for(let y=0;y<=2;y++){if(await D(o.agentId,n,i.status,l,ne(i.actionInfo),{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})!==void 0)return;y<2&&(h.warn(`[${t.displayName}] compaction sendStatus attempt ${y+1} failed (HTTP), retrying in ${1e3*(y+1)}ms...`),await new Promise(b=>setTimeout(b,1e3*(y+1))))}h.warn(`[${t.displayName}] compaction sendStatus failed after 3 attempts, event may be lost`)}).catch(T=>{h.warn(`[${t.displayName}] compaction status chain error:`,T)});ie.set(n,p),p.finally(()=>{ie.get(n)===p&&ie.delete(n)})}else{const m=d&&!i.actionInfo?.actionType;if(l?.actionType==="idle"||o.currentRuntimeActionType==="idle"&&d){const y=(ae.get(n)??Promise.resolve()).then(async()=>{for(let b=0;b<=2;b++){if(await D(o.agentId,n,i.status,m?void 0:l,ne(i.actionInfo),{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})!==void 0)return;b<2&&await new Promise(M=>setTimeout(M,1e3*(b+1)))}h.warn(`[${t.displayName}] idle tool sendStatus failed after 3 attempts, status may be stale (frontend will fall back to timeline tool_use event)`)}).catch(g=>{h.warn(`[${t.displayName}] idle status chain error:`,g)});ae.set(n,y),y.finally(()=>{ae.get(n)===y&&ae.delete(n)})}else D(o.agentId,n,i.status,m?void 0:l,ne(i.actionInfo),{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})}if(i.status==="waiting_input"&&o.cachedCapabilitiesActionDetail){const m=o.cachedCapabilitiesActionDetail;o.cachedCapabilitiesActionDetail=void 0,console.log(`[${t.displayName} Adapter] Re-sending cached runtime_capabilities for agent ${o.agentId} (session stabilized to waiting_input)`),D(o.agentId,n,"waiting_input",{actionType:"runtime_capabilities",actionLabel:"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:m},void 0,{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})}}}),e.on("ask-user-question",n=>{const r=f.get(n.sessionId);r&&(console.log(`[${t.displayName} Adapter] AskUserQuestion for agent ${r.agentId}`),Ze(r.agentId,n.sessionId,Array.isArray(n.questions)?n.questions:[],{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},n.toolCallId))}),e.on("permission-request",n=>{const r=f.get(n.sessionId);if(r){console.log(`[${t.displayName} Adapter] Permission request: ${n.toolName} for agent ${r.agentId}`);const s=n.toolInput?q(JSON.stringify(n.toolInput).slice(0,400)):void 0;D(r.agentId,n.sessionId,"waiting_input",{actionType:"other",actionLabel:"\u6743\u9650\u786E\u8BA4",actionDetail:s||n.toolName},void 0,{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl})}})}A.post("/start",S,async(e,t)=>{const{agentId:n,workspacePath:r,mode:s="sdk"}=e.body||{};if(!n||!r){t.status(400).json({error:"agentId and workspacePath are required"});return}const o=String(e.body?.schedulerBaseUrl||"").trim()||String(e.header("x-bridge-tunnel-source")||"").trim()||we($e(e))||void 0;Ve({agentId:String(n),workspacePath:String(r),serverUrl:e.body?.serverUrl||o,runtimeAccessToken:e.body?.runtimeAccessToken,userId:e.body?.userId,schedulerBaseUrl:o}),s&&s!=="sdk"&&console.warn(`[Runtime] Unsupported runtime mode "${s}" requested for agent ${n}; starting SDK session instead.`),await an(e,t)});async function an(e,t){const{agentId:n,workspacePath:r,command:s,autoAccept:o=!0,initialPrompt:i,systemPrompt:a,globalPrompt:c,rolePrompt:u,memory:d,mcpConfigPath:l,extraMcpServers:m,envOverrides:p,idleInputAutoCommand:T,nonInputAutoCommand:y,model:g,instanceAiConfig:b,subAgentModel:$,subAgentEffort:M}=e.body||{},F=at();F.log({level:"info",category:"launch",message:"startSdkSession: \u6536\u5230\u542F\u52A8\u8BF7\u6C42",source:"bridge",agentId:String(n||"").trim()||void 0,details:{reqBodyKeys:Object.keys(e.body||{}),perInstanceAiConfig:b?ee(b):null,perAgentModel:g??null}});let _=null;const I=String(n||"").trim(),de=String(e.body?.runtimeAccessToken||"").trim()||void 0,B=String(e.body?.schedulerBaseUrl||"").trim()||String(e.header("x-bridge-tunnel-source")||"").trim()||we($e(e))||void 0;B?h.info(`[startSdkSession] \u56DE\u8C03\u76EE\u6807 server: ${B} (agentId=${I})`):h.warn(`[startSdkSession] \u672A\u89E3\u6790\u5230 schedulerBaseUrl\uFF0C\u5C06\u56DE\u9000\u5230\u9ED8\u8BA4\u5730\u5740 (agentId=${I})`);try{if(on(),!I){t.status(400).json({error:"agentId is required"});return}const O=Ee(I);if(O){t.json(await Dt(O));return}const k=await nt(I);if(k){const P=_t(k);if(!P.reusable)console.warn(`[Runtime] Ignoring stale persisted SDK session for agentId=${I}, sessionId=${k.sessionId}, reason=${P.reason}`),await v(k.sessionId);else{const R=oe(k.runtimeStatus,k.runtimeStatus,k.runtimeActionType);t.json({sessionId:k.sessionId,status:R,runtimeStatus:R,runtimeActionType:k.runtimeActionType,runtimeActionLabel:k.runtimeActionLabel,runtimeActionDetail:k.runtimeActionDetail,agentId:k.agentId,workspacePath:k.workspacePath,command:k.command,mode:k.mode||"sdk",pid:k.pid,reused:!0,persistedOnly:!0});return}}if(K.has(I)){t.status(409).json({error:"SDK session is already starting for this agent"});return}K.add(I);const ln=(s||"acode").toLowerCase(),x=Ne(s),ve=C.get(x);_=We();const Ke=x==="claude-code"?await Lt():null,V=je(x==="claude-code"?Ke:null,p),z=x==="acode"?g?String(g).trim():void 0:(()=>{const P=g?String(g).trim():void 0,R=V.model?String(V.model).trim():void 0;return P||R})();F.log({level:"info",category:"resolve",message:"\u6A21\u578B\u89E3\u6790\u7ED3\u679C",source:"bridge",agentId:I,sessionId:_??void 0,details:{perAgentModel:g??null,globalModel:V.model??null,resolvedModel:z??null,providerId:x,note:x==="acode"?"adapter handles full priority":"request > global"}});const le={...V.envOverrides};z&&(le.ANTHROPIC_MODEL=z,le.CODEX_MODEL=z);let W,me=l;if(x==="acode"){const P=b||{},R=await Ge({apiOverrides:he(P)??void 0,agentId:I,sessionId:_??void 0,runtimeBridgeBaseUrl:B});W=R.instanceConfig.config,me=R.perInstanceConfigPath,F.log({level:"info",category:"apply",message:"prepareAcodeInstanceConfig \u5B8C\u6210",source:"bridge",agentId:I,sessionId:_??void 0,details:{sanitizedApiOverrides:he(P)?ee(he(P)):null,resolvedInstanceAiConfig:W?ee(W):null,perInstanceConfigPath:me,instanceConfigSources:R.instanceConfig.source??null}})}let Ae=a||void 0,fe,pe,J;if(x==="acode")if(fe=typeof c=="string"&&c.trim()||void 0,pe=typeof u=="string"&&u.trim()||void 0,typeof d=="string"&&d.trim())J=d.trim();else{const P=await mt(r,{schedulerBaseUrl:B,runtimeAccessToken:de,agentId:I});P&&(J=P,h.info(`[startSdkSession] Auto-loaded memories for ACode agent ${I}`))}else if(typeof c=="string"&&c.trim()||typeof u=="string"&&u.trim()||typeof d=="string"&&d.trim()){const R=[c,u,d,a].filter(Y=>typeof Y=="string"&&Y.trim().length>0).map(Y=>Y.trim());Ae=R.length>0?R.join(`
48
+ `:void 0}function qt(e){const t=Ft(e);return{sourceEventType:e.type,logCategory:"acode",...Kt(e),...t?{logLevel:vt(e),logMessage:t}:{}}}function vt(e){return e.type==="error"?"error":e.type==="command_output"&&e.data.stream==="stderr"?"warn":"info"}function Kt(e){return e.type!=="command_output"?{}:{...typeof e.data.stream=="string"?{stream:e.data.stream}:{},...typeof e.data.sequence=="number"?{sequence:e.data.sequence}:{},...typeof e.data.cwd=="string"?{cwd:e.data.cwd}:{},...typeof e.data.commandFilePath=="string"?{commandFilePath:e.data.commandFilePath}:{},...typeof e.data.commandLineCount=="number"?{commandLineCount:e.data.commandLineCount}:{}}}function Ft(e){if(e.type==="ai_request"){const t=e.data.model||"unknown-model",n=e.data.endpoint?` @ ${e.data.endpoint}`:"",r=typeof e.data.toolCount=="number"?`, tools=${e.data.toolCount}`:"";return`AI request started: ${t}${n}${r}`}if(e.type==="tool_use_start")return Be(e,"\u5F00\u59CB");if(e.type==="tool_use_end")return Be(e,"\u5B8C\u6210");if(e.type==="command_output")return Ht(e);if(e.type==="turn_complete")return`Turn completed${e.data.finishReason?`, finish=${e.data.finishReason}`:""}`;if(e.type==="session_complete")return`Session completed: exitCode=${e.data.exitCode??0}`;if(e.type==="error")return e.data.text||"ACode runtime error"}const zt=/\x1b\[[0-9;?]*[a-zA-Z]/g;function Wt(e){return e.replace(zt,"")}function Ht(e){const t=typeof e.data.stream=="string"?e.data.stream:"mixed",n=typeof e.data.sequence=="number"?` #${e.data.sequence}`:"",r=Wt(String(e.data.text||"")).replace(/\s+/g," ").trim(),s=r.length>240?`${r.slice(0,240)}...`:r;return`\u547D\u4EE4\u8F93\u51FA(${t}${n}): ${s||"(empty)"}`}function Be(e,t){const n=ge(e.data.toolName,e.data.toolInput),r=e.data.actionLabel||n.actionLabel||"\u8C03\u7528\u5DE5\u5177",s=Oe(e,n);return s?`${t}${r}: ${s}`:`${t}${r}: ${e.data.actionDetail||e.data.toolName||"tool"}`}function Oe(e,t){const n=e.data.toolInput;return t.actionType==="bash"?Qt(n)||e.data.actionDetail||t.actionDetail:t.actionType==="read_file"||t.actionType==="edit_file"||t.actionType==="write_file"?Xt(n)||e.data.actionDetail||t.actionDetail:e.data.actionDetail||t.actionDetail}function Qt(e){const t=Se(e?.command,e?.cmd);if(t)return t;if(Array.isArray(e?.argv)){const n=e.argv.map(r=>String(r??"").trim()).filter(Boolean).join(" ");return n?q(n):void 0}return Se(e?.args)}function Xt(e){const t=Ne(e?.paths);return t.length>0?t.length===1?t[0]:`${t.length}\u4E2A\u6587\u4EF6: ${t.join(", ")}`:Se(e?.file_path,e?.filePath,e?.path,e?.target_file,e?.targetFile)}function Se(...e){for(const t of e){if(typeof t=="string"&&t.trim())return q(t.trim());if(Array.isArray(t)){const n=Ne(t)[0];if(n)return n}}}function Ne(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean).map(t=>q(t)):[]}function Gt(e){if(!(!e||Object.keys(e).length===0))try{const t=q(JSON.stringify(e,null,2));return t.length>8e3?`${t.slice(0,8e3)}
49
+ ...\uFF08\u8F93\u5165\u53C2\u6570\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD\uFF09`:t}catch{return}}function Vt(e){const t=[e.model?`\u6A21\u578B: ${e.model}`:void 0,e.endpoint||e.requestUrl?`\u63A5\u53E3: ${e.endpoint||e.requestUrl}`:void 0,e.requestMethod?`\u65B9\u6CD5: ${e.requestMethod}`:void 0,typeof e.stream=="boolean"?`\u6D41\u5F0F: ${e.stream?"\u662F":"\u5426"}`:void 0,typeof e.messageCount=="number"?`\u4E0A\u4E0B\u6587\u6D88\u606F: ${e.messageCount}`:void 0,typeof e.toolCount=="number"?`\u53EF\u7528\u5DE5\u5177: ${e.toolCount}`:void 0,e.lastUserMessagePreview?`\u6700\u540E\u8BF7\u6C42: ${e.lastUserMessagePreview}`:void 0].filter(i=>!!i),n=Jt(e.requestHeaders),r=t.join(`
50
+ `)||"ACode \u6B63\u5728\u53D1\u9001 AI \u8BF7\u6C42",s=n.length>0?`${mt}${n.join(`
51
+ `)}`:"",o=e.requestBody?`${lt}${e.requestBody}`:"";return`${r}${s}${o}`}function Jt(e){return e?Object.entries(e).map(([t,n])=>`${t}: ${n}`).filter(t=>t.trim().length>0):[]}function Yt(e,t){return String(t||"").trim().toLowerCase()!=="waiting_input"?!1:e.type==="thinking"||e.type==="text_delta"}function Zt(e){for(const t of["estimatedContextTokens","contextTokens","context_tokens","contextUsedTokens","context_used_tokens"]){const n=e[t],r=Number(n);if(Number.isFinite(r)&&r>0)return r}}function en(e,t){if(!Yt(e,t)){if(e.type==="ai_request"){const n=Zt(e.data);return{status:"thinking",actionInfo:{actionType:"ai_request",actionLabel:"AI\u8BF7\u6C42",actionDetail:Vt(e.data),...n!==void 0?{usage:{inputTokens:n,outputTokens:0}}:{}}}}if(e.type==="background_command_completed")return{status:"tool_result",actionInfo:{actionType:"background_command",actionLabel:"\u540E\u53F0\u547D\u4EE4",actionDetail:"background_command_completed"}};if(e.type==="thinking"||e.type==="text_delta")return{status:"thinking"};if(e.type==="tool_use_start"){const n=ge(e.data.toolName,e.data.toolInput),r=Oe(e,n),s=Gt(e.data.toolInput);return e.data.actionType==="idle"||n.actionType==="idle"?{status:"waiting_input",actionInfo:{actionType:e.data.actionType||n.actionType,actionLabel:e.data.actionLabel||n.actionLabel,actionDetail:r||e.data.actionDetail||n.actionDetail||e.data.toolName,actionInput:s,actionId:e.data.actionId||e.data.toolUseId}}:{status:"tool_using",actionInfo:{actionType:e.data.actionType||n.actionType,actionLabel:e.data.actionLabel||n.actionLabel,actionDetail:r||e.data.actionDetail||n.actionDetail||e.data.toolName,actionInput:s,actionId:e.data.actionId||e.data.toolUseId}}}if(e.type==="turn_complete")return{status:"waiting_input",actionInfo:e.data.usage?{usage:e.data.usage}:void 0};if(e.type==="error")return{status:"error"};if(e.type==="context_compaction")return{status:"compacting",actionInfo:{actionType:"context_compaction",actionLabel:e.data.actionLabel,actionDetail:e.data.actionDetail,...e.data.actionId?{actionId:e.data.actionId}:{},...e.data.parentId?{parentId:e.data.parentId}:{}}};if(e.type==="runtime_capabilities")return{status:t||"waiting_input",actionInfo:{actionType:"runtime_capabilities",actionLabel:e.data.actionLabel||"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:e.data.actionDetail}}}}const L=new Map,ie=new Map,ae=new Map,G=new Map,tn=20,nn=500,rn=3e4;async function ce(e,t=rn,n=2){for(let r=0;r<=n;r++){const s=new AbortController;let o;try{const i=e(s.signal);i.catch(()=>{}),await Promise.race([i,new Promise((a,c)=>{o=setTimeout(()=>{s.abort(),c(new Error(`sendOutput timeout after ${t}ms`))},t)})]),o&&clearTimeout(o);return}catch(i){o&&clearTimeout(o);const a=i instanceof Error?i.message:String(i);if(r<n){const c=1e3*(r+1);h.warn(`sendOutput attempt ${r+1}/${n+1} failed (${a}), retrying in ${c}ms...`),await new Promise(d=>setTimeout(d,c));continue}h.warn(`sendOutput failed after ${n+1} attempts (${a}), giving up to unblock serial queue`)}}}function ue(e,t){const n=t?`${e}:${t}`:void 0;let r,s;if(n)r=G.get(n),s=n;else{const p=[];for(const[T,y]of G)T.startsWith(e+":")&&y.buffer&&p.push(y.sourceEventType);for(const T of p)ue(e,T);return}if(!r||!r.buffer)return;r.timer=null;const o=r.buffer,i=r.seq,a=r.entry,c=r.sourceEventType;r.buffer="",s&&G.delete(s);const d={sourceEventType:c,logCategory:"acode"},u={runtimeAccessToken:a.runtimeAccessToken,schedulerBaseUrl:a.schedulerBaseUrl},m=(L.get(e)??Promise.resolve()).then(()=>ce(p=>H(a.agentId,o,e,i,d,u,p)),()=>ce(p=>H(a.agentId,o,e,i,d,u,p)));L.set(e,m),m.finally(()=>{L.get(e)===m&&L.delete(e)})}function on(e,t){const n=Nt(e);if(!n)return;t.seq+=1;const r=t.seq,s=qt(e),o={runtimeAccessToken:t.runtimeAccessToken,schedulerBaseUrl:t.schedulerBaseUrl};if((e.type==="command_output"||e.type==="text_delta"||e.type==="thinking")&&n.length<tn){const c=`${e.sessionId}:${e.type}`;let d=G.get(c);if(d||(d={buffer:"",seq:0,timer:null,entry:t,sourceEventType:e.type}),d.buffer+=n,d.seq=r,d.entry=t,!d.timer){const u=e.sessionId,l=e.type;d.timer=setTimeout(()=>ue(u,l),nn)}G.set(c,d);return}ue(e.sessionId);const a=(L.get(e.sessionId)??Promise.resolve()).then(()=>ce(c=>H(t.agentId,n,e.sessionId,r,s,o,c)),()=>ce(c=>H(t.agentId,n,e.sessionId,r,s,o,c)));L.set(e.sessionId,a),a.finally(()=>{L.get(e.sessionId)===a&&L.delete(e.sessionId)})}function qe(e){return Xe(e)}let ve=!1;function sn(){ve||(Qe(w,an),nt(),ve=!0)}function an(e,t){e.on("event",n=>{const r=f.get(n.sessionId);if(r){if(console.log(`[${t.displayName} Adapter] Event: ${n.type} for session ${n.sessionId}`),!(n.type==="thinking"||n.type==="text_delta"||n.type==="tool_use_start"||n.type==="context_compaction"||n.type==="ai_request")){n.type==="runtime_capabilities"&&n.data.actionDetail&&(r.cachedCapabilitiesActionDetail=n.data.actionDetail);const i=en(n,r.currentRuntimeStatus);i&&_(r.agentId,n.sessionId,i.status,i.actionInfo,ne(i.actionInfo),{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},n.timestamp?new Date(n.timestamp).getTime():void 0,n.type)}on(n,r);const o=Ot(n);if(o){const i={runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},a=n.timestamp?new Date(n.timestamp).getTime():void 0;String(n.data?.toolName||"").toLowerCase()==="browser_launch"?(async()=>{for(let u=0;u<3;u++){if(await _(r.agentId,n.sessionId,"tool_result",o,void 0,i,a,n.type)!==void 0)return;u<2&&await new Promise(m=>setTimeout(m,3e3*(u+1)))}})().catch(d=>console.warn("[Runtime] browser_launch sendStatus retry exhausted:",d)):_(r.agentId,n.sessionId,"tool_result",o,void 0,i,a,n.type)}}}),e.on("status-change",(n,r,s)=>{const o=f.get(n);if(o){ue(n),r==="thinking"||r==="tool_using"||r==="compacting"?dt(n):M(n);const i=ht(r,s);o.currentRuntimeStatus=i.status;const a=o.currentRuntimeActionDetail??"",c=a.includes("poll_message")||a.includes("get_message"),u=!(i.actionInfo?.actionType==="ai_request")&&(i.status==="thinking"||i.status==="waiting_input")&&(o.currentRuntimeActionType==="idle"||o.currentRuntimeActionType==="mcp")&&c;(i.actionInfo?.actionType||!u)&&(o.currentRuntimeActionType=i.actionInfo?.actionType,o.currentRuntimeActionLabel=i.actionInfo?.actionLabel,o.currentRuntimeActionDetail=i.actionInfo?.actionDetail,o.currentRuntimeActionInput=i.actionInfo?.actionInput),console.log(`[${t.displayName} Adapter] Status changed: ${i.status} for agent ${o.agentId}`,i.actionInfo||""),it(n,{runtimeStatus:i.status,runtimeActionType:o.currentRuntimeActionType,runtimeActionLabel:o.currentRuntimeActionLabel,runtimeActionDetail:o.currentRuntimeActionDetail});const l=i.actionInfo?.actionType?i.actionInfo:o.currentRuntimeActionType?{actionType:o.currentRuntimeActionType,actionLabel:o.currentRuntimeActionLabel??"",actionDetail:o.currentRuntimeActionDetail,actionInput:o.currentRuntimeActionInput}:void 0;if(i.status==="compacting"){const p=(ie.get(n)??Promise.resolve()).then(async()=>{for(let y=0;y<=2;y++){if(await _(o.agentId,n,i.status,l,ne(i.actionInfo),{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})!==void 0)return;y<2&&(h.warn(`[${t.displayName}] compaction sendStatus attempt ${y+1} failed (HTTP), retrying in ${1e3*(y+1)}ms...`),await new Promise(b=>setTimeout(b,1e3*(y+1))))}h.warn(`[${t.displayName}] compaction sendStatus failed after 3 attempts, event may be lost`)}).catch(T=>{h.warn(`[${t.displayName}] compaction status chain error:`,T)});ie.set(n,p),p.finally(()=>{ie.get(n)===p&&ie.delete(n)})}else{const m=u&&!i.actionInfo?.actionType;if(l?.actionType==="idle"||o.currentRuntimeActionType==="idle"&&u){const y=(ae.get(n)??Promise.resolve()).then(async()=>{for(let b=0;b<=2;b++){if(await _(o.agentId,n,i.status,m?void 0:l,ne(i.actionInfo),{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})!==void 0)return;b<2&&await new Promise(E=>setTimeout(E,1e3*(b+1)))}h.warn(`[${t.displayName}] idle tool sendStatus failed after 3 attempts, status may be stale (frontend will fall back to timeline tool_use event)`)}).catch(g=>{h.warn(`[${t.displayName}] idle status chain error:`,g)});ae.set(n,y),y.finally(()=>{ae.get(n)===y&&ae.delete(n)})}else _(o.agentId,n,i.status,m?void 0:l,ne(i.actionInfo),{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})}if(i.status==="waiting_input"&&o.cachedCapabilitiesActionDetail){const m=o.cachedCapabilitiesActionDetail;o.cachedCapabilitiesActionDetail=void 0,console.log(`[${t.displayName} Adapter] Re-sending cached runtime_capabilities for agent ${o.agentId} (session stabilized to waiting_input)`),_(o.agentId,n,"waiting_input",{actionType:"runtime_capabilities",actionLabel:"\u8FD0\u884C\u65F6\u80FD\u529B",actionDetail:m},void 0,{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})}}}),e.on("ask-user-question",n=>{const r=f.get(n.sessionId);r&&(console.log(`[${t.displayName} Adapter] AskUserQuestion for agent ${r.agentId}`),et(r.agentId,n.sessionId,Array.isArray(n.questions)?n.questions:[],{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl},n.toolCallId))}),e.on("permission-request",n=>{const r=f.get(n.sessionId);if(r){console.log(`[${t.displayName} Adapter] Permission request: ${n.toolName} for agent ${r.agentId}`);const s=n.toolInput?q(JSON.stringify(n.toolInput).slice(0,400)):void 0;_(r.agentId,n.sessionId,"waiting_input",{actionType:"other",actionLabel:"\u6743\u9650\u786E\u8BA4",actionDetail:s||n.toolName},void 0,{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl})}})}A.post("/start",S,async(e,t)=>{const{agentId:n,workspacePath:r,mode:s="sdk"}=e.body||{};if(!n||!r){t.status(400).json({error:"agentId and workspacePath are required"});return}const o=String(e.body?.schedulerBaseUrl||"").trim()||String(e.header("x-bridge-tunnel-source")||"").trim()||be(_e(e))||void 0;Je({agentId:String(n),workspacePath:String(r),serverUrl:e.body?.serverUrl||o,runtimeAccessToken:e.body?.runtimeAccessToken,userId:e.body?.userId,schedulerBaseUrl:o}),s&&s!=="sdk"&&console.warn(`[Runtime] Unsupported runtime mode "${s}" requested for agent ${n}; starting SDK session instead.`),await cn(e,t)});async function cn(e,t){const{agentId:n,workspacePath:r,command:s,autoAccept:o=!0,initialPrompt:i,systemPrompt:a,globalPrompt:c,rolePrompt:d,memory:u,mcpConfigPath:l,extraMcpServers:m,envOverrides:p,idleInputAutoCommand:T,nonInputAutoCommand:y,model:g,instanceAiConfig:b,subAgentModel:$,subAgentEffort:E,scopeKey:Ae}=e.body||{},F=ct();F.log({level:"info",category:"launch",message:"startSdkSession: \u6536\u5230\u542F\u52A8\u8BF7\u6C42",source:"bridge",agentId:String(n||"").trim()||void 0,details:{reqBodyKeys:Object.keys(e.body||{}),perInstanceAiConfig:b?ee(b):null,perAgentModel:g??null}});let D=null;const I=String(n||"").trim(),de=String(e.body?.runtimeAccessToken||"").trim()||void 0,B=String(e.body?.schedulerBaseUrl||"").trim()||String(e.header("x-bridge-tunnel-source")||"").trim()||be(_e(e))||void 0;B?h.info(`[startSdkSession] \u56DE\u8C03\u76EE\u6807 server: ${B} (agentId=${I})`):h.warn(`[startSdkSession] \u672A\u89E3\u6790\u5230 schedulerBaseUrl\uFF0C\u5C06\u56DE\u9000\u5230\u9ED8\u8BA4\u5730\u5740 (agentId=${I})`);try{if(sn(),!I){t.status(400).json({error:"agentId is required"});return}const O=Le(I);if(O){t.json(await Dt(O));return}const k=await rt(I);if(k){const P=Pt(k);if(!P.reusable)console.warn(`[Runtime] Ignoring stale persisted SDK session for agentId=${I}, sessionId=${k.sessionId}, reason=${P.reason}`),await v(k.sessionId);else{const R=oe(k.runtimeStatus,k.runtimeStatus,k.runtimeActionType);t.json({sessionId:k.sessionId,status:R,runtimeStatus:R,runtimeActionType:k.runtimeActionType,runtimeActionLabel:k.runtimeActionLabel,runtimeActionDetail:k.runtimeActionDetail,agentId:k.agentId,workspacePath:k.workspacePath,command:k.command,mode:k.mode||"sdk",pid:k.pid,reused:!0,persistedOnly:!0});return}}if(K.has(I)){t.status(409).json({error:"SDK session is already starting for this agent"});return}K.add(I);const mn=(s||"acode").toLowerCase(),x=qe(s),Ke=w.get(x);D=He();const Fe=x==="claude-code"?await jt():null,V=Ue(x==="claude-code"?Fe:null,p),z=x==="acode"?g?String(g).trim():void 0:(()=>{const P=g?String(g).trim():void 0,R=V.model?String(V.model).trim():void 0;return P||R})();F.log({level:"info",category:"resolve",message:"\u6A21\u578B\u89E3\u6790\u7ED3\u679C",source:"bridge",agentId:I,sessionId:D??void 0,details:{perAgentModel:g??null,globalModel:V.model??null,resolvedModel:z??null,providerId:x,note:x==="acode"?"adapter handles full priority":"request > global"}});const le={...V.envOverrides};z&&(le.ANTHROPIC_MODEL=z,le.CODEX_MODEL=z);let W,me=l;if(x==="acode"){const P=b||{},R=await Ve({apiOverrides:he(P)??void 0,agentId:I,sessionId:D??void 0,runtimeBridgeBaseUrl:B});W=R.instanceConfig.config,me=R.perInstanceConfigPath,F.log({level:"info",category:"apply",message:"prepareAcodeInstanceConfig \u5B8C\u6210",source:"bridge",agentId:I,sessionId:D??void 0,details:{sanitizedApiOverrides:he(P)?ee(he(P)):null,resolvedInstanceAiConfig:W?ee(W):null,perInstanceConfigPath:me,instanceConfigSources:R.instanceConfig.source??null}})}let Te=a||void 0,fe,pe,J;if(x==="acode")if(fe=typeof c=="string"&&c.trim()||void 0,pe=typeof d=="string"&&d.trim()||void 0,typeof u=="string"&&u.trim())J=u.trim();else{const P=await ft(r,{schedulerBaseUrl:B,runtimeAccessToken:de,agentId:I});P&&(J=P,h.info(`[startSdkSession] Auto-loaded memories for ACode agent ${I}`))}else if(typeof c=="string"&&c.trim()||typeof d=="string"&&d.trim()||typeof u=="string"&&u.trim()){const R=[c,d,u,a].filter(Y=>typeof Y=="string"&&Y.trim().length>0).map(Y=>Y.trim());Te=R.length>0?R.join(`
52
52
 
53
- `):void 0}const j={command:s||"acode",workingDirectory:r,agentId:I,autoAccept:!!o,initialPrompt:i,systemPrompt:Ae,...fe!==void 0?{globalPrompt:fe}:{},...pe!==void 0?{rolePrompt:pe}:{},...J!==void 0?{memory:J}:{},model:z,mcpConfigPath:me,...W?{instanceAiConfig:W}:{},...typeof $=="string"&&$.trim()?{subAgentModel:$.trim()}:{},...typeof M=="string"&&M.trim()?{subAgentEffort:M.trim()}:{},extraMcpServers:m||{},envOverrides:Le(String(n),String(r),process.env,le)};F.log({level:"info",category:"launch",message:"\u4F20\u9012\u7ED9 Adapter \u7684\u5B8C\u6574 AdapterSessionConfig",source:"bridge",agentId:I,sessionId:_,details:{adapterModel:j.model??null,adapterInstanceAiConfig:j.instanceAiConfig?ee(j.instanceAiConfig):null,adapterMcpConfigPath:j.mcpConfigPath??null}}),await F.flush(),f.set(_,{agentId:I,workspacePath:r,sessionId:_,config:j,providerId:x,seq:0,runtimeAccessToken:de,schedulerBaseUrl:B}),t.json({sessionId:_,status:"starting",runtimeStatus:"starting",agentId:I,workspacePath:r,command:j.command,mode:"sdk"}),cn({sessionId:_,agentId:I,config:j,adapter:ve,providerId:x,idleInputAutoCommand:T,nonInputAutoCommand:y,runtimeAccessToken:de,requestedSchedulerBaseUrl:B})}catch(O){if(_&&(E(_),f.delete(_)),I&&K.delete(I),!t.headersSent){const k=O instanceof Error?O.message:String(O);t.status(500).json({error:`Failed to start SDK session: ${k}`})}}}async function cn(e){const{sessionId:t,agentId:n,config:r,adapter:s,providerId:o,idleInputAutoCommand:i,nonInputAutoCommand:a,runtimeAccessToken:c,requestedSchedulerBaseUrl:u}=e;try{await s.startSession(t,r),(i||a)&&s.setIdleCommands?.(t,{idleInputCommand:i||"",nonInputCommand:a||""});let d;if(pt(o))try{if(await new Promise(m=>setTimeout(m,500)),d=s.getSessionPid?.(t),!d){const p=(await Je()).find(T=>T.agentId===n||T.cwd===r.workingDirectory||T.command.includes(r.workingDirectory));p&&(d=p.pid,console.log(`[Runtime] Found SDK process PID: ${d} for agentId=${n}`))}}catch(m){console.warn(`[Runtime] Failed to get SDK PID for agentId=${n}:`,m)}const l=oe(s.getSessionStatus(t),f.get(t)?.currentRuntimeStatus,f.get(t)?.currentRuntimeActionType);await it({sessionId:t,agentId:n,workspacePath:r.workingDirectory,command:r.command,startedAt:new Date().toISOString(),status:"running",runtimeStatus:l,mode:"sdk",pid:d,providerSessionId:s.getProviderSessionId(t)}),d&&await ye().startProcess({agentId:n,sessionId:t,pid:d,mode:"sdk",workspacePath:r.workingDirectory,command:r.command}),await un({agentId:n,sessionId:t,sdkPid:d,status:l,schedulerBaseUrl:u,runtimeAccessToken:c})}catch(d){E(t),f.delete(t),await v(t);const l=d instanceof Error?d.message:String(d);console.error(`[Runtime] Background SDK session startup failed for agentId=${n}: ${l}`),await dn({agentId:n,sessionId:t,schedulerBaseUrl:u,runtimeAccessToken:c,errorMessage:l})}finally{K.delete(n)}}async function un(e){const{agentId:t,sessionId:n,sdkPid:r,status:s,schedulerBaseUrl:o,runtimeAccessToken:i}=e;if(!o||!i){h.debug(`[Runtime] notifyServerSessionReady skipped: missing schedulerBaseUrl or runtimeAccessToken for agentId=${t}`);return}const a=`${o.replace(/\/+$/,"")}/api/runtime/callback/status`;try{await ke.post(a,{agentId:t,sessionId:n,status:s,pid:r},{headers:{"X-Runtime-Token":i,"Content-Type":"application/json"},timeout:5e3}),h.debug(`[Runtime] Notified server session ready: agentId=${t}, sessionId=${n}, status=${s}`)}catch(c){const u=c instanceof Error?c.message:String(c);h.warn(`[Runtime] Failed to notify server session ready: agentId=${t}, error=${u}`)}}async function dn(e){const{agentId:t,sessionId:n,schedulerBaseUrl:r,runtimeAccessToken:s}=e;if(!r||!s)return;const o=`${r.replace(/\/+$/,"")}/api/runtime/callback/status`;try{await ke.post(o,{agentId:t,sessionId:n,status:"stopped"},{headers:{"X-Runtime-Token":s,"Content-Type":"application/json"},timeout:5e3}),h.debug(`[Runtime] Notified server session failed: agentId=${t}, sessionId=${n}`)}catch(i){const a=i instanceof Error?i.message:String(i);h.warn(`[Runtime] Failed to notify server session failed: agentId=${t}, error=${a}`)}}A.post("/sdk/message",S,async(e,t)=>{const{sessionId:n,message:r}=e.body||{};if(!n||!r){t.status(400).json({error:"sessionId and message are required"});return}const s=f.get(n);if(!s){t.status(404).json({error:"SDK session not found"});return}try{const o=s.providerId||"claude-code";await C.get(o).sendMessage(n,r),t.json({ok:!0})}catch(o){const i=o instanceof Error?o.message:String(o);t.status(500).json({error:i})}}),A.post("/sdk/answer",S,async(e,t)=>{const{sessionId:n,answers:r}=e.body||{};if(!n||!r){t.status(400).json({error:"sessionId and answers are required"});return}const s=f.get(n);if(!s){t.status(404).json({error:"SDK session not found"});return}try{const o=s.providerId||"claude-code",i=C.get(o);i.sendQuestionAnswer&&await i.sendQuestionAnswer(n,r),t.json({ok:!0})}catch(o){const i=o instanceof Error?o.message:String(o);t.status(500).json({error:i})}}),A.post("/sdk/confirm",S,async(e,t)=>{const{sessionId:n,accept:r}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const s=f.get(n);if(!s){t.status(404).json({error:"SDK session not found"});return}try{const o=s.providerId||"claude-code";await C.get(o).sendConfirmation(n,!!r),t.json({ok:!0})}catch(o){const i=o instanceof Error?o.message:String(o);t.status(500).json({error:i})}}),A.post("/sdk/abort",S,async(e,t)=>{const{sessionId:n}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code";await C.get(s).abortCurrentTurn(n),t.json({ok:!0})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.post("/sdk/stop",S,async(e,t)=>{const{sessionId:n}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.json({ok:!0,status:"stopped"});return}try{const s=r.providerId||"claude-code",o=C.get(s);o.abortCurrentTurn(n).catch(()=>{}),await o.terminateSession(n),E(n),f.delete(n),se(n),await v(n),await ye().removeProcess(r.agentId),await D(r.agentId,null,"stopped",void 0,void 0,{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl}),t.json({ok:!0,status:"stopped"})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.get("/sdk/status/:sessionId",S,(e,t)=>{const n=e.params.sessionId;if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code",o=C.get(s),i=o.getSessionStatus(n),a=o.getConversation(n);t.json({sessionId:n,status:i,agentId:r.agentId,workspacePath:r.workspacePath,messageCount:a.length})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.get("/sdk/capabilities/:sessionId",S,(e,t)=>{const n=e.params.sessionId;if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code",i=C.get(s).getCapabilities?.(n)??null;t.json({ok:!0,sessionId:n,agentId:r.agentId,capabilities:i,fetchedAt:Date.now()})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.get("/sdk/pending-questions/:sessionId",S,(e,t)=>{const n=e.params.sessionId;if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code",i=C.get(s).getPendingQuestion?.(n)??null;t.json({ok:!0,sessionId:n,agentId:r.agentId,pendingQuestion:i?{toolCallId:i.toolCallId,questions:i.questions}:null,fetchedAt:Date.now()})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.post("/command",S,async(e,t)=>{const{sessionId:n,command:r}=e.body||{};if(!n||r===void 0||r===null){t.status(400).json({error:"sessionId and command are required"});return}try{const s=await xt(String(n),r);t.json({ok:!0,mode:"terminal",...s})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.post("/input",S,async(e,t)=>{const{sessionId:n,input:r,mode:s}=e.body||{};if(!n||r===void 0||r===null){t.status(400).json({error:"sessionId and input are required"});return}const o=f.get(n);if(!o){t.status(404).json({error:"SDK session not found"});return}try{const i=o.providerId||"claude-code",a=C.get(i);if(s==="shortcut"){if(!a.sendShortcutInput){t.status(400).json({error:"shortcut input is not supported by this SDK provider"});return}await a.sendShortcutInput(n,String(r)),t.json({ok:!0,mode:"shortcut"});return}await a.sendMessage(n,await Et(r)),t.json({ok:!0,mode:"sdk"})}catch(i){const a=i instanceof Error?i.message:String(i);t.status(500).json({error:a})}}),A.post("/update-auto-commands",S,async(e,t)=>{const{agentId:n,idleInputAutoCommand:r="",nonInputAutoCommand:s=""}=e.body||{},o=String(n||"").trim();if(!o){t.status(400).json({error:"agentId is required"});return}const i=[...f.values()].find(c=>c.agentId===o),a={idleInputCommand:String(r||""),nonInputCommand:String(s||"")};try{let c=!1;i&&(C.get(i.providerId||"claude-code").setIdleCommands?.(i.sessionId,a),c=!0);const u=await ot(o,{idleInputAutoCommand:a.idleInputCommand,nonInputAutoCommand:a.nonInputCommand});t.json({ok:!0,mode:"sdk",sessionUpdated:c,persistedUpdated:u})}catch(c){const u=c instanceof Error?c.message:String(c);t.status(500).json({ok:!1,mode:"sdk",error:u})}}),A.post("/resize",S,(e,t)=>{const{sessionId:n,cols:r,rows:s}=e.body||{};if(!n||!r||!s){t.status(400).json({error:"sessionId, cols, rows are required"});return}if(!f.has(n)){t.status(404).json({error:"SDK session not found"});return}t.json({ok:!0,mode:"sdk",noop:!0,cols:Number(r),rows:Number(s)})}),A.post("/reset-context",S,async(e,t)=>{const{sessionId:n,reason:r}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const s=f.get(n);if(!s){t.status(404).json({error:"SDK session not found"});return}const o=s.providerId||"claude-code",i=C.get(o),a=i.resetContext?.bind(i),c=ft(o,!!a);if(!c.supported){t.status(c.statusCode).json({error:c.error});return}if(!a){t.status(500).json({error:"ACode adapter does not expose resetContext"});return}try{await a(String(n));const u=oe(i.getSessionStatus(String(n)),s.currentRuntimeStatus,s.currentRuntimeActionType);t.json({ok:!0,contextReset:!0,sessionId:n,status:u,runtimeStatus:u,agentId:s.agentId,mode:"sdk",providerId:o,reason:typeof r=="string"&&r.trim()?r.trim():void 0})}catch(u){const d=u instanceof Error?u.message:String(u);t.status(500).json({ok:!1,contextReset:!1,mode:"sdk",error:d})}}),A.post("/stop",S,async(e,t)=>{const{sessionId:n}=e.body||{},r=gt(e.body);if(!n){t.status(400).json({error:"sessionId is required"});return}const s=f.get(n);if(!s){await v(n),t.json({ok:!0,status:"stopped",mode:"none",statusNotified:!1,reason:r.reason});return}const o=s.agentId;try{console.log(`[Runtime] Stopping SDK session ${n}; suppressStatus=${!r.statusNotified}, reason=${r.reason||"unspecified"}`);const i=s.providerId||"claude-code",a=C.get(i);a.abortCurrentTurn(n).catch(()=>{}),await a.terminateSession(n),E(n),f.delete(n),se(n),await v(n),await ye().removeProcess(o),r.statusNotified?await D(o,null,"stopped",void 0,void 0,{runtimeAccessToken:s.runtimeAccessToken,schedulerBaseUrl:s.schedulerBaseUrl}):console.log(`[Runtime] Stopped status notification suppressed for SDK session ${n}; reason=${r.reason||"unspecified"}`),t.json({ok:!0,status:"stopped",mode:"sdk",statusNotified:r.statusNotified,reason:r.reason})}catch(i){const a=i instanceof Error?i.message:String(i);console.error(`[Runtime] Failed to terminate SDK session ${n}:`,a),t.status(500).json({ok:!1,status:"stop_failed",mode:"sdk",error:a})}}),A.post("/stop-all",S,async(e,t)=>{const n=[],r=[];for(const[s,o]of f.entries())try{const i=o.providerId||"claude-code",a=C.get(i);a.abortCurrentTurn(s).catch(()=>{}),await a.terminateSession(s),E(s),f.delete(s),se(s),n.push(s),await D(o.agentId,null,"stopped",void 0,void 0,{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})}catch(i){const a=i instanceof Error?i.message:String(i);r.push(`SDK ${s}: ${a}`)}try{await rt([]),console.log("[Runtime] \u5DF2\u6E05\u7A7A\u6240\u6709\u6301\u4E45\u5316\u4F1A\u8BDD")}catch(s){const o=s instanceof Error?s.message:String(s);r.push(`Persistence: ${o}`)}t.json({ok:!0,stopped:{sdk:n.length},errors:r.length>0?r:void 0})}),A.get("/events/last/:n",S,(e,t)=>{const n=parseInt(e.params.n,10);if(!Number.isFinite(n)||n<1){t.status(400).json({error:":n must be a positive integer"});return}const r=be.getLastN(n);t.json({ok:!0,count:r.length,entries:r})}),A.get("/events/since/:index",S,(e,t)=>{const n=parseInt(e.params.index,10);if(!Number.isFinite(n)||n<0){t.status(400).json({error:":index must be a non-negative integer"});return}const r=be.getSinceIndex(n);t.json({ok:!0,entries:r.entries,nextIndex:r.nextIndex,oldestIndex:r.oldestIndex,dataLoss:r.oldestIndex>n+1})}),A.get("/events/push-stats",S,(e,t)=>{const n=et();t.json({ok:!0,count:n.length,agents:n})});export{It as buildAcodeCommandOutputPath,je as buildClaudeCodeLaunchConfig,Le as buildRuntimeEnv,Nt as buildSdkOutputMetadata,Bt as buildToolResultTimelineActionInfo,En as cleanupSdkSessionByAgentId,St as countTerminalOutputLines,Me as createTerminalOutputDecoder,re as decodeTerminalOutputChunk,_t as evaluatePersistedSessionReuse,Tt as formatCommandInactivityTimeoutNotice,At as formatCommandOutputSpilloverNotice,Ot as formatSdkOutputEvent,Ie as formatTerminalPrompt,kt as normalizeTerminalCommandInput,gt as parseRuntimeStopOptions,bt as parseTerminalDirectoryChangeTarget,ce as raceSendOutputWithRetry,ft as resolveRuntimeContextResetSupport,Zt as resolveRuntimeStatusFromProviderEvent,Et as resolveSdkInputMessage,Ne as resolveSdkProviderId,oe as resolveSdkSessionDisplayStatus,yt as resolveStatusChangeRuntimeState,ne as resolveStatusChangeUsage,Ct as resolveTerminalOutputEncoding,f as sdkSessions,pt as shouldProbeSdkProcessPid,A as terminalRouter};
53
+ `):void 0}const j={command:s||"acode",workingDirectory:r,agentId:I,...Ae?{scopeKey:Ae}:{},autoAccept:!!o,initialPrompt:i,systemPrompt:Te,...fe!==void 0?{globalPrompt:fe}:{},...pe!==void 0?{rolePrompt:pe}:{},...J!==void 0?{memory:J}:{},model:z,mcpConfigPath:me,...W?{instanceAiConfig:W}:{},...typeof $=="string"&&$.trim()?{subAgentModel:$.trim()}:{},...typeof E=="string"&&E.trim()?{subAgentEffort:E.trim()}:{},extraMcpServers:m||{},envOverrides:je(String(n),String(r),process.env,le)};F.log({level:"info",category:"launch",message:"\u4F20\u9012\u7ED9 Adapter \u7684\u5B8C\u6574 AdapterSessionConfig",source:"bridge",agentId:I,sessionId:D,details:{adapterModel:j.model??null,adapterInstanceAiConfig:j.instanceAiConfig?ee(j.instanceAiConfig):null,adapterMcpConfigPath:j.mcpConfigPath??null}}),await F.flush(),f.set(D,{agentId:I,workspacePath:r,sessionId:D,config:j,providerId:x,seq:0,runtimeAccessToken:de,schedulerBaseUrl:B}),t.json({sessionId:D,status:"starting",runtimeStatus:"starting",agentId:I,workspacePath:r,command:j.command,mode:"sdk"}),un({sessionId:D,agentId:I,config:j,adapter:Ke,providerId:x,idleInputAutoCommand:T,nonInputAutoCommand:y,runtimeAccessToken:de,requestedSchedulerBaseUrl:B})}catch(O){if(D&&(M(D),f.delete(D)),I&&K.delete(I),!t.headersSent){const k=O instanceof Error?O.message:String(O);t.status(500).json({error:`Failed to start SDK session: ${k}`})}}}async function un(e){const{sessionId:t,agentId:n,config:r,adapter:s,providerId:o,idleInputAutoCommand:i,nonInputAutoCommand:a,runtimeAccessToken:c,requestedSchedulerBaseUrl:d}=e;try{await s.startSession(t,r),(i||a)&&s.setIdleCommands?.(t,{idleInputCommand:i||"",nonInputCommand:a||""});let u;if(gt(o))try{if(await new Promise(m=>setTimeout(m,500)),u=s.getSessionPid?.(t),!u){const p=(await Ye()).find(T=>T.agentId===n||T.cwd===r.workingDirectory||T.command.includes(r.workingDirectory));p&&(u=p.pid,console.log(`[Runtime] Found SDK process PID: ${u} for agentId=${n}`))}}catch(m){console.warn(`[Runtime] Failed to get SDK PID for agentId=${n}:`,m)}const l=oe(s.getSessionStatus(t),f.get(t)?.currentRuntimeStatus,f.get(t)?.currentRuntimeActionType);await at({sessionId:t,agentId:n,workspacePath:r.workingDirectory,command:r.command,startedAt:new Date().toISOString(),status:"running",runtimeStatus:l,mode:"sdk",pid:u,providerSessionId:s.getProviderSessionId(t)}),u&&await ye().startProcess({agentId:n,sessionId:t,pid:u,mode:"sdk",workspacePath:r.workingDirectory,command:r.command}),await dn({agentId:n,sessionId:t,sdkPid:u,status:l,schedulerBaseUrl:d,runtimeAccessToken:c})}catch(u){M(t),f.delete(t),await v(t);const l=u instanceof Error?u.message:String(u);console.error(`[Runtime] Background SDK session startup failed for agentId=${n}: ${l}`),await ln({agentId:n,sessionId:t,schedulerBaseUrl:d,runtimeAccessToken:c,errorMessage:l})}finally{K.delete(n)}}async function dn(e){const{agentId:t,sessionId:n,sdkPid:r,status:s,schedulerBaseUrl:o,runtimeAccessToken:i}=e;if(!o||!i){h.debug(`[Runtime] notifyServerSessionReady skipped: missing schedulerBaseUrl or runtimeAccessToken for agentId=${t}`);return}const a=`${o.replace(/\/+$/,"")}/api/runtime/callback/status`;try{await we.post(a,{agentId:t,sessionId:n,status:s,pid:r},{headers:{"X-Runtime-Token":i,"Content-Type":"application/json"},timeout:5e3}),h.debug(`[Runtime] Notified server session ready: agentId=${t}, sessionId=${n}, status=${s}`)}catch(c){const d=c instanceof Error?c.message:String(c);h.warn(`[Runtime] Failed to notify server session ready: agentId=${t}, error=${d}`)}}async function ln(e){const{agentId:t,sessionId:n,schedulerBaseUrl:r,runtimeAccessToken:s}=e;if(!r||!s)return;const o=`${r.replace(/\/+$/,"")}/api/runtime/callback/status`;try{await we.post(o,{agentId:t,sessionId:n,status:"stopped"},{headers:{"X-Runtime-Token":s,"Content-Type":"application/json"},timeout:5e3}),h.debug(`[Runtime] Notified server session failed: agentId=${t}, sessionId=${n}`)}catch(i){const a=i instanceof Error?i.message:String(i);h.warn(`[Runtime] Failed to notify server session failed: agentId=${t}, error=${a}`)}}A.post("/sdk/message",S,async(e,t)=>{const{sessionId:n,message:r}=e.body||{};if(!n||!r){t.status(400).json({error:"sessionId and message are required"});return}const s=f.get(n);if(!s){t.status(404).json({error:"SDK session not found"});return}try{const o=s.providerId||"claude-code";await w.get(o).sendMessage(n,r),t.json({ok:!0})}catch(o){const i=o instanceof Error?o.message:String(o);t.status(500).json({error:i})}}),A.post("/sdk/answer",S,async(e,t)=>{const{sessionId:n,answers:r}=e.body||{};if(!n||!r){t.status(400).json({error:"sessionId and answers are required"});return}const s=f.get(n);if(!s){t.status(404).json({error:"SDK session not found"});return}try{const o=s.providerId||"claude-code",i=w.get(o);i.sendQuestionAnswer&&await i.sendQuestionAnswer(n,r),t.json({ok:!0})}catch(o){const i=o instanceof Error?o.message:String(o);t.status(500).json({error:i})}}),A.post("/sdk/confirm",S,async(e,t)=>{const{sessionId:n,accept:r}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const s=f.get(n);if(!s){t.status(404).json({error:"SDK session not found"});return}try{const o=s.providerId||"claude-code";await w.get(o).sendConfirmation(n,!!r),t.json({ok:!0})}catch(o){const i=o instanceof Error?o.message:String(o);t.status(500).json({error:i})}}),A.post("/sdk/abort",S,async(e,t)=>{const{sessionId:n}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code";await w.get(s).abortCurrentTurn(n),t.json({ok:!0})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.post("/sdk/stop",S,async(e,t)=>{const{sessionId:n}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.json({ok:!0,status:"stopped"});return}try{const s=r.providerId||"claude-code",o=w.get(s);o.abortCurrentTurn(n).catch(()=>{}),await o.terminateSession(n),M(n),f.delete(n),se(n),await v(n),await ye().removeProcess(r.agentId),await _(r.agentId,null,"stopped",void 0,void 0,{runtimeAccessToken:r.runtimeAccessToken,schedulerBaseUrl:r.schedulerBaseUrl}),t.json({ok:!0,status:"stopped"})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.get("/sdk/status/:sessionId",S,(e,t)=>{const n=e.params.sessionId;if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code",o=w.get(s),i=o.getSessionStatus(n),a=o.getConversation(n);t.json({sessionId:n,status:i,agentId:r.agentId,workspacePath:r.workspacePath,messageCount:a.length})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.get("/sdk/capabilities/:sessionId",S,(e,t)=>{const n=e.params.sessionId;if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code",i=w.get(s).getCapabilities?.(n)??null;t.json({ok:!0,sessionId:n,agentId:r.agentId,capabilities:i,fetchedAt:Date.now()})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.get("/sdk/pending-questions/:sessionId",S,(e,t)=>{const n=e.params.sessionId;if(!n){t.status(400).json({error:"sessionId is required"});return}const r=f.get(n);if(!r){t.status(404).json({error:"SDK session not found"});return}try{const s=r.providerId||"claude-code",i=w.get(s).getPendingQuestion?.(n)??null;t.json({ok:!0,sessionId:n,agentId:r.agentId,pendingQuestion:i?{toolCallId:i.toolCallId,questions:i.questions}:null,fetchedAt:Date.now()})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.post("/command",S,async(e,t)=>{const{sessionId:n,command:r}=e.body||{};if(!n||r===void 0||r===null){t.status(400).json({error:"sessionId and command are required"});return}try{const s=await Et(String(n),r);t.json({ok:!0,mode:"terminal",...s})}catch(s){const o=s instanceof Error?s.message:String(s);t.status(500).json({error:o})}}),A.post("/input",S,async(e,t)=>{const{sessionId:n,input:r,mode:s}=e.body||{};if(!n||r===void 0||r===null){t.status(400).json({error:"sessionId and input are required"});return}const o=f.get(n);if(!o){t.status(404).json({error:"SDK session not found"});return}try{const i=o.providerId||"claude-code",a=w.get(i);if(s==="shortcut"){if(!a.sendShortcutInput){t.status(400).json({error:"shortcut input is not supported by this SDK provider"});return}await a.sendShortcutInput(n,String(r)),t.json({ok:!0,mode:"shortcut"});return}await a.sendMessage(n,await Lt(r)),t.json({ok:!0,mode:"sdk"})}catch(i){const a=i instanceof Error?i.message:String(i);t.status(500).json({error:a})}}),A.post("/update-auto-commands",S,async(e,t)=>{const{agentId:n,idleInputAutoCommand:r="",nonInputAutoCommand:s=""}=e.body||{},o=String(n||"").trim();if(!o){t.status(400).json({error:"agentId is required"});return}const i=[...f.values()].find(c=>c.agentId===o),a={idleInputCommand:String(r||""),nonInputCommand:String(s||"")};try{let c=!1;i&&(w.get(i.providerId||"claude-code").setIdleCommands?.(i.sessionId,a),c=!0);const d=await st(o,{idleInputAutoCommand:a.idleInputCommand,nonInputAutoCommand:a.nonInputCommand});t.json({ok:!0,mode:"sdk",sessionUpdated:c,persistedUpdated:d})}catch(c){const d=c instanceof Error?c.message:String(c);t.status(500).json({ok:!1,mode:"sdk",error:d})}}),A.post("/resize",S,(e,t)=>{const{sessionId:n,cols:r,rows:s}=e.body||{};if(!n||!r||!s){t.status(400).json({error:"sessionId, cols, rows are required"});return}if(!f.has(n)){t.status(404).json({error:"SDK session not found"});return}t.json({ok:!0,mode:"sdk",noop:!0,cols:Number(r),rows:Number(s)})}),A.post("/reset-context",S,async(e,t)=>{const{sessionId:n,reason:r}=e.body||{};if(!n){t.status(400).json({error:"sessionId is required"});return}const s=f.get(n);if(!s){t.status(404).json({error:"SDK session not found"});return}const o=s.providerId||"claude-code",i=w.get(o),a=i.resetContext?.bind(i),c=pt(o,!!a);if(!c.supported){t.status(c.statusCode).json({error:c.error});return}if(!a){t.status(500).json({error:"ACode adapter does not expose resetContext"});return}try{await a(String(n));const d=oe(i.getSessionStatus(String(n)),s.currentRuntimeStatus,s.currentRuntimeActionType);t.json({ok:!0,contextReset:!0,sessionId:n,status:d,runtimeStatus:d,agentId:s.agentId,mode:"sdk",providerId:o,reason:typeof r=="string"&&r.trim()?r.trim():void 0})}catch(d){const u=d instanceof Error?d.message:String(d);t.status(500).json({ok:!1,contextReset:!1,mode:"sdk",error:u})}}),A.post("/stop",S,async(e,t)=>{const{sessionId:n}=e.body||{},r=yt(e.body);if(!n){t.status(400).json({error:"sessionId is required"});return}const s=f.get(n);if(!s){await v(n),t.json({ok:!0,status:"stopped",mode:"none",statusNotified:!1,reason:r.reason});return}const o=s.agentId;try{console.log(`[Runtime] Stopping SDK session ${n}; suppressStatus=${!r.statusNotified}, reason=${r.reason||"unspecified"}`);const i=s.providerId||"claude-code",a=w.get(i);a.abortCurrentTurn(n).catch(()=>{}),await a.terminateSession(n),M(n),f.delete(n),se(n),await v(n),await ye().removeProcess(o),r.statusNotified?await _(o,null,"stopped",void 0,void 0,{runtimeAccessToken:s.runtimeAccessToken,schedulerBaseUrl:s.schedulerBaseUrl}):console.log(`[Runtime] Stopped status notification suppressed for SDK session ${n}; reason=${r.reason||"unspecified"}`),t.json({ok:!0,status:"stopped",mode:"sdk",statusNotified:r.statusNotified,reason:r.reason})}catch(i){const a=i instanceof Error?i.message:String(i);console.error(`[Runtime] Failed to terminate SDK session ${n}:`,a),t.status(500).json({ok:!1,status:"stop_failed",mode:"sdk",error:a})}}),A.post("/stop-all",S,async(e,t)=>{const n=[],r=[];for(const[s,o]of f.entries())try{const i=o.providerId||"claude-code",a=w.get(i);a.abortCurrentTurn(s).catch(()=>{}),await a.terminateSession(s),M(s),f.delete(s),se(s),n.push(s),await _(o.agentId,null,"stopped",void 0,void 0,{runtimeAccessToken:o.runtimeAccessToken,schedulerBaseUrl:o.schedulerBaseUrl})}catch(i){const a=i instanceof Error?i.message:String(i);r.push(`SDK ${s}: ${a}`)}try{await ot([]),console.log("[Runtime] \u5DF2\u6E05\u7A7A\u6240\u6709\u6301\u4E45\u5316\u4F1A\u8BDD")}catch(s){const o=s instanceof Error?s.message:String(s);r.push(`Persistence: ${o}`)}t.json({ok:!0,stopped:{sdk:n.length},errors:r.length>0?r:void 0})}),A.get("/events/last/:n",S,(e,t)=>{const n=parseInt(e.params.n,10);if(!Number.isFinite(n)||n<1){t.status(400).json({error:":n must be a positive integer"});return}const r=$e.getLastN(n);t.json({ok:!0,count:r.length,entries:r})}),A.get("/events/since/:index",S,(e,t)=>{const n=parseInt(e.params.index,10);if(!Number.isFinite(n)||n<0){t.status(400).json({error:":index must be a non-negative integer"});return}const r=$e.getSinceIndex(n);t.json({ok:!0,entries:r.entries,nextIndex:r.nextIndex,oldestIndex:r.oldestIndex,dataLoss:r.oldestIndex>n+1})}),A.get("/events/push-stats",S,(e,t)=>{const n=tt();t.json({ok:!0,count:n.length,agents:n})});export{St as buildAcodeCommandOutputPath,Ue as buildClaudeCodeLaunchConfig,je as buildRuntimeEnv,qt as buildSdkOutputMetadata,Ot as buildToolResultTimelineActionInfo,Ln as cleanupSdkSessionByAgentId,At as countTerminalOutputLines,Me as createTerminalOutputDecoder,re as decodeTerminalOutputChunk,Pt as evaluatePersistedSessionReuse,kt as formatCommandInactivityTimeoutNotice,Tt as formatCommandOutputSpilloverNotice,Nt as formatSdkOutputEvent,Ie as formatTerminalPrompt,wt as normalizeTerminalCommandInput,yt as parseRuntimeStopOptions,$t as parseTerminalDirectoryChangeTarget,ce as raceSendOutputWithRetry,pt as resolveRuntimeContextResetSupport,en as resolveRuntimeStatusFromProviderEvent,Lt as resolveSdkInputMessage,qe as resolveSdkProviderId,oe as resolveSdkSessionDisplayStatus,ht as resolveStatusChangeRuntimeState,ne as resolveStatusChangeUsage,Ct as resolveTerminalOutputEncoding,f as sdkSessions,gt as shouldProbeSdkProcessPid,A as terminalRouter};
54
54
 
@@ -0,0 +1,22 @@
1
+
2
+ import type { TerminalManager, TerminalCreateOpts, TerminalReadOpts, TerminalReadResult } from "@agentswork/acode";
3
+
4
+ export declare function detectNeedsInput(text: string): boolean;
5
+ export declare class AgentPtyManager implements TerminalManager {
6
+ private cursors;
7
+ private idleTimers;
8
+ create(opts: TerminalCreateOpts): {
9
+ id: string;
10
+ pid: number | undefined;
11
+ };
12
+ write(id: string, data: string): void;
13
+ read(id: string, opts: TerminalReadOpts): TerminalReadResult;
14
+ kill(id: string): void;
15
+
16
+ killByAgent(agentId: string): void;
17
+ resize(id: string, cols: number, rows: number): void;
18
+
19
+ private touch;
20
+ private clearIdle;
21
+ }
22
+ export declare const agentPtyManager: AgentPtyManager;
@@ -0,0 +1,5 @@
1
+ import{ptySessions as c,createPtySession as p,closePtySession as l}from"../routes/pty.js";const y=30*60*1e3,g=2e3,u=500;function T(a){const e=a.trimEnd();if(!e)return!1;const t=e.split(`
2
+ `).pop()??"";return!!(/[:?]\s*$/.test(t)||/\((?:yes\/no|Y\/N|y\/n)\)/i.test(t)||/\b[Yy]\/?[Nn]\b/.test(t)||/\(press RETURN\)/i.test(t)||/\(press ENTER\)/i.test(t)||/press ENTER[^]*continue/i.test(t))}class M{constructor(){this.cursors=new Map,this.idleTimers=new Map}create(e){const t=e.shell&&e.shell.trim()?e.shell.trim():"auto",s=typeof e.cols=="number"&&e.cols>0?Math.min(e.cols,u):120,r=typeof e.rows=="number"&&e.rows>0?Math.min(e.rows,u):30,i=e.preCommand&&e.preCommand.trim()?e.preCommand:void 0,n=p({workspacePath:e.cwd,shell:t,cols:s,rows:r,preCommand:i,persistent:!0,ownerUserId:e.agentId}),o=c.get(n.id);return this.cursors.set(n.id,0),this.touch(n.id),{id:n.id,pid:o?.ptyProcess.pid}}write(e,t){const s=c.get(e);!s||s.status==="exited"||(s.ptyProcess.write(t.replace(/\n/g,"\r")),this.touch(e))}read(e,t){const s=c.get(e);if(!s)return{status:"closed",exit_code:null,output:"",needs_input:!1,truncated:!1};this.touch(e);const r=s.outputBuffer,i=this.cursors.get(e)??0,n=i>=r.length?"":r.slice(i);this.cursors.set(e,r.length);const o=n.split(`
3
+ `),m=Math.min(Math.max(1,t.lines??200),g);let h=o,d=!1;o.length>m&&(h=o.slice(o.length-m),d=!0);const f=s.status==="running"&&T(n);return{status:s.status,exit_code:s.exitCode??null,output:h.join(`
4
+ `),needs_input:f,truncated:d}}kill(e){l(e,"agent-kill"),this.cursors.delete(e),this.clearIdle(e)}killByAgent(e){if(!e)return;const t=[];for(const[s,r]of c.entries())r.ownerUserId===e&&t.push(s);for(const s of t){try{l(s,`agent-stop:${e}`)}catch{}this.cursors.delete(s),this.clearIdle(s)}}resize(e,t,s){const r=c.get(e);if(!r)return;const i=typeof t=="number"&&t>0?Math.min(t,u):120,n=typeof s=="number"&&s>0?Math.min(s,u):30;r.ptyProcess.resize(i,n)}touch(e){const t=this.idleTimers.get(e);t&&clearTimeout(t);const s=setTimeout(()=>{l(e,"agent-idle-timeout"),this.cursors.delete(e),this.idleTimers.delete(e)},y);s.unref?.(),this.idleTimers.set(e,s)}clearIdle(e){const t=this.idleTimers.get(e);t&&clearTimeout(t),this.idleTimers.delete(e)}}const E=new M;export{M as AgentPtyManager,E as agentPtyManager,T as detectNeedsInput};
5
+
@@ -0,0 +1,55 @@
1
+
2
+ import { type BrowserPool } from "../browser/browser-pool.js";
3
+ import { type BrowserWsServer } from "../browser/ws-server.js";
4
+ import { createBuiltInBrowserTools } from "../browser/built-in-browser-tools.js";
5
+ import type { BrowserPoolConfig, WsServerConfig } from "../browser/types.js";
6
+ import type { PageListener, PageListenerInfo, ListenerId, ListenerTriggerEvent } from "../browser/page-listener-types.js";
7
+ import type { AddListenerParams, UpdateListenerParams } from "../browser/page-listener-manager.js";
8
+
9
+ interface BrowserSessionManagerState {
10
+ pool: BrowserPool;
11
+ wsServer: BrowserWsServer;
12
+ wsPort: number;
13
+ wsHost: string;
14
+ }
15
+
16
+ export declare function startBrowserSessionManager(poolConfig?: Partial<BrowserPoolConfig>, wsConfig?: Partial<WsServerConfig>): Promise<BrowserSessionManagerState>;
17
+
18
+ export declare function getBrowserWsUrl(agentId: string, browserId?: string): string | null;
19
+
20
+ export declare function listBrowserWsUrls(agentId: string): Array<{
21
+ browserId: string;
22
+ title: string;
23
+ wsUrl: string;
24
+ }>;
25
+
26
+ export declare function getBrowserWsPort(): number | null;
27
+
28
+ export declare function getBrowserTools(agentId: string | undefined, scopeKey?: string): Promise<ReturnType<typeof createBuiltInBrowserTools>>;
29
+
30
+ export declare function closeBrowserSession(agentId: string): Promise<void>;
31
+
32
+ export declare function closeBrowserSessionById(agentId: string, browserId?: string): Promise<void>;
33
+
34
+ export declare function disposeBrowserSessionManager(): Promise<void>;
35
+
36
+ export declare function isBrowserSessionManagerStarted(): boolean;
37
+
38
+ export declare function addBrowserListener(agentId: string, browserId: string, params: AddListenerParams): Promise<PageListener>;
39
+
40
+ export declare function updateBrowserListener(agentId: string, browserId: string, listenerId: ListenerId, params: Omit<UpdateListenerParams, "listenerId">): Promise<PageListener | undefined>;
41
+
42
+ export declare function removeBrowserListener(agentId: string, browserId: string, listenerId: ListenerId): Promise<boolean>;
43
+
44
+ export declare function toggleBrowserListener(agentId: string, browserId: string, listenerId: ListenerId, enabled?: boolean): Promise<PageListener | undefined>;
45
+
46
+ export declare function listBrowserListeners(agentId: string, browserId: string): Promise<PageListenerInfo[]>;
47
+
48
+ export declare function collectAgentListenerEvents(agentId: string): Promise<ListenerTriggerEvent[]>;
49
+
50
+ export declare function registerListenerWakeHook(agentId: string | undefined, fn: () => void): void;
51
+
52
+ export declare function unregisterListenerWakeHook(agentId: string | undefined, fn?: () => void): void;
53
+
54
+ export declare function buildListenerInjectionPrompt(events: ListenerTriggerEvent[]): string;
55
+ export {};
@@ -0,0 +1,12 @@
1
+ import{resolve as g}from"node:path";import{getBrowserPool as L,disposeBrowserPool as y}from"../browser/browser-pool.js";import{getBrowserWsServer as S,stopBrowserWsServer as B}from"../browser/ws-server.js";import{createBuiltInBrowserTools as h}from"../browser/built-in-browser-tools.js";import{WS_HOST as d}from"../browser/types.js";let t=null,a=null;const x={headless:!0,stealth:!0,viewportWidth:1280,viewportHeight:800,maxPagesPerSession:5,maxSessionDurationMs:0,idleTimeoutMs:0,profileDir:T()},W={port:v(),host:d,heartbeatMs:30*1e3,idleTimeoutMs:30*60*1e3};function v(){const r=process.env.AWS_BROWSER_WS_PORT;if(r){const e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<65536)return e}return 7891}function T(){const r=process.env.AWS_BROWSER_PROFILE_DIR;return r||g(process.cwd(),".browser-profiles")}async function P(r,e){return t||a||(a=(async()=>{const o=L({...x,...r}),s=await S(o,{...W,...e}),{port:n,host:i}=await s.start();o.setListenerTriggerHook((c,f,l,m)=>{try{s.broadcastListenerTriggered(c,f,{listenerId:l.listenerId,selector:m.selector,prompt:l.prompt,url:l.url,text:l.text??"",at:l.triggeredAt,changeType:l.changeType})}catch{}u(c,f).catch(()=>{});try{w.get(c)?.()}catch{}});const p={pool:o,wsServer:s,wsPort:n,wsHost:i};return t=p,a=null,p})(),a)}function O(r,e){return!t||!r?null:t.wsServer.getUrl(r,e)}function U(r){return!t||!r?[]:t.pool.listSessions(r).map(o=>({browserId:o.browserId,title:o.title,wsUrl:t.wsServer.getUrl(r,o.browserId)}))}function b(){return t?.wsPort??null}async function H(r,e){return r?(await P(),t?h({pool:t.pool,wsServer:t.wsServer,agentId:r,scopeKey:e}):[]):[]}async function R(r){if(!(!t||!r))try{await t.pool.closeByAgent(r)}catch{}}async function k(r,e){if(!(!t||!r))try{await t.pool.close(r,e)}catch{}}async function D(){if(t)try{await B(),await y()}finally{t=null,a=null}}function F(){return t!==null}async function C(r,e,o){if(!t||!r)throw new Error("browser manager not started");const s=t.pool.get(r,e);if(!s)throw new Error(`Browser session not launched for ${r}/${e}. Call browser_launch first.`);const n=await s.listenerManager.addListener(o);return await u(r,e),n}async function N(r,e,o,s){if(!t||!r)return;const n=t.pool.get(r,e);if(!n)return;const i=await n.listenerManager.updateListener({...s,listenerId:o});return await u(r,e),i}async function G(r,e,o){if(!t||!r)return!1;const s=t.pool.get(r,e);if(!s)return!1;const n=await s.listenerManager.removeListener(o);return await u(r,e),n}async function j(r,e,o,s){if(!t||!r)return;const n=t.pool.get(r,e);if(!n)return;const i=await n.listenerManager.toggleListener(o,s);return await u(r,e),i}async function Y(r,e){if(!t||!r)return[];const o=t.pool.get(r,e);return o?o.listenerManager.listListeners():[]}async function u(r,e){if(!t)return;const o=t.pool.get(r,e);if(o)try{const s=await o.listenerManager.listListeners();t.wsServer.broadcastListenerUpdate(r,e,s)}catch{}}async function q(r){return!t||!r?[]:t.pool.collectListenerEvents(r)}const w=new Map;function z(r,e){r&&w.set(r,e)}function J(r,e){r&&(e&&w.get(r)!==e||w.delete(r))}function K(r){if(r.length===0)return"";const e={added:"\u65B0\u589E",removed:"\u5220\u9664",changed:"\u6539\u53D8"};return`\u7CFB\u7EDF\u63D0\u9192\uFF1A\u4EE5\u4E0B\u6D4F\u89C8\u5668\u76D1\u542C\u5668\u5DF2\u89E6\u53D1\uFF0C\u8BF7\u7ACB\u5373\u5904\u7406\uFF1A
2
+
3
+ `+r.map((s,n)=>{const i=s.browserId&&s.browserId!=="default"?`\u6D4F\u89C8\u5668[${s.browserId}]`:"\u6D4F\u89C8\u5668",p=s.selector?`\u5143\u7D20\u9009\u62E9\u5668: ${s.selector}
4
+ `:"",c=e[s.changeType??"changed"]??"\u6539\u53D8",f=new Date(s.triggeredAt).toISOString();return`\u3010\u76D1\u542C\u5668\u4E8B\u4EF6 ${n+1} | ${i} | URL: ${s.url}\u3011
5
+ ${p}\u53D8\u5316\u7C7B\u578B: ${c}
6
+ \u89E6\u53D1\u65F6\u95F4: ${f}
7
+ \u63D0\u793A\u8BCD: ${s.prompt}`}).join(`
8
+
9
+ `)+`
10
+
11
+ \u5904\u7406\u5B8C\u6210\u540E\u7EE7\u7EED\u901A\u8FC7 poll_message \u7B49\u5F85\u4E0B\u4E00\u4E2A\u4EFB\u52A1\u3002`}export{C as addBrowserListener,K as buildListenerInjectionPrompt,R as closeBrowserSession,k as closeBrowserSessionById,q as collectAgentListenerEvents,D as disposeBrowserSessionManager,H as getBrowserTools,b as getBrowserWsPort,O as getBrowserWsUrl,F as isBrowserSessionManagerStarted,Y as listBrowserListeners,U as listBrowserWsUrls,z as registerListenerWakeHook,G as removeBrowserListener,P as startBrowserSessionManager,j as toggleBrowserListener,J as unregisterListenerWakeHook,N as updateBrowserListener};
12
+
@@ -49,4 +49,8 @@ export declare function createLaunchdPlistContent(executablePath: string, option
49
49
  userHomeDir?: string;
50
50
  logPath?: string;
51
51
  }): string;
52
+
53
+ export declare function defaultFindRunningBridgeProcesses(platform: NodeJS.Platform): number[];
54
+
55
+ export declare function defaultKillBridgeProcess(pid: number, platform: NodeJS.Platform): void;
52
56
  export declare function handleCliCommand(options?: CliCommandOptions): Promise<CliCommandResult>;