agentroam-runtime-darwin-arm64 0.2.0-preview.21 → 0.2.0-preview.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/manifest.json +2 -2
- package/package.json +1 -1
- package/runtime/.next/BUILD_ID +1 -1
- package/runtime/.next/app-build-manifest.json +6 -6
- package/runtime/.next/app-path-routes-manifest.json +1 -1
- package/runtime/.next/build-manifest.json +3 -3
- package/runtime/.next/prerender-manifest.json +1 -1
- package/runtime/.next/required-server-files.json +1 -1
- package/runtime/.next/server/app/_not-found/page.js +1 -1
- package/runtime/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/runtime/.next/server/app/_not-found.html +1 -1
- package/runtime/.next/server/app/_not-found.rsc +1 -1
- package/runtime/.next/server/app/api/agent/abort/route.js +1 -1
- package/runtime/.next/server/app/api/agent/answer/route.js +1 -1
- package/runtime/.next/server/app/api/agent/harness/status/route.js +1 -1
- package/runtime/.next/server/app/api/agent/model/route.js +1 -1
- package/runtime/.next/server/app/api/agent/models/route.js +1 -1
- package/runtime/.next/server/app/api/agent/run/route.js +1 -1
- package/runtime/.next/server/app/api/agent/runtime-health/route.js +1 -1
- package/runtime/.next/server/app/api/agent/steer/route.js +1 -1
- package/runtime/.next/server/app/api/agent/stream/route.js +2 -2
- package/runtime/.next/server/app/api/agent-workspaces/[workspaceId]/sessions/route.js +1 -1
- package/runtime/.next/server/app/api/agent-workspaces/route.js +1 -1
- package/runtime/.next/server/app/api/auth/verify/route.js +1 -1
- package/runtime/.next/server/app/api/business/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/connect/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/disconnect/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/servers/route.js +1 -1
- package/runtime/.next/server/app/api/memory/[key]/route.js +1 -1
- package/runtime/.next/server/app/api/memory/route.js +1 -1
- package/runtime/.next/server/app/api/plugins/load/route.js +1 -1
- package/runtime/.next/server/app/api/projects/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/projects/check/route.js +1 -1
- package/runtime/.next/server/app/api/projects/directories/route.js +1 -1
- package/runtime/.next/server/app/api/projects/roots/route.js +1 -1
- package/runtime/.next/server/app/api/projects/route.js +1 -1
- package/runtime/.next/server/app/api/remote-tools/register/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/changes/route.js +2 -2
- package/runtime/.next/server/app/api/sessions/[id]/fork/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/goals/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/handoff/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/query-index/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/release/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/tool-result/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/route.js +1 -1
- package/runtime/.next/server/app/api/settings/route.js +1 -1
- package/runtime/.next/server/app/api/skills/route.js +1 -1
- package/runtime/.next/server/app/api/tools/route.js +1 -1
- package/runtime/.next/server/app/api/update/check/route.js +1 -1
- package/runtime/.next/server/app/api/update/install/route.js +1 -1
- package/runtime/.next/server/app/api/update/status/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/login/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/logout/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/revoke-all/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/setup/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/status/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/bootstrap/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/device-state/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/history/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/preferences/route.js +1 -1
- package/runtime/.next/server/app/web/page.js +2 -2
- package/runtime/.next/server/app/web/page_client-reference-manifest.js +1 -1
- package/runtime/.next/server/app/web.html +1 -1
- package/runtime/.next/server/app/web.rsc +3 -3
- package/runtime/.next/server/app-paths-manifest.json +19 -19
- package/runtime/.next/server/chunks/1322.js +1 -1
- package/runtime/.next/server/chunks/2083.js +1 -1
- package/runtime/.next/server/chunks/5303.js +1 -1
- package/runtime/.next/server/middleware-build-manifest.js +1 -1
- package/runtime/.next/server/pages/404.html +1 -1
- package/runtime/.next/server/pages/500.html +1 -1
- package/runtime/.next/server/pages-manifest.json +1 -1
- package/runtime/.next/server/server-reference-manifest.json +1 -1
- package/runtime/.next/static/chunks/app/web/{error-9b5f82c29dc27335.js → error-828d278147a0619d.js} +1 -1
- package/runtime/.next/static/chunks/app/web/{page-16895961b998f8df.js → page-93b87fd495171494.js} +1 -1
- package/runtime/.next/static/chunks/{main-app-e3fd18ce9c4c0d03.js → main-app-07d67f2d4e96ecb8.js} +1 -1
- package/runtime/lib/remote-control/remote-authorization.mjs +65 -12
- package/runtime/lib/remote-control/webrtc-video.mjs +12 -3
- package/runtime/native/AgentRoam Remote Desktop.app/Contents/MacOS/agentroam-remote-desktop +0 -0
- package/runtime/node_modules/.package-lock.json +84 -84
- package/runtime/node_modules/@agent/core/dist/domain/browser-live/BrowserLiveRegistry.d.ts +43 -0
- package/runtime/node_modules/@agent/core/dist/domain/browser-live/BrowserLiveRegistry.test.d.ts +2 -0
- package/runtime/node_modules/@agent/core/dist/domain/browser-live/entities.d.ts +57 -0
- package/runtime/node_modules/@agent/core/dist/domain/live-view/live-view-registry.d.ts.map +1 -1
- package/runtime/node_modules/@agent/core/dist/index.js +4 -2
- package/runtime/node_modules/@agent/core/dist/index.js.map +3 -3
- package/runtime/package-lock.json +189 -189
- package/runtime/webapp/dist/assets/App-C0GaUX7E.js +381 -0
- package/runtime/webapp/dist/assets/{abnfDiagram-VCTEODGH-BNxk5qEZ.js → abnfDiagram-VCTEODGH-DFIVS5-b.js} +1 -1
- package/runtime/webapp/dist/assets/{arc-7MQbjMvc.js → arc-BR_jY5YA.js} +1 -1
- package/runtime/webapp/dist/assets/{architectureDiagram-5GKGNRK7-Dhg4Rz1D.js → architectureDiagram-5GKGNRK7-B_RjH8A7.js} +1 -1
- package/runtime/webapp/dist/assets/{blockDiagram-I7D4REHJ-DeJHr92S.js → blockDiagram-I7D4REHJ-BS7yaS6P.js} +1 -1
- package/runtime/webapp/dist/assets/{c4Diagram-7LVT6UL2-RA8xRbEK.js → c4Diagram-7LVT6UL2-CSFzzphk.js} +1 -1
- package/runtime/webapp/dist/assets/channel-D_GjJ9-f.js +1 -0
- package/runtime/webapp/dist/assets/{chunk-2Q5K7J3B-CzoEDy2v.js → chunk-2Q5K7J3B-lxf-31fr.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-5VM5RSS4-IasmnKPT.js → chunk-5VM5RSS4-CealgGAH.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-F27PBJKO-ClQmWB2a.js → chunk-F27PBJKO-BVUWtnPQ.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-IMKFNOWR-BeWBx5Wn.js → chunk-IMKFNOWR-C9CDXZmG.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-JWPE2WC7-TcEEZ4Dp.js → chunk-JWPE2WC7-CBIKc-82.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-POPQ4Y6H-DuWXzzSb.js → chunk-POPQ4Y6H-H46jF2zC.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-SVP7TREG-D2X9Pa1W.js → chunk-SVP7TREG-BWLkgj_W.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-TICWLB2K-D_-XYQ_R.js → chunk-TICWLB2K-D4lbsBHo.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-XXDRQBXY-B2mHmyk9.js → chunk-XXDRQBXY-DixiVi8X.js} +1 -1
- package/runtime/webapp/dist/assets/classDiagram-ZZMXUADV-BbKxNRrL.js +1 -0
- package/runtime/webapp/dist/assets/classDiagram-v2-VYDZK3BY-BbKxNRrL.js +1 -0
- package/runtime/webapp/dist/assets/{cose-bilkent-JH36ORCC-OmMALi3i.js → cose-bilkent-JH36ORCC-DApgY-7v.js} +1 -1
- package/runtime/webapp/dist/assets/{cynefin-OW5HDTMX-BVhxjnGZ.js → cynefin-OW5HDTMX-wPkyEnRo.js} +1 -1
- package/runtime/webapp/dist/assets/{cynefinDiagram-5FMLGOSQ-8EafeZWa.js → cynefinDiagram-5FMLGOSQ-BL3nX8zr.js} +1 -1
- package/runtime/webapp/dist/assets/{dagre-GXQ25YYZ-BlMjveyN.js → dagre-GXQ25YYZ-C-ST5Gq6.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-S7CK7UJ4-BTgDeYAz.js → diagram-S7CK7UJ4-1Uf0VNoU.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-UQ7AKVKN-9m-QUpEs.js → diagram-UQ7AKVKN-BqQU5Gdv.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-VSXAHHWV-BYWenf8W.js → diagram-VSXAHHWV-C59hTOGw.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-VX7I27RA-DQ-PRQyX.js → diagram-VX7I27RA-9Q55OM5Y.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-Z3DM3KII-BFCpyvaL.js → diagram-Z3DM3KII-CynlxwLb.js} +1 -1
- package/runtime/webapp/dist/assets/{ebnfDiagram-PWID7BFC-Ds9oV_wz.js → ebnfDiagram-PWID7BFC-Clg7fTnt.js} +1 -1
- package/runtime/webapp/dist/assets/{erDiagram-RLTQ6QDP-ncaaStop.js → erDiagram-RLTQ6QDP-BRtMTjkq.js} +1 -1
- package/runtime/webapp/dist/assets/{flowDiagram-HODETNUW-wL7U3M2L.js → flowDiagram-HODETNUW-1NtZ9wGO.js} +1 -1
- package/runtime/webapp/dist/assets/{ganttDiagram-EL5Y4UJY-CVZIk8qz.js → ganttDiagram-EL5Y4UJY-BqtMVkoY.js} +1 -1
- package/runtime/webapp/dist/assets/{gitGraphDiagram-WWUBYQGX-CGjtUEFY.js → gitGraphDiagram-WWUBYQGX-D-ugp1Bz.js} +1 -1
- package/runtime/webapp/dist/assets/{index-CixxJ3A7.js → index-Cg-anTNr.js} +29 -29
- package/runtime/webapp/dist/assets/{infoDiagram-27XIBGKW-BqTzY6Bv.js → infoDiagram-27XIBGKW-BbmiUqFV.js} +1 -1
- package/runtime/webapp/dist/assets/{ishikawaDiagram-5VMMS53U-9AARy1zU.js → ishikawaDiagram-5VMMS53U-DvsCcWwa.js} +1 -1
- package/runtime/webapp/dist/assets/{journeyDiagram-3NMN7TZE-D3w-levY.js → journeyDiagram-3NMN7TZE-yNHLBbVt.js} +1 -1
- package/runtime/webapp/dist/assets/{kanban-definition-UXKFOSKX-CNvdBbcg.js → kanban-definition-UXKFOSKX-C17XKWBo.js} +1 -1
- package/runtime/webapp/dist/assets/{layout-l0aDluv6.js → layout-Dhqc3tGq.js} +1 -1
- package/runtime/webapp/dist/assets/{linear-BlLgYv8s.js → linear-C2_mlhLl.js} +1 -1
- package/runtime/webapp/dist/assets/{mermaid.core-UNYsT27K.js → mermaid.core-CjC7QuvE.js} +5 -5
- package/runtime/webapp/dist/assets/{mindmap-definition-YA3MSWOX-BiVsBQL9.js → mindmap-definition-YA3MSWOX-D7AKW2qI.js} +1 -1
- package/runtime/webapp/dist/assets/{pegDiagram-XKGWAZYB-kr19ZOFB.js → pegDiagram-XKGWAZYB-BAI26fj8.js} +1 -1
- package/runtime/webapp/dist/assets/{pieDiagram-E7YTZNPT-BKWCGLlM.js → pieDiagram-E7YTZNPT-C_4G2czx.js} +1 -1
- package/runtime/webapp/dist/assets/{quadrantDiagram-AXDQQJYC-B1oUT2Jo.js → quadrantDiagram-AXDQQJYC-BhOZnXFN.js} +1 -1
- package/runtime/webapp/dist/assets/{railroadDiagram-O6MQD6OU-HSe2vXxQ.js → railroadDiagram-O6MQD6OU-760zGjdr.js} +1 -1
- package/runtime/webapp/dist/assets/{requirementDiagram-BXWQKSXE-Cy8adj_C.js → requirementDiagram-BXWQKSXE-D0-agCrc.js} +1 -1
- package/runtime/webapp/dist/assets/{sankeyDiagram-P5KCCOFB-tnBEmP5l.js → sankeyDiagram-P5KCCOFB-CsHjbmcp.js} +1 -1
- package/runtime/webapp/dist/assets/{sequenceDiagram-WJ2MYXX4-DvOTKmyz.js → sequenceDiagram-WJ2MYXX4-Ccp7FnLK.js} +1 -1
- package/runtime/webapp/dist/assets/{sizeCapture-INFHLROL-Da7A6hqr.js → sizeCapture-INFHLROL-DFCk9Vjd.js} +1 -1
- package/runtime/webapp/dist/assets/{stateDiagram-D77RDMKH-BU17k_M-.js → stateDiagram-D77RDMKH-tFA-WlZT.js} +1 -1
- package/runtime/webapp/dist/assets/stateDiagram-v2-MP3YSRHH-CA4qjX_b.js +1 -0
- package/runtime/webapp/dist/assets/{swimlanes-42K2YHIH-DZZPRxnW.js → swimlanes-42K2YHIH-Bh-owCha.js} +1 -1
- package/runtime/webapp/dist/assets/swimlanesDiagram-VR7AAH4N-DrldJDwD.js +8 -0
- package/runtime/webapp/dist/assets/{timeline-definition-24CTP7MA-26Xh93Et.js → timeline-definition-24CTP7MA-D5CQ3vgW.js} +1 -1
- package/runtime/webapp/dist/assets/{vennDiagram-4TSXK5OY-Q4-BkJH1.js → vennDiagram-4TSXK5OY-1m-k4Zip.js} +1 -1
- package/runtime/webapp/dist/assets/{wardleyDiagram-VM6X3IG4-DlUP-PlT.js → wardleyDiagram-VM6X3IG4-C5agAk3M.js} +1 -1
- package/runtime/webapp/dist/assets/{web-DWyw2SAG.js → web-CzXjoC1h.js} +1 -1
- package/runtime/webapp/dist/assets/{web-ueoOhAeL.js → web-DseRebF6.js} +1 -1
- package/runtime/webapp/dist/assets/{xychartDiagram-S5SC5T6Z-BQZRjKtR.js → xychartDiagram-S5SC5T6Z-EEKnPDSd.js} +1 -1
- package/runtime/webapp/dist/index.html +1 -1
- package/runtime/webapp/dist/assets/App-Cso_5v1O.js +0 -381
- package/runtime/webapp/dist/assets/channel-AsHr5ZE0.js +0 -1
- package/runtime/webapp/dist/assets/classDiagram-ZZMXUADV-BZj1pbnq.js +0 -1
- package/runtime/webapp/dist/assets/classDiagram-v2-VYDZK3BY-BZj1pbnq.js +0 -1
- package/runtime/webapp/dist/assets/stateDiagram-v2-MP3YSRHH-BROH63Ny.js +0 -1
- package/runtime/webapp/dist/assets/swimlanesDiagram-VR7AAH4N-B4lr9wuD.js +0 -8
- /package/runtime/.next/static/{6OR2fRy79-A-DrqiN3FNa → ZqeC5NkIDDyPiS-mzOs28}/_buildManifest.js +0 -0
- /package/runtime/.next/static/{6OR2fRy79-A-DrqiN3FNa → ZqeC5NkIDDyPiS-mzOs28}/_ssgManifest.js +0 -0
|
@@ -1,53 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"/_not-found/page": "app/_not-found/page.js",
|
|
3
3
|
"/api/auth/verify/route": "app/api/auth/verify/route.js",
|
|
4
|
-
"/api/mcp/connect/route": "app/api/mcp/connect/route.js",
|
|
5
4
|
"/api/mcp/disconnect/route": "app/api/mcp/disconnect/route.js",
|
|
6
|
-
"/api/
|
|
5
|
+
"/api/mcp/connect/route": "app/api/mcp/connect/route.js",
|
|
6
|
+
"/api/memory/[key]/route": "app/api/memory/[key]/route.js",
|
|
7
7
|
"/api/mcp/servers/route": "app/api/mcp/servers/route.js",
|
|
8
8
|
"/api/memory/route": "app/api/memory/route.js",
|
|
9
|
-
"/api/projects/check/route": "app/api/projects/check/route.js",
|
|
10
9
|
"/api/projects/[id]/route": "app/api/projects/[id]/route.js",
|
|
10
|
+
"/api/plugins/load/route": "app/api/plugins/load/route.js",
|
|
11
|
+
"/api/projects/check/route": "app/api/projects/check/route.js",
|
|
11
12
|
"/api/projects/roots/route": "app/api/projects/roots/route.js",
|
|
12
13
|
"/api/projects/directories/route": "app/api/projects/directories/route.js",
|
|
13
|
-
"/api/memory/[key]/route": "app/api/memory/[key]/route.js",
|
|
14
|
-
"/api/remote-tools/register/route": "app/api/remote-tools/register/route.js",
|
|
15
14
|
"/api/projects/route": "app/api/projects/route.js",
|
|
15
|
+
"/api/remote-tools/register/route": "app/api/remote-tools/register/route.js",
|
|
16
16
|
"/api/skills/route": "app/api/skills/route.js",
|
|
17
17
|
"/api/tools/route": "app/api/tools/route.js",
|
|
18
|
-
"/api/web-auth/logout/route": "app/api/web-auth/logout/route.js",
|
|
19
|
-
"/api/web-auth/setup/route": "app/api/web-auth/setup/route.js",
|
|
20
18
|
"/api/web-auth/login/route": "app/api/web-auth/login/route.js",
|
|
21
19
|
"/api/web-auth/revoke-all/route": "app/api/web-auth/revoke-all/route.js",
|
|
20
|
+
"/api/web-auth/setup/route": "app/api/web-auth/setup/route.js",
|
|
22
21
|
"/api/web-console/history/route": "app/api/web-console/history/route.js",
|
|
23
22
|
"/api/web-console/preferences/route": "app/api/web-console/preferences/route.js",
|
|
23
|
+
"/api/web-auth/logout/route": "app/api/web-auth/logout/route.js",
|
|
24
|
+
"/web/page": "app/web/page.js",
|
|
24
25
|
"/api/agent-workspaces/route": "app/api/agent-workspaces/route.js",
|
|
25
|
-
"/api/agent/model/route": "app/api/agent/model/route.js",
|
|
26
|
-
"/api/agent/abort/route": "app/api/agent/abort/route.js",
|
|
27
26
|
"/api/agent-workspaces/[workspaceId]/sessions/route": "app/api/agent-workspaces/[workspaceId]/sessions/route.js",
|
|
27
|
+
"/api/agent/abort/route": "app/api/agent/abort/route.js",
|
|
28
|
+
"/api/agent/answer/route": "app/api/agent/answer/route.js",
|
|
29
|
+
"/api/agent/model/route": "app/api/agent/model/route.js",
|
|
28
30
|
"/api/agent/harness/status/route": "app/api/agent/harness/status/route.js",
|
|
29
|
-
"/api/agent/runtime-health/route": "app/api/agent/runtime-health/route.js",
|
|
30
31
|
"/api/agent/models/route": "app/api/agent/models/route.js",
|
|
32
|
+
"/api/agent/runtime-health/route": "app/api/agent/runtime-health/route.js",
|
|
31
33
|
"/api/agent/steer/route": "app/api/agent/steer/route.js",
|
|
32
|
-
"/api/agent/
|
|
34
|
+
"/api/agent/run/route": "app/api/agent/run/route.js",
|
|
33
35
|
"/api/business/route": "app/api/business/route.js",
|
|
34
36
|
"/api/sessions/[id]/fork/route": "app/api/sessions/[id]/fork/route.js",
|
|
35
37
|
"/api/sessions/[id]/changes/route": "app/api/sessions/[id]/changes/route.js",
|
|
36
38
|
"/api/agent/stream/route": "app/api/agent/stream/route.js",
|
|
39
|
+
"/api/sessions/[id]/goals/route": "app/api/sessions/[id]/goals/route.js",
|
|
40
|
+
"/api/sessions/[id]/release/route": "app/api/sessions/[id]/release/route.js",
|
|
41
|
+
"/api/sessions/[id]/route": "app/api/sessions/[id]/route.js",
|
|
37
42
|
"/api/sessions/[id]/handoff/route": "app/api/sessions/[id]/handoff/route.js",
|
|
38
|
-
"/api/agent/run/route": "app/api/agent/run/route.js",
|
|
39
43
|
"/api/sessions/[id]/query-index/route": "app/api/sessions/[id]/query-index/route.js",
|
|
40
|
-
"/api/sessions/
|
|
44
|
+
"/api/sessions/route": "app/api/sessions/route.js",
|
|
41
45
|
"/api/sessions/[id]/tool-result/route": "app/api/sessions/[id]/tool-result/route.js",
|
|
42
46
|
"/api/settings/route": "app/api/settings/route.js",
|
|
43
|
-
"/api/sessions/[id]/release/route": "app/api/sessions/[id]/release/route.js",
|
|
44
|
-
"/api/update/check/route": "app/api/update/check/route.js",
|
|
45
|
-
"/api/sessions/route": "app/api/sessions/route.js",
|
|
46
47
|
"/api/update/status/route": "app/api/update/status/route.js",
|
|
47
|
-
"/
|
|
48
|
+
"/api/update/check/route": "app/api/update/check/route.js",
|
|
48
49
|
"/api/update/install/route": "app/api/update/install/route.js",
|
|
49
|
-
"/api/sessions/[id]/route": "app/api/sessions/[id]/route.js",
|
|
50
|
-
"/api/web-auth/status/route": "app/api/web-auth/status/route.js",
|
|
51
50
|
"/api/web-console/bootstrap/route": "app/api/web-console/bootstrap/route.js",
|
|
51
|
+
"/api/web-auth/status/route": "app/api/web-auth/status/route.js",
|
|
52
52
|
"/api/web-console/device-state/route": "app/api/web-console/device-state/route.js"
|
|
53
53
|
}
|
|
@@ -534,6 +534,6 @@ ${e.entry.content}`;if(a+t.length>n)break;i.push(t),a+=t.length}return i.join(`
|
|
|
534
534
|
DELETE FROM anonymous_ws_nonces
|
|
535
535
|
WHERE nonce_hash = ? AND expires_at > ?
|
|
536
536
|
RETURNING user_id
|
|
537
|
-
`).get(il(e),t);return r?.user_id??null}findPrincipal(){return this.db.prepare("SELECT id, username_display FROM users ORDER BY created_at, id LIMIT 1").get()}}class ic{constructor(e){this.db=s9(e).db}markStaleTerminalsExited(e){return this.db.prepare("UPDATE terminal_tabs SET status='exited', exited_at=? WHERE status IN ('active','detached')").run(e).changes}listTabs(e){return this.db.prepare("SELECT * FROM terminal_tabs WHERE user_id=? AND status<>'closed' ORDER BY sort_order, created_at").all(e).map(ih)}createTab(e){this.db.prepare("INSERT INTO terminal_tabs (id,user_id,title,shell,start_cwd,current_cwd,status,sort_order,created_at,last_active_at,exited_at,closed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)").run(e.id,e.userId,e.title,e.shell,e.startCwd,e.currentCwd,e.status,e.sortOrder,e.createdAt,e.lastActiveAt,e.exitedAt,e.closedAt)}updateTab(e,t,r){let s={title:"title",currentCwd:"current_cwd",status:"status",sortOrder:"sort_order",lastActiveAt:"last_active_at",exitedAt:"exited_at",closedAt:"closed_at"},i=Object.entries(r).filter(([e])=>s[e]);return!!i.length&&1===this.db.prepare(`UPDATE terminal_tabs SET ${i.map(([e])=>`${s[e]}=?`).join(",")} WHERE id=? AND user_id=?`).run(...i.map(([,e])=>e),e,t).changes}getPreferences(e){let t=this.db.prepare("SELECT * FROM user_preferences WHERE user_id=?").get(e);return t?ip(t):null}savePreferences(e,t){if(null===t)try{return this.db.prepare("INSERT INTO user_preferences (user_id,revision,theme,terminal_font_size,file_button_position_json,keybar_position_json,keybar_hidden,key_order_json,pinned_commands_json,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?)").run(e.userId,e.revision,e.theme,e.terminalFontSize,JSON.stringify(e.fileButtonPosition),JSON.stringify(e.keybarPosition),e.keybarHidden?1:0,JSON.stringify(e.keyOrder),JSON.stringify(e.pinnedCommands),e.updatedAt),!0}catch{return!1}return 1===this.db.prepare("UPDATE user_preferences SET revision=?,theme=?,terminal_font_size=?,file_button_position_json=?,keybar_position_json=?,keybar_hidden=?,key_order_json=?,pinned_commands_json=?,updated_at=? WHERE user_id=? AND revision=?").run(e.revision,e.theme,e.terminalFontSize,JSON.stringify(e.fileButtonPosition),JSON.stringify(e.keybarPosition),e.keybarHidden?1:0,JSON.stringify(e.keyOrder),JSON.stringify(e.pinnedCommands),e.updatedAt,e.userId,t).changes}getDeviceState(e,t){let r=this.db.prepare("SELECT * FROM device_states WHERE user_id=? AND device_id=?").get(e,t);return r?im(r):null}saveDeviceState(e){this.db.prepare("INSERT INTO device_states (user_id,device_id,active_terminal_id,drawer_open,drawer_tab,file_tree_root,file_tree_follow_mode,expanded_paths_json,selected_file,terminal_scroll_json,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(user_id,device_id) DO UPDATE SET active_terminal_id=excluded.active_terminal_id,drawer_open=excluded.drawer_open,drawer_tab=excluded.drawer_tab,file_tree_root=excluded.file_tree_root,file_tree_follow_mode=excluded.file_tree_follow_mode,expanded_paths_json=excluded.expanded_paths_json,selected_file=excluded.selected_file,terminal_scroll_json=excluded.terminal_scroll_json,updated_at=excluded.updated_at").run(e.userId,e.deviceId,e.activeTerminalId,e.drawerOpen?1:0,e.drawerTab,e.fileTreeRoot,e.fileTreeFollowMode?1:0,JSON.stringify(e.expandedPaths),e.selectedFile,JSON.stringify(e.terminalScroll),e.updatedAt)}addHistory(e,t,r,s,i,a=null){let n=r.toLowerCase(),o=this.db.prepare("INSERT INTO command_history (user_id,terminal_id,command,command_normalized,cwd,executed_at,exit_code) VALUES (?,?,?,?,?,?,?)").run(e,t,iy(r),iy(n),s,i,a);this.db.prepare("DELETE FROM command_history WHERE user_id=? AND command_normalized=? AND id<>?").run(e,iy(n),o.lastInsertRowid),this.db.prepare("DELETE FROM command_history WHERE user_id=? AND id NOT IN (SELECT id FROM command_history WHERE user_id=? ORDER BY id DESC LIMIT 5000)").run(e,e)}listHistory(e,t="",r=100,s){let i=`%${t.toLowerCase()}%`,a="AND (exit_code IS NULL OR exit_code=0)",n=s?this.db.prepare(`SELECT * FROM command_history WHERE user_id=? AND terminal_id=? AND command_normalized LIKE ? ${a} ORDER BY id DESC LIMIT ?`).all(e,s,i,r):this.db.prepare(`SELECT * FROM command_history WHERE user_id=? AND command_normalized LIKE ? ${a} ORDER BY id DESC LIMIT ?`).all(e,i,r),o=new Set;return n.filter(e=>!o.has(e.command_normalized)&&(o.add(e.command_normalized),!0)).map(ig)}deleteHistory(e,t){return 1===this.db.prepare("DELETE FROM command_history WHERE id=? AND user_id=?").run(t,e).changes}clearHistory(e,t){return(t?this.db.prepare("DELETE FROM command_history WHERE user_id=? AND terminal_id=?").run(e,t):this.db.prepare("DELETE FROM command_history WHERE user_id=?").run(e)).changes}}var iu=(e,t)=>{try{return JSON.parse(e)}catch{return t}},ih=e=>({id:e.id,userId:e.user_id,title:e.title,shell:e.shell,startCwd:e.start_cwd,currentCwd:e.current_cwd,status:e.status,sortOrder:e.sort_order,createdAt:e.created_at,lastActiveAt:e.last_active_at,exitedAt:e.exited_at,closedAt:e.closed_at}),ip=e=>({userId:e.user_id,revision:e.revision,theme:e.theme,terminalFontSize:e.terminal_font_size,fileButtonPosition:iu(e.file_button_position_json,{}),keybarPosition:iu(e.keybar_position_json,{}),keybarHidden:!!e.keybar_hidden,keyOrder:iu(e.key_order_json,[]),pinnedCommands:function(e){if(null==e)return ej();try{return eF(JSON.parse(e))}catch{return ej()}}(e.pinned_commands_json),updatedAt:e.updated_at}),im=e=>({userId:e.user_id,deviceId:e.device_id,activeTerminalId:e.active_terminal_id,drawerOpen:!!e.drawer_open,drawerTab:e.drawer_tab,fileTreeRoot:e.file_tree_root,fileTreeFollowMode:!!e.file_tree_follow_mode,expandedPaths:iu(e.expanded_paths_json,[]),selectedFile:e.selected_file,terminalScroll:iu(e.terminal_scroll_json,{}),updatedAt:e.updated_at}),ig=e=>({id:e.id,userId:e.user_id,terminalId:e.terminal_id,command:e.command,cwd:e.cwd,executedAt:e.executed_at,exitCode:e.exit_code??null});function iy(e){return/(?:token|password|secret|api[_-]?key)\s*=/.test(e.toLowerCase())?"[REDACTED]":e}class i_ extends Error{constructor(e,t,r){super(t,r),this.name="HostPathError",this.code=e}}function iT(e,t){let r=e?.code;return"ENOENT"===r||"ENOTDIR"===r?new i_("PATH_NOT_FOUND",`路径不存在:${t}`,{cause:e}):new i_("PATH_UNREADABLE",`无法访问路径:${t}`,{cause:e})}function iE(e){let t=(0,l.resolve)(e);try{return u.realpathSync.native(t)}catch(e){throw iT(e,t)}}class ib{constructor(e){let t=[];for(let r of e){let e;if(!r?.trim())continue;let s=iE(r.trim());try{e=(0,u.statSync)(s)}catch(e){throw iT(e,s)}if(!e.isDirectory())throw new i_("PATH_NOT_DIRECTORY",`不是目录:${s}`);t.includes(s)||t.push(s)}if(0===t.length)throw new i_("PATH_UNREADABLE","没有可用的宿主机目录根路径");this.roots=t}static fromEnvironment(e,t){return new ib((e?.trim()?e:t).split(l.delimiter))}assertAllowed(e){if("string"!=typeof e||!e.trim())throw new i_("PATH_NOT_FOUND","路径不能为空");let t=iE(e.trim());if(!this.roots.some(e=>(function(e,t){let r=(0,l.relative)(e,t);return""===r||".."!==r&&!r.startsWith(`..${l.sep}`)&&!(0,l.isAbsolute)(r)})(e,t)))throw new i_("PATH_OUTSIDE_ROOT",`路径不在允许范围内:${t}`);return t}assertDirectory(e){let t;let r=this.assertAllowed(e);try{t=(0,u.statSync)(r)}catch(e){throw iT(e,r)}if(!t.isDirectory())throw new i_("PATH_NOT_DIRECTORY",`不是目录:${r}`);return r}listDirectories(e){let t;let r=this.assertDirectory(e);try{t=(0,u.readdirSync)(r,{withFileTypes:!0})}catch(e){throw iT(e,r)}let s=[];for(let e of t){let t,i;let a=(0,l.resolve)(r,e.name);try{t=this.assertAllowed(a)}catch{continue}try{let e=(0,u.statSync)(t);if(e.isDirectory())i="directory";else{if(!e.isFile())continue;i="file"}}catch{continue}s.push({name:e.name||(0,l.basename)(t),path:t,kind:i,hasChildren:"directory"===i&&this.hasAllowedDirectoryChild(t)})}return s.sort((e,t)=>{if(e.kind!==t.kind)return"directory"===e.kind?-1:1;let r=e.name.startsWith(".");return r!==t.name.startsWith(".")?r?1:-1:e.name.localeCompare(t.name,void 0,{sensitivity:"base"})})}hasAllowedDirectoryChild(e){try{return(0,u.readdirSync)(e,{withFileTypes:!0}).some(t=>{if(!t.isDirectory()&&!t.isSymbolicLink())return!1;try{return this.assertDirectory((0,l.resolve)(e,t.name)),!0}catch{return!1}})}catch{return!1}}}function iv(e){return e.replace(/\b(?:sk|rk)-[A-Za-z0-9_-]{8,}/g,"[REDACTED]").replace(/(bearer\s+)[^\s"']+/gi,"$1[REDACTED]").replace(/((?:api[_-]?key|token|password|secret|authorization|cookie)["']?\s*[:=]\s*["']?)[^\s,"'}]+/gi,"$1[REDACTED]").replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/g,"$1[REDACTED]@")}function iw(e,t=0){return t>6?"[depth limit]":"string"==typeof e?iv(e).slice(0,1600):Array.isArray(e)?e.slice(0,24).map(e=>iw(e,t+1)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).slice(0,40).map(([e,r])=>[e,/api.?key|token$|password|secret|authorization|cookie|images|reasoning/i.test(e)&&!/tokens|ratio/i.test(e)?"[REDACTED]":iw(r,t+1)])):e}function iS(e){let t=e=>Array.isArray(e)?e.map(t):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,r])=>[e,t(r)])):e;return(0,p.createHash)("sha256").update(JSON.stringify(t(e))).digest("hex").slice(0,24)}async function iN(e){for(let t of e)if(t)try{return await (0,m.access)(t,m.constants.X_OK),t}catch{}}async function ik(e){let t=[e,process.cwd()];try{t.push((0,l.dirname)((0,h.fileURLToPath)("file:///private/tmp/agentroam-release21-20260914/packages/core/dist/index.js")))}catch{}for(let e of t){if(!e)continue;let t=e;for(let e=0;e<8;e++){try{return await (0,m.access)((0,l.join)(t,"scripts/harness/daemon.ts")),t}catch{}let e=(0,l.dirname)(t);if(e===t)break;t=e}}}class iI{constructor(e){this.child=null,this.starting=null,this.closed=!1,this.model=null,this.current={state:"stopped"},this.restartCount=0,this.runtimeVersion="unknown",this.onExit=()=>{this.child?.stdin.end(),this.child?.kill("SIGTERM")},this.options=e}get status(){return{...this.current}}setModel(e){}start(){return this.closed||this.child?Promise.resolve():(this.starting||(this.starting=this.launch().catch(()=>{this.current={state:"unavailable",detail:"Companion launch failed"}}).finally(()=>{this.starting=null})),this.starting)}async launch(){if(!1===this.options.enabled||!0!==this.options.enabled&&(process.env.VITEST||"0"===process.env.AGENT_HARNESS_AUTOSTART))return;this.current={state:"starting"};let e=await ik(this.options.sourceRoot),t=await iN([this.options.bunExecutable,process.env.HARNESS_BUN_BINARY,(0,l.join)((0,f.homedir)(),".bun/bin/bun"),"/opt/homebrew/bin/bun"]),r=await iN([this.options.nodeExecutable,process.env.HARNESS_NODE_BINARY,(0,l.join)((0,f.homedir)(),".nvm/versions/node/v22.22.0/bin/node"),"/opt/homebrew/opt/node@22/bin/node"]);if(!e||!t||!r||"darwin"!==process.platform){this.current={state:"unavailable",detail:"Requires a source checkout, Bun, Node 22 and macOS"};return}if(this.closed)return;if("unknown"===this.runtimeVersion)try{this.runtimeVersion=iS(await (0,m.readFile)((0,h.fileURLToPath)("file:///private/tmp/agentroam-release21-20260914/packages/core/dist/index.js"),"utf8"))}catch{}let s=this.options.stateDirectory??(0,l.join)((0,f.homedir)(),".customer-agent-harness"),i=(0,d.spawn)(t,[(0,l.join)(e,"scripts/harness/daemon.ts"),e,s,this.options.owner,r],{cwd:e,env:{...process.env,HARNESS_PARENT_PID:String(process.pid)},stdio:["pipe","pipe","pipe"]});this.child=i,process.removeListener("exit",this.onExit),process.once("exit",this.onExit);let a="";i.stdout.on("data",e=>{let t;for(a=(a+e.toString()).slice(-256e3);(t=a.indexOf(`
|
|
537
|
+
`).get(il(e),t);return r?.user_id??null}findPrincipal(){return this.db.prepare("SELECT id, username_display FROM users ORDER BY created_at, id LIMIT 1").get()}}class ic{constructor(e){this.db=s9(e).db}markStaleTerminalsExited(e){return this.db.prepare("UPDATE terminal_tabs SET status='exited', exited_at=? WHERE status IN ('active','detached')").run(e).changes}listTabs(e){return this.db.prepare("SELECT * FROM terminal_tabs WHERE user_id=? AND status<>'closed' ORDER BY sort_order, created_at").all(e).map(ih)}createTab(e){this.db.prepare("INSERT INTO terminal_tabs (id,user_id,title,shell,start_cwd,current_cwd,status,sort_order,created_at,last_active_at,exited_at,closed_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)").run(e.id,e.userId,e.title,e.shell,e.startCwd,e.currentCwd,e.status,e.sortOrder,e.createdAt,e.lastActiveAt,e.exitedAt,e.closedAt)}updateTab(e,t,r){let s={title:"title",currentCwd:"current_cwd",status:"status",sortOrder:"sort_order",lastActiveAt:"last_active_at",exitedAt:"exited_at",closedAt:"closed_at"},i=Object.entries(r).filter(([e])=>s[e]);return!!i.length&&1===this.db.prepare(`UPDATE terminal_tabs SET ${i.map(([e])=>`${s[e]}=?`).join(",")} WHERE id=? AND user_id=?`).run(...i.map(([,e])=>e),e,t).changes}getPreferences(e){let t=this.db.prepare("SELECT * FROM user_preferences WHERE user_id=?").get(e);return t?ip(t):null}savePreferences(e,t){if(null===t)try{return this.db.prepare("INSERT INTO user_preferences (user_id,revision,theme,terminal_font_size,file_button_position_json,keybar_position_json,keybar_hidden,key_order_json,pinned_commands_json,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?)").run(e.userId,e.revision,e.theme,e.terminalFontSize,JSON.stringify(e.fileButtonPosition),JSON.stringify(e.keybarPosition),e.keybarHidden?1:0,JSON.stringify(e.keyOrder),JSON.stringify(e.pinnedCommands),e.updatedAt),!0}catch{return!1}return 1===this.db.prepare("UPDATE user_preferences SET revision=?,theme=?,terminal_font_size=?,file_button_position_json=?,keybar_position_json=?,keybar_hidden=?,key_order_json=?,pinned_commands_json=?,updated_at=? WHERE user_id=? AND revision=?").run(e.revision,e.theme,e.terminalFontSize,JSON.stringify(e.fileButtonPosition),JSON.stringify(e.keybarPosition),e.keybarHidden?1:0,JSON.stringify(e.keyOrder),JSON.stringify(e.pinnedCommands),e.updatedAt,e.userId,t).changes}getDeviceState(e,t){let r=this.db.prepare("SELECT * FROM device_states WHERE user_id=? AND device_id=?").get(e,t);return r?im(r):null}saveDeviceState(e){this.db.prepare("INSERT INTO device_states (user_id,device_id,active_terminal_id,drawer_open,drawer_tab,file_tree_root,file_tree_follow_mode,expanded_paths_json,selected_file,terminal_scroll_json,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(user_id,device_id) DO UPDATE SET active_terminal_id=excluded.active_terminal_id,drawer_open=excluded.drawer_open,drawer_tab=excluded.drawer_tab,file_tree_root=excluded.file_tree_root,file_tree_follow_mode=excluded.file_tree_follow_mode,expanded_paths_json=excluded.expanded_paths_json,selected_file=excluded.selected_file,terminal_scroll_json=excluded.terminal_scroll_json,updated_at=excluded.updated_at").run(e.userId,e.deviceId,e.activeTerminalId,e.drawerOpen?1:0,e.drawerTab,e.fileTreeRoot,e.fileTreeFollowMode?1:0,JSON.stringify(e.expandedPaths),e.selectedFile,JSON.stringify(e.terminalScroll),e.updatedAt)}addHistory(e,t,r,s,i,a=null){let n=r.toLowerCase(),o=this.db.prepare("INSERT INTO command_history (user_id,terminal_id,command,command_normalized,cwd,executed_at,exit_code) VALUES (?,?,?,?,?,?,?)").run(e,t,iy(r),iy(n),s,i,a);this.db.prepare("DELETE FROM command_history WHERE user_id=? AND command_normalized=? AND id<>?").run(e,iy(n),o.lastInsertRowid),this.db.prepare("DELETE FROM command_history WHERE user_id=? AND id NOT IN (SELECT id FROM command_history WHERE user_id=? ORDER BY id DESC LIMIT 5000)").run(e,e)}listHistory(e,t="",r=100,s){let i=`%${t.toLowerCase()}%`,a="AND (exit_code IS NULL OR exit_code=0)",n=s?this.db.prepare(`SELECT * FROM command_history WHERE user_id=? AND terminal_id=? AND command_normalized LIKE ? ${a} ORDER BY id DESC LIMIT ?`).all(e,s,i,r):this.db.prepare(`SELECT * FROM command_history WHERE user_id=? AND command_normalized LIKE ? ${a} ORDER BY id DESC LIMIT ?`).all(e,i,r),o=new Set;return n.filter(e=>!o.has(e.command_normalized)&&(o.add(e.command_normalized),!0)).map(ig)}deleteHistory(e,t){return 1===this.db.prepare("DELETE FROM command_history WHERE id=? AND user_id=?").run(t,e).changes}clearHistory(e,t){return(t?this.db.prepare("DELETE FROM command_history WHERE user_id=? AND terminal_id=?").run(e,t):this.db.prepare("DELETE FROM command_history WHERE user_id=?").run(e)).changes}}var iu=(e,t)=>{try{return JSON.parse(e)}catch{return t}},ih=e=>({id:e.id,userId:e.user_id,title:e.title,shell:e.shell,startCwd:e.start_cwd,currentCwd:e.current_cwd,status:e.status,sortOrder:e.sort_order,createdAt:e.created_at,lastActiveAt:e.last_active_at,exitedAt:e.exited_at,closedAt:e.closed_at}),ip=e=>({userId:e.user_id,revision:e.revision,theme:e.theme,terminalFontSize:e.terminal_font_size,fileButtonPosition:iu(e.file_button_position_json,{}),keybarPosition:iu(e.keybar_position_json,{}),keybarHidden:!!e.keybar_hidden,keyOrder:iu(e.key_order_json,[]),pinnedCommands:function(e){if(null==e)return ej();try{return eF(JSON.parse(e))}catch{return ej()}}(e.pinned_commands_json),updatedAt:e.updated_at}),im=e=>({userId:e.user_id,deviceId:e.device_id,activeTerminalId:e.active_terminal_id,drawerOpen:!!e.drawer_open,drawerTab:e.drawer_tab,fileTreeRoot:e.file_tree_root,fileTreeFollowMode:!!e.file_tree_follow_mode,expandedPaths:iu(e.expanded_paths_json,[]),selectedFile:e.selected_file,terminalScroll:iu(e.terminal_scroll_json,{}),updatedAt:e.updated_at}),ig=e=>({id:e.id,userId:e.user_id,terminalId:e.terminal_id,command:e.command,cwd:e.cwd,executedAt:e.executed_at,exitCode:e.exit_code??null});function iy(e){return/(?:token|password|secret|api[_-]?key)\s*=/.test(e.toLowerCase())?"[REDACTED]":e}class i_ extends Error{constructor(e,t,r){super(t,r),this.name="HostPathError",this.code=e}}function iT(e,t){let r=e?.code;return"ENOENT"===r||"ENOTDIR"===r?new i_("PATH_NOT_FOUND",`路径不存在:${t}`,{cause:e}):new i_("PATH_UNREADABLE",`无法访问路径:${t}`,{cause:e})}function iE(e){let t=(0,l.resolve)(e);try{return u.realpathSync.native(t)}catch(e){throw iT(e,t)}}class ib{constructor(e){let t=[];for(let r of e){let e;if(!r?.trim())continue;let s=iE(r.trim());try{e=(0,u.statSync)(s)}catch(e){throw iT(e,s)}if(!e.isDirectory())throw new i_("PATH_NOT_DIRECTORY",`不是目录:${s}`);t.includes(s)||t.push(s)}if(0===t.length)throw new i_("PATH_UNREADABLE","没有可用的宿主机目录根路径");this.roots=t}static fromEnvironment(e,t){return new ib((e?.trim()?e:t).split(l.delimiter))}assertAllowed(e){if("string"!=typeof e||!e.trim())throw new i_("PATH_NOT_FOUND","路径不能为空");let t=iE(e.trim());if(!this.roots.some(e=>(function(e,t){let r=(0,l.relative)(e,t);return""===r||".."!==r&&!r.startsWith(`..${l.sep}`)&&!(0,l.isAbsolute)(r)})(e,t)))throw new i_("PATH_OUTSIDE_ROOT",`路径不在允许范围内:${t}`);return t}assertDirectory(e){let t;let r=this.assertAllowed(e);try{t=(0,u.statSync)(r)}catch(e){throw iT(e,r)}if(!t.isDirectory())throw new i_("PATH_NOT_DIRECTORY",`不是目录:${r}`);return r}listDirectories(e){let t;let r=this.assertDirectory(e);try{t=(0,u.readdirSync)(r,{withFileTypes:!0})}catch(e){throw iT(e,r)}let s=[];for(let e of t){let t,i;let a=(0,l.resolve)(r,e.name);try{t=this.assertAllowed(a)}catch{continue}try{let e=(0,u.statSync)(t);if(e.isDirectory())i="directory";else{if(!e.isFile())continue;i="file"}}catch{continue}s.push({name:e.name||(0,l.basename)(t),path:t,kind:i,hasChildren:"directory"===i&&this.hasAllowedDirectoryChild(t)})}return s.sort((e,t)=>{if(e.kind!==t.kind)return"directory"===e.kind?-1:1;let r=e.name.startsWith(".");return r!==t.name.startsWith(".")?r?1:-1:e.name.localeCompare(t.name,void 0,{sensitivity:"base"})})}hasAllowedDirectoryChild(e){try{return(0,u.readdirSync)(e,{withFileTypes:!0}).some(t=>{if(!t.isDirectory()&&!t.isSymbolicLink())return!1;try{return this.assertDirectory((0,l.resolve)(e,t.name)),!0}catch{return!1}})}catch{return!1}}}function iv(e){return e.replace(/\b(?:sk|rk)-[A-Za-z0-9_-]{8,}/g,"[REDACTED]").replace(/(bearer\s+)[^\s"']+/gi,"$1[REDACTED]").replace(/((?:api[_-]?key|token|password|secret|authorization|cookie)["']?\s*[:=]\s*["']?)[^\s,"'}]+/gi,"$1[REDACTED]").replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/g,"$1[REDACTED]@")}function iw(e,t=0){return t>6?"[depth limit]":"string"==typeof e?iv(e).slice(0,1600):Array.isArray(e)?e.slice(0,24).map(e=>iw(e,t+1)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).slice(0,40).map(([e,r])=>[e,/api.?key|token$|password|secret|authorization|cookie|images|reasoning/i.test(e)&&!/tokens|ratio/i.test(e)?"[REDACTED]":iw(r,t+1)])):e}function iS(e){let t=e=>Array.isArray(e)?e.map(t):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,r])=>[e,t(r)])):e;return(0,p.createHash)("sha256").update(JSON.stringify(t(e))).digest("hex").slice(0,24)}async function iN(e){for(let t of e)if(t)try{return await (0,m.access)(t,m.constants.X_OK),t}catch{}}async function ik(e){let t=[e,process.cwd()];try{t.push((0,l.dirname)((0,h.fileURLToPath)("file:///Users/caoqu/team-agent/customer-agent/packages/core/dist/index.js")))}catch{}for(let e of t){if(!e)continue;let t=e;for(let e=0;e<8;e++){try{return await (0,m.access)((0,l.join)(t,"scripts/harness/daemon.ts")),t}catch{}let e=(0,l.dirname)(t);if(e===t)break;t=e}}}class iI{constructor(e){this.child=null,this.starting=null,this.closed=!1,this.model=null,this.current={state:"stopped"},this.restartCount=0,this.runtimeVersion="unknown",this.onExit=()=>{this.child?.stdin.end(),this.child?.kill("SIGTERM")},this.options=e}get status(){return{...this.current}}setModel(e){}start(){return this.closed||this.child?Promise.resolve():(this.starting||(this.starting=this.launch().catch(()=>{this.current={state:"unavailable",detail:"Companion launch failed"}}).finally(()=>{this.starting=null})),this.starting)}async launch(){if(!1===this.options.enabled||!0!==this.options.enabled&&(process.env.VITEST||"0"===process.env.AGENT_HARNESS_AUTOSTART))return;this.current={state:"starting"};let e=await ik(this.options.sourceRoot),t=await iN([this.options.bunExecutable,process.env.HARNESS_BUN_BINARY,(0,l.join)((0,f.homedir)(),".bun/bin/bun"),"/opt/homebrew/bin/bun"]),r=await iN([this.options.nodeExecutable,process.env.HARNESS_NODE_BINARY,(0,l.join)((0,f.homedir)(),".nvm/versions/node/v22.22.0/bin/node"),"/opt/homebrew/opt/node@22/bin/node"]);if(!e||!t||!r||"darwin"!==process.platform){this.current={state:"unavailable",detail:"Requires a source checkout, Bun, Node 22 and macOS"};return}if(this.closed)return;if("unknown"===this.runtimeVersion)try{this.runtimeVersion=iS(await (0,m.readFile)((0,h.fileURLToPath)("file:///Users/caoqu/team-agent/customer-agent/packages/core/dist/index.js"),"utf8"))}catch{}let s=this.options.stateDirectory??(0,l.join)((0,f.homedir)(),".customer-agent-harness"),i=(0,d.spawn)(t,[(0,l.join)(e,"scripts/harness/daemon.ts"),e,s,this.options.owner,r],{cwd:e,env:{...process.env,HARNESS_PARENT_PID:String(process.pid)},stdio:["pipe","pipe","pipe"]});this.child=i,process.removeListener("exit",this.onExit),process.once("exit",this.onExit);let a="";i.stdout.on("data",e=>{let t;for(a=(a+e.toString()).slice(-256e3);(t=a.indexOf(`
|
|
538
538
|
`))>=0;){let e=a.slice(0,t);a=a.slice(t+1);try{let t=JSON.parse(e);"status"===t.type&&(this.current={state:t.state,pid:i.pid,modelId:t.modelId,detail:t.detail,quality:t.quality},console.info(`[harness] ${this.options.owner}: ${t.state} (pid ${i.pid})`))}catch{}}}),i.stderr.on("data",()=>{}),i.stdin.on("error",()=>{}),i.once("error",()=>{this.current={state:"unavailable",detail:"Companion launch failed"}}),i.once("close",()=>{this.child===i&&(this.child=null),this.current={state:this.closed?"stopped":"unavailable",detail:this.closed?void 0:"Companion exited"},!this.closed&&this.restartCount++<2&&setTimeout(()=>{this.start()},1e3).unref()}),this.model&&this.send({type:"configure",model:this.model})}send(e){this.child?.stdin.writable&&this.child.stdin.write(JSON.stringify(e)+`
|
|
539
539
|
`)}observe(e,t){try{this.send({type:"observation",sessionId:e,data:iw(t)})}catch{}}async *monitor(e,t){await this.start();let r=(0,p.randomUUID)();this.send({type:"begin",id:r,...t,input:iv(t.input).slice(0,8e3),runtimeVersion:this.runtimeVersion,owner:this.options.owner});let s=0;try{for await(let t of e){if("text_chunk"!==t.type||Date.now()-s>1e3){let e="ask_user"===t.type||"tool_call"===t.type&&"ask_user"===t.toolCall.name,i={type:t.type};"tool_call"===t.type?i={type:t.type,tool:t.toolCall.name,callId:t.toolCall.id,argumentsHash:iS(t.toolCall.arguments),arguments:iw(t.toolCall.arguments)}:"tool_result"===t.type?i={type:t.type,callId:t.result.toolCallId,resultHash:iS(t.result.content),isError:t.result.isError,preview:iv(t.result.content).slice(0,1200)}:["context_usage","compacted","error","done","turn_aborted"].includes(t.type)&&(i=iw(t)),this.send({type:"progress",id:r,eventType:t.type,waiting:e,data:i,tool:"tool_call"===t.type?t.toolCall.name:void 0}),s=Date.now()}yield t}}catch(e){throw this.send({type:"fault",id:r,message:iv(e instanceof Error?e.stack??e.message:String(e))}),e}finally{this.send({type:"end",id:r})}}async withUserWait(e,t){this.send({type:"waiting",sessionId:e,waiting:!0});try{return await t()}finally{this.send({type:"waiting",sessionId:e,waiting:!1})}}close(){this.closed=!0,process.removeListener("exit",this.onExit),this.send({type:"shutdown"});let e=this.child;if(e){e.stdin.end();let t=setTimeout(()=>{null===e.exitCode&&e.kill("SIGTERM")},3e3);t.unref(),e.once("exit",()=>clearTimeout(t))}this.current={state:"stopped"}}}}};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";exports.id=2083,exports.ids=[2083],exports.modules={2557:(e,t,s)=>{s.d(t,{L:()=>f,MO:()=>u,Nr:()=>c,Vk:()=>_,ZN:()=>d,vT:()=>v});var i=s(6005),r=s(9411),a=s(132);let n="codex-native:",o="codex-catalog:",l="codex:recent";function d(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 u(e){return Buffer.from(JSON.stringify({offset:e}),"utf8").toString("base64url")}function c(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 h(e,t){let s="native"===e?n:o;return`${s}${Buffer.from(t,"utf8").toString("base64url")}`}function p(e,t){let s=e.slice(t.length),i=Buffer.from(s,"base64url").toString("utf8");if(!s||!i||Buffer.from(i,"utf8").toString("base64url")!==s)throw new a.n("Invalid Codex workspace cursor","INVALID_SESSION_ID");return i}function m(e){if(!e)return null;if(e.startsWith(n))return{kind:"native",value:p(e,n)};if(e.startsWith(o))return{kind:"catalog",value:p(e,o)};try{return c(e),{kind:"catalog",value:e}}catch{return{kind:"native",value:e}}}function f(e,t={},s=null){let i=c(t.cursor),r=d(t.limit),a=e.slice(i,i+r),n=i+a.length;return{data:a,nextCursor:n<e.length?u(n):null,watermark:s}}function g(e,t,s){let i=m(t.cursor);if(i?.kind==="native")throw new a.n("Native Codex cursor cannot page the classified catalog","INVALID_SESSION_ID");let r=f(e,{...t,cursor:i?.value??null},s);return{...r,nextCursor:r.nextCursor?h("catalog",r.nextCursor):null}}function y(e,t,s){let i=new Set(e.map(e=>e.id));return[...e.map(e=>({...e,projectId:s})),...t.filter(e=>!i.has(e.id))].sort((e,t)=>t.updated.localeCompare(e.updated)||e.id.localeCompare(t.id))}function w(e,t){return JSON.stringify(e.map(e=>({workspaceId:e.workspaceId,source:e.source,roots:e.roots.map(e=>v(e,t)).sort()})).sort((e,t)=>e.workspaceId.localeCompare(t.workspaceId)))}function v(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 I(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 _{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.codexDirectSessions=new Map,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{...f(s.data,t,s.watermark),stale:s.stale};let i=this.workspaceRequests.get(e);if(i){let e=await i;return{...f(e.data,t,e.watermark),stale:e.stale}}}let i=this.loadWorkspaceCatalog(s,t);this.workspaceRequests.set(e,i);try{let s=this.workspaceCache.get(e),r=await i;return this.workspaceCache.set(e,r),t.refresh&&"codex"===e&&s&&w(s.data,this.platform)!==w(r.data,this.platform)&&this.clearSessionCache(e),{...f(r.data,t,r.watermark),stale:r.stale}}catch(i){let s=this.workspaceCache.get(e);if(s)return{...f(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=v(t,this.platform),l=this.workspaceCache.get(e)?.data.find(e=>e.roots.some(e=>v(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=>v(e,this.platform)===o));if(e)return{workspace:e,existing:!0}}catch{}if(d)return{workspace:I(d,Number.MAX_SAFE_INTEGER),existing:!0};let u=Date.now(),c=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:I(c.workspace,Number.MAX_SAFE_INTEGER),existing:c.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,o="codex"===e?this.listCodexWorkspaceSessions(i,t,s):n?this.listImportedWorkspaceSessions(i,n,s):i.listWorkspaceSessions(t,{...s,limit:d(s.limit)});this.sessionRequests.set(r,o);try{let e=await o;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)===o&&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,this.codexDirectSessions.clear()}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 n=s;if(this.importedWorkspaces&&"customer-agent"!==e.agentType){let t=new Set(s.flatMap(e=>e.roots.map(e=>v(e,this.platform)))),i=this.importedWorkspaces.list(e.agentType).filter(e=>!t.has(e.normalizedPath)).map((e,t)=>I(e,s.length+t));n=[...s,...i]}return"codex"===e.agentType&&(n=[{agentType:"codex",workspaceId:l,name:"最近",roots:[],order:-1,source:"derived",canCreateSession:!1},...n]),{data:n,watermark:r,...a?{stale:!0}:{}}}async listCodexWorkspaceSessions(e,t,s){this.workspaceCache.has("codex")||await this.listWorkspaces("codex",{limit:200});let i=this.workspaceCache.get("codex")?.data.find(e=>e.workspaceId===t);if(!i)throw new a.n(`Codex workspace not found: ${t}`,"SESSION_NOT_FOUND");let r=m(s.cursor);if("native"===i.source&&r?.kind!=="catalog"){let i=await e.listWorkspaceSessions(t,{...s,cursor:r?.value??null,limit:d(s.limit)});return(this.rememberCodexDirectSessions(t,i.data),!s.cursor&&this.codexSessionCatalog)?g(this.codexSessionCatalog.byWorkspace.get(t)??[],s,this.codexSessionCatalog.watermark):(this.getCodexSessionCatalog(e,!1).catch(()=>void 0),{...i,nextCursor:i.nextCursor?h("native",i.nextCursor):null})}let n=!0===s.refresh&&!s.cursor,o=await this.getCodexSessionCatalog(e,n),l=o.byWorkspace.get(t);if(!l)throw new a.n(`Codex workspace not found: ${t}`,"SESSION_NOT_FOUND");return g(l,s,o.watermark)}rememberCodexDirectSessions(e,t){let s=y(t,this.codexDirectSessions.get(e)??[],e);if(this.codexDirectSessions.set(e,s),!this.codexSessionCatalog?.byWorkspace.has(e))return;let i=this.codexSessionCatalog.byWorkspace.get(e)??[];this.codexSessionCatalog.byWorkspace.set(e,y(s,i,e));let r=this.codexSessionCatalog.byWorkspace.get(e)?.[0]?.updated;r&&(!this.codexSessionCatalog.watermark||r>this.codexSessionCatalog.watermark)&&(this.codexSessionCatalog.watermark=r)}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 t=await i;if(s!==this.codexSessionCatalogGeneration)return this.getCodexSessionCatalog(e,!1);return this.codexSessionCatalog=t,this.deleteSessionCacheEntries("codex"),t}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(),i=function(e,t,s=process.platform){let i=t.filter(e=>e.workspaceId!==l),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:v(t,s)}]}catch{return[]}})).sort((e,t)=>t.path.length-e.path.length),n=new Map(t.map(e=>[e.workspaceId,[]])),o=[...e].sort((e,t)=>t.updated.localeCompare(e.updated)||e.id.localeCompare(t.id)),d=new Set;for(let e of o){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=v(e.cwd,s);t=a.find(e=>{var t;return(t=e.path)===i||i.startsWith(`${t}${"win32"===s?"\\":"/"}`)})?.workspaceId}catch{}t??=l;let i=n.get(t)??n.get(l);i?.push({...e,projectId:t})}return{byWorkspace:n,watermark:o[0]?.updated??null}}(this.supplementCodexSessions?.(s)??s,t,this.platform);for(let[e,t]of this.codexDirectSessions){let s=i.byWorkspace.get(e);if(!s)continue;i.byWorkspace.set(e,y(t,s,e));let r=i.byWorkspace.get(e)?.[0]?.updated;r&&(!i.watermark||r>i.watermark)&&(i.watermark=r)}return i}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:d(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:()=>D});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),h=s(8224),p=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 k=(0,d.promisify)(r.execFile),P=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;async function v(e){let t=await (0,a.stat)(e);return`${t.mtimeMs}:${t.size}`}let M=[{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:O(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?O(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=T(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:R(o.activity.messages,s.text)},o.streamedText=!0,[this.update(o)]):[]}if("assistant"===e.type){let t=o.activity.messages,s=Array.isArray(e.message.content)?e.message.content:[],i=C(s);for(let e of(i&&!o.streamedText&&(t=R(t,i)),s)){let s=x(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 D{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.sessionPaths=new Map,this.sessionInfoCache=new Map,this.occupancyCache=null,this.permissionEvents=new Map,this.sessionRoot=e.sessionRoot??(0,o.join)((0,n.homedir)(),".claude","projects"),this.occupancyTtlMs=e.occupancyTtlMs??1e3}async health(){try{let{stdout:e}=await k("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 M}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),I(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?I(await this.toSummary(s,r),t):t,n=b(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&&P.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=S(o,void 0,s),d=this.drafts.has(e),p=(0,c.NyU)(a?.permissionMode),m="full-access"===p?void 0:(t,s,i)=>this.requestPermission(e,t,s,i,p,n.cwd,a?.brokerRunId),f=new h.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"===p?"bypassPermissions":"default",..."full-access"===p?{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 h.K;this.permissionEvents.set(e,e=>w.push(e));let v="",I=new L,_=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(I.hasActiveBackgroundTasks()){for(let e of I.stopActive())yield e;yield t?{type:"turn_aborted"}:{type:"error",message:"Claude Code ended before a background subagent completed",code:"NATIVE_PROTOCOL_ERROR"},_=null}else t&&(yield{type:"turn_aborted"});break}let n=a.result.value;for(let e of(i=t.next(),I.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(T(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=x(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,v.length>0))"text_chunk"===e.type&&(v+=e.text),yield e;if("system"===n.type&&"init"===n.subtype&&n.session_id!==e)throw new y.n(`Claude Code returned unexpected session ID ${n.session_id}`,"NATIVE_PROTOCOL_ERROR");if("result"===n.type){_=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}]:[]]}}}(_,++this.contextUsageRequestIndex);e&&(yield e)}if(_&&!I.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"}}(_,v),_=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(S(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=this.sessionInfoCache.get(e);if(t){let s=await this.findSessionPath(e);if(s&&await v(s)===t.stamp)return t.info;this.sessionInfoCache.delete(e)}let s=0;for(;;){let t=await (0,u.listSessions)({limit:200,offset:s}),i=t.find(t=>t.sessionId===e);if(i)return await this.cacheSessionInfo(e,i),i;if(t.length<200)return;s+=200}}async cacheSessionInfo(e,t){let s=await this.findSessionPath(e);s&&this.sessionInfoCache.set(e,{info:t,stamp:await v(s)})}async externalOccupancy(){let e;let t=Date.now();if(this.occupancyCache&&t-this.occupancyCache.at<this.occupancyTtlMs)e=this.occupancyCache.raw;else{let[s,i]=await Promise.all([(0,m.g)("claude",this.sessionRoot),E()]);for(let t of(e=new Set,s)){let s=(0,o.basename)(t);s.endsWith(".jsonl")&&e.add(s.slice(0,-6))}for(let t of i)t.sessionId&&("done"!==t.state||"active"===t.status||"running"===t.status)&&e.add(t.sessionId);this.occupancyCache={at:t,raw:e}}let s=new Set(e);for(let e of this.ownedSessions)s.delete(e);return s}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=b(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||!P.test(e))return null;let s=this.sessionPaths.get(e);if(s&&await (0,a.stat)(s).then(e=>e.isFile()).catch(()=>!1))return s;this.sessionPaths.delete(e);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 this.sessionPaths.set(e,t),t}catch{}}return null}async toSummary(e,t){let s=this.ownedSessions.has(e.sessionId),i=t.has(e.sessionId),r=s?"owned-by-customer-agent":i?"owned-externally":"available",a=new Date(e.lastModified).toISOString(),n=e.cwd?.trim()||await this.readSessionCwd(e.sessionId);return{id:(0,f.F)(this.agentType,e.sessionId),agentType:this.agentType,nativeSessionId:e.sessionId,title:(e.customTitle||e.summary||e.firstPrompt||"Claude Code session").trim(),cwd:n,created:new Date(e.createdAt??e.lastModified).toISOString(),updated:a,status:"available"===r?"idle":"running",occupancy:r,sourceLabel:"Claude Code CLI",canResume:"owned-externally"!==r,canDelete:!1}}async readSessionCwd(e){let t;let s=await this.findSessionPath(e);if(!s)return"";try{t=await (0,a.open)(s,"r");let e=Buffer.alloc(65536),i=new l.StringDecoder("utf8"),r="",n=0;for(;n<2097152;){let s=Math.min(e.length,2097152-n),{bytesRead:a}=await t.read(e,0,s,n);if(0===a)break;n+=a;let o=(r+=i.write(e.subarray(0,a))).indexOf("\n");for(;o>=0;){let e=_(r.slice(0,o));if(e)return e;o=(r=r.slice(o+1)).indexOf("\n")}}return _(r+i.end())}catch{}finally{await t?.close().catch(()=>void 0)}return""}requestPermission(e,t,s,i,r,a,n){let o=function(e,t,s){let i=function(e){let t=e.replace(/[^a-z]/gi,"").toLowerCase();return({read:"read_file",glob:"glob",grep:"grep",write:"write_file",edit:"str_replace",multiedit:"str_replace",bash:"bash",webfetch:"web_fetch",websearch:"web_search"})[t]??`claude_${t||"unknown"}`}(e),r=("write_file"===i||"str_replace"===i)&&"string"!=typeof t.file_path&&"string"==typeof t.path?{...t,file_path:t.path}:t;return(0,c.CrD)(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 I(e,t){return t?{...e,cwd:e.cwd||t.cwd,projectId:e.projectId??t.projectId}:e}function _(e){if(!e.trim())return"";try{let t=JSON.parse(e);return"string"==typeof t.cwd?t.cwd.trim():""}catch{return""}}function S(e,t,s){let i=(0,p.u)(s),r=i.length>0?[{type:"text",text:e},...i.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.base64}}))]:e;return{type:"user",message:{role:"user",content:r},parent_tool_use_id:null,...t?{priority:t}:{}}}async function E(){try{let{stdout:e}=await k("claude",["agents","--json","--all"],{encoding:"utf8",timeout:5e3,maxBuffer:4194304}),t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function b(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(x).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 T(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 O(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 R(e,t){if(!t)return e;let s=e[e.length-1];return s?.role!=="assistant"||s.toolCalls?.length?[...e,{role:"assistant",content:t}]:[...e.slice(0,-1),{...s,content:s.content+t}]}function x(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(){console.log(`[codex-app-server-client] spawning: ${this.executable} app-server --stdio`);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=>{console.log("[codex-app-server-client] child error:",e.message),this.handleExit(e)}),e.once("exit",(e,t)=>{console.log(`[codex-app-server-client] child exit: code=${e} signal=${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}}),console.log(`[codex-app-server-client ${new Date().toISOString().slice(11,23)}] initialize completed`),this.write({method:"initialized",params:{}})}sendRequest(e,t){let s=this.nextId++;return console.log(`[codex-app-server-client ${new Date().toISOString().slice(11,23)}] -> ${e} (id=${s})`),new Promise((i,a)=>{let n=setTimeout(()=>{console.log(`[codex-app-server-client] TIMEOUT ${e} (id=${s})`),this.pending.delete(s),a(new r.n(`Codex request timed out: ${e}`,"NATIVE_PROTOCOL_ERROR"))},this.requestTimeoutMs);this.pending.set(s,{resolve:t=>{console.log(`[codex-app-server-client ${new Date().toISOString().slice(11,23)}] <- ${e} resolved (id=${s})`),clearTimeout(n),i(t)},reject:t=>{console.log(`[codex-app-server-client] <- ${e} rejected (id=${s}):`,t.message),clearTimeout(n),a(t)},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
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:()=>q});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"]),h=new Set(["task_complete","turn_complete","turn_aborted"]);function p(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(h.has(e.payload.type))return"idle"}catch{}return"unknown"}async function m(e,t=1048576){let s=null;try{s=await (0,r.open)(e,"r");let i=await s.stat();if(!i.isFile()||0===i.size)return null;let a=Math.min(i.size,Math.max(1,t)),n=i.size-a,o=Buffer.allocUnsafe(a),{bytesRead:l}=await s.read(o,0,a,n),d=await s.stat();if(d.size!==i.size||d.ino!==i.ino)return null;let u=o.subarray(0,l).toString("utf8").split("\n");n>0&&u.shift();for(let e=u.length-1;e>=0;e-=1){let t=function(e){if(!e.trim())return{boundary:!1,finalAnswer:null};try{let t=JSON.parse(e),s=w(t.payload);if("event_msg"===t.type&&"string"==typeof s.type){if(c.has(s.type)||h.has(s.type))return{boundary:!0,finalAnswer:null};if("item_completed"===s.type)return{boundary:!1,finalAnswer:f(s.item,s.turn_id)}}if("response_item"===t.type)return{boundary:!1,finalAnswer:f(s,s.turn_id)}}catch{}return{boundary:!1,finalAnswer:null}}(u[e]);if(t.boundary)break;if(t.finalAnswer)return t.finalAnswer}return null}catch{return null}finally{await s?.close().catch(()=>void 0)}}function f(e,t){let s=w(e),i="string"==typeof s.type?s.type.toLowerCase():"",r="string"==typeof s.role?s.role.toLowerCase():"";if("agentmessage"!==i&&"message"!==i||r&&"assistant"!==r||"final_answer"!==s.phase)return null;let a=v(w(s.internal_chat_message_metadata_passthrough).turn_id)||v(s.turn_id)||v(t);if(!a)return null;let n=g(s);return n.trim()?{turnId:a,..."string"==typeof s.id?{itemId:s.id}:{},text:n}:null}function g(e){return Array.isArray(e.content)?e.content.flatMap(e=>{let t=w(e),s="string"==typeof t.type?t.type.toLowerCase():"";return("text"===s||"output_text"===s)&&"string"==typeof t.text?[t.text]:[]}).join(""):"string"==typeof e.text?e.text:""}class y{constructor(e=65536){if(this.chunkSize=e,this.cache=new Map,!Number.isInteger(e)||e<=0)throw Error("Codex rollout commentary chunk size must be a positive integer")}async read(e,t){let s=null;try{s=await (0,r.open)(e,"r");let i=await s.stat();if(!i.isFile())return{commentary:[],itemOrder:[]};let a=`${i.dev}:${i.ino}`,n=this.cache.get(e),o=n&&n.identity===a&&i.size>=n.size&&(i.size>n.size||i.mtimeMs===n.mtimeMs)?n:{identity:a,size:0,mtimeMs:i.mtimeMs,trailing:Buffer.alloc(0),trailingOverflow:!1,turns:new Map};await this.readAppendedCommentary(s,o,i.size),o.size=i.size,o.mtimeMs=i.mtimeMs,this.cache.set(e,o),this.cache.size>64&&this.cache.delete(this.cache.keys().next().value);let l=o.turns.get(t);return l?{commentary:[...l.commentary.values()],itemOrder:[...l.itemOrder]}:{commentary:[],itemOrder:[]}}catch{return this.cache.delete(e),{commentary:[],itemOrder:[]}}finally{await s?.close().catch(()=>void 0)}}async readAppendedCommentary(e,t,s){let i=t.size;for(;i<s;){let r=Math.min(this.chunkSize,s-i),a=Buffer.allocUnsafe(r),{bytesRead:n}=await e.read(a,0,r,i);if(n<=0)break;i+=n;let o=a.subarray(0,n);if(t.trailingOverflow){let e=o.indexOf(10);if(e<0)continue;o=o.subarray(e+1),t.trailingOverflow=!1}else t.trailing.length>0&&(o=Buffer.concat([t.trailing,o]));let l=o.lastIndexOf(10);if(l<0){t.trailing=o.length<=262144?Buffer.from(o):Buffer.alloc(0),t.trailingOverflow=o.length>262144;continue}for(let e of o.subarray(0,l).toString("utf8").split("\n"))this.consumeCommentaryLine(t,e);let d=o.subarray(l+1);t.trailing=d.length<=262144?Buffer.from(d):Buffer.alloc(0),t.trailingOverflow=d.length>262144}}consumeCommentaryLine(e,t){if(t.trim())try{let s,i;let r=JSON.parse(t),a=w(r.payload);if("response_item"===r.type)s=a,i=a.turn_id;else{if("event_msg"!==r.type||"item_completed"!==a.type)return;s=w(a.item),i=a.turn_id}let n=v(w(s.internal_chat_message_metadata_passthrough).turn_id)||v(s.turn_id)||v(i);if(!n)return;let o=e.turns.get(n);o||(o={commentary:new Map,itemOrder:[],itemIds:new Set},e.turns.set(n,o));let l=v(s.id);l&&!o.itemIds.has(l)&&(o.itemIds.add(l),o.itemOrder.push(l));let d=v(s.type).toLowerCase(),u=v(s.role).toLowerCase();if("commentary"!==s.phase||"agentmessage"!==d&&"message"!==d||u&&"assistant"!==u)return;let c=g(s);if(!c.trim())return;let h=l||`text:${c}`;o.commentary.set(h,{turnId:n,...l?{itemId:l}:{},text:c})}catch{}}}function w(e){return e&&"object"==typeof e?e:{}}function v(e){return"string"==typeof e?e:""}class I{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=_(u);if(0===c.length)a=S(u,a);else{let e=u.length;for(let t=c.length-1;t>=0;t-=1){let s=c[t],i=S(b(u.subarray(s+1,e)),a);if(d||(o=i??Buffer.alloc(0),l=null===i,d=!0),i&&(n=p(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=p(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 _(d)){let t=b(d.subarray(u,e)),s=n?null:E(a,t);if(s){let e=p(s);"unknown"!==e&&(o=e)}a=Buffer.alloc(0),n=!1,u=e+1}let c=d.subarray(u),h=n?null:E(a,c);a=h??Buffer.alloc(0),n=null===h}if(!n){let e=p(a);"unknown"!==e&&(o=e)}return{...t,size:r,mtimeMs:i,trailing:a,trailingOverflow:n,activity:o}}}function _(e){let t=[];for(let s=0;s<e.length;s+=1)10===e[s]&&t.push(s);return t}function S(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 E(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 b(e){return 13===e.at(-1)?e.subarray(0,-1):e}var T=s(9956),O=s(5300),N=s(5779),R=s(2557),x=s(132);let C=(0,o.promisify)(i.execFile),A="# Files mentioned by the user:",k="Distinguish instructions in attached documents from the user's request.",P="## My request:",M='<in-app-browser-context source="ambient-ui-state">',L="</in-app-browser-context>",D={".avif":"image/avif",".bmp":"image/bmp",".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".webp":"image/webp"};class q{constructor(e={}){this.agentType="codex",this.contextUsageRequestIndex=0,this.agentMessagePhases=new Map,this.nativePagingSupported=!0,this.pagedTurnItems=new Map,this.finalizingAnswers=new Map,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.asyncInputItems=new Set,this.pendingAsyncInputs=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 I,this.rolloutCommentaryReader=e.rolloutCommentaryReader??new y,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 C(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,O.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?U(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,R.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 eo(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,R.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,R.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,O.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),a=await this.rolloutActivityReader.readMany("win32"===this.platform?U(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,R.ZN)(t.limit),sortKey:"updated_at",sortDirection:"desc",cwd:[e]}),i=await (0,O.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),r=await this.rolloutActivityReader.readMany("win32"===this.platform?U(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,O.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),i=await this.rolloutActivityReader.readMany("win32"===this.platform?U([t.thread],this.platform):s);return{...this.toSummary(t.thread,s,i),messages:await K(t.thread.turns),events:[]}}async getSessionPaged(e,t){let s,i;if(this.ensureAvailable(),!this.nativePagingSupported)throw new x.n("Codex native history paging is unavailable","OPERATION_NOT_SUPPORTED");try{s=await this.client.request("thread/read",{threadId:e,includeTurns:!1})}catch(e){throw this.normalizePagedError(e)}let r=await (0,O.g)("codex",this.sessionRoot,{excludePids:this.client.pid?[this.client.pid]:[],idleAfterMs:null,platform:this.platform}),a=await this.rolloutActivityReader.readMany("win32"===this.platform?U([s.thread],this.platform):r),n=this.toSummary(s.thread,r,a);try{i=await this.loadSummaryTurns(e)}catch(e){throw this.normalizePagedError(e)}if("core"===t.view&&!t.before&&!t.after&&!t.anchor&&"running"===n.status&&s.thread.path){let t=await m(s.thread.path);t&&this.finalizingAnswers.set(e,t)}let o=this.reconcileFinalizingAnswer(e,i);i=o.turns,o.latestTurnFinalizing&&"running"===n.status&&(n={...n,status:"idle"});let d=[];for(let e of i){let t=Y(e);for(let s of e.items??[])"userMessage"===s.type?d.push({turnId:e.id,role:"user"}):Z(s,e.status,t)&&d.push({turnId:e.id,role:"assistant"})}let u=X(i),c=(0,l.Q3Q)(u);if("trace"===t.view&&t.turnId){if(!t.revision||t.revision!==c)throw new x.n("Session history changed; reload the core page","STALE_SESSION_ANCHOR");let r=i.find(e=>e.id===t.turnId);if(!r)throw new x.n("Session history turn changed; reload the core page","STALE_SESSION_ANCHOR");await this.hydrateTurnRange(e,i,r.id,r.id,{refreshTurnId:i.at(-1)?.id===r.id?r.id:void 0,preserveRefreshedItems:"running"===n.status});let a=this.pagedTurnItems.get(e)?.turns.get(r.id)??r.items??[];s.thread.path&&(a=function(e,t){if(0===t.commentary.length)return e;let s=[...e],i=new Set(s.flatMap(e=>"string"==typeof e.id?[e.id]:[]));for(let e of t.commentary){if(e.itemId&&i.has(e.itemId)){let t=s.findIndex(t=>t.id===e.itemId),i=s[t];i?.type==="agentMessage"&&(s[t]={...i,text:e.text,phase:"commentary"});continue}s.push({type:"agentMessage",...e.itemId?{id:e.itemId}:{},text:e.text,phase:"commentary"}),e.itemId&&i.add(e.itemId)}let r=new Map(t.itemOrder.map((e,t)=>[e,t]));return s.map((e,t)=>({item:e,index:t})).sort((e,t)=>{let s=e.item.id?r.get(e.item.id):void 0,i=t.item.id?r.get(t.item.id):void 0;return void 0===s&&void 0===i?e.index-t.index:void 0===s?1:void 0===i?-1:s-i}).map(({item:e})=>e)}(a,await this.rolloutCommentaryReader.read(s.thread.path,r.id)));let o={...r,items:a},l=(await K([o],{toolResultMode:"lazy",revision:c,reasoningMaxBytes:4096,toolArgumentsMaxBytes:2048})).filter(J);return{...n,messages:l,events:[],history:{nextCursor:null,hasMore:!1,pageSize:0,totalItems:d.length,kind:"anchored",revision:c,delivery:"trace"}}}let{start:h,end:p,kind:f}=this.selectNativeRange(d,t,c),g=d[h]?.turnId,y=p>h?d[p-1].turnId:void 0,w=i.findIndex(e=>e.id===g),v=i.findIndex(e=>e.id===y),I=w>=0&&v>=w?i.slice(w,v+1):[];if("core"===t.view){let e=new Map;for(let t of I)for(let s of t.items??[])if("userMessage"===s.type)for(let t of H(s.content))e.has(t)||e.set(t,await j(t));let t=X(I,e);return this.assignNativeHistoryIds(t,d,h,p),{...n,messages:t,events:[],history:{...this.nativeHistoryWindow(h,p,d.length,f,c),delivery:"core"}}}if("trace"===t.view&&t.revision&&t.revision!==c)throw new x.n("Session history changed; reload the core page","STALE_SESSION_ANCHOR");g&&y&&await this.hydrateTurnRange(e,i,g,y,{refreshTurnId:p===d.length?y:void 0,preserveRefreshedItems:"running"===n.status});let _=this.pagedTurnItems.get(e),S=w>=0&&v>=w?i.slice(w,v+1).map(e=>({...e,items:_?.turns.get(e.id)??e.items??[]})):[],E=await K(S,"trace"===t.view?{toolResultMode:"lazy",revision:c,reasoningMaxBytes:4096,toolArgumentsMaxBytes:2048}:void 0);return this.assignNativeHistoryIds(E,d,h,p),{...n,messages:E,events:[],history:{...this.nativeHistoryWindow(h,p,d.length,f,c),delivery:"trace"===t.view?"trace":"legacy-full"}}}async getSessionToolResult(e,t){let s;if(this.ensureAvailable(),!this.nativePagingSupported)throw new x.n("Codex native history paging is unavailable","OPERATION_NOT_SUPPORTED");try{s=await this.loadSummaryTurns(e)}catch(e){throw this.normalizePagedError(e)}s=this.reconcileFinalizingAnswer(e,s).turns;let i=(0,l.Q3Q)(X(s));if(i!==t.revision)throw new x.n("Session history changed; reload the tool result","STALE_SESSION_ANCHOR");let r=s.find(e=>e.id===t.turnId);if(!r)throw new x.n("Codex turn not found","SESSION_NOT_FOUND");await this.hydrateTurnRange(e,s,r.id,r.id);let a=er(this.pagedTurnItems.get(e)?.turns.get(r.id)?.find(e=>e.id===t.itemId));if(!a)throw new x.n("Codex tool result not found","SESSION_NOT_FOUND");return{turnId:r.id,itemId:t.itemId,revision:i,byteSize:Buffer.byteLength(a.content,"utf8"),...void 0===a.isError?{}:{isError:a.isError},content:a.content}}async getQueryIndex(e){let t;if(this.ensureAvailable(),!this.nativePagingSupported)return null;try{t=await this.loadSummaryTurns(e)}catch(e){throw this.normalizePagedError(e)}let s=X(t=this.reconcileFinalizingAnswer(e,t).turns);return(0,l.buildSessionQueryIndex)((0,N.F)(this.agentType,e),s)}nativeHistoryWindow(e,t,s,i,r){return{nextCursor:e>0?B(e):null,hasMore:e>0,pageSize:Math.max(0,t-e),totalItems:s,olderCursor:e>0?B(e):null,newerCursor:t<s?B(t):null,kind:i,revision:r}}async loadSummaryTurns(e){return((await this.client.request("thread/turns/list",{threadId:e,itemsView:"summary"})).data??[]).slice().reverse()}reconcileFinalizingAnswer(e,t){let s=this.finalizingAnswers.get(e);if(!s)return{turns:t,latestTurnFinalizing:!1};let i=t.findIndex(e=>e.id===s.turnId);if(i<0)return t.length>0&&t.at(-1)?.id!==s.turnId&&this.finalizingAnswers.delete(e),{turns:t,latestTurnFinalizing:!1};let r=t[i],a=r.items??[],n=a.findIndex(e=>"agentMessage"===e.type&&(s.itemId&&e.id===s.itemId||e.text===s.text));if(n>=0&&a[n].text===s.text&&"final_answer"===a[n].phase)return this.finalizingAnswers.delete(e),{turns:t,latestTurnFinalizing:i===t.length-1};let o=[...a],l={type:"agentMessage",...s.itemId?{id:s.itemId}:{},text:s.text,phase:"final_answer"};n>=0?o[n]=l:o.push(l);let d=[...t];return d[i]={...r,items:o},{turns:d,latestTurnFinalizing:i===t.length-1}}selectNativeRange(e,t,s){var i;let r=e.length,a=Number.isFinite(i=t.limit)?Math.max(1,Math.min(100,Math.floor(i))):50,n=(t,s)=>{let i=Math.min(r,t+s);for(;i<r&&e[i]?.role!=="user";)i+=1;return i},o=t=>{if(t<=0||e[t]?.role==="user")return Math.max(0,t);for(let s=t-1;s>=0;s-=1)if("user"===e[s].role)return s;return 0};if(t.anchor){let i=(0,l.OGe)(t.anchor,s);if(i>=r||e[i]?.role!=="user")throw new l.ujo;let d=o(Math.max(0,i-Math.floor(a/2)));return{start:d,end:n(d,Math.max(a,i-d+1)),kind:"anchored"}}if(t.after){let e=z(t.after,r);return{start:e,end:n(e,a),kind:"anchored"}}let d=z(t.before,r);return{start:o(Math.max(0,d-a)),end:d,kind:"latest"}}async hydrateTurnRange(e,t,s,i,r={}){let a=this.pagedTurnItems.get(e);a||(a={turns:new Map,statuses:new Map,walkCursor:void 0,exhausted:!1},this.pagedTurnItems.set(e,a));let n=a;for(let e of t){let t=n.statuses.get(e.id);void 0!==t&&t!==e.status&&(n.turns.delete(e.id),n.statuses.delete(e.id),n.walkCursor=void 0,n.exhausted=!1)}t.length>0&&!n.turns.has(t[t.length-1].id)&&(n.walkCursor=void 0,n.exhausted=!1);let o=new Set,l=!1;for(let e of t)if(e.id===s&&(l=!0),l&&o.add(e.id),e.id===i)break;let d=r.refreshTurnId&&o.has(r.refreshTurnId)?n.turns.get(r.refreshTurnId):void 0;if(r.refreshTurnId&&o.has(r.refreshTurnId)&&(n.turns.delete(r.refreshTurnId),n.walkCursor=void 0,n.exhausted=!1),[...o].every(e=>n.turns.has(e)))return;let u=0,c=n.walkCursor;for(;u<400&&([...o].some(e=>!n.turns.has(e))||!n.walkCursor)&&!n.exhausted;){let t=await this.client.request("thread/turns/list",{threadId:e,itemsView:"full",limit:5,sortDirection:"desc",...c?{cursor:c}:{}}),s=t.data??[];for(let e of s){if(n.turns.has(e.id))continue;let t=e.id===r.refreshTurnId&&r.preserveRefreshedItems&&d?function(e,t){let s=new Map(t.flatMap(e=>"string"==typeof e.id?[[e.id,e]]:[])),i=new Set(e.flatMap(e=>"string"==typeof e.id?[e.id]:[]));return[...e.flatMap(e=>"string"!=typeof e.id?[]:[s.get(e.id)??e]),...t.filter(e=>"string"!=typeof e.id||!i.has(e.id))]}(d,e.items??[]):e.items??[];n.turns.set(e.id,t),n.statuses.set(e.id,e.status)}u+=1;let i=t.nextCursor??void 0;if(!i||0===s.length){n.exhausted=!0;break}c=i,n.walkCursor=i}n.turns.size>800&&this.pagedTurnItems.delete(e)}assignNativeHistoryIds(e,t,s,i){let r=s;for(let s of e){if(r>=i)break;let e=s.role;"user"!==e&&"assistant"!==e||"assistant"===e&&(s.toolCalls?.length||s.presentation?.reasoning||s.presentation?.agentMessagePhase==="commentary")||t[r]?.role!==e||(s.historyId=(0,l.kEw)(r,s),r+=1)}}normalizePagedError(e){if(e instanceof x.n&&"NATIVE_PROTOCOL_ERROR"!==e.code)return e;let t=e instanceof Error?e.message:String(e);return/unknown method|method not found|unknown variant [`'"](?:thread\/(?:read|turns\/list)|summary|full|notLoaded)[`'"]|(?:^|\D)-32601(?:\D|$)/i.test(t)?(this.nativePagingSupported=!1,new x.n(`Codex native history paging failed: ${t}`,"OPERATION_NOT_SUPPORTED")):/invalid (?:request|params?)|expected one of|failed to deserialize|thread (?:not loaded|not found)|(?:^|\D)-3260(?:0|2)(?:\D|$)/i.test(t)?new x.n(`Codex native history paging failed for this request: ${t}`,"OPERATION_NOT_SUPPORTED"):e instanceof x.n?e:new x.n(t,"NATIVE_PROTOCOL_ERROR")}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 renameSession(e,t){this.ensureAvailable(),await this.client.request("thread/name/set",{threadId:e,name:t})}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 x.n("Codex session is already running","SESSION_ALREADY_RUNNING");let o=await this.getSession(e),u=(0,T.u)(s),c=new d.K,h=(0,l.NyU)(n?.permissionMode),p=null,m=!1;this.activeQueues.set(e,c),this.activePermissionModes.set(e,h),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 F(u,this.imageStorageRoot).then(e=>(p=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"===h?{approvalPolicy:"onRequest",sandboxPolicy:{type:"readOnly"}}:"auto-approval"===h?{approvalPolicy:"onRequest",sandboxPolicy:{type:"workspaceWrite",writableRoots:f?[f]:[],networkAccess:!1}}:{approvalPolicy:"never",sandboxPolicy:{type:"dangerFullAccess"}})});for await(let t of(m=null!==p,this.activeTurnIds.set(e,l.turn.id),c))yield t}catch(t){let e=eo(t);yield{type:"error",message:e.message,code:e.code}}finally{this.clearAsyncInputs(e),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),p&&!m&&await (0,r.rm)(p,{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 release(e){this.ensureAvailable(),await this.client.request("thread/unsubscribe",{threadId:e})}async answerQuestion(e,t){let s=this.pendingAsyncInputs.get(e);if(s){let i=t.answer.trim();if(!i||this.activeTurnIds.get(s.threadId)!==s.turnId)throw new x.n("问题已结束或回答为空,请刷新会话后重试。","QUESTION_ANSWER_FAILED");try{await this.client.request("turn/steer",{threadId:s.threadId,expectedTurnId:s.turnId,input:[{type:"text",text:`关于“${s.question}”的回答:
|
|
3
|
-
${i}`,text_elements:[]}]})}catch(e){throw new x.n(e instanceof Error?e.message:"回答发送失败,请重试。","QUESTION_ANSWER_FAILED")}return this.pendingAsyncInputs.delete(e),!0}let i=this.pendingApprovals.get(e);if(!i)return!1;this.pendingApprovals.delete(e);let r=t.answer.trim();if("item/tool/requestUserInput"===i.method){let e=i.params.questions;return this.client.respond(i.requestId,{answers:Object.fromEntries((e??[]).map(e=>[e.id,{answers:[r]}]))}),!0}return this.client.respond(i.requestId,$(i,r)),!0}async dispose(){await this.client.dispose()}ensureAvailable(){if(this.unavailableError)throw new x.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,N.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,N.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;if("turn/completed"===e.method){let e=en(t.turn).id,i=this.pagedTurnItems.get(s);i&&"string"==typeof e&&(i.turns.delete(e),i.statuses.delete(e),i.walkCursor=void 0,i.exhausted=!1),this.clearAsyncInputs(s)}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=en(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="string"==typeof t.turnId?t.turnId:"string"==typeof t.turn?.id?t.turn.id:this.activeTurnIds.get(s),a=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=en(en(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);a&&i.push(a);let n=t.item;if(("item/started"===e.method||"item/completed"===e.method)&&n?.type==="agentMessage"&&"async"===n.delivery&&n.id&&r){let t=`${s}:${n.id}`;if(this.asyncInputItems.add(t),"item/completed"===e.method){if(this.asyncInputItems.has(`${t}:completed`))return;this.asyncInputItems.add(`${t}:completed`),(Array.isArray(n.questions)?n.questions:[]).forEach((e,t)=>{let a=en(e);if("string"!=typeof a.title||!a.title.trim())return;let o=`native:${this.activeBrokerRunIds.get(s)??s}:async:${n.id}:${t}`;this.pendingAsyncInputs.has(o)||(this.pendingAsyncInputs.set(o,{threadId:s,turnId:r,question:a.title}),i.push({type:"ask_user",questionId:o,question:a.title,options:Array.isArray(a.options)?a.options.flatMap(e=>"string"==typeof e?[{label:e,description:""}]:[]):void 0}))})}return}if("item/started"===e.method&&n?.type==="agentMessage"&&"string"==typeof n.id){let e=et(n.phase);e&&this.agentMessagePhases.set(`${s}:${n.id}`,e)}let o=function(e){if("item/reasoning/summaryTextDelta"!==e.method&&"item/reasoning/summaryPartAdded"!==e.method)return null;let t=en(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(o){i.push(r?{...o,turnId:r}:o);return}if("item/reasoning/textDelta"!==e.method){if("item/agentMessage/delta"===e.method&&"string"==typeof t.delta){let e="string"==typeof t.itemId?t.itemId:void 0;if(e&&this.asyncInputItems.has(`${s}:${e}`))return;let a=e?this.agentMessagePhases.get(`${s}:${e}`):void 0;i.push({type:"text_chunk",text:t.delta,...r?{turnId:r}:{},...e?{itemId:e}:{},...a?{messagePhase:a}:{}});return}if("item/started"===e.method){let e=ei(t.item);e&&i.push({type:"tool_call",toolCall:e,...r?{turnId:r}:{}});return}if("item/completed"===e.method){n?.type==="agentMessage"&&"string"==typeof n.id&&this.agentMessagePhases.delete(`${s}:${n.id}`);let e=er(n);e&&i.push({type:"tool_result",result:e,...r?{turnId:r}:{}});return}if("turn/completed"===e.method){let e=t.turn;for(let e of(this.activeTurnIds.delete(s),this.agentMessagePhases.keys()))e.startsWith(`${s}:`)&&this.agentMessagePhases.delete(e);if(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,ea(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=ea(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())}}clearAsyncInputs(e){for(let[t,s]of this.pendingAsyncInputs)s.threadId===e&&(this.pendingAsyncInputs.delete(t),this.onApprovalResolved?.(t));for(let t of this.asyncInputItems)t.startsWith(`${e}:`)&&this.asyncInputItems.delete(t)}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 x.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,$(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(W(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 U(e,t){return e.flatMap(e=>e.path&&("win32"===t?n.win32.isAbsolute(e.path):(0,n.isAbsolute)(e.path))?[e.path]:[])}function $(e,t){let s="本会话允许"===t?"acceptForSession":"允许一次"===t?"accept":"取消"===t?"cancel":"decline";return"item/permissions/requestApproval"!==e.method?{decision:s}:{permissions:"accept"===s||"acceptForSession"===s?W(e.params):Array.isArray(W(e.params))?[]:{},scope:"acceptForSession"===s?"session":"turn"}}function W(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 F(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}}function V(e){let t=e.trim(),s=-1;if(t.startsWith(A)){let e=t.indexOf(k,A.length);if(e<0)return{content:t};s=e+k.length}else{if(!t.startsWith(M))return{content:t};let e=t.indexOf(L,M.length);if(e<0)return{content:t};s=e+L.length}let i=t.indexOf(P,s);if(i<0)return{content:t};let r=t.slice(i+P.length).trim();return r?{content:r,rawContent:t}:{content:t}}async function j(e){let t=(0,n.basename)(e)||"image",s=D[(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}}}let G="history.v1.";function B(e){return`${G}${e}`}function z(e,t){if(!e?.startsWith(G))return t;let s=Number(e.slice(G.length));return!Number.isSafeInteger(s)||s<0?t:Math.min(s,t)}function H(e){return(e??[]).flatMap(e=>("local_image"===e.type||"localImage"===e.type)&&"string"==typeof e.path?[e.path]:[])}function X(e,t){let s=[];for(let i of e){let e=Y(i);for(let r of i.items??[])if("userMessage"===r.type){let e=r.content,a=e?.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>String(e.text)).join("\n").trim();if(!a)continue;let o=V(a),l=H(e);s.push({role:"user",content:o.content,presentation:{executionTrace:{turnId:i.id},...o.rawContent?{rawContent:o.rawContent}:{},...l.length>0?{attachments:l.map(e=>t?.get(e)??{type:"image",name:(0,n.basename)(e),unavailable:!0})}:{}}})}else if(Z(r,i.status,e)&&"string"==typeof r.text&&r.text.trim()){let e=ee(r);s.push({role:"assistant",content:r.text,...e?{presentation:e}:{}})}}return s}function Q(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let s="",i=0;for(let r of e){let e=Buffer.byteLength(r,"utf8");if(i+e>Math.max(0,t-3))break;s+=r,i+=e}return`${s}...`}async function K(e,t={}){let s=[];for(let i of e)for(let e of i.items??[])if("userMessage"===e.type){let t=e.content,i=t?.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>String(e.text)).join("\n").trim();if(i){let e=V(i),r=H(t),a=await Promise.all(r.map(j)),n=e.rawContent||a.length>0?{...e.rawContent?{rawContent:e.rawContent}:{},...a.length>0?{attachments:a}:{}}:void 0;s.push({role:"user",content:e.content,...n?{presentation:n}:{}})}}else if("agentMessage"===e.type&&"string"==typeof e.text&&e.text.trim()){if("async"===e.delivery&&"inProgress"===i.status)continue;let t=ee(e);s.push({role:"assistant",content:e.text,...es(i.id,"agent",e.id)?{historyId:es(i.id,"agent",e.id)}:{},...t?{presentation:t}:{}})}else if("reasoning"===e.type&&Array.isArray(e.summary)){let r=e.summary.flatMap((s,i)=>"string"==typeof s&&s.trim()?[{itemId:e.id??`reasoning-${i}`,sectionIndex:i,text:t.reasoningMaxBytes?Q(s,t.reasoningMaxBytes):s}]:[]);r.length>0&&s.push({role:"assistant",content:"",...es(i.id,"reasoning",e.id)?{historyId:es(i.id,"reasoning",e.id)}:{},presentation:{reasoning:r}})}else{let r=ei(e),a=r&&t.toolArgumentsMaxBytes?{...r,arguments:function(e,t){let s=JSON.stringify(e);if(Buffer.byteLength(s,"utf8")<=t)return e;let i={__truncated:!0};for(let[t,s]of Object.entries(e))"string"==typeof s?i[t]=Q(s,512):"number"==typeof s||"boolean"==typeof s||null===s?i[t]=s:"changes"===t&&Array.isArray(s)?i[t]=s.slice(0,20).map(e=>{let t=en(e);return Object.fromEntries(["path","file_path","kind","status"].flatMap(e=>e in t?[[e,t[e]]]:[]))}):Array.isArray(s)?i[t]=`[${s.length} items omitted]`:i[t]="[object omitted]";let r=JSON.stringify(i);return Buffer.byteLength(r,"utf8")<=t?i:{__truncated:!0,preview:Q(s,t-64)}}(r.arguments,t.toolArgumentsMaxBytes)}:r;a&&s.push({role:"assistant",content:"",...es(i.id,"tool-call",e.id)?{historyId:es(i.id,"tool-call",e.id)}:{},toolCalls:[a]});let n=er(e);n&&"lazy"===t.toolResultMode&&t.revision&&e.id?s.push({role:"tool",content:"",historyId:es(i.id,"tool-result",e.id),toolCallId:n.toolCallId,name:r?.name,toolResultRef:{turnId:i.id,itemId:e.id,revision:t.revision,byteSize:Buffer.byteLength(n.content,"utf8"),...void 0===n.isError?{}:{isError:n.isError}}}):n&&s.push({role:"tool",content:n.content,...es(i.id,"tool-result",e.id)?{historyId:es(i.id,"tool-result",e.id)}:{},toolCallId:n.toolCallId,name:r?.name})}return s}function J(e){return"tool"===e.role||"assistant"===e.role&&!!(e.toolCalls?.length||e.presentation?.reasoning?.length||e.presentation?.agentMessagePhase==="commentary")}function Y(e){if(!("completed"!==e.status||e.items.some(e=>"final_answer"===e.phase&&"async"!==e.delivery)))for(let t=e.items.length-1;t>=0;t-=1){let s=e.items[t];if("agentMessage"===s.type&&"async"!==s.delivery&&"commentary"!==s.phase&&"string"==typeof s.text&&s.text.trim())return s}}function Z(e,t,s){return"agentMessage"===e.type&&"commentary"!==e.phase&&"async"!==e.delivery&&("final_answer"===e.phase||"completed"===t&&e===s)}function ee(e){let t="async"===e.delivery?"commentary":et(e.phase);return t?{agentMessagePhase:t}:void 0}function et(e){return"commentary"===e||"final_answer"===e?e:void 0}function es(e,t,s){return"string"==typeof s&&s?`codex-trace:${e}:${t}:${s}`:void 0}function ei(e){if(!e?.id)return null;if("commandExecution"===e.type){let t=Array.isArray(e.commandActions)?e.commandActions:[],s=1===t.length?en(t[0]):null;return s?.type==="read"&&"string"==typeof s.path&&s.path?{id:e.id,name:"read_file",arguments:{file_path:s.path,command:e.command,cwd:e.cwd}}:{id:e.id,name:"shell",arguments:{command:e.command,cwd:e.cwd}}}return"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:en(e.arguments)}:"dynamicToolCall"===e.type?{id:e.id,name:String(e.tool),arguments:en(e.arguments)}:null}function er(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 ea(e){for(let t=e.length-1;t>=0;t--){let s=e[t];if("agentMessage"===s.type&&"async"!==s.delivery&&"string"==typeof s.text)return s.text}return""}function en(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{value:e}}function eo(e){return e instanceof x.n?e:new x.n(e instanceof Error?e.message:String(e),"NATIVE_PROTOCOL_ERROR")}},7186:(e,t,s)=>{s.d(t,{c:()=>r});var i=s(132);class r{constructor(e,t,s=()=>void 0){this.adapter=e,this.catalog=t,this.onCompatibilityChanged=s,this.primaryNativeSessionIds=new Set,this.pendingProbes=new Map,this.probing=!1,this.disposed=!1,this.catalog.setOnCheckingEntry(e=>this.enqueueProbe(e))}setOnCompatibilityChanged(e){this.onCompatibilityChanged=e}start(){this.catalog.start()}supplement(e){for(let t of e)this.primaryNativeSessionIds.add(t.nativeSessionId);return[...e,...this.catalog.summaries().filter(e=>!this.primaryNativeSessionIds.has(e.nativeSessionId))]}registerPrimary(e){this.primaryNativeSessionIds.add(e)}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.disposed=!0,this.pendingProbes.clear(),this.catalog.setOnCheckingEntry(void 0),this.catalog.dispose()}enqueueProbe(e){this.disposed||(this.pendingProbes.set(e.nativeSessionId,e),this.drainProbes())}async drainProbes(){if(!this.probing&&!this.disposed){this.probing=!0;try{for(;!this.disposed&&this.pendingProbes.size>0;){let e=this.pendingProbes.entries().next().value;if(!e)break;let[t,s]=e;this.pendingProbes.delete(t),await this.probeEntry(s)}}finally{this.probing=!1}}}async probeEntry(e){try{if(await this.adapter.getSession(e.nativeSessionId),!this.isCurrentEntry(e))return;this.catalog.updateCompatibility(e.nativeSessionId,{status:"direct",readerVersion:e.compatibility.readerVersion,...e.producerVersion?{producerVersion:e.producerVersion}:{},...e.formatKey?{formatKey:e.formatKey}:{}}),this.onCompatibilityChanged()}catch(s){if(s instanceof i.n&&("RUNTIME_UNAVAILABLE"===s.code||"SESSION_NOT_FOUND"===s.code)||!this.isCurrentEntry(e))return;let t=e.producerVersion?`该会话由 Codex ${e.producerVersion} 创建,当前 Codex ${e.compatibility.readerVersion} 无法读取`:`当前 Codex ${e.compatibility.readerVersion} 无法读取该会话的历史格式`;this.catalog.updateCompatibility(e.nativeSessionId,{status:"incompatible",readerVersion:e.compatibility.readerVersion,...e.producerVersion?{producerVersion:e.producerVersion}:{},...e.formatKey?{formatKey:e.formatKey}:{},reasonCode:"CODEX_SESSION_DIRECT_READ_FAILED",reason:t}),this.onCompatibilityChanged()}}isCurrentEntry(e){let t=this.catalog.findByNativeSessionId(e.nativeSessionId);return t?.canonicalPath===e.canonicalPath&&t.size===e.size&&t.mtimeNs===e.mtimeNs&&"checking"===t.compatibility.status}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??h,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)}setOnCheckingEntry(e){this.onCheckingEntry=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,h=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);h+=g.bytesRead;let y=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 h=c?.type==="session_meta"&&c.payload&&"object"==typeof c.payload?c.payload:null,m="string"==typeof h?.id&&d.test(h.id)?h.id:void 0,f=p(h?.cli_version),g=function(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}(p(h?.timestamp))??l,y=p(h?.cwd)??"",w=p(h?.parent_thread_id)??p(h?.parent_id),v=h?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)}`}(h):void 0,I=s.complete?h?void 0:"无法识别会话元数据格式":`会话元数据超过 256 KiB 安全上限`,_=!I&&(m||n)?{status:"checking",readerVersion:r,...f?{producerVersion:f}:{},...v?{formatKey:v}:{}}:{status:"incompatible",readerVersion:r,...f?{producerVersion:f}:{},...v?{formatKey:v}:{},reasonCode:"CODEX_SESSION_SCHEMA_UNKNOWN",reason:I??"无法恢复可验证的 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}:{},...v?{formatKey:v}:{},compatibility:_}}(s,l,g,this.options.readerVersion);n[e]=m&&m.nativeSessionId===y.nativeSessionId&&m.producerVersion===y.producerVersion&&m.formatKey===y.formatKey&&m.probeable===y.probeable?{...y,compatibility:m.compatibility}:y}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),v=this.hasCompletedScan?y.filter(e=>{let t=a.get(e.canonicalPath);return e.probeable&&"checking"===e.compatibility.status&&(!t||t.size!==e.size||t.mtimeNs!==e.mtimeNs)}):[];for(let e of(this.entries=y,(c>0||w)&&this.options.repository.replace(this.entries,this.cacheIdentity()),v))this.onCheckingEntry?.(e);let I=Math.max(0,this.now()-r),_=this.hasCompletedScan?200:1e3;return this.hasCompletedScan=!0,I>_?this.consecutiveBudgetBreaches+=1:this.consecutiveBudgetBreaches=0,this.consecutiveBudgetBreaches>=3&&(this.breakerUntil=this.now()+3e5,this.consecutiveBudgetBreaches=0),{durationMs:I,filesVisited:s.length,changedFiles:c,metadataBytesRead:h,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 h={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 p(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),h=s(3088),p=s(9529),m=s(4998),f=s(7186),g=s(3053),y=s(8733),w=s(2815),v=s(5779),I=s(132),_=s(2428),S=e([h]);h=(S.then?(await S)():S)[0];class V{constructor(e,t){this.now=t,this.closed=!1,(0,a.mkdirSync)(e,{recursive:!0,mode:448});try{(0,a.chmodSync)(e,448)}catch{}this.database=new d.G1b(e),this.database.db.exec(`
|
|
3
|
+
${i}`,text_elements:[]}]})}catch(e){throw new x.n(e instanceof Error?e.message:"回答发送失败,请重试。","QUESTION_ANSWER_FAILED")}return this.pendingAsyncInputs.delete(e),!0}let i=this.pendingApprovals.get(e);if(!i)return!1;this.pendingApprovals.delete(e);let r=t.answer.trim();if("item/tool/requestUserInput"===i.method){let e=i.params.questions;return this.client.respond(i.requestId,{answers:Object.fromEntries((e??[]).map(e=>[e.id,{answers:[r]}]))}),!0}return this.client.respond(i.requestId,$(i,r)),!0}async dispose(){await this.client.dispose()}ensureAvailable(){if(this.unavailableError)throw new x.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,N.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,N.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;if("turn/completed"===e.method){let e=en(t.turn).id,i=this.pagedTurnItems.get(s);i&&"string"==typeof e&&(i.turns.delete(e),i.statuses.delete(e),i.walkCursor=void 0,i.exhausted=!1),this.clearAsyncInputs(s)}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=en(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="string"==typeof t.turnId?t.turnId:"string"==typeof t.turn?.id?t.turn.id:this.activeTurnIds.get(s),a=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=en(en(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);a&&i.push(a);let n=t.item;if(("item/started"===e.method||"item/completed"===e.method)&&n?.type==="agentMessage"&&"async"===n.delivery&&n.id&&r){let t=`${s}:${n.id}`;if(this.asyncInputItems.add(t),"item/completed"===e.method){if(this.asyncInputItems.has(`${t}:completed`))return;this.asyncInputItems.add(`${t}:completed`),(Array.isArray(n.questions)?n.questions:[]).forEach((e,t)=>{let a=en(e);if("string"!=typeof a.title||!a.title.trim())return;let o=`native:${this.activeBrokerRunIds.get(s)??s}:async:${n.id}:${t}`;this.pendingAsyncInputs.has(o)||(this.pendingAsyncInputs.set(o,{threadId:s,turnId:r,question:a.title}),i.push({type:"ask_user",questionId:o,question:a.title,options:Array.isArray(a.options)?a.options.flatMap(e=>"string"==typeof e?[{label:e,description:""}]:[]):void 0}))})}return}if("item/started"===e.method&&n?.type==="agentMessage"&&"string"==typeof n.id){let e=et(n.phase);e&&this.agentMessagePhases.set(`${s}:${n.id}`,e)}let o=function(e){if("item/reasoning/summaryTextDelta"!==e.method&&"item/reasoning/summaryPartAdded"!==e.method)return null;let t=en(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(o){i.push(r?{...o,turnId:r}:o);return}if("item/reasoning/textDelta"!==e.method){if("item/agentMessage/delta"===e.method&&"string"==typeof t.delta){let e="string"==typeof t.itemId?t.itemId:void 0;if(e&&this.asyncInputItems.has(`${s}:${e}`))return;let a=e?this.agentMessagePhases.get(`${s}:${e}`):void 0;i.push({type:"text_chunk",text:t.delta,...r?{turnId:r}:{},...e?{itemId:e}:{},...a?{messagePhase:a}:{}});return}if("item/started"===e.method){let e=ei(t.item);e&&i.push({type:"tool_call",toolCall:e,...r?{turnId:r}:{}});return}if("item/completed"===e.method){n?.type==="agentMessage"&&"string"==typeof n.id&&this.agentMessagePhases.delete(`${s}:${n.id}`);let e=er(n);e&&i.push({type:"tool_result",result:e,...r?{turnId:r}:{}});return}if("turn/completed"===e.method){let e=t.turn;for(let e of(this.activeTurnIds.delete(s),this.agentMessagePhases.keys()))e.startsWith(`${s}:`)&&this.agentMessagePhases.delete(e);if(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,ea(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=ea(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())}}clearAsyncInputs(e){for(let[t,s]of this.pendingAsyncInputs)s.threadId===e&&(this.pendingAsyncInputs.delete(t),this.onApprovalResolved?.(t));for(let t of this.asyncInputItems)t.startsWith(`${e}:`)&&this.asyncInputItems.delete(t)}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 x.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,$(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(W(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 U(e,t){return e.flatMap(e=>e.path&&("win32"===t?n.win32.isAbsolute(e.path):(0,n.isAbsolute)(e.path))?[e.path]:[])}function $(e,t){let s="本会话允许"===t?"acceptForSession":"允许一次"===t?"accept":"取消"===t?"cancel":"decline";return"item/permissions/requestApproval"!==e.method?{decision:s}:{permissions:"accept"===s||"acceptForSession"===s?W(e.params):Array.isArray(W(e.params))?[]:{},scope:"acceptForSession"===s?"session":"turn"}}function W(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 F(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}}function V(e){let t=e.trim(),s=-1;if(t.startsWith(A)){let e=t.indexOf(k,A.length);if(e<0)return{content:t};s=e+k.length}else{if(!t.startsWith(M))return{content:t};let e=t.indexOf(L,M.length);if(e<0)return{content:t};s=e+L.length}let i=t.indexOf(P,s);if(i<0)return{content:t};let r=t.slice(i+P.length).trim();return r?{content:r,rawContent:t}:{content:t}}async function j(e){let t=(0,n.basename)(e)||"image",s=D[(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}}}let G="history.v1.";function B(e){return`${G}${e}`}function z(e,t){if(!e?.startsWith(G))return t;let s=Number(e.slice(G.length));return!Number.isSafeInteger(s)||s<0?t:Math.min(s,t)}function H(e){return(e??[]).flatMap(e=>("local_image"===e.type||"localImage"===e.type)&&"string"==typeof e.path?[e.path]:[])}function X(e,t){let s=[];for(let i of e){let e=Y(i);for(let r of i.items??[])if("userMessage"===r.type){let e=r.content,a=e?.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>String(e.text)).join("\n").trim();if(!a)continue;let o=V(a),l=H(e);s.push({role:"user",content:o.content,presentation:{executionTrace:{turnId:i.id},...o.rawContent?{rawContent:o.rawContent}:{},...l.length>0?{attachments:l.map(e=>t?.get(e)??{type:"image",name:(0,n.basename)(e),unavailable:!0})}:{}}})}else if(Z(r,i.status,e)&&"string"==typeof r.text&&r.text.trim()){let e=ee(r);s.push({role:"assistant",content:r.text,...e?{presentation:e}:{}})}}return s}function Q(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let s="",i=0;for(let r of e){let e=Buffer.byteLength(r,"utf8");if(i+e>Math.max(0,t-3))break;s+=r,i+=e}return`${s}...`}async function K(e,t={}){let s=[];for(let i of e)for(let e of i.items??[])if("userMessage"===e.type){let t=e.content,i=t?.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>String(e.text)).join("\n").trim();if(i){let e=V(i),r=H(t),a=await Promise.all(r.map(j)),n=e.rawContent||a.length>0?{...e.rawContent?{rawContent:e.rawContent}:{},...a.length>0?{attachments:a}:{}}:void 0;s.push({role:"user",content:e.content,...n?{presentation:n}:{}})}}else if("agentMessage"===e.type&&"string"==typeof e.text&&e.text.trim()){if("async"===e.delivery&&"inProgress"===i.status)continue;let t=ee(e);s.push({role:"assistant",content:e.text,...es(i.id,"agent",e.id)?{historyId:es(i.id,"agent",e.id)}:{},...t?{presentation:t}:{}})}else if("reasoning"===e.type&&Array.isArray(e.summary)){let r=e.summary.flatMap((s,i)=>"string"==typeof s&&s.trim()?[{itemId:e.id??`reasoning-${i}`,sectionIndex:i,text:t.reasoningMaxBytes?Q(s,t.reasoningMaxBytes):s}]:[]);r.length>0&&s.push({role:"assistant",content:"",...es(i.id,"reasoning",e.id)?{historyId:es(i.id,"reasoning",e.id)}:{},presentation:{reasoning:r}})}else{let r=ei(e),a=r&&t.toolArgumentsMaxBytes?{...r,arguments:function(e,t){let s=JSON.stringify(e);if(Buffer.byteLength(s,"utf8")<=t)return e;let i={__truncated:!0};for(let[t,s]of Object.entries(e))"string"==typeof s?i[t]=Q(s,512):"number"==typeof s||"boolean"==typeof s||null===s?i[t]=s:"changes"===t&&Array.isArray(s)?i[t]=s.slice(0,20).map(e=>{let t=en(e);return Object.fromEntries(["path","file_path","kind","status"].flatMap(e=>e in t?[[e,t[e]]]:[]))}):Array.isArray(s)?i[t]=`[${s.length} items omitted]`:i[t]="[object omitted]";let r=JSON.stringify(i);return Buffer.byteLength(r,"utf8")<=t?i:{__truncated:!0,preview:Q(s,t-64)}}(r.arguments,t.toolArgumentsMaxBytes)}:r;a&&s.push({role:"assistant",content:"",...es(i.id,"tool-call",e.id)?{historyId:es(i.id,"tool-call",e.id)}:{},toolCalls:[a]});let n=er(e);n&&"lazy"===t.toolResultMode&&t.revision&&e.id?s.push({role:"tool",content:"",historyId:es(i.id,"tool-result",e.id),toolCallId:n.toolCallId,name:r?.name,toolResultRef:{turnId:i.id,itemId:e.id,revision:t.revision,byteSize:Buffer.byteLength(n.content,"utf8"),...void 0===n.isError?{}:{isError:n.isError}}}):n&&s.push({role:"tool",content:n.content,...es(i.id,"tool-result",e.id)?{historyId:es(i.id,"tool-result",e.id)}:{},toolCallId:n.toolCallId,name:r?.name})}return s}function J(e){return"tool"===e.role||"assistant"===e.role&&!!(e.toolCalls?.length||e.presentation?.reasoning?.length||e.presentation?.agentMessagePhase==="commentary")}function Y(e){if(!("completed"!==e.status||e.items.some(e=>"final_answer"===e.phase&&"async"!==e.delivery)))for(let t=e.items.length-1;t>=0;t-=1){let s=e.items[t];if("agentMessage"===s.type&&"async"!==s.delivery&&"commentary"!==s.phase&&"string"==typeof s.text&&s.text.trim())return s}}function Z(e,t,s){return"agentMessage"===e.type&&"commentary"!==e.phase&&"async"!==e.delivery&&("final_answer"===e.phase||"completed"===t&&e===s)}function ee(e){let t="async"===e.delivery?"commentary":et(e.phase);return t?{agentMessagePhase:t}:void 0}function et(e){return"commentary"===e||"final_answer"===e?e:void 0}function es(e,t,s){return"string"==typeof s&&s?`codex-trace:${e}:${t}:${s}`:void 0}function ei(e){if(!e?.id)return null;if("commandExecution"===e.type){let t=Array.isArray(e.commandActions)?e.commandActions:[],s=1===t.length?en(t[0]):null;return s?.type==="read"&&"string"==typeof s.path&&s.path?{id:e.id,name:"read_file",arguments:{file_path:s.path,command:e.command,cwd:e.cwd}}:{id:e.id,name:"shell",arguments:{command:e.command,cwd:e.cwd}}}return"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:en(e.arguments)}:"dynamicToolCall"===e.type?{id:e.id,name:String(e.tool),arguments:en(e.arguments)}:null}function er(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 ea(e){for(let t=e.length-1;t>=0;t--){let s=e[t];if("agentMessage"===s.type&&"async"!==s.delivery&&"string"==typeof s.text)return s.text}return""}function en(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{value:e}}function eo(e){return e instanceof x.n?e:new x.n(e instanceof Error?e.message:String(e),"NATIVE_PROTOCOL_ERROR")}},7186:(e,t,s)=>{s.d(t,{c:()=>r});var i=s(132);class r{constructor(e,t,s=()=>void 0){this.adapter=e,this.catalog=t,this.onCompatibilityChanged=s,this.primaryNativeSessionIds=new Set,this.pendingProbes=new Map,this.probing=!1,this.disposed=!1,this.catalog.setOnCheckingEntry(e=>this.enqueueProbe(e))}setOnCompatibilityChanged(e){this.onCompatibilityChanged=e}start(){this.catalog.start()}supplement(e){for(let t of e)this.primaryNativeSessionIds.add(t.nativeSessionId);return[...e,...this.catalog.summaries().filter(e=>!this.primaryNativeSessionIds.has(e.nativeSessionId))]}registerPrimary(e){this.primaryNativeSessionIds.add(e)}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.disposed=!0,this.pendingProbes.clear(),this.catalog.setOnCheckingEntry(void 0),this.catalog.dispose()}enqueueProbe(e){this.disposed||(this.pendingProbes.set(e.nativeSessionId,e),this.drainProbes())}async drainProbes(){if(!this.probing&&!this.disposed){this.probing=!0;try{for(;!this.disposed&&this.pendingProbes.size>0;){let e=this.pendingProbes.entries().next().value;if(!e)break;let[t,s]=e;this.pendingProbes.delete(t),await this.probeEntry(s)}}finally{this.probing=!1}}}async probeEntry(e){try{if(await this.adapter.getSession(e.nativeSessionId),!this.isCurrentEntry(e))return;this.catalog.updateCompatibility(e.nativeSessionId,{status:"direct",readerVersion:e.compatibility.readerVersion,...e.producerVersion?{producerVersion:e.producerVersion}:{},...e.formatKey?{formatKey:e.formatKey}:{}}),this.onCompatibilityChanged()}catch(s){if(s instanceof i.n&&("RUNTIME_UNAVAILABLE"===s.code||"SESSION_NOT_FOUND"===s.code)||!this.isCurrentEntry(e))return;let t=e.producerVersion?`该会话由 Codex ${e.producerVersion} 创建,当前 Codex ${e.compatibility.readerVersion} 无法读取`:`当前 Codex ${e.compatibility.readerVersion} 无法读取该会话的历史格式`;this.catalog.updateCompatibility(e.nativeSessionId,{status:"incompatible",readerVersion:e.compatibility.readerVersion,...e.producerVersion?{producerVersion:e.producerVersion}:{},...e.formatKey?{formatKey:e.formatKey}:{},reasonCode:"CODEX_SESSION_DIRECT_READ_FAILED",reason:t}),this.onCompatibilityChanged()}}isCurrentEntry(e){let t=this.catalog.findByNativeSessionId(e.nativeSessionId);return t?.canonicalPath===e.canonicalPath&&t.size===e.size&&t.mtimeNs===e.mtimeNs&&"checking"===t.compatibility.status}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??h,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)}setOnCheckingEntry(e){this.onCheckingEntry=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,h=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);h+=g.bytesRead;let y=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 h=c?.type==="session_meta"&&c.payload&&"object"==typeof c.payload?c.payload:null,m="string"==typeof h?.id&&d.test(h.id)?h.id:void 0,f=p(h?.cli_version),g=function(e){if(!e)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}(p(h?.timestamp))??l,y=p(h?.cwd)??"",w=p(h?.parent_thread_id)??p(h?.parent_id),v=h?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)}`}(h):void 0,I=s.complete?h?void 0:"无法识别会话元数据格式":`会话元数据超过 256 KiB 安全上限`,_=!I&&(m||n)?{status:"checking",readerVersion:r,...f?{producerVersion:f}:{},...v?{formatKey:v}:{}}:{status:"incompatible",readerVersion:r,...f?{producerVersion:f}:{},...v?{formatKey:v}:{},reasonCode:"CODEX_SESSION_SCHEMA_UNKNOWN",reason:I??"无法恢复可验证的 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}:{},...v?{formatKey:v}:{},compatibility:_}}(s,l,g,this.options.readerVersion);n[e]=m&&m.nativeSessionId===y.nativeSessionId&&m.producerVersion===y.producerVersion&&m.formatKey===y.formatKey&&m.probeable===y.probeable?{...y,compatibility:m.compatibility}:y}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),v=this.hasCompletedScan?y.filter(e=>{let t=a.get(e.canonicalPath);return e.probeable&&"checking"===e.compatibility.status&&(!t||t.size!==e.size||t.mtimeNs!==e.mtimeNs)}):[];for(let e of(this.entries=y,(c>0||w)&&this.options.repository.replace(this.entries,this.cacheIdentity()),v))this.onCheckingEntry?.(e);let I=Math.max(0,this.now()-r),_=this.hasCompletedScan?200:1e3;return this.hasCompletedScan=!0,I>_?this.consecutiveBudgetBreaches+=1:this.consecutiveBudgetBreaches=0,this.consecutiveBudgetBreaches>=3&&(this.breakerUntil=this.now()+3e5,this.consecutiveBudgetBreaches=0),{durationMs:I,filesVisited:s.length,changedFiles:c,metadataBytesRead:h,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 h={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 p(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={}){let i=s.platform??process.platform;if("win32"===i)return new Set;try{let n=s.execute??a,{stdout:o}=await n("darwin"===i?"/usr/sbin/lsof":"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}(o,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),h=s(3088),p=s(9529),m=s(4998),f=s(7186),g=s(3053),y=s(8733),w=s(2815),v=s(5779),I=s(132),_=s(2428),S=e([h]);h=(S.then?(await S)():S)[0];class V{constructor(e,t){this.now=t,this.closed=!1,(0,a.mkdirSync)(e,{recursive:!0,mode:448});try{(0,a.chmodSync)(e,448)}catch{}this.database=new d.G1b(e),this.database.db.exec(`
|
|
4
4
|
CREATE TABLE IF NOT EXISTS native_runtime_policy (
|
|
5
5
|
session_id TEXT PRIMARY KEY,
|
|
6
6
|
permission_mode TEXT NOT NULL,
|