agentroam-runtime-darwin-arm64 0.2.0-preview.12 → 0.2.0-preview.13

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 (101) 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 +7 -7
  5. package/runtime/.next/app-path-routes-manifest.json +1 -1
  6. package/runtime/.next/build-manifest.json +6 -6
  7. package/runtime/.next/prerender-manifest.json +1 -1
  8. package/runtime/.next/react-loadable-manifest.json +1 -1
  9. package/runtime/.next/required-server-files.json +1 -1
  10. package/runtime/.next/routes-manifest.json +1 -1
  11. package/runtime/.next/server/app/_not-found/page.js +1 -1
  12. package/runtime/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  13. package/runtime/.next/server/app/_not-found.html +1 -1
  14. package/runtime/.next/server/app/_not-found.rsc +1 -1
  15. package/runtime/.next/server/app/api/agent/abort/route.js +1 -1
  16. package/runtime/.next/server/app/api/agent/answer/route.js +1 -1
  17. package/runtime/.next/server/app/api/agent/model/route.js +1 -1
  18. package/runtime/.next/server/app/api/agent/models/route.js +1 -1
  19. package/runtime/.next/server/app/api/agent/run/route.js +1 -1
  20. package/runtime/.next/server/app/api/agent/runtime-health/route.js +1 -1
  21. package/runtime/.next/server/app/api/agent/steer/route.js +1 -1
  22. package/runtime/.next/server/app/api/agent/stream/route.js +2 -2
  23. package/runtime/.next/server/app/api/agent-workspaces/[workspaceId]/sessions/route.js +1 -1
  24. package/runtime/.next/server/app/api/agent-workspaces/route.js +1 -1
  25. package/runtime/.next/server/app/api/auth/verify/route.js +1 -1
  26. package/runtime/.next/server/app/api/mcp/connect/route.js +1 -1
  27. package/runtime/.next/server/app/api/mcp/disconnect/route.js +1 -1
  28. package/runtime/.next/server/app/api/mcp/servers/route.js +1 -1
  29. package/runtime/.next/server/app/api/memory/[key]/route.js +1 -1
  30. package/runtime/.next/server/app/api/memory/route.js +1 -1
  31. package/runtime/.next/server/app/api/plugins/load/route.js +1 -1
  32. package/runtime/.next/server/app/api/projects/[id]/route.js +1 -1
  33. package/runtime/.next/server/app/api/projects/check/route.js +1 -1
  34. package/runtime/.next/server/app/api/projects/directories/route.js +1 -1
  35. package/runtime/.next/server/app/api/projects/roots/route.js +1 -1
  36. package/runtime/.next/server/app/api/projects/route.js +1 -1
  37. package/runtime/.next/server/app/api/remote-tools/register/route.js +1 -1
  38. package/runtime/.next/server/app/api/sessions/[id]/changes/route.js +2 -2
  39. package/runtime/.next/server/app/api/sessions/[id]/fork/route.js +1 -1
  40. package/runtime/.next/server/app/api/sessions/[id]/goals/route.js +1 -1
  41. package/runtime/.next/server/app/api/sessions/[id]/handoff/route.js +1 -1
  42. package/runtime/.next/server/app/api/sessions/[id]/query-index/route.js +1 -0
  43. package/runtime/.next/server/app/api/sessions/[id]/query-index/route.js.nft.json +1 -0
  44. package/runtime/.next/server/app/api/sessions/[id]/route.js +1 -1
  45. package/runtime/.next/server/app/api/sessions/route.js +1 -1
  46. package/runtime/.next/server/app/api/skills/route.js +1 -1
  47. package/runtime/.next/server/app/api/tools/route.js +1 -1
  48. package/runtime/.next/server/app/api/web-auth/login/route.js +1 -1
  49. package/runtime/.next/server/app/api/web-auth/logout/route.js +1 -1
  50. package/runtime/.next/server/app/api/web-auth/revoke-all/route.js +1 -1
  51. package/runtime/.next/server/app/api/web-auth/setup/route.js +1 -1
  52. package/runtime/.next/server/app/api/web-auth/status/route.js +1 -1
  53. package/runtime/.next/server/app/api/web-console/bootstrap/route.js +1 -1
  54. package/runtime/.next/server/app/api/web-console/device-state/route.js +1 -1
  55. package/runtime/.next/server/app/api/web-console/history/route.js +1 -1
  56. package/runtime/.next/server/app/api/web-console/preferences/route.js +1 -1
  57. package/runtime/.next/server/app/web/page.js +3 -4
  58. package/runtime/.next/server/app/web/page_client-reference-manifest.js +1 -1
  59. package/runtime/.next/server/app/web.html +1 -1
  60. package/runtime/.next/server/app/web.rsc +2 -2
  61. package/runtime/.next/server/app-paths-manifest.json +21 -20
  62. package/runtime/.next/server/chunks/1322.js +37 -37
  63. package/runtime/.next/server/chunks/2083.js +7 -7
  64. package/runtime/.next/server/chunks/5303.js +2 -2
  65. package/runtime/.next/server/middleware-build-manifest.js +1 -1
  66. package/runtime/.next/server/middleware-react-loadable-manifest.js +1 -1
  67. package/runtime/.next/server/pages/404.html +1 -1
  68. package/runtime/.next/server/pages/500.html +1 -1
  69. package/runtime/.next/server/server-reference-manifest.json +1 -1
  70. package/runtime/.next/static/chunks/137.261fab9d606d75d3.js +1 -0
  71. package/runtime/.next/static/chunks/app/web/page-8e4da33d77868123.js +1 -0
  72. package/runtime/.next/static/chunks/{main-app-e9c7dfe241898866.js → main-app-3596fd7d2841e9a3.js} +1 -1
  73. package/runtime/.next/static/chunks/{webpack-aa3dd6c115307361.js → webpack-d22db940097662ef.js} +1 -1
  74. package/runtime/node_modules/@agent/core/dist/domain/model/entities.d.ts +2 -0
  75. package/runtime/node_modules/@agent/core/dist/domain/model/entities.d.ts.map +1 -1
  76. package/runtime/node_modules/@agent/core/dist/domain/session/SessionHistory.d.ts.map +1 -1
  77. package/runtime/node_modules/@agent/core/dist/domain/session/SessionQueryIndex.d.ts +16 -0
  78. package/runtime/node_modules/@agent/core/dist/domain/session/SessionQueryIndex.d.ts.map +1 -0
  79. package/runtime/node_modules/@agent/core/dist/domain/session/SessionQueryIndex.test.d.ts +2 -0
  80. package/runtime/node_modules/@agent/core/dist/domain/session/SessionQueryIndex.test.d.ts.map +1 -0
  81. package/runtime/node_modules/@agent/core/dist/domain/session/SessionQueryIndexCache.d.ts +11 -0
  82. package/runtime/node_modules/@agent/core/dist/domain/session/SessionQueryIndexCache.d.ts.map +1 -0
  83. package/runtime/node_modules/@agent/core/dist/domain/session/SessionQueryIndexCache.test.d.ts +2 -0
  84. package/runtime/node_modules/@agent/core/dist/domain/session/SessionQueryIndexCache.test.d.ts.map +1 -0
  85. package/runtime/node_modules/@agent/core/dist/domain/session/entities.d.ts +18 -0
  86. package/runtime/node_modules/@agent/core/dist/domain/session/entities.d.ts.map +1 -1
  87. package/runtime/node_modules/@agent/core/dist/domain/session/index.d.ts +3 -1
  88. package/runtime/node_modules/@agent/core/dist/domain/session/index.d.ts.map +1 -1
  89. package/runtime/node_modules/@agent/core/dist/index.js +202 -7
  90. package/runtime/node_modules/@agent/core/dist/index.js.map +6 -4
  91. package/runtime/webapp/dist/assets/App-CZspcejP.js +275 -0
  92. package/runtime/webapp/dist/assets/{index-CTuREapw.js → index-BAH3pT_c.js} +6 -6
  93. package/runtime/webapp/dist/assets/index-lt5J4xDf.css +1 -0
  94. package/runtime/webapp/dist/index.html +2 -2
  95. package/runtime/ws-server.mjs +13 -2
  96. package/runtime/.next/static/chunks/137.b2c5a562cf28417d.js +0 -1
  97. package/runtime/.next/static/chunks/app/web/page-2a4cea1bebd50375.js +0 -1
  98. package/runtime/webapp/dist/assets/App-Bf3AhvuP.js +0 -270
  99. package/runtime/webapp/dist/assets/index-B1fGLxCu.css +0 -1
  100. /package/runtime/.next/static/{z8n2mClYDr-eB4JXiAbLG → iaxCayE60RyqJY_Zj-OjS}/_buildManifest.js +0 -0
  101. /package/runtime/.next/static/{z8n2mClYDr-eB4JXiAbLG → iaxCayE60RyqJY_Zj-OjS}/_ssgManifest.js +0 -0
