agentroam-runtime-darwin-arm64 0.2.0-preview.7 → 0.2.0-preview.9

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 (237) hide show
  1. package/manifest.json +1 -1
  2. package/package.json +1 -1
  3. package/runtime/.next/BUILD_ID +1 -1
  4. package/runtime/.next/app-build-manifest.json +12 -12
  5. package/runtime/.next/app-path-routes-manifest.json +1 -1
  6. package/runtime/.next/build-manifest.json +9 -9
  7. package/runtime/.next/prerender-manifest.json +1 -1
  8. package/runtime/.next/react-loadable-manifest.json +2 -2
  9. package/runtime/.next/routes-manifest.json +1 -1
  10. package/runtime/.next/server/app/_not-found/page.js +1 -1
  11. package/runtime/.next/server/app/_not-found/page.js.nft.json +1 -1
  12. package/runtime/.next/server/app/_not-found.html +1 -1
  13. package/runtime/.next/server/app/_not-found.rsc +1 -1
  14. package/runtime/.next/server/app/api/agent/abort/route.js +2 -2
  15. package/runtime/.next/server/app/api/agent/abort/route.js.nft.json +1 -1
  16. package/runtime/.next/server/app/api/agent/answer/route.js +2 -2
  17. package/runtime/.next/server/app/api/agent/answer/route.js.nft.json +1 -1
  18. package/runtime/.next/server/app/api/agent/model/route.js +2 -2
  19. package/runtime/.next/server/app/api/agent/model/route.js.nft.json +1 -1
  20. package/runtime/.next/server/app/api/agent/run/route.js +2 -2
  21. package/runtime/.next/server/app/api/agent/run/route.js.nft.json +1 -1
  22. package/runtime/.next/server/app/api/agent/runtime-health/route.js +1 -1
  23. package/runtime/.next/server/app/api/agent/runtime-health/route.js.nft.json +1 -1
  24. package/runtime/.next/server/app/api/agent/steer/route.js +2 -2
  25. package/runtime/.next/server/app/api/agent/steer/route.js.nft.json +1 -1
  26. package/runtime/.next/server/app/api/agent/stream/route.js +5 -5
  27. package/runtime/.next/server/app/api/agent/stream/route.js.nft.json +1 -1
  28. package/runtime/.next/server/app/api/agent-workspaces/[workspaceId]/sessions/route.js +1 -0
  29. package/runtime/.next/server/app/api/agent-workspaces/[workspaceId]/sessions/route.js.nft.json +1 -0
  30. package/runtime/.next/server/app/api/agent-workspaces/route.js +1 -0
  31. package/runtime/.next/server/app/api/agent-workspaces/route.js.nft.json +1 -0
  32. package/runtime/.next/server/app/api/auth/verify/route.js +1 -1
  33. package/runtime/.next/server/app/api/auth/verify/route.js.nft.json +1 -1
  34. package/runtime/.next/server/app/api/mcp/connect/route.js +2 -2
  35. package/runtime/.next/server/app/api/mcp/connect/route.js.nft.json +1 -1
  36. package/runtime/.next/server/app/api/mcp/disconnect/route.js +1 -1
  37. package/runtime/.next/server/app/api/mcp/disconnect/route.js.nft.json +1 -1
  38. package/runtime/.next/server/app/api/mcp/servers/route.js +1 -1
  39. package/runtime/.next/server/app/api/mcp/servers/route.js.nft.json +1 -1
  40. package/runtime/.next/server/app/api/memory/[key]/route.js +1 -1
  41. package/runtime/.next/server/app/api/memory/[key]/route.js.nft.json +1 -1
  42. package/runtime/.next/server/app/api/memory/route.js +1 -1
  43. package/runtime/.next/server/app/api/memory/route.js.nft.json +1 -1
  44. package/runtime/.next/server/app/api/plugins/load/route.js +2 -2
  45. package/runtime/.next/server/app/api/plugins/load/route.js.nft.json +1 -1
  46. package/runtime/.next/server/app/api/projects/[id]/route.js +1 -1
  47. package/runtime/.next/server/app/api/projects/[id]/route.js.nft.json +1 -1
  48. package/runtime/.next/server/app/api/projects/check/route.js +1 -1
  49. package/runtime/.next/server/app/api/projects/check/route.js.nft.json +1 -1
  50. package/runtime/.next/server/app/api/projects/directories/route.js +1 -1
  51. package/runtime/.next/server/app/api/projects/directories/route.js.nft.json +1 -1
  52. package/runtime/.next/server/app/api/projects/roots/route.js +1 -1
  53. package/runtime/.next/server/app/api/projects/roots/route.js.nft.json +1 -1
  54. package/runtime/.next/server/app/api/projects/route.js +1 -1
  55. package/runtime/.next/server/app/api/projects/route.js.nft.json +1 -1
  56. package/runtime/.next/server/app/api/remote-tools/register/route.js +2 -2
  57. package/runtime/.next/server/app/api/remote-tools/register/route.js.nft.json +1 -1
  58. package/runtime/.next/server/app/api/sessions/[id]/changes/route.js +2 -2
  59. package/runtime/.next/server/app/api/sessions/[id]/changes/route.js.nft.json +1 -1
  60. package/runtime/.next/server/app/api/sessions/[id]/fork/route.js +1 -1
  61. package/runtime/.next/server/app/api/sessions/[id]/fork/route.js.nft.json +1 -1
  62. package/runtime/.next/server/app/api/sessions/[id]/goals/route.js +2 -2
  63. package/runtime/.next/server/app/api/sessions/[id]/goals/route.js.nft.json +1 -1
  64. package/runtime/.next/server/app/api/sessions/[id]/handoff/route.js +1 -1
  65. package/runtime/.next/server/app/api/sessions/[id]/handoff/route.js.nft.json +1 -1
  66. package/runtime/.next/server/app/api/sessions/[id]/route.js +2 -2
  67. package/runtime/.next/server/app/api/sessions/[id]/route.js.nft.json +1 -1
  68. package/runtime/.next/server/app/api/sessions/route.js +2 -2
  69. package/runtime/.next/server/app/api/sessions/route.js.nft.json +1 -1
  70. package/runtime/.next/server/app/api/skills/route.js +2 -2
  71. package/runtime/.next/server/app/api/skills/route.js.nft.json +1 -1
  72. package/runtime/.next/server/app/api/tools/route.js +2 -2
  73. package/runtime/.next/server/app/api/tools/route.js.nft.json +1 -1
  74. package/runtime/.next/server/app/api/web-auth/login/route.js +1 -1
  75. package/runtime/.next/server/app/api/web-auth/login/route.js.nft.json +1 -1
  76. package/runtime/.next/server/app/api/web-auth/logout/route.js +1 -1
  77. package/runtime/.next/server/app/api/web-auth/logout/route.js.nft.json +1 -1
  78. package/runtime/.next/server/app/api/web-auth/revoke-all/route.js +1 -1
  79. package/runtime/.next/server/app/api/web-auth/revoke-all/route.js.nft.json +1 -1
  80. package/runtime/.next/server/app/api/web-auth/setup/route.js +1 -1
  81. package/runtime/.next/server/app/api/web-auth/setup/route.js.nft.json +1 -1
  82. package/runtime/.next/server/app/api/web-auth/status/route.js +1 -1
  83. package/runtime/.next/server/app/api/web-auth/status/route.js.nft.json +1 -1
  84. package/runtime/.next/server/app/api/web-console/bootstrap/route.js +1 -1
  85. package/runtime/.next/server/app/api/web-console/bootstrap/route.js.nft.json +1 -1
  86. package/runtime/.next/server/app/api/web-console/device-state/route.js +1 -1
  87. package/runtime/.next/server/app/api/web-console/device-state/route.js.nft.json +1 -1
  88. package/runtime/.next/server/app/api/web-console/history/route.js +1 -1
  89. package/runtime/.next/server/app/api/web-console/history/route.js.nft.json +1 -1
  90. package/runtime/.next/server/app/api/web-console/preferences/route.js +1 -1
  91. package/runtime/.next/server/app/api/web-console/preferences/route.js.nft.json +1 -1
  92. package/runtime/.next/server/app/web/page.js +2 -2
  93. package/runtime/.next/server/app/web/page.js.nft.json +1 -1
  94. package/runtime/.next/server/app/web/page_client-reference-manifest.js +1 -1
  95. package/runtime/.next/server/app/web.html +1 -1
  96. package/runtime/.next/server/app/web.rsc +2 -2
  97. package/runtime/.next/server/app-paths-manifest.json +18 -16
  98. package/runtime/.next/server/chunks/{322.js → 1322.js} +39 -38
  99. package/runtime/.next/server/chunks/2083.js +177 -0
  100. package/runtime/.next/server/chunks/4214.js +3 -0
  101. package/runtime/.next/server/chunks/5303.js +2 -0
  102. package/runtime/.next/server/chunks/{923.js → 5923.js} +1 -1
  103. package/runtime/.next/server/chunks/6244.js +1 -0
  104. package/runtime/.next/server/chunks/6703.js +12 -0
  105. package/runtime/.next/server/chunks/8375.js +2 -0
  106. package/runtime/.next/server/middleware-build-manifest.js +1 -1
  107. package/runtime/.next/server/middleware-react-loadable-manifest.js +1 -1
  108. package/runtime/.next/server/pages/404.html +1 -1
  109. package/runtime/.next/server/pages/500.html +1 -1
  110. package/runtime/.next/server/pages/_app.js +1 -1
  111. package/runtime/.next/server/pages/_document.js +1 -1
  112. package/runtime/.next/server/pages/_document.js.nft.json +1 -1
  113. package/runtime/.next/server/pages/_error.js +1 -1
  114. package/runtime/.next/server/pages/_error.js.nft.json +1 -1
  115. package/runtime/.next/server/server-reference-manifest.json +1 -1
  116. package/runtime/.next/server/webpack-runtime.js +1 -1
  117. package/runtime/.next/static/chunks/803.c32a9408d3e3bb51.js +1 -0
  118. package/runtime/.next/static/chunks/app/web/{page-c8af455b0fde4d74.js → page-7bce2f13423aa839.js} +1 -1
  119. package/runtime/.next/static/chunks/{main-a03d29ab49823387.js → main-46a4068052b74acf.js} +1 -1
  120. package/runtime/.next/static/chunks/{webpack-22b57460ff31be13.js → webpack-05ad459942a1242f.js} +1 -1
  121. package/runtime/lib/file-preview-service.mjs +159 -0
  122. package/runtime/node_modules/.package-lock.json +85 -11
  123. package/runtime/node_modules/@agent/core/dist/domain/session/SessionTitle.d.ts +9 -0
  124. package/runtime/node_modules/@agent/core/dist/domain/session/SessionTitle.d.ts.map +1 -0
  125. package/runtime/node_modules/@agent/core/dist/domain/session/SessionTitle.test.d.ts +2 -0
  126. package/runtime/node_modules/@agent/core/dist/domain/session/SessionTitle.test.d.ts.map +1 -0
  127. package/runtime/node_modules/@agent/core/dist/domain/session/index.d.ts +1 -0
  128. package/runtime/node_modules/@agent/core/dist/domain/session/index.d.ts.map +1 -1
  129. package/runtime/node_modules/@agent/core/dist/index.js +57 -7
  130. package/runtime/node_modules/@agent/core/dist/index.js.map +7 -6
  131. package/runtime/node_modules/@agent/core/dist/infrastructure/SQLiteDatabase.d.ts +2 -0
  132. package/runtime/node_modules/@agent/core/dist/infrastructure/SQLiteDatabase.d.ts.map +1 -1
  133. package/runtime/node_modules/@agent/core/dist/infrastructure/SQLiteProjectStore.test.d.ts +2 -0
  134. package/runtime/node_modules/@agent/core/dist/infrastructure/SQLiteProjectStore.test.d.ts.map +1 -0
  135. package/runtime/node_modules/@agent/core/dist/infrastructure/SQLiteSessionStore.d.ts +1 -0
  136. package/runtime/node_modules/@agent/core/dist/infrastructure/SQLiteSessionStore.d.ts.map +1 -1
  137. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/bridge.mjs +82 -87
  138. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/browser-sdk.js +53 -53
  139. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/manifest.json +19 -20
  140. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/manifest.zst.json +23 -24
  141. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/package.json +10 -10
  142. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs +80 -80
  143. package/runtime/node_modules/@opencode-ai/sdk/dist/client.js +53 -0
  144. package/runtime/node_modules/@opencode-ai/sdk/dist/error-interceptor.js +43 -0
  145. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/client/client.gen.js +165 -0
  146. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/client/index.js +5 -0
  147. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/client/types.gen.js +2 -0
  148. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/client/utils.gen.js +226 -0
  149. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/client.gen.js +5 -0
  150. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/core/auth.gen.js +14 -0
  151. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/core/bodySerializer.gen.js +57 -0
  152. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/core/params.gen.js +89 -0
  153. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/core/pathSerializer.gen.js +106 -0
  154. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/core/queryKeySerializer.gen.js +93 -0
  155. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/core/serverSentEvents.gen.js +117 -0
  156. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/core/types.gen.js +2 -0
  157. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/core/utils.gen.js +69 -0
  158. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/sdk.gen.js +881 -0
  159. package/runtime/node_modules/@opencode-ai/sdk/dist/gen/types.gen.js +2 -0
  160. package/runtime/node_modules/@opencode-ai/sdk/dist/index.js +16 -0
  161. package/runtime/node_modules/@opencode-ai/sdk/dist/process.js +33 -0
  162. package/runtime/node_modules/@opencode-ai/sdk/dist/server.js +105 -0
  163. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/client.js +80 -0
  164. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/data.js +22 -0
  165. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/client/client.gen.js +232 -0
  166. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/client/index.js +6 -0
  167. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/client/types.gen.js +2 -0
  168. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/client/utils.gen.js +226 -0
  169. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/client.gen.js +3 -0
  170. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/core/auth.gen.js +14 -0
  171. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/core/bodySerializer.gen.js +57 -0
  172. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/core/params.gen.js +102 -0
  173. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/core/pathSerializer.gen.js +106 -0
  174. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/core/queryKeySerializer.gen.js +93 -0
  175. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/core/serverSentEvents.gen.js +133 -0
  176. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/core/types.gen.js +2 -0
  177. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/core/utils.gen.js +87 -0
  178. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/sdk.gen.js +4456 -0
  179. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/gen/types.gen.js +2 -0
  180. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/index.js +17 -0
  181. package/runtime/node_modules/@opencode-ai/sdk/dist/v2/server.js +105 -0
  182. package/runtime/node_modules/@opencode-ai/sdk/package.json +60 -0
  183. package/runtime/node_modules/cross-spawn/LICENSE +21 -0
  184. package/runtime/node_modules/cross-spawn/README.md +89 -0
  185. package/runtime/node_modules/cross-spawn/index.js +39 -0
  186. package/runtime/node_modules/cross-spawn/lib/enoent.js +59 -0
  187. package/runtime/node_modules/cross-spawn/lib/parse.js +91 -0
  188. package/runtime/node_modules/cross-spawn/lib/util/escape.js +47 -0
  189. package/runtime/node_modules/cross-spawn/lib/util/readShebang.js +23 -0
  190. package/runtime/node_modules/cross-spawn/lib/util/resolveCommand.js +52 -0
  191. package/runtime/node_modules/cross-spawn/package.json +73 -0
  192. package/runtime/node_modules/isexe/LICENSE +15 -0
  193. package/runtime/node_modules/isexe/README.md +51 -0
  194. package/runtime/node_modules/isexe/index.js +57 -0
  195. package/runtime/node_modules/isexe/mode.js +41 -0
  196. package/runtime/node_modules/isexe/package.json +31 -0
  197. package/runtime/node_modules/isexe/test/basic.js +221 -0
  198. package/runtime/node_modules/isexe/windows.js +42 -0
  199. package/runtime/node_modules/path-key/index.js +16 -0
  200. package/runtime/node_modules/path-key/license +9 -0
  201. package/runtime/node_modules/path-key/package.json +39 -0
  202. package/runtime/node_modules/path-key/readme.md +61 -0
  203. package/runtime/node_modules/shebang-command/index.js +19 -0
  204. package/runtime/node_modules/shebang-command/license +9 -0
  205. package/runtime/node_modules/shebang-command/package.json +34 -0
  206. package/runtime/node_modules/shebang-command/readme.md +34 -0
  207. package/runtime/node_modules/shebang-regex/index.js +2 -0
  208. package/runtime/node_modules/shebang-regex/license +9 -0
  209. package/runtime/node_modules/shebang-regex/package.json +35 -0
  210. package/runtime/node_modules/shebang-regex/readme.md +33 -0
  211. package/runtime/node_modules/which/CHANGELOG.md +166 -0
  212. package/runtime/node_modules/which/LICENSE +15 -0
  213. package/runtime/node_modules/which/README.md +54 -0
  214. package/runtime/node_modules/which/bin/node-which +52 -0
  215. package/runtime/node_modules/which/package.json +43 -0
  216. package/runtime/node_modules/which/which.js +125 -0
  217. package/runtime/package-lock.json +47 -43
  218. package/runtime/package.json +2 -1
  219. package/runtime/webapp/dist/assets/App-DhjG0cSw.js +240 -0
  220. package/runtime/webapp/dist/assets/{index-wTH7T_Ah.css → index-BXTtTSvB.css} +1 -1
  221. package/runtime/webapp/dist/assets/{index-BjCuCFYF.js → index-CngFUejN.js} +7 -7
  222. package/runtime/webapp/dist/index.html +2 -2
  223. package/runtime/ws-server.mjs +8 -1
  224. package/runtime/.next/server/app/api/agent/runtime-health.body +0 -1
  225. package/runtime/.next/server/app/api/agent/runtime-health.meta +0 -1
  226. package/runtime/.next/server/chunks/303.js +0 -2
  227. package/runtime/.next/server/chunks/375.js +0 -2
  228. package/runtime/.next/server/chunks/703.js +0 -12
  229. package/runtime/.next/server/chunks/988.js +0 -119
  230. package/runtime/.next/static/chunks/115.95ca5e1861314f5c.js +0 -1
  231. package/runtime/webapp/dist/assets/App-D8mcRu-Q.js +0 -231
  232. /package/runtime/.next/static/chunks/{108-5a2df9f74c5fd4ea.js → 108-bc4a0fe192dfff08.js} +0 -0
  233. /package/runtime/.next/static/chunks/{183-ffe4acb07968be9e.js → 183-d2f78a21998813ba.js} +0 -0
  234. /package/runtime/.next/static/chunks/{3cc391f0-6377b9b71382a170.js → 3cc391f0-d7ec74603652803d.js} +0 -0
  235. /package/runtime/.next/static/chunks/app/_not-found/{page-09f702519672bb02.js → page-4a73d1777b316883.js} +0 -0
  236. /package/runtime/.next/static/{WbNomgtKBalC4rAWPGRjU → pBpxqLpcmaz3BAj7sw5Ya}/_buildManifest.js +0 -0
  237. /package/runtime/.next/static/{WbNomgtKBalC4rAWPGRjU → pBpxqLpcmaz3BAj7sw5Ya}/_ssgManifest.js +0 -0
@@ -0,0 +1,177 @@
1
+ "use strict";exports.id=2083,exports.ids=[2083],exports.modules={2557:(e,t,s)=>{s.d(t,{L:()=>d,MO:()=>o,Nr:()=>l,Vk:()=>p,ZN:()=>n,vT:()=>u});var i=s(6005),r=s(9411),a=s(132);function n(e){if(void 0===e)return 50;if(!Number.isInteger(e)||e<1||e>200)throw new a.n("Workspace page limit must be between 1 and 200","INVALID_SESSION_ID");return e}function o(e){return Buffer.from(JSON.stringify({offset:e}),"utf8").toString("base64url")}function l(e){if(!e)return 0;try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(!Number.isInteger(t.offset)||t.offset<0)throw Error("invalid offset");return t.offset}catch{throw new a.n("Invalid workspace cursor","INVALID_SESSION_ID")}}function d(e,t={},s=null){let i=l(t.cursor),r=n(t.limit),a=e.slice(i,i+r),d=i+a.length;return{data:a,nextCursor:d<e.length?o(d):null,watermark:s}}function u(e,t=process.platform){let s=e.trim();if(!s)throw new a.n("A workspace directory is required","INVALID_SESSION_ID");if("win32"!==t)return(0,r.resolve)(s);let i=r.win32.resolve(s),n=r.win32.parse(i).root;return(i.length>n.length?i.replace(/[\\/]+$/,""):i).toLowerCase()}function c(e,t){return{agentType:e.agentType,workspaceId:e.workspaceId,name:e.name,roots:[e.normalizedPath],order:t,updatedAt:new Date(e.createdAt).toISOString(),source:"imported"}}class p{constructor(e,t,s=process.platform){for(let i of(this.importedWorkspaces=t,this.platform=s,this.adapters=new Map,this.workspaceCache=new Map,this.workspaceRequests=new Map,this.sessionCache=new Map,this.sessionRequests=new Map,e))this.adapters.set(i.agentType,i)}async listWorkspaces(e,t={}){let s=this.requireWorkspaceAdapter(e);if(!t.refresh){let s=this.workspaceCache.get(e);if(s)return{...d(s.data,t,s.watermark),stale:s.stale};let i=this.workspaceRequests.get(e);if(i){let e=await i;return{...d(e.data,t,e.watermark),stale:e.stale}}}let i=this.loadWorkspaceCatalog(s,t);this.workspaceRequests.set(e,i);try{let s=await i;return this.workspaceCache.set(e,s),{...d(s.data,t,s.watermark),stale:s.stale}}catch(i){let s=this.workspaceCache.get(e);if(s)return{...d(s.data,t,s.watermark),stale:!0};throw i}finally{this.workspaceRequests.get(e)===i&&this.workspaceRequests.delete(e)}}async importWorkspace(e,t,s){let n=this.requireWorkspaceAdapter(e);if(!this.importedWorkspaces){if(n.importWorkspace){let i=await n.importWorkspace(t,s);return this.invalidate(e),i}throw new a.n(`Runtime does not support workspace imports: ${e}`,"OPERATION_NOT_SUPPORTED")}if("customer-agent"===e)throw new a.n("Customer Agent workspaces use the project repository","OPERATION_NOT_SUPPORTED");let o=u(t,this.platform),l=this.workspaceCache.get(e)?.data.find(e=>e.roots.some(e=>u(e,this.platform)===o));if(l)return{workspace:l,existing:!0};let d=this.importedWorkspaces.findByPath(e,o);try{let e=(await this.loadWorkspaceCatalog(n,{refresh:!0})).data.find(e=>"imported"!==e.source&&e.roots.some(e=>u(e,this.platform)===o));if(e)return{workspace:e,existing:!0}}catch{}if(d)return{workspace:c(d,Number.MAX_SAFE_INTEGER),existing:!0};let p=Date.now(),h=this.importedWorkspaces.save({agentType:e,workspaceId:function(e,t){let s=(0,i.createHash)("sha256").update(`${e}\0${t}`).digest("base64url").slice(0,24);return`imported:${s}`}(e,o),normalizedPath:o,name:s?.trim()||(0,r.basename)(o)||o,createdAt:p});return this.invalidate(e),{workspace:c(h.workspace,Number.MAX_SAFE_INTEGER),existing:h.existing}}async listWorkspaceSessions(e,t,s={}){let i=this.requireWorkspaceAdapter(e);if(!i.listWorkspaceSessions)throw new a.n(`Runtime does not expose workspace sessions: ${e}`,"OPERATION_NOT_SUPPORTED");let r=`${e}\0${t}\0${s.cursor??""}`;if(!s.refresh){let e=this.sessionCache.get(r);if(e)return e;let t=this.sessionRequests.get(r);if(t)return t}let o="customer-agent"===e?null:this.importedWorkspaces?.list(e).find(e=>e.workspaceId===t)??null,l=o?this.listImportedWorkspaceSessions(i,o,s):i.listWorkspaceSessions(t,{...s,limit:n(s.limit)});this.sessionRequests.set(r,l);try{let e=await l;return this.sessionCache.set(r,e),e}catch(t){let e=this.sessionCache.get(r);if(e)return{...e,stale:!0};throw t}finally{this.sessionRequests.get(r)===l&&this.sessionRequests.delete(r)}}invalidate(e,t){if(this.workspaceCache.delete(e),!t){for(let t of this.sessionCache.keys())t.startsWith(`${e}\0`)&&this.sessionCache.delete(t);return}let s=`${e}\0${t}\0`;for(let e of this.sessionCache.keys())e.startsWith(s)&&this.sessionCache.delete(e)}requireWorkspaceAdapter(e){let t=this.adapters.get(e);if(!t?.listWorkspaces)throw new a.n(`Runtime does not expose workspaces: ${e}`,"OPERATION_NOT_SUPPORTED");return t}async loadWorkspaceCatalog(e,t){let s=[],i=null,r=null,a=!1;do{let n=await e.listWorkspaces({cursor:i,limit:200,refresh:t.refresh&&null===i,since:null===i?t.since:null});s.push(...n.data),r=n.watermark??r,a||=!0===n.stale,i=n.nextCursor}while(i);if(!this.importedWorkspaces||"customer-agent"===e.agentType)return{data:s,watermark:r,...a?{stale:!0}:{}};let n=new Set(s.flatMap(e=>e.roots.map(e=>u(e,this.platform)))),o=this.importedWorkspaces.list(e.agentType).filter(e=>!n.has(e.normalizedPath)).map((e,t)=>c(e,s.length+t));return{data:[...s,...o],watermark:r,...a?{stale:!0}:{}}}async listImportedWorkspaceSessions(e,t,s){if(!e.listWorkspaceSessionsByPath)throw new a.n(`Runtime cannot query imported workspace sessions: ${e.agentType}`,"OPERATION_NOT_SUPPORTED");let i=await e.listWorkspaceSessionsByPath(t.normalizedPath,{...s,limit:n(s.limit)});return{...i,data:i.data.map(e=>({...e,projectId:t.workspaceId}))}}}},8224:(e,t,s)=>{s.d(t,{K:()=>i});class i{push(e){if(this.closed)return;let t=this.waiters.shift();t?t({value:e,done:!1}):this.values.push(e)}close(){if(!this.closed)for(let e of(this.closed=!0,this.waiters.splice(0)))e({value:void 0,done:!0})}[Symbol.asyncIterator](){return{next:async()=>{let e=this.values.shift();return void 0!==e?{value:e,done:!1}:this.closed?{value:void 0,done:!0}:new Promise(e=>this.waiters.push(e))}}}constructor(){this.values=[],this.waiters=[],this.closed=!1}}},3088:(e,t,s)=>{s.a(e,async(e,i)=>{try{s.d(t,{IW:()=>L});var r=s(7718),a=s(3977),n=s(612),o=s(9411),l=s(6915),d=s(5881),u=s(2728),c=s(1322),p=s(8224),h=s(9956),m=s(5300),f=s(5779),y=s(2557),g=s(132),w=e([u]);u=(w.then?(await w)():w)[0];let C=(0,d.promisify)(r.execFile),x=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;class P{consume(e){var t,s,i,r,a;if("system"===e.type&&"task_started"===e.subtype){if(!0===e.ambient||!0===e.skip_transcript||"local_agent"!==e.task_type&&!e.subagent_type||"string"!=typeof e.tool_use_id)return[];let t={ambient:!1,settled:!1,streamedText:!1,activity:{taskId:e.task_id,parentToolCallId:e.tool_use_id,agentName:e.subagent_type,description:e.description.trim(),status:"running",isBackgrounded:e.is_backgrounded,spawnDepth:e.spawn_depth,messages:[]}};return this.tasks.set(e.task_id,t),[this.update(t)]}if("system"===e.type&&"task_progress"===e.subtype){let t=this.tasks.get(e.task_id);return!t||t.ambient?[]:(t.activity={...t.activity,description:e.description.trim()||t.activity.description,agentName:e.subagent_type??t.activity.agentName,summary:e.summary?.trim()||t.activity.summary,lastToolName:e.last_tool_name??t.activity.lastToolName,elapsedSeconds:T(e.usage.duration_ms),toolUses:O(e.usage.tool_uses)},[this.update(t)])}if("system"===e.type&&"task_updated"===e.subtype){let s=this.tasks.get(e.task_id);return!s||s.ambient?[]:(s.activity={...s.activity,status:e.patch.status?(t=e.patch.status,"completed"===t||"failed"===t?t:"killed"===t?"stopped":"running"):s.activity.status,description:e.patch.description?.trim()||s.activity.description,isBackgrounded:e.patch.is_backgrounded??s.activity.isBackgrounded,summary:e.patch.error?.trim()||s.activity.summary},[this.update(s)])}if("system"===e.type&&"task_notification"===e.subtype){let t=this.tasks.get(e.task_id);return!t||t.ambient||!0===e.ambient||!0===e.skip_transcript?[]:(t.activity={...t.activity,status:e.status,summary:e.summary?.trim()||t.activity.summary,elapsedSeconds:e.usage?T(e.usage.duration_ms):t.activity.elapsedSeconds,toolUses:e.usage?O(e.usage.tool_uses):t.activity.toolUses},t.settled=!0,[this.update(t)])}let n=b(e);if(!n)return[];let o=[...this.tasks.values()].find(e=>e.activity.parentToolCallId===n&&!e.ambient);if(!o)return[];if("stream_event"===e.type){let t=e.event;if("content_block_delta"!==t.type)return[];let s=k(t.delta);return"text_delta"===s.type&&"string"==typeof s.text&&s.text?(o.activity={...o.activity,messages:R(o.activity.messages,s.text)},o.streamedText=!0,[this.update(o)]):[]}if("assistant"===e.type){let t=o.activity.messages,s=Array.isArray(e.message.content)?e.message.content:[],i=A(s);for(let e of(i&&!o.streamedText&&(t=R(t,i)),s)){let s=N(e);s&&(t=function(e,t){let s=e[e.length-1];return s?.role==="assistant"?[...e.slice(0,-1),{...s,toolCalls:[...s.toolCalls??[],t]}]:[...e,{role:"assistant",content:"",toolCalls:[t]}]}(t,s))}return(o.streamedText=!1,t===o.activity.messages)?[]:(o.activity={...o.activity,messages:t},[this.update(o)])}if("user"===e.type){let t=e.message.content;if(!Array.isArray(t))return[];let n=o.activity.messages;for(let e of t){let t=k(e);"tool_result"===t.type&&"string"==typeof t.tool_use_id&&(s=n,i=t.tool_use_id,r=A(t.content),a=!0===t.is_error,n=[...s,{role:"tool",content:r,toolCallId:i,...a?{name:"error"}:{}}])}return n===o.activity.messages?[]:(o.activity={...o.activity,messages:n},[this.update(o)])}return[]}hasActiveBackgroundTasks(){return[...this.tasks.values()].some(({activity:e,ambient:t,settled:s})=>!t&&!s&&!0===e.isBackgrounded)}stopActive(){let e=[];for(let t of this.tasks.values())t.ambient||t.settled||(t.activity={...t.activity,status:"stopped"},e.push(this.update(t)));return e}update(e){return{type:"native_subagent_update",activity:{...e.activity,messages:e.activity.messages.map(e=>({...e,...e.toolCalls?{toolCalls:e.toolCalls.map(e=>({...e}))}:{}}))}}}constructor(){this.tasks=new Map}}class L{constructor(e={}){this.agentType="claude-code",this.drafts=new Map,this.workspaces=new Map,this.ownedSessions=new Set,this.activeQueries=new Map,this.activeInputs=new Map,this.pendingPermissions=new Map,this.abortedSessions=new Set,this.permissionEvents=new Map,this.sessionRoot=e.sessionRoot??(0,o.join)((0,n.homedir)(),".claude","projects")}async health(){try{let{stdout:e}=await C("claude",["--version"],{encoding:"utf8",timeout:5e3});return{agentType:this.agentType,available:!0,label:"Claude Code",version:e.trim()}}catch(e){return{agentType:this.agentType,available:!1,label:"Claude Code",error:e instanceof Error?e.message:String(e)}}}async discoverSessions(){let[e,t]=await Promise.all([this.listAllSessions(),this.externalOccupancy()]),s=await Promise.all(e.map(async e=>{let s=await this.toSummary(e,t),i=this.drafts.get(e.sessionId);return i?(this.drafts.delete(e.sessionId),v(s,i)):s})),i=new Set(s.map(e=>e.nativeSessionId));for(let e of this.drafts.values())i.has(e.nativeSessionId)||s.push(e);return s}async listWorkspaces(e={}){let t=await this.listAllSessions(),s=[],i=new Set;for(let e of t){let t=e.cwd?.trim()||await this.readSessionCwd(e.sessionId);if(!t)continue;let r=`cwd_${Buffer.from((0,o.resolve)(t),"utf8").toString("base64url")}`;if(i.has(r))continue;i.add(r);let a={agentType:this.agentType,workspaceId:r,name:(0,o.basename)(t)||t,roots:[t],order:s.length,updatedAt:new Date(e.lastModified).toISOString(),source:"derived"};this.workspaces.set(r,a),s.push(a)}return(0,y.L)(s,e,s[0]?.updatedAt??null)}async listWorkspaceSessions(e,t={}){let s=this.workspaces.get(e);if(!s){let t=null;do{let i=await this.listWorkspaces({cursor:t,limit:200,refresh:!0});s=i.data.find(t=>t.workspaceId===e),t=i.nextCursor}while(!s&&t)}let i=s?.roots[0];if(!i)throw new g.n(`Claude Code workspace not found: ${e}`,"SESSION_NOT_FOUND");let r=await this.listWorkspaceSessionsByPath(i,t);return{...r,watermark:r.watermark??s?.updatedAt??null}}async listWorkspaceSessionsByPath(e,t={}){let s=(0,y.ZN)(t.limit),i=(0,y.Nr)(t.cursor),[r,a]=await Promise.all([(0,u.listSessions)({dir:e,limit:s,offset:i}),this.externalOccupancy()]),n=await Promise.all(r.map(e=>this.toSummary(e,a)));return{data:n,nextCursor:r.length===s?(0,y.MO)(i+r.length):null,watermark:n[0]?.updated??null}}async getSession(e){let t=this.drafts.get(e),[s,i,r]=await Promise.all([this.findSession(e),(0,u.getSessionMessages)(e).catch(()=>[]),this.externalOccupancy()]);if(!s&&!t)throw new g.n(`Claude Code session not found: ${e}`,"SESSION_NOT_FOUND");let a=s?v(await this.toSummary(s,r),t):t,n=S(i),o=await this.recoverSubagentActivities(e,a.cwd,n);return{...a,messages:n,events:o}}async getSessionWatchPath(e){return this.findSessionPath(e)}async create(e){let t=crypto.randomUUID(),s=new Date().toISOString(),i={id:(0,f.F)(this.agentType,t),agentType:this.agentType,nativeSessionId:t,title:e.title,cwd:e.cwd,projectId:e.projectId,created:s,updated:s,status:"idle",occupancy:"available",sourceLabel:"Claude Code SDK",canResume:!0,canDelete:!1};return this.drafts.set(t,i),i}restoreDraft(e){e.agentType===this.agentType&&x.test(e.nativeSessionId)&&e.id===(0,f.F)(this.agentType,e.nativeSessionId)&&e.cwd.trim()&&this.drafts.set(e.nativeSessionId,{...e})}async *run(e,t,s,i,r,a){if(this.activeQueries.has(e))throw new g.n("Claude Code session is already running","SESSION_OCCUPIED");let n=await this.getSession(e);if("owned-externally"===n.occupancy)throw new g.n("Claude Code session is open in another client","SESSION_OCCUPIED");let o=a?.goal?`/goal ${a.goal.objective}`:t,l=I(o,void 0,s),d=this.drafts.has(e),h=(0,c.Ny)(a?.permissionMode),m="full-access"===h?void 0:(t,s,i)=>this.requestPermission(e,t,s,i,h,n.cwd,a?.brokerRunId),f=new p.K;f.push(l);let y=(0,u.query)({prompt:f,options:{cwd:n.cwd,...d?{sessionId:e}:{resume:e},includePartialMessages:!0,forwardSubagentText:!0,agentProgressSummaries:!0,permissionMode:"full-access"===h?"bypassPermissions":"default",..."full-access"===h?{allowDangerouslySkipPermissions:!0}:{canUseTool:m},tools:{type:"preset",preset:"claude_code"},skills:"all"}});this.activeQueries.set(e,y),this.activeInputs.set(e,f),this.ownedSessions.add(e);let w=new p.K;this.permissionEvents.set(e,e=>w.push(e));let v="",_=new P,E=null;try{let t=y[Symbol.asyncIterator](),s=w[Symbol.asyncIterator](),i=t.next(),r=s.next();for(;;){let a=await Promise.race([i.then(e=>({source:"sdk",result:e})),r.then(e=>({source:"permission",result:e}))]);if("permission"===a.source){a.result.done||(yield a.result.value),r=s.next();continue}if(a.result.done){let t=this.abortedSessions.delete(e);if(_.hasActiveBackgroundTasks()){for(let e of _.stopActive())yield e;yield t?{type:"turn_aborted"}:{type:"error",message:"Claude Code ended before a background subagent completed",code:"NATIVE_PROTOCOL_ERROR"},E=null}else t&&(yield{type:"turn_aborted"});break}let n=a.result.value;for(let e of(i=t.next(),_.consume(n)))yield e;for(let e of function(e,t){if("active_goal"===e.type)return e.value?[{type:"runtime_progress",progressId:"claude:goal",phase:"status",label:"正在推进目标",current:e.value.iterations,detail:e.value.last_reason||e.value.condition}]:[];if(b(e))return[];if("stream_event"===e.type){let t=e.event;if("content_block_delta"===t.type){let e=k(t.delta);if("text_delta"===e.type&&"string"==typeof e.text)return[{type:"text_chunk",text:e.text}]}return[]}if("tool_progress"===e.type)return"string"==typeof e.tool_use_id&&"number"==typeof e.elapsed_time_seconds&&Number.isFinite(e.elapsed_time_seconds)?[{type:"runtime_progress",progressId:`claude:tool:${e.tool_use_id}`,phase:"tool",label:"string"==typeof e.tool_name&&e.tool_name?`正在使用 ${e.tool_name}`:"正在使用工具",toolCallId:e.tool_use_id,elapsedSeconds:Math.max(0,e.elapsed_time_seconds),detail:`${Math.max(0,Math.round(e.elapsed_time_seconds))} 秒`}]:[];if("system"===e.type&&"thinking_tokens"===e.subtype){if("number"!=typeof e.estimated_tokens||!Number.isFinite(e.estimated_tokens))return[];let t=Math.max(0,Math.round(e.estimated_tokens));return[{type:"runtime_progress",progressId:"claude:thinking",phase:"thinking",label:"正在思考",current:t,detail:`${t.toLocaleString("en-US")} tokens`}]}if("system"===e.type&&"api_retry"===e.subtype){if("number"!=typeof e.attempt||"number"!=typeof e.max_retries||!Number.isFinite(e.attempt)||!Number.isFinite(e.max_retries))return[];let t=Math.max(0,Math.round(e.attempt)),s=Math.max(0,Math.round(e.max_retries));return[{type:"runtime_progress",progressId:"claude:api-retry",phase:"retry",label:"请求重试",current:t,total:s,detail:`${t}/${s}`}]}if("system"===e.type&&"status"===e.subtype&&e.status){let t="compacting"===e.status?"正在压缩上下文":"正在请求模型";return[{type:"runtime_progress",progressId:"claude:status",phase:"status",label:t}]}if("system"===e.type&&"informational"===e.subtype)return"string"==typeof e.content&&e.content.trim()?[{type:"runtime_progress",progressId:e.tool_use_id?`claude:info:${e.tool_use_id}`:"claude:info",phase:"status",label:e.content.trim(),...e.tool_use_id?{toolCallId:e.tool_use_id}:{}}]:[];if("system"===e.type&&"hook_progress"===e.subtype)return"string"==typeof e.hook_name&&e.hook_name.trim()?[{type:"runtime_progress",progressId:`claude:hook:${e.hook_id}`,phase:"status",label:`正在运行 ${e.hook_name.trim()}`,detail:"string"==typeof e.hook_event&&e.hook_event.trim()?e.hook_event.trim():void 0}]:[];if("system"===e.type&&"task_progress"===e.subtype){if("string"!=typeof e.task_id||"string"!=typeof e.description||!e.description.trim())return[];let t="number"==typeof e.usage?.duration_ms&&Number.isFinite(e.usage.duration_ms)?Math.max(0,Math.round(e.usage.duration_ms/1e3)):void 0;return[{type:"runtime_progress",progressId:`claude:task:${e.task_id}`,phase:"status",label:e.description.trim(),...e.tool_use_id?{toolCallId:e.tool_use_id}:{},...void 0===t?{}:{elapsedSeconds:t,detail:`${t} 秒`}}]}if("assistant"===e.type){let s=[],i=Array.isArray(e.message.content)?e.message.content:[];if(!t){let e=A(i);e&&s.push({type:"text_chunk",text:e})}for(let e of i){let t=N(e);t&&s.push({type:"tool_call",toolCall:t})}return s}if("user"===e.type){let t=e.message.content;return Array.isArray(t)?t.flatMap(e=>{let t=k(e);return"tool_result"!==t.type||"string"!=typeof t.tool_use_id?[]:[{type:"tool_result",result:{toolCallId:t.tool_use_id,content:A(t.content),isError:!0===t.is_error}}]}):[]}return[]}(n,v.length>0))"text_chunk"===e.type&&(v+=e.text),yield e;if("system"===n.type&&"init"===n.subtype&&n.session_id!==e)throw new g.n(`Claude Code returned unexpected session ID ${n.session_id}`,"NATIVE_PROTOCOL_ERROR");if("result"===n.type&&(E=n),E&&!_.hasActiveBackgroundTasks()){yield function(e,t){if("success"===e.subtype&&!e.is_error)return{type:"done",finalText:e.result||t};let s="result"in e&&"string"==typeof e.result?e.result:"errors"in e&&Array.isArray(e.errors)?e.errors.join("\n"):"Claude Code run failed";return{type:"error",message:s||"Claude Code run failed"}}(E,v),E=null;break}}this.drafts.delete(e)}catch(e){yield{type:"error",message:e instanceof Error?e.message:String(e),code:e instanceof g.n?e.code:"NATIVE_PROTOCOL_ERROR"}}finally{this.rejectPermissionsForSession(e,"Claude Code run ended"),w.close(),f.close(),this.permissionEvents.delete(e),this.activeQueries.delete(e),this.activeInputs.delete(e),this.ownedSessions.delete(e),this.abortedSessions.delete(e),y.close()}}async steer(e,t){let s=this.activeInputs.get(e);return!!s&&(s.push(I(t,"now")),!0)}async abort(e){let t=this.activeQueries.get(e);t&&(this.abortedSessions.add(e),await t.interrupt().catch(()=>void 0),t.close())}async answerQuestion(e,t){let s=this.pendingPermissions.get(e);return!!s&&(this.pendingPermissions.delete(e),"允许一次"===t.answer||"本会话允许"===t.answer?s.resolve({behavior:"allow",updatedInput:s.input,..."本会话允许"===t.answer&&s.suggestions?.length?{updatedPermissions:s.suggestions}:{}}):s.resolve({behavior:"deny",message:"取消"===t.answer?"User cancelled the operation":"User declined the operation",interrupt:"取消"===t.answer}),!0)}async dispose(){for(let e of this.activeInputs.values())e.close();for(let e of(this.activeInputs.clear(),this.activeQueries.values()))e.close();for(let[e,t]of(this.activeQueries.clear(),this.ownedSessions.clear(),this.pendingPermissions))t.resolve({behavior:"deny",message:"Customer Agent is shutting down",interrupt:!0}),this.pendingPermissions.delete(e)}async listAllSessions(){let e=[];for(let t=0;;t+=200){let s=await (0,u.listSessions)({limit:200,offset:t});if(e.push(...s),s.length<200)return e}}async findSession(e){let t=0;for(;;){let s=await (0,u.listSessions)({limit:200,offset:t}),i=s.find(t=>t.sessionId===e);if(i)return i;if(s.length<200)return;t+=200}}async externalOccupancy(){let e=new Set,[t,s]=await Promise.all([(0,m.g)("claude",this.sessionRoot),E()]);for(let s of t){let t=(0,o.basename)(s);t.endsWith(".jsonl")&&e.add(t.slice(0,-6))}for(let t of s)t.sessionId&&("done"!==t.state||"active"===t.status||"running"===t.status)&&e.add(t.sessionId);for(let t of this.ownedSessions)e.delete(t);return e}async recoverSubagentActivities(e,t,s){let i=new Set(s.flatMap(e=>(e.toolCalls??[]).filter(e=>"Agent"===e.name).map(e=>e.id)));if(0===i.size)return[];let r=await this.findSessionPath(e);if(!r)return[];let n=(0,o.join)((0,o.dirname)(r),e,"subagents"),l=await (0,u.listSubagents)(e,t?{dir:t}:void 0).catch(()=>[]);return(await Promise.all(l.map(async s=>{if(!/^[a-z0-9_-]+$/i.test(s))return null;try{let r=JSON.parse(await (0,a.readFile)((0,o.join)(n,`agent-${s}.meta.json`),"utf8"));if("string"!=typeof r.toolUseId||!i.has(r.toolUseId)||"string"!=typeof r.description||!r.description.trim())return null;let l=await (0,u.getSubagentMessages)(e,s,t?{dir:t}:void 0),d=S(l);if(0===d.length)return null;let c=[...d].reverse().find(e=>"assistant"===e.role&&e.content.trim())?.content.trim();return{type:"native_subagent_update",activity:{taskId:s,parentToolCallId:r.toolUseId,agentName:"string"==typeof r.agentType?r.agentType:void 0,description:r.description.trim(),status:c?"completed":"stopped",spawnDepth:"number"==typeof r.spawnDepth?r.spawnDepth:void 0,summary:c,messages:d}}}catch{return null}}))).filter(e=>null!==e)}async findSessionPath(e){let t;if((0,o.basename)(e)!==e||!x.test(e))return null;try{t=await (0,a.readdir)(this.sessionRoot,{withFileTypes:!0})}catch{return null}for(let s of t){if(!s.isDirectory())continue;let t=(0,o.join)(this.sessionRoot,s.name,`${e}.jsonl`);try{if((await (0,a.stat)(t)).isFile())return t}catch{}}return null}async toSummary(e,t){let s=this.ownedSessions.has(e.sessionId),i=t.has(e.sessionId),r=s?"owned-by-customer-agent":i?"owned-externally":"available",a=new Date(e.lastModified).toISOString(),n=e.cwd?.trim()||await this.readSessionCwd(e.sessionId);return{id:(0,f.F)(this.agentType,e.sessionId),agentType:this.agentType,nativeSessionId:e.sessionId,title:(e.customTitle||e.summary||e.firstPrompt||"Claude Code session").trim(),cwd:n,created:new Date(e.createdAt??e.lastModified).toISOString(),updated:a,status:"available"===r?"idle":"running",occupancy:r,sourceLabel:"Claude Code CLI",canResume:"owned-externally"!==r,canDelete:!1}}async readSessionCwd(e){let t;let s=await this.findSessionPath(e);if(!s)return"";try{t=await (0,a.open)(s,"r");let e=Buffer.alloc(65536),i=new l.StringDecoder("utf8"),r="",n=0;for(;n<2097152;){let s=Math.min(e.length,2097152-n),{bytesRead:a}=await t.read(e,0,s,n);if(0===a)break;n+=a;let o=(r+=i.write(e.subarray(0,a))).indexOf("\n");for(;o>=0;){let e=_(r.slice(0,o));if(e)return e;o=(r=r.slice(o+1)).indexOf("\n")}}return _(r+i.end())}catch{}finally{await t?.close().catch(()=>void 0)}return""}requestPermission(e,t,s,i,r,a,n){let o=function(e,t,s){let i=function(e){let t=e.replace(/[^a-z]/gi,"").toLowerCase();return({read:"read_file",glob:"glob",grep:"grep",write:"write_file",edit:"str_replace",multiedit:"str_replace",bash:"bash",webfetch:"web_fetch",websearch:"web_search"})[t]??`claude_${t||"unknown"}`}(e),r=("write_file"===i||"str_replace"===i)&&"string"!=typeof t.file_path&&"string"==typeof t.path?{...t,file_path:t.path}:t;return(0,c.Cr)(i,r,s)}(t,s,a);if(!("full-access"!==r&&("request-approval"===r?"safe"!==o.kind:o.risky||["shell","network","external-write","remote","risky-local","unknown"].includes(o.kind))))return Promise.resolve({behavior:"allow",updatedInput:s});let l=n?`native:${n}:${i.requestId}`:`claude:${e}:${i.requestId}`;return new Promise(r=>{let a=()=>{this.pendingPermissions.delete(l),r({behavior:"deny",message:"Operation aborted",interrupt:!0})};if(i.signal.aborted){a();return}i.signal.addEventListener("abort",a,{once:!0}),this.pendingPermissions.set(l,{nativeSessionId:e,input:s,suggestions:i.suggestions,resolve:e=>{i.signal.removeEventListener("abort",a),r(e)}});let n={type:"ask_user",questionId:l,question:i.title||i.decisionReason||o.summary||`Claude Code requests permission to use ${t}`,options:[{label:"允许一次",description:i.description||"Allow this operation once"},{label:"本会话允许",description:"Allow the suggested operation for this session"},{label:"拒绝",description:"Decline this operation"},{label:"取消",description:"Cancel the current operation"}]};this.permissionEvents.get(e)?.(n)})}rejectPermissionsForSession(e,t){for(let[s,i]of this.pendingPermissions)i.nativeSessionId===e&&(i.resolve({behavior:"deny",message:t,interrupt:!0}),this.pendingPermissions.delete(s))}}function v(e,t){return t?{...e,cwd:e.cwd||t.cwd,projectId:e.projectId??t.projectId}:e}function _(e){if(!e.trim())return"";try{let t=JSON.parse(e);return"string"==typeof t.cwd?t.cwd.trim():""}catch{return""}}function I(e,t,s){let i=(0,h.u)(s),r=i.length>0?[{type:"text",text:e},...i.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.base64}}))]:e;return{type:"user",message:{role:"user",content:r},parent_tool_use_id:null,...t?{priority:t}:{}}}async function E(){try{let{stdout:e}=await C("claude",["agents","--json","--all"],{encoding:"utf8",timeout:5e3,maxBuffer:4194304}),t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function S(e){let t=[];for(let s of e){if("user"!==s.type&&"assistant"!==s.type)continue;let e=k(s.message).content;if("assistant"===s.type){let s=Array.isArray(e)?e:[],i=A(e),r=s.map(N).filter(e=>null!==e);(i||r.length)&&t.push({role:"assistant",content:i,...r.length?{toolCalls:r}:{}});continue}let i=Array.isArray(e)?e:[],r=A(e),a=function(e){let t=[];for(let s of e){let e=k(s);if("image"!==e.type)continue;let i=k(e.source),r=i.media_type,a=i.data;if("base64"!==i.type||"string"!=typeof r||"string"!=typeof a)continue;let n="image/jpeg"===r?"jpg":"image/png"===r?"png":"image/gif"===r?"gif":"image/webp"===r?"webp":null;n&&t.push({type:"image",name:`image-${t.length+1}.${n}`,dataUrl:`data:${r};base64,${a}`})}return t}(i);for(let e of((r||a.length>0)&&t.push({role:"user",content:r,...a.length>0?{presentation:{attachments:a}}:{}}),i)){let s=k(e);"tool_result"===s.type&&"string"==typeof s.tool_use_id&&t.push({role:"tool",content:A(s.content),toolCallId:s.tool_use_id})}}return t}function b(e){return"parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id&&e.parent_tool_use_id?e.parent_tool_use_id:null}function T(e){return Number.isFinite(e)?Math.max(0,Math.round(e/1e3)):void 0}function O(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):void 0}function R(e,t){if(!t)return e;let s=e[e.length-1];return s?.role!=="assistant"||s.toolCalls?.length?[...e,{role:"assistant",content:t}]:[...e.slice(0,-1),{...s,content:s.content+t}]}function N(e){let t=k(e);return"tool_use"!==t.type||"string"!=typeof t.id||"string"!=typeof t.name?null:{id:t.id,name:t.name,arguments:k(t.input)}}function A(e){return"string"==typeof e?e:Array.isArray(e)?e.flatMap(e=>{if("string"==typeof e)return[e];let t=k(e);return"text"===t.type&&"string"==typeof t.text?[t.text]:[]}).join("\n").trim():""}function k(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}i()}catch(e){i(e)}})},9529:(e,t,s)=>{s.d(t,{b:()=>a});var i=s(7718),r=s(132);class a{constructor(e={}){this.process=null,this.startPromise=null,this.buffer="",this.nextId=1,this.disposed=!1,this.pending=new Map,this.notificationListeners=new Set,this.exitListeners=new Set,this.serverRequestHandler=null,this.executable=e.executable??"codex",this.requestTimeoutMs=e.requestTimeoutMs??12e4,this.spawnProcess=e.spawnProcess??i.spawn}get pid(){return this.process?.pid}onNotification(e){return this.notificationListeners.add(e),()=>this.notificationListeners.delete(e)}onExit(e){return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}setServerRequestHandler(e){this.serverRequestHandler=e}async request(e,t){return await this.ensureStarted(),this.sendRequest(e,t)}respond(e,t){this.write({id:e,result:t})}respondError(e,t,s){this.write({id:e,error:{code:t,message:s}})}async restart(){await this.stop(),this.disposed=!1,await this.ensureStarted()}async dispose(){this.disposed=!0,await this.stop()}async ensureStarted(){if(!this.process||this.process.killed){if(this.disposed)throw new r.n("Codex App Server is disposed","RUNTIME_UNAVAILABLE");this.startPromise||(this.startPromise=this.start().finally(()=>{this.startPromise=null})),await this.startPromise}}async start(){let e=this.spawnProcess(this.executable,["app-server","--stdio"],{stdio:["pipe","pipe","pipe"]});this.process=e,this.buffer="",e.stdout.setEncoding("utf8"),e.stdout.on("data",e=>this.handleStdout(e)),e.stderr.setEncoding("utf8"),e.stderr.on("data",e=>{let t=e.trim();t&&console.warn(`[codex-app-server] ${t}`)}),e.once("error",e=>this.handleExit(e)),e.once("exit",(e,t)=>{this.handleExit(Error(`Codex App Server exited (${e??t??"unknown"})`))}),await this.sendRequest("initialize",{clientInfo:{name:"customer-agent",title:"Customer Agent",version:"0.1.0"},capabilities:{experimentalApi:!0}}),this.write({method:"initialized",params:{}})}sendRequest(e,t){let s=this.nextId++;return new Promise((i,a)=>{let n=setTimeout(()=>{this.pending.delete(s),a(new r.n(`Codex request timed out: ${e}`,"NATIVE_PROTOCOL_ERROR"))},this.requestTimeoutMs);this.pending.set(s,{resolve:i,reject:a,timer:n});try{this.write({method:e,id:s,params:t})}catch(e){clearTimeout(n),this.pending.delete(s),a(e instanceof Error?e:Error(String(e)))}})}write(e){if(!this.process||this.process.killed||!this.process.stdin.writable)throw new r.n("Codex App Server is unavailable","RUNTIME_UNAVAILABLE");this.process.stdin.write(`${JSON.stringify(e)}
2
+ `)}handleStdout(e){this.buffer+=e;let t=this.buffer.indexOf("\n");for(;t>=0;){let e=this.buffer.slice(0,t).trim();this.buffer=this.buffer.slice(t+1),e&&this.handleLine(e),t=this.buffer.indexOf("\n")}}handleLine(e){let t;try{t=JSON.parse(e)}catch{console.warn("[codex-app-server] Ignoring malformed JSON-RPC line");return}if("string"==typeof t.method&&void 0!==t.id){let e=t;this.serverRequestHandler?this.serverRequestHandler(e):this.respondError(e.id,-32601,`Unsupported server request: ${e.method}`);return}if(void 0!==t.id){let e=this.pending.get(t.id);if(!e)return;if(clearTimeout(e.timer),this.pending.delete(t.id),t.error){let s=t.error;e.reject(new r.n(s.message??`Codex request failed (${s.code??"unknown"})`,/active writer|already.*loaded|in use/i.test(s.message??"")?"SESSION_OCCUPIED":"NATIVE_PROTOCOL_ERROR"))}else e.resolve(t.result);return}if("string"==typeof t.method){let e=t;for(let t of this.notificationListeners)t(e)}}handleExit(e){if(this.process){for(let t of(this.process=null,this.pending.values()))clearTimeout(t.timer),t.reject(new r.n(e.message,"RUNTIME_UNAVAILABLE"));for(let t of(this.pending.clear(),this.exitListeners))t(e)}}async stop(){let e=this.process;this.process=null,e&&!e.killed&&(e.kill("SIGTERM"),await new Promise(t=>{let s=setTimeout(t,1e3);e.once("exit",()=>{clearTimeout(s),t()})}))}}},3053:(e,t,s)=>{s.d(t,{tX:()=>C});var i=s(7718),r=s(3977),a=s(612),n=s(9411),o=s(5881),l=s(1322),d=s(8224),u=s(9529);let c=new Set(["task_started","turn_started"]),p=new Set(["task_complete","turn_complete","turn_aborted"]);function h(e){let t="string"==typeof e?e:e.toString("utf8");if(!t.trim())return"unknown";try{let e=JSON.parse(t);if("event_msg"!==e.type||"string"!=typeof e.payload?.type)return"unknown";if(c.has(e.payload.type))return"running";if(p.has(e.payload.type))return"idle"}catch{}return"unknown"}class m{constructor(e=65536){if(this.chunkSize=e,this.cache=new Map,!Number.isInteger(e)||e<=0)throw Error("Codex rollout activity chunk size must be a positive integer")}async read(e){let t=null;try{t=await (0,r.open)(e,"r");let s=await t.stat();if(!s.isFile())return this.cache.delete(e),"unknown";let i=`${s.dev}:${s.ino}`,a=this.cache.get(e),n=a&&a.identity===i&&s.size>=a.size&&(s.size>a.size||s.mtimeMs===a.mtimeMs)?await this.readAppended(t,a,s.size,s.mtimeMs):await this.bootstrap(t,i,s.size,s.mtimeMs);return this.cache.set(e,n),n.activity}catch{return this.cache.delete(e),"unknown"}finally{await t?.close().catch(()=>void 0)}}async readMany(e){let t=[...new Set(e)],s=new Set(t);for(let e of this.cache.keys())s.has(e)||this.cache.delete(e);return new Map(await Promise.all(t.map(async e=>[e,await this.read(e)])))}async bootstrap(e,t,s,i){let r=s,a=Buffer.alloc(0),n="unknown",o=Buffer.alloc(0),l=!1,d=!1;for(;r>0&&"unknown"===n;){let t=Math.min(this.chunkSize,r);r-=t;let s=Buffer.allocUnsafe(t),{bytesRead:i}=await e.read(s,0,t,r),u=s.subarray(0,i),c=f(u);if(0===c.length)a=y(u,a);else{let e=u.length;for(let t=c.length-1;t>=0;t-=1){let s=c[t],i=y(w(u.subarray(s+1,e)),a);if(d||(o=i??Buffer.alloc(0),l=null===i,d=!0),i&&(n=h(i)),"unknown"!==n)break;a=Buffer.alloc(0),e=s}"unknown"===n&&(a=Buffer.from(u.subarray(0,e)))}}return"unknown"===n&&0===r&&a&&(d||(o=a,d=!0),n=h(a)),d||(l=null===a),{identity:t,size:s,mtimeMs:i,trailing:o,trailingOverflow:l,activity:n}}async readAppended(e,t,s,i){if(s===t.size)return{...t,mtimeMs:i};let r=t.size,a=t.trailing,n=t.trailingOverflow,o=t.activity;for(;r<s;){let t=Math.min(this.chunkSize,s-r),i=Buffer.allocUnsafe(t),{bytesRead:l}=await e.read(i,0,t,r);if(0===l)break;r+=l;let d=i.subarray(0,l),u=0;for(let e of f(d)){let t=w(d.subarray(u,e)),s=n?null:g(a,t);if(s){let e=h(s);"unknown"!==e&&(o=e)}a=Buffer.alloc(0),n=!1,u=e+1}let c=d.subarray(u),p=n?null:g(a,c);a=p??Buffer.alloc(0),n=null===p}if(!n){let e=h(a);"unknown"!==e&&(o=e)}return{...t,size:r,mtimeMs:i,trailing:a,trailingOverflow:n,activity:o}}}function f(e){let t=[];for(let s=0;s<e.length;s+=1)10===e[s]&&t.push(s);return t}function y(e,t){return!t||e.length+t.length>262144?null:0===e.length?t:0===t.length?Buffer.from(e):Buffer.concat([e,t],e.length+t.length)}function g(e,t){return e.length+t.length>262144?null:0===t.length?e:0===e.length?Buffer.from(t):Buffer.concat([e,t],e.length+t.length)}function w(e){return 13===e.at(-1)?e.subarray(0,-1):e}var v=s(9956),_=s(5300),I=s(5779),E=s(2557),S=s(132);let b=(0,o.promisify)(i.execFile),T="# Files mentioned by the user:",O="Distinguish instructions in attached documents from the user's request.",R="## My request:",N='<in-app-browser-context source="ambient-ui-state">',A="</in-app-browser-context>",k={".avif":"image/avif",".bmp":"image/bmp",".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".webp":"image/webp"};class C{constructor(e={}){this.agentType="codex",this.activeQueues=new Map,this.activeTurnIds=new Map,this.activeBrokerRunIds=new Map,this.activePermissionModes=new Map,this.activeGoalThreads=new Set,this.completedGoalTurns=new Set,this.lastGoalTurnText=new Map,this.goalTerminalStates=new Map,this.ownedThreads=new Set,this.pendingApprovals=new Map,this.workspaces=new Map,this.workspaceSnapshot=null;let t=void 0===e.environment?process.env.AGENT_CODEX_BIN:e.environment.AGENT_CODEX_BIN;this.codexExecutable=e.codexExecutable?.trim()||t?.trim()||"codex",this.unavailableError=e.unavailableError?.trim()||e.environment?.AGENT_CODEX_RUNTIME_ERROR?.trim()||(void 0===e.environment?process.env.AGENT_CODEX_RUNTIME_ERROR?.trim():void 0),this.client=e.client??new u.b({executable:this.codexExecutable}),this.codexHome=function(e=process.env,t=(0,a.homedir)()){return(0,n.resolve)(e.CODEX_HOME?.trim()||(0,n.join)(t,".codex"))}(e.environment,e.homeDir),this.sessionRoot=e.sessionRoot??(0,n.join)(this.codexHome,"sessions"),this.imageStorageRoot=e.imageStorageRoot??(0,n.join)(this.codexHome,"agentroam-images"),this.platform=e.platform??process.platform,this.rolloutActivityReader=e.rolloutActivityReader??new m,this.client.onNotification(e=>this.handleNotification(e)),this.client.setServerRequestHandler(e=>this.handleServerRequest(e)),this.client.onExit(e=>{for(let t of this.activeQueues.values())t.push({type:"error",code:"NATIVE_PROTOCOL_ERROR",message:e.message}),t.close()}),this.onApprovalResolved=e.onApprovalResolved}async health(){if(this.unavailableError)return{agentType:this.agentType,available:!1,label:"Codex",error:this.unavailableError};try{let{stdout:e}=await b(this.codexExecutable,["--version"],{encoding:"utf8",timeout:5e3});return{agentType:this.agentType,available:!0,label:"Codex",version:e.trim()}}catch(e){return{agentType:this.agentType,available:!1,label:"Codex",error:e instanceof Error?e.message:String(e)}}}async discoverSessions(){this.ensureAvailable();let e=await (0,_.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),t=[],s=null;do{let e=await this.client.request("thread/list",{cursor:s,limit:200,sortKey:"updated_at",sortDirection:"desc"});t.push(...e.data),s=e.nextCursor}while(s);let i=await this.rolloutActivityReader.readMany("win32"===this.platform?x(t,this.platform):e);return t.map(t=>this.toSummary(t,e,i))}async listWorkspaces(e={}){if(this.ensureAvailable(),!e.cursor&&!e.refresh&&this.workspaceSnapshot)return this.workspaceSnapshot;try{let t=await this.client.request("project/list",{cursor:e.cursor??null,limit:(0,E.ZN)(e.limit),sortKey:"position",sortDirection:"asc"}),s=t.data.map(e=>({agentType:this.agentType,workspaceId:e.id,name:e.name,roots:e.roots.map(e=>e.path),order:e.position,updatedAt:new Date(1e3*e.updatedAt).toISOString(),source:"native"}));for(let e of s)this.workspaces.set(e.workspaceId,e);let i={data:s,nextCursor:t.nextCursor,watermark:String(Math.max(0,...t.data.map(e=>e.updatedAt)))};return e.cursor||(this.workspaceSnapshot=i),i}catch(t){if(!e.cursor&&this.workspaceSnapshot)return{...this.workspaceSnapshot,stale:!0};throw j(t)}}async listWorkspaceSessions(e,t={}){this.ensureAvailable();let s=await this.findWorkspace(e);if(0===s.roots.length)return{data:[],nextCursor:null,watermark:s.updatedAt??null};let i=await this.client.request("thread/list",{cursor:t.cursor??null,limit:(0,E.ZN)(t.limit),sortKey:"updated_at",sortDirection:"desc",projectId:e});if(!t.cursor&&0===i.data.length){let r=await this.client.request("thread/list",{cursor:null,limit:(0,E.ZN)(t.limit),sortKey:"updated_at",sortDirection:"desc",cwd:s.roots});i={...r,data:r.data.filter(t=>!t.projectId||t.projectId===e)}}let r=await (0,_.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),a=await this.rolloutActivityReader.readMany("win32"===this.platform?x(i.data,this.platform):r);return{data:i.data.map(e=>this.toSummary(e,r,a)),nextCursor:i.nextCursor,watermark:String(Math.max(0,...i.data.map(e=>e.updatedAt)))}}async listWorkspaceSessionsByPath(e,t={}){this.ensureAvailable();let s=await this.client.request("thread/list",{cursor:t.cursor??null,limit:(0,E.ZN)(t.limit),sortKey:"updated_at",sortDirection:"desc",cwd:[e]}),i=await (0,_.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),r=await this.rolloutActivityReader.readMany("win32"===this.platform?x(s.data,this.platform):i);return{data:s.data.map(e=>this.toSummary(e,i,r)),nextCursor:s.nextCursor,watermark:String(Math.max(0,...s.data.map(e=>e.updatedAt)))}}async getSession(e){this.ensureAvailable();let t=await this.client.request("thread/read",{threadId:e,includeTurns:!0}),s=await (0,_.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),i=await this.rolloutActivityReader.readMany("win32"===this.platform?x([t.thread],this.platform):s);return{...this.toSummary(t.thread,s,i),messages:await M(t.thread.turns),events:[]}}async getSessionWatchPath(e){this.ensureAvailable();let t=(await this.client.request("thread/read",{threadId:e,includeTurns:!1})).thread.path;if(!t||!(0,n.isAbsolute)(t))return null;try{let[e,s,i]=await Promise.all([(0,r.realpath)(this.sessionRoot),(0,r.realpath)(t),(0,r.stat)(t)]),a=(0,n.relative)((0,n.resolve)(e),(0,n.resolve)(s));if(i.isFile()&&""!==a&&!a.startsWith(`..${n.sep}`)&&".."!==a&&!(0,n.isAbsolute)(a))return s}catch{}return null}async create(e){this.ensureAvailable();let t=await this.client.request("thread/start",{cwd:e.cwd,threadSource:"customer-agent",...e.projectId?{projectId:e.projectId}:{}});return await this.client.request("thread/name/set",{threadId:t.thread.id,name:e.title}).catch(()=>void 0),await this.client.request("thread/unsubscribe",{threadId:t.thread.id}).catch(()=>void 0),this.toSummary({...t.thread,name:e.title,projectId:t.thread.projectId??e.projectId},new Set)}async fork(e){this.ensureAvailable();let t=await this.client.request("thread/read",{threadId:e,includeTurns:!1}),s=await this.client.request("thread/fork",{threadId:e}),i=(t.thread.name||t.thread.preview||"Codex session").trim(),r=`${i}(副本)`;return await this.client.request("thread/name/set",{threadId:s.thread.id,name:r}),this.toSummary({...s.thread,name:r},new Set)}async *run(e,t,s,i,a,n){if(this.activeQueues.has(e))throw new S.n("Codex session is already running","SESSION_OCCUPIED");let o=await this.getSession(e);if("owned-externally"===o.occupancy)throw new S.n("Codex session is open in another client","SESSION_OCCUPIED");let u=(0,v.u)(s),c=new d.K,p=(0,l.Ny)(n?.permissionMode),h=null,m=!1;this.activeQueues.set(e,c),this.activePermissionModes.set(e,p),this.ownedThreads.add(e),n?.brokerRunId&&this.activeBrokerRunIds.set(e,n.brokerRunId);try{var f;await this.client.request("thread/resume",{threadId:e,excludeTurns:!0}),n?.goal&&(await this.client.request("thread/goal/set",{threadId:e,objective:n.goal.objective,status:"active"}),this.activeGoalThreads.add(e));let s=u.length>0?await D(u,this.imageStorageRoot).then(e=>(h=e.directory,e.inputs)):[],i=function(e){let t=e.trim().match(/^\/([\w-]+)(?:\s+([\s\S]*))?$/);return!t||["goal","compact","loop"].includes(t[1].toLowerCase())?null:{name:t[1],rest:t[2]?.trim()??""}}(t),r=i?await this.resolveSkillPath(o.cwd,i.name):null,a=i?`$${i.name}${i.rest?` ${i.rest}`:""}`:t,l=await this.client.request("turn/start",{threadId:e,input:[{type:"text",text:a,text_elements:[]},...i&&r?[{type:"skill",name:i.name,path:r}]:[],...s],...(f=o.cwd,"request-approval"===p?{approvalPolicy:"onRequest",sandboxPolicy:{type:"readOnly"}}:"auto-approval"===p?{approvalPolicy:"onRequest",sandboxPolicy:{type:"workspaceWrite",writableRoots:f?[f]:[],networkAccess:!1}}:{approvalPolicy:"never",sandboxPolicy:{type:"dangerFullAccess"}})});for await(let t of(m=null!==h,this.activeTurnIds.set(e,l.turn.id),c))yield t}catch(t){let e=j(t);yield{type:"error",message:e.message,code:e.code}}finally{this.activeTurnIds.delete(e),this.activeQueues.delete(e),this.activePermissionModes.delete(e),this.ownedThreads.delete(e),this.activeBrokerRunIds.delete(e),this.activeGoalThreads.delete(e),this.completedGoalTurns.delete(e),this.lastGoalTurnText.delete(e),this.goalTerminalStates.delete(e),await this.client.request("thread/unsubscribe",{threadId:e}).catch(()=>void 0),h&&!m&&await (0,r.rm)(h,{recursive:!0,force:!0}).catch(()=>void 0)}}async abort(e){let t=this.activeTurnIds.get(e),s=[];t&&s.push(this.client.request("turn/interrupt",{threadId:e,turnId:t})),this.activeGoalThreads.has(e)&&s.push(this.client.request("thread/goal/clear",{threadId:e}));let i=(await Promise.allSettled(s)).find(e=>"rejected"===e.status);if(i)throw i.reason}async answerQuestion(e,t){let s=this.pendingApprovals.get(e);if(!s)return!1;this.pendingApprovals.delete(e);let i=t.answer.trim();if("item/tool/requestUserInput"===s.method){let e=s.params.questions;return this.client.respond(s.requestId,{answers:Object.fromEntries((e??[]).map(e=>[e.id,{answers:[i]}]))}),!0}return this.client.respond(s.requestId,P(s,i)),!0}async dispose(){await this.client.dispose()}ensureAvailable(){if(this.unavailableError)throw new S.n(this.unavailableError,"RUNTIME_UNAVAILABLE")}async resolveSkillPath(e,t){for(let s of[(0,n.join)(this.codexHome,"skills",t,"SKILL.md"),(0,n.join)((0,a.homedir)(),".agent","skills",t,"SKILL.md"),...e?[(0,n.join)(e,".codex","skills",t,"SKILL.md"),(0,n.join)(e,".agent","skills",t,"SKILL.md")]:[]])try{if((await (0,r.stat)(s)).isFile())return s}catch{}try{let s=await this.client.request("skills/list",{cwds:e?[e]:[],forceReload:!1});return function e(t,s){if(!t||"object"!=typeof t)return null;if(Array.isArray(t)){for(let i of t){let t=e(i,s);if(t)return t}return null}if(t.name===s&&"string"==typeof t.path)return t.path;for(let i of Object.values(t)){let t=e(i,s);if(t)return t}return null}(s,t)}catch{return null}}toSummary(e,t,s=new Map){var i;let r=this.ownedThreads.has(e.id),a=!!(e.path&&t.has(e.path)),n=!!(e.path&&"running"===s.get(e.path)),o="win32"===this.platform?n:a,l=r?"owned-by-customer-agent":o?"owned-externally":"available";return{id:(0,I.F)(this.agentType,e.id),agentType:this.agentType,nativeSessionId:e.id,title:(e.name||e.preview||"Codex session").trim(),cwd:e.cwd,projectId:e.projectId??void 0,parentSessionId:e.parentThreadId?(0,I.F)(this.agentType,e.parentThreadId):void 0,created:new Date(1e3*e.createdAt).toISOString(),updated:new Date(1e3*e.updatedAt).toISOString(),status:function(e,t=!1,s=!1){return t||s||"active"===e?"running":"systemError"===e?"failed":"idle"}(e.status?.type,r,"win32"===this.platform?n:a&&n),occupancy:l,sourceLabel:"vscode"===(i=e.source)?"Codex Desktop":"cli"===i?"Codex CLI":"exec"===i?"Codex Exec":"appServer"===i?"Customer Agent / Codex":i&&"object"==typeof i&&"custom"in i?String(i.custom):"Codex",canResume:"owned-externally"!==l,canDelete:!1}}handleNotification(e){let t=e.params??{};if("project/changed"===e.method){this.workspaceSnapshot=null;return}if("serverRequest/resolved"===e.method){let e=t.requestId??t.id;for(let[t,s]of this.pendingApprovals)if(String(s.requestId)===String(e)){this.pendingApprovals.delete(t),this.onApprovalResolved?.(t);break}return}let s="string"==typeof t.threadId?t.threadId:void 0;if(!s)return;let i=this.activeQueues.get(s);if(!i)return;if("thread/goal/updated"===e.method&&this.activeGoalThreads.has(s)){let e=function(e){let t=G(e).status;return"active"===t||"paused"===t||"blocked"===t||"usageLimited"===t||"budgetLimited"===t||"complete"===t?t:null}(t.goal);e&&"active"!==e&&(this.goalTerminalStates.set(s,{status:e}),this.activeTurnIds.has(s)||this.completedGoalTurns.add(s),this.finishGoalQueueIfReady(s,i));return}if("thread/goal/cleared"===e.method&&this.activeGoalThreads.has(s)){this.goalTerminalStates.set(s,{status:"cleared"}),this.activeTurnIds.has(s)||this.completedGoalTurns.add(s),this.finishGoalQueueIfReady(s,i);return}if("turn/started"===e.method){let e=t.turn;"string"==typeof e?.id&&this.activeTurnIds.set(s,e.id),this.completedGoalTurns.delete(s)}let r=function(e){if("turn/started"===e.method)return{type:"runtime_progress",progressId:"codex:status",phase:"status",label:"正在开始处理"};if("item/started"!==e.method)return null;let t=G(G(e.params).item);return"reasoning"===t.type&&"string"==typeof t.id&&t.id?{type:"runtime_progress",progressId:`codex:reasoning:${t.id}`,phase:"thinking",label:"正在思考"}:null}(e);r&&i.push(r);let a=function(e){if("item/reasoning/summaryTextDelta"!==e.method&&"item/reasoning/summaryPartAdded"!==e.method)return null;let t=G(e.params),s=t.itemId,i=t.summaryIndex;if("string"!=typeof s||!s||"number"!=typeof i||!Number.isSafeInteger(i)||i<0)return null;let r="item/reasoning/summaryPartAdded"===e.method?"":t.delta;return"string"!=typeof r?null:{type:"reasoning_summary_delta",itemId:s,sectionIndex:i,delta:r}}(e);if(a){i.push(a);return}if("item/reasoning/textDelta"!==e.method){if("item/agentMessage/delta"===e.method&&"string"==typeof t.delta){i.push({type:"text_chunk",text:t.delta});return}if("item/started"===e.method){let e=U(t.item);e&&i.push({type:"tool_call",toolCall:e});return}if("item/completed"===e.method){let e=W(t.item);e&&i.push({type:"tool_result",result:e});return}if("turn/completed"===e.method){let e=t.turn;if(this.activeTurnIds.delete(s),this.activeGoalThreads.has(s)){e?.status==="failed"?(i.push({type:"error",message:e.error?.message??"Codex turn failed"}),i.close()):e?.status==="interrupted"?(i.push({type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Codex turn was interrupted."}),i.close()):(this.lastGoalTurnText.set(s,$(e?.items??[])),this.completedGoalTurns.add(s),this.finishGoalQueueIfReady(s,i));return}if(e?.status==="failed")i.push({type:"error",message:e.error?.message??"Codex turn failed"});else if(e?.status==="interrupted")i.push({type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Codex turn was interrupted."});else{let t=$(e?.items??[]);i.push({type:"done",finalText:t})}i.close();return}if("turn/interrupt"===e.method){i.push({type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Codex turn was interrupted."}),i.close();return}"error"===e.method&&(i.push({type:"error",message:String(t.message??"Codex runtime error")}),i.close())}}async findWorkspace(e){let t=this.workspaces.get(e);if(t)return t;let s=null;do{let t=await this.listWorkspaces({cursor:s,limit:200,refresh:!0}),i=t.data.find(t=>t.workspaceId===e);if(i)return i;s=t.nextCursor}while(s);throw new S.n(`Codex workspace not found: ${e}`,"SESSION_NOT_FOUND")}finishGoalQueueIfReady(e,t){if(!this.completedGoalTurns.has(e))return;let s=this.goalTerminalStates.get(e);s&&("complete"===s.status?t.push({type:"done",finalText:this.lastGoalTurnText.get(e)??""}):t.push({type:"error",code:"NATIVE_PROTOCOL_ERROR",message:function(e){switch(e){case"paused":return"Codex goal was paused.";case"blocked":return"Codex goal is blocked.";case"usageLimited":return"Codex goal stopped because the usage limit was reached.";case"budgetLimited":return"Codex goal stopped because the token budget was reached.";case"cleared":return"Codex goal was cleared."}}(s.status)}),t.close())}handleServerRequest(e){let t=e.params??{};if("currentTime/read"===e.method){this.client.respond(e.id,{currentTime:new Date().toISOString()});return}let s="string"==typeof t.threadId?t.threadId:"string"==typeof t.conversationId?t.conversationId:void 0,i=s?this.activeQueues.get(s):void 0;if(!i){this.client.respondError(e.id,-32601,`Unsupported server request: ${e.method}`);return}let r=s?this.activeBrokerRunIds.get(s):void 0,a=r?`native:${r}:${String(e.id)}`:`codex:${String(e.id)}`,n={requestId:e.id,method:e.method,params:t,questionId:a};if("item/tool/requestUserInput"===e.method){this.pendingApprovals.set(a,n);let e=t.questions,s=e?.[0];i.push({type:"ask_user",questionId:a,question:s?.question??"Codex needs additional input",options:s?.options?.map(e=>({label:e.label,description:e.description??""}))});return}if(!new Set(["item/commandExecution/requestApproval","item/fileChange/requestApproval","item/permissions/requestApproval","applyPatchApproval","execCommandApproval"]).has(e.method)){this.client.respondError(e.id,-32601,`Unsupported server request: ${e.method}`);return}if(s&&"full-access"===this.activePermissionModes.get(s)){this.client.respond(e.id,P(n,"允许一次"));return}this.pendingApprovals.set(a,n);let o="string"==typeof t.command?t.command:Array.isArray(t.command)?t.command.join(" "):void 0,l="string"==typeof t.reason?t.reason:void 0,d="item/permissions/requestApproval"===e.method?function(e){let t=JSON.stringify(L(e));return t&&"{}"!==t?`Codex requests permission: ${t.slice(0,500)}`:"Codex requests expanded filesystem or network permission"}(t):void 0;i.push({type:"ask_user",questionId:a,question:l||d||(o?`Codex requests permission to run: ${o}`:"Codex requests permission to modify files"),options:[{label:"允许一次",description:"Allow this operation once"},{label:"本会话允许",description:"Allow equivalent operations for this session"},{label:"拒绝",description:"Decline this operation"},{label:"取消",description:"Cancel the current operation"}]})}}function x(e,t){return e.flatMap(e=>e.path&&("win32"===t?n.win32.isAbsolute(e.path):(0,n.isAbsolute)(e.path))?[e.path]:[])}function P(e,t){let s="本会话允许"===t?"acceptForSession":"允许一次"===t?"accept":"取消"===t?"cancel":"decline";return"item/permissions/requestApproval"!==e.method?{decision:s}:{permissions:"accept"===s||"acceptForSession"===s?L(e.params):Array.isArray(L(e.params))?[]:{},scope:"acceptForSession"===s?"session":"turn"}}function L(e){if("permissions"in e)return e.permissions;if("requestedPermissions"in e)return e.requestedPermissions;let t={};for(let s of["filesystem","network","filesystemPermissions","networkPermissions"])s in e&&(t[s]=e[s]);return t}async function D(e,t){await (0,r.mkdir)(t,{recursive:!0,mode:448});let s=await (0,r.mkdtemp)((0,n.join)(t,"customer-agent-codex-images-"));try{let t=[];for(let[i,a]of e.entries()){let e=(0,n.join)(s,`image-${i+1}.${a.extension}`);await (0,r.writeFile)(e,a.bytes,{mode:384}),t.push({type:"localImage",path:e})}return{directory:s,inputs:t}}catch(e){throw await (0,r.rm)(s,{recursive:!0,force:!0}).catch(()=>void 0),e}}async function q(e){let t=(0,n.basename)(e)||"image",s=k[(0,n.extname)(e).toLowerCase()];if(!s)return{type:"image",name:t,unavailable:!0};try{let i=await (0,r.stat)(e);if(!i.isFile()||i.size>20971520)return{type:"image",name:t,unavailable:!0};let a=await (0,r.readFile)(e);if(a.byteLength>20971520)return{type:"image",name:t,unavailable:!0};return{type:"image",name:t,dataUrl:`data:${s};base64,${a.toString("base64")}`}}catch{return{type:"image",name:t,unavailable:!0}}}async function M(e){let t=[];for(let s of e)for(let e of s.items??[])if("userMessage"===e.type){let s=e.content,i=s?.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>String(e.text)).join("\n").trim();if(i){let e=function(e){let t=e.trim(),s=-1;if(t.startsWith(T)){let e=t.indexOf(O,T.length);if(e<0)return{content:t};s=e+O.length}else{if(!t.startsWith(N))return{content:t};let e=t.indexOf(A,N.length);if(e<0)return{content:t};s=e+A.length}let i=t.indexOf(R,s);if(i<0)return{content:t};let r=t.slice(i+R.length).trim();return r?{content:r,rawContent:t}:{content:t}}(i),r=(s??[]).filter(e=>("local_image"===e.type||"localImage"===e.type)&&"string"==typeof e.path).map(e=>String(e.path)),a=await Promise.all(r.map(q)),n=e.rawContent||a.length>0?{...e.rawContent?{rawContent:e.rawContent}:{},...a.length>0?{attachments:a}:{}}:void 0;t.push({role:"user",content:e.content,...n?{presentation:n}:{}})}}else if("agentMessage"===e.type&&"string"==typeof e.text&&e.text.trim())t.push({role:"assistant",content:e.text});else if("reasoning"===e.type&&Array.isArray(e.summary)){let s=e.summary.flatMap((t,s)=>"string"==typeof t&&t.trim()?[{itemId:e.id??`reasoning-${s}`,sectionIndex:s,text:t}]:[]);s.length>0&&t.push({role:"assistant",content:"",presentation:{reasoning:s}})}else{let s=U(e);s&&t.push({role:"assistant",content:"",toolCalls:[s]});let i=W(e);i&&t.push({role:"tool",content:i.content,toolCallId:i.toolCallId,name:s?.name})}return t}function U(e){return e?.id?"commandExecution"===e.type?{id:e.id,name:"shell",arguments:{command:e.command,cwd:e.cwd}}:"fileChange"===e.type?{id:e.id,name:"apply_patch",arguments:{changes:e.changes}}:"mcpToolCall"===e.type?{id:e.id,name:`${String(e.server)}:${String(e.tool)}`,arguments:G(e.arguments)}:"dynamicToolCall"===e.type?{id:e.id,name:String(e.tool),arguments:G(e.arguments)}:null:null}function W(e){return e?.id?"commandExecution"===e.type?{toolCallId:e.id,content:"string"==typeof e.aggregatedOutput?e.aggregatedOutput:"",isError:"number"==typeof e.exitCode&&0!==e.exitCode}:"fileChange"===e.type?{toolCallId:e.id,content:JSON.stringify(e.changes??[],null,2),isError:"failed"===e.status}:"mcpToolCall"===e.type||"dynamicToolCall"===e.type?{toolCallId:e.id,content:JSON.stringify(e.result??e.contentItems??e.error??{},null,2),isError:!!e.error||!1===e.success}:null:null}function $(e){for(let t=e.length-1;t>=0;t--){let s=e[t];if("agentMessage"===s.type&&"string"==typeof s.text)return s.text}return""}function G(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{value:e}}function j(e){return e instanceof S.n?e:new S.n(e instanceof Error?e.message:String(e),"NATIVE_PROTOCOL_ERROR")}},9956:(e,t,s)=>{s.d(t,{u:()=>n});var i=s(132);let r=4*Math.ceil(6990506.666666667),a={"image/jpeg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp"};function n(e){return(e??[]).map((e,t)=>(function(e,t){let s=`Image ${t+1}`,i=/^data:(image\/(?:jpeg|png|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec(e);if(!i)throw o(`${s} must be a base64 JPEG, PNG, GIF, or WebP data URL`);let n=i[1],l=i[2];if(l.length%4!=0||l.length>r)throw o(`${s} is malformed or exceeds the 20 MB limit`);let d=Buffer.from(l,"base64");if(d.toString("base64").replace(/=+$/,"")!==l.replace(/=+$/,"")||!function(e,t){if("image/jpeg"===e)return t.length>=3&&255===t[0]&&216===t[1]&&255===t[2];if("image/png"===e)return t.length>=8&&t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]));if("image/gif"===e){let e=t.subarray(0,6).toString("ascii");return"GIF87a"===e||"GIF89a"===e}return t.length>=12&&"RIFF"===t.subarray(0,4).toString("ascii")&&"WEBP"===t.subarray(8,12).toString("ascii")}(n,d))throw o(`${s} content does not match its declared media type`);if(d.byteLength>20971520)throw o(`${s} exceeds the 20 MB limit`);return{mimeType:n,extension:a[n],base64:l,bytes:d}})(e,t))}function o(e){return new i.n(e,"NATIVE_PROTOCOL_ERROR")}},5300:(e,t,s)=>{s.d(t,{g:()=>n});var i=s(7718),r=s(7561);let a=(0,s(5881).promisify)(i.execFile);async function n(e,t,s={}){if((s.platform??process.platform)==="win32")return new Set;try{let i=s.execute??a,{stdout:n}=await i("lsof",["+c","0","-a","-c",e,"-FpFn"],{encoding:"utf8",timeout:5e3,maxBuffer:4194304});return function(e,t,s={}){let i=t.endsWith("/")?t:`${t}/`,a=new Set(s.excludePids??[]),n=void 0===s.idleAfterMs?12e4:s.idleAfterMs,o=s.nowMs??Date.now(),l=s.getMtimeMs??(e=>(0,r.statSync)(e).mtimeMs),d=new Set,u=null;for(let t of e.split("\n"))if(t.startsWith("p"))u=Number(t.slice(1));else if(t.startsWith(`n${i}`)&&(null===u||!a.has(u))){let e=t.slice(1);try{let t=l(e);if(null!==n&&o-t>n)continue}catch{continue}d.add(e)}return d}(n,t,s)}catch{return new Set}}},7578:(e,t,s)=>{s.a(e,async(e,i)=>{try{s.d(t,{WH:()=>E,v6:()=>I});var r=s(6005),a=s(7561),n=s(7503),o=s(612),l=s(9411),d=s(1322),u=s(8224),c=s(2557),p=s(3088),h=s(9529),m=s(3053),f=s(8733),y=s(2815),g=s(5779),w=s(132),v=s(2428),_=e([p]);p=(_.then?(await _)():_)[0];let q="native-runtime.sock";class M{constructor(e,t){this.now=t,(0,a.mkdirSync)(e,{recursive:!0,mode:448});try{(0,a.chmodSync)(e,448)}catch{}this.database=new d.G1(e),this.database.db.exec(`
3
+ CREATE TABLE IF NOT EXISTS native_runtime_policy (
4
+ session_id TEXT PRIMARY KEY,
5
+ permission_mode TEXT NOT NULL,
6
+ updated_at INTEGER NOT NULL
7
+ );
8
+ CREATE TABLE IF NOT EXISTS native_runtime_run (
9
+ run_id TEXT PRIMARY KEY,
10
+ session_id TEXT NOT NULL,
11
+ agent_type TEXT NOT NULL,
12
+ native_session_id TEXT NOT NULL,
13
+ input TEXT NOT NULL,
14
+ permission_mode TEXT NOT NULL,
15
+ controller TEXT NOT NULL,
16
+ status TEXT NOT NULL,
17
+ next_sequence INTEGER NOT NULL DEFAULT 0,
18
+ created_at INTEGER NOT NULL,
19
+ terminal_at INTEGER,
20
+ goal_id TEXT
21
+ );
22
+ CREATE UNIQUE INDEX IF NOT EXISTS native_runtime_active_run_per_session
23
+ ON native_runtime_run(session_id) WHERE status = 'active';
24
+ CREATE INDEX IF NOT EXISTS native_runtime_runs_by_session
25
+ ON native_runtime_run(session_id, created_at DESC);
26
+ CREATE TABLE IF NOT EXISTS native_runtime_event (
27
+ run_id TEXT NOT NULL,
28
+ sequence INTEGER NOT NULL,
29
+ payload TEXT NOT NULL,
30
+ created_at INTEGER NOT NULL,
31
+ PRIMARY KEY(run_id, sequence)
32
+ );
33
+ CREATE TABLE IF NOT EXISTS native_runtime_approval (
34
+ question_id TEXT PRIMARY KEY,
35
+ run_id TEXT NOT NULL,
36
+ state TEXT NOT NULL,
37
+ created_at INTEGER NOT NULL,
38
+ resolved_at INTEGER
39
+ );
40
+ CREATE INDEX IF NOT EXISTS native_runtime_approval_by_run
41
+ ON native_runtime_approval(run_id, state);
42
+ CREATE TABLE IF NOT EXISTS native_runtime_lock (
43
+ session_id TEXT PRIMARY KEY,
44
+ occupancy TEXT NOT NULL,
45
+ revision INTEGER NOT NULL,
46
+ sample_state TEXT,
47
+ sample_at INTEGER,
48
+ updated_at INTEGER NOT NULL
49
+ );
50
+ CREATE TABLE IF NOT EXISTS native_runtime_goal_state (
51
+ session_id TEXT PRIMARY KEY,
52
+ payload TEXT NOT NULL,
53
+ updated_at INTEGER NOT NULL
54
+ );
55
+ CREATE TABLE IF NOT EXISTS native_runtime_pending_session (
56
+ session_id TEXT PRIMARY KEY,
57
+ payload TEXT NOT NULL,
58
+ updated_at INTEGER NOT NULL
59
+ );
60
+ CREATE TABLE IF NOT EXISTS native_runtime_session_title (
61
+ session_id TEXT PRIMARY KEY,
62
+ title TEXT NOT NULL,
63
+ auto_title_pending INTEGER NOT NULL,
64
+ updated_at INTEGER NOT NULL
65
+ );
66
+ CREATE TABLE IF NOT EXISTS native_runtime_hidden_session (
67
+ session_id TEXT PRIMARY KEY,
68
+ hidden_at INTEGER NOT NULL
69
+ );
70
+ CREATE TABLE IF NOT EXISTS native_runtime_imported_workspace (
71
+ workspace_id TEXT PRIMARY KEY,
72
+ agent_type TEXT NOT NULL,
73
+ normalized_path TEXT NOT NULL,
74
+ name TEXT NOT NULL,
75
+ created_at INTEGER NOT NULL,
76
+ UNIQUE(agent_type, normalized_path)
77
+ );
78
+ CREATE INDEX IF NOT EXISTS native_runtime_imported_workspace_order
79
+ ON native_runtime_imported_workspace(agent_type, created_at ASC, workspace_id ASC);
80
+ `),this.database.db.prepare("PRAGMA table_info(native_runtime_run)").all().some(e=>"goal_id"===e.name)||this.database.db.exec("ALTER TABLE native_runtime_run ADD COLUMN goal_id TEXT")}list(e){return this.database.db.prepare(`
81
+ SELECT workspace_id, agent_type, normalized_path, name, created_at
82
+ FROM native_runtime_imported_workspace
83
+ WHERE agent_type = ?
84
+ ORDER BY created_at ASC, workspace_id ASC
85
+ `).all(e).map(T)}findByPath(e,t){let s=this.database.db.prepare(`
86
+ SELECT workspace_id, agent_type, normalized_path, name, created_at
87
+ FROM native_runtime_imported_workspace
88
+ WHERE agent_type = ? AND normalized_path = ?
89
+ `).get(e,t);return s?T(s):null}findImportedWorkspace(e,t){let s=this.database.db.prepare(`
90
+ SELECT workspace_id, agent_type, normalized_path, name, created_at
91
+ FROM native_runtime_imported_workspace
92
+ WHERE agent_type = ? AND workspace_id = ?
93
+ `).get(e,t);return s?T(s):null}save(e){let t=this.database.db.prepare(`
94
+ INSERT OR IGNORE INTO native_runtime_imported_workspace(
95
+ workspace_id, agent_type, normalized_path, name, created_at
96
+ ) VALUES (?, ?, ?, ?, ?)
97
+ `).run(e.workspaceId,e.agentType,e.normalizedPath,e.name,e.createdAt);return{workspace:this.findByPath(e.agentType,e.normalizedPath)??e,existing:0===t.changes}}recoverInterruptedRuns(){for(let e of this.database.db.prepare("SELECT * FROM native_runtime_run WHERE status = 'active'").all())this.appendTerminal(e.run_id,{type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Native runtime restarted; this turn was interrupted. You can send again."});this.pruneExpiredTerminals()}getPermissionMode(e){let t=this.database.db.prepare("SELECT permission_mode FROM native_runtime_policy WHERE session_id = ?").get(e);return(0,d.Ny)(t?.permission_mode)}setPermissionMode(e,t){let s=(0,d.Ny)(t);return this.database.db.prepare(`
98
+ INSERT INTO native_runtime_policy(session_id, permission_mode, updated_at)
99
+ VALUES (?, ?, ?)
100
+ ON CONFLICT(session_id) DO UPDATE SET permission_mode=excluded.permission_mode, updated_at=excluded.updated_at
101
+ `).run(e,s,this.now()),s}trackPendingAutoTitle(e,t){t===d.Fi&&this.database.db.prepare(`
102
+ INSERT OR IGNORE INTO native_runtime_session_title(
103
+ session_id, title, auto_title_pending, updated_at
104
+ ) VALUES (?, ?, 1, ?)
105
+ `).run(e,t,this.now())}getDisplayTitle(e){let t=this.database.db.prepare("SELECT title FROM native_runtime_session_title WHERE session_id = ?").get(e);return t?.title??null}listPendingSessions(){return this.database.db.prepare("SELECT payload FROM native_runtime_pending_session ORDER BY updated_at DESC").all().flatMap(e=>{let t=function(e){try{let t=JSON.parse(e);if("claude-code"!==t.agentType||"string"!=typeof t.id||"string"!=typeof t.nativeSessionId||"string"!=typeof t.title||"string"!=typeof t.cwd||"string"!=typeof t.created||"string"!=typeof t.updated||"idle"!==t.status&&"running"!==t.status||!["available","owned-externally","owned-by-customer-agent"].includes(t.occupancy??"")||"string"!=typeof t.sourceLabel||"boolean"!=typeof t.canResume||"boolean"!=typeof t.canDelete)return null;return t}catch{return null}}(e.payload);return t?[t]:[]})}savePendingSession(e){this.database.db.prepare(`
106
+ INSERT INTO native_runtime_pending_session(session_id, payload, updated_at)
107
+ VALUES (?, ?, ?)
108
+ ON CONFLICT(session_id) DO UPDATE SET payload=excluded.payload, updated_at=excluded.updated_at
109
+ `).run(e.id,JSON.stringify(e),this.now())}deletePendingSession(e){this.database.db.prepare("DELETE FROM native_runtime_pending_session WHERE session_id = ?").run(e)}hideSession(e){this.database.db.transaction(()=>{if(this.activeRun(e))throw new w.n("Session is currently running","SESSION_OCCUPIED");this.database.db.prepare(`
110
+ INSERT OR IGNORE INTO native_runtime_hidden_session(session_id, hidden_at)
111
+ VALUES (?, ?)
112
+ `).run(e,this.now()),this.database.db.prepare("DELETE FROM native_runtime_pending_session WHERE session_id = ?").run(e),this.database.db.prepare("DELETE FROM native_runtime_goal_state WHERE session_id = ?").run(e)})()}isSessionHidden(e){return!!this.database.db.prepare("SELECT 1 AS hidden FROM native_runtime_hidden_session WHERE session_id = ?").get(e)}filterHiddenSessions(e){let t=new Set(this.database.db.prepare("SELECT session_id FROM native_runtime_hidden_session").all().map(e=>e.session_id));return e.filter(e=>!t.has(e.id))}assertSessionVisible(e){if(this.isSessionHidden(e))throw new w.n(`Native session not found: ${e}`,"SESSION_NOT_FOUND")}getGoalState(e){let t=this.database.db.prepare("SELECT payload FROM native_runtime_goal_state WHERE session_id = ?").get(e);if(!t?.payload)return(0,d.uA)(void 0);try{return(0,d.uA)({goalState:JSON.parse(t.payload)})}catch{return(0,d.uA)(void 0)}}enqueueGoal(e,t,s){return this.updateGoalState(e,i=>(0,d.Wf)(i,{id:(0,r.randomUUID)(),sessionId:e,objective:t,sourceMessageId:s,now:this.now()}))}reorderGoals(e,t){return this.updateGoalState(e,e=>(0,d.ZC)(e,t))}cancelGoal(e,t){return this.updateGoalState(e,e=>(0,d.LJ)(e,t,this.now()))}finishGoal(e,t,s,i){return this.updateGoalState(e,e=>e.active?.id===t?(0,d.JX)(e,s,this.now(),i):e)}listActiveGoals(){return this.database.db.prepare("SELECT payload FROM native_runtime_goal_state").all().flatMap(e=>{try{let t=(0,d.uA)({goalState:JSON.parse(e.payload)});return t.active?[t.active]:[]}catch{return[]}})}updateGoalState(e,t){return this.database.db.transaction(()=>{let s=t(this.getGoalState(e));return this.database.db.prepare(`
113
+ INSERT INTO native_runtime_goal_state(session_id, payload, updated_at)
114
+ VALUES (?, ?, ?)
115
+ ON CONFLICT(session_id) DO UPDATE SET payload=excluded.payload, updated_at=excluded.updated_at
116
+ `).run(e,JSON.stringify(s),this.now()),s})()}admit(e){return this.database.db.transaction(()=>{let t=this.database.db.prepare("SELECT run_id FROM native_runtime_run WHERE session_id = ? AND status = 'active'").get(e.sessionId);if(t?.run_id)throw new w.n("Session is already running","SESSION_OCCUPIED");let s=this.now();e.message.trim()&&this.database.db.prepare(`
117
+ UPDATE native_runtime_session_title
118
+ SET title = ?, auto_title_pending = 0, updated_at = ?
119
+ WHERE session_id = ? AND auto_title_pending = 1
120
+ `).run(e.message.slice(0,60),s,e.sessionId);let i={sessionId:e.sessionId,runId:(0,r.randomUUID)(),agentType:e.agentType,nativeSessionId:e.nativeSessionId,input:e.message,permissionMode:this.getPermissionMode(e.sessionId),controller:e.controller,status:"active",nextSequence:0,createdAt:s,terminalAt:null,goalId:e.goalId??null};return this.database.db.prepare(`
121
+ INSERT INTO native_runtime_run(
122
+ run_id, session_id, agent_type, native_session_id, input, permission_mode,
123
+ controller, status, next_sequence, created_at, terminal_at, goal_id
124
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
125
+ `).run(i.runId,i.sessionId,i.agentType,i.nativeSessionId,i.input,i.permissionMode,i.controller,i.status,i.nextSequence,i.createdAt,i.terminalAt,i.goalId),this.transitionLock(e.sessionId,"owned-by-customer-agent",null,null),i})()}appendEvent(e,t){return this.database.db.transaction(()=>{let s=this.getRunById(e);if(!s||"active"!==s.status)return null;let i=s.nextSequence+1;return this.database.db.prepare("INSERT INTO native_runtime_event(run_id, sequence, payload, created_at) VALUES (?, ?, ?, ?)").run(e,i,JSON.stringify(t),this.now()),this.database.db.prepare("UPDATE native_runtime_run SET next_sequence = ? WHERE run_id = ?").run(i,e),"ask_user"===t.type&&this.database.db.prepare(`
126
+ INSERT INTO native_runtime_approval(question_id, run_id, state, created_at, resolved_at)
127
+ VALUES (?, ?, 'pending', ?, NULL)
128
+ ON CONFLICT(question_id) DO NOTHING
129
+ `).run(t.questionId,e,this.now()),O(t)&&this.finalizeRun(e,"error"===t.type?t.message:null),{runId:e,sequence:i,event:t}})()}appendTerminal(e,t){let s=this.getRunById(e);return s&&"active"===s.status?this.appendEvent(e,t):null}getSnapshot(e,t=0){let s=this.projection(e,t);return{sessionId:e,runId:s.run?.runId??null,snapshotRevision:s.run?.nextSequence??0,events:s.events,controller:s.run?.status==="active"?s.run.controller:null}}projection(e,t=0){let s=this.getLatestRetainedRun(e);if(!s)return{run:null,events:[]};let i=this.database.db.prepare(`
130
+ SELECT run_id, sequence, payload FROM native_runtime_event
131
+ WHERE run_id = ? AND sequence > ? ORDER BY sequence ASC
132
+ `).all(s.runId,t).flatMap(e=>{let t=function(e){try{let t=JSON.parse(e);return t&&"object"==typeof t&&"string"==typeof t.type?t:null}catch{return null}}(e.payload);return t&&("ask_user"!==t.type||this.isApprovalVisible(t.questionId))?[{runId:e.run_id,sequence:e.sequence,event:t}]:[]});return{run:s,events:i}}claimApproval(e){return this.database.db.transaction(()=>{let t=this.database.db.prepare(`
133
+ SELECT approval.run_id
134
+ FROM native_runtime_approval approval
135
+ JOIN native_runtime_run run ON run.run_id = approval.run_id
136
+ WHERE approval.question_id = ? AND approval.state = 'pending' AND run.status = 'active'
137
+ `).get(e);if(!t?.run_id)return null;let s=this.database.db.prepare(`
138
+ UPDATE native_runtime_approval SET state = 'claimed'
139
+ WHERE question_id = ? AND state = 'pending'
140
+ `).run(e).changes;return 1===s?this.getRunById(t.run_id):null})()}resolveApproval(e){let t=this.database.db.transaction(()=>{let t=this.database.db.prepare(`
141
+ SELECT run_id FROM native_runtime_approval
142
+ WHERE question_id = ? AND state IN ('pending', 'claimed')
143
+ `).get(e);if(!t?.run_id)return null;let s=this.database.db.prepare(`
144
+ UPDATE native_runtime_approval SET state = 'resolved', resolved_at = ?
145
+ WHERE question_id = ? AND state IN ('pending', 'claimed')
146
+ `).run(this.now(),e).changes;return 1===s?t.run_id:null})();return t?this.appendEvent(t,{type:"approval_resolved",questionId:e}):null}restoreApproval(e){this.database.db.prepare(`
147
+ UPDATE native_runtime_approval SET state = 'pending', resolved_at = NULL
148
+ WHERE question_id = ? AND state = 'claimed'
149
+ `).run(e)}changeController(e,t){return this.database.db.prepare(`
150
+ UPDATE native_runtime_run SET controller = ? WHERE session_id = ? AND status = 'active'
151
+ `).run(t,e),this.getSnapshot(e)}activeRun(e){let t=this.database.db.prepare("SELECT * FROM native_runtime_run WHERE session_id = ? AND status = 'active'").get(e);return t?b(t):null}hasActiveRuns(){let e=this.database.db.prepare("SELECT 1 AS active FROM native_runtime_run WHERE status = 'active' LIMIT 1").get();return e?.active===1}sessionIdForRun(e){return this.getRunById(e)?.sessionId??null}recordExplicitExternalOwnership(e){this.activeRun(e)||this.transitionLock(e,"owned-externally","occupied",this.now())}observeDiscovery(e,t){if(this.activeRun(e))return this.transitionLock(e,"owned-by-customer-agent",null,null);let s=this.getLock(e),i=t?"occupied":"clean",r=this.now();return s.sampleState===i&&null!==s.sampleAt&&r-s.sampleAt>=5e3?this.transitionLock(e,t?"owned-externally":"available",i,r):(this.database.db.prepare(`
152
+ INSERT INTO native_runtime_lock(session_id, occupancy, revision, sample_state, sample_at, updated_at)
153
+ VALUES (?, ?, ?, ?, ?, ?)
154
+ ON CONFLICT(session_id) DO UPDATE SET sample_state=excluded.sample_state, sample_at=excluded.sample_at, updated_at=excluded.updated_at
155
+ `).run(e,s.occupancy,s.revision,i,r,r),{...s,sampleState:i,sampleAt:r})}applySummary(e){let t="owned-externally"===e.occupancy,s=this.observeDiscovery(e.id,t),i=this.getPermissionMode(e.id),r=this.activeRun(e.id),a=r?"owned-by-customer-agent":s.occupancy;return{...e,title:this.getDisplayTitle(e.id)??e.title,occupancy:a,status:r?"running":e.status,canResume:"owned-externally"!==a,canDelete:!r,permissionMode:i,occupancyRevision:s.revision,controller:r?.controller??null,goalState:this.getGoalState(e.id)}}applyDetail(e){let t=this.applySummary(e),s=this.projection(e.id),i=function(e,t,s){if(!t)return e;let i=[...e],r=-1;for(let e=i.length-1;e>=0;e-=1){let s=i[e];if("user"===s.role&&s.content===t.input){r=e;break}}let a=r>=0,n=i.length;for(let e=r+1;a&&e<i.length;e+=1)if("user"===i[e].role){n=e;break}let o=a?i.slice(r+1,n).filter(e=>"assistant"===e.role).map(e=>e.content).join(""):null,l=0;a||i.push({role:"user",content:t.input,name:`__native_run:${t.runId}`});let u=[],c=null;for(let{event:e}of s){if("reasoning_summary_delta"===e.type){let s=`__native_reasoning:${t.runId}:${e.itemId}`,i=u.findIndex(e=>e.name===s);i<0&&(i=u.length,u.push({role:"assistant",content:"",name:s,presentation:{reasoning:[]}}));let r=u[i];u[i]={...r,presentation:{...r.presentation,reasoning:(0,d.bX)(r.presentation?.reasoning,e)}},c=null;continue}if("text_chunk"!==e.type&&"tool_call"!==e.type)continue;null===c&&(c=u.length,u.push({role:"assistant",content:"",name:`__native_run:${t.runId}`}));let s=u[c];u[c]="text_chunk"===e.type?{...s,content:s.content+e.text}:{...s,toolCalls:[...s.toolCalls??[],e.toolCall]}}for(let e of u){let t=e.presentation?.reasoning;if(t?.length){let s=i.findIndex(e=>e.presentation?.reasoning?.some(e=>t.some(t=>t.itemId===e.itemId)));if(s<0)i.push(e);else{let e=i[s],r=[...e.presentation?.reasoning??[]];for(let e of t){let t=r.findIndex(t=>t.itemId===e.itemId&&t.sectionIndex===e.sectionIndex);t<0?r.push(e):e.text.startsWith(r[t].text)&&(r[t]=e)}i[s]={...e,presentation:{...e.presentation,reasoning:r.sort((e,t)=>e.sectionIndex-t.sectionIndex)}}}continue}let s=function(e,t,s){let i=e.filter(e=>"assistant"===e.role),r=t.content,a=0;r&&null!==s?r.startsWith(s)?(a=s.length,r=r.slice(a)):s.startsWith(r)&&(a=r.length,r=""):r&&i.some(e=>e.content===r)&&(r="");let n=new Set(i.flatMap(e=>e.toolCalls?.map(e=>e.id)??[])),o=t.toolCalls?.filter(e=>!n.has(e.id));return{consumedAssistantText:a,message:r||o?.length?{...t,content:r,toolCalls:o?.length?o:void 0}:null}}(i,e,o?.slice(l)??null);l+=s.consumedAssistantText,s.message&&i.push(s.message)}return i}(e.messages,s.run,s.events);return{...e,...t,messages:i,events:s.events.map(({event:e})=>e),snapshotRevision:s.run?.nextSequence??0,snapshotRunId:s.run?.runId??null}}getRunById(e){let t=this.database.db.prepare("SELECT * FROM native_runtime_run WHERE run_id = ?").get(e);return t?b(t):null}getLatestRetainedRun(e){let t=this.database.db.prepare(`
156
+ SELECT * FROM native_runtime_run
157
+ WHERE session_id = ? AND (status = 'active' OR terminal_at >= ?)
158
+ ORDER BY CASE status WHEN 'active' THEN 0 ELSE 1 END, created_at DESC LIMIT 1
159
+ `).get(e,this.now()-6e5);return t?b(t):null}isApprovalVisible(e){let t=this.database.db.prepare("SELECT state FROM native_runtime_approval WHERE question_id = ?").get(e);return t?.state==="pending"||t?.state==="claimed"}finalizeRun(e,t){let s=this.getRunById(e);if(!s||"active"!==s.status)return;let i=this.now();this.database.db.prepare(`
160
+ UPDATE native_runtime_run SET status = 'terminal', terminal_at = ? WHERE run_id = ?
161
+ `).run(i,e),this.database.db.prepare(`
162
+ UPDATE native_runtime_approval SET state = 'resolved', resolved_at = ?
163
+ WHERE run_id = ? AND state IN ('pending', 'claimed')
164
+ `).run(i,e),this.transitionLock(s.sessionId,"available",null,null)}getLock(e){let t=this.database.db.prepare("SELECT * FROM native_runtime_lock WHERE session_id = ?").get(e);return t?{sessionId:t.session_id,occupancy:t.occupancy,revision:t.revision,sampleState:t.sample_state,sampleAt:t.sample_at}:{sessionId:e,occupancy:"available",revision:0,sampleState:null,sampleAt:null}}transitionLock(e,t,s,i){let r=this.getLock(e),a=r.occupancy===t?r.revision:r.revision+1,n=this.now();return this.database.db.prepare(`
165
+ INSERT INTO native_runtime_lock(session_id, occupancy, revision, sample_state, sample_at, updated_at)
166
+ VALUES (?, ?, ?, ?, ?, ?)
167
+ ON CONFLICT(session_id) DO UPDATE SET
168
+ occupancy=excluded.occupancy,
169
+ revision=excluded.revision,
170
+ sample_state=excluded.sample_state,
171
+ sample_at=excluded.sample_at,
172
+ updated_at=excluded.updated_at
173
+ `).run(e,t,a,s,i,n),{sessionId:e,occupancy:t,revision:a,sampleState:s,sampleAt:i}}pruneExpiredTerminals(){let e=this.now()-6e5,t=this.database.db.prepare("SELECT run_id FROM native_runtime_run WHERE status = 'terminal' AND terminal_at < ?").all(e);this.database.db.transaction(()=>{for(let e of t)this.database.db.prepare("DELETE FROM native_runtime_event WHERE run_id = ?").run(e.run_id),this.database.db.prepare("DELETE FROM native_runtime_approval WHERE run_id = ?").run(e.run_id),this.database.db.prepare("DELETE FROM native_runtime_run WHERE run_id = ?").run(e.run_id)})()}}class U{constructor(e,t,s=Date.now){this.directory=e,this.activeExecutions=new Map,this.subscribers=new Map,this.localSubscribers=new Set,this.pendingCreations=new Map,this.server=null,this.ownsSocket=!1,this.state=new M(e,s),this.runtime="function"==typeof t?t({onApprovalResolved:e=>this.handleApprovalResolved(e),importedWorkspaceRepository:this.state}):t;let i=this.state.listPendingSessions();for(let e of i)this.pendingCreations.set(e.id,e);this.runtime.restoreDrafts?.(i)}get socketPath(){return(0,l.join)(this.directory,q)}async start(){if(this.server)return;(0,a.mkdirSync)(this.directory,{recursive:!0,mode:448});try{(0,a.chmodSync)(this.directory,448)}catch{}if((0,a.existsSync)(this.socketPath)){let e=Error(`Native runtime broker socket is already in use: ${this.socketPath}`);throw e.code="EADDRINUSE",e}let e=(0,n.createServer)(e=>this.handleSocket(e));await new Promise((t,s)=>{let i=t=>{e.removeListener("listening",r),s(t)},r=()=>{e.removeListener("error",i),t()};e.once("error",i),e.once("listening",r),e.listen(this.socketPath)});try{(0,a.chmodSync)(this.socketPath,384)}catch{}for(let t of(this.server=e,this.ownsSocket=!0,this.state.recoverInterruptedRuns(),this.state.listActiveGoals()))this.startGoal(t,"web")}async stop(){let e=this.server;for(let e of(this.server=null,this.subscribers.keys()))e.destroy();this.subscribers.clear(),this.localSubscribers.clear(),e&&await new Promise(t=>e.close(()=>t())),this.ownsSocket&&(0,a.existsSync)(this.socketPath)&&(0,a.rmSync)(this.socketPath,{force:!0}),this.ownsSocket=!1,await this.runtime.dispose()}async health(){return this.runtime.health()}async list(e){return this.state.filterHiddenSessions(this.mergePending(await this.runtime.list(e),e)).map(e=>this.state.applySummary(e))}listWorkspaces(e,t){return this.runtime.listWorkspaces(e,t)}importWorkspace(e,t,s){return this.runtime.importWorkspace(e,t,s)}async listWorkspaceSessions(e,t,s){let i=await this.runtime.listWorkspaceSessions(e,t,s),r=this.state.findImportedWorkspace(e,t);return{...i,data:this.state.filterHiddenSessions(this.mergePending(i.data,void 0,s=>s.agentType===e&&(s.projectId===t||!!(r&&s.cwd&&(0,c.vT)(s.cwd)===r.normalizedPath)))).map(e=>this.state.applySummary(e))}}async refresh(e){return this.state.filterHiddenSessions(this.mergePending(await this.runtime.refresh(e),e)).map(e=>this.state.applySummary(e))}async create(e){let t=await this.runtime.create(e);return this.pendingCreations.set(t.id,t),"claude-code"===t.agentType&&this.state.savePendingSession(t),this.state.trackPendingAutoTitle(t.id,e.title),this.state.applySummary(t)}async fork(e){this.state.assertSessionVisible(e);let t=await this.runtime.fork(e);return this.pendingCreations.set(t.id,t),this.state.applySummary(t)}async delete(e){this.state.hideSession(e),this.pendingCreations.delete(e),this.runtime.invalidate(e)}async get(e,t){this.state.assertSessionVisible(e);try{let s=await this.runtime.getUnpaginated(e,!!t?.before),i=this.state.applyDetail(s);return t?{...i,...(0,d.MO)(i.messages,i.events,t)}:i}catch(r){let s=this.pendingCreations.get(e);if(!s)throw r;let i=this.state.applyDetail({...s,messages:[],events:[]});return t?{...i,...(0,d.MO)(i.messages,i.events,t)}:i}}async getSessionWatchPath(e){return this.state.assertSessionVisible(e),this.runtime.getSessionWatchPath(e)}async startRun(e,t,s,i="web",r){this.state.assertSessionVisible(e);let a=this.activeExecutions.get(e);a&&!this.state.activeRun(e)&&await a;let n=S(e);try{let t=await this.runtime.get(e);if(!t.canResume||"owned-externally"===t.occupancy)throw this.state.recordExplicitExternalOwnership(e),new w.n("Session is currently owned by another client","SESSION_OCCUPIED")}catch(t){throw t instanceof w.n&&"SESSION_OCCUPIED"===t.code&&this.state.recordExplicitExternalOwnership(e),t}let o=this.state.admit({sessionId:e,agentType:n.agentType,nativeSessionId:n.nativeSessionId,message:t,controller:i,goalId:r}),l=this.executeRun(o,s);this.activeExecutions.set(e,l);let d=()=>{this.activeExecutions.get(e)===l&&this.activeExecutions.delete(e)};return l.then(d,d),{runId:o.runId,snapshotRevision:o.nextSequence,permissionMode:o.permissionMode}}async getGoals(e,t="web"){let s=this.state.getGoalState(e);return s.active&&!this.state.activeRun(e)&&await this.startGoal(s.active,t),this.state.getGoalState(e)}async enqueueGoal(e,t,s,i="web"){S(e);let r=!!this.state.getGoalState(e).active,a=this.state.enqueueGoal(e,t,s);if(r||!a.active)return{state:a};let n=await this.startGoal(a.active,i);return{state:this.state.getGoalState(e),...n?{started:n}:{}}}reorderGoals(e,t){return S(e),this.state.reorderGoals(e,t)}async cancelGoal(e,t,s="web"){S(e);let i=this.state.getGoalState(e).active?.id===t,r=this.state.activeRun(e),a=this.state.cancelGoal(e,t);return i&&r?.goalId===t?(await this.runtime.abort(e).catch(()=>void 0),!this.state.activeRun(e)&&a.active&&this.startGoal(a.active,s)):i&&!r&&a.active&&this.startGoal(a.active,s),a}subscribe(e,t,s){let i=this.state.getSnapshot(e,t);for(let e of i.events)s(e);let r={sessionId:e,runId:i.runId,afterSequence:i.snapshotRevision,listener:s};return this.localSubscribers.add(r),()=>this.localSubscribers.delete(r)}snapshot(e,t=0){return this.state.getSnapshot(e,t)}async answerQuestion(e,t){let s=this.state.claimApproval(e);if(!s)return!1;try{if(await this.runtime.answerQuestion(e,t))return this.handleApprovalResolved(e),!0}catch{}let i=this.state.appendTerminal(s.runId,{type:"error",code:"APPROVAL_EXPIRED",message:"This approval request is no longer active; the native turn was interrupted. You can send again."});throw i&&this.broadcast(i),new w.n("This approval request is no longer active; the native turn was interrupted.","APPROVAL_EXPIRED")}async abort(e){if(!e)return;let t=this.state.activeRun(e);await this.runtime.abort(e),t&&setTimeout(()=>{let e=this.state.appendTerminal(t.runId,{type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Native turn was interrupted before the runtime confirmed completion."});e&&this.broadcast(e)},3e3).unref?.()}steer(e,t){return this.runtime.steer(e,t)}setPermissionMode(e,t){let s=this.state.activeRun(e),i=this.state.setPermissionMode(e,t),r={id:e,agentType:S(e).agentType,nativeSessionId:S(e).nativeSessionId,title:"Native session",cwd:"",created:new Date().toISOString(),updated:new Date().toISOString(),status:s?"running":"idle",occupancy:s?"owned-by-customer-agent":"available",sourceLabel:"Native runtime broker",canResume:!0,canDelete:!1,permissionMode:i};return this.state.applySummary(r)}handoff(e,t){return this.state.changeController(e,t)}async executeRun(e,t){let s=!1,i=!1;try{let r={permissionMode:e.permissionMode,brokerRunId:e.runId,...e.goalId?{goal:{id:e.goalId,objective:this.state.getGoalState(e.sessionId).active?.objective??e.input}}:{}};for await(let a of this.runtime.run(e.sessionId,e.input,t,void 0,void 0,r)){let t=this.state.appendEvent(e.runId,a);t&&this.broadcast(t),"error"===a.type&&"SESSION_OCCUPIED"===a.code&&this.state.recordExplicitExternalOwnership(e.sessionId),s||=O(a),i||="done"===a.type}if(s)i&&(this.pendingCreations.delete(e.sessionId),this.state.deletePendingSession(e.sessionId));else{let t=this.state.appendTerminal(e.runId,{type:"error",code:"NATIVE_PROTOCOL_ERROR",message:"Native runtime stopped without a terminal event."});t&&this.broadcast(t)}}catch(i){let t=i instanceof w.n&&"SESSION_OCCUPIED"===i.code,s=this.state.appendTerminal(e.runId,{type:"error",code:i instanceof w.n?i.code:"NATIVE_PROTOCOL_ERROR",message:i instanceof Error?i.message:"Native runtime failed"});s&&this.broadcast(s),t&&this.state.recordExplicitExternalOwnership(e.sessionId)}finally{if(e.goalId){let t=this.state.getSnapshot(e.sessionId).events,s=[...t].reverse().find(({event:e})=>O(e))?.event,i=s?.type==="done"?"completed":"failed",r=s?.type==="error"?s.message:void 0,a=this.state.finishGoal(e.sessionId,e.goalId,i,r).active;a&&!this.state.activeRun(e.sessionId)&&this.startGoal(a,e.controller)}else{let t=this.state.getGoalState(e.sessionId).active;t&&!this.state.activeRun(e.sessionId)&&this.startGoal(t,e.controller)}}}async startGoal(e,t){if(!this.state.activeRun(e.sessionId))try{return await this.startRun(e.sessionId,e.objective,void 0,t,e.id)}catch(i){let s=this.state.finishGoal(e.sessionId,e.id,"failed",i instanceof Error?i.message:String(i));s.active&&this.startGoal(s.active,t);return}}handleApprovalResolved(e){let t=this.state.resolveApproval(e);t&&this.broadcast(t)}mergePending(e,t,s=()=>!0){let i=new Set(e.map(e=>e.id)),r=[...e.map(e=>{let t=this.pendingCreations.get(e.id);return t&&("claude-code"!==e.agentType||"Claude Code SDK"!==e.sourceLabel)&&(this.pendingCreations.delete(e.id),this.state.deletePendingSession(e.id)),t?{...e,cwd:e.cwd||t.cwd,projectId:e.projectId??t.projectId}:e}),...[...this.pendingCreations.values()].filter(e=>!i.has(e.id)&&s(e))].sort((e,t)=>t.updated.localeCompare(e.updated));return void 0===t?r:r.filter(e=>e.projectId===t)}handleSocket(e){let t="";e.setEncoding("utf8"),e.on("data",s=>{let i=(t+=s).indexOf("\n");for(;i>=0;){let s=t.slice(0,i).trim();t=t.slice(i+1),s&&this.handleSocketLine(e,s),i=t.indexOf("\n")}}),e.on("close",()=>this.subscribers.delete(e)),e.on("error",()=>this.subscribers.delete(e))}handleSocketLine(e,t){let s;try{s=JSON.parse(t)}catch{e.end();return}if(!s.id||!s.method||!s.params||"object"!=typeof s.params){this.write(e,{id:s.id||"",ok:!1,error:{message:"Invalid broker request"}}),e.end();return}if("subscribe"===s.method){let t=A(s.params,"sessionId"),i=C(s.params,"afterSequence")??0;if(!t){this.write(e,{id:s.id,ok:!1,error:{message:"sessionId is required"}}),e.end();return}let r=this.state.getSnapshot(t,i);for(let i of(this.subscribers.set(e,{sessionId:t,runId:r.runId,afterSequence:r.snapshotRevision}),this.write(e,{id:s.id,ok:!0,result:{snapshotRevision:r.snapshotRevision}}),r.events))this.write(e,{type:"event",event:i});return}this.handleRequest(s).then(t=>{this.write(e,{id:s.id,ok:!0,result:t}),e.end()},t=>{this.write(e,{id:s.id,ok:!1,error:{message:t instanceof Error?t.message:String(t),...t instanceof w.n?{code:t.code}:{}}}),e.end()})}async handleRequest(e){var t,s,i;let r=A(e.params,"sessionId");switch(e.method){case"ping":return{ok:!0};case"health":return this.health();case"listWorkspaces":return this.listWorkspaces(P(e.params,"agentType"),(t=e.params,{cursor:A(t,"cursor"),limit:C(t,"limit")??void 0,refresh:!0===t.refresh,since:A(t,"since")}));case"importWorkspace":return this.importWorkspace(P(e.params,"agentType"),k(e.params,"path"),A(e.params,"name")||void 0);case"listWorkspaceSessions":return this.listWorkspaceSessions(P(e.params,"agentType"),k(e.params,"workspaceId"),(s=e.params,{cursor:A(s,"cursor"),limit:C(s,"limit")??void 0,refresh:!0===s.refresh}));case"list":return this.list(A(e.params,"projectId")||void 0);case"refresh":return this.refresh(A(e.params,"projectId")||void 0);case"create":return this.create({agentType:P(e.params,"agentType"),title:A(e.params,"title")||"New session",cwd:A(e.params,"cwd")||"",...A(e.params,"projectId")?{projectId:A(e.params,"projectId")}:{}});case"fork":return this.fork(N(r));case"delete":return this.delete(N(r));case"get":return this.get(N(r),function(e){let t=A(e,"before")||void 0,s=C(e,"limit")??void 0;return t||void 0!==s?{before:t,limit:s}:void 0}(e.params));case"watchPath":return this.getSessionWatchPath(N(r));case"startRun":return this.startRun(N(r),A(e.params,"input")||"",x(e.params.images),L(e.params.controller));case"snapshot":return this.snapshot(N(r),C(e.params,"afterSequence")??0);case"getGoals":return this.getGoals(N(r),L(e.params.controller));case"enqueueGoal":return this.enqueueGoal(N(r),A(e.params,"objective")||"",A(e.params,"sourceMessageId")||void 0,L(e.params.controller));case"reorderGoals":return this.reorderGoals(N(r),x(e.params.orderedIds)??[]);case"cancelGoal":return this.cancelGoal(N(r),A(e.params,"goalId")||"",L(e.params.controller));case"answer":return this.answerQuestion(A(e.params,"questionId")||"",{answer:A(e.params,"answer")||"",selectedIndices:(i=e.params.selectedIndices,Array.isArray(i)&&i.every(e=>"number"==typeof e)?i:void 0)});case"abort":return this.abort(r||void 0);case"steer":return this.steer(N(r),A(e.params,"input")||"");case"setPermissionMode":return this.setPermissionMode(N(r),(0,d.Ny)(e.params.permissionMode));case"handoff":return this.handoff(N(r),L(e.params.controller));default:throw new w.n(`Unsupported broker method: ${e.method}`,"OPERATION_NOT_SUPPORTED")}}broadcast(e){let t=this.state.sessionIdForRun(e.runId);if(t){for(let[s,i]of this.subscribers)i.sessionId===t&&(i.runId!==e.runId&&(i.runId=e.runId,i.afterSequence=0),e.sequence<=i.afterSequence||(i.afterSequence=e.sequence,this.write(s,{type:"event",event:e})));for(let s of this.localSubscribers)s.sessionId===t&&(s.runId!==e.runId&&(s.runId=e.runId,s.afterSequence=0),e.sequence<=s.afterSequence||(s.afterSequence=e.sequence,s.listener(e)))}}write(e,t){!e.destroyed&&e.writable&&e.write(`${JSON.stringify(t)}
174
+ `)}}class W{constructor(e={}){this.options=e,this.ensurePromise=null}get directory(){return this.options.directory||process.env.AGENT_NATIVE_RUNTIME_DIR?.trim()||(0,l.join)((0,o.homedir)(),".agentroam","native-runtime")}async health(){return this.request("health",{})}async list(e){return this.request("list",e?{projectId:e}:{})}listWorkspaces(e,t={}){return this.request("listWorkspaces",{agentType:e,...t})}importWorkspace(e,t,s){return this.request("importWorkspace",{agentType:e,path:t,...s?{name:s}:{}})}listWorkspaceSessions(e,t,s={}){return this.request("listWorkspaceSessions",{agentType:e,workspaceId:t,...s})}async refresh(e){return this.request("refresh",e?{projectId:e}:{})}async create(e){return this.request("create",{...e})}async fork(e){return this.request("fork",{sessionId:e})}async delete(e){await this.request("delete",{sessionId:e})}async get(e,t){return this.request("get",{sessionId:e,...t??{}})}async getSessionWatchPath(e){return this.request("watchPath",{sessionId:e})}async startRun(e,t,s,i="web"){return this.request("startRun",{sessionId:e,input:t,images:s,controller:i})}async *run(e,t,s,i,r,a="desktop"){let n=await this.startRun(e,t,s,a);yield{type:"run_admitted",_nativeRunId:n.runId,_nativeSequence:0};let o=new u.K,l=await this.subscribe(e,0,e=>{e.runId===n.runId&&(o.push({...e.event,_nativeRunId:e.runId,_nativeSequence:e.sequence}),O(e.event)&&o.close())});try{for await(let e of o)yield e}finally{l()}}async subscribe(e,t,s){await this.ensureHost();let i=await D((0,l.join)(this.directory,q)),a=(0,r.randomUUID)(),n=!1,o="",d=new Promise((e,t)=>{let r=s=>{n||(n=!0,s?t(s):e())};i.setEncoding("utf8"),i.on("data",e=>{let t=(o+=e).indexOf("\n");for(;t>=0;){let e=o.slice(0,t).trim();if(o=o.slice(t+1),e)try{let t=JSON.parse(e);"id"in t&&t.id===a?t.ok?r():r(R(t.error)):"type"in t&&"event"===t.type&&t.event&&s(t.event)}catch{r(new w.n("Malformed broker response","NATIVE_PROTOCOL_ERROR"))}t=o.indexOf("\n")}}),i.once("error",e=>r(e)),i.once("close",()=>{n||r(new w.n("Native runtime broker disconnected","RUNTIME_UNAVAILABLE"))})});return i.write(`${JSON.stringify({id:a,method:"subscribe",params:{sessionId:e,afterSequence:t}})}
175
+ `),await d,()=>i.end()}async snapshot(e,t=0){return this.request("snapshot",{sessionId:e,afterSequence:t})}async getGoals(e,t="web"){return this.request("getGoals",{sessionId:e,controller:t})}async enqueueGoal(e,t,s,i="web"){return this.request("enqueueGoal",{sessionId:e,objective:t,sourceMessageId:s,controller:i})}async reorderGoals(e,t){return this.request("reorderGoals",{sessionId:e,orderedIds:[...t]})}async cancelGoal(e,t,s="web"){return this.request("cancelGoal",{sessionId:e,goalId:t,controller:s})}async answerQuestion(e,t){return this.request("answer",{questionId:e,answer:t.answer,selectedIndices:t.selectedIndices})}async abort(e){await this.request("abort",e?{sessionId:e}:{})}async steer(e,t){return this.request("steer",{sessionId:e,input:t})}async setPermissionMode(e,t){return this.request("setPermissionMode",{sessionId:e,permissionMode:t})}async handoff(e,t){return this.request("handoff",{sessionId:e,controller:t})}async request(e,t){return await this.ensureHost(),this.requestRaw(e,t)}async ensureHost(){return this.ensurePromise||(this.ensurePromise=(async()=>{try{await this.requestRaw("ping",{});return}catch{let e=this.options.runtimeFactory;if(!e)throw new w.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");let t=this.directory,s=(0,l.join)(t,q);if((0,a.existsSync)(s))try{await this.requestRaw("ping",{});return}catch{(0,a.rmSync)(s,{force:!0})}let i=function(){let e=globalThis;return e.__agentroamNativeRuntimeBrokerHosts||(e.__agentroamNativeRuntimeBrokerHosts=new Map),e.__agentroamNativeRuntimeBrokerHosts}(),r=i.get(t);if(!r){r=new U(t,e,this.options.now);try{await r.start(),i.set(t,r)}catch(e){if(await r.stop().catch(()=>void 0),!(e&&"object"==typeof e&&"EADDRINUSE"===e.code))throw e}}await this.requestRaw("ping",{})}})().finally(()=>{this.ensurePromise=null})),this.ensurePromise}async requestRaw(e,t){let s=await D((0,l.join)(this.directory,q)),i=(0,r.randomUUID)();return new Promise((r,a)=>{let n="",o=!1,l=(e,t)=>{o||(o=!0,s.destroy(),e?a(e):r(t))};s.setEncoding("utf8"),s.on("data",e=>{let t=(n+=e).indexOf("\n");if(t<0)return;let s=n.slice(0,t).trim();if(s)try{let e=JSON.parse(s);if(e.id!==i)return;e.ok?l(void 0,e.result):l(R(e.error))}catch{l(new w.n("Malformed broker response","NATIVE_PROTOCOL_ERROR"))}}),s.once("error",e=>l(e)),s.once("close",()=>{o||l(new w.n("Native runtime broker disconnected","RUNTIME_UNAVAILABLE"))}),s.write(`${JSON.stringify({id:i,method:e,params:t})}
176
+ `)})}}function I(e={}){return new W(e)}function E(e,t,s){let i=new h.b({executable:e||"codex"}),r=new y.O({executable:s||"opencode",unavailableError:process.env.AGENT_OPENCODE_RUNTIME_ERROR});return new v.V([new m.tX({client:i,codexExecutable:e||"codex",onApprovalResolved:t?.onApprovalResolved}),new p.IW,new f.nI({server:r,executable:s||"opencode",unavailableError:process.env.AGENT_OPENCODE_RUNTIME_ERROR,onApprovalResolved:t?.onApprovalResolved})],()=>Promise.resolve([]),t?.importedWorkspaceRepository)}function S(e){let t;try{t=(0,g.V)(e)}catch(t){if(t instanceof w.n)throw t;throw new w.n(`Invalid native session id: ${e}`,"INVALID_SESSION_ID")}if("customer-agent"===t.agentType)throw new w.n("Customer Agent sessions are not handled by the native broker","INVALID_SESSION_ID");return t}function b(e){return{sessionId:e.session_id,runId:e.run_id,agentType:e.agent_type,nativeSessionId:e.native_session_id,input:e.input,permissionMode:(0,d.Ny)(e.permission_mode),controller:e.controller,status:e.status,nextSequence:e.next_sequence,createdAt:e.created_at,terminalAt:e.terminal_at,goalId:e.goal_id??null}}function T(e){return{workspaceId:e.workspace_id,agentType:e.agent_type,normalizedPath:e.normalized_path,name:e.name,createdAt:e.created_at}}function O(e){return"done"===e.type||"error"===e.type}function R(e){let t=e?.code;return t&&["INVALID_SESSION_ID","SESSION_NOT_FOUND","SESSION_OCCUPIED","RUNTIME_UNAVAILABLE","OPERATION_NOT_SUPPORTED","APPROVAL_EXPIRED","NATIVE_PROTOCOL_ERROR"].includes(t)?new w.n(e?.message||"Native runtime broker failed",t):new w.n(e?.message||"Native runtime broker failed","NATIVE_PROTOCOL_ERROR")}function N(e){if(!e)throw new w.n("sessionId is required","INVALID_SESSION_ID");return e}function A(e,t){return"string"==typeof e[t]?e[t]:null}function k(e,t){let s=A(e,t);if(!s)throw new w.n(`${t} is required`,"INVALID_SESSION_ID");return s}function C(e,t){return"number"==typeof e[t]&&Number.isSafeInteger(e[t])?e[t]:null}function x(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)?e:void 0}function P(e,t){let s=A(e,t);if("codex"===s||"claude-code"===s||"opencode"===s)return s;throw new w.n("A native agent type is required","INVALID_SESSION_ID")}function L(e){return"desktop"===e||"web"===e?e:"web"}function D(e){return new Promise((t,s)=>{let i=(0,n.createConnection)(e),r=setTimeout(()=>{i.destroy(),s(new w.n("Timed out connecting to native runtime broker","RUNTIME_UNAVAILABLE"))},2e3);i.once("connect",()=>{clearTimeout(r),i.removeListener("error",a),t(i)});let a=e=>{clearTimeout(r),s(e)};i.once("error",a)})}i()}catch(e){i(e)}})},8733:(e,t,s)=>{s.d(t,{nI:()=>w});var i=s(7718),r=s(6005),a=s(7561),n=s(612),o=s(9411),l=s(5881),d=s(1322),u=s(8224),c=s(9956),p=s(2815),h=s(5779),m=s(2557),f=s(132);let y=(0,l.promisify)(i.execFile),g="1.18.27";class w{constructor(e={}){this.agentType="opencode",this.activeRuns=new Map,this.ownedSessions=new Set,this.sessionDirectories=new Map,this.pendingPermissions=new Map,this.workspaces=new Map,this.unsubscribe=null,this.availabilityPromise=null,this.executable=e.executable?.trim()||"opencode",this.unavailableError=e.unavailableError?.trim()||void 0,this.validateExecutable=void 0===e.server,this.onApprovalResolved=e.onApprovalResolved,this.dataRoot=e.dataRoot??function(e=process.env){let t=e.XDG_DATA_HOME?.trim();return t?(0,o.resolve)(t,"opencode"):"win32"===process.platform&&e.LOCALAPPDATA?.trim()?(0,o.resolve)(e.LOCALAPPDATA,"opencode"):(0,o.join)((0,n.homedir)(),".local","share","opencode")}(e.environment),this.server=e.server??new p.O({executable:this.executable,unavailableError:this.unavailableError,environment:e.environment})}async health(){if(this.unavailableError)return{agentType:this.agentType,available:!1,label:"OpenCode",error:this.unavailableError};try{let{stdout:e,stderr:t}=await y(this.executable,["--version"],{encoding:"utf8",timeout:5e3,windowsHide:!0});return{agentType:this.agentType,available:!0,label:"OpenCode",version:function(e,t){let s=e.match(/(?:^|\s)(\d+\.\d+\.\d+)(?:\s|$)/)?.[1];if(!s)throw Error(`Unable to parse OpenCode version from ${t}`);if(s!==g)throw Error(`OpenCode ${s} at ${t} is incompatible; AgentRoam requires ${g}`);return s}(`${e}
177
+ ${t}`,this.executable)}}catch(e){return{agentType:this.agentType,available:!1,label:"OpenCode",error:_(e)}}}async discoverSessions(){let e=await this.getClient(),t=[...new Set((await e.project.list({throwOnError:!0})).data.map(e=>e.worktree).filter(Boolean))],s=await Promise.all(t.map(async t=>{let[s,i]=await Promise.all([e.session.list({query:{directory:t},throwOnError:!0}).then(e=>e.data),e.session.status({query:{directory:t},throwOnError:!0}).then(e=>e.data)]);return s.map(e=>({session:e,status:i[e.id]}))})),i=new Map;for(let{session:e,status:t}of s.flat())this.sessionDirectories.set(e.id,e.directory),i.set(e.id,v(e,t,this.ownedSessions.has(e.id)));return[...i.values()].sort((e,t)=>t.updated.localeCompare(e.updated))}async listWorkspaces(e={}){let t=await this.getClient(),s=(await t.project.list({throwOnError:!0})).data,i=s.map((e,t)=>{let s={agentType:this.agentType,workspaceId:e.id,name:e.name?.trim()||(0,o.basename)(e.worktree)||e.worktree,roots:[e.worktree],order:t,updatedAt:new Date(e.time.initialized??e.time.created).toISOString(),source:"native"};return this.workspaces.set(s.workspaceId,s),s});return(0,m.L)(i,e,String(Math.max(0,...s.map(e=>e.time.initialized??e.time.created))))}async listWorkspaceSessions(e,t={}){await this.getClient();let s=this.workspaces.get(e);s||(s=(await this.listWorkspaces({limit:200,refresh:!0})).data.find(t=>t.workspaceId===e));let i=s?.roots[0];if(!i)throw new f.n(`OpenCode workspace not found: ${e}`,"SESSION_NOT_FOUND");let r=await this.listWorkspaceSessionsByPath(i,t);return{...r,watermark:r.watermark??s?.updatedAt??null}}async listWorkspaceSessionsByPath(e,t={}){let s=await this.getClient(),[i,r]=await Promise.all([s.session.list({query:{directory:e},throwOnError:!0}).then(e=>e.data),s.session.status({query:{directory:e},throwOnError:!0}).then(e=>e.data)]),a=i.map(e=>(this.sessionDirectories.set(e.id,e.directory),v(e,r[e.id],this.ownedSessions.has(e.id))));return(0,m.L)(a,t,a[0]?.updated??null)}async getSession(e){let t=await this.getClient(),s=await this.resolveDirectory(e);try{let[i,r,a]=await Promise.all([t.session.get({path:{id:e},query:{directory:s},throwOnError:!0}).then(e=>e.data),t.session.messages({path:{id:e},query:{directory:s},throwOnError:!0}).then(e=>e.data),t.session.status({query:{directory:s},throwOnError:!0}).then(e=>e.data)]);return this.sessionDirectories.set(i.id,i.directory),{...v(i,a[i.id],this.ownedSessions.has(i.id)),messages:function(e){let t=[];for(let s of e){let e=s.parts.filter(e=>"text"===e.type&&!e.ignored).map(e=>e.text).join(""),i=s.parts.filter(e=>"file"===e.type).filter(e=>e.mime.startsWith("image/")),r=i.map(e=>({type:"image",name:e.filename||"image",dataUrl:e.mime.startsWith("image/")&&e.url.startsWith("data:")?e.url:void 0,unavailable:!e.url.startsWith("data:")})),a=s.parts.filter(e=>"reasoning"===e.type).map((e,t)=>({itemId:e.id,sectionIndex:t,text:e.text})),n=s.parts.filter(e=>"tool"===e.type),o={role:s.info.role,content:e,...i.filter(e=>e.url.startsWith("data:")).length>0?{images:i.filter(e=>e.url.startsWith("data:")).map(e=>e.url)}:{},...r.length>0||a.length>0?{presentation:{attachments:r.length?r:void 0,reasoning:a.length?a:void 0}}:{},...n.length>0?{toolCalls:n.map(e=>({id:e.callID,name:e.tool,arguments:e.state.input}))}:{}};for(let e of((o.content||o.images?.length||o.toolCalls?.length||a.length)&&t.push(o),n))("completed"===e.state.status||"error"===e.state.status)&&t.push({role:"tool",toolCallId:e.callID,content:"completed"===e.state.status?e.state.output:e.state.error})}return t}(r),events:[]}}catch(t){throw function(e,t){let s=_(e);return/not found|404/i.test(s)?new f.n(`OpenCode session not found: ${t}`,"SESSION_NOT_FOUND"):new f.n(s,"NATIVE_PROTOCOL_ERROR")}(t,e)}}async getSessionWatchPath(e){await this.resolveDirectory(e);let t=(0,o.join)(this.dataRoot,"opencode.db"),s=`${t}-wal`;return(0,a.existsSync)(s)?s:t}async create(e){let t=await this.getClient(),s=(await t.session.create({body:{title:e.title},query:{directory:e.cwd},throwOnError:!0})).data;return this.sessionDirectories.set(s.id,s.directory),v(s,{type:"idle"})}async fork(e){let t=await this.getClient(),s=await this.resolveDirectory(e),i=(await t.session.fork({path:{id:e},query:{directory:s},throwOnError:!0})).data;return this.sessionDirectories.set(i.id,i.directory),v(i,{type:"idle"})}async *run(e,t,s,i,a,n){if(this.activeRuns.has(e))throw new f.n("OpenCode session is already running","SESSION_OCCUPIED");let o=await this.getSession(e);if("owned-externally"===o.occupancy)throw new f.n("OpenCode session is open in another client","SESSION_OCCUPIED");let l=new u.K,p={queue:l,cwd:o.cwd,permissionMode:(0,d.Ny)(n?.permissionMode),brokerRunId:n?.brokerRunId,finalText:"",messageRoles:new Map,partText:new Map,toolStates:new Map};this.activeRuns.set(e,p),this.ownedSessions.add(e);try{let i=await this.getClient(),a=`msg_${(0,r.randomUUID)()}`;p.messageRoles.set(a,"user");let n=(0,c.u)(s).map((e,t)=>({type:"file",mime:e.mimeType,filename:`image-${t+1}.${e.extension}`,url:`data:${e.mimeType};base64,${e.base64}`}));for await(let s of(await i.session.promptAsync({path:{id:e},query:{directory:o.cwd},body:{messageID:a,parts:[{type:"text",text:t},...n]},throwOnError:!0}),l))yield s}catch(e){yield{type:"error",message:_(e),code:"NATIVE_PROTOCOL_ERROR"}}finally{for(let[t,s]of(this.activeRuns.delete(e),this.ownedSessions.delete(e),this.pendingPermissions))s.sessionId===e&&this.pendingPermissions.delete(t)}}async abort(e){let t=e?[e]:[...this.activeRuns.keys()],s=await this.getClient();await Promise.all(t.map(async e=>{let t=await this.resolveDirectory(e);await s.session.abort({path:{id:e},query:{directory:t},throwOnError:!0});let i=this.activeRuns.get(e);i&&(i.queue.push({type:"turn_aborted"}),i.queue.close())}))}async answerQuestion(e,t){let s=this.pendingPermissions.get(e);if(!s)return!1;this.pendingPermissions.delete(e);let i=function(e){let t=e.answer.trim();return"本会话允许"===t||"always"===t||e.selectedIndices?.[0]===1?"always":"允许一次"===t||"once"===t||e.selectedIndices?.[0]===0?"once":"reject"}(t),r=await this.getClient();return await r.postSessionIdPermissionsPermissionId({path:{id:s.sessionId,permissionID:s.permissionId},query:{directory:s.directory},body:{response:i},throwOnError:!0}),this.onApprovalResolved?.(e),!0}async dispose(){this.unsubscribe?.(),this.unsubscribe=null,await this.server.dispose()}async getClient(){return this.validateExecutable&&(this.availabilityPromise??=this.ensureCompatibleExecutable(),await this.availabilityPromise),this.unsubscribe||(this.unsubscribe=this.server.subscribe(e=>this.handleEvent(e),e=>this.handleFailure(e))),this.server.client()}async ensureCompatibleExecutable(){let e=await this.health();if(!e.available)throw new f.n(e.error||"OpenCode runtime is unavailable","RUNTIME_UNAVAILABLE")}async resolveDirectory(e){let t=this.sessionDirectories.get(e);if(t)return t;let s=(await this.discoverSessions()).find(t=>t.nativeSessionId===e);if(!s)throw new f.n(`OpenCode session not found: ${e}`,"SESSION_NOT_FOUND");return s.cwd}handleEvent({directory:e,payload:t}){let s=function(e){if("message.updated"===e.type)return e.properties.info.sessionID;if("message.part.updated"===e.type)return e.properties.part.sessionID;let t=e.properties;return"string"==typeof t.sessionID?t.sessionID:"string"==typeof t.info?.id&&e.type.startsWith("session.")?t.info.id:void 0}(t);if(!s)return;this.sessionDirectories.set(s,e);let i=this.activeRuns.get(s);if(i){if("message.updated"===t.type){i.messageRoles.set(t.properties.info.id,t.properties.info.role);let e="assistant"===t.properties.info.role?t.properties.info.error:void 0;e&&this.failRun(s,_(e));return}if("message.part.updated"===t.type){this.handlePart(i,t.properties.part,t.properties.delta);return}if("todo.updated"===t.type){i.queue.push({type:"todo_update",todos:t.properties.todos.map(e=>({id:e.id,title:e.content,status:"in_progress"===e.status?"in-progress":"completed"===e.status?"completed":"pending"}))});return}if("permission.updated"===t.type){this.handlePermission(i,e,t.properties);return}if("permission.replied"===t.type){let e=[...this.pendingPermissions.values()].find(e=>e.permissionId===t.properties.permissionID);e&&(this.pendingPermissions.delete(e.questionId),this.onApprovalResolved?.(e.questionId));return}if("session.status"===t.type&&"retry"===t.properties.status.type){i.queue.push({type:"runtime_progress",progressId:"opencode:retry",phase:"retry",label:`OpenCode retry ${t.properties.status.attempt}`,detail:t.properties.status.message});return}if("session.idle"===t.type||"session.status"===t.type&&"idle"===t.properties.status.type){i.queue.push({type:"text_done"}),i.queue.push({type:"done",finalText:i.finalText}),i.queue.close();return}"session.error"===t.type&&this.failRun(s,_(t.properties.error??"OpenCode session failed"))}}handlePart(e,t,s){if("text"===t.type){if("user"===e.messageRoles.get(t.messageID))return;let i=e.partText.get(t.id)??"",r=s??(t.text.startsWith(i)?t.text.slice(i.length):t.text);e.partText.set(t.id,t.text),r&&(e.finalText+=r,e.queue.push({type:"text_chunk",text:r}));return}if("reasoning"===t.type){let i=e.partText.get(t.id)??"",r=s??(t.text.startsWith(i)?t.text.slice(i.length):t.text);e.partText.set(t.id,t.text),r&&e.queue.push({type:"reasoning_summary_delta",itemId:t.id,sectionIndex:0,delta:r});return}if("retry"===t.type){e.queue.push({type:"runtime_progress",progressId:`opencode:retry:${t.id}`,phase:"retry",label:`OpenCode retry ${t.attempt}`,detail:_(t.error)});return}if("tool"!==t.type)return;let i=e.toolStates.get(t.callID),r=t.state.status;e.toolStates.set(t.callID,r),void 0===i&&e.queue.push({type:"tool_call",toolCall:{id:t.callID,name:t.tool,arguments:t.state.input}}),"running"===r&&e.queue.push({type:"runtime_progress",progressId:`opencode:tool:${t.callID}`,phase:"tool",label:t.state.title||t.tool,toolCallId:t.callID}),("completed"===r||"error"===r)&&i!==r&&e.queue.push({type:"tool_result",result:{toolCallId:t.callID,content:"completed"===r?t.state.output:t.state.error,isError:"error"===r||void 0,metadata:t.state.metadata}})}async handlePermission(e,t,s){let i=function(e){let t=Array.isArray(e.pattern)?e.pattern.join(" "):e.pattern;return{name:({read:"read_file",list:"list_files",glob:"list_files",grep:"search_files",edit:"apply_patch",write:"write_file",patch:"apply_patch",bash:"bash",webfetch:"web_fetch",websearch:"web_search",task:"dispatch_agent",todowrite:"todo_write"})[e.type.toLowerCase()]??e.type,arguments:{...e.metadata,..."bash"===e.type.toLowerCase()&&t?{command:t}:{},...t?{pattern:t}:{}}}}(s),r=(0,d.Cr)(i.name,i.arguments,e.cwd);if("full-access"===e.permissionMode||"auto-approval"===e.permissionMode&&("safe"===r.kind||"workspace-write"===r.kind)){let e=await this.getClient();await e.postSessionIdPermissionsPermissionId({path:{id:s.sessionID,permissionID:s.id},query:{directory:t},body:{response:"once"},throwOnError:!0}).catch(e=>this.failRun(s.sessionID,_(e)));return}let a=e.brokerRunId?`native:${e.brokerRunId}:${s.id}`:`opencode:${s.sessionID}:${s.id}`;this.pendingPermissions.set(a,{questionId:a,sessionId:s.sessionID,directory:t,permissionId:s.id}),e.queue.push({type:"ask_user",questionId:a,question:s.title||r.summary,options:[{label:"允许一次",description:r.reason},{label:"本会话允许",description:"Allow matching OpenCode operations for this session"},{label:"拒绝",description:"Decline this operation"}]})}failRun(e,t){let s=this.activeRuns.get(e);s&&(s.queue.push({type:"error",message:t,code:"NATIVE_PROTOCOL_ERROR"}),s.queue.close())}handleFailure(e){for(let t of this.activeRuns.keys())this.failRun(t,e.message)}}function v(e,t,s=!1){let i=t?.type==="busy"||t?.type==="retry",r=i&&!s,a=e.model?.id?`${e.model.providerID?`${e.model.providerID}/`:""}${e.model.id}`:void 0,n=[e.agent,a].filter(Boolean).join(" \xb7 ");return{id:(0,h.F)("opencode",e.id),agentType:"opencode",nativeSessionId:e.id,title:e.title||"OpenCode session",cwd:e.directory,parentSessionId:e.parentID?(0,h.F)("opencode",e.parentID):void 0,created:new Date(e.time.created).toISOString(),updated:new Date(e.time.updated).toISOString(),status:i?"running":"idle",occupancy:r?"owned-externally":s?"owned-by-customer-agent":"available",sourceLabel:n?`OpenCode \xb7 ${n}`:"OpenCode",canResume:!r,canDelete:!1}}function _(e){if(e instanceof Error)return e.message;if(e&&"object"==typeof e){let t=e.data;if("string"==typeof t?.message)return t.message;if("string"==typeof e.message)return e.message}return String(e)}},2815:(e,t,s)=>{s.d(t,{O:()=>o});var i=s(7718),r=s(7503),a=s(6244),n=s(132);class o{constructor(e={}){this.startPromise=null,this.process=null,this.eventAbort=null,this.listeners=new Set,this.failureListeners=new Set,this.disposed=!1,this.executable=e.executable?.trim()||"opencode",this.unavailableError=e.unavailableError?.trim()||void 0,this.environment=e.environment??process.env}async client(){if(this.disposed)throw new n.n("OpenCode runtime has been disposed","RUNTIME_UNAVAILABLE");if(this.unavailableError)throw new n.n(this.unavailableError,"RUNTIME_UNAVAILABLE");return this.startPromise??=this.start(),this.startPromise}subscribe(e,t){return this.listeners.add(e),t&&this.failureListeners.add(t),this.client().catch(e=>this.notifyFailure(u(e))),()=>{this.listeners.delete(e),t&&this.failureListeners.delete(t)}}async dispose(){this.disposed=!0,this.eventAbort?.abort(),this.eventAbort=null;let e=this.process;if(this.process=null,this.startPromise=null,!e||null!==e.exitCode)return;let t=new Promise(t=>e.once("exit",()=>t()));e.kill("SIGTERM");let s=setTimeout(()=>{null===e.exitCode&&e.kill("SIGKILL")},2e3);s.unref(),await t,clearTimeout(s)}async start(){let e=await l(),t=`http://127.0.0.1:${e}`,s=(0,i.spawn)(this.executable,["serve","--hostname=127.0.0.1",`--port=${e}`],{env:{...this.environment,OPENCODE_CONFIG_CONTENT:function(e){let t={};try{let s=e?JSON.parse(e):{};s&&"object"==typeof s&&!Array.isArray(s)&&(t=s)}catch{}let s=t.permission&&"object"==typeof t.permission&&!Array.isArray(t.permission)?t.permission:{};return JSON.stringify({...t,permission:{"*":"ask",...s}})}(this.environment.OPENCODE_CONFIG_CONTENT)},stdio:["ignore","pipe","pipe"],windowsHide:!0});this.process=s;let r="",n=null,o=e=>{r=`${r}${e.toString("utf8")}`.slice(-8e3)};s.stdout?.on("data",o),s.stderr?.on("data",o),s.once("error",e=>{n=e});try{await d(t,s,()=>r,()=>n)}catch(e){throw null===s.exitCode&&s.kill("SIGTERM"),this.process=null,this.startPromise=null,e}let u=(0,a.dF)({baseUrl:t,throwOnError:!0});return s.once("exit",(e,t)=>{this.process!==s||this.disposed||(this.process=null,this.startPromise=null,this.eventAbort?.abort(),this.eventAbort=null,this.notifyFailure(Error(`OpenCode server exited${null===e?"":` with code ${e}`}${t?` (${t})`:""}`)))}),this.startEventStream(u),u}startEventStream(e){let t=new AbortController;this.eventAbort=t,e.global.event({signal:t.signal}).then(async({stream:e})=>{for await(let s of e){if(t.signal.aborted)break;for(let e of this.listeners)e(s)}t.signal.aborted||this.notifyFailure(Error("OpenCode event stream ended unexpectedly"))}).catch(e=>{t.signal.aborted||this.notifyFailure(u(e))})}notifyFailure(e){for(let t of this.failureListeners)t(e)}}async function l(){return new Promise((e,t)=>{let s=(0,r.createServer)();s.unref(),s.once("error",t),s.listen(0,"127.0.0.1",()=>{let i=s.address();if(!i||"string"==typeof i){s.close(),t(Error("Unable to reserve a port for OpenCode"));return}s.close(s=>s?t(s):e(i.port))})})}async function d(e,t,s,i){let r=Date.now()+1e4;for(;Date.now()<r;){if(i())throw i();if(null!==t.exitCode)throw Error(`OpenCode server exited with code ${t.exitCode}: ${s().trim()}`);try{if((await fetch(`${e}/global/health`,{signal:AbortSignal.timeout(1e3)})).ok)return}catch{}await new Promise(e=>setTimeout(e,100))}throw Error(`Timed out starting OpenCode server: ${s().trim()}`)}function u(e){return e instanceof Error?e:Error(String(e))}},5779:(e,t,s)=>{s.d(t,{F:()=>n,V:()=>o});var i=s(132);let r="runtime:",a=new Set(["customer-agent","codex","claude-code","opencode"]);function n(e,t){if(!t)throw new i.n("Native session ID is required","INVALID_SESSION_ID");let s=Buffer.from(t,"utf8").toString("base64url");return`${r}${e}:${s}`}function o(e){if(!e)throw new i.n("Session ID is required","INVALID_SESSION_ID");if(!e.startsWith(r))return{agentType:"customer-agent",nativeSessionId:e};let t=/^runtime:([^:]+):([A-Za-z0-9_-]+)$/.exec(e);if(!t||!a.has(t[1]))throw new i.n(`Invalid unified session ID: ${e}`,"INVALID_SESSION_ID");let s=t[2],n=Buffer.from(s,"base64url").toString("utf8");if(!n||Buffer.from(n,"utf8").toString("base64url")!==s)throw new i.n(`Invalid unified session ID: ${e}`,"INVALID_SESSION_ID");return{agentType:t[1],nativeSessionId:n}}},132:(e,t,s)=>{s.d(t,{n:()=>i});class i extends Error{constructor(e,t){super(e),this.code=t,this.name="RuntimeSessionError"}}},2428:(e,t,s)=>{s.d(t,{V:()=>l});var i=s(9411),r=s(1322),a=s(5779),n=s(2557),o=s(132);class l{constructor(e,t,s){for(let s of(this.listProjects=t,this.adapters=new Map,this.activeSessionIds=new Set,this.healthCache=[],this.discoveryPromise=null,this.detailCache=new Map,e))this.adapters.set(s.agentType,s);this.workspaceIndex=new n.Vk(e,s)}listWorkspaces(e,t){return this.workspaceIndex.listWorkspaces(e,t)}listWorkspaceSessions(e,t,s){return this.workspaceIndex.listWorkspaceSessions(e,t,s)}importWorkspace(e,t,s){return this.workspaceIndex.importWorkspace(e,t,s)}async health(){let e=await Promise.all([...this.adapters.values()].map(async e=>{try{return await e.health()}catch(t){return{agentType:e.agentType,available:!1,label:e.agentType,error:t instanceof Error?t.message:String(t)}}}));return this.healthCache=e,e}getCachedHealth(){return this.healthCache}async list(e){return(await this.discoverAll()).filter(t=>void 0===e||t.projectId===e)}async refresh(e){return this.discoveryPromise=null,this.detailCache.clear(),this.list(e)}invalidate(e){this.detailCache.delete(e),this.discoveryPromise=null;let t=(0,a.V)(e);this.workspaceIndex.invalidate(t.agentType)}async discoverAll(){return this.discoveryPromise||(this.discoveryPromise=this.performDiscovery().catch(e=>{throw this.discoveryPromise=null,e})),this.discoveryPromise}async performDiscovery(){let e=await this.listProjects();return(await Promise.all([...this.adapters.values()].map(async t=>{try{return(await t.discoverSessions()).map(t=>d(t,e))}catch(e){return this.recordFailure(t.agentType,e),[]}}))).flat().sort((e,t)=>t.updated.localeCompare(e.updated))}async listChildren(e){return(await this.list()).filter(t=>t.parentSessionId===e)}async get(e,t){let s=await this.getUnpaginated(e,!!t?.before);return t?{...s,...(0,r.MO)(s.messages,s.events,t)}:s}async getUnpaginated(e,t=!1){let{adapter:s,nativeSessionId:i}=this.resolveAdapter(e),r=(t?this.detailCache.get(e):void 0)??await s.getSession(i);return this.cacheDetail(e,r),d(r,await this.listProjects())}async getSessionWatchPath(e){let{adapter:t,nativeSessionId:s}=this.resolveAdapter(e);return t.getSessionWatchPath?.(s)??null}async create(e){let t=this.adapters.get(e.agentType);if(!t)throw new o.n(`Runtime is unavailable: ${e.agentType}`,"RUNTIME_UNAVAILABLE");if("customer-agent"!==e.agentType&&!e.cwd)throw new o.n("A project working directory is required","INVALID_SESSION_ID");let s=await t.create(e);return this.discoveryPromise=null,s}restoreDrafts(e){for(let t of e)this.adapters.get(t.agentType)?.restoreDraft?.(t);this.discoveryPromise=null}async fork(e){let{adapter:t,nativeSessionId:s}=this.resolveAdapter(e);if(!t.fork)throw new o.n("This runtime does not support session forks","OPERATION_NOT_SUPPORTED");let i=await t.fork(s);return this.discoveryPromise=null,i}async *run(e,t,s,i,r,a){let{adapter:n,nativeSessionId:l}=this.resolveAdapter(e),d=await n.getSession(l);if(!d.canResume||"owned-externally"===d.occupancy)throw new o.n("Session is currently owned by another client","SESSION_OCCUPIED");if(this.activeSessionIds.has(e))throw new o.n("Session is already running","SESSION_OCCUPIED");this.activeSessionIds.add(e),this.detailCache.delete(e);try{yield*void 0===a?n.run(l,t,s,i,r):n.run(l,t,s,i,r,a)}finally{this.activeSessionIds.delete(e),this.detailCache.delete(e),this.discoveryPromise=null}}async abort(e){if(e){let{adapter:t,nativeSessionId:s}=this.resolveAdapter(e);await t.abort(s);return}await Promise.allSettled([...this.adapters.values()].map(e=>e.abort("")))}async steer(e,t){let{adapter:s,nativeSessionId:i}=this.resolveAdapter(e);if(!s.steer)throw new o.n("This runtime does not support mid-turn steering","OPERATION_NOT_SUPPORTED");return!!this.activeSessionIds.has(e)&&s.steer(i,t)}async answerQuestion(e,t){for(let s of this.adapters.values())if(await s.answerQuestion(e,t))return!0;return!1}async delete(e){let{adapter:t,nativeSessionId:s}=this.resolveAdapter(e);if(this.activeSessionIds.has(e))throw new o.n("Session is currently running","SESSION_OCCUPIED");if(!t.delete)throw new o.n("This session cannot be deleted","OPERATION_NOT_SUPPORTED");await t.delete(s),this.detailCache.delete(e),this.discoveryPromise=null}async dispose(){await Promise.allSettled([...this.adapters.values()].map(e=>e.dispose?.()))}agentTypeFor(e){return(0,a.V)(e).agentType}resolveAdapter(e){let t=(0,a.V)(e),s=this.adapters.get(t.agentType);if(!s)throw new o.n(`Runtime is unavailable: ${t.agentType}`,"RUNTIME_UNAVAILABLE");return{adapter:s,nativeSessionId:t.nativeSessionId}}recordFailure(e,t){let s=this.healthCache.find(t=>t.agentType===e),i={agentType:e,available:!1,label:s?.label??e,error:t instanceof Error?t.message:String(t)};this.healthCache=[...this.healthCache.filter(t=>t.agentType!==e),i]}cacheDetail(e,t){for(this.detailCache.delete(e),this.detailCache.set(e,t);this.detailCache.size>3;){let e=this.detailCache.keys().next().value;if(!e)break;this.detailCache.delete(e)}}}function d(e,t){if(e.projectId||!e.cwd)return e;let s=(0,i.resolve)(e.cwd),r=t.filter(e=>e.description).map(e=>({project:e,path:(0,i.resolve)(e.description)})).filter(({path:e})=>s===e||s.startsWith(`${e}${i.sep}`)).sort((e,t)=>t.path.length-e.path.length)[0];return r?{...e,projectId:r.project.id}:e}},2083:(e,t,s)=>{s.a(e,async(e,i)=>{try{s.d(t,{NL:()=>m,V_:()=>w,WW:()=>v});var r=s(7561),a=s(612),n=s(9411),o=s(1322),l=s(7578),d=s(5779),u=s(132),c=s(785),p=e([l]);l=(p.then?(await p)():p)[0];let _=globalThis;class I{constructor(e,t=async()=>[],s=process.platform){this.runtime=e,this.listProjects=t,this.platform=s,this.pendingCreations=new Map}health(){return this.runtime.health()}listWorkspaces(e,t){return this.runtime.listWorkspaces(e,t)}importWorkspace(e,t,s){if(!this.runtime.importWorkspace)throw new u.n("Native workspace import is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.importWorkspace(e,t,s)}async listWorkspaceSessions(e,t,s){let i=await this.runtime.listWorkspaceSessions(e,t,s);if(s?.cursor)return i;let r=new Set(i.data.map(e=>e.id)),a=i.data.map(e=>{let t=this.pendingCreations.get(e.id);return t?(this.pendingCreations.delete(e.id),h(e,t)):e});for(let s of this.pendingCreations.values())s.agentType!==e||s.projectId!==t||r.has(s.id)||a.unshift(s);return{...i,data:a}}async list(e){let[t,s]=await Promise.all([this.runtime.list(),this.listProjects()]);return g(this.withPendingCreations(t).map(e=>f(e,s,this.platform)),e)}async refresh(e){let[t,s]=await Promise.all([this.runtime.refresh(),this.listProjects()]);return g(this.withPendingCreations(t).map(e=>f(e,s,this.platform)),e)}async create(e){let t=f(await this.runtime.create(e),await this.listProjects(),this.platform),s=e.projectId?{...t,projectId:e.projectId}:t;return this.pendingCreations.set(s.id,s),s}async fork(e){if(!w(e))throw new u.n("Customer Agent sessions do not support native forks","OPERATION_NOT_SUPPORTED");let t=f(await this.runtime.fork(e),await this.listProjects(),this.platform);return this.pendingCreations.set(t.id,t),t}async delete(e){await this.runtime.delete(e),this.pendingCreations.delete(e)}async get(e,t){let s;try{s=await this.runtime.get(e,t)}catch(i){let s=this.pendingCreations.get(e);if(!s)throw i;return t?{...s,messages:[],events:[],history:{nextCursor:null,hasMore:!1,pageSize:0,totalItems:0}}:{...s,messages:[],events:[]}}return f(s,await this.listProjects(),this.platform)}getSessionWatchPath(e){return this.runtime.getSessionWatchPath(e)}run(e,t,s,i,r){return this.runtime.run(e,t,s,i,r)}steer(e,t){return this.runtime.steer(e,t)}abort(e){return this.runtime.abort(e)}answerQuestion(e,t){return this.runtime.answerQuestion(e,t)}async startRun(e,t,s,i="web"){if(!this.runtime.startRun)throw new u.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.startRun(e,t,s,i)}async subscribe(e,t,s){if(!this.runtime.subscribe)throw new u.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.subscribe(e,t,s)}async snapshot(e,t=0){if(!this.runtime.snapshot)throw new u.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.snapshot(e,t)}async setPermissionMode(e,t){if(!this.runtime.setPermissionMode)throw new u.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.setPermissionMode(e,t)}async handoff(e,t){if(!this.runtime.handoff)throw new u.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.handoff(e,t)}async getGoals(e,t="web"){if(!this.runtime.getGoals)throw new u.n("Goal mode is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.getGoals(e,t)}async enqueueGoal(e,t,s,i="web"){if(!this.runtime.enqueueGoal)throw new u.n("Goal mode is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.enqueueGoal(e,t,s,i)}async reorderGoals(e,t){if(!this.runtime.reorderGoals)throw new u.n("Goal mode is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.reorderGoals(e,t)}async cancelGoal(e,t){if(!this.runtime.cancelGoal)throw new u.n("Goal mode is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.cancelGoal(e,t,"web")}withPendingCreations(e){let t=new Set,s=e.map(e=>{t.add(e.id);let s=this.pendingCreations.get(e.id);return this.pendingCreations.delete(e.id),s?h(e,s):e});for(let e of this.pendingCreations.values())t.has(e.id)||s.push(e);return s.sort((e,t)=>t.updated.localeCompare(e.updated))}}function h(e,t){return{...e,cwd:e.cwd||t.cwd,projectId:e.projectId??t.projectId}}function m(){if(!_.__nativeRuntimeService){!function(){let e=[(0,n.join)((0,a.homedir)(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],t=(process.env.PATH??"").split(n.delimiter),s=e.filter(e=>(0,r.existsSync)(e)&&!t.includes(e));s.length>0&&(process.env.PATH=[...t,...s].join(n.delimiter))}();let e=new o.XW((0,c.kO)());_.__nativeRuntimeService=new I((0,l.v6)({runtimeFactory:e=>(0,l.WH)(process.env.AGENT_CODEX_BIN?.trim()||"codex",e,process.env.AGENT_OPENCODE_BIN?.trim()||"opencode")}),()=>e.list())}return _.__nativeRuntimeService}function f(e,t,s=process.platform){let{projectId:i,...r}=e;if(!e.cwd)return r;let a=y(e.cwd,s),o="win32"===s?n.win32.sep:n.sep,l=t.filter(e=>e.description).map(e=>({project:e,path:y(e.description,s)})).filter(({path:e})=>a===e||a.startsWith(`${e}${o}`)).sort((e,t)=>t.path.length-e.path.length)[0];return l?{...r,projectId:l.project.id}:r}function y(e,t=process.platform){if("win32"!==t)return(0,n.resolve)(e);let s=n.win32.resolve(e),i=n.win32.parse(s).root;return(s.length>i.length?s.replace(/[\\/]+$/,""):s).toLowerCase()}function g(e,t){return void 0===t?e:e.filter(e=>e.projectId===t)}function w(e){try{return"customer-agent"!==(0,d.V)(e).agentType}catch{return!1}}function v(e){if(e instanceof u.n)switch(e.code){case"SESSION_NOT_FOUND":return 404;case"SESSION_OCCUPIED":case"APPROVAL_EXPIRED":return 409;case"RUNTIME_UNAVAILABLE":return 503;case"OPERATION_NOT_SUPPORTED":return 405;default:return 400}return 500}i()}catch(e){i(e)}})},785:(e,t,s)=>{s.d(t,{kO:()=>a,sr:()=>n});var i=s(9411);let r=function(){let e=process.argv[1];if(e){let t=(0,i.dirname)((0,i.resolve)(e)),s=`${i.sep}node_modules${i.sep}.bin`;return t.endsWith(s)?(0,i.resolve)(t,"..",".."):t}return(0,i.resolve)(process.cwd())}();function a(){return function(e=process.env,t=r){return(0,i.resolve)(e.AGENT_DATA_DIR?.trim()||t)}()}function n(){return function(e=process.env,t=r){return(0,i.resolve)(e.AGENT_WORKING_DIRECTORY?.trim()||t)}(process.env,a())}}};
@@ -0,0 +1,3 @@
1
+ "use strict";exports.id=4214,exports.ids=[4214],exports.modules={7186:(e,t,s)=>{s.d(t,{B:()=>a,f:()=>u});var r=s(1322),i=s(612),o=s(785);let n={jpeg:"jpg",png:"png",gif:"gif",webp:"webp"};class a extends Error{constructor(e,t,s){super(e),this.code=t,this.status=s,this.name="ProjectWorkingDirectoryError"}}class c{constructor(){this.baseDir=(0,o.kO)(),this.workingDirectory=(0,o.sr)(),this.builder=null,this.sessionStore=new r.m6(this.baseDir),this.projectStore=new r.XW(this.baseDir),this.remoteToolStore=new r.rt((0,r.N8)(this.baseDir).db),this.defaultRemoteToolsProjectId=process.env.AGENT_PROJECT_ID??"default",this.activeRun=null,this.activeAgent=null,this.activeRunSessionId=null,this.subscribers=new Map,this.recentEvents=new Map,this.eventCounters=new Map,this.pendingQuestions=new Map,this.toolPermissionGate=new r.XP({resolveMode:async e=>{let t=await this.sessionStore.get(e);return(0,r.Ny)(t?.metadata.permissionMode)},requestApproval:async e=>{let t=await this.createQuestion({question:`Customer Agent 请求权限
2
+ ${e.summary}
3
+ 原因:${e.reason}`,options:[...r.Sf],toolCallId:""},e.sessionId);return(0,r.wM)(t.answer,t.selectedIndices)}});let e=process.env.AGENT_API_KEY,t=process.env.AGENT_MODEL_PROVIDER||"openai",s=process.env.AGENT_MODEL_ID||"gpt-4o",i=process.env.AGENT_BASE_URL||void 0,n=new r.Y4().withSessionStore(this.sessionStore).withWorkingDirectory(this.workingDirectory).withToolPermissionGate(this.toolPermissionGate);n.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e&&n.withModel(t,{apiKey:e,modelId:s,baseUrl:i}),this.builder=n}getBuilder(){return this.builder||(this.builder=new r.Y4().withToolPermissionGate(this.toolPermissionGate)),this.builder}setBuilder(e){e.withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId),e.withWorkingDirectory(this.workingDirectory),e.withToolPermissionGate(this.toolPermissionGate),this.builder=e}getSessionStore(){return this.sessionStore}isSessionRunning(e){return this.activeRunSessionId===e}hasActiveRun(){return null!==this.activeRunSessionId}getProjectStore(){return this.projectStore}async resolveProjectWorkingDirectory(e,t=!1){if(!e)return this.workingDirectory;let s=await this.projectStore.get(e);if(!s)throw new a("项目不存在","PROJECT_NOT_FOUND",404);if(!s.description?.trim()){if(!t)return this.workingDirectory;throw new a("该项目没有宿主机目录","PROJECT_PATH_REQUIRED",400)}try{return r.Tp.fromEnvironment(process.env.AGENT_WEB_ROOTS,(0,i.homedir)()).assertDirectory(s.description)}catch(e){throw new a(e instanceof Error?e.message:"项目目录不可用","PROJECT_PATH_INVALID",400)}}getModelConfig(){return{provider:process.env.AGENT_MODEL_PROVIDER||"openai",modelId:process.env.AGENT_MODEL_ID||"gpt-4o",baseUrl:process.env.AGENT_BASE_URL||""}}getWebAppBuildId(){return globalThis.__webAppBuildId??""}registerRemoteTools(e,t){return this.remoteToolStore.upsertTools(e,t)}getRemoteToolStore(){return this.remoteToolStore}async createSession(e,t=""){let s=new Date().toISOString();return t&&!await this.projectStore.get(t)&&await this.projectStore.create({id:t,name:t,description:"",created:s,updated:s}),this.sessionStore.create({id:crypto.randomUUID(),projectId:t,title:e,status:"idle",messages:[],events:[],created:s,updated:s,metadata:(0,r.Tu)(e,{permissionMode:"full-access"})})}async setSessionPermissionMode(e,t){if(!(0,r.ue)(t))throw Error(`Invalid permission mode: ${String(t)}`);let s=await this.sessionStore.get(e);if(!s)throw Error(`Session not found: ${e}`);return this.toolPermissionGate.clearSession(e),this.sessionStore.update(e,{metadata:{...s.metadata,permissionMode:t}})}getLatestEventId(e){return this.eventCounters.get(e)??0}subscribe(e,t,s=-1){for(let r of this.recentEvents.get(e)??[])if(!(r.id<=s))try{t(r.event,r.id)}catch{}let r=this.subscribers.get(e)??new Set;return r.add(t),this.subscribers.set(e,r),()=>{r.delete(t),0===r.size&&this.subscribers.delete(e)}}emit(e,t){let s=(this.eventCounters.get(e)??0)+1;this.eventCounters.set(e,s);let r=this.recentEvents.get(e);for(let i of(r&&(r.push({id:s,event:t}),r.length>500&&r.splice(0,r.length-500)),this.subscribers.get(e)??[]))try{i(t,s)}catch{}}publishExternal(e,t){this.emit(e,t)}resetExternalStream(e){this.eventCounters.set(e,0),this.recentEvents.set(e,[])}projectMessagesFromEvents(e){let t=[],s=null;for(let r of e){if("text_chunk"===r.type){s||(s={role:"assistant",content:""},t.push(s)),s.content+=r.text;continue}if("tool_call"===r.type){s&&!s.toolCalls?s.toolCalls=[r.toolCall]:t.push({role:"assistant",content:"",toolCalls:[r.toolCall]}),s=null;continue}if("tool_result"===r.type){t.push({role:"tool",content:r.result.content,toolCallId:r.result.toolCallId});continue}if("ask_user"===r.type){t.push({role:"assistant",content:""}),s=null;continue}"done"===r.type&&(s?s.content=r.finalText||s.content:r.finalText?.trim()&&t.push({role:"assistant",content:r.finalText}),s=null)}return t}async run(e,t,s){let i;let o=await this.sessionStore.get(t),a=await this.resolveProjectWorkingDirectory(o?.projectId);await this.sessionStore.consumePendingAutoTitle(t,e);let c=function(e){let t=[];for(let[s,r]of(e??[]).entries()){let e=/^data:image\/(jpeg|png|gif|webp);base64,/i.exec(r);e&&t.push({type:"image",name:`image-${s+1}.${n[e[1].toLowerCase()]}`,dataUrl:r})}return t.length>0?{attachments:t}:void 0}(s);await this.sessionStore.addMessage(t,{role:"user",content:e,...c?{presentation:c}:{}}),this.eventCounters.set(t,0),this.recentEvents.set(t,[]);let l=o?.projectId||this.defaultRemoteToolsProjectId;try{i=await this.getBuilder().withWorkingDirectory(a).withRemoteToolStore(this.remoteToolStore,l).withTool(new r.as(async e=>this.createQuestion(e,t))).build()}catch(s){let e={type:"error",message:s instanceof Error?s.message:"Failed to build agent"};try{await this.sessionStore.addEvent(t,e)}catch{}throw this.emit(t,e),s}finally{this.builder?.withWorkingDirectory(this.workingDirectory).withRemoteToolStore(this.remoteToolStore,this.defaultRemoteToolsProjectId)}this.activeAgent=i,this.activeRunSessionId=t,this.activeRun=i.run(e,t,s);let u=!1;try{for await(let e of this.activeRun)await this.sessionStore.addEvent(t,e),"error"===e.type?(u=!0,await this.sessionStore.update(t,{status:"failed"})):"done"!==e.type||u||(e.finalText.trim()&&await this.sessionStore.addMessage(t,{role:"assistant",content:e.finalText}),await this.sessionStore.update(t,{status:"completed"})),this.emit(t,e)}catch(s){u=!0;let e={type:"error",message:s instanceof Error?s.message:"Agent run failed"};try{await this.sessionStore.addEvent(t,e),await this.sessionStore.update(t,{status:"failed"})}catch{}this.emit(t,e)}finally{this.activeRunSessionId===t&&(this.activeAgent=null,this.activeRunSessionId=null),this.activeRun=null}try{let e=await this.sessionStore.get(t),s=(e?.messages??[]).filter(e=>"user"===e.role),r=this.projectMessagesFromEvents(e?.events??[]);await this.sessionStore.replaceMessages(t,[...s,...r])}catch{}}createQuestion(e,t){let s=crypto.randomUUID();return this.emit(t,{type:"ask_user",questionId:s,question:e.question,options:e.options,multiSelect:e.multiSelect}),new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingQuestions.has(s)&&(this.pendingQuestions.delete(s),t(Error("Question timed out after 5 minutes")))},3e5);this.pendingQuestions.set(s,{resolve:e,reject:t,timer:r})})}answerQuestion(e,t,s){let r=this.pendingQuestions.get(e);return!!r&&(clearTimeout(r.timer),this.pendingQuestions.delete(e),r.resolve({answer:t,selectedIndices:s}),!0)}async steer(e,t){return await this.sessionStore.addMessage(t,{role:"user",content:e,name:"__steer__"}),this.activeRunSessionId===t&&!!this.activeAgent&&(this.emit(t,{type:"thinking",message:`User added: ${e.slice(0,60)}`}),!0)}abort(){for(let[e,t]of(this.activeAgent?.abort(),this.pendingQuestions))clearTimeout(t.timer),t.reject(Error("Agent aborted")),this.pendingQuestions.delete(e)}}let l=globalThis,u=l.__agentHost??new c;l.__agentHost=u},4214:(e,t,s)=>{s.a(e,async(e,r)=>{try{s.r(t),s.d(t,{GET:()=>d,POST:()=>p,readAgentType:()=>u,readWorkspaceQuery:()=>h});var i=s(1890),o=s(2557),n=s(7186),a=s(2083),c=s(556),l=e([a]);a=(l.then?(await l)():l)[0];let m=new Set(["customer-agent","codex","claude-code","opencode"]);function u(e){return e&&m.has(e)?e:null}function h(e){let t=e.searchParams.get("limit"),s=null===t?50:Number(t);if(!Number.isInteger(s)||s<1||s>200)throw Error("limit must be an integer between 1 and 200");return{cursor:e.searchParams.get("cursor"),since:e.searchParams.get("since"),refresh:"1"===e.searchParams.get("refresh"),limit:s}}async function d(e){let t;let s=new URL(e.url),r=u(s.searchParams.get("agentType"));if(!r)return i.NextResponse.json({error:"A valid agentType is required"},{status:400});try{t=h(s)}catch(e){return i.NextResponse.json({error:e instanceof Error?e.message:"Invalid query"},{status:400})}try{if("customer-agent"!==r)return i.NextResponse.json(await (0,a.NL)().listWorkspaces(r,t));let e=(await n.f.getProjectStore().list()).map((e,t)=>({agentType:r,workspaceId:e.id,name:e.name,roots:e.description?[e.description]:[],order:t,updatedAt:e.updated,source:"native"}));return i.NextResponse.json((0,o.L)(e,t,e[0]?.updatedAt??null))}catch(e){return i.NextResponse.json({error:e instanceof Error?e.message:"Workspace discovery failed"},{status:(0,a.WW)(e)})}}async function p(e){let t;try{t=await e.json()}catch{return i.NextResponse.json({error:"A JSON body is required"},{status:400})}let s=u(t.agentType??null);if(!s||!t.path?.trim())return i.NextResponse.json({error:"A valid agentType and path are required"},{status:400});try{let e=c.a.canonicalDirectory(t.path);if("customer-agent"!==s)return i.NextResponse.json(await (0,a.NL)().importWorkspace(s,e,t.name),{status:201});let r=await c.a.list(),o=await c.a.create(e,t.name);return i.NextResponse.json({workspace:{agentType:s,workspaceId:o.id,name:o.name,roots:o.description?[o.description]:[],order:Math.max(0,r.findIndex(e=>e.id===o.id)),updatedAt:o.updated,source:"native"},existing:r.some(e=>e.id===o.id)},{status:201})}catch(t){let e=(0,c.r)(t);if(500!==e.status)return i.NextResponse.json(e.body,{status:e.status});return i.NextResponse.json({error:t instanceof Error?t.message:"Workspace import failed"},{status:(0,a.WW)(t)})}}r()}catch(e){r(e)}})},556:(e,t,s)=>{s.d(t,{r:()=>h,a:()=>u});var r=s(612),i=s(1322),o=s(785),n=s(6005),a=s(9411);class c extends Error{constructor(e,t,s){super(e),this.code=t,this.status=s,this.name="WebProjectError"}}class l{constructor(e,t){this.store=e,this.paths=t}list(){return this.store.list()}async get(e){let t=await this.store.get(e);if(!t)throw new c("项目不存在","PROJECT_NOT_FOUND",404);return t}async create(e,t){let s=this.paths.assertDirectory(e);for(let e of(await this.store.list()))try{if(this.paths.assertDirectory(e.description)===s)return e}catch{}let r=new Date().toISOString();return this.store.create({id:(0,n.randomUUID)(),name:t?.trim()||(0,a.basename)(s)||s,description:s,created:r,updated:r})}async rename(e,t){await this.get(e);let s=t.trim();if(!s)throw new c("项目名称不能为空","PROJECT_NAME_REQUIRED",400);return this.store.update(e,{name:s})}async delete(e){await this.get(e),await this.store.delete(e)}roots(){return this.paths.roots}directories(e){return this.paths.listDirectories(e)}check(e){try{return this.paths.assertDirectory(e),!0}catch{return!1}}canonicalDirectory(e){return this.paths.assertDirectory(e)}}let u=new l(new i.XW((0,o.kO)()),i.Tp.fromEnvironment(process.env.AGENT_WEB_ROOTS,(0,r.homedir)()));function h(e){return e instanceof c?{status:e.status,body:{error:e.message,code:e.code}}:e instanceof i.TL?{status:400,body:{error:e.message,code:e.code}}:{status:500,body:{error:e instanceof Error?e.message:"项目操作失败",code:"PROJECT_OPERATION_FAILED"}}}}};