@@ -1,5 +1,5 @@
1
- "use strict";exports.id=2083,exports.ids=[2083],exports.modules={2557:(e,t,s)=>{s.d(t,{L:()=>u,MO:()=>l,Nr:()=>d,Vk:()=>h,ZN:()=>o,vT:()=>c});var i=s(6005),r=s(9411),a=s(132);let n="codex:recent";function o(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 l(e){return Buffer.from(JSON.stringify({offset:e}),"utf8").toString("base64url")}function d(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 u(e,t={},s=null){let i=d(t.cursor),r=o(t.limit),a=e.slice(i,i+r),n=i+a.length;return{data:a,nextCursor:n<e.length?l(n):null,watermark:s}}function c(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 p(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 h{constructor(e,t,s=process.platform,i){for(let r of(this.importedWorkspaces=t,this.platform=s,this.supplementCodexSessions=i,this.adapters=new Map,this.workspaceCache=new Map,this.workspaceRequests=new Map,this.sessionCache=new Map,this.sessionRequests=new Map,this.codexSessionCatalog=null,this.codexSessionCatalogRequest=null,this.codexSessionCatalogGeneration=0,e))this.adapters.set(r.agentType,r)}async listWorkspaces(e,t={}){let s=this.requireWorkspaceAdapter(e);if(!t.refresh){let s=this.workspaceCache.get(e);if(s)return{...u(s.data,t,s.watermark),stale:s.stale};let i=this.workspaceRequests.get(e);if(i){let e=await i;return{...u(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),t.refresh&&"codex"===e&&this.clearSessionCache(e),{...u(s.data,t,s.watermark),stale:s.stale}}catch(i){let s=this.workspaceCache.get(e);if(s)return{...u(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=c(t,this.platform),l=this.workspaceCache.get(e)?.data.find(e=>e.roots.some(e=>c(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=>c(e,this.platform)===o));if(e)return{workspace:e,existing:!0}}catch{}if(d)return{workspace:p(d,Number.MAX_SAFE_INTEGER),existing:!0};let u=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:u});return this.invalidate(e),{workspace:p(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 n="customer-agent"===e?null:this.importedWorkspaces?.list(e).find(e=>e.workspaceId===t)??null,l="codex"===e?this.listCodexWorkspaceSessions(i,t,s):n?this.listImportedWorkspaceSessions(i,n,s):i.listWorkspaceSessions(t,{...s,limit:o(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){this.clearSessionCache(e);return}"codex"===e&&this.resetCodexSessionCatalog();let s=`${e}\0${t}\0`;for(let e of this.sessionCache.keys())e.startsWith(s)&&this.sessionCache.delete(e)}clearSessionCache(e){this.deleteSessionCacheEntries(e),"codex"===e&&this.resetCodexSessionCatalog()}deleteSessionCacheEntries(e){for(let t of this.sessionCache.keys())t.startsWith(`${e}\0`)&&this.sessionCache.delete(t)}resetCodexSessionCatalog(){this.codexSessionCatalogGeneration+=1,this.codexSessionCatalog=null,this.codexSessionCatalogRequest=null}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);let o=s;if(this.importedWorkspaces&&"customer-agent"!==e.agentType){let t=new Set(s.flatMap(e=>e.roots.map(e=>c(e,this.platform)))),i=this.importedWorkspaces.list(e.agentType).filter(e=>!t.has(e.normalizedPath)).map((e,t)=>p(e,s.length+t));o=[...s,...i]}return"codex"===e.agentType&&(o=[{agentType:"codex",workspaceId:n,name:"最近",roots:[],order:-1,source:"derived",canCreateSession:!1},...o]),{data:o,watermark:r,...a?{stale:!0}:{}}}async listCodexWorkspaceSessions(e,t,s){let i=await this.getCodexSessionCatalog(e,!0===s.refresh),r=i.byWorkspace.get(t);if(!r)throw new a.n(`Codex workspace not found: ${t}`,"SESSION_NOT_FOUND");return u(r,s,i.watermark)}async getCodexSessionCatalog(e,t){if(t&&this.resetCodexSessionCatalog(),!t&&this.codexSessionCatalog)return this.codexSessionCatalog;if(!t&&this.codexSessionCatalogRequest)return this.codexSessionCatalogRequest;let s=this.codexSessionCatalogGeneration,i=this.loadCodexSessionCatalog(e);this.codexSessionCatalogRequest=i;try{let r=await i;if(s!==this.codexSessionCatalogGeneration)return this.getCodexSessionCatalog(e,!1);return t&&this.deleteSessionCacheEntries("codex"),this.codexSessionCatalog=r,r}finally{this.codexSessionCatalogRequest===i&&(this.codexSessionCatalogRequest=null)}}async loadCodexSessionCatalog(e){this.workspaceCache.has("codex")||await this.listWorkspaces("codex",{limit:200});let t=this.workspaceCache.get("codex")?.data;if(!t)throw new a.n("Codex workspace catalog is unavailable","RUNTIME_UNAVAILABLE");let s=await e.discoverSessions();return function(e,t,s=process.platform){let i=t.filter(e=>e.workspaceId!==n),r=new Map(i.map(e=>[e.workspaceId,e])),a=i.flatMap(e=>e.roots.flatMap(t=>{if(!t.trim())return[];try{return[{workspaceId:e.workspaceId,path:c(t,s)}]}catch{return[]}})).sort((e,t)=>t.path.length-e.path.length),o=new Map(t.map(e=>[e.workspaceId,[]])),l=[...e].sort((e,t)=>t.updated.localeCompare(e.updated)||e.id.localeCompare(t.id)),d=new Set;for(let e of l){if(d.has(e.id))continue;d.add(e.id);let t=e.projectId&&r.has(e.projectId)?e.projectId:void 0;if(!t&&e.cwd.trim())try{let i=c(e.cwd,s);t=a.find(e=>{var t;return(t=e.path)===i||i.startsWith(`${t}${"win32"===s?"\\":"/"}`)})?.workspaceId}catch{}t??=n;let i=o.get(t)??o.get(n);i?.push({...e,projectId:t})}return{byWorkspace:o,watermark:l[0]?.updated??null}}(this.supplementCodexSessions?.(s)??s,t,this.platform)}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:o(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:()=>M});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),g=s(2557),y=s(132),w=e([u]);u=(w.then?(await w)():w)[0];let x=(0,d.promisify)(r.execFile),k=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,P=[{id:"sonnet",displayName:"Claude Sonnet(均衡)",reasoningEfforts:["low","medium","high","xhigh"]},{id:"opus",displayName:"Claude Opus(最强)",reasoningEfforts:["low","medium","high","xhigh","max"]},{id:"haiku",displayName:"Claude Haiku(最快)",reasoningEfforts:["low","medium","high"]}];class L{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:N(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?N(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=A(t.delta);return"text_delta"===s.type&&"string"==typeof s.text&&s.text?(o.activity={...o.activity,messages:O(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=C(s);for(let e of(i&&!o.streamedText&&(t=O(t,i)),s)){let s=R(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=A(e);"tool_result"===t.type&&"string"==typeof t.tool_use_id&&(s=n,i=t.tool_use_id,r=C(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 M{constructor(e={}){this.agentType="claude-code",this.contextUsageRequestIndex=0,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 x("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 listModels(){return P}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),_(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,g.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 y.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,g.ZN)(t.limit),i=(0,g.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,g.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 y.n(`Claude Code session not found: ${e}`,"SESSION_NOT_FOUND");let a=s?_(await this.toSummary(s,r),t):t,n=E(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&&k.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 y.n("Claude Code session is already running","SESSION_ALREADY_RUNNING");let n=await this.getSession(e);if("owned-externally"===n.occupancy)throw new y.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 g=(0,u.query)({prompt:f,options:{cwd:n.cwd,...d?{sessionId:e}:{resume:e},includePartialMessages:!0,forwardSubagentText:!0,agentProgressSummaries:!0,...a?.model?.id?{model:a.model.id}:{},...a?.reasoningEffort?{effort:a.reasoningEffort}:{},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,g),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 L,S=null;try{let t=g[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(v.hasActiveBackgroundTasks()){for(let e of v.stopActive())yield e;yield t?{type:"turn_aborted"}:{type:"error",message:"Claude Code ended before a background subagent completed",code:"NATIVE_PROTOCOL_ERROR"},S=null}else t&&(yield{type:"turn_aborted"});break}let n=a.result.value;for(let e of(i=t.next(),v.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=A(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=C(i);e&&s.push({type:"text_chunk",text:e})}for(let e of i){let t=R(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=A(e);return"tool_result"!==t.type||"string"!=typeof t.tool_use_id?[]:[{type:"tool_result",result:{toolCallId:t.tool_use_id,content:C(t.content),isError:!0===t.is_error}}]}):[]}return[]}(n,_.length>0))"text_chunk"===e.type&&(_+=e.text),yield e;if("system"===n.type&&"init"===n.subtype&&n.session_id!==e)throw new y.n(`Claude Code returned unexpected session ID ${n.session_id}`,"NATIVE_PROTOCOL_ERROR");if("result"===n.type){S=n;let e=function(e,t){let s="usage"in e&&"object"==typeof e.usage&&null!==e.usage?e.usage:null;if(!s)return null;let i=e=>{let t=s[e];return"number"==typeof t&&Number.isFinite(t)&&t>0?Math.round(t):0},r=i("input_tokens")+i("cache_read_input_tokens")+i("cache_creation_input_tokens"),a=i("output_tokens"),n=r+a;return n<=0?null:{type:"context_usage",usage:{requestIndex:t,providerId:"claude",modelId:"model"in e&&"string"==typeof e.model?e.model:"claude",maxTokens:2e5,totalTokens:n,ratio:Math.min(n/2e5,1),estimationMode:"heuristic",segments:[{category:"conversationHistory",tokens:r},...a>0?[{category:"assistantMessages",tokens:a}]:[]]}}}(S,++this.contextUsageRequestIndex);e&&(yield e)}if(S&&!v.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"}}(S,_),S=null;break}}this.drafts.delete(e)}catch(e){yield{type:"error",message:e instanceof Error?e.message:String(e),code:e instanceof y.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),g.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),S()]);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=E(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||!k.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=v(r.slice(0,o));if(e)return e;o=(r=r.slice(o+1)).indexOf("\n")}}return v(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 _(e,t){return t?{...e,cwd:e.cwd||t.cwd,projectId:e.projectId??t.projectId}:e}function v(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 S(){try{let{stdout:e}=await x("claude",["agents","--json","--all"],{encoding:"utf8",timeout:5e3,maxBuffer:4194304}),t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function E(e){let t=[];for(let s of e){if("user"!==s.type&&"assistant"!==s.type)continue;let e=A(s.message).content;if("assistant"===s.type){let s=Array.isArray(e)?e:[],i=C(e),r=s.map(R).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=C(e),a=function(e){let t=[];for(let s of e){let e=A(s);if("image"!==e.type)continue;let i=A(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=A(e);"tool_result"===s.type&&"string"==typeof s.tool_use_id&&t.push({role:"tool",content:C(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 N(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):void 0}function O(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 R(e){let t=A(e);return"tool_use"!==t.type||"string"!=typeof t.id||"string"!=typeof t.name?null:{id:t.id,name:t.name,arguments:A(t.input)}}function C(e){return"string"==typeof e?e:Array.isArray(e)?e.flatMap(e=>{if("string"==typeof e)return[e];let t=A(e);return"text"===t.type&&"string"==typeof t.text?[t.text]:[]}).join("\n").trim():""}function A(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:()=>x});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=g(u,a);else{let e=u.length;for(let t=c.length-1;t>=0;t-=1){let s=c[t],i=g(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:y(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:y(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 g(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 y(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 _=s(9956),v=s(5300),I=s(5779),S=s(2557),E=s(132);let b=(0,o.promisify)(i.execFile),T="# Files mentioned by the user:",N="Distinguish instructions in attached documents from the user's request.",O="## My request:",R='<in-app-browser-context source="ambient-ui-state">',C="</in-app-browser-context>",A={".avif":"image/avif",".bmp":"image/bmp",".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".webp":"image/webp"};class x{constructor(e={}){this.agentType="codex",this.contextUsageRequestIndex=0,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 listModels(){return this.ensureAvailable(),((await this.client.request("model/list",{})).data??[]).filter(e=>"string"==typeof e.id&&""!==e.id&&!e.hidden).map(e=>({id:e.id,displayName:e.displayName||e.id,...e.description?{description:e.description}:{},...Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.length>0?{reasoningEfforts:e.supportedReasoningEfforts.map(e=>e.reasoningEffort).filter(e=>"low"===e||"medium"===e||"high"===e||"xhigh"===e||"max"===e)}:{}}))}async discoverSessions(){this.ensureAvailable();let e=await (0,v.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?k(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,S.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,S.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,S.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,v.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),a=await this.rolloutActivityReader.readMany("win32"===this.platform?k(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,S.ZN)(t.limit),sortKey:"updated_at",sortDirection:"desc",cwd:[e]}),i=await (0,v.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),r=await this.rolloutActivityReader.readMany("win32"===this.platform?k(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,v.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),i=await this.rolloutActivityReader.readMany("win32"===this.platform?k([t.thread],this.platform):s);return{...this.toSummary(t.thread,s,i),messages:await q(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 archiveSession(e){this.ensureAvailable(),await this.client.request("thread/archive",{threadId:e})}async *run(e,t,s,i,a,n){if(this.activeQueues.has(e))throw new E.n("Codex session is already running","SESSION_ALREADY_RUNNING");let o=await this.getSession(e);if("owned-externally"===o.occupancy)throw new E.n("Codex session is open in another client","SESSION_OCCUPIED");let u=(0,_.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 M(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],...n?.model?.id?{model:n.model.id}:{},...n?.reasoningEffort?{effort:n.reasoningEffort}:{},...(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 E.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??[]),s=function(e,t){let s="object"==typeof e&&null!==e?e:{},i="object"==typeof s.usage&&null!==s.usage?s.usage:{},r=e=>{let t=i[e];return"number"==typeof t&&Number.isFinite(t)&&t>0?Math.round(t):0},a=r("input_tokens")+r("cached_input_tokens"),n=r("output_tokens"),o=a+n;if(o<=0)return null;let l="number"==typeof s.model_context_window&&Number.isFinite(s.model_context_window)&&s.model_context_window>0?Math.round(s.model_context_window):272e3;return{type:"context_usage",usage:{requestIndex:t,providerId:"codex",modelId:"string"==typeof s.model?s.model:"codex",maxTokens:l,totalTokens:o,ratio:Math.min(o/l,1),estimationMode:"heuristic",segments:[{category:"conversationHistory",tokens:a},...n>0?[{category:"assistantMessages",tokens:n}]:[]]}}}(e,++this.contextUsageRequestIndex);s&&i.push(s),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 E.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 k(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 M(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 D(e){let t=(0,n.basename)(e)||"image",s=A[(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 q(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(N,T.length);if(e<0)return{content:t};s=e+N.length}else{if(!t.startsWith(R))return{content:t};let e=t.indexOf(C,R.length);if(e<0)return{content:t};s=e+C.length}let i=t.indexOf(O,s);if(i<0)return{content:t};let r=t.slice(i+O.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(D)),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 E.n?e:new E.n(e instanceof Error?e.message:String(e),"NATIVE_PROTOCOL_ERROR")}},3555:(e,t,s)=>{s.d(t,{c:()=>r});var i=s(132);class r{constructor(e,t){this.adapter=e,this.catalog=t,this.primaryNativeSessionIds=new Set}start(){this.catalog.start()}supplement(e){return this.primaryNativeSessionIds=new Set(e.map(e=>e.nativeSessionId)),[...e,...this.catalog.summaries().filter(e=>!this.primaryNativeSessionIds.has(e.nativeSessionId))]}isSupplemental(e){return!this.primaryNativeSessionIds.has(e)&&void 0!==this.catalog.findByNativeSessionId(e)}async readSupplemental(e){let t=this.catalog.findByNativeSessionId(e);if(!t||this.primaryNativeSessionIds.has(e))throw new i.n("Codex session is not a supplemental catalog entry","SESSION_NOT_FOUND");if(!t.probeable)throw this.incompatibleError(t,t.compatibility.reason??"无法恢复可验证的 Codex 会话 ID");try{let s=await this.adapter.getSession(e);return this.catalog.updateCompatibility(e,{status:"direct",readerVersion:t.compatibility.readerVersion,...t.producerVersion?{producerVersion:t.producerVersion}:{},...t.formatKey?{formatKey:t.formatKey}:{}}),s}catch(r){if(r instanceof i.n&&"RUNTIME_UNAVAILABLE"===r.code){let s=`Codex ${t.compatibility.readerVersion} 当前不可用,无法验证该会话`;throw this.catalog.updateCompatibility(e,{status:"incompatible",readerVersion:t.compatibility.readerVersion,...t.producerVersion?{producerVersion:t.producerVersion}:{},...t.formatKey?{formatKey:t.formatKey}:{},reasonCode:"CODEX_SESSION_RUNTIME_UNAVAILABLE",reason:s}),new i.n(s,"CODEX_SESSION_VERSION_INCOMPATIBLE")}let s=t.producerVersion?`该会话由 Codex ${t.producerVersion} 创建,当前 Codex ${t.compatibility.readerVersion} 无法读取`:`当前 Codex ${t.compatibility.readerVersion} 无法读取该会话的历史格式`;throw this.catalog.updateCompatibility(e,{status:"incompatible",readerVersion:t.compatibility.readerVersion,...t.producerVersion?{producerVersion:t.producerVersion}:{},...t.formatKey?{formatKey:t.formatKey}:{},reasonCode:"CODEX_SESSION_DIRECT_READ_FAILED",reason:s}),new i.n(s,"CODEX_SESSION_VERSION_INCOMPATIBLE")}}dispose(){this.catalog.dispose()}incompatibleError(e,t){return this.catalog.updateCompatibility(e.nativeSessionId,{...e.compatibility,status:"incompatible",reasonCode:e.compatibility.reasonCode??"CODEX_SESSION_SCHEMA_UNKNOWN",reason:t}),new i.n(t,"CODEX_SESSION_VERSION_INCOMPATIBLE")}}},4998:(e,t,s)=>{s.d(t,{VK:()=>c});var i=s(6005),r=s(3977),a=s(7561),n=s(612),o=s(9411),l=s(5779);let d=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,u=/^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(?:\.\d+)?-([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\.jsonl$/i;class c{constructor(e){this.options=e,this.watcher=null,this.debounceTimer=null,this.repairTimer=null,this.scanPromise=null,this.consecutiveBudgetBreaches=0,this.breakerUntil=0,this.disposed=!1,this.hasCompletedScan=!1,this.fileSystem=e.fileSystem??p,this.now=e.now??Date.now,this.setTimer=e.setTimer??setTimeout,this.clearTimer=e.clearTimer??clearTimeout,this.setRepeatingTimer=e.setRepeatingTimer??setInterval,this.clearRepeatingTimer=e.clearRepeatingTimer??clearInterval,this.concurrency=Math.max(1,Math.min(e.concurrency??(0,n.availableParallelism)(),(0,n.availableParallelism)(),8)),this.entries=e.repository.load(this.cacheIdentity())}snapshot(){return this.entries}summaries(){return this.entries.map(e=>(function(e){let t=e.created.slice(0,10);return{id:(0,l.F)("codex",e.nativeSessionId),agentType:"codex",nativeSessionId:e.nativeSessionId,title:`Codex 会话 ${t}`,cwd:e.cwd,...e.parentSessionId?{parentSessionId:e.parentSessionId}:{},created:e.created,updated:e.updated,status:"idle",occupancy:"available",sourceLabel:e.producerVersion?`Codex ${e.producerVersion}`:"Codex",canResume:"direct"===e.compatibility.status,canDelete:!0,compatibility:e.compatibility}})(e))}findByNativeSessionId(e){return this.entries.find(t=>t.nativeSessionId===e)}start(){this.disposed||this.repairTimer||(this.scheduleReconciliation(),this.fileSystem.realpath(this.options.sessionRoot).then(e=>{this.disposed||(this.watcher=this.fileSystem.watch(e,()=>this.scheduleDebouncedReconciliation()))}).catch(()=>void 0),this.repairTimer=this.setRepeatingTimer(()=>{this.scheduleReconciliation()},6e4),this.repairTimer.unref?.())}scheduleReconciliation(e=!1){return this.scanPromise||(this.scanPromise=this.reconcile(e).finally(()=>{this.scanPromise=null})),this.scanPromise}async reconcile(e=!1){let t,s;let r=this.now();if(this.disposed||!e&&this.breakerUntil>r)return m(this.breakerUntil>r);try{t=await this.fileSystem.realpath(this.options.sessionRoot),s=await this.fileSystem.listFiles(t)}catch{return m(!1)}let a=new Map(this.entries.map(e=>[e.canonicalPath,e])),n=Array(s.length).fill(null),l=0,c=0,p=0,f=0,g=async()=>{for(;;){let e=l++;if(e>=s.length)return;let r=s[e];try{let s=await this.fileSystem.realpath(r);if(!function(e,t){let s=(0,o.relative)((0,o.resolve)(e),(0,o.resolve)(t));return""!==s&&".."!==s&&!s.startsWith(`..${o.sep}`)&&!(0,o.isAbsolute)(s)}(t,s))continue;let l=await this.fileSystem.stat(s);if(!l.isFile())continue;let m=a.get(s);if(m&&m.size===l.size&&m.mtimeNs===l.mtimeNs){n[e]=m,f+=1;continue}c+=1;let g=await this.fileSystem.readMetadata(s,262144);p+=g.bytesRead,n[e]=function(e,t,s,r){var a;let n=function(e){let t=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1);return u.exec(t)?.[1]}(e),o=`catalog:${(0,i.createHash)("sha256").update(e).digest("base64url").slice(0,24)}`,l=(a=t.mtimeNs,new Date(Number(BigInt(a)/1000000n)).toISOString()),c=null;try{c=JSON.parse(s.text)}catch{c=null}let p=c?.type==="session_meta"&&c.payload&&"object"==typeof c.payload?c.payload:null,m="string"==typeof p?.id&&d.test(p.id)?p.id:void 0,f=h(p?.cli_version),g=function(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}(h(p?.timestamp))??l,y=h(p?.cwd)??"",w=h(p?.parent_thread_id)??h(p?.parent_id),_=p?function(e){let t=Object.keys(e).sort().map(t=>{let s=e[t];return Array.isArray(s)?`${t}:array`:s&&"object"==typeof s?`${t}:{${Object.keys(s).sort().join(",")}}`:`${t}:${typeof s}`}).join("|");return`meta-v1:${(0,i.createHash)("sha256").update(t).digest("base64url").slice(0,16)}`}(p):void 0,v=s.complete?p?void 0:"无法识别会话元数据格式":`会话元数据超过 256 KiB 安全上限`,I=!v&&(m||n)?{status:"checking",readerVersion:r,...f?{producerVersion:f}:{},..._?{formatKey:_}:{}}:{status:"incompatible",readerVersion:r,...f?{producerVersion:f}:{},..._?{formatKey:_}:{},reasonCode:"CODEX_SESSION_SCHEMA_UNKNOWN",reason:v??"无法恢复可验证的 Codex 会话 ID"};return{canonicalPath:e,size:t.size,mtimeNs:t.mtimeNs,nativeSessionId:m??n??o,probeable:!!(m||n),...f?{producerVersion:f}:{},cwd:y,created:g,updated:l,...w?{parentSessionId:w}:{},..._?{formatKey:_}:{},compatibility:I}}(s,l,g,this.options.readerVersion)}catch{}(e+1)%32==0&&await new Promise(e=>setImmediate(e))}};await Promise.all(Array.from({length:Math.min(this.concurrency,Math.max(1,s.length))},g));let y=n.filter(e=>null!==e).sort((e,t)=>t.updated.localeCompare(e.updated)||e.nativeSessionId.localeCompare(t.nativeSessionId)),w=y.length!==this.entries.length||y.some((e,t)=>e.canonicalPath!==this.entries[t]?.canonicalPath);this.entries=y,(c>0||w)&&this.options.repository.replace(this.entries,this.cacheIdentity());let _=Math.max(0,this.now()-r),v=this.hasCompletedScan?200:1e3;return this.hasCompletedScan=!0,_>v?this.consecutiveBudgetBreaches+=1:this.consecutiveBudgetBreaches=0,this.consecutiveBudgetBreaches>=3&&(this.breakerUntil=this.now()+3e5,this.consecutiveBudgetBreaches=0),{durationMs:_,filesVisited:s.length,changedFiles:c,metadataBytesRead:p,cacheHits:f,breakerOpen:this.breakerUntil>this.now()}}updateCompatibility(e,t){let s=this.entries.findIndex(t=>t.nativeSessionId===e);if(s<0)return;let i=this.entries[s],r={...i,compatibility:t};this.entries=this.entries.map((e,t)=>t===s?r:e),this.options.repository.updateCompatibility(i.canonicalPath,i.size,i.mtimeNs,t)}dispose(){this.disposed=!0,this.watcher?.close(),this.watcher=null,this.debounceTimer&&this.clearTimer(this.debounceTimer),this.repairTimer&&this.clearRepeatingTimer(this.repairTimer),this.debounceTimer=null,this.repairTimer=null}cacheIdentity(){return{schemaVersion:1,registryVersion:1,readerVersion:this.options.readerVersion}}scheduleDebouncedReconciliation(){this.debounceTimer&&this.clearTimer(this.debounceTimer),this.debounceTimer=this.setTimer(()=>{this.debounceTimer=null,this.scheduleReconciliation()},500),this.debounceTimer.unref?.()}}let p={async listFiles(e){let t=[],s=[e];for(;s.length>0;){let e=s.pop();for(let i of(await (0,r.readdir)(e,{withFileTypes:!0}))){let r=(0,o.join)(e,i.name);!i.isSymbolicLink()&&(i.isDirectory()?s.push(r):i.isFile()&&i.name.endsWith(".jsonl")&&t.push(r))}s.length%32==0&&await new Promise(e=>setImmediate(e))}return t},realpath:r.realpath,async stat(e){let t=await (0,r.stat)(e,{bigint:!0});return{isFile:()=>t.isFile(),size:Number(t.size),mtimeNs:t.mtimeNs.toString()}},async readMetadata(e,t){let s=await (0,r.open)(e,"r"),i=[],a=0,n=!1;try{for(;a<t;){let e=Buffer.allocUnsafe(Math.min(16384,t-a)),r=await s.read(e,0,e.length,a);if(0===r.bytesRead){n=!0;break}a+=r.bytesRead;let o=e.subarray(0,r.bytesRead),l=o.indexOf(10);if(i.push(l>=0?o.subarray(0,l):o),l>=0){n=!0;break}}return{text:Buffer.concat(i).toString("utf8"),bytesRead:a,complete:n}}finally{await s.close()}},watch(e,t){try{return(0,a.watch)(e,{recursive:!0},t)}catch{return null}}};function h(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function m(e){return{durationMs:0,filesVisited:0,changedFiles:0,metadataBytesRead:0,cacheHits:0,breakerOpen:e}}},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:()=>b,v6:()=>E});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(4998),f=s(3555),g=s(3053),y=s(8733),w=s(2815),_=s(5779),v=s(132),I=s(2428),S=e([p]);p=(S.then?(await S)():S)[0];let $="native-runtime.sock";class G{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(`
1
+ "use strict";exports.id=2083,exports.ids=[2083],exports.modules={2557:(e,t,s)=>{s.d(t,{L:()=>u,MO:()=>l,Nr:()=>d,Vk:()=>h,ZN:()=>o,vT:()=>c});var i=s(6005),r=s(9411),a=s(132);let n="codex:recent";function o(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 l(e){return Buffer.from(JSON.stringify({offset:e}),"utf8").toString("base64url")}function d(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 u(e,t={},s=null){let i=d(t.cursor),r=o(t.limit),a=e.slice(i,i+r),n=i+a.length;return{data:a,nextCursor:n<e.length?l(n):null,watermark:s}}function c(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 p(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 h{constructor(e,t,s=process.platform,i){for(let r of(this.importedWorkspaces=t,this.platform=s,this.supplementCodexSessions=i,this.adapters=new Map,this.workspaceCache=new Map,this.workspaceRequests=new Map,this.sessionCache=new Map,this.sessionRequests=new Map,this.codexSessionCatalog=null,this.codexSessionCatalogRequest=null,this.codexSessionCatalogGeneration=0,e))this.adapters.set(r.agentType,r)}async listWorkspaces(e,t={}){let s=this.requireWorkspaceAdapter(e);if(!t.refresh){let s=this.workspaceCache.get(e);if(s)return{...u(s.data,t,s.watermark),stale:s.stale};let i=this.workspaceRequests.get(e);if(i){let e=await i;return{...u(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),t.refresh&&"codex"===e&&this.clearSessionCache(e),{...u(s.data,t,s.watermark),stale:s.stale}}catch(i){let s=this.workspaceCache.get(e);if(s)return{...u(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=c(t,this.platform),l=this.workspaceCache.get(e)?.data.find(e=>e.roots.some(e=>c(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=>c(e,this.platform)===o));if(e)return{workspace:e,existing:!0}}catch{}if(d)return{workspace:p(d,Number.MAX_SAFE_INTEGER),existing:!0};let u=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:u});return this.invalidate(e),{workspace:p(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 n="customer-agent"===e?null:this.importedWorkspaces?.list(e).find(e=>e.workspaceId===t)??null,l="codex"===e?this.listCodexWorkspaceSessions(i,t,s):n?this.listImportedWorkspaceSessions(i,n,s):i.listWorkspaceSessions(t,{...s,limit:o(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){this.clearSessionCache(e);return}"codex"===e&&this.resetCodexSessionCatalog();let s=`${e}\0${t}\0`;for(let e of this.sessionCache.keys())e.startsWith(s)&&this.sessionCache.delete(e)}clearSessionCache(e){this.deleteSessionCacheEntries(e),"codex"===e&&this.resetCodexSessionCatalog()}deleteSessionCacheEntries(e){for(let t of this.sessionCache.keys())t.startsWith(`${e}\0`)&&this.sessionCache.delete(t)}resetCodexSessionCatalog(){this.codexSessionCatalogGeneration+=1,this.codexSessionCatalog=null,this.codexSessionCatalogRequest=null}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);let o=s;if(this.importedWorkspaces&&"customer-agent"!==e.agentType){let t=new Set(s.flatMap(e=>e.roots.map(e=>c(e,this.platform)))),i=this.importedWorkspaces.list(e.agentType).filter(e=>!t.has(e.normalizedPath)).map((e,t)=>p(e,s.length+t));o=[...s,...i]}return"codex"===e.agentType&&(o=[{agentType:"codex",workspaceId:n,name:"最近",roots:[],order:-1,source:"derived",canCreateSession:!1},...o]),{data:o,watermark:r,...a?{stale:!0}:{}}}async listCodexWorkspaceSessions(e,t,s){let i=await this.getCodexSessionCatalog(e,!0===s.refresh),r=i.byWorkspace.get(t);if(!r)throw new a.n(`Codex workspace not found: ${t}`,"SESSION_NOT_FOUND");return u(r,s,i.watermark)}async getCodexSessionCatalog(e,t){if(t&&this.resetCodexSessionCatalog(),!t&&this.codexSessionCatalog)return this.codexSessionCatalog;if(!t&&this.codexSessionCatalogRequest)return this.codexSessionCatalogRequest;let s=this.codexSessionCatalogGeneration,i=this.loadCodexSessionCatalog(e);this.codexSessionCatalogRequest=i;try{let r=await i;if(s!==this.codexSessionCatalogGeneration)return this.getCodexSessionCatalog(e,!1);return t&&this.deleteSessionCacheEntries("codex"),this.codexSessionCatalog=r,r}finally{this.codexSessionCatalogRequest===i&&(this.codexSessionCatalogRequest=null)}}async loadCodexSessionCatalog(e){this.workspaceCache.has("codex")||await this.listWorkspaces("codex",{limit:200});let t=this.workspaceCache.get("codex")?.data;if(!t)throw new a.n("Codex workspace catalog is unavailable","RUNTIME_UNAVAILABLE");let s=await e.discoverSessions();return function(e,t,s=process.platform){let i=t.filter(e=>e.workspaceId!==n),r=new Map(i.map(e=>[e.workspaceId,e])),a=i.flatMap(e=>e.roots.flatMap(t=>{if(!t.trim())return[];try{return[{workspaceId:e.workspaceId,path:c(t,s)}]}catch{return[]}})).sort((e,t)=>t.path.length-e.path.length),o=new Map(t.map(e=>[e.workspaceId,[]])),l=[...e].sort((e,t)=>t.updated.localeCompare(e.updated)||e.id.localeCompare(t.id)),d=new Set;for(let e of l){if(d.has(e.id))continue;d.add(e.id);let t=e.projectId&&r.has(e.projectId)?e.projectId:void 0;if(!t&&e.cwd.trim())try{let i=c(e.cwd,s);t=a.find(e=>{var t;return(t=e.path)===i||i.startsWith(`${t}${"win32"===s?"\\":"/"}`)})?.workspaceId}catch{}t??=n;let i=o.get(t)??o.get(n);i?.push({...e,projectId:t})}return{byWorkspace:o,watermark:l[0]?.updated??null}}(this.supplementCodexSessions?.(s)??s,t,this.platform)}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:o(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:()=>M});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),g=s(2557),y=s(132),w=e([u]);u=(w.then?(await w)():w)[0];let A=(0,d.promisify)(r.execFile),k=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,P=[{id:"sonnet",displayName:"Claude Sonnet(均衡)",reasoningEfforts:["low","medium","high","xhigh"]},{id:"opus",displayName:"Claude Opus(最强)",reasoningEfforts:["low","medium","high","xhigh","max"]},{id:"haiku",displayName:"Claude Haiku(最快)",reasoningEfforts:["low","medium","high"]}];class L{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:N(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?N(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=x(t.delta);return"text_delta"===s.type&&"string"==typeof s.text&&s.text?(o.activity={...o.activity,messages:O(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=C(s);for(let e of(i&&!o.streamedText&&(t=O(t,i)),s)){let s=R(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=x(e);"tool_result"===t.type&&"string"==typeof t.tool_use_id&&(s=n,i=t.tool_use_id,r=C(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 M{constructor(e={}){this.agentType="claude-code",this.contextUsageRequestIndex=0,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 A("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 listModels(){return P}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),_(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,g.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 y.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,g.ZN)(t.limit),i=(0,g.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,g.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 y.n(`Claude Code session not found: ${e}`,"SESSION_NOT_FOUND");let a=s?_(await this.toSummary(s,r),t):t,n=E(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&&k.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 y.n("Claude Code session is already running","SESSION_ALREADY_RUNNING");let n=await this.getSession(e);if("owned-externally"===n.occupancy)throw new y.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 g=(0,u.query)({prompt:f,options:{cwd:n.cwd,...d?{sessionId:e}:{resume:e},includePartialMessages:!0,forwardSubagentText:!0,agentProgressSummaries:!0,...a?.model?.id?{model:a.model.id}:{},...a?.reasoningEffort?{effort:a.reasoningEffort}:{},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,g),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 L,S=null;try{let t=g[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(v.hasActiveBackgroundTasks()){for(let e of v.stopActive())yield e;yield t?{type:"turn_aborted"}:{type:"error",message:"Claude Code ended before a background subagent completed",code:"NATIVE_PROTOCOL_ERROR"},S=null}else t&&(yield{type:"turn_aborted"});break}let n=a.result.value;for(let e of(i=t.next(),v.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=x(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=C(i);e&&s.push({type:"text_chunk",text:e})}for(let e of i){let t=R(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=x(e);return"tool_result"!==t.type||"string"!=typeof t.tool_use_id?[]:[{type:"tool_result",result:{toolCallId:t.tool_use_id,content:C(t.content),isError:!0===t.is_error}}]}):[]}return[]}(n,_.length>0))"text_chunk"===e.type&&(_+=e.text),yield e;if("system"===n.type&&"init"===n.subtype&&n.session_id!==e)throw new y.n(`Claude Code returned unexpected session ID ${n.session_id}`,"NATIVE_PROTOCOL_ERROR");if("result"===n.type){S=n;let e=function(e,t){let s="usage"in e&&"object"==typeof e.usage&&null!==e.usage?e.usage:null;if(!s)return null;let i=e=>{let t=s[e];return"number"==typeof t&&Number.isFinite(t)&&t>0?Math.round(t):0},r=i("input_tokens")+i("cache_read_input_tokens")+i("cache_creation_input_tokens"),a=i("output_tokens"),n=r+a;return n<=0?null:{type:"context_usage",usage:{requestIndex:t,providerId:"claude",modelId:"model"in e&&"string"==typeof e.model?e.model:"claude",maxTokens:2e5,totalTokens:n,ratio:Math.min(n/2e5,1),estimationMode:"heuristic",segments:[{category:"conversationHistory",tokens:r},...a>0?[{category:"assistantMessages",tokens:a}]:[]]}}}(S,++this.contextUsageRequestIndex);e&&(yield e)}if(S&&!v.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"}}(S,_),S=null;break}}this.drafts.delete(e)}catch(e){yield{type:"error",message:e instanceof Error?e.message:String(e),code:e instanceof y.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),g.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),S()]);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=E(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||!k.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=v(r.slice(0,o));if(e)return e;o=(r=r.slice(o+1)).indexOf("\n")}}return v(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 _(e,t){return t?{...e,cwd:e.cwd||t.cwd,projectId:e.projectId??t.projectId}:e}function v(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 S(){try{let{stdout:e}=await A("claude",["agents","--json","--all"],{encoding:"utf8",timeout:5e3,maxBuffer:4194304}),t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function E(e){let t=[];for(let s of e){if("user"!==s.type&&"assistant"!==s.type)continue;let e=x(s.message).content;if("assistant"===s.type){let s=Array.isArray(e)?e:[],i=C(e),r=s.map(R).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=C(e),a=function(e){let t=[];for(let s of e){let e=x(s);if("image"!==e.type)continue;let i=x(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=x(e);"tool_result"===s.type&&"string"==typeof s.tool_use_id&&t.push({role:"tool",content:C(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 N(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):void 0}function O(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 R(e){let t=x(e);return"tool_use"!==t.type||"string"!=typeof t.id||"string"!=typeof t.name?null:{id:t.id,name:t.name,arguments:x(t.input)}}function C(e){return"string"==typeof e?e:Array.isArray(e)?e.flatMap(e=>{if("string"==typeof e)return[e];let t=x(e);return"text"===t.type&&"string"==typeof t.text?[t.text]:[]}).join("\n").trim():""}function x(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:()=>A});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=g(u,a);else{let e=u.length;for(let t=c.length-1;t>=0;t-=1){let s=c[t],i=g(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:y(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:y(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 g(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 y(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 _=s(9956),v=s(5300),I=s(5779),S=s(2557),E=s(132);let b=(0,o.promisify)(i.execFile),T="# Files mentioned by the user:",N="Distinguish instructions in attached documents from the user's request.",O="## My request:",R='<in-app-browser-context source="ambient-ui-state">',C="</in-app-browser-context>",x={".avif":"image/avif",".bmp":"image/bmp",".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".webp":"image/webp"};class A{constructor(e={}){this.agentType="codex",this.contextUsageRequestIndex=0,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 listModels(){return this.ensureAvailable(),((await this.client.request("model/list",{})).data??[]).filter(e=>"string"==typeof e.id&&""!==e.id&&!e.hidden).map(e=>({id:e.id,displayName:e.displayName||e.id,...e.description?{description:e.description}:{},...Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.length>0?{reasoningEfforts:e.supportedReasoningEfforts.map(e=>e.reasoningEffort).filter(e=>"low"===e||"medium"===e||"high"===e||"xhigh"===e||"max"===e)}:{}}))}async discoverSessions(){this.ensureAvailable();let e=await (0,v.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?k(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,S.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,S.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,S.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,v.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),a=await this.rolloutActivityReader.readMany("win32"===this.platform?k(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,S.ZN)(t.limit),sortKey:"updated_at",sortDirection:"desc",cwd:[e]}),i=await (0,v.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),r=await this.rolloutActivityReader.readMany("win32"===this.platform?k(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,v.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),i=await this.rolloutActivityReader.readMany("win32"===this.platform?k([t.thread],this.platform):s);return{...this.toSummary(t.thread,s,i),messages:await q(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 archiveSession(e){this.ensureAvailable(),await this.client.request("thread/archive",{threadId:e})}async *run(e,t,s,i,a,n){if(this.activeQueues.has(e))throw new E.n("Codex session is already running","SESSION_ALREADY_RUNNING");let o=await this.getSession(e);if("owned-externally"===o.occupancy)throw new E.n("Codex session is open in another client","SESSION_OCCUPIED");let u=(0,_.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 M(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],...n?.model?.id?{model:n.model.id}:{},...n?.reasoningEffort?{effort:n.reasoningEffort}:{},...(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 E.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??[]),s=function(e,t){let s="object"==typeof e&&null!==e?e:{},i="object"==typeof s.usage&&null!==s.usage?s.usage:{},r=e=>{let t=i[e];return"number"==typeof t&&Number.isFinite(t)&&t>0?Math.round(t):0},a=r("input_tokens")+r("cached_input_tokens"),n=r("output_tokens"),o=a+n;if(o<=0)return null;let l="number"==typeof s.model_context_window&&Number.isFinite(s.model_context_window)&&s.model_context_window>0?Math.round(s.model_context_window):272e3;return{type:"context_usage",usage:{requestIndex:t,providerId:"codex",modelId:"string"==typeof s.model?s.model:"codex",maxTokens:l,totalTokens:o,ratio:Math.min(o/l,1),estimationMode:"heuristic",segments:[{category:"conversationHistory",tokens:a},...n>0?[{category:"assistantMessages",tokens:n}]:[]]}}}(e,++this.contextUsageRequestIndex);s&&i.push(s),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 E.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 k(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 M(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 D(e){let t=(0,n.basename)(e)||"image",s=x[(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 q(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(N,T.length);if(e<0)return{content:t};s=e+N.length}else{if(!t.startsWith(R))return{content:t};let e=t.indexOf(C,R.length);if(e<0)return{content:t};s=e+C.length}let i=t.indexOf(O,s);if(i<0)return{content:t};let r=t.slice(i+O.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(D)),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 E.n?e:new E.n(e instanceof Error?e.message:String(e),"NATIVE_PROTOCOL_ERROR")}},3555:(e,t,s)=>{s.d(t,{c:()=>r});var i=s(132);class r{constructor(e,t){this.adapter=e,this.catalog=t,this.primaryNativeSessionIds=new Set}start(){this.catalog.start()}supplement(e){return this.primaryNativeSessionIds=new Set(e.map(e=>e.nativeSessionId)),[...e,...this.catalog.summaries().filter(e=>!this.primaryNativeSessionIds.has(e.nativeSessionId))]}isSupplemental(e){return!this.primaryNativeSessionIds.has(e)&&void 0!==this.catalog.findByNativeSessionId(e)}async readSupplemental(e){let t=this.catalog.findByNativeSessionId(e);if(!t||this.primaryNativeSessionIds.has(e))throw new i.n("Codex session is not a supplemental catalog entry","SESSION_NOT_FOUND");if(!t.probeable)throw this.incompatibleError(t,t.compatibility.reason??"无法恢复可验证的 Codex 会话 ID");try{let s=await this.adapter.getSession(e);return this.catalog.updateCompatibility(e,{status:"direct",readerVersion:t.compatibility.readerVersion,...t.producerVersion?{producerVersion:t.producerVersion}:{},...t.formatKey?{formatKey:t.formatKey}:{}}),s}catch(r){if(r instanceof i.n&&"RUNTIME_UNAVAILABLE"===r.code){let s=`Codex ${t.compatibility.readerVersion} 当前不可用,无法验证该会话`;throw this.catalog.updateCompatibility(e,{status:"incompatible",readerVersion:t.compatibility.readerVersion,...t.producerVersion?{producerVersion:t.producerVersion}:{},...t.formatKey?{formatKey:t.formatKey}:{},reasonCode:"CODEX_SESSION_RUNTIME_UNAVAILABLE",reason:s}),new i.n(s,"CODEX_SESSION_VERSION_INCOMPATIBLE")}let s=t.producerVersion?`该会话由 Codex ${t.producerVersion} 创建,当前 Codex ${t.compatibility.readerVersion} 无法读取`:`当前 Codex ${t.compatibility.readerVersion} 无法读取该会话的历史格式`;throw this.catalog.updateCompatibility(e,{status:"incompatible",readerVersion:t.compatibility.readerVersion,...t.producerVersion?{producerVersion:t.producerVersion}:{},...t.formatKey?{formatKey:t.formatKey}:{},reasonCode:"CODEX_SESSION_DIRECT_READ_FAILED",reason:s}),new i.n(s,"CODEX_SESSION_VERSION_INCOMPATIBLE")}}dispose(){this.catalog.dispose()}incompatibleError(e,t){return this.catalog.updateCompatibility(e.nativeSessionId,{...e.compatibility,status:"incompatible",reasonCode:e.compatibility.reasonCode??"CODEX_SESSION_SCHEMA_UNKNOWN",reason:t}),new i.n(t,"CODEX_SESSION_VERSION_INCOMPATIBLE")}}},4998:(e,t,s)=>{s.d(t,{VK:()=>c});var i=s(6005),r=s(3977),a=s(7561),n=s(612),o=s(9411),l=s(5779);let d=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,u=/^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(?:\.\d+)?-([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\.jsonl$/i;class c{constructor(e){this.options=e,this.watcher=null,this.debounceTimer=null,this.repairTimer=null,this.scanPromise=null,this.consecutiveBudgetBreaches=0,this.breakerUntil=0,this.disposed=!1,this.hasCompletedScan=!1,this.fileSystem=e.fileSystem??p,this.now=e.now??Date.now,this.setTimer=e.setTimer??setTimeout,this.clearTimer=e.clearTimer??clearTimeout,this.setRepeatingTimer=e.setRepeatingTimer??setInterval,this.clearRepeatingTimer=e.clearRepeatingTimer??clearInterval,this.concurrency=Math.max(1,Math.min(e.concurrency??(0,n.availableParallelism)(),(0,n.availableParallelism)(),8)),this.entries=e.repository.load(this.cacheIdentity())}snapshot(){return this.entries}summaries(){return this.entries.map(e=>(function(e){let t=e.created.slice(0,10);return{id:(0,l.F)("codex",e.nativeSessionId),agentType:"codex",nativeSessionId:e.nativeSessionId,title:`Codex 会话 ${t}`,cwd:e.cwd,...e.parentSessionId?{parentSessionId:e.parentSessionId}:{},created:e.created,updated:e.updated,status:"idle",occupancy:"available",sourceLabel:e.producerVersion?`Codex ${e.producerVersion}`:"Codex",canResume:"direct"===e.compatibility.status,canDelete:!0,compatibility:e.compatibility}})(e))}findByNativeSessionId(e){return this.entries.find(t=>t.nativeSessionId===e)}start(){this.disposed||this.repairTimer||(this.scheduleReconciliation(),this.fileSystem.realpath(this.options.sessionRoot).then(e=>{this.disposed||(this.watcher=this.fileSystem.watch(e,()=>this.scheduleDebouncedReconciliation()))}).catch(()=>void 0),this.repairTimer=this.setRepeatingTimer(()=>{this.scheduleReconciliation()},6e4),this.repairTimer.unref?.())}scheduleReconciliation(e=!1){return this.scanPromise||(this.scanPromise=this.reconcile(e).finally(()=>{this.scanPromise=null})),this.scanPromise}async reconcile(e=!1){let t,s;let r=this.now();if(this.disposed||!e&&this.breakerUntil>r)return m(this.breakerUntil>r);try{t=await this.fileSystem.realpath(this.options.sessionRoot),s=await this.fileSystem.listFiles(t)}catch{return m(!1)}let a=new Map(this.entries.map(e=>[e.canonicalPath,e])),n=Array(s.length).fill(null),l=0,c=0,p=0,f=0,g=async()=>{for(;;){let e=l++;if(e>=s.length)return;let r=s[e];try{let s=await this.fileSystem.realpath(r);if(!function(e,t){let s=(0,o.relative)((0,o.resolve)(e),(0,o.resolve)(t));return""!==s&&".."!==s&&!s.startsWith(`..${o.sep}`)&&!(0,o.isAbsolute)(s)}(t,s))continue;let l=await this.fileSystem.stat(s);if(!l.isFile())continue;let m=a.get(s);if(m&&m.size===l.size&&m.mtimeNs===l.mtimeNs){n[e]=m,f+=1;continue}c+=1;let g=await this.fileSystem.readMetadata(s,262144);p+=g.bytesRead,n[e]=function(e,t,s,r){var a;let n=function(e){let t=e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1);return u.exec(t)?.[1]}(e),o=`catalog:${(0,i.createHash)("sha256").update(e).digest("base64url").slice(0,24)}`,l=(a=t.mtimeNs,new Date(Number(BigInt(a)/1000000n)).toISOString()),c=null;try{c=JSON.parse(s.text)}catch{c=null}let p=c?.type==="session_meta"&&c.payload&&"object"==typeof c.payload?c.payload:null,m="string"==typeof p?.id&&d.test(p.id)?p.id:void 0,f=h(p?.cli_version),g=function(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}(h(p?.timestamp))??l,y=h(p?.cwd)??"",w=h(p?.parent_thread_id)??h(p?.parent_id),_=p?function(e){let t=Object.keys(e).sort().map(t=>{let s=e[t];return Array.isArray(s)?`${t}:array`:s&&"object"==typeof s?`${t}:{${Object.keys(s).sort().join(",")}}`:`${t}:${typeof s}`}).join("|");return`meta-v1:${(0,i.createHash)("sha256").update(t).digest("base64url").slice(0,16)}`}(p):void 0,v=s.complete?p?void 0:"无法识别会话元数据格式":`会话元数据超过 256 KiB 安全上限`,I=!v&&(m||n)?{status:"checking",readerVersion:r,...f?{producerVersion:f}:{},..._?{formatKey:_}:{}}:{status:"incompatible",readerVersion:r,...f?{producerVersion:f}:{},..._?{formatKey:_}:{},reasonCode:"CODEX_SESSION_SCHEMA_UNKNOWN",reason:v??"无法恢复可验证的 Codex 会话 ID"};return{canonicalPath:e,size:t.size,mtimeNs:t.mtimeNs,nativeSessionId:m??n??o,probeable:!!(m||n),...f?{producerVersion:f}:{},cwd:y,created:g,updated:l,...w?{parentSessionId:w}:{},..._?{formatKey:_}:{},compatibility:I}}(s,l,g,this.options.readerVersion)}catch{}(e+1)%32==0&&await new Promise(e=>setImmediate(e))}};await Promise.all(Array.from({length:Math.min(this.concurrency,Math.max(1,s.length))},g));let y=n.filter(e=>null!==e).sort((e,t)=>t.updated.localeCompare(e.updated)||e.nativeSessionId.localeCompare(t.nativeSessionId)),w=y.length!==this.entries.length||y.some((e,t)=>e.canonicalPath!==this.entries[t]?.canonicalPath);this.entries=y,(c>0||w)&&this.options.repository.replace(this.entries,this.cacheIdentity());let _=Math.max(0,this.now()-r),v=this.hasCompletedScan?200:1e3;return this.hasCompletedScan=!0,_>v?this.consecutiveBudgetBreaches+=1:this.consecutiveBudgetBreaches=0,this.consecutiveBudgetBreaches>=3&&(this.breakerUntil=this.now()+3e5,this.consecutiveBudgetBreaches=0),{durationMs:_,filesVisited:s.length,changedFiles:c,metadataBytesRead:p,cacheHits:f,breakerOpen:this.breakerUntil>this.now()}}updateCompatibility(e,t){let s=this.entries.findIndex(t=>t.nativeSessionId===e);if(s<0)return;let i=this.entries[s],r={...i,compatibility:t};this.entries=this.entries.map((e,t)=>t===s?r:e),this.options.repository.updateCompatibility(i.canonicalPath,i.size,i.mtimeNs,t)}dispose(){this.disposed=!0,this.watcher?.close(),this.watcher=null,this.debounceTimer&&this.clearTimer(this.debounceTimer),this.repairTimer&&this.clearRepeatingTimer(this.repairTimer),this.debounceTimer=null,this.repairTimer=null}cacheIdentity(){return{schemaVersion:1,registryVersion:1,readerVersion:this.options.readerVersion}}scheduleDebouncedReconciliation(){this.debounceTimer&&this.clearTimer(this.debounceTimer),this.debounceTimer=this.setTimer(()=>{this.debounceTimer=null,this.scheduleReconciliation()},500),this.debounceTimer.unref?.()}}let p={async listFiles(e){let t=[],s=[e];for(;s.length>0;){let e=s.pop();for(let i of(await (0,r.readdir)(e,{withFileTypes:!0}))){let r=(0,o.join)(e,i.name);!i.isSymbolicLink()&&(i.isDirectory()?s.push(r):i.isFile()&&i.name.endsWith(".jsonl")&&t.push(r))}s.length%32==0&&await new Promise(e=>setImmediate(e))}return t},realpath:r.realpath,async stat(e){let t=await (0,r.stat)(e,{bigint:!0});return{isFile:()=>t.isFile(),size:Number(t.size),mtimeNs:t.mtimeNs.toString()}},async readMetadata(e,t){let s=await (0,r.open)(e,"r"),i=[],a=0,n=!1;try{for(;a<t;){let e=Buffer.allocUnsafe(Math.min(16384,t-a)),r=await s.read(e,0,e.length,a);if(0===r.bytesRead){n=!0;break}a+=r.bytesRead;let o=e.subarray(0,r.bytesRead),l=o.indexOf(10);if(i.push(l>=0?o.subarray(0,l):o),l>=0){n=!0;break}}return{text:Buffer.concat(i).toString("utf8"),bytesRead:a,complete:n}}finally{await s.close()}},watch(e,t){try{return(0,a.watch)(e,{recursive:!0},t)}catch{return null}}};function h(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function m(e){return{durationMs:0,filesVisited:0,changedFiles:0,metadataBytesRead:0,cacheHits:0,breakerOpen:e}}},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:()=>b,v6:()=>E});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(4998),f=s(3555),g=s(3053),y=s(8733),w=s(2815),_=s(5779),v=s(132),I=s(2428),S=e([p]);p=(S.then?(await S)():S)[0];let $="native-runtime.sock";class G{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
3
  CREATE TABLE IF NOT EXISTS native_runtime_policy (
4
4
  session_id TEXT PRIMARY KEY,
5
5
  permission_mode TEXT NOT NULL,
@@ -224,8 +224,8 @@
224
224
  sample_state=excluded.sample_state,
225
225
  sample_at=excluded.sample_at,
226
226
  updated_at=excluded.updated_at
227
- `).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 j{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 G(e,s),this.runtime="function"==typeof t?t({onApprovalResolved:e=>this.handleApprovalResolved(e),importedWorkspaceRepository:this.state,codexSessionCatalogRepository: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,$)}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.listResumableQueueItems()))this.startQueueItem(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=(0,c.ZN)(s?.limit),r=[],a=new Set,n=new Set,o=s?.cursor??null,l=o,d=null,u=!1,p=!0;for(;p||l&&this.state.filterHiddenSessions(r).length<i;){if(o){if(n.has(o))throw new v.n("Workspace pagination cursor did not advance","NATIVE_PROTOCOL_ERROR");n.add(o)}let c=this.state.filterHiddenSessions(r).length,h=await this.runtime.listWorkspaceSessions(e,t,{...s,cursor:o,limit:Math.max(1,i-c),refresh:p&&s?.refresh===!0});for(let e of(p&&(d=h.watermark),u||=!0===h.stale,h.data))a.has(e.id)||(a.add(e.id),r.push(e));o=l=h.nextCursor,p=!1}let h=this.state.findImportedWorkspace(e,t);return{nextCursor:l,watermark:d,...u?{stale:!0}:{},data:this.state.filterHiddenSessions(this.mergePending(r,void 0,s=>s.agentType===e&&(s.projectId===t||!!(h&&s.cwd&&(0,c.vT)(s.cwd)===h.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.isSessionHidden(e)||(this.state.assertSessionCanHide(e),"codex"===(0,_.V)(e).agentType&&await this.runtime.archive(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,a,n,o){this.state.assertSessionVisible(e);let l=this.activeExecutions.get(e);l&&!this.state.activeRun(e)&&await l;let d=T(e);try{let t=await this.runtime.get(e);if(!t.canResume||"owned-externally"===t.occupancy)throw this.state.recordExplicitExternalOwnership(e),new v.n("Session is currently owned by another client","SESSION_OCCUPIED")}catch(t){throw t instanceof v.n&&"SESSION_OCCUPIED"===t.code&&this.state.recordExplicitExternalOwnership(e),t}let u=this.state.admit({sessionId:e,agentType:d.agentType,nativeSessionId:d.nativeSessionId,message:t,controller:i,goalId:r}),c=this.executeRun(u,s,a,n,o);this.activeExecutions.set(e,c);let p=()=>{this.activeExecutions.get(e)===c&&this.activeExecutions.delete(e)};return c.then(p,p),{runId:u.runId,snapshotRevision:u.nextSequence,permissionMode:u.permissionMode}}async listModels(e){return this.runtime.listModels(e)}async getGoals(e,t="web"){let s=this.state.getGoalState(e);return s.active||!(s.queued.length>0)||this.state.activeRun(e)||(s=this.state.promoteNextItem(e)),s.active&&!this.state.activeRun(e)&&await this.startQueueItemAfterSettling(s.active,t),this.state.getGoalState(e)}async enqueueGoal(e,t,s,i="web"){T(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.startQueueItemAfterSettling(a.active,i);return{state:this.state.getGoalState(e),...n?{started:n}:{}}}reorderGoals(e,t){return T(e),this.state.reorderGoals(e,t)}async enqueueMessage(e,t,s="web"){T(e);let i=this.state.enqueueMessage(e,t);if(!i.active||this.state.activeRun(e))return{state:i};let r=await this.startQueueItemAfterSettling(i.active,s);return{state:this.state.getGoalState(e),...r?{started:r}:{}}}reorderMessages(e,t){return T(e),this.state.reorderMessages(e,t)}updateMessage(e,t,s,i){return T(e),this.state.updateMessage(e,t,s,i)}cancelMessage(e,t){return T(e),this.state.cancelMessage(e,t)}async steerMessage(e,t){T(e);let s=this.state.queuedMessages(e).find(e=>e.id===t);if(!s)throw new v.n("Queued message not found","SESSION_NOT_FOUND");let i=await this.runtime.steer(e,s.objective);return{steered:i,state:i?this.state.cancelMessage(e,t):this.state.getGoalState(e)}}async cancelGoal(e,t,s="web"){T(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.startQueueItem(a.active,s)):i&&!r&&a.active&&this.startQueueItem(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 v.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:T(e).agentType,nativeSessionId:T(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,s,i,r){let a=!1,n=!1;try{let o=e.goalId?this.state.getGoalState(e.sessionId).active:null,l={permissionMode:e.permissionMode,brokerRunId:e.runId,...r?.model?{model:r.model}:{},...r?.reasoningEffort?{reasoningEffort:r.reasoningEffort}:{},...e.goalId&&o?.id===e.goalId&&"goal"===(0,d.tw)(o)?{goal:{id:e.goalId,objective:o.objective}}:{}};for await(let r of this.runtime.run(e.sessionId,e.input,t,s,i,l)){let t=this.state.appendEvent(e.runId,r);t&&this.broadcast(t),"error"===r.type&&"SESSION_OCCUPIED"===r.code&&this.state.recordExplicitExternalOwnership(e.sessionId),a||=C(r),n||="done"===r.type}if(a)n&&(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 v.n&&"SESSION_OCCUPIED"===i.code,s=this.state.appendTerminal(e.runId,{type:"error",code:i instanceof v.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})=>C(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.startQueueItem(a,e.controller)}else{let t=this.state.getGoalState(e.sessionId).active;t||this.state.activeRun(e.sessionId)||(t=this.state.promoteNextItem(e.sessionId).active),t&&!this.state.activeRun(e.sessionId)&&this.startQueueItem(t,e.controller)}}}async startQueueItemAfterSettling(e,t){let s=this.activeExecutions.get(e.sessionId);if(s&&!this.state.activeRun(e.sessionId)){await s;return}return this.startQueueItem(e,t)}async startQueueItem(e,t){if(!this.state.activeRun(e.sessionId))try{return await this.startRun(e.sessionId,e.objective,e.messagePayload?.images,t,e.id,e.messagePayload?.agentIds,e.messagePayload?.agentName)}catch(i){let s=this.state.finishGoal(e.sessionId,e.id,"failed",i instanceof Error?i.message:String(i));s.active&&this.startQueueItem(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),s=t&&void 0===e.compatibility&&("claude-code"!==e.agentType||"Claude Code SDK"!==e.sourceLabel);return(s&&(this.pendingCreations.delete(e.id),this.state.deletePendingSession(e.id)),t)?s?R(e,t):R(t,e):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=k(s.params,"sessionId"),i=L(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 v.n?{code:t.code}:{}}}),e.end()})}async handleRequest(e){var t,s,i;let r=k(e.params,"sessionId");switch(e.method){case"ping":return{ok:!0};case"health":return this.health();case"listWorkspaces":return this.listWorkspaces(q(e.params,"agentType"),(t=e.params,{cursor:k(t,"cursor"),limit:L(t,"limit")??void 0,refresh:!0===t.refresh,since:k(t,"since")}));case"importWorkspace":return this.importWorkspace(q(e.params,"agentType"),P(e.params,"path"),k(e.params,"name")||void 0);case"listWorkspaceSessions":return this.listWorkspaceSessions(q(e.params,"agentType"),P(e.params,"workspaceId"),(s=e.params,{cursor:k(s,"cursor"),limit:L(s,"limit")??void 0,refresh:!0===s.refresh}));case"list":return this.list(k(e.params,"projectId")||void 0);case"refresh":return this.refresh(k(e.params,"projectId")||void 0);case"create":return this.create({agentType:q(e.params,"agentType"),title:k(e.params,"title")||"New session",cwd:k(e.params,"cwd")||"",...k(e.params,"projectId")?{projectId:k(e.params,"projectId")}:{}});case"fork":return this.fork(x(r));case"delete":return this.delete(x(r));case"get":return this.get(x(r),function(e){let t=k(e,"before")||void 0,s=L(e,"limit")??void 0;return t||void 0!==s?{before:t,limit:s}:void 0}(e.params));case"watchPath":return this.getSessionWatchPath(x(r));case"startRun":return this.startRun(x(r),k(e.params,"input")||"",M(e.params.images),U(e.params.controller),void 0,void 0,void 0,function(e){let t;let s=e.runOverrides;if(!s||"object"!=typeof s)return;let i=s.model;i&&"object"==typeof i&&"string"==typeof i.id&&""!==i.id&&(t={id:i.id,..."string"==typeof i.providerID&&""!==i.providerID?{providerID:i.providerID}:{}});let r=V.find(e=>e===s.reasoningEffort);if(t||r)return{...t?{model:t}:{},...r?{reasoningEffort:r}:{}}}(e.params));case"listModels":return this.listModels(q(e.params,"agentType"));case"snapshot":return this.snapshot(x(r),L(e.params,"afterSequence")??0);case"getGoals":return this.getGoals(x(r),U(e.params.controller));case"enqueueGoal":return this.enqueueGoal(x(r),k(e.params,"objective")||"",k(e.params,"sourceMessageId")||void 0,U(e.params.controller));case"enqueueMessage":return this.enqueueMessage(x(r),{sourceMessageId:P(e.params,"sourceMessageId"),content:P(e.params,"content"),messagePayload:D(e.params.messagePayload)},U(e.params.controller));case"reorderGoals":return this.reorderGoals(x(r),M(e.params.orderedIds)??[]);case"reorderMessages":return this.reorderMessages(x(r),M(e.params.orderedIds)??[]);case"updateMessage":return this.updateMessage(x(r),P(e.params,"messageId"),P(e.params,"content"),D(e.params.messagePayload));case"cancelMessage":return this.cancelMessage(x(r),P(e.params,"messageId"));case"steerMessage":return this.steerMessage(x(r),P(e.params,"messageId"));case"cancelGoal":return this.cancelGoal(x(r),k(e.params,"goalId")||"",U(e.params.controller));case"answer":return this.answerQuestion(k(e.params,"questionId")||"",{answer:k(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(x(r),k(e.params,"input")||"");case"setPermissionMode":return this.setPermissionMode(x(r),(0,d.Ny)(e.params.permissionMode));case"handoff":return this.handoff(x(r),U(e.params.controller));default:throw new v.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)}
228
- `)}}class F{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",r){return this.request("startRun",{sessionId:e,input:t,images:s,controller:i,...r?{runOverrides:r}:{}})}async listModels(e){return this.request("listModels",{agentType:e})}async *run(e,t,s,i,r,a="desktop",n){let o=await this.startRun(e,t,s,a,n);yield{type:"run_admitted",_nativeRunId:o.runId,_nativeSequence:0};let l=new u.K,d=await this.subscribe(e,0,e=>{e.runId===o.runId&&(l.push({...e.event,_nativeRunId:e.runId,_nativeSequence:e.sequence}),C(e.event)&&l.close())});try{for await(let e of l)yield e}finally{d()}}async subscribe(e,t,s){await this.ensureHost();let i=await W((0,l.join)(this.directory,$)),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(A(t.error)):"type"in t&&"event"===t.type&&t.event&&s(t.event)}catch{r(new v.n("Malformed broker response","NATIVE_PROTOCOL_ERROR"))}t=o.indexOf("\n")}}),i.once("error",e=>r(e)),i.once("close",()=>{n||r(new v.n("Native runtime broker disconnected","RUNTIME_UNAVAILABLE"))})});return i.write(`${JSON.stringify({id:a,method:"subscribe",params:{sessionId:e,afterSequence:t}})}
229
- `),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 enqueueMessage(e,t,s="web"){return this.request("enqueueMessage",{sessionId:e,...t,controller:s})}async reorderGoals(e,t){return this.request("reorderGoals",{sessionId:e,orderedIds:[...t]})}async reorderMessages(e,t){return this.request("reorderMessages",{sessionId:e,orderedIds:[...t]})}async updateMessage(e,t,s,i){return this.request("updateMessage",{sessionId:e,messageId:t,content:s,messagePayload:i})}async cancelMessage(e,t){return this.request("cancelMessage",{sessionId:e,messageId:t})}async steerMessage(e,t){return this.request("steerMessage",{sessionId:e,messageId: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 v.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");let t=this.directory,s=(0,l.join)(t,$);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 j(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 W((0,l.join)(this.directory,$)),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(A(e.error))}catch{l(new v.n("Malformed broker response","NATIVE_PROTOCOL_ERROR"))}}),s.once("error",e=>l(e)),s.once("close",()=>{o||l(new v.n("Native runtime broker disconnected","RUNTIME_UNAVAILABLE"))}),s.write(`${JSON.stringify({id:i,method:e,params:t})}
230
- `)})}}function E(e={}){return new F(e)}function b(e,t,s){let i=new h.b({executable:e||"codex"}),r=new g.tX({client:i,codexExecutable:e||"codex",onApprovalResolved:t?.onApprovalResolved}),a=t?.codexSessionCatalogRepository?new f.c(r,new m.VK({sessionRoot:(0,l.join)(process.env.CODEX_HOME?.trim()||(0,l.join)((0,o.homedir)(),".codex"),"sessions"),readerVersion:"0.153.0",repository:t.codexSessionCatalogRepository})):void 0;a?.start();let n=new w.O({executable:s||"opencode",unavailableError:process.env.AGENT_OPENCODE_RUNTIME_ERROR});return new I.V([r,new p.IW,new y.nI({server:n,executable:s||"opencode",unavailableError:process.env.AGENT_OPENCODE_RUNTIME_ERROR,onApprovalResolved:t?.onApprovalResolved})],()=>Promise.resolve([]),t?.importedWorkspaceRepository,a)}function T(e){let t;try{t=(0,_.V)(e)}catch(t){if(t instanceof v.n)throw t;throw new v.n(`Invalid native session id: ${e}`,"INVALID_SESSION_ID")}if("customer-agent"===t.agentType)throw new v.n("Customer Agent sessions are not handled by the native broker","INVALID_SESSION_ID");return t}function N(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 O(e){return{workspaceId:e.workspace_id,agentType:e.agent_type,normalizedPath:e.normalized_path,name:e.name,createdAt:e.created_at}}function R(e,t){return{...e,cwd:e.cwd||t.cwd,projectId:e.projectId??t.projectId}}function C(e){return"done"===e.type||"error"===e.type}function A(e){let t=e?.code;return t&&["INVALID_SESSION_ID","SESSION_NOT_FOUND","SESSION_OCCUPIED","SESSION_ALREADY_RUNNING","RUNTIME_UNAVAILABLE","OPERATION_NOT_SUPPORTED","APPROVAL_EXPIRED","CODEX_SESSION_VERSION_INCOMPATIBLE","NATIVE_PROTOCOL_ERROR"].includes(t)?new v.n(e?.message||"Native runtime broker failed",t):new v.n(e?.message||"Native runtime broker failed","NATIVE_PROTOCOL_ERROR")}function x(e){if(!e)throw new v.n("sessionId is required","INVALID_SESSION_ID");return e}function k(e,t){return"string"==typeof e[t]?e[t]:null}function P(e,t){let s=k(e,t);if(!s)throw new v.n(`${t} is required`,"INVALID_SESSION_ID");return s}function L(e,t){return"number"==typeof e[t]&&Number.isSafeInteger(e[t])?e[t]:null}function M(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)?e:void 0}function D(e){if(!e||"object"!=typeof e)return;let t=M(e.images),s=M(e.agentIds),i="string"==typeof e.agentName?e.agentName:void 0;return{...t?.length?{images:t}:{},...s?.length?{agentIds:s}:{},...i?{agentName:i}:{}}}function q(e,t){let s=k(e,t);if("codex"===s||"claude-code"===s||"opencode"===s)return s;throw new v.n("A native agent type is required","INVALID_SESSION_ID")}function U(e){return"desktop"===e||"web"===e?e:"web"}let V=["low","medium","high","xhigh","max"];function W(e){return new Promise((t,s)=>{let i=(0,n.createConnection)(e),r=setTimeout(()=>{i.destroy(),s(new v.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 g=(0,l.promisify)(i.execFile),y="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 g(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!==y)throw Error(`OpenCode ${s} at ${t} is incompatible; AgentRoam requires ${y}`);return s}(`${e}
231
- ${t}`,this.executable)}}catch(e){return{agentType:this.agentType,available:!1,label:"OpenCode",error:v(e)}}}async listModels(){let e=await this.getClient(),t=await e.config.providers({throwOnError:!0}),s=t.data?.providers??[],i=[];for(let e of s)if(e?.id)for(let[t,s]of Object.entries(e.models??{}))t&&i.push({id:t,providerID:e.id,displayName:s?.name||`${e.id}/${t}`});return i}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,_(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),_(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),{..._(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=v(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),_(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),_(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_ALREADY_RUNNING");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 d=(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},...d],...n?.model?.id&&n.model.providerID?{model:{providerID:n.model.providerID,modelID:n.model.id}}:{}},throwOnError:!0}),l))yield s}catch(e){yield{type:"error",message:v(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,v(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,v(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:v(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,v(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 _(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 v(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,i){for(let s of(this.listProjects=t,this.codexCompatibility=i,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,process.platform,i?e=>i.supplement(e):void 0)}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 listModels(e){let t=this.adapters.get(e);if(!t||!t.listModels)throw new o.n(`Runtime ${e} does not expose a model list`,"OPERATION_NOT_SUPPORTED");return t.listModels()}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{let s=await t.discoverSessions();return("codex"===t.agentType&&this.codexCompatibility?this.codexCompatibility.supplement(s):s).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 ("codex"===s.agentType&&this.codexCompatibility?.isSupplemental(i)?this.codexCompatibility.readSupplemental(i):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_ALREADY_RUNNING");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 archive(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.archiveSession)throw new o.n("This session cannot be archived","OPERATION_NOT_SUPPORTED");await t.archiveSession(s),this.invalidate(e)}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(){this.codexCompatibility?.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:()=>_});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 v=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()}listModels(e){return this.runtime.listModels(e)}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 y(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 y(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",r){if(!this.runtime.startRun)throw new u.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.startRun(e,t,s,i,r)}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")}async enqueueMessage(e,t,s="web"){if(!this.runtime.enqueueMessage)throw new u.n("Message queue is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.enqueueMessage(e,t,s)}async reorderMessages(e,t){if(!this.runtime.reorderMessages)throw new u.n("Message queue is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.reorderMessages(e,t)}async updateMessage(e,t,s,i){if(!this.runtime.updateMessage)throw new u.n("Message queue is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.updateMessage(e,t,s,i)}async cancelMessage(e,t){if(!this.runtime.cancelMessage)throw new u.n("Message queue is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.cancelMessage(e,t)}async steerMessage(e,t){if(!this.runtime.steerMessage)throw new u.n("Message queue is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.steerMessage(e,t)}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(!v.__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)());v.__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 v.__nativeRuntimeService}function f(e,t,s=process.platform){let{projectId:i,...r}=e;if(!e.cwd)return r;let a=g(e.cwd,s),o="win32"===s?n.win32.sep:n.sep,l=t.filter(e=>e.description).map(e=>({project:e,path:g(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 g(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 y(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 _(e){if(e instanceof u.n)switch(e.code){case"SESSION_NOT_FOUND":return 404;case"SESSION_OCCUPIED":case"SESSION_ALREADY_RUNNING":case"APPROVAL_EXPIRED":case"CODEX_SESSION_VERSION_INCOMPATIBLE":return 409;case"RUNTIME_UNAVAILABLE":return 503;case"OPERATION_NOT_SUPPORTED":return 405;default:return 400}return 500}i()}catch(e){i(e)}})}};
227
+ `).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 j{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.queryIndexCache=new d.pG,this.server=null,this.ownsSocket=!1,this.state=new G(e,s),this.runtime="function"==typeof t?t({onApprovalResolved:e=>this.handleApprovalResolved(e),importedWorkspaceRepository:this.state,codexSessionCatalogRepository: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,$)}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.listResumableQueueItems()))this.startQueueItem(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=(0,c.ZN)(s?.limit),r=[],a=new Set,n=new Set,o=s?.cursor??null,l=o,d=null,u=!1,p=!0;for(;p||l&&this.state.filterHiddenSessions(r).length<i;){if(o){if(n.has(o))throw new v.n("Workspace pagination cursor did not advance","NATIVE_PROTOCOL_ERROR");n.add(o)}let c=this.state.filterHiddenSessions(r).length,h=await this.runtime.listWorkspaceSessions(e,t,{...s,cursor:o,limit:Math.max(1,i-c),refresh:p&&s?.refresh===!0});for(let e of(p&&(d=h.watermark),u||=!0===h.stale,h.data))a.has(e.id)||(a.add(e.id),r.push(e));o=l=h.nextCursor,p=!1}let h=this.state.findImportedWorkspace(e,t);return{nextCursor:l,watermark:d,...u?{stale:!0}:{},data:this.state.filterHiddenSessions(this.mergePending(r,void 0,s=>s.agentType===e&&(s.projectId===t||!!(h&&s.cwd&&(0,c.vT)(s.cwd)===h.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.isSessionHidden(e)||(this.state.assertSessionCanHide(e),"codex"===(0,_.V)(e).agentType&&await this.runtime.archive(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,(0,I.D)(t)),i=this.state.applyDetail(s);return this.queryIndexCache.getOrCreate(e,i.messages),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 getQueryIndex(e){this.state.assertSessionVisible(e);try{let t=await this.runtime.getUnpaginated(e,!0),s=this.state.applyDetail(t);return this.queryIndexCache.getOrCreate(e,s.messages)}catch(i){let t=this.pendingCreations.get(e);if(!t)throw i;let s=this.state.applyDetail({...t,messages:[],events:[]});return this.queryIndexCache.getOrCreate(e,s.messages)}}async getSessionWatchPath(e){return this.state.assertSessionVisible(e),this.runtime.getSessionWatchPath(e)}async startRun(e,t,s,i="web",r,a,n,o){this.state.assertSessionVisible(e);let l=this.activeExecutions.get(e);l&&!this.state.activeRun(e)&&await l;let d=T(e);try{let t=await this.runtime.get(e);if(!t.canResume||"owned-externally"===t.occupancy)throw this.state.recordExplicitExternalOwnership(e),new v.n("Session is currently owned by another client","SESSION_OCCUPIED")}catch(t){throw t instanceof v.n&&"SESSION_OCCUPIED"===t.code&&this.state.recordExplicitExternalOwnership(e),t}let u=this.state.admit({sessionId:e,agentType:d.agentType,nativeSessionId:d.nativeSessionId,message:t,controller:i,goalId:r}),c=this.executeRun(u,s,a,n,o);this.activeExecutions.set(e,c);let p=()=>{this.activeExecutions.get(e)===c&&this.activeExecutions.delete(e)};return c.then(p,p),{runId:u.runId,snapshotRevision:u.nextSequence,permissionMode:u.permissionMode}}async listModels(e){return this.runtime.listModels(e)}async getGoals(e,t="web"){let s=this.state.getGoalState(e);return s.active||!(s.queued.length>0)||this.state.activeRun(e)||(s=this.state.promoteNextItem(e)),s.active&&!this.state.activeRun(e)&&await this.startQueueItemAfterSettling(s.active,t),this.state.getGoalState(e)}async enqueueGoal(e,t,s,i="web"){T(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.startQueueItemAfterSettling(a.active,i);return{state:this.state.getGoalState(e),...n?{started:n}:{}}}reorderGoals(e,t){return T(e),this.state.reorderGoals(e,t)}async enqueueMessage(e,t,s="web"){T(e);let i=this.state.enqueueMessage(e,t);if(!i.active||this.state.activeRun(e))return{state:i};let r=await this.startQueueItemAfterSettling(i.active,s);return{state:this.state.getGoalState(e),...r?{started:r}:{}}}reorderMessages(e,t){return T(e),this.state.reorderMessages(e,t)}updateMessage(e,t,s,i){return T(e),this.state.updateMessage(e,t,s,i)}cancelMessage(e,t){return T(e),this.state.cancelMessage(e,t)}async steerMessage(e,t){T(e);let s=this.state.queuedMessages(e).find(e=>e.id===t);if(!s)throw new v.n("Queued message not found","SESSION_NOT_FOUND");let i=await this.runtime.steer(e,s.objective);return{steered:i,state:i?this.state.cancelMessage(e,t):this.state.getGoalState(e)}}async cancelGoal(e,t,s="web"){T(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.startQueueItem(a.active,s)):i&&!r&&a.active&&this.startQueueItem(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 v.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:T(e).agentType,nativeSessionId:T(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,s,i,r){let a=!1,n=!1;try{let o=e.goalId?this.state.getGoalState(e.sessionId).active:null,l={permissionMode:e.permissionMode,brokerRunId:e.runId,...r?.model?{model:r.model}:{},...r?.reasoningEffort?{reasoningEffort:r.reasoningEffort}:{},...e.goalId&&o?.id===e.goalId&&"goal"===(0,d.tw)(o)?{goal:{id:e.goalId,objective:o.objective}}:{}};for await(let r of this.runtime.run(e.sessionId,e.input,t,s,i,l)){let t=this.state.appendEvent(e.runId,r);t&&this.broadcast(t),"error"===r.type&&"SESSION_OCCUPIED"===r.code&&this.state.recordExplicitExternalOwnership(e.sessionId),a||=C(r),n||="done"===r.type}if(a)n&&(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 v.n&&"SESSION_OCCUPIED"===i.code,s=this.state.appendTerminal(e.runId,{type:"error",code:i instanceof v.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})=>C(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.startQueueItem(a,e.controller)}else{let t=this.state.getGoalState(e.sessionId).active;t||this.state.activeRun(e.sessionId)||(t=this.state.promoteNextItem(e.sessionId).active),t&&!this.state.activeRun(e.sessionId)&&this.startQueueItem(t,e.controller)}}}async startQueueItemAfterSettling(e,t){let s=this.activeExecutions.get(e.sessionId);if(s&&!this.state.activeRun(e.sessionId)){await s;return}return this.startQueueItem(e,t)}async startQueueItem(e,t){if(!this.state.activeRun(e.sessionId))try{return await this.startRun(e.sessionId,e.objective,e.messagePayload?.images,t,e.id,e.messagePayload?.agentIds,e.messagePayload?.agentName)}catch(i){let s=this.state.finishGoal(e.sessionId,e.id,"failed",i instanceof Error?i.message:String(i));s.active&&this.startQueueItem(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),s=t&&void 0===e.compatibility&&("claude-code"!==e.agentType||"Claude Code SDK"!==e.sourceLabel);return(s&&(this.pendingCreations.delete(e.id),this.state.deletePendingSession(e.id)),t)?s?R(e,t):R(t,e):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=k(s.params,"sessionId"),i=L(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 v.n||t instanceof d.uj?{code:t.code}:{}}}),e.end()})}async handleRequest(e){var t,s,i;let r=k(e.params,"sessionId");switch(e.method){case"ping":return{ok:!0};case"health":return this.health();case"listWorkspaces":return this.listWorkspaces(q(e.params,"agentType"),(t=e.params,{cursor:k(t,"cursor"),limit:L(t,"limit")??void 0,refresh:!0===t.refresh,since:k(t,"since")}));case"importWorkspace":return this.importWorkspace(q(e.params,"agentType"),P(e.params,"path"),k(e.params,"name")||void 0);case"listWorkspaceSessions":return this.listWorkspaceSessions(q(e.params,"agentType"),P(e.params,"workspaceId"),(s=e.params,{cursor:k(s,"cursor"),limit:L(s,"limit")??void 0,refresh:!0===s.refresh}));case"list":return this.list(k(e.params,"projectId")||void 0);case"refresh":return this.refresh(k(e.params,"projectId")||void 0);case"create":return this.create({agentType:q(e.params,"agentType"),title:k(e.params,"title")||"New session",cwd:k(e.params,"cwd")||"",...k(e.params,"projectId")?{projectId:k(e.params,"projectId")}:{}});case"fork":return this.fork(A(r));case"delete":return this.delete(A(r));case"get":return this.get(A(r),function(e){let t=k(e,"before")||void 0,s=k(e,"after")||void 0,i=k(e,"anchor")||void 0,r=L(e,"limit")??void 0;return t||s||i||void 0!==r?{before:t,after:s,anchor:i,limit:r}:void 0}(e.params));case"getQueryIndex":return this.getQueryIndex(A(r));case"watchPath":return this.getSessionWatchPath(A(r));case"startRun":return this.startRun(A(r),k(e.params,"input")||"",M(e.params.images),U(e.params.controller),void 0,void 0,void 0,function(e){let t;let s=e.runOverrides;if(!s||"object"!=typeof s)return;let i=s.model;i&&"object"==typeof i&&"string"==typeof i.id&&""!==i.id&&(t={id:i.id,..."string"==typeof i.providerID&&""!==i.providerID?{providerID:i.providerID}:{}});let r=V.find(e=>e===s.reasoningEffort);if(t||r)return{...t?{model:t}:{},...r?{reasoningEffort:r}:{}}}(e.params));case"listModels":return this.listModels(q(e.params,"agentType"));case"snapshot":return this.snapshot(A(r),L(e.params,"afterSequence")??0);case"getGoals":return this.getGoals(A(r),U(e.params.controller));case"enqueueGoal":return this.enqueueGoal(A(r),k(e.params,"objective")||"",k(e.params,"sourceMessageId")||void 0,U(e.params.controller));case"enqueueMessage":return this.enqueueMessage(A(r),{sourceMessageId:P(e.params,"sourceMessageId"),content:P(e.params,"content"),messagePayload:D(e.params.messagePayload)},U(e.params.controller));case"reorderGoals":return this.reorderGoals(A(r),M(e.params.orderedIds)??[]);case"reorderMessages":return this.reorderMessages(A(r),M(e.params.orderedIds)??[]);case"updateMessage":return this.updateMessage(A(r),P(e.params,"messageId"),P(e.params,"content"),D(e.params.messagePayload));case"cancelMessage":return this.cancelMessage(A(r),P(e.params,"messageId"));case"steerMessage":return this.steerMessage(A(r),P(e.params,"messageId"));case"cancelGoal":return this.cancelGoal(A(r),k(e.params,"goalId")||"",U(e.params.controller));case"answer":return this.answerQuestion(k(e.params,"questionId")||"",{answer:k(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(A(r),k(e.params,"input")||"");case"setPermissionMode":return this.setPermissionMode(A(r),(0,d.Ny)(e.params.permissionMode));case"handoff":return this.handoff(A(r),U(e.params.controller));default:throw new v.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)}
228
+ `)}}class F{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 getQueryIndex(e){return this.request("getQueryIndex",{sessionId:e})}async getSessionWatchPath(e){return this.request("watchPath",{sessionId:e})}async startRun(e,t,s,i="web",r){return this.request("startRun",{sessionId:e,input:t,images:s,controller:i,...r?{runOverrides:r}:{}})}async listModels(e){return this.request("listModels",{agentType:e})}async *run(e,t,s,i,r,a="desktop",n){let o=await this.startRun(e,t,s,a,n);yield{type:"run_admitted",_nativeRunId:o.runId,_nativeSequence:0};let l=new u.K,d=await this.subscribe(e,0,e=>{e.runId===o.runId&&(l.push({...e.event,_nativeRunId:e.runId,_nativeSequence:e.sequence}),C(e.event)&&l.close())});try{for await(let e of l)yield e}finally{d()}}async subscribe(e,t,s){await this.ensureHost();let i=await W((0,l.join)(this.directory,$)),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(x(t.error)):"type"in t&&"event"===t.type&&t.event&&s(t.event)}catch{r(new v.n("Malformed broker response","NATIVE_PROTOCOL_ERROR"))}t=o.indexOf("\n")}}),i.once("error",e=>r(e)),i.once("close",()=>{n||r(new v.n("Native runtime broker disconnected","RUNTIME_UNAVAILABLE"))})});return i.write(`${JSON.stringify({id:a,method:"subscribe",params:{sessionId:e,afterSequence:t}})}
229
+ `),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 enqueueMessage(e,t,s="web"){return this.request("enqueueMessage",{sessionId:e,...t,controller:s})}async reorderGoals(e,t){return this.request("reorderGoals",{sessionId:e,orderedIds:[...t]})}async reorderMessages(e,t){return this.request("reorderMessages",{sessionId:e,orderedIds:[...t]})}async updateMessage(e,t,s,i){return this.request("updateMessage",{sessionId:e,messageId:t,content:s,messagePayload:i})}async cancelMessage(e,t){return this.request("cancelMessage",{sessionId:e,messageId:t})}async steerMessage(e,t){return this.request("steerMessage",{sessionId:e,messageId: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 v.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");let t=this.directory,s=(0,l.join)(t,$);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 j(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 W((0,l.join)(this.directory,$)),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(x(e.error))}catch{l(new v.n("Malformed broker response","NATIVE_PROTOCOL_ERROR"))}}),s.once("error",e=>l(e)),s.once("close",()=>{o||l(new v.n("Native runtime broker disconnected","RUNTIME_UNAVAILABLE"))}),s.write(`${JSON.stringify({id:i,method:e,params:t})}
230
+ `)})}}function E(e={}){return new F(e)}function b(e,t,s){let i=new h.b({executable:e||"codex"}),r=new g.tX({client:i,codexExecutable:e||"codex",onApprovalResolved:t?.onApprovalResolved}),a=t?.codexSessionCatalogRepository?new f.c(r,new m.VK({sessionRoot:(0,l.join)(process.env.CODEX_HOME?.trim()||(0,l.join)((0,o.homedir)(),".codex"),"sessions"),readerVersion:"0.153.0",repository:t.codexSessionCatalogRepository})):void 0;a?.start();let n=new w.O({executable:s||"opencode",unavailableError:process.env.AGENT_OPENCODE_RUNTIME_ERROR});return new I.V([r,new p.IW,new y.nI({server:n,executable:s||"opencode",unavailableError:process.env.AGENT_OPENCODE_RUNTIME_ERROR,onApprovalResolved:t?.onApprovalResolved})],()=>Promise.resolve([]),t?.importedWorkspaceRepository,a)}function T(e){let t;try{t=(0,_.V)(e)}catch(t){if(t instanceof v.n)throw t;throw new v.n(`Invalid native session id: ${e}`,"INVALID_SESSION_ID")}if("customer-agent"===t.agentType)throw new v.n("Customer Agent sessions are not handled by the native broker","INVALID_SESSION_ID");return t}function N(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 O(e){return{workspaceId:e.workspace_id,agentType:e.agent_type,normalizedPath:e.normalized_path,name:e.name,createdAt:e.created_at}}function R(e,t){return{...e,cwd:e.cwd||t.cwd,projectId:e.projectId??t.projectId}}function C(e){return"done"===e.type||"error"===e.type}function x(e){let t=e?.code;return t&&["INVALID_SESSION_ID","SESSION_NOT_FOUND","SESSION_OCCUPIED","SESSION_ALREADY_RUNNING","RUNTIME_UNAVAILABLE","OPERATION_NOT_SUPPORTED","APPROVAL_EXPIRED","CODEX_SESSION_VERSION_INCOMPATIBLE","STALE_SESSION_ANCHOR","NATIVE_PROTOCOL_ERROR"].includes(t)?new v.n(e?.message||"Native runtime broker failed",t):new v.n(e?.message||"Native runtime broker failed","NATIVE_PROTOCOL_ERROR")}function A(e){if(!e)throw new v.n("sessionId is required","INVALID_SESSION_ID");return e}function k(e,t){return"string"==typeof e[t]?e[t]:null}function P(e,t){let s=k(e,t);if(!s)throw new v.n(`${t} is required`,"INVALID_SESSION_ID");return s}function L(e,t){return"number"==typeof e[t]&&Number.isSafeInteger(e[t])?e[t]:null}function M(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)?e:void 0}function D(e){if(!e||"object"!=typeof e)return;let t=M(e.images),s=M(e.agentIds),i="string"==typeof e.agentName?e.agentName:void 0;return{...t?.length?{images:t}:{},...s?.length?{agentIds:s}:{},...i?{agentName:i}:{}}}function q(e,t){let s=k(e,t);if("codex"===s||"claude-code"===s||"opencode"===s)return s;throw new v.n("A native agent type is required","INVALID_SESSION_ID")}function U(e){return"desktop"===e||"web"===e?e:"web"}let V=["low","medium","high","xhigh","max"];function W(e){return new Promise((t,s)=>{let i=(0,n.createConnection)(e),r=setTimeout(()=>{i.destroy(),s(new v.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 g=(0,l.promisify)(i.execFile),y="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 g(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!==y)throw Error(`OpenCode ${s} at ${t} is incompatible; AgentRoam requires ${y}`);return s}(`${e}
231
+ ${t}`,this.executable)}}catch(e){return{agentType:this.agentType,available:!1,label:"OpenCode",error:v(e)}}}async listModels(){let e=await this.getClient(),t=await e.config.providers({throwOnError:!0}),s=t.data?.providers??[],i=[];for(let e of s)if(e?.id)for(let[t,s]of Object.entries(e.models??{}))t&&i.push({id:t,providerID:e.id,displayName:s?.name||`${e.id}/${t}`});return i}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,_(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),_(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),{..._(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=v(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),_(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),_(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_ALREADY_RUNNING");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 d=(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},...d],...n?.model?.id&&n.model.providerID?{model:{providerID:n.model.providerID,modelID:n.model.id}}:{}},throwOnError:!0}),l))yield s}catch(e){yield{type:"error",message:v(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,v(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,v(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:v(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,v(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 _(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 v(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,{D:()=>d,V:()=>l});var i=s(9411),r=s(1322),a=s(5779),n=s(2557),o=s(132);class l{constructor(e,t,s,i){for(let s of(this.listProjects=t,this.codexCompatibility=i,this.adapters=new Map,this.activeSessionIds=new Set,this.healthCache=[],this.discoveryPromise=null,this.detailCache=new Map,this.queryIndexCache=new r.pG,e))this.adapters.set(s.agentType,s);this.workspaceIndex=new n.Vk(e,s,process.platform,i?e=>i.supplement(e):void 0)}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 listModels(e){let t=this.adapters.get(e);if(!t||!t.listModels)throw new o.n(`Runtime ${e} does not expose a model list`,"OPERATION_NOT_SUPPORTED");return t.listModels()}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.queryIndexCache.clear(),this.list(e)}invalidate(e){this.detailCache.delete(e),this.queryIndexCache.invalidate(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{let s=await t.discoverSessions();return("codex"===t.agentType&&this.codexCompatibility?this.codexCompatibility.supplement(s):s).map(t=>u(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,d(t));return(this.queryIndexCache.getOrCreate(e,s.messages),t)?{...s,...(0,r.MO)(s.messages,s.events,t)}:s}async getQueryIndex(e){let t=await this.getUnpaginated(e,!0);return this.queryIndexCache.getOrCreate(e,t.messages)}async getUnpaginated(e,t=!1){let{adapter:s,nativeSessionId:i}=this.resolveAdapter(e),r=(t?this.detailCache.get(e):void 0)??await ("codex"===s.agentType&&this.codexCompatibility?.isSupplemental(i)?this.codexCompatibility.readSupplemental(i):s.getSession(i));return this.cacheDetail(e,r),u(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_ALREADY_RUNNING");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 archive(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.archiveSession)throw new o.n("This session cannot be archived","OPERATION_NOT_SUPPORTED");await t.archiveSession(s),this.invalidate(e)}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(){this.codexCompatibility?.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){return!!(e?.before||e?.after||e?.anchor)}function u(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:()=>_});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 v=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()}listModels(e){return this.runtime.listModels(e)}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 y(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 y(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)}async getQueryIndex(e){if(this.runtime.getQueryIndex)return this.runtime.getQueryIndex(e);let t=await this.runtime.get(e),{buildSessionQueryIndex:i}=await Promise.resolve().then(s.bind(s,1322));return i(e,t.messages)}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",r){if(!this.runtime.startRun)throw new u.n("Native runtime broker is unavailable","RUNTIME_UNAVAILABLE");return this.runtime.startRun(e,t,s,i,r)}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")}async enqueueMessage(e,t,s="web"){if(!this.runtime.enqueueMessage)throw new u.n("Message queue is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.enqueueMessage(e,t,s)}async reorderMessages(e,t){if(!this.runtime.reorderMessages)throw new u.n("Message queue is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.reorderMessages(e,t)}async updateMessage(e,t,s,i){if(!this.runtime.updateMessage)throw new u.n("Message queue is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.updateMessage(e,t,s,i)}async cancelMessage(e,t){if(!this.runtime.cancelMessage)throw new u.n("Message queue is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.cancelMessage(e,t)}async steerMessage(e,t){if(!this.runtime.steerMessage)throw new u.n("Message queue is unavailable","OPERATION_NOT_SUPPORTED");return this.runtime.steerMessage(e,t)}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(!v.__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)());v.__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 v.__nativeRuntimeService}function f(e,t,s=process.platform){let{projectId:i,...r}=e;if(!e.cwd)return r;let a=g(e.cwd,s),o="win32"===s?n.win32.sep:n.sep,l=t.filter(e=>e.description).map(e=>({project:e,path:g(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 g(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 y(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 _(e){if(e instanceof u.n)switch(e.code){case"SESSION_NOT_FOUND":return 404;case"SESSION_OCCUPIED":case"SESSION_ALREADY_RUNNING":case"APPROVAL_EXPIRED":case"CODEX_SESSION_VERSION_INCOMPATIBLE":case"STALE_SESSION_ANCHOR":return 409;case"RUNTIME_UNAVAILABLE":return 503;case"OPERATION_NOT_SUPPORTED":return 405;default:return 400}return 500}i()}catch(e){i(e)}})}};