@tencent-ai/agent-sdk 0.3.269 → 0.3.270
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/cli/CHANGELOG.md +21 -0
- package/cli/dist/codebuddy-headless.js +111 -108
- package/cli/dist/codebuddy-lite-wb.mjs +143 -140
- package/cli/dist/web-ui/assets/{CanvasPaneStandaloneView-AFymTrqt.js → CanvasPaneStandaloneView-CDO7isWn.js} +1 -1
- package/cli/dist/web-ui/assets/{CanvasView-CoxUIOeY.js → CanvasView-DJNkeBGK.js} +1 -1
- package/cli/dist/web-ui/assets/{ChangesView-CTnio3qy.js → ChangesView-fCuIktEK.js} +1 -1
- package/cli/dist/web-ui/assets/{DocsView-DfGq3q0Y.js → DocsView-B79hLvzs.js} +1 -1
- package/cli/dist/web-ui/assets/{EditorView-CYw2oZg1.js → EditorView-7YnlryBL.js} +1 -1
- package/cli/dist/web-ui/assets/{KeybindingsView-D6w9QUh3.js → KeybindingsView-CIDkpkAb.js} +1 -1
- package/cli/dist/web-ui/assets/{LogsView-CP5xbyy4.js → LogsView-Bcv52scT.js} +1 -1
- package/cli/dist/web-ui/assets/{MetricsView-C2c14t7O.js → MetricsView-DUSiPsda.js} +1 -1
- package/cli/dist/web-ui/assets/{PluginsView-BSEje_UM.js → PluginsView-BTOCj9co.js} +1 -1
- package/cli/dist/web-ui/assets/{RemoteControlView-2f1ZwMQ5.js → RemoteControlView-YqmY0vro.js} +1 -1
- package/cli/dist/web-ui/assets/{SettingsView-tOHto0ek.js → SettingsView-D2wIPOBw.js} +1 -1
- package/cli/dist/web-ui/assets/{SplitContainer-q9iSME5N.js → SplitContainer-DlEN5H4s.js} +1 -1
- package/cli/dist/web-ui/assets/{StatsView-BVIL7ys1.js → StatsView-C7iB42TQ.js} +1 -1
- package/cli/dist/web-ui/assets/{TasksView-BuNGf8H8.js → TasksView-CKm5dh4d.js} +1 -1
- package/cli/dist/web-ui/assets/{TerminalPaneView-IZXBrZd0.js → TerminalPaneView-Cs-7CKCw.js} +1 -1
- package/cli/dist/web-ui/assets/{TracesView-BagVLm59.js → TracesView-4MhXOs0J.js} +1 -1
- package/cli/dist/web-ui/assets/{WorkersView-CFhFpbFC.js → WorkersView-B5SyD2xB.js} +1 -1
- package/cli/dist/web-ui/assets/{abnfDiagram-O67JEVCF-BbyhIfaI.js → abnfDiagram-O67JEVCF-luL6Qe5x.js} +1 -1
- package/cli/dist/web-ui/assets/architecture-7GRP2DOG-CVyCykh_.js +1 -0
- package/cli/dist/web-ui/assets/{architectureDiagram-NJMV4G6O-DxDD6eVt.js → architectureDiagram-NJMV4G6O-CXZjweyd.js} +1 -1
- package/cli/dist/web-ui/assets/{blockDiagram-BEXU5L5S-DTRa2Tb9.js → blockDiagram-BEXU5L5S-DceMcN-6.js} +1 -1
- package/cli/dist/web-ui/assets/{c4Diagram-YGBWAQC7--r-yED_M.js → c4Diagram-YGBWAQC7-Chr6hcY4.js} +1 -1
- package/cli/dist/web-ui/assets/{canvas-store-BpQ38Vml.js → canvas-store-CLGZ388s.js} +1 -1
- package/cli/dist/web-ui/assets/channel-pxcszUh2.js +1 -0
- package/cli/dist/web-ui/assets/{chunk-3FUC2YCW-CrLNasJM.js → chunk-3FUC2YCW-BRXxiofJ.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-5DYCD2WN-BvGB0nx-.js → chunk-5DYCD2WN-BJidDn4j.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-742MDFTN-BTBNbBjA.js → chunk-742MDFTN-D8PKsc6_.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-7INBJB4K-CnYo9mzQ.js → chunk-7INBJB4K-0OOQXMSm.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-7M6MHVWA-ChPc3AIy.js → chunk-7M6MHVWA-CinmEwpu.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-7PRAP22T-BWJP0sRU.js → chunk-7PRAP22T-D0WpyU-H.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-GTNCS2PH-BWIt5JBZ.js → chunk-GTNCS2PH-NNZzPISm.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-GWA4HPMP-DPP9EzOc.js → chunk-GWA4HPMP-CVQtrfg2.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-MBY4JIJT-WW7QGbUd.js → chunk-MBY4JIJT-B2Fs2skV.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-NETBCI7D-DvHPTWgP.js → chunk-NETBCI7D-DS15Lcf7.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-O7XYJQB3-DNIHMsy6.js → chunk-O7XYJQB3-irIWVhcH.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-UA2S7LBM-FmyRAjon.js → chunk-UA2S7LBM-DHv_5vdC.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-WEXAMYUT-DPGJtaXE.js → chunk-WEXAMYUT-DTnPpX3o.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-Z7XXMR3K-xCwg-Yew.js → chunk-Z7XXMR3K-CL6QEwjv.js} +1 -1
- package/cli/dist/web-ui/assets/{chunk-ZIGJFQKS-C33Iz6Fl.js → chunk-ZIGJFQKS-D-9hFu_x.js} +1 -1
- package/cli/dist/web-ui/assets/{classDiagram-v2-NBCMYWYE-CYRZjfMU.js → classDiagram-v2-NBCMYWYE-BGpw8OWR.js} +1 -1
- package/cli/dist/web-ui/assets/{cssMode-ClDS6DMb.js → cssMode-DYH1pn7V.js} +1 -1
- package/cli/dist/web-ui/assets/{cynefin-OW5HDTMX-BZMPI_-L.js → cynefin-OW5HDTMX-BwDHcOb3.js} +1 -1
- package/cli/dist/web-ui/assets/{cynefinDiagram-VND7K2PF-xv7006O3.js → cynefinDiagram-VND7K2PF-C04bh7p8.js} +1 -1
- package/cli/dist/web-ui/assets/{dagre-6A5THRUB-BaA5Prow.js → dagre-6A5THRUB-Dea8s6xE.js} +1 -1
- package/cli/dist/web-ui/assets/{diagram-22UHCM2B-CLPFfA4R.js → diagram-22UHCM2B-DJVauquX.js} +1 -1
- package/cli/dist/web-ui/assets/{diagram-3UASUU5V-DX9eVGvg.js → diagram-3UASUU5V-C7-A4v72.js} +1 -1
- package/cli/dist/web-ui/assets/{diagram-ATOU4E4O-C6tAUS3M.js → diagram-ATOU4E4O-7B6YBDOj.js} +1 -1
- package/cli/dist/web-ui/assets/{diagram-CDSNMT55-C4bjVjgp.js → diagram-CDSNMT55-DMAwoRXf.js} +1 -1
- package/cli/dist/web-ui/assets/{diagram-MLGK6HIB--R4pb2v7.js → diagram-MLGK6HIB-CNB_vlIZ.js} +1 -1
- package/cli/dist/web-ui/assets/{diagram-MPIPVDR6-DBZrcvRV.js → diagram-MPIPVDR6-hyhLuNp3.js} +1 -1
- package/cli/dist/web-ui/assets/{ebnfDiagram-ZINNZB2B-guH8XqK5.js → ebnfDiagram-ZINNZB2B-CJWaxsG5.js} +1 -1
- package/cli/dist/web-ui/assets/{editor-store-B581kWHa.js → editor-store-BxjPLrr9.js} +1 -1
- package/cli/dist/web-ui/assets/{editor.main-BDJb4JDA.js → editor.main-Czm6gHJH.js} +2 -2
- package/cli/dist/web-ui/assets/{elk-276RUBZZ-CeiKMULj.js → elk-276RUBZZ-D5Y00SxR.js} +1 -1
- package/cli/dist/web-ui/assets/{erDiagram-OPXOYQCR-sBAqBzrO.js → erDiagram-OPXOYQCR-BmYHBZJv.js} +1 -1
- package/cli/dist/web-ui/assets/eventmodeling-NTZA5JFV-D5vLpI9F.js +1 -0
- package/cli/dist/web-ui/assets/flowDiagram-KWPJA3E3-Cf58WNhf.js +1 -0
- package/cli/dist/web-ui/assets/{ganttDiagram-FUAMR5RP-C6_HpREX.js → ganttDiagram-FUAMR5RP-DbhB40jH.js} +1 -1
- package/cli/dist/web-ui/assets/{gitGraph-4MIJSDKK-BXoSq3Gg.js → gitGraph-4MIJSDKK-mjDyHNS1.js} +1 -1
- package/cli/dist/web-ui/assets/{gitGraphDiagram-X574FWY7-CGtaH2jU.js → gitGraphDiagram-X574FWY7-D7jHGUGu.js} +1 -1
- package/cli/dist/web-ui/assets/{htmlMode-D5olfuMo.js → htmlMode-BSBNaQvK.js} +1 -1
- package/cli/dist/web-ui/assets/{index-ClsikMuk.js → index-BtMp20L0.js} +6 -6
- package/cli/dist/web-ui/assets/{info-A6RAGUB7-DEwLfJ7B.js → info-A6RAGUB7-yf2Iyt5X.js} +1 -1
- package/cli/dist/web-ui/assets/{infoDiagram-VRGFBTTK-DCSOdK6X.js → infoDiagram-VRGFBTTK-CmWWZT96.js} +1 -1
- package/cli/dist/web-ui/assets/{ishikawaDiagram-OU5B5YK6-BseHnvYw.js → ishikawaDiagram-OU5B5YK6-NcOpKVNl.js} +1 -1
- package/cli/dist/web-ui/assets/{journeyDiagram-ZHPQQLJL-BRxQJTqW.js → journeyDiagram-ZHPQQLJL-dY4w9tp1.js} +1 -1
- package/cli/dist/web-ui/assets/{jsonMode-Cg5YHEwQ.js → jsonMode-BUaimt20.js} +1 -1
- package/cli/dist/web-ui/assets/{kanban-definition-PNTS6WVX-KI9YMfJk.js → kanban-definition-PNTS6WVX-BctMsDJJ.js} +1 -1
- package/cli/dist/web-ui/assets/{line-DprNiO-0.js → line-BYkTAP3U.js} +1 -1
- package/cli/dist/web-ui/assets/loader-circle-wVK1RLLa.js +1 -0
- package/cli/dist/web-ui/assets/{mermaid-parser.core-GTP4u3FU.js → mermaid-parser.core-BLRTQ_8m.js} +3 -3
- package/cli/dist/web-ui/assets/{mermaid.core-CNUJl-CG.js → mermaid.core-DGYOOYu5.js} +4 -4
- package/cli/dist/web-ui/assets/{mindmap-definition-NLK3R4M7-C2PcP9ry.js → mindmap-definition-NLK3R4M7-DtFEhmgs.js} +1 -1
- package/cli/dist/web-ui/assets/{packet-AYTQ26CC-CZLuLwvG.js → packet-AYTQ26CC-DG8Ws-Q6.js} +1 -1
- package/cli/dist/web-ui/assets/{pegDiagram-GJSIUBJH-Bm2hR9le.js → pegDiagram-GJSIUBJH-C1B_R8sV.js} +1 -1
- package/cli/dist/web-ui/assets/{pie-WAS4IAKB-CRzoh5ox.js → pie-WAS4IAKB-WpUKIR_Y.js} +1 -1
- package/cli/dist/web-ui/assets/{pieDiagram-5QR66LMP-CTJ2r9nd.js → pieDiagram-5QR66LMP-C7VoNMU4.js} +1 -1
- package/cli/dist/web-ui/assets/power-BNRlQx4o.js +1 -0
- package/cli/dist/web-ui/assets/{quadrantDiagram-O4NWA36T-CTKetN5z.js → quadrantDiagram-O4NWA36T-CXYTQ4y2.js} +1 -1
- package/cli/dist/web-ui/assets/{radar-RG4KPBEZ-DXjTvI5t.js → radar-RG4KPBEZ-C3VHLzXv.js} +1 -1
- package/cli/dist/web-ui/assets/{railroad-74A4TZTK-BDdQn4Gc.js → railroad-74A4TZTK-Py_5hLH_.js} +1 -1
- package/cli/dist/web-ui/assets/railroad-abnf-HS5TGJTU-CqoDhjmj.js +1 -0
- package/cli/dist/web-ui/assets/railroad-ebnf-LZEXJU2U-DUWdDy3z.js +1 -0
- package/cli/dist/web-ui/assets/railroad-peg-WCYAUIDC-Co6yi1zs.js +1 -0
- package/cli/dist/web-ui/assets/{railroadDiagram-XR7U4H2S-B_YntG1t.js → railroadDiagram-XR7U4H2S-5OEyONOk.js} +1 -1
- package/cli/dist/web-ui/assets/{requirementDiagram-PLB6GJNP-CDjL2cNi.js → requirementDiagram-PLB6GJNP-DUJYTLHd.js} +1 -1
- package/cli/dist/web-ui/assets/{sankeyDiagram-IPEJSGJF-qXJEVvf1.js → sankeyDiagram-IPEJSGJF-Bedevch2.js} +1 -1
- package/cli/dist/web-ui/assets/{sequenceDiagram-PO4LG4MO-l-r7gLpE.js → sequenceDiagram-PO4LG4MO-pgraPAoD.js} +1 -1
- package/cli/dist/web-ui/assets/{server-O9q4QgxP.js → server-Ccbyj1qh.js} +1 -1
- package/cli/dist/web-ui/assets/{sidebar-store-BI5HJsXT.js → sidebar-store-Rkdixr53.js} +1 -1
- package/cli/dist/web-ui/assets/{stateDiagram-v2-GCMORJYK-IswgvzFJ.js → stateDiagram-v2-GCMORJYK-DALpfmXP.js} +1 -1
- package/cli/dist/web-ui/assets/{swimlanes-2SLR337P-JwNdJjRm.js → swimlanes-2SLR337P-DYo2RgRV.js} +1 -1
- package/cli/dist/web-ui/assets/swimlanesDiagram-TC7HE7FX-Dxiovvmi.js +8 -0
- package/cli/dist/web-ui/assets/{terminal-store-DxSL6lew.js → terminal-store-DOTQJFag.js} +1 -1
- package/cli/dist/web-ui/assets/{theme-store-B-x3NJPZ.js → theme-store-7kL2_Dih.js} +1 -1
- package/cli/dist/web-ui/assets/{timeline-definition-EJHVYXUP-DZbLKd2p.js → timeline-definition-EJHVYXUP-teGYk-dY.js} +1 -1
- package/cli/dist/web-ui/assets/{timer-CPkvO7Hr.js → timer-DsflRbuo.js} +1 -1
- package/cli/dist/web-ui/assets/{treeView-Q6P3EWNA-ClDx_xC6.js → treeView-Q6P3EWNA-DsuuN89d.js} +1 -1
- package/cli/dist/web-ui/assets/{treemap-WGGIJYW6-RDLtBb4P.js → treemap-WGGIJYW6-BqqhgGGn.js} +1 -1
- package/cli/dist/web-ui/assets/{triangle-alert-RxeG6BcU.js → triangle-alert-BL4rmdOu.js} +1 -1
- package/cli/dist/web-ui/assets/{tsMode-D4E8Qd-x.js → tsMode-B6SPhuNF.js} +1 -1
- package/cli/dist/web-ui/assets/{use-i18n-BCKBlfpd.js → use-i18n-BvJYl_9l.js} +1 -1
- package/cli/dist/web-ui/assets/{usecaseDiagram-POWQR4AR-DEfQU35o.js → usecaseDiagram-POWQR4AR-2sD6xPnt.js} +1 -1
- package/cli/dist/web-ui/assets/{vennDiagram-UO4OBE2U-C4yxYnjL.js → vennDiagram-UO4OBE2U-DHLn-BEs.js} +1 -1
- package/cli/dist/web-ui/assets/{wardley-WFR3VGLG-wNwnrEey.js → wardley-WFR3VGLG-BD5dMb6v.js} +1 -1
- package/cli/dist/web-ui/assets/{wardleyDiagram-VNRHLVJA-nrPZlF5q.js → wardleyDiagram-VNRHLVJA-6V8TM6o7.js} +1 -1
- package/cli/dist/web-ui/assets/{workspace-dock-store-5JIgHIqh.js → workspace-dock-store-D1kqgYR-.js} +1 -1
- package/cli/dist/web-ui/assets/{xychartDiagram-PMCCYNJV-BXJAFZRI.js → xychartDiagram-PMCCYNJV-B5wGEmv3.js} +1 -1
- package/cli/dist/web-ui/assets/{zap-JdzyzkaE.js → zap-u2SXZ7au.js} +1 -1
- package/cli/dist/web-ui/index.html +9 -9
- package/cli/dist/web-ui/sw.js +1 -1
- package/cli/dist-server/2701.codebuddy.js +2 -2
- package/cli/dist-server/3080.codebuddy.js +1 -1
- package/cli/dist-server/3163.codebuddy.js +1 -1
- package/cli/dist-server/codebuddy.js +41 -39
- package/cli/dist-server/types/node/agent-task/agent-task.d.ts +1 -0
- package/cli/dist-server/types/node/permission/brokered-sandbox/host-service.d.ts +1 -0
- package/cli/dist-server/types/node/permission/sandbox-orchestrator.d.ts +2 -1
- package/cli/dist-server/types/node/server/formats/acp/acp-trace-context.d.ts +2 -0
- package/cli/dist-server/types/node/server/types.d.ts +8 -1
- package/cli/dist-server/types/node/utils/clipboard-utils.d.ts +1 -1
- package/cli/dist-server/types/node/utils/image-preparation-guard.d.ts +5 -1
- package/cli/dist-server/types/node/utils/request-scene.d.ts +5 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/history-utils.d.ts +33 -8
- package/cli/dist-server/types/vendor/cbc-core/node/utils/input-item-utils.d.ts +27 -0
- package/cli/package.json +4 -4
- package/cli/product.cloudhosted.json +2 -2
- package/cli/product.internal.json +2 -2
- package/cli/product.ioa.json +2 -2
- package/cli/product.json +2 -2
- package/cli/product.selfhosted.json +2 -2
- package/package.json +1 -1
- package/cli/dist/web-ui/assets/architecture-7GRP2DOG-CHYM9JTs.js +0 -1
- package/cli/dist/web-ui/assets/channel-DtDG5p59.js +0 -1
- package/cli/dist/web-ui/assets/eventmodeling-NTZA5JFV-PAdtPpRo.js +0 -1
- package/cli/dist/web-ui/assets/flowDiagram-KWPJA3E3-EJkyCIxy.js +0 -1
- package/cli/dist/web-ui/assets/loader-circle-1kyJNWeb.js +0 -1
- package/cli/dist/web-ui/assets/power-CbA3xFVD.js +0 -1
- package/cli/dist/web-ui/assets/railroad-abnf-HS5TGJTU-C9Q7Ymc5.js +0 -1
- package/cli/dist/web-ui/assets/railroad-ebnf-LZEXJU2U-Bg_FzoOI.js +0 -1
- package/cli/dist/web-ui/assets/railroad-peg-WCYAUIDC-cvFGmoWK.js +0 -1
- package/cli/dist/web-ui/assets/swimlanesDiagram-TC7HE7FX-Bopn2-Vs.js +0 -8
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";exports.ids=["3080"],exports.modules={35550(e,t,r){r.d(t,{$6:()=>handleBrokeredFileTokenRequest,H0:()=>denyBrokeredHostOperationRequest,i5:()=>handleBrokeredHostOperation,rU:()=>l,yR:()=>d});var o=r(70857),s=r(16928),i=r.n(s),a=r(68390),n=r(46816);let l="HostFileOperation",d="FileTokenRequest",c={delete:{buildParams:e=>e.path?{path:e.path,deleteMode:e.deleteMode,recursive:e.recursive,force:e.force,safeDeleteReportPath:e.safeDeleteReportPath,runtime:e.runtime}:void 0,audits:["delete"],execute:(e,t)=>e.deletePath(t)},mkdir:{buildParams:e=>e.path?{path:e.path,recursive:e.recursive,mode:e.mode}:void 0,audits:["write"],execute:(e,t)=>e.mkdirPath(t)},rename:{buildParams:e=>e.from&&e.to?{from:e.from,to:e.to}:void 0,audits:["delete","target:write","target:delete"],execute:(e,t)=>e.renamePath(t)},copy:{buildParams:e=>e.from&&e.to?{from:e.from,to:e.to,recursive:e.recursive}:void 0,audits:["read","target:write","target:delete"],execute:(e,t)=>e.copyPath(t)},chmod:{buildParams:e=>e.path&&"number"==typeof e.mode?{path:e.path,mode:e.mode}:void 0,audits:["write"],execute:(e,t)=>e.chmodPath(t)},link:{buildParams:e=>e.from&&e.to?{from:e.from,to:e.to,symbolic:e.symbolic}:void 0,audits:e=>e.symbolic?["target:write"]:["read","target:write"],execute:(e,t)=>e.linkPath(t)},touch:{buildParams:e=>e.path?{path:e.path}:void 0,audits:["write"],execute:(e,t)=>e.touchPath(t)}};async function handleBrokeredHostOperation(e){let{service:t,approvalCoordinator:r,request:o,orderedFileRules:s,sandboxFilesystem:i}=e,a=await r.dispatchAndRecordPrompt(o,async e=>{let r=await dispatchBrokeredHostOperation({service:t,request:o,orderedFileRules:s,sandboxFilesystem:i,approvalScope:e});return r&&reportBrokeredHostOperationAudits(o,r.result,r.audits,s),r?.result});return a?withResponseId(o.id,a):denyBrokeredHostOperationRequest(o,`Unsupported brokered host file operation: ${o.operation??"<unknown>"}`)}async function handleBrokeredFileTokenRequest(e){let{service:t,approvalCoordinator:r,request:o,orderedFileRules:s}=e,i=await r.dispatchAndRecordPrompt(o,async e=>{let r=await t.requestFileToken({...o,orderedFileRules:s,approvalScope:e});return reportBrokeredResult(o,r,r.operation,s),r});return i?withResponseId(o.id,i):denyBrokeredFileTokenRequest(o,"No result from brokered file token approval loop")}async function dispatchBrokeredHostOperation(e){let{service:t,request:r,orderedFileRules:o,sandboxFilesystem:s,approvalScope:i}=e,a=r.operation?c[r.operation]:void 0,n=a?.buildParams(r);if(!a||!n)return;let l={...n,orderedFileRules:o,sandboxFilesystem:s,approvalScope:i,sessionId:r.sessionId},d="function"==typeof a.audits?a.audits(r):a.audits;return withAudits(a.execute(t,l),d)}function denyBrokeredHostOperationRequest(e,t){return withResponseId(e.id,{ok:!1,operation:e.operation??"unknown",path:e.path??e.from??"",normalisedPath:e.path??e.from??"",decision:"deny",error:t})}function denyBrokeredFileTokenRequest(e,t){return withResponseId(e.id,{ok:!1,operation:e.operation,path:e.path,normalisedPath:e.path,decision:"deny",error:t})}async function withAudits(e,t){return{result:await e,audits:t}}function reportBrokeredHostOperationAudits(e,t,r,o){for(let s of r){let r="target:delete"===s&&t.to&&t.toDeleteDecision?{...t,path:t.to,normalisedPath:t.normalisedTo??t.to,decision:t.toDeleteDecision,matchedRule:t.toDeleteMatchedRule,approvedByUser:t.toDeleteApprovedByUser}:"target:write"===s&&t.to?{...t,path:t.to,normalisedPath:t.normalisedTo??t.to,matchedRule:t.toMatchedRule,approvedByUser:t.toApprovedByUser}:t.to?{...t,approvedByUser:t.sourceApprovedByUser}:s.startsWith("target:")?void 0:t;r&&reportBrokeredResult(e,r,"target:write"===s?"write":"target:delete"===s?"delete":s,o)}}function reportBrokeredResult(e,t,r,o){if(!shouldReportBrokeredAudit(t))return;let s={sessionId:e.sessionId,requestId:e.id,toolCallId:e.toolCallId,paths:[t.path],matchedRule:t.matchedRule?.pathPattern,operation:r};if(t.approvedByUser){(0,a.AC)("ask-matched",s),(0,a.AC)("approved",s);return}"deny"===t.decision?(0,a.AC)("deny-matched",s):"prompt"===t.decision?(0,a.AC)("ask-matched",s):"policyReason"in t&&"implicit-safe-delete-fallback"===t.policyReason?(0,a.AC)("auto-approved",s):("grant-token"===t.decision||"host-op"===t.decision||"sandbox"===t.decision&&t.ok)&&isOrderedFileAllow(t.matchedRule?.pathPattern,r,o)&&(0,a.AC)("allow-listed",s)}function isOrderedFileAllow(e,t,r){if(!e)return!1;let o=normaliseOrderedRuleIdentity(e),s=r?.find(e=>normaliseOrderedRuleIdentity(e.path)===o);return s?.source!=="preset"&&s?.["access"===t?"read":t]==="allow"}function normaliseOrderedRuleIdentity(e){let t="~"===e?(0,o.homedir)():e.startsWith("~/")?i().join((0,o.homedir)(),e.slice(2)):e,r=i().normalize(t).replace(/\\/g,"/"),s=r.length>1?r.replace(/\/+$/,""):r;return"win32"===process.platform?s.toLowerCase():s}function shouldReportBrokeredAudit(e){return!!e.matchedRule&&e.matchedRule.pathPattern!==n.uf}function withResponseId(e,t){return e?{id:e,...t}:{...t}}},57659(e,t,r){r.d(t,{l:()=>C,t:()=>x});var o,s,i=r(88523),a=r(21215),n=r(91943),l=r(73339),d=r(70857),c=r.n(d),h=r(16928),p=r(9386),u=r(15526),g=r(26258),f=r(737),m=r(26384),y=r(12128),S=r(9890),_=r(96893),b=r(29801);function isAccessApproved(e,t,r){return e.decision===t||hasApprovedAccess(e,r)}function hasApprovedAccess(e,t){return"prompt"===e.decision&&(t?.accesses??[]).some(t=>t.operation===e.operation&&t.normalisedPath===e.normalisedPath&&t.matchedRule?.source===e.matchedRule?.source&&t.matchedRule?.pathPattern===e.matchedRule?.pathPattern)}function toApprovalAccess(e){return"prompt"===e.decision?{operation:e.operation,normalisedPath:e.normalisedPath,matchedRule:e.matchedRule}:void 0}function hostDeny(e,t,r,o={}){return hostRefusal(e,rawPathRef(t),"deny",r,o)}function hostPolicyRefusal(e,t,r,o={}){return hostRefusal(e,t,t.decision,r,{...o,...t.decisionRecord?{refusedOperation:t.operation}:{},approvalAccess:toApprovalAccess(t)})}function hostRefusal(e,t,r,o,s={}){return{ok:!1,operation:e,...hostPathFields(t),decision:r,...t.decisionRecord?{decisionRecord:t.decisionRecord}:{},...s,error:o}}function hostSuccess(e,t,r,o,s={}){return{ok:!0,operation:e,...hostPathFields(t),decision:r,...approvedByUser(o,t),...s}}function rawPathRef(e){return{path:e,normalisedPath:e}}function hostPairPolicyRefusal(e,t,r,o,s){return hostRefusal(e,t,o.decision,s,{...hostPairFields(r),..."delete"===o.operation&&o.path===r.path?hostPairDeleteFields(o):{},matchedRule:o.matchedRule,decisionRecord:o.decisionRecord,...o.decisionRecord?{refusedOperation:o.operation}:{},approvalAccess:toApprovalAccess(o)})}function hostPairCompletion(e,t,r,o,s,i){let a={...hostPairFields(r,o),...isFileAccessDecision(t)&&hasApprovedAccess(t,o)?{sourceApprovedByUser:!0}:{},...i?hostPairDeleteFields(i,o):{},matchedRule:t.matchedRule??r.matchedRule};return void 0!==s?hostRefusal(e,t,"host-op",s,a):{ok:!0,operation:e,...hostPathFields(t),decision:"host-op",...a,...approvedByUser(o,isFileAccessDecision(t)?t:void 0,r,i)}}function hostPathFields(e){return{path:e.path,normalisedPath:e.normalisedPath,matchedRule:e.matchedRule}}function hostPairFields(e,t){return{to:e.path,normalisedTo:e.normalisedPath,toMatchedRule:e.matchedRule,...isFileAccessDecision(e)&&hasApprovedAccess(e,t)?{toApprovedByUser:!0}:{}}}function isFileAccessDecision(e){return"decision"in e&&"operation"in e&&"level"in e}function hostPairDeleteFields(e,t){return{toDeleteDecision:e.decision,toDeleteMatchedRule:e.matchedRule,...hasApprovedAccess(e,t)?{toDeleteApprovedByUser:!0}:{}}}function approvedByUser(e,...t){return t.some(t=>t&&hasApprovedAccess(t,e))?{approvedByUser:!0}:{}}var v=r(45869);let BrokeredSandboxPathValidator=class BrokeredSandboxPathValidator{async resolveExistingPath(e){try{return await (0,n.realpath)(e)}catch{return}}async resolvePathThroughParent(e){let t=await this.resolveCreatablePath((0,h.dirname)(e));return t?(0,h.join)(t,(0,h.basename)(e)):void 0}async resolveExistingOrCreatablePath(e){return await this.resolveExistingPath(e)??this.resolvePathThroughParent(e)}async refuseIfResolvedPathUnsafe(e){let t=await this.refuseIfResolvedPathNotAllowed({...e,resolvedPath:e.approvedResolvedPath});if(t)return t;let r=await e.resolvePath();if(e.approvedResolvedPath===r)return;let o=await this.refuseIfResolvedPathNotAllowed({...e,resolvedPath:r});if(o)return o;let s=r?"changed":"could not be revalidated";return this.resolvedPathRefusal(e,`Brokered ${e.resultOperation} refused because the resolved path ${s} before execution`)}async refuseIfResolvedPathNotAllowed(e){if(!e.resolvedPath)return;let t=await e.resolveAccess(e.resolvedPath);if(t.available&&(t.allowed||hasApprovedAccess(t.access,e.approvalScope)))return;let r=!!e.fromAccess,o="read"===e.resultOperation||"write"===e.resultOperation?"file token":e.resultOperation,s=t.available?t.access.decision:e.unavailableDecision??"deny";return this.resolvedPathRefusal(e,`Brokered ${o} refused by resolved path policy: ${s}`,{decision:s,matchedRule:r?(e.fromAccess??e.access).matchedRule:t.access.matchedRule,toMatchedRule:r?t.access.matchedRule:e.toAccess?.matchedRule,approvalAccess:t.available?toApprovalAccess(t.access):void 0})}async resolveCreatablePath(e){let t=await this.resolveExistingPath(e);if(t)return t;let r=(0,h.dirname)(e);if(r===e)return;let o=await this.resolveCreatablePath(r);return o?(0,h.join)(o,(0,h.basename)(e)):void 0}resolvedPathRefusal(e,t,r={}){let o=e.fromAccess??e.access,s=e.toAccess??(e.fromAccess?e.access:void 0),{decision:i="deny",...a}=r;return hostRefusal(e.resultOperation,o,i,t,{to:s?.path,normalisedTo:s?.normalisedPath,toMatchedRule:s?.matchedRule,...a})}};var R=r(46816);let SandboxFileRuleMatcher=class SandboxFileRuleMatcher{constructor(e,t){this.resolveCenterClient=e,this.getLogger=t}async resolve(e){let t,r=(0,_.QH)(e.path),o="rename"===e.operation?"write":e.operation,s={path:e.requestPath??e.path,normalisedPath:r,operation:o,decision:"sandbox",level:"unknown"};if((0,R.Lg)(r,o))return{access:{...s,decision:"sandbox",level:"low",matchedRule:R.ZH},allowed:!0,available:!0};let i=this.resolveCenterClient(e.sessionId);if(!i||!e.sessionId)return{access:s,available:!1};try{t=await (0,p.Ej)(i,e.sessionId,{path:e.path,op:e.operation,...void 0===e.dstPath?{}:{dstPath:e.dstPath},...void 0===e.targetExists?{}:{targetExists:e.targetExists},...void 0===e.skipSensitiveDetect?{}:{skipSensitiveDetect:e.skipSensitiveDetect}})}catch(t){return this.getLogger()?.info?.(`[BrokeredShell] phase=decide-file | result=unknown | sessionId=${e.sessionId} | path=${e.path} | error=${t?.message??String(t)}`),{access:s,available:!1}}if("allow"!==t.action&&"ask"!==t.action&&"deny"!==t.action)return this.getLogger()?.info?.(`[BrokeredShell] phase=decide-file | result=unknown | sessionId=${e.sessionId} | path=${e.path} | error=invalid action ${t.action}`),{access:s,available:!1};let a=t.action,n="allow"===a,l=t.decisionRecord.matchRule?.pattern;return{access:{...s,decisionRecord:t.decisionRecord,decision:"allow"===a?"sandbox":"deny"===a?"deny":"prompt",level:"deny"===a?"high":n?"low":"unknown",matchedRule:l?{pathPattern:l,level:n?"low":"high",source:n?"user-allowlist":"user-blocklist"}:void 0},allowed:n,modifier:t.modifier,ruleCategory:t.decisionRecord.matchRule?.category,available:!0}}};var __decorate=function(e,t,r,o){var s,i=arguments.length,a=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,o);else for(var n=e.length-1;n>=0;n--)(s=e[n])&&(a=(i<3?s(a):i>3?s(t,r,a):s(t,r))||a);return i>3&&a&&Object.defineProperty(t,r,a),a},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let C=Symbol("BrokeredSandboxHostService"),w=(0,l.createRequire)(__filename),errorMessage=e=>e?.message??String(e),brokeredRuleSource=e=>e?.source??"none",accessForHostExecution=(e,t)=>e.available&&e.allowed?{...e.access,decision:t}:e.access,remapResolutionAccess=(e,t,r)=>{let o={...e.access,path:t,normalisedPath:(0,_.QH)(t),operation:r};return e.available?{...e,access:o}:{access:o,available:!1}};function hasMeaningfulResolvedPathDifference(e,t){if(!t)return!1;let normaliseForAliasComparison=e=>{let t=(0,_.QH)(e).replace(/\/+$/,"");for(let e of["/private/var","/private/tmp"])if(t===e||t.startsWith(`${e}/`))return t.slice(8);return t};return normaliseForAliasComparison(e)!==normaliseForAliasComparison(t)}let executeHostAction=async e=>{try{await e();return}catch(e){return errorMessage(e)}},x=class{constructor(){this.pathValidator=new BrokeredSandboxPathValidator,this.fileRuleMatcher=new SandboxFileRuleMatcher(()=>this.sandboxCenterClient,()=>this.logger),this.targetOperationLocks=new Map,this.maxRecursiveCopyEntries=1e4}async requestFileToken(e){if(!(0,h.isAbsolute)(e.path))return hostDeny(e.operation,e.path,"Brokered file token requires an absolute path");let t=await this.pathValidator.resolveExistingOrCreatablePath(e.path),r=t&&/[/\\]$/.test(e.path)&&!/[/\\]$/.test(t)?`${t}/`:t??e.path,o="write"===e.operation?await this.targetPathExists(r):void 0,s="read"===e.operation||void 0,i=await this.fileRuleMatcher.resolve({path:r,requestPath:e.path,operation:e.operation,targetExists:o,skipSensitiveDetect:s,sessionId:e.sessionId}),a=i.access;if(!i.available)return hostPolicyRefusal(e.operation,a,"Brokered file token deferred to sandbox because runtime file rule is unavailable");let n=i.allowed;if(n&&hasMeaningfulResolvedPathDifference(e.path,t)){let t=await this.fileRuleMatcher.resolve({path:e.path,requestPath:e.path,operation:e.operation,targetExists:o,skipSensitiveDetect:s,sessionId:e.sessionId});if(!t.available)return hostPolicyRefusal(e.operation,t.access,"Brokered file token deferred to sandbox because the request path rule is unavailable");if(!t.allowed){if(!hasApprovedAccess(t.access,e.approvalScope))return hostPolicyRefusal(e.operation,t.access,"Brokered file token requires approval for the request path runtime file rule");a=t.access,n=!1}}if(n)return hostSuccess(e.operation,a,"sandbox",e.approvalScope);if(!hasApprovedAccess(a,e.approvalScope))return hostPolicyRefusal(e.operation,a,"Brokered file token requires approval for the matched runtime file rule");let l=await this.pathValidator.refuseIfResolvedPathUnsafe({access:a,resultOperation:e.operation,approvedResolvedPath:t,resolvePath:()=>this.pathValidator.resolveExistingOrCreatablePath(e.path),approvalScope:e.approvalScope,unavailableDecision:"sandbox",resolveAccess:t=>this.fileRuleMatcher.resolve({path:t,requestPath:e.path,operation:e.operation,targetExists:o,skipSensitiveDetect:s,sessionId:e.sessionId})});if(l)return l;let d=Date.now();try{let t=await this.issueFileToken({operation:e.operation,tokenPath:r}),o=hasApprovedAccess(a,e.approvalScope)?"grant-token":a.decision;return hostSuccess(e.operation,a,o,e.approvalScope,{inspectionPath:r,token:t})}catch(o){let t=o?.code??o?.signal??o?.name??"unknown";return this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=host-file-token | event=issuer-failed | operation=${e.operation} | tokenPath=${r} | durationMs=${Date.now()-d} | errorCode=${t} | error=${errorMessage(o)}`),hostRefusal(e.operation,a,"deny",`Brokered file token issuer failed: ${errorMessage(o)}`)}}async issueFileToken(e){if("darwin"!==process.platform)throw Error("macOS sandbox extension tokens are only available on darwin");let t="read"===e.operation?"com.workbuddy.sandbox.read":"com.workbuddy.sandbox.read-write",r=this.loadFileSandboxExtensionIssuer().issueFileSandboxExtension(t,e.tokenPath,0);if("string"!=typeof r||0===r.length)throw Error("macOS sandbox extension issuer returned no token");return r}loadFileSandboxExtensionIssuer(){let e=(0,y.hR)()?.shimDir;if(!e)throw Error("macOS sandbox extension native addon is unavailable");let t=(0,h.join)(e,"native",`darwin-${process.arch}`,"brokered-sandbox-native.node"),r=w(t);if("function"!=typeof r.issueFileSandboxExtension)throw Error(`Native addon does not export issueFileSandboxExtension: ${t}`);return r}async deletePath(e){let t=e.deleteMode??("darwin"===process.platform?"trash":"unlink"),r={deleteMode:t},o=Date.now();return this.logger?.info?.(`[BrokeredShell] phase=host-delete | event=received | path=${e.path} | deleteMode=${t} | recursive=${e.recursive??!1} | force=${e.force??!1} | reportPath=${e.safeDeleteReportPath?"set":"none"}`),this.executeSingleHostOperation({resultOperation:"delete",...e,fileOperation:"delete",expectedDecision:"host-op",resolvePath:()=>this.pathValidator.resolvePathThroughParent(e.path),execute:async s=>{let i=s.access.matchedRule?.pathPattern,a="trash"===t&&s.available&&"auto_grant"===s.ruleCategory&&void 0!==i&&(0,_.QH)(i)===s.access.normalisedPath?"unlink":t;r.deleteMode=a;let l={recursive:e.recursive??!1,force:e.force??!1};this.logger?.info?.(`[BrokeredShell] phase=host-delete | event=executing | path=${e.path} | deleteMode=${a}`);try{if("trash"!==a)return void await (0,n.rm)(e.path,l);let t="node"===e.runtime||"python"===e.runtime?e.runtime:"bash";await this.trashPath(e.path,{...l,reportPath:e.safeDeleteReportPath,runtime:t,onNativeTrashError:t=>this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=host-delete | event=native-trash-failed | path=${e.path} | error=${t?.message??t} | fallback=attempting`)}),this.logger?.info?.(`[BrokeredShell] phase=host-delete | event=trash-succeeded | path=${e.path} | reportPath=${e.safeDeleteReportPath?"set":"none"} | durationMs=${Date.now()-o}`)}catch(t){throw this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=host-delete | event=failed | path=${e.path} | durationMs=${Date.now()-o} | error=${t?.message??t}`),t}},resultExtra:r})}async trashPath(e,t){await (0,m.w)(e,t)}async mkdirPath(e){return this.executeSingleHostOperation({resultOperation:"mkdir",...e,resolvePath:()=>this.pathValidator.resolvePathThroughParent(e.path),execute:()=>(0,n.mkdir)(e.path,{recursive:e.recursive??!1,mode:e.mode})})}async executeSingleHostOperation(e){let t=Date.now(),r=e.fileOperation??"write",o=e.expectedDecision??"grant-token";if(!(0,h.isAbsolute)(e.path)){let r=hostDeny(e.resultOperation,e.path,`Brokered host ${e.resultOperation} requires an absolute path`,e.resultExtra);return this.logHostOperationComplete(e.resultOperation,e.path,r,t),r}let s=await e.resolvePath(),i="write"===r?await this.targetPathExists(e.path):void 0,a=await this.fileRuleMatcher.resolve({path:e.path,operation:r,targetExists:i,sessionId:e.sessionId});if(!a.available){let r=hostRefusal(e.resultOperation,a.access,"deny",`Brokered host ${e.resultOperation} requires an available runtime file rule`,e.resultExtra);return this.logHostOperationComplete(e.resultOperation,e.path,r,t),r}let n=this.isDarwinImplicitFallbackSafeDelete(e,a),l=n?{...a.access,decision:o}:accessForHostExecution(a,o);if(!isAccessApproved(l,o,e.approvalScope)){this.logger?.info?.(`[BrokeredShell] phase=host-policy | operation=${e.resultOperation} | decision=${l.decision} | expectedDecision=${o} | matchedRuleSource=${brokeredRuleSource(l.matchedRule)} | approvedByUser=${hasApprovedAccess(l,e.approvalScope)} | result=refused`);let r=hostPolicyRefusal(e.resultOperation,l,`Brokered host ${e.resultOperation} refused by file policy: ${l.decision}`,e.resultExtra);return this.logHostOperationComplete(e.resultOperation,e.path,r,t),r}this.logger?.info?.(`[BrokeredShell] phase=host-policy | operation=${e.resultOperation} | decision=${l.decision} | expectedDecision=${o} | matchedRuleSource=${brokeredRuleSource(l.matchedRule)} | approvedByUser=${hasApprovedAccess(l,e.approvalScope)} | result=approved`);let d=await this.refuseResolvedHostPath(e,l,r,s,e.resolvePath);if(d)return this.logHostOperationComplete(e.resultOperation,e.path,d,t),d;let c=await (0,b.OB)({enabled:"mkdir"===e.resultOperation||"touch"===e.resultOperation,sessionId:e.sessionId,targetPath:e.path,deps:this.createdPathAutoGrantDeps()}),p=await executeHostAction(async()=>{await this.backupBeforeSingleHostOperation(e,this.shouldUseCenterBackup(a)),await e.execute(a),await c?.afterSuccess()});if(void 0!==p){let r=hostRefusal(e.resultOperation,l,"host-op"===o?l.decision:"host-op",p,e.resultExtra);return this.logHostOperationComplete(e.resultOperation,e.path,r,t),r}let u="host-op"===o?hasApprovedAccess(l,e.approvalScope)?o:l.decision:"host-op",g=hostSuccess(e.resultOperation,l,u,e.approvalScope,{...e.resultExtra,...n?{policyReason:"implicit-safe-delete-fallback"}:{}});return this.logHostOperationComplete(e.resultOperation,e.path,g,t),g}async renamePath(e){return this.executeTwoPathHostOperation({resultOperation:"rename",...e,execute:()=>(0,n.rename)(e.from,e.to)})}async copyPath(e){return e.recursive?this.copyPathRecursive(e):this.executeTwoPathHostOperation({resultOperation:"copy",...e,resolveTargetPath:()=>this.pathValidator.resolveExistingOrCreatablePath(e.to),execute:()=>(0,n.copyFile)(e.from,e.to)})}async executeTwoPathHostOperation(e){return this.withTargetOperationLock(e.to,()=>this.executeTwoPathHostOperationLocked(e))}async copyPathRecursive(e){let t;try{t=await (0,n.lstat)(e.from)}catch(t){return hostDeny("copy",e.from,`Brokered host recursive copy source is unavailable: ${errorMessage(t)}`,{to:e.to,normalisedTo:e.to})}return t.isDirectory()?this.withTargetOperationLock(e.to,()=>this.copyDirectoryRecursiveLocked(e)):this.executeTwoPathHostOperation({resultOperation:"copy",...e,resolveTargetPath:()=>this.pathValidator.resolveExistingOrCreatablePath(e.to),execute:()=>(0,n.copyFile)(e.from,e.to)})}async copyDirectoryRecursiveLocked(e){let t,r=Date.now();if(!(0,h.isAbsolute)(e.from)||!(0,h.isAbsolute)(e.to)){let t=hostDeny("copy",e.from,"Brokered host recursive copy requires absolute source and target paths",{to:e.to,normalisedTo:e.to});return this.logHostOperationComplete("copy",e.from,t,r,e.to),t}let o=await this.refuseRecursiveCopySymlinks(e);if(o)return this.logHostOperationComplete("copy",e.from,o,r,e.to),o;try{t=await this.scanRecursiveCopyEntries(e.from,e.to)}catch(o){let t=hostRefusal("copy",rawPathRef(e.from),"sandbox",`Brokered host recursive copy deferred to sandbox: ${errorMessage(o)}`,{to:e.to,normalisedTo:e.to});return this.logHostOperationComplete("copy",e.from,t,r,e.to),t}let s=await this.resolveRecursiveCopyAccess(e.from,e.from,"read","grant-token",e.sessionId),i=await this.targetPathExists(e.to),a=await this.resolveRecursiveCopyAccess(e.to,e.to,"write","host-op",e.sessionId,i),l=await this.buildRecursiveCopyPolicyChecks(e,t,s,a),d=this.recursiveCopyPolicyRefusal(e,l);if(d)return this.logHostOperationComplete("copy",e.from,d,r,e.to),d;let c=t.filter(e=>e.targetExists&&!(e.isDirectory&&e.targetIsDirectory)).map(e=>e.targetPath),p=await (0,b.OB)({enabled:!0,sessionId:e.sessionId,targetPath:e.to,deps:this.createdPathAutoGrantDeps()}),u=l.find(e=>"delete"===e.access.operation)?.access,g=await executeHostAction(async()=>{await this.backupBeforeHostMutation(c,e.sessionId),await (0,n.cp)(e.from,e.to,{recursive:!0}),await p?.afterSuccess()}),f=hostPairCompletion("copy",s.access,a.access,e.approvalScope,g,u);return this.logHostOperationComplete("copy",e.from,f,r,e.to),f}async scanRecursiveCopyEntries(e,t){let r=[],visit=async o=>{let s;if(r.length>=this.maxRecursiveCopyEntries)throw Error(`recursive copy exceeds ${this.maxRecursiveCopyEntries} entries`);let i=await (0,n.lstat)(o);if(i.isSymbolicLink())throw Error(`recursive copy source tree contains a symlink: ${o}`);let a=(0,h.relative)(e,o),l=a?(0,h.join)(t,a):t;try{s=await (0,n.lstat)(l)}catch(e){if("ENOENT"!==e.code)throw e}if(r.push({sourcePath:o,targetPath:l,isDirectory:i.isDirectory(),targetExists:void 0!==s,targetIsDirectory:s?.isDirectory()??!1}),i.isDirectory())for(let e of(await (0,n.readdir)(o)))await visit((0,h.join)(o,e))};return await visit(e),r}async refuseRecursiveCopySymlinks(e){let t=(0,h.join)(e.to,"..");try{let r=await this.pathValidator.resolveExistingPath(t);if(r&&hasMeaningfulResolvedPathDifference(t,r))return hostRefusal("copy",rawPathRef(e.from),"sandbox","Brokered host recursive copy deferred to sandbox: target path contains symlinks",{to:e.to,normalisedTo:e.to})}catch{}}async resolveRecursiveCopyAccess(e,t,r,o,s,i){let a=await this.fileRuleMatcher.resolve({path:e,requestPath:t,operation:r,targetExists:i,sessionId:s});return{access:a.available?accessForHostExecution(a,o):{...a.access,decision:"deny"},expectedDecision:o,available:a.available}}async buildRecursiveCopyPolicyChecks(e,t,r,o){let s=[{...r,pathRef:r.access,toRef:rawPathRef(e.to),error:`Brokered host recursive copy source refused by file policy: ${r.access.decision}`},{...o,pathRef:r.access,toRef:o.access,error:`Brokered host recursive copy target refused by file policy: ${o.access.decision}`}];for(let o of t){if(o.sourcePath!==e.from){let t=await this.resolveRecursiveCopyAccess(o.sourcePath,o.sourcePath,"read","grant-token",e.sessionId);s.push({...t,pathRef:t.access,toRef:rawPathRef(o.targetPath),error:`Brokered host recursive copy source entry refused by file policy: ${t.access.decision}`})}if(o.targetPath!==e.to){let t=await this.resolveRecursiveCopyAccess(o.targetPath,o.targetPath,"write","host-op",e.sessionId,o.targetExists);s.push({...t,pathRef:r.access,toRef:t.access,error:`Brokered host recursive copy target entry refused by file policy: ${t.access.decision}`})}if(o.targetExists&&!(o.isDirectory&&o.targetIsDirectory)){let t=await this.resolveTargetDeleteAccess(o.targetPath,o.targetPath,e.sessionId);s.push({access:t,expectedDecision:"host-op",pathRef:r.access,toRef:t,error:`Brokered host recursive copy overwrite refused by file policy: ${t.decision}`})}}return s}recursiveCopyPolicyRefusal(e,t){let r=t.find(e=>"deny"===e.access.decision);if(r)return hostPairPolicyRefusal("copy",r.pathRef,r.toRef,r.access,r.error);let o=t.find(t=>!isAccessApproved(t.access,t.expectedDecision,e.approvalScope));if(o)return"sandbox"!==o.access.decision&&o.access.matchedRule?hostPairPolicyRefusal("copy",o.pathRef,o.toRef,o.access,o.error):hostRefusal("copy",rawPathRef(e.from),"sandbox","Brokered host recursive copy deferred to sandbox: no rule covers the target path",{to:e.to,normalisedTo:e.to})}async executeTwoPathHostOperationLocked(e){let t,r=Date.now(),o=e.sourcePolicy??("link"===e.resultOperation?void 0:{operation:"rename"===e.resultOperation?"delete":"read",expectedDecision:"rename"===e.resultOperation?"host-op":"grant-token"});if((e.requireAbsoluteSource??!!o)&&!(0,h.isAbsolute)(e.from)||!(0,h.isAbsolute)(e.to)){let t="link"===e.resultOperation?"Brokered host link requires an absolute target path, and hard-link requires an absolute source path":`Brokered host ${e.resultOperation} requires absolute source and target paths`,o=hostDeny(e.resultOperation,e.from,t,{to:e.to,normalisedTo:e.to});return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}let s=o?o.resolvePath??(()=>this.pathValidator.resolvePathThroughParent(e.from)):void 0,i=s?await s():void 0,a=await this.targetPathExists(e.to),n="rename"===e.resultOperation&&o&&s?await this.fileRuleMatcher.resolve({path:e.from,operation:"rename",dstPath:e.to,targetExists:a,sessionId:e.sessionId}):void 0,l=n?remapResolutionAccess(n,e.from,"delete"):o&&s?await this.fileRuleMatcher.resolve({path:e.from,operation:o.operation,sessionId:e.sessionId}):void 0,d=o&&l?{policy:o,access:accessForHostExecution(l,o.expectedDecision),resolvePath:s}:void 0,c=d?.access??rawPathRef(e.from);if(l&&!l.available){let t={...l.access,decision:"deny"},o=hostPairPolicyRefusal(e.resultOperation,t,rawPathRef(e.to),t,`Brokered host ${e.resultOperation} requires an available runtime file rule for the source`);return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}if(d&&!isAccessApproved(d.access,d.policy.expectedDecision,e.approvalScope)){if(!d.access.matchedRule){let t=hostRefusal(e.resultOperation,rawPathRef(e.from),"sandbox",`Brokered host ${e.resultOperation} deferred to sandbox: no rule covers the source`,{to:e.to,normalisedTo:e.to});return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}let t=hostPairPolicyRefusal(e.resultOperation,d.access,rawPathRef(e.to),d.access,`Brokered host ${e.resultOperation} source refused by file policy: ${d.access.decision}`);return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}let p=e.resolveTargetPath??(()=>this.pathValidator.resolvePathThroughParent(e.to)),u=await p(),g=n?remapResolutionAccess(n,e.to,"write"):await this.fileRuleMatcher.resolve({path:e.to,operation:"write",targetExists:a,sessionId:e.sessionId}),f=accessForHostExecution(g,"host-op");if(!g.available){let t={...f,decision:"deny"},o=hostPairPolicyRefusal(e.resultOperation,c,t,t,`Brokered host ${e.resultOperation} requires an available runtime file rule for the target`);return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}if(!isAccessApproved(f,"host-op",e.approvalScope)){if(!f.matchedRule){let t=hostRefusal(e.resultOperation,rawPathRef(e.from),"sandbox",`Brokered host ${e.resultOperation} deferred to sandbox: no rule covers the target`,{to:e.to,normalisedTo:e.to});return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}let t=hostPairPolicyRefusal(e.resultOperation,c,f,f,`Brokered host ${e.resultOperation} target refused by file policy: ${f.decision}`);return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}if(a&&(t=await this.resolveTargetDeleteAccess(u??e.to,e.to,e.sessionId)),t&&!isAccessApproved(t,"host-op",e.approvalScope)){let o=hostPairPolicyRefusal(e.resultOperation,c,t,t,`Brokered host ${e.resultOperation} overwrite refused by file policy: ${t.decision}`);return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}if(d){let t=await this.refuseResolvedHostPath(e,d.access,d.policy.operation,i,d.resolvePath,{toAccess:f});if(t)return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}let m=await this.refuseResolvedHostPath(e,f,"write",u,p,{fromAccess:d?.access});if(m)return this.logHostOperationComplete(e.resultOperation,e.from,m,r,e.to),m;if(t){let o=await this.refuseResolvedHostPath(e,t,"delete",u,p,{fromAccess:d?.access});if(o)return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}let y=await p(),S=await this.targetPathExists(e.to);if(S){if(!isAccessApproved(t=await this.resolveTargetDeleteAccess(y??e.to,e.to,e.sessionId),"host-op",e.approvalScope)){let o=hostPairPolicyRefusal(e.resultOperation,c,t,t,`Brokered host ${e.resultOperation} overwrite refused by file policy: ${t.decision}`);return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}let o=await this.refuseResolvedHostPath(e,t,"delete",y,p,{fromAccess:d?.access});if(o)return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}let v=n??g,R=f;if(S&&!a){let t=n?await this.fileRuleMatcher.resolve({path:e.from,operation:"rename",dstPath:e.to,targetExists:!0,sessionId:e.sessionId}):await this.fileRuleMatcher.resolve({path:e.to,operation:"write",targetExists:!0,sessionId:e.sessionId}),o=n?remapResolutionAccess(t,e.to,"write"):t;if(!o.available){let t={...accessForHostExecution(o,"host-op"),decision:"deny"},s=hostPairPolicyRefusal(e.resultOperation,c,t,t,`Brokered host ${e.resultOperation} target write refused: target appeared after initial authorization`);return this.logHostOperationComplete(e.resultOperation,e.from,s,r,e.to),s}let s=accessForHostExecution(o,"host-op");if(!isAccessApproved(s,"host-op",e.approvalScope)){let t=hostPairPolicyRefusal(e.resultOperation,c,s,s,`Brokered host ${e.resultOperation} target write ${"deny"===s.decision?"denied":"requires re-approval"} after target appeared`);return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}v=o,R=s}if("copy"===e.resultOperation){let t=await this.refuseResolvedHostPath(e,R,"write",y,p,{fromAccess:d?.access});if(t)return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}let C="rename"===e.resultOperation?await this.fileRuleMatcher.resolve({path:e.from,operation:"delete",sessionId:e.sessionId}):void 0,w=C?.access.matchedRule?.pathPattern,x=C?.available===!0&&"auto_grant"===C.ruleCategory&&void 0!==w&&(0,_.QH)(w)===C.access.normalisedPath,k="rename"!==e.resultOperation||x?"created":"renamed_existing",I=await (0,b.OB)({enabled:!0,sessionId:e.sessionId,targetPath:e.to,createdPathOrigin:k,deps:this.createdPathAutoGrantDeps()}),O=await executeHostAction(async()=>{let t=this.shouldUseCenterBackup(v);await this.backupBeforeTwoPathHostOperation(e,!!S&&!a||t),await e.execute(),await I?.afterSuccess()}),P=hostPairCompletion(e.resultOperation,c,R,e.approvalScope,O,t);return this.logHostOperationComplete(e.resultOperation,e.from,P,r,e.to),P}async targetPathExists(e){try{return await (0,n.lstat)(e),!0}catch(e){return"ENOENT"!==e.code}}async withTargetOperationLock(e,t){let r,o=(0,_.QH)(e),s=this.targetOperationLocks.get(o),i=new Promise(e=>{r=e});this.targetOperationLocks.set(o,i),s&&await s;try{return await t()}finally{r(),this.targetOperationLocks.get(o)===i&&this.targetOperationLocks.delete(o)}}async resolveTargetDeleteAccess(e,t,r){let o=await this.fileRuleMatcher.resolve({path:e,requestPath:t,operation:"delete",sessionId:r}),s=accessForHostExecution(o,"host-op");return o.available?s:{...s,decision:"deny"}}createdPathAutoGrantDeps(){return{logger:this.logger,sandboxLifecycle:this.sandboxLifecycle,sandboxCenterClient:this.sandboxCenterClient,sessionManager:this.sessionManager,sandboxTurnConfig:this.sandboxTurnConfig}}logHostOperationComplete(e,t,r,o,s){let i=`[BrokeredShell] phase=host-op | event=complete | operation=${e} | path=${t} ${s?`| to=${s} `:""}| ok=${String(r.ok)} | decision=${r.decision} | durationMs=${Date.now()-o}${r.error?` | error=${r.error}`:""}`;r.ok?this.logger?.info?.(i):this.logger?.warn?.(i)}async chmodPath(e){return this.executeSingleHostOperation({resultOperation:"chmod",...e,resolvePath:()=>this.pathValidator.resolveExistingPath(e.path),execute:()=>(0,n.chmod)(e.path,e.mode)})}async linkPath(e){return this.executeTwoPathHostOperation({resultOperation:"link",...e,requireAbsoluteSource:!e.symbolic,sourcePolicy:e.symbolic?void 0:{operation:"read",expectedDecision:"grant-token",resolvePath:()=>this.pathValidator.resolveExistingPath(e.from)},resolveTargetPath:()=>this.pathValidator.resolvePathThroughParent(e.to),execute:()=>e.symbolic?(0,n.symlink)(e.from,e.to):(0,n.link)(e.from,e.to)})}async touchPath(e){return this.executeSingleHostOperation({resultOperation:"touch",...e,resolvePath:()=>this.pathValidator.resolveExistingOrCreatablePath(e.path),execute:async()=>{let t=new Date;try{await (0,n.lstat)(e.path)}catch(t){if(t?.code!=="ENOENT")throw t;await (await (0,n.open)(e.path,"a")).close()}await (0,n.utimes)(e.path,t,t)}})}refuseResolvedHostPath(e,t,r,o,s,i={}){return this.pathValidator.refuseIfResolvedPathUnsafe({access:t,resultOperation:e.resultOperation,approvedResolvedPath:o,resolvePath:s,approvalScope:e.approvalScope,resolveAccess:async o=>{let s=await this.fileRuleMatcher.resolve({path:o,requestPath:t.path,operation:r,sessionId:e.sessionId});return this.isDarwinImplicitFallbackSafeDelete(e,s)?{...s,allowed:!0}:s},...i})}isDarwinImplicitFallbackSafeDelete(e,t){let r=e.orderedFileRules?.some(e=>"**"===e.path||"/"===e.path)??!1;return"darwin"===process.platform&&"delete"===e.resultOperation&&e.resultExtra?.deleteMode==="trash"&&t.available&&"prompt"===t.access.decision&&t.access.matchedRule?.pathPattern==="**"&&!r}shouldUseCenterBackup(e){return!e.available||void 0===e.modifier||(e.modifier&p.IJ)!=0}async backupBeforeSingleHostOperation(e,t){"delete"!==e.resultOperation&&"touch"!==e.resultOperation||("touch"!==e.resultOperation||t)&&await this.backupBeforeHostMutation([e.path],e.sessionId,"delete"!==e.resultOperation,"delete"===e.resultOperation?"d":"m")}async backupBeforeTwoPathHostOperation(e,t){switch(e.resultOperation){case"rename":await this.backupBeforeHostMutation([e.from],e.sessionId,!1,"d"),t&&await this.backupBeforeHostMutation([e.to],e.sessionId,!1);return;case"copy":t&&await this.backupBeforeHostMutation([e.to],e.sessionId);return;case"link":return}}async backupBeforeHostMutation(e,t,r=!0,o="m"){await (0,v.Z)({paths:e,sessionId:t,followSymlinks:r,excludedPathOptions:this.getModifyBackupExcludedPathOptions(),logPhase:"host-modify-backup",sandboxTurnConfig:this.sandboxTurnConfig,sandboxLifecycle:this.sandboxLifecycle,sandboxCenterClient:this.sandboxCenterClient,sessionManager:this.sessionManager,logger:this.logger,reason:o})}getModifyBackupExcludedPathOptions(){return{homeDir:c().homedir(),codebuddyHome:S.P.getHomeDir()}}};__decorate([(0,i.Autowired)(i.Logger),(0,i.Optional)(),__metadata("design:type","function"==typeof(o=void 0!==i.Logger&&i.Logger)?o:Object)],x.prototype,"logger",void 0),__decorate([(0,i.Autowired)(g.x),(0,i.Optional)(),__metadata("design:type",Object)],x.prototype,"sandboxTurnConfig",void 0),__decorate([(0,i.Autowired)(u.k),(0,i.Optional)(),__metadata("design:type",Object)],x.prototype,"sandboxLifecycle",void 0),__decorate([(0,i.Autowired)(f.SandboxCenterIpcClient),(0,i.Optional)(),__metadata("design:type",Object)],x.prototype,"sandboxCenterClient",void 0),__decorate([(0,i.Autowired)(a.SessionManager),(0,i.Optional)(),__metadata("design:type","function"==typeof(s=void 0!==a.SessionManager&&a.SessionManager)?s:Object)],x.prototype,"sessionManager",void 0),x=__decorate([(0,i.Component)(C)],x)},46816(e,t,r){r.d(t,{Lg:()=>isBrokeredShellInternalPath,ZH:()=>s,uf:()=>o}),r(70857),r(16928),r(12128);let o="<brokered-shell-runtime>",s={pathPattern:o,level:"low",source:"builtin"};function isBrokeredShellInternalPath(e,t){return"/dev/null"===e?"read"===t||"write"===t:"read"===t&&("/etc/zshenv"===e||"/private/etc/zshenv"===e)}},91168(e,t,r){r.d(t,{t:()=>D,v:()=>E});var o,s,i=r(88523),a=r(21215),n=r(91943),l=r(69278),d=r.n(l),c=r(70857),h=r.n(c),p=r(16928),u=r(43391),g=r(38073),f=r(15526),m=r(26258),y=r(737),S=r(42685),_=r(29889),b=r(572),v=r(43144),R=r(9890),C=r(29801),w=r(35550),x=r(45869),k=r(74262);let I="FileWriteCompleted";let BrokeredSensitiveAccessDenialRegistry=class BrokeredSensitiveAccessDenialRegistry{constructor(){this.denials=new Map}remember(e,t){this.prune(),this.denials.set(`${e}\0${t}`,Date.now())}consume(e,t){return!!e&&!!t&&(this.prune(),this.denials.delete(`${e}\0${t}`))}clear(){this.denials.clear()}prune(){let e=Date.now()-3e5;for(let[t,r]of this.denials.entries())r<e&&this.denials.delete(t)}};let BrokeredTextWriteAutoGrantRegistry=class BrokeredTextWriteAutoGrantRegistry{constructor(){this.candidates=new Map}async remember(e){this.prune();let t=R.P.toBackupPayloadPath(e.targetPath),r=getBrokeredTextWriteAutoGrantCandidateKey(e.sessionId,e.toolCallId,t);if(this.candidates.has(r))return e.onResult?void e.onResult("skip:already-queued",t):void e.deps.logger?.info?.(`[BrokeredShell] phase=ipc-token-auto-grant | result=skip | reason=already-queued | toolCallId=set | path=${t}`);let o=await isMissingPath(t,e.deps),s=await (0,C.OB)({enabled:!0,sessionId:e.sessionId,targetPath:t,deps:e.deps});if(s){if(this.candidates.set(r,{sessionId:e.sessionId,toolCallId:e.toolCallId,targetPath:t,effect:s,createdFromMissing:o,createdAtMs:Date.now()}),e.onResult)return void e.onResult("queued",e.targetPath);e.deps.logger?.info?.(`[BrokeredShell] phase=ipc-token-auto-grant | result=queued | toolCallId=set | path=${e.targetPath}`)}}async flush(e){let t=this.take(e.sessionId,e.toolCallId,e.targetPath);if(t.length){for(let e of t)await e.effect.afterSuccess();e.deps.logger?.info?.(`[BrokeredShell] phase=shell-auto-grant-flush | result=ok | count=${t.length} | toolCallId=${e.toolCallId?"set":"none"}`)}}hasCurrentTurnCreatedPath(e){for(let t of(this.prune(),this.candidates.values()))if(t.createdFromMissing&&t.sessionId===e.sessionId&&t.targetPath===e.targetPath&&(!e.toolCallId||t.toolCallId===e.toolCallId))return!0;return!1}clear(){this.candidates.clear()}take(e,t,r){this.prune();let o=[];for(let[s,i]of this.candidates.entries())e&&i.sessionId!==e||t&&i.toolCallId!==t||r&&i.targetPath!==r||(this.candidates.delete(s),o.push(i));return o}prune(){let e=Date.now()-3e5;for(let[t,r]of this.candidates.entries())r.createdAtMs<e&&this.candidates.delete(t)}};async function handleBrokeredJsonFileTokenRequest(e,t){let r,o=e.brokerTraceId||"none",s=e.sessionId,i="string"==typeof e.path?e.path:"",a="read"===e.operation||"write"===e.operation?e.operation:void 0;if(!s||!(0,k.Y)(s,e.toolCallId,t))return t.logger?.info?.(`[BrokeredShell] phase=ipc-file-token | operation=${e.operation??"<unknown>"} | sessionMatch=false | brokerTraceId=${o} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=session-mismatch`),denyBrokeredFileRequest(e,i,"Brokered sandbox IPC session mismatch");if(!a)return t.logger?.info?.(`[BrokeredShell] phase=ipc-file-token | operation=${e.operation??"<unknown>"} | sessionMatch=true | brokerTraceId=${o} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=unsupported-operation`),denyBrokeredFileRequest(e,i,`Unsupported brokered file token operation: ${e.operation??"<unknown>"}`);if(!i)return t.logger?.info?.(`[BrokeredShell] phase=ipc-file-token | operation=${a} | sessionMatch=true | brokerTraceId=${o} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=missing-path`),denyBrokeredFileRequest(e,i,"Brokered file token request requires a path");let n=await t.bashSandboxManager.getConfig(),l=await (0,w.$6)({service:t.brokeredSandboxHostService,approvalCoordinator:t.approvalCoordinator,request:{id:e.id,operation:a,path:i,sessionId:s,toolCallId:e.toolCallId,brokerTraceId:e.brokerTraceId},orderedFileRules:n?.orderedRules?.file.rules}),d=classifyFileTokenResponse(l);if("read"===a&&"deny"!==d){let r=await authorizeBrokeredReadOpen({request:e,inspectionPath:l.inspectionPath??l.path,runtime:e.runtime,sessionId:s,forceSensitiveDetection:!0===l.approvedByUser,deps:t});if(r?.kind==="deny")return rememberSensitiveAccessDenial(r,s,e.toolCallId,t),t.logger?.info?.(`[BrokeredShell] phase=ipc-sensitive-open | runtime=json | result=deny | reason=${r.code}`),denyBrokeredFileRequest(e,i,r.message)}let c=[],h=createFileTokenStageRecorder(i,c);if("write"===a&&"deny"!==d){try{await backupBeforeBrokeredWrite(s,i,t,e.toolCallId,h("backup"))}catch(o){d="deny",r=o?.message??String(o),t.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-file-token-backup | result=deny | reason=modify-backup-failed | runtime=${e.runtime??"unknown"} | error=${r}`)}r||await rememberTextWriteAutoGrant({registry:t.textWriteAutoGrantRegistry,sessionId:s,toolCallId:e.toolCallId??"",targetPath:i,deps:t,logPhase:"ipc-file-token-auto-grant",onResult:h("autoGrant")})}return(t.logger?.info?.(`[BrokeredShell] phase=ipc-file-token | operation=${a} | sessionMatch=true | brokerTraceId=${o} | toolCallId=${e.toolCallId?"set":"none"} | runtime=${e.runtime??"unknown"} | path=${i}${c.length?` | ${c.join(" | ")}`:""} | result=${d}`),r)?denyBrokeredFileRequest(e,i,"Brokered file token refused: modify backup failed"):l}async function handleBrokeredFileWriteCompletedRequest(e,t){let r=e.brokerTraceId||"none",o="string"==typeof e.path?e.path:"";return(0,k.Y)(e.sessionId,e.toolCallId,t)?"write"!==e.operation?(t.logger?.info?.(`[BrokeredShell] phase=ipc-file-write-completed | operation=${e.operation??"<unknown>"} | sessionMatch=true | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=unsupported-operation`),denyFileWriteCompletedRequest(e,o,`Unsupported brokered file write completion operation: ${e.operation??"<unknown>"}`)):o?(await t.textWriteAutoGrantRegistry?.flush({sessionId:e.sessionId,toolCallId:e.toolCallId,targetPath:R.P.toBackupPayloadPath(o),deps:{logger:t.logger,sandboxLifecycle:t.sandboxLifecycle,sandboxCenterClient:t.sandboxCenterClient,sessionManager:t.sessionManager}}),t.logger?.info?.(`[BrokeredShell] phase=ipc-file-write-completed | operation=write | sessionMatch=true | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | runtime=${e.runtime??"unknown"} | result=ok`),{...e.id?{id:e.id}:{},ok:!0,operation:"write-completed",path:o,normalisedPath:o,decision:"host-op"}):(t.logger?.info?.(`[BrokeredShell] phase=ipc-file-write-completed | operation=write | sessionMatch=true | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=missing-path`),denyFileWriteCompletedRequest(e,o,"Brokered file write completion requires a path")):(t.logger?.info?.(`[BrokeredShell] phase=ipc-file-write-completed | operation=${e.operation??"<unknown>"} | sessionMatch=false | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=session-mismatch`),denyFileWriteCompletedRequest(e,o,"Brokered sandbox IPC session mismatch"))}async function handleBrokeredToyboxTextLine(e,t){let r=e.split(" ");if(4!==r.length||r.some(e=>!e))return t.logger?.info?.("[BrokeredShell] phase=ipc-token | result=deny | reason=invalid-text-protocol"),"DENY";let[o,s,i,a]=r,n={"com.workbuddy.sandbox.read":"read","com.workbuddy.sandbox.read-write":"write"}[o];if(!n)return t.logger?.info?.(`[BrokeredShell] phase=ipc-token | toolCallId=${a?"set":"none"} | result=deny | reason=unknown-extension-class`),"DENY";if(!(0,k.Y)(i,a,t))return t.logger?.info?.(`[BrokeredShell] phase=ipc-token | operation=${n} | sessionMatch=false | toolCallId=${a?"set":"none"} | result=deny | reason=session-mismatch`),"DENY";let l=await t.bashSandboxManager.getConfig(),d=await (0,w.$6)({service:t.brokeredSandboxHostService,approvalCoordinator:t.approvalCoordinator,request:{operation:n,path:s,sessionId:i,toolCallId:a},orderedFileRules:l?.orderedRules?.file.rules}),c=classifyFileTokenResponse(d);if("read"===n&&"deny"!==c){let e=await authorizeBrokeredReadOpen({request:{sessionId:i,toolCallId:a},inspectionPath:d.inspectionPath??d.path,runtime:"bash",sessionId:i,forceSensitiveDetection:!0===d.approvedByUser,deps:t});if(e?.kind==="deny")return rememberSensitiveAccessDenial(e,i,a,t),t.logger?.info?.(`[BrokeredShell] phase=ipc-sensitive-open | runtime=bash | result=deny | reason=${e.code}`),"DENY"}let h=[],p=createFileTokenStageRecorder(s,h);if("write"===n&&"deny"!==c){try{await backupBeforeBrokeredWrite(i,s,t,a,p("backup"))}catch(e){c="deny",t.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-token-backup | result=deny | reason=modify-backup-failed | error=${e?.message??e}`)}"deny"!==c&&await rememberTextWriteAutoGrant({registry:t.textWriteAutoGrantRegistry,sessionId:i,toolCallId:a,targetPath:s,deps:t,logPhase:"ipc-token-auto-grant",onResult:p("autoGrant")})}return(t.logger?.info?.(`[BrokeredShell] phase=ipc-token | operation=${n} | sessionMatch=true | toolCallId=${a?"set":"none"} | path=${s}${h.length?` | ${h.join(" | ")}`:""} | result=${c}`),"deny"===c)?"DENY":!0===d.ok&&"string"==typeof d.token&&d.token?d.token:"sandbox"===d.decision?"SANDBOX":"DENY"}function createFileTokenStageRecorder(e,t){return r=>(o,s)=>{t.push(`${o.startsWith("continue:")?`${r}Check`:r}=${o}`),s!==e&&t.push(`${r}Path=${s}`)}}function denyFileWriteCompletedRequest(e,t,r){return denyBrokeredFileRequest(e,t,r,"write-completed")}function denyBrokeredFileRequest(e,t,r,o=e.operation??"unknown"){return{...e.id?{id:e.id}:{},ok:!1,operation:o,path:t,normalisedPath:t,decision:"deny",error:r}}async function backupBeforeBrokeredWrite(e,t,r,o,s){await (0,x.Z)({paths:[t],sessionId:e,excludedPathOptions:getModifyBackupExcludedPathOptions(),logPhase:"ipc-token-backup",onResult:s,sandboxTurnConfig:r.sandboxTurnConfig,sandboxLifecycle:r.sandboxLifecycle,sandboxCenterClient:r.sandboxCenterClient,logger:r.logger,isCurrentTurnCreatedPath:t=>r.textWriteAutoGrantRegistry?.hasCurrentTurnCreatedPath({sessionId:e,toolCallId:o,targetPath:t})??!1})}async function rememberTextWriteAutoGrant(e){try{await e.registry?.remember({onResult:e.onResult,sessionId:e.sessionId,toolCallId:e.toolCallId,targetPath:e.targetPath,deps:{logger:e.deps.logger,sandboxLifecycle:e.deps.sandboxLifecycle,sandboxCenterClient:e.deps.sandboxCenterClient,sessionManager:e.deps.sessionManager,sandboxTurnConfig:e.deps.sandboxTurnConfig,modifyBackupExcludedPathOptions:getModifyBackupExcludedPathOptions()}})}catch(t){e.deps.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=${e.logPhase} | result=skip | reason=remember-failed | path=${e.targetPath} | error=${t?.message??t}`)}}function getModifyBackupExcludedPathOptions(){return{homeDir:h().homedir(),codebuddyHome:R.P.getHomeDir()}}function classifyFileTokenResponse(e){return!0===e.ok&&"string"==typeof e.token&&e.token?"token":"sandbox"===e.decision?"sandbox":"deny"}function rememberSensitiveAccessDenial(e,t,r,o){"deny"===e.kind&&"sensitive_access_denied"===e.code&&r&&o.sensitiveAccessDenialRegistry?.remember(t,r)}async function authorizeBrokeredReadOpen(e){let t,{sensitiveContentMediation:r,sensitiveProtectionPolicy:o}=e.deps;if(o){try{t=await (0,v.i)(o.isEnabled({sessionId:e.sessionId,...e.deps.signal?{signal:e.deps.signal}:{}}),e.deps.signal)}catch{if(e.deps.signal?.aborted)return cancelledReadOpenDecision();e.deps.logger?.warn?.("[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-sensitive-open | result=allow | reason=policy-state-unavailable");return}if("boolean"!=typeof t)return void e.deps.logger?.warn?.("[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-sensitive-open | result=allow | reason=policy-state-invalid");if(t&&r){if(!isReadOpenRuntime(e.runtime))return{kind:"deny",code:"sensitive_open_runtime_invalid",message:"Sensitive open review requires a supported runtime."};if("string"!=typeof e.inspectionPath||!e.inspectionPath)return{kind:"deny",code:"sensitive_open_path_invalid",message:"Sensitive open review requires an inspection path."};try{let t="function"==typeof e.deps.sessionManager.get?await e.deps.sessionManager.get(e.sessionId):void 0,o=t?t.id:void 0;return await (0,v.i)(r.authorizeReadOpen({path:e.inspectionPath,runtime:e.runtime,sessionId:e.sessionId,...o?{runtimeKey:o}:{},toolCallId:e.request.toolCallId,brokerTraceId:e.request.brokerTraceId,...e.forceSensitiveDetection?{forceSensitiveDetection:!0}:{},...e.deps.signal?{signal:e.deps.signal}:{}}),e.deps.signal)}catch{if(e.deps.signal?.aborted)return cancelledReadOpenDecision();e.deps.logger?.warn?.("[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-sensitive-open | result=allow | reason=adapter-failed");return}}}}function cancelledReadOpenDecision(){return{kind:"deny",code:"sensitive_review_cancelled",message:"Sensitive content review was cancelled."}}function isReadOpenRuntime(e){return"bash"===e||"node"===e||"python"===e}async function isMissingPath(e,t){try{return await (0,n.lstat)(e),!1}catch(r){if(r?.code==="ENOENT"||r?.code==="ENOTDIR")return!0;return t.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-token-auto-grant | result=skip | reason=stat-failed | path=${e} | error=${r?.message??r}`),!1}}function getBrokeredTextWriteAutoGrantCandidateKey(e,t,r){return`${e}\0${t}\0${r}`}var O=r(57659);async function handleBrokeredHostOperationRequest(e,t){let r=e.brokerTraceId||"none";if(!(0,k.Y)(e.sessionId,e.toolCallId,t))return t.logger?.info?.(`[BrokeredShell] phase=ipc-host-op | operation=${e.operation??"<unknown>"} | sessionMatch=false | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | runtime=${e.runtime??"unknown"} | result=deny | reason=session-mismatch`),(0,w.H0)(e,"Brokered sandbox IPC session mismatch");let o=await t.bashSandboxManager.getConfig(),s=t.safeDeleteReportRegistry.get(e.sessionId,e.toolCallId);t.logger?.info?.(`[BrokeredShell] phase=ipc-host-op | operation=${e.operation??"<unknown>"} | sessionMatch=true | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | runtime=${e.runtime??"unknown"} | reportPath=${s?"resolved":"missing"} | result=dispatch`);let i=await (0,w.i5)({service:t.brokeredSandboxHostService,approvalCoordinator:t.approvalCoordinator,request:{...e,safeDeleteReportPath:s},orderedFileRules:o?.orderedRules?.file.rules,sandboxFilesystem:o?.filesystem});return t.logger?.info?.(`[BrokeredShell] phase=ipc-host-op-complete | operation=${e.operation??"<unknown>"} | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | runtime=${e.runtime??"unknown"} | decision=${String(i.decision??"unknown")} | ok=${String(!0===i.ok)}`),i}var P=r(51460);async function handleBrokeredIpcLine(e,t){let r;if(!e.startsWith("{"))return handleBrokeredToyboxTextLine(e,t);try{r=JSON.parse(e)}catch{return t.logger?.info?.("[BrokeredShell] phase=ipc-host-op | brokerTraceId=none | result=deny | reason=invalid-json"),{ok:!1,decision:"deny",error:"Invalid broker IPC JSON request"}}let o=r.brokerTraceId||"none";return r.command===w.yR?handleBrokeredJsonFileTokenRequest(r,t):r.command===I?handleBrokeredFileWriteCompletedRequest(r,t):r.command===P.$m?(0,P.Ad)(r,t):r.command!==w.rU?(t.logger?.info?.(`[BrokeredShell] phase=ipc-host-op | operation=${r.operation??"<unknown>"} | brokerTraceId=${o} | toolCallId=${r.toolCallId?"set":"none"} | runtime=${r.runtime??"unknown"} | result=deny | reason=unsupported-command`),(0,w.H0)(r,`Unsupported brokered host file operation: ${r.operation??"<unknown>"}`)):handleBrokeredHostOperationRequest(r,t)}let BrokeredSafeDeleteReportRegistry=class BrokeredSafeDeleteReportRegistry{constructor(){this.safeDeleteReportPaths=new Map}remember(e,t,r,o){if(o?.info?.(`[BrokeredShell] phase=report-register | sessionId=${e?"set":"none"} | toolCallId=${t?"set":"none"} | reportPath=${r?"set":"none"}`),!e||!t||!r)return;let s=this.safeDeleteReportKey(e,t);this.safeDeleteReportPaths.delete(s),this.safeDeleteReportPaths.set(s,r),this.prune(o)}get(e,t){return e&&t?this.safeDeleteReportPaths.get(this.safeDeleteReportKey(e,t)):void 0}clear(){this.safeDeleteReportPaths.clear()}safeDeleteReportKey(e,t){return`${e}\0${t}`}prune(e){for(;this.safeDeleteReportPaths.size>5e3;){let t=this.safeDeleteReportPaths.keys().next().value;if(!t)return;this.safeDeleteReportPaths.delete(t),e?.warn?.("[cbc-kw=PERMISSION] [BrokeredSandboxIpc] safe-delete report path evicted | limit=5000")}}};var __decorate=function(e,t,r,o){var s,i=arguments.length,a=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,o);else for(var n=e.length-1;n>=0;n--)(s=e[n])&&(a=(i<3?s(a):i>3?s(t,r,a):s(t,r))||a);return i>3&&a&&Object.defineProperty(t,r,a),a},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let D=Symbol("BrokeredSandboxIpcServer");function shellCallKey(e,t){return`${e}\0${t}`}let E=class{constructor(){this.sockets=new Set,this.safeDeleteReportRegistry=new BrokeredSafeDeleteReportRegistry,this.sensitiveAccessDenialRegistry=new BrokeredSensitiveAccessDenialRegistry,this.textWriteAutoGrantRegistry=new BrokeredTextWriteAutoGrantRegistry,this.programBlockRegistry=new P.jO,this.nextConnectionId=0,this.activeRequests=0,this.activeDataRequests=0,this.requestWaiters=new Set,this.activeShellCalls=new Map}registerShellCall(e,t,r){if(!t)return()=>void 0;let o=shellCallKey(e,t),s=this.activeShellCalls.get(o)??new Set;return s.add(r),this.activeShellCalls.set(o,s),()=>{s.delete(r),0===s.size&&this.activeShellCalls.get(o)===s&&this.activeShellCalls.delete(o)}}isActiveShellCall(e,t){return(0,g.W)()?!!t&&this.activeShellCalls.has(shellCallKey(e,t)):e===this.sessionManager.sessionSubject.value?.id}shellContextFor(e){let t,r;if(e.startsWith("{"))try{let o=JSON.parse(e);t=o?.sessionId,r=o?.toolCallId}catch{return}else{let o=e.split(" ");if(4!==o.length)return;[,,t,r]=o}if("string"!=typeof t||"string"!=typeof r)return;let o=this.activeShellCalls.get(shellCallKey(t,r));return o?.values().next().value}async ensureStarted(){return this.server&&this.socketPath?this.socketPath:(this.startPromise??=this.start().finally(()=>{this.startPromise=void 0}),this.startPromise)}async start(){let e=await (0,n.mkdtemp)((0,p.join)((0,c.tmpdir)(),"cbb-"));await (0,n.chmod)(e,448);let t=(0,p.join)(e,"broker.sock"),r=d().createServer(e=>{let t=`${process.pid}-${++this.nextConnectionId}`;if(this.sockets.size>=256){this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] connection rejected | connectionId=${t} | reason=connection-limit | connections=${this.sockets.size} | limit=256`),e.destroy();return}let r=new AbortController,o=Date.now(),s="peer-close",i="request=none",a=0,n=0,l="";this.sockets.add(e);let d=setTimeout(()=>{s="first-frame-timeout",e.destroy()},5e3);e.once("close",()=>{clearTimeout(d),this.sockets.delete(e),r.abort();let c=`[BrokeredSandboxIpc] connection closed | connectionId=${t} | firstFrame: ${i} | reason=${this.server?s:"server-stop"} | durationMs=${Date.now()-o} | received=${a} | responded=${n} | unfinished=${a-n}`;"first-frame-timeout"===s?this.logger?.warn?.(`[cbc-kw=PERMISSION] ${c} | bufferedBytes=${Buffer.byteLength(l,"utf8")}`):this.logger?.info?.(c)}),e.on("error",o=>{s="socket-error",this.sockets.delete(e),r.abort(),this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] socket error | connectionId=${t}: ${o?.message??o}`),e.destroy()});let c=Promise.resolve(),h=0,p=0;e.on("data",o=>{let u;for(l+=o.toString("utf8");-1!==(u=l.indexOf("\n"));){let o=l.slice(0,u),g=Buffer.byteLength(o,"utf8");if(g>1048576){s="oversized-frame",this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] socket closed | connectionId=${t} | reason=oversized-frame | limit=1048576`),e.destroy();return}let f=o.trim();if(l=l.slice(u+1),f){if(clearTimeout(d),1==++a&&(i=this.requestLogContext(f)),h>=128||p+g>1048576){s="request-backlog",this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] socket closed | connectionId=${t} | reason=request-backlog | pending=${h} | pendingBytes=${p}`),e.destroy();return}h++,p+=g,c=c.then(async()=>{!e.destroyed&&await this.writeLineResponse(e,f,r.signal)&&n++}).catch(e=>{this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] response error | connectionId=${t}: ${e?.message??e}`)}).finally(()=>{h--,p-=g})}}Buffer.byteLength(l,"utf8")>1048576&&(s="oversized-frame",this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] socket closed | connectionId=${t} | reason=oversized-frame | limit=1048576`),e.destroy())})});try{await new Promise((e,o)=>{r.once("error",o),r.listen(t,()=>{r.off("error",o),e()})}),await (0,n.chmod)(t,384)}catch(e){throw await this.closeServer(r).catch(()=>void 0),await this.removeSocketResources(t),e}return this.server=r,this.socketPath=t,this.logger?.info?.("[BrokeredSandboxIpc] listening | endpoint=unix-socket"),t}getSocketPath(){return this.socketPath}rememberSafeDeleteReportPath(e,t,r){this.safeDeleteReportRegistry.remember(e,t,r,this.logger)}consumeSensitiveAccessDenied(e,t){return this.sensitiveAccessDenialRegistry.consume(e,t)}async flushTextWriteAutoGrants(e,t,r){await this.textWriteAutoGrantRegistry.flush({sessionId:e,toolCallId:t,deps:r??{logger:this.logger,sandboxLifecycle:this.sandboxLifecycle,sandboxCenterClient:this.sandboxCenterClient,sessionManager:this.sessionManager}})}drainProgramBlocks(e,t){return this.programBlockRegistry.drain({sessionId:e,toolCallId:t})}async stop(){await this.startPromise?.catch(()=>void 0);let{server:e,socketPath:t}=this;for(let e of(this.server=void 0,this.socketPath=void 0,this.startPromise=void 0,this.safeDeleteReportRegistry.clear(),this.sensitiveAccessDenialRegistry.clear(),this.textWriteAutoGrantRegistry.clear(),this.programBlockRegistry.clear(),this.activeShellCalls.clear(),this.approvalCoordinator.clearSessionApprovals(),Array.from(this.sockets)))e.destroy();this.sockets.clear(),e&&await this.closeServer(e),await this.removeSocketResources(t)}async closeServer(e){await new Promise(t=>e.close(()=>t()))}async removeSocketResources(e){e&&await (0,n.rm)((0,p.dirname)(e),{recursive:!0,force:!0}).catch(()=>void 0)}requestLogContext(e){let t;if(e.startsWith("{"))try{t=JSON.parse(e)??{}}catch{return"request=invalid-json"}else{let r=e.split(" ");t={command:"toybox",sessionId:4===r.length?r[2]:void 0,toolCallId:4===r.length?r[3]:void 0}}let field=e=>"string"==typeof e?e.slice(0,128).replace(/[^a-zA-Z0-9_.:-]/g,"_"):"none";return`request=${field(t.command)} | sessionId=${field(t.sessionId)} | toolCallId=${field(t.toolCallId)}`}async writeLineResponse(e,t,r){let o,s=this.isDataRequest(t);await this.acquireRequestCapacity(s,r);try{o=await this.handleLine(t,r).catch(e=>({ok:!1,decision:"deny",error:e?.message??String(e)}))}finally{this.releaseRequestCapacity(s)}let i="string"==typeof o?o:JSON.stringify(o);return!e.destroyed&&(e.write(`${i}
|
|
1
|
+
"use strict";exports.ids=["3080"],exports.modules={35550(e,t,r){r.d(t,{$6:()=>handleBrokeredFileTokenRequest,H0:()=>denyBrokeredHostOperationRequest,i5:()=>handleBrokeredHostOperation,rU:()=>l,yR:()=>d});var o=r(70857),s=r(16928),i=r.n(s),a=r(68390),n=r(46816);let l="HostFileOperation",d="FileTokenRequest",c={delete:{buildParams:e=>e.path?{path:e.path,deleteMode:e.deleteMode,recursive:e.recursive,force:e.force,safeDeleteReportPath:e.safeDeleteReportPath,runtime:e.runtime}:void 0,audits:["delete"],execute:(e,t)=>e.deletePath(t)},mkdir:{buildParams:e=>e.path?{path:e.path,recursive:e.recursive,mode:e.mode}:void 0,audits:["write"],execute:(e,t)=>e.mkdirPath(t)},rename:{buildParams:e=>e.from&&e.to?{from:e.from,to:e.to}:void 0,audits:["delete","target:write","target:delete"],execute:(e,t)=>e.renamePath(t)},copy:{buildParams:e=>e.from&&e.to?{from:e.from,to:e.to,recursive:e.recursive}:void 0,audits:["read","target:write","target:delete"],execute:(e,t)=>e.copyPath(t)},chmod:{buildParams:e=>e.path&&"number"==typeof e.mode?{path:e.path,mode:e.mode}:void 0,audits:["write"],execute:(e,t)=>e.chmodPath(t)},link:{buildParams:e=>e.from&&e.to?{from:e.from,to:e.to,symbolic:e.symbolic}:void 0,audits:e=>e.symbolic?["target:write"]:["read","target:write"],execute:(e,t)=>e.linkPath(t)},touch:{buildParams:e=>e.path?{path:e.path}:void 0,audits:["write"],execute:(e,t)=>e.touchPath(t)}};async function handleBrokeredHostOperation(e){let{service:t,approvalCoordinator:r,request:o,orderedFileRules:s,sandboxFilesystem:i}=e,a=await r.dispatchAndRecordPrompt(o,async e=>{let r=await dispatchBrokeredHostOperation({service:t,request:o,orderedFileRules:s,sandboxFilesystem:i,approvalScope:e});return r&&reportBrokeredHostOperationAudits(o,r.result,r.audits,s),r?.result});return a?withResponseId(o.id,a):denyBrokeredHostOperationRequest(o,`Unsupported brokered host file operation: ${o.operation??"<unknown>"}`)}async function handleBrokeredFileTokenRequest(e){let{service:t,approvalCoordinator:r,request:o,orderedFileRules:s}=e,i=await r.dispatchAndRecordPrompt(o,async e=>{let r=await t.requestFileToken({...o,orderedFileRules:s,approvalScope:e});return reportBrokeredResult(o,r,r.operation,s),r});return i?withResponseId(o.id,i):denyBrokeredFileTokenRequest(o,"No result from brokered file token approval loop")}async function dispatchBrokeredHostOperation(e){let{service:t,request:r,orderedFileRules:o,sandboxFilesystem:s,approvalScope:i}=e,a=r.operation?c[r.operation]:void 0,n=a?.buildParams(r);if(!a||!n)return;let l={...n,orderedFileRules:o,sandboxFilesystem:s,approvalScope:i,sessionId:r.sessionId},d="function"==typeof a.audits?a.audits(r):a.audits;return withAudits(a.execute(t,l),d)}function denyBrokeredHostOperationRequest(e,t){return withResponseId(e.id,{ok:!1,operation:e.operation??"unknown",path:e.path??e.from??"",normalisedPath:e.path??e.from??"",decision:"deny",error:t})}function denyBrokeredFileTokenRequest(e,t){return withResponseId(e.id,{ok:!1,operation:e.operation,path:e.path,normalisedPath:e.path,decision:"deny",error:t})}async function withAudits(e,t){return{result:await e,audits:t}}function reportBrokeredHostOperationAudits(e,t,r,o){for(let s of r){let r="target:delete"===s&&t.to&&t.toDeleteDecision?{...t,path:t.to,normalisedPath:t.normalisedTo??t.to,decision:t.toDeleteDecision,matchedRule:t.toDeleteMatchedRule,approvedByUser:t.toDeleteApprovedByUser}:"target:write"===s&&t.to?{...t,path:t.to,normalisedPath:t.normalisedTo??t.to,matchedRule:t.toMatchedRule,approvedByUser:t.toApprovedByUser}:t.to?{...t,approvedByUser:t.sourceApprovedByUser}:s.startsWith("target:")?void 0:t;r&&reportBrokeredResult(e,r,"target:write"===s?"write":"target:delete"===s?"delete":s,o)}}function reportBrokeredResult(e,t,r,o){if(!shouldReportBrokeredAudit(t))return;let s={sessionId:e.sessionId,requestId:e.id,toolCallId:e.toolCallId,paths:[t.path],matchedRule:t.matchedRule?.pathPattern,operation:r};if(t.approvedByUser){(0,a.AC)("ask-matched",s),(0,a.AC)("approved",s);return}"deny"===t.decision?(0,a.AC)("deny-matched",s):"prompt"===t.decision?(0,a.AC)("ask-matched",s):"policyReason"in t&&"implicit-safe-delete-fallback"===t.policyReason?(0,a.AC)("auto-approved",s):("grant-token"===t.decision||"host-op"===t.decision||"sandbox"===t.decision&&t.ok)&&isOrderedFileAllow(t.matchedRule?.pathPattern,r,o)&&(0,a.AC)("allow-listed",s)}function isOrderedFileAllow(e,t,r){if(!e)return!1;let o=normaliseOrderedRuleIdentity(e),s=r?.find(e=>normaliseOrderedRuleIdentity(e.path)===o);return s?.source!=="preset"&&s?.["access"===t?"read":t]==="allow"}function normaliseOrderedRuleIdentity(e){let t="~"===e?(0,o.homedir)():e.startsWith("~/")?i().join((0,o.homedir)(),e.slice(2)):e,r=i().normalize(t).replace(/\\/g,"/"),s=r.length>1?r.replace(/\/+$/,""):r;return"win32"===process.platform?s.toLowerCase():s}function shouldReportBrokeredAudit(e){return!!e.matchedRule&&e.matchedRule.pathPattern!==n.uf}function withResponseId(e,t){return e?{id:e,...t}:{...t}}},57659(e,t,r){r.d(t,{l:()=>C,t:()=>x});var o,s,i=r(88523),a=r(21215),n=r(91943),l=r(73339),d=r(70857),c=r.n(d),h=r(16928),p=r(9386),u=r(15526),g=r(26258),f=r(737),m=r(26384),y=r(12128),S=r(9890),_=r(96893),b=r(29801);function isAccessApproved(e,t,r){return e.decision===t||hasApprovedAccess(e,r)}function hasApprovedAccess(e,t){return"prompt"===e.decision&&(t?.accesses??[]).some(t=>t.operation===e.operation&&t.normalisedPath===e.normalisedPath&&t.matchedRule?.source===e.matchedRule?.source&&t.matchedRule?.pathPattern===e.matchedRule?.pathPattern)}function toApprovalAccess(e){return"prompt"===e.decision?{operation:e.operation,normalisedPath:e.normalisedPath,matchedRule:e.matchedRule}:void 0}function hostDeny(e,t,r,o={}){return hostRefusal(e,rawPathRef(t),"deny",r,o)}function hostPolicyRefusal(e,t,r,o={}){return hostRefusal(e,t,t.decision,r,{...o,...t.decisionRecord?{refusedOperation:t.operation}:{},approvalAccess:toApprovalAccess(t)})}function hostRefusal(e,t,r,o,s={}){return{ok:!1,operation:e,...hostPathFields(t),decision:r,...t.decisionRecord?{decisionRecord:t.decisionRecord}:{},...s,error:o}}function hostSuccess(e,t,r,o,s={}){return{ok:!0,operation:e,...hostPathFields(t),decision:r,...approvedByUser(o,t),...s}}function rawPathRef(e){return{path:e,normalisedPath:e}}function hostPairPolicyRefusal(e,t,r,o,s){return hostRefusal(e,t,o.decision,s,{...hostPairFields(r),..."delete"===o.operation&&o.path===r.path?hostPairDeleteFields(o):{},matchedRule:o.matchedRule,decisionRecord:o.decisionRecord,...o.decisionRecord?{refusedOperation:o.operation}:{},approvalAccess:toApprovalAccess(o)})}function hostPairCompletion(e,t,r,o,s,i){let a={...hostPairFields(r,o),...isFileAccessDecision(t)&&hasApprovedAccess(t,o)?{sourceApprovedByUser:!0}:{},...i?hostPairDeleteFields(i,o):{},matchedRule:t.matchedRule??r.matchedRule};return void 0!==s?hostRefusal(e,t,"host-op",s,a):{ok:!0,operation:e,...hostPathFields(t),decision:"host-op",...a,...approvedByUser(o,isFileAccessDecision(t)?t:void 0,r,i)}}function hostPathFields(e){return{path:e.path,normalisedPath:e.normalisedPath,matchedRule:e.matchedRule}}function hostPairFields(e,t){return{to:e.path,normalisedTo:e.normalisedPath,toMatchedRule:e.matchedRule,...isFileAccessDecision(e)&&hasApprovedAccess(e,t)?{toApprovedByUser:!0}:{}}}function isFileAccessDecision(e){return"decision"in e&&"operation"in e&&"level"in e}function hostPairDeleteFields(e,t){return{toDeleteDecision:e.decision,toDeleteMatchedRule:e.matchedRule,...hasApprovedAccess(e,t)?{toDeleteApprovedByUser:!0}:{}}}function approvedByUser(e,...t){return t.some(t=>t&&hasApprovedAccess(t,e))?{approvedByUser:!0}:{}}var v=r(45869);let BrokeredSandboxPathValidator=class BrokeredSandboxPathValidator{async resolveExistingPath(e){try{return await (0,n.realpath)(e)}catch{return}}async resolvePathThroughParent(e){let t=await this.resolveCreatablePath((0,h.dirname)(e));return t?(0,h.join)(t,(0,h.basename)(e)):void 0}async resolveExistingOrCreatablePath(e){return await this.resolveExistingPath(e)??this.resolvePathThroughParent(e)}async refuseIfResolvedPathUnsafe(e){let t=await this.refuseIfResolvedPathNotAllowed({...e,resolvedPath:e.approvedResolvedPath});if(t)return t;let r=await e.resolvePath();if(e.approvedResolvedPath===r)return;let o=await this.refuseIfResolvedPathNotAllowed({...e,resolvedPath:r});if(o)return o;let s=r?"changed":"could not be revalidated";return this.resolvedPathRefusal(e,`Brokered ${e.resultOperation} refused because the resolved path ${s} before execution`)}async refuseIfResolvedPathNotAllowed(e){if(!e.resolvedPath)return;let t=await e.resolveAccess(e.resolvedPath);if(t.available&&(t.allowed||hasApprovedAccess(t.access,e.approvalScope)))return;let r=!!e.fromAccess,o="read"===e.resultOperation||"write"===e.resultOperation?"file token":e.resultOperation,s=t.available?t.access.decision:e.unavailableDecision??"deny";return this.resolvedPathRefusal(e,`Brokered ${o} refused by resolved path policy: ${s}`,{decision:s,matchedRule:r?(e.fromAccess??e.access).matchedRule:t.access.matchedRule,toMatchedRule:r?t.access.matchedRule:e.toAccess?.matchedRule,approvalAccess:t.available?toApprovalAccess(t.access):void 0})}async resolveCreatablePath(e){let t=await this.resolveExistingPath(e);if(t)return t;let r=(0,h.dirname)(e);if(r===e)return;let o=await this.resolveCreatablePath(r);return o?(0,h.join)(o,(0,h.basename)(e)):void 0}resolvedPathRefusal(e,t,r={}){let o=e.fromAccess??e.access,s=e.toAccess??(e.fromAccess?e.access:void 0),{decision:i="deny",...a}=r;return hostRefusal(e.resultOperation,o,i,t,{to:s?.path,normalisedTo:s?.normalisedPath,toMatchedRule:s?.matchedRule,...a})}};var R=r(46816);let SandboxFileRuleMatcher=class SandboxFileRuleMatcher{constructor(e,t){this.resolveCenterClient=e,this.getLogger=t}async resolve(e){let t,r=(0,_.QH)(e.path),o="rename"===e.operation?"write":e.operation,s={path:e.requestPath??e.path,normalisedPath:r,operation:o,decision:"sandbox",level:"unknown"};if((0,R.Lg)(r,o))return{access:{...s,decision:"sandbox",level:"low",matchedRule:R.ZH},allowed:!0,available:!0};let i=this.resolveCenterClient(e.sessionId);if(!i||!e.sessionId)return{access:s,available:!1};try{t=await (0,p.Ej)(i,e.sessionId,{path:e.path,op:e.operation,...void 0===e.dstPath?{}:{dstPath:e.dstPath},...void 0===e.targetExists?{}:{targetExists:e.targetExists},...void 0===e.skipSensitiveDetect?{}:{skipSensitiveDetect:e.skipSensitiveDetect}})}catch(t){return this.getLogger()?.info?.(`[BrokeredShell] phase=decide-file | result=unknown | sessionId=${e.sessionId} | path=${e.path} | error=${t?.message??String(t)}`),{access:s,available:!1}}if("allow"!==t.action&&"ask"!==t.action&&"deny"!==t.action)return this.getLogger()?.info?.(`[BrokeredShell] phase=decide-file | result=unknown | sessionId=${e.sessionId} | path=${e.path} | error=invalid action ${t.action}`),{access:s,available:!1};let a=t.action,n="allow"===a,l=t.decisionRecord.matchRule?.pattern;return{access:{...s,decisionRecord:t.decisionRecord,decision:"allow"===a?"sandbox":"deny"===a?"deny":"prompt",level:"deny"===a?"high":n?"low":"unknown",matchedRule:l?{pathPattern:l,level:n?"low":"high",source:n?"user-allowlist":"user-blocklist"}:void 0},allowed:n,modifier:t.modifier,ruleCategory:t.decisionRecord.matchRule?.category,available:!0}}};var __decorate=function(e,t,r,o){var s,i=arguments.length,a=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,o);else for(var n=e.length-1;n>=0;n--)(s=e[n])&&(a=(i<3?s(a):i>3?s(t,r,a):s(t,r))||a);return i>3&&a&&Object.defineProperty(t,r,a),a},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let C=Symbol("BrokeredSandboxHostService"),w=(0,l.createRequire)(__filename),errorMessage=e=>e?.message??String(e),brokeredRuleSource=e=>e?.source??"none",accessForHostExecution=(e,t)=>e.available&&e.allowed?{...e.access,decision:t}:e.access,remapResolutionAccess=(e,t,r)=>{let o={...e.access,path:t,normalisedPath:(0,_.QH)(t),operation:r};return e.available?{...e,access:o}:{access:o,available:!1}};function hasMeaningfulResolvedPathDifference(e,t){if(!t)return!1;let normaliseForAliasComparison=e=>{let t=(0,_.QH)(e).replace(/\/+$/,"");for(let e of["/private/var","/private/tmp"])if(t===e||t.startsWith(`${e}/`))return t.slice(8);return t};return normaliseForAliasComparison(e)!==normaliseForAliasComparison(t)}let executeHostAction=async e=>{try{await e();return}catch(e){return errorMessage(e)}},x=class{constructor(){this.pathValidator=new BrokeredSandboxPathValidator,this.fileRuleMatcher=new SandboxFileRuleMatcher(()=>this.sandboxCenterClient,()=>this.logger),this.targetOperationLocks=new Map,this.maxRecursiveCopyEntries=1e4}async requestFileToken(e){if(!(0,h.isAbsolute)(e.path))return hostDeny(e.operation,e.path,"Brokered file token requires an absolute path");let t=await this.pathValidator.resolveExistingOrCreatablePath(e.path),r=t&&/[/\\]$/.test(e.path)&&!/[/\\]$/.test(t)?`${t}/`:t??e.path,o="write"===e.operation?await this.targetPathExists(r):void 0,s="read"===e.operation||void 0,i=await this.fileRuleMatcher.resolve({path:r,requestPath:e.path,operation:e.operation,targetExists:o,skipSensitiveDetect:s,sessionId:e.sessionId}),a=i.access;if(!i.available)return hostPolicyRefusal(e.operation,a,"Brokered file token deferred to sandbox because runtime file rule is unavailable");let n=await this.canDeferDirectoryRead(e,t,i),l=i.allowed||n;if(l&&hasMeaningfulResolvedPathDifference(e.path,t)){let r=await this.fileRuleMatcher.resolve({path:e.path,requestPath:e.path,operation:e.operation,targetExists:o,skipSensitiveDetect:s,sessionId:e.sessionId});if(!r.available)return hostPolicyRefusal(e.operation,n?a:r.access,"Brokered file token request path runtime file rule is unavailable");if(!r.allowed)if(a=r.access,await this.canDeferDirectoryRead(e,t,r))n=!0;else{if(!hasApprovedAccess(a,e.approvalScope))return hostPolicyRefusal(e.operation,a,"Brokered file token requires approval for the request path runtime file rule");l=!1}}if(l)return n&&this.logger?.info?.(`[BrokeredShell] phase=directory-read | centerAction=ask | result=sandbox | path=${e.path} | resolvedPath=${t}`),hostSuccess(e.operation,a,"sandbox",n?void 0:e.approvalScope);if(!hasApprovedAccess(a,e.approvalScope))return hostPolicyRefusal(e.operation,a,"Brokered file token requires approval for the matched runtime file rule");let d=await this.pathValidator.refuseIfResolvedPathUnsafe({access:a,resultOperation:e.operation,approvedResolvedPath:t,resolvePath:()=>this.pathValidator.resolveExistingOrCreatablePath(e.path),approvalScope:e.approvalScope,unavailableDecision:"sandbox",resolveAccess:t=>this.fileRuleMatcher.resolve({path:t,requestPath:e.path,operation:e.operation,targetExists:o,skipSensitiveDetect:s,sessionId:e.sessionId})});if(d)return d;let c=Date.now();try{let t=await this.issueFileToken({operation:e.operation,tokenPath:r}),o=hasApprovedAccess(a,e.approvalScope)?"grant-token":a.decision;return hostSuccess(e.operation,a,o,e.approvalScope,{inspectionPath:r,token:t})}catch(o){let t=o?.code??o?.signal??o?.name??"unknown";return this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=host-file-token | event=issuer-failed | operation=${e.operation} | tokenPath=${r} | durationMs=${Date.now()-c} | errorCode=${t} | error=${errorMessage(o)}`),hostRefusal(e.operation,a,"deny",`Brokered file token issuer failed: ${errorMessage(o)}`)}}async canDeferDirectoryRead(e,t,r){if("darwin"!==process.platform||"read"!==e.operation||!t||!this.sandboxTurnConfig?.useSandboxCLI||"default-strict"!==this.sandboxTurnConfig.ruleProfile||!e.sessionId||e.sessionId!==this.sandboxLifecycle?.getOpenedSessionId()||r.access.decisionRecord?.action!=="ask"||"rule"!==r.access.decisionRecord.reason||!r.access.matchedRule)return!1;try{return(await (0,n.lstat)(t)).isDirectory()}catch{return!1}}async issueFileToken(e){if("darwin"!==process.platform)throw Error("macOS sandbox extension tokens are only available on darwin");let t="read"===e.operation?"com.workbuddy.sandbox.read":"com.workbuddy.sandbox.read-write",r=this.loadFileSandboxExtensionIssuer().issueFileSandboxExtension(t,e.tokenPath,0);if("string"!=typeof r||0===r.length)throw Error("macOS sandbox extension issuer returned no token");return r}loadFileSandboxExtensionIssuer(){let e=(0,y.hR)()?.shimDir;if(!e)throw Error("macOS sandbox extension native addon is unavailable");let t=(0,h.join)(e,"native",`darwin-${process.arch}`,"brokered-sandbox-native.node"),r=w(t);if("function"!=typeof r.issueFileSandboxExtension)throw Error(`Native addon does not export issueFileSandboxExtension: ${t}`);return r}async deletePath(e){let t=e.deleteMode??("darwin"===process.platform?"trash":"unlink"),r={deleteMode:t},o=Date.now();return this.logger?.info?.(`[BrokeredShell] phase=host-delete | event=received | path=${e.path} | deleteMode=${t} | recursive=${e.recursive??!1} | force=${e.force??!1} | reportPath=${e.safeDeleteReportPath?"set":"none"}`),this.executeSingleHostOperation({resultOperation:"delete",...e,fileOperation:"delete",expectedDecision:"host-op",resolvePath:()=>this.pathValidator.resolvePathThroughParent(e.path),execute:async s=>{let i=s.access.matchedRule?.pathPattern,a="trash"===t&&s.available&&"auto_grant"===s.ruleCategory&&void 0!==i&&(0,_.QH)(i)===s.access.normalisedPath?"unlink":t;r.deleteMode=a;let l={recursive:e.recursive??!1,force:e.force??!1};this.logger?.info?.(`[BrokeredShell] phase=host-delete | event=executing | path=${e.path} | deleteMode=${a}`);try{if("trash"!==a)return void await (0,n.rm)(e.path,l);let t="node"===e.runtime||"python"===e.runtime?e.runtime:"bash";await this.trashPath(e.path,{...l,reportPath:e.safeDeleteReportPath,runtime:t,onNativeTrashError:t=>this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=host-delete | event=native-trash-failed | path=${e.path} | error=${t?.message??t} | fallback=attempting`)}),this.logger?.info?.(`[BrokeredShell] phase=host-delete | event=trash-succeeded | path=${e.path} | reportPath=${e.safeDeleteReportPath?"set":"none"} | durationMs=${Date.now()-o}`)}catch(t){throw this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=host-delete | event=failed | path=${e.path} | durationMs=${Date.now()-o} | error=${t?.message??t}`),t}},resultExtra:r})}async trashPath(e,t){await (0,m.w)(e,t)}async mkdirPath(e){return this.executeSingleHostOperation({resultOperation:"mkdir",...e,resolvePath:()=>this.pathValidator.resolvePathThroughParent(e.path),execute:()=>(0,n.mkdir)(e.path,{recursive:e.recursive??!1,mode:e.mode})})}async executeSingleHostOperation(e){let t=Date.now(),r=e.fileOperation??"write",o=e.expectedDecision??"grant-token";if(!(0,h.isAbsolute)(e.path)){let r=hostDeny(e.resultOperation,e.path,`Brokered host ${e.resultOperation} requires an absolute path`,e.resultExtra);return this.logHostOperationComplete(e.resultOperation,e.path,r,t),r}let s=await e.resolvePath(),i="write"===r?await this.targetPathExists(e.path):void 0,a=await this.fileRuleMatcher.resolve({path:e.path,operation:r,targetExists:i,sessionId:e.sessionId});if(!a.available){let r=hostRefusal(e.resultOperation,a.access,"deny",`Brokered host ${e.resultOperation} requires an available runtime file rule`,e.resultExtra);return this.logHostOperationComplete(e.resultOperation,e.path,r,t),r}let n=this.isDarwinImplicitFallbackSafeDelete(e,a),l=n?{...a.access,decision:o}:accessForHostExecution(a,o);if(!isAccessApproved(l,o,e.approvalScope)){this.logger?.info?.(`[BrokeredShell] phase=host-policy | operation=${e.resultOperation} | decision=${l.decision} | expectedDecision=${o} | matchedRuleSource=${brokeredRuleSource(l.matchedRule)} | approvedByUser=${hasApprovedAccess(l,e.approvalScope)} | result=refused`);let r=hostPolicyRefusal(e.resultOperation,l,`Brokered host ${e.resultOperation} refused by file policy: ${l.decision}`,e.resultExtra);return this.logHostOperationComplete(e.resultOperation,e.path,r,t),r}this.logger?.info?.(`[BrokeredShell] phase=host-policy | operation=${e.resultOperation} | decision=${l.decision} | expectedDecision=${o} | matchedRuleSource=${brokeredRuleSource(l.matchedRule)} | approvedByUser=${hasApprovedAccess(l,e.approvalScope)} | result=approved`);let d=await this.refuseResolvedHostPath(e,l,r,s,e.resolvePath);if(d)return this.logHostOperationComplete(e.resultOperation,e.path,d,t),d;let c=await (0,b.OB)({enabled:"mkdir"===e.resultOperation||"touch"===e.resultOperation,sessionId:e.sessionId,targetPath:e.path,deps:this.createdPathAutoGrantDeps()}),p=await executeHostAction(async()=>{await this.backupBeforeSingleHostOperation(e,this.shouldUseCenterBackup(a)),await e.execute(a),await c?.afterSuccess()});if(void 0!==p){let r=hostRefusal(e.resultOperation,l,"host-op"===o?l.decision:"host-op",p,e.resultExtra);return this.logHostOperationComplete(e.resultOperation,e.path,r,t),r}let u="host-op"===o?hasApprovedAccess(l,e.approvalScope)?o:l.decision:"host-op",g=hostSuccess(e.resultOperation,l,u,e.approvalScope,{...e.resultExtra,...n?{policyReason:"implicit-safe-delete-fallback"}:{}});return this.logHostOperationComplete(e.resultOperation,e.path,g,t),g}async renamePath(e){return this.executeTwoPathHostOperation({resultOperation:"rename",...e,execute:()=>(0,n.rename)(e.from,e.to)})}async copyPath(e){return e.recursive?this.copyPathRecursive(e):this.executeTwoPathHostOperation({resultOperation:"copy",...e,resolveTargetPath:()=>this.pathValidator.resolveExistingOrCreatablePath(e.to),execute:()=>(0,n.copyFile)(e.from,e.to)})}async executeTwoPathHostOperation(e){return this.withTargetOperationLock(e.to,()=>this.executeTwoPathHostOperationLocked(e))}async copyPathRecursive(e){let t;try{t=await (0,n.lstat)(e.from)}catch(t){return hostDeny("copy",e.from,`Brokered host recursive copy source is unavailable: ${errorMessage(t)}`,{to:e.to,normalisedTo:e.to})}return t.isDirectory()?this.withTargetOperationLock(e.to,()=>this.copyDirectoryRecursiveLocked(e)):this.executeTwoPathHostOperation({resultOperation:"copy",...e,resolveTargetPath:()=>this.pathValidator.resolveExistingOrCreatablePath(e.to),execute:()=>(0,n.copyFile)(e.from,e.to)})}async copyDirectoryRecursiveLocked(e){let t,r=Date.now();if(!(0,h.isAbsolute)(e.from)||!(0,h.isAbsolute)(e.to)){let t=hostDeny("copy",e.from,"Brokered host recursive copy requires absolute source and target paths",{to:e.to,normalisedTo:e.to});return this.logHostOperationComplete("copy",e.from,t,r,e.to),t}let o=await this.refuseRecursiveCopySymlinks(e);if(o)return this.logHostOperationComplete("copy",e.from,o,r,e.to),o;try{t=await this.scanRecursiveCopyEntries(e.from,e.to)}catch(o){let t=hostRefusal("copy",rawPathRef(e.from),"sandbox",`Brokered host recursive copy deferred to sandbox: ${errorMessage(o)}`,{to:e.to,normalisedTo:e.to});return this.logHostOperationComplete("copy",e.from,t,r,e.to),t}let s=await this.resolveRecursiveCopyAccess(e.from,e.from,"read","grant-token",e.sessionId),i=await this.targetPathExists(e.to),a=await this.resolveRecursiveCopyAccess(e.to,e.to,"write","host-op",e.sessionId,i),l=await this.buildRecursiveCopyPolicyChecks(e,t,s,a),d=this.recursiveCopyPolicyRefusal(e,l);if(d)return this.logHostOperationComplete("copy",e.from,d,r,e.to),d;let c=t.filter(e=>e.targetExists&&!(e.isDirectory&&e.targetIsDirectory)).map(e=>e.targetPath),p=await (0,b.OB)({enabled:!0,sessionId:e.sessionId,targetPath:e.to,deps:this.createdPathAutoGrantDeps()}),u=l.find(e=>"delete"===e.access.operation)?.access,g=await executeHostAction(async()=>{await this.backupBeforeHostMutation(c,e.sessionId),await (0,n.cp)(e.from,e.to,{recursive:!0}),await p?.afterSuccess()}),f=hostPairCompletion("copy",s.access,a.access,e.approvalScope,g,u);return this.logHostOperationComplete("copy",e.from,f,r,e.to),f}async scanRecursiveCopyEntries(e,t){let r=[],visit=async o=>{let s;if(r.length>=this.maxRecursiveCopyEntries)throw Error(`recursive copy exceeds ${this.maxRecursiveCopyEntries} entries`);let i=await (0,n.lstat)(o);if(i.isSymbolicLink())throw Error(`recursive copy source tree contains a symlink: ${o}`);let a=(0,h.relative)(e,o),l=a?(0,h.join)(t,a):t;try{s=await (0,n.lstat)(l)}catch(e){if("ENOENT"!==e.code)throw e}if(r.push({sourcePath:o,targetPath:l,isDirectory:i.isDirectory(),targetExists:void 0!==s,targetIsDirectory:s?.isDirectory()??!1}),i.isDirectory())for(let e of(await (0,n.readdir)(o)))await visit((0,h.join)(o,e))};return await visit(e),r}async refuseRecursiveCopySymlinks(e){let t=(0,h.join)(e.to,"..");try{let r=await this.pathValidator.resolveExistingPath(t);if(r&&hasMeaningfulResolvedPathDifference(t,r))return hostRefusal("copy",rawPathRef(e.from),"sandbox","Brokered host recursive copy deferred to sandbox: target path contains symlinks",{to:e.to,normalisedTo:e.to})}catch{}}async resolveRecursiveCopyAccess(e,t,r,o,s,i){let a=await this.fileRuleMatcher.resolve({path:e,requestPath:t,operation:r,targetExists:i,sessionId:s});return{access:a.available?accessForHostExecution(a,o):{...a.access,decision:"deny"},expectedDecision:o,available:a.available}}async buildRecursiveCopyPolicyChecks(e,t,r,o){let s=[{...r,pathRef:r.access,toRef:rawPathRef(e.to),error:`Brokered host recursive copy source refused by file policy: ${r.access.decision}`},{...o,pathRef:r.access,toRef:o.access,error:`Brokered host recursive copy target refused by file policy: ${o.access.decision}`}];for(let o of t){if(o.sourcePath!==e.from){let t=await this.resolveRecursiveCopyAccess(o.sourcePath,o.sourcePath,"read","grant-token",e.sessionId);s.push({...t,pathRef:t.access,toRef:rawPathRef(o.targetPath),error:`Brokered host recursive copy source entry refused by file policy: ${t.access.decision}`})}if(o.targetPath!==e.to){let t=await this.resolveRecursiveCopyAccess(o.targetPath,o.targetPath,"write","host-op",e.sessionId,o.targetExists);s.push({...t,pathRef:r.access,toRef:t.access,error:`Brokered host recursive copy target entry refused by file policy: ${t.access.decision}`})}if(o.targetExists&&!(o.isDirectory&&o.targetIsDirectory)){let t=await this.resolveTargetDeleteAccess(o.targetPath,o.targetPath,e.sessionId);s.push({access:t,expectedDecision:"host-op",pathRef:r.access,toRef:t,error:`Brokered host recursive copy overwrite refused by file policy: ${t.decision}`})}}return s}recursiveCopyPolicyRefusal(e,t){let r=t.find(e=>"deny"===e.access.decision);if(r)return hostPairPolicyRefusal("copy",r.pathRef,r.toRef,r.access,r.error);let o=t.find(t=>!isAccessApproved(t.access,t.expectedDecision,e.approvalScope));if(o)return"sandbox"!==o.access.decision&&o.access.matchedRule?hostPairPolicyRefusal("copy",o.pathRef,o.toRef,o.access,o.error):hostRefusal("copy",rawPathRef(e.from),"sandbox","Brokered host recursive copy deferred to sandbox: no rule covers the target path",{to:e.to,normalisedTo:e.to})}async executeTwoPathHostOperationLocked(e){let t,r=Date.now(),o=e.sourcePolicy??("link"===e.resultOperation?void 0:{operation:"rename"===e.resultOperation?"delete":"read",expectedDecision:"rename"===e.resultOperation?"host-op":"grant-token"});if((e.requireAbsoluteSource??!!o)&&!(0,h.isAbsolute)(e.from)||!(0,h.isAbsolute)(e.to)){let t="link"===e.resultOperation?"Brokered host link requires an absolute target path, and hard-link requires an absolute source path":`Brokered host ${e.resultOperation} requires absolute source and target paths`,o=hostDeny(e.resultOperation,e.from,t,{to:e.to,normalisedTo:e.to});return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}let s=o?o.resolvePath??(()=>this.pathValidator.resolvePathThroughParent(e.from)):void 0,i=s?await s():void 0,a=await this.targetPathExists(e.to),n="rename"===e.resultOperation&&o&&s?await this.fileRuleMatcher.resolve({path:e.from,operation:"rename",dstPath:e.to,targetExists:a,sessionId:e.sessionId}):void 0,l=n?remapResolutionAccess(n,e.from,"delete"):o&&s?await this.fileRuleMatcher.resolve({path:e.from,operation:o.operation,sessionId:e.sessionId}):void 0,d=o&&l?{policy:o,access:accessForHostExecution(l,o.expectedDecision),resolvePath:s}:void 0,c=d?.access??rawPathRef(e.from);if(l&&!l.available){let t={...l.access,decision:"deny"},o=hostPairPolicyRefusal(e.resultOperation,t,rawPathRef(e.to),t,`Brokered host ${e.resultOperation} requires an available runtime file rule for the source`);return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}if(d&&!isAccessApproved(d.access,d.policy.expectedDecision,e.approvalScope)){if(!d.access.matchedRule){let t=hostRefusal(e.resultOperation,rawPathRef(e.from),"sandbox",`Brokered host ${e.resultOperation} deferred to sandbox: no rule covers the source`,{to:e.to,normalisedTo:e.to});return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}let t=hostPairPolicyRefusal(e.resultOperation,d.access,rawPathRef(e.to),d.access,`Brokered host ${e.resultOperation} source refused by file policy: ${d.access.decision}`);return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}let p=e.resolveTargetPath??(()=>this.pathValidator.resolvePathThroughParent(e.to)),u=await p(),g=n?remapResolutionAccess(n,e.to,"write"):await this.fileRuleMatcher.resolve({path:e.to,operation:"write",targetExists:a,sessionId:e.sessionId}),f=accessForHostExecution(g,"host-op");if(!g.available){let t={...f,decision:"deny"},o=hostPairPolicyRefusal(e.resultOperation,c,t,t,`Brokered host ${e.resultOperation} requires an available runtime file rule for the target`);return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}if(!isAccessApproved(f,"host-op",e.approvalScope)){if(!f.matchedRule){let t=hostRefusal(e.resultOperation,rawPathRef(e.from),"sandbox",`Brokered host ${e.resultOperation} deferred to sandbox: no rule covers the target`,{to:e.to,normalisedTo:e.to});return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}let t=hostPairPolicyRefusal(e.resultOperation,c,f,f,`Brokered host ${e.resultOperation} target refused by file policy: ${f.decision}`);return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}if(a&&(t=await this.resolveTargetDeleteAccess(u??e.to,e.to,e.sessionId)),t&&!isAccessApproved(t,"host-op",e.approvalScope)){let o=hostPairPolicyRefusal(e.resultOperation,c,t,t,`Brokered host ${e.resultOperation} overwrite refused by file policy: ${t.decision}`);return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}if(d){let t=await this.refuseResolvedHostPath(e,d.access,d.policy.operation,i,d.resolvePath,{toAccess:f});if(t)return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}let m=await this.refuseResolvedHostPath(e,f,"write",u,p,{fromAccess:d?.access});if(m)return this.logHostOperationComplete(e.resultOperation,e.from,m,r,e.to),m;if(t){let o=await this.refuseResolvedHostPath(e,t,"delete",u,p,{fromAccess:d?.access});if(o)return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}let y=await p(),S=await this.targetPathExists(e.to);if(S){if(!isAccessApproved(t=await this.resolveTargetDeleteAccess(y??e.to,e.to,e.sessionId),"host-op",e.approvalScope)){let o=hostPairPolicyRefusal(e.resultOperation,c,t,t,`Brokered host ${e.resultOperation} overwrite refused by file policy: ${t.decision}`);return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}let o=await this.refuseResolvedHostPath(e,t,"delete",y,p,{fromAccess:d?.access});if(o)return this.logHostOperationComplete(e.resultOperation,e.from,o,r,e.to),o}let v=n??g,R=f;if(S&&!a){let t=n?await this.fileRuleMatcher.resolve({path:e.from,operation:"rename",dstPath:e.to,targetExists:!0,sessionId:e.sessionId}):await this.fileRuleMatcher.resolve({path:e.to,operation:"write",targetExists:!0,sessionId:e.sessionId}),o=n?remapResolutionAccess(t,e.to,"write"):t;if(!o.available){let t={...accessForHostExecution(o,"host-op"),decision:"deny"},s=hostPairPolicyRefusal(e.resultOperation,c,t,t,`Brokered host ${e.resultOperation} target write refused: target appeared after initial authorization`);return this.logHostOperationComplete(e.resultOperation,e.from,s,r,e.to),s}let s=accessForHostExecution(o,"host-op");if(!isAccessApproved(s,"host-op",e.approvalScope)){let t=hostPairPolicyRefusal(e.resultOperation,c,s,s,`Brokered host ${e.resultOperation} target write ${"deny"===s.decision?"denied":"requires re-approval"} after target appeared`);return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}v=o,R=s}if("copy"===e.resultOperation){let t=await this.refuseResolvedHostPath(e,R,"write",y,p,{fromAccess:d?.access});if(t)return this.logHostOperationComplete(e.resultOperation,e.from,t,r,e.to),t}let C="rename"===e.resultOperation?await this.fileRuleMatcher.resolve({path:e.from,operation:"delete",sessionId:e.sessionId}):void 0,w=C?.access.matchedRule?.pathPattern,x=C?.available===!0&&"auto_grant"===C.ruleCategory&&void 0!==w&&(0,_.QH)(w)===C.access.normalisedPath,k="rename"!==e.resultOperation||x?"created":"renamed_existing",I=await (0,b.OB)({enabled:!0,sessionId:e.sessionId,targetPath:e.to,createdPathOrigin:k,deps:this.createdPathAutoGrantDeps()}),O=await executeHostAction(async()=>{let t=this.shouldUseCenterBackup(v);await this.backupBeforeTwoPathHostOperation(e,!!S&&!a||t),await e.execute(),await I?.afterSuccess()}),P=hostPairCompletion(e.resultOperation,c,R,e.approvalScope,O,t);return this.logHostOperationComplete(e.resultOperation,e.from,P,r,e.to),P}async targetPathExists(e){try{return await (0,n.lstat)(e),!0}catch(e){return"ENOENT"!==e.code}}async withTargetOperationLock(e,t){let r,o=(0,_.QH)(e),s=this.targetOperationLocks.get(o),i=new Promise(e=>{r=e});this.targetOperationLocks.set(o,i),s&&await s;try{return await t()}finally{r(),this.targetOperationLocks.get(o)===i&&this.targetOperationLocks.delete(o)}}async resolveTargetDeleteAccess(e,t,r){let o=await this.fileRuleMatcher.resolve({path:e,requestPath:t,operation:"delete",sessionId:r}),s=accessForHostExecution(o,"host-op");return o.available?s:{...s,decision:"deny"}}createdPathAutoGrantDeps(){return{logger:this.logger,sandboxLifecycle:this.sandboxLifecycle,sandboxCenterClient:this.sandboxCenterClient,sessionManager:this.sessionManager,sandboxTurnConfig:this.sandboxTurnConfig}}logHostOperationComplete(e,t,r,o,s){let i=`[BrokeredShell] phase=host-op | event=complete | operation=${e} | path=${t} ${s?`| to=${s} `:""}| ok=${String(r.ok)} | decision=${r.decision} | durationMs=${Date.now()-o}${r.error?` | error=${r.error}`:""}`;r.ok?this.logger?.info?.(i):this.logger?.warn?.(i)}async chmodPath(e){return this.executeSingleHostOperation({resultOperation:"chmod",...e,resolvePath:()=>this.pathValidator.resolveExistingPath(e.path),execute:()=>(0,n.chmod)(e.path,e.mode)})}async linkPath(e){return this.executeTwoPathHostOperation({resultOperation:"link",...e,requireAbsoluteSource:!e.symbolic,sourcePolicy:e.symbolic?void 0:{operation:"read",expectedDecision:"grant-token",resolvePath:()=>this.pathValidator.resolveExistingPath(e.from)},resolveTargetPath:()=>this.pathValidator.resolvePathThroughParent(e.to),execute:()=>e.symbolic?(0,n.symlink)(e.from,e.to):(0,n.link)(e.from,e.to)})}async touchPath(e){return this.executeSingleHostOperation({resultOperation:"touch",...e,resolvePath:()=>this.pathValidator.resolveExistingOrCreatablePath(e.path),execute:async()=>{let t=new Date;try{await (0,n.lstat)(e.path)}catch(t){if(t?.code!=="ENOENT")throw t;await (await (0,n.open)(e.path,"a")).close()}await (0,n.utimes)(e.path,t,t)}})}refuseResolvedHostPath(e,t,r,o,s,i={}){return this.pathValidator.refuseIfResolvedPathUnsafe({access:t,resultOperation:e.resultOperation,approvedResolvedPath:o,resolvePath:s,approvalScope:e.approvalScope,resolveAccess:async o=>{let s=await this.fileRuleMatcher.resolve({path:o,requestPath:t.path,operation:r,sessionId:e.sessionId});return this.isDarwinImplicitFallbackSafeDelete(e,s)?{...s,allowed:!0}:s},...i})}isDarwinImplicitFallbackSafeDelete(e,t){let r=e.orderedFileRules?.some(e=>"**"===e.path||"/"===e.path)??!1;return"darwin"===process.platform&&"delete"===e.resultOperation&&e.resultExtra?.deleteMode==="trash"&&t.available&&"prompt"===t.access.decision&&t.access.matchedRule?.pathPattern==="**"&&!r}shouldUseCenterBackup(e){return!e.available||void 0===e.modifier||(e.modifier&p.IJ)!=0}async backupBeforeSingleHostOperation(e,t){"delete"!==e.resultOperation&&"touch"!==e.resultOperation||("touch"!==e.resultOperation||t)&&await this.backupBeforeHostMutation([e.path],e.sessionId,"delete"!==e.resultOperation,"delete"===e.resultOperation?"d":"m")}async backupBeforeTwoPathHostOperation(e,t){switch(e.resultOperation){case"rename":await this.backupBeforeHostMutation([e.from],e.sessionId,!1,"d"),t&&await this.backupBeforeHostMutation([e.to],e.sessionId,!1);return;case"copy":t&&await this.backupBeforeHostMutation([e.to],e.sessionId);return;case"link":return}}async backupBeforeHostMutation(e,t,r=!0,o="m"){await (0,v.Z)({paths:e,sessionId:t,followSymlinks:r,excludedPathOptions:this.getModifyBackupExcludedPathOptions(),logPhase:"host-modify-backup",sandboxTurnConfig:this.sandboxTurnConfig,sandboxLifecycle:this.sandboxLifecycle,sandboxCenterClient:this.sandboxCenterClient,sessionManager:this.sessionManager,logger:this.logger,reason:o})}getModifyBackupExcludedPathOptions(){return{homeDir:c().homedir(),codebuddyHome:S.P.getHomeDir()}}};__decorate([(0,i.Autowired)(i.Logger),(0,i.Optional)(),__metadata("design:type","function"==typeof(o=void 0!==i.Logger&&i.Logger)?o:Object)],x.prototype,"logger",void 0),__decorate([(0,i.Autowired)(g.x),(0,i.Optional)(),__metadata("design:type",Object)],x.prototype,"sandboxTurnConfig",void 0),__decorate([(0,i.Autowired)(u.k),(0,i.Optional)(),__metadata("design:type",Object)],x.prototype,"sandboxLifecycle",void 0),__decorate([(0,i.Autowired)(f.SandboxCenterIpcClient),(0,i.Optional)(),__metadata("design:type",Object)],x.prototype,"sandboxCenterClient",void 0),__decorate([(0,i.Autowired)(a.SessionManager),(0,i.Optional)(),__metadata("design:type","function"==typeof(s=void 0!==a.SessionManager&&a.SessionManager)?s:Object)],x.prototype,"sessionManager",void 0),x=__decorate([(0,i.Component)(C)],x)},46816(e,t,r){r.d(t,{Lg:()=>isBrokeredShellInternalPath,ZH:()=>s,uf:()=>o}),r(70857),r(16928),r(12128);let o="<brokered-shell-runtime>",s={pathPattern:o,level:"low",source:"builtin"};function isBrokeredShellInternalPath(e,t){return"/dev/null"===e?"read"===t||"write"===t:"read"===t&&("/etc/zshenv"===e||"/private/etc/zshenv"===e)}},91168(e,t,r){r.d(t,{t:()=>D,v:()=>E});var o,s,i=r(88523),a=r(21215),n=r(91943),l=r(69278),d=r.n(l),c=r(70857),h=r.n(c),p=r(16928),u=r(43391),g=r(38073),f=r(15526),m=r(26258),y=r(737),S=r(42685),_=r(29889),b=r(572),v=r(43144),R=r(9890),C=r(29801),w=r(35550),x=r(45869),k=r(74262);let I="FileWriteCompleted";let BrokeredSensitiveAccessDenialRegistry=class BrokeredSensitiveAccessDenialRegistry{constructor(){this.denials=new Map}remember(e,t){this.prune(),this.denials.set(`${e}\0${t}`,Date.now())}consume(e,t){return!!e&&!!t&&(this.prune(),this.denials.delete(`${e}\0${t}`))}clear(){this.denials.clear()}prune(){let e=Date.now()-3e5;for(let[t,r]of this.denials.entries())r<e&&this.denials.delete(t)}};let BrokeredTextWriteAutoGrantRegistry=class BrokeredTextWriteAutoGrantRegistry{constructor(){this.candidates=new Map}async remember(e){this.prune();let t=R.P.toBackupPayloadPath(e.targetPath),r=getBrokeredTextWriteAutoGrantCandidateKey(e.sessionId,e.toolCallId,t);if(this.candidates.has(r))return e.onResult?void e.onResult("skip:already-queued",t):void e.deps.logger?.info?.(`[BrokeredShell] phase=ipc-token-auto-grant | result=skip | reason=already-queued | toolCallId=set | path=${t}`);let o=await isMissingPath(t,e.deps),s=await (0,C.OB)({enabled:!0,sessionId:e.sessionId,targetPath:t,deps:e.deps});if(s){if(this.candidates.set(r,{sessionId:e.sessionId,toolCallId:e.toolCallId,targetPath:t,effect:s,createdFromMissing:o,createdAtMs:Date.now()}),e.onResult)return void e.onResult("queued",e.targetPath);e.deps.logger?.info?.(`[BrokeredShell] phase=ipc-token-auto-grant | result=queued | toolCallId=set | path=${e.targetPath}`)}}async flush(e){let t=this.take(e.sessionId,e.toolCallId,e.targetPath);if(t.length){for(let e of t)await e.effect.afterSuccess();e.deps.logger?.info?.(`[BrokeredShell] phase=shell-auto-grant-flush | result=ok | count=${t.length} | toolCallId=${e.toolCallId?"set":"none"}`)}}hasCurrentTurnCreatedPath(e){for(let t of(this.prune(),this.candidates.values()))if(t.createdFromMissing&&t.sessionId===e.sessionId&&t.targetPath===e.targetPath&&(!e.toolCallId||t.toolCallId===e.toolCallId))return!0;return!1}clear(){this.candidates.clear()}take(e,t,r){this.prune();let o=[];for(let[s,i]of this.candidates.entries())e&&i.sessionId!==e||t&&i.toolCallId!==t||r&&i.targetPath!==r||(this.candidates.delete(s),o.push(i));return o}prune(){let e=Date.now()-3e5;for(let[t,r]of this.candidates.entries())r.createdAtMs<e&&this.candidates.delete(t)}};async function handleBrokeredJsonFileTokenRequest(e,t){let r,o=e.brokerTraceId||"none",s=e.sessionId,i="string"==typeof e.path?e.path:"",a="read"===e.operation||"write"===e.operation?e.operation:void 0;if(!s||!(0,k.Y)(s,e.toolCallId,t))return t.logger?.info?.(`[BrokeredShell] phase=ipc-file-token | operation=${e.operation??"<unknown>"} | sessionMatch=false | brokerTraceId=${o} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=session-mismatch`),denyBrokeredFileRequest(e,i,"Brokered sandbox IPC session mismatch");if(!a)return t.logger?.info?.(`[BrokeredShell] phase=ipc-file-token | operation=${e.operation??"<unknown>"} | sessionMatch=true | brokerTraceId=${o} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=unsupported-operation`),denyBrokeredFileRequest(e,i,`Unsupported brokered file token operation: ${e.operation??"<unknown>"}`);if(!i)return t.logger?.info?.(`[BrokeredShell] phase=ipc-file-token | operation=${a} | sessionMatch=true | brokerTraceId=${o} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=missing-path`),denyBrokeredFileRequest(e,i,"Brokered file token request requires a path");let n=await t.bashSandboxManager.getConfig(),l=await (0,w.$6)({service:t.brokeredSandboxHostService,approvalCoordinator:t.approvalCoordinator,request:{id:e.id,operation:a,path:i,sessionId:s,toolCallId:e.toolCallId,brokerTraceId:e.brokerTraceId},orderedFileRules:n?.orderedRules?.file.rules}),d=classifyFileTokenResponse(l);if("read"===a&&"deny"!==d){let r=await authorizeBrokeredReadOpen({request:e,inspectionPath:l.inspectionPath??l.path,runtime:e.runtime,sessionId:s,forceSensitiveDetection:!0===l.approvedByUser,deps:t});if(r?.kind==="deny")return rememberSensitiveAccessDenial(r,s,e.toolCallId,t),t.logger?.info?.(`[BrokeredShell] phase=ipc-sensitive-open | runtime=json | result=deny | reason=${r.code}`),denyBrokeredFileRequest(e,i,r.message)}let c=[],h=createFileTokenStageRecorder(i,c);if("write"===a&&"deny"!==d){try{await backupBeforeBrokeredWrite(s,i,t,e.toolCallId,h("backup"))}catch(o){d="deny",r=o?.message??String(o),t.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-file-token-backup | result=deny | reason=modify-backup-failed | runtime=${e.runtime??"unknown"} | error=${r}`)}r||await rememberTextWriteAutoGrant({registry:t.textWriteAutoGrantRegistry,sessionId:s,toolCallId:e.toolCallId??"",targetPath:i,deps:t,logPhase:"ipc-file-token-auto-grant",onResult:h("autoGrant")})}return(t.logger?.info?.(`[BrokeredShell] phase=ipc-file-token | operation=${a} | sessionMatch=true | brokerTraceId=${o} | toolCallId=${e.toolCallId?"set":"none"} | runtime=${e.runtime??"unknown"} | path=${i}${c.length?` | ${c.join(" | ")}`:""} | result=${d}`),r)?denyBrokeredFileRequest(e,i,"Brokered file token refused: modify backup failed"):l}async function handleBrokeredFileWriteCompletedRequest(e,t){let r=e.brokerTraceId||"none",o="string"==typeof e.path?e.path:"";return(0,k.Y)(e.sessionId,e.toolCallId,t)?"write"!==e.operation?(t.logger?.info?.(`[BrokeredShell] phase=ipc-file-write-completed | operation=${e.operation??"<unknown>"} | sessionMatch=true | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=unsupported-operation`),denyFileWriteCompletedRequest(e,o,`Unsupported brokered file write completion operation: ${e.operation??"<unknown>"}`)):o?(await t.textWriteAutoGrantRegistry?.flush({sessionId:e.sessionId,toolCallId:e.toolCallId,targetPath:R.P.toBackupPayloadPath(o),deps:{logger:t.logger,sandboxLifecycle:t.sandboxLifecycle,sandboxCenterClient:t.sandboxCenterClient,sessionManager:t.sessionManager}}),t.logger?.info?.(`[BrokeredShell] phase=ipc-file-write-completed | operation=write | sessionMatch=true | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | runtime=${e.runtime??"unknown"} | result=ok`),{...e.id?{id:e.id}:{},ok:!0,operation:"write-completed",path:o,normalisedPath:o,decision:"host-op"}):(t.logger?.info?.(`[BrokeredShell] phase=ipc-file-write-completed | operation=write | sessionMatch=true | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=missing-path`),denyFileWriteCompletedRequest(e,o,"Brokered file write completion requires a path")):(t.logger?.info?.(`[BrokeredShell] phase=ipc-file-write-completed | operation=${e.operation??"<unknown>"} | sessionMatch=false | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=session-mismatch`),denyFileWriteCompletedRequest(e,o,"Brokered sandbox IPC session mismatch"))}async function handleBrokeredToyboxTextLine(e,t){let r=e.split(" ");if(4!==r.length||r.some(e=>!e))return t.logger?.info?.("[BrokeredShell] phase=ipc-token | result=deny | reason=invalid-text-protocol"),"DENY";let[o,s,i,a]=r,n={"com.workbuddy.sandbox.read":"read","com.workbuddy.sandbox.read-write":"write"}[o];if(!n)return t.logger?.info?.(`[BrokeredShell] phase=ipc-token | toolCallId=${a?"set":"none"} | result=deny | reason=unknown-extension-class`),"DENY";if(!(0,k.Y)(i,a,t))return t.logger?.info?.(`[BrokeredShell] phase=ipc-token | operation=${n} | sessionMatch=false | toolCallId=${a?"set":"none"} | result=deny | reason=session-mismatch`),"DENY";let l=await t.bashSandboxManager.getConfig(),d=await (0,w.$6)({service:t.brokeredSandboxHostService,approvalCoordinator:t.approvalCoordinator,request:{operation:n,path:s,sessionId:i,toolCallId:a},orderedFileRules:l?.orderedRules?.file.rules}),c=classifyFileTokenResponse(d);if("read"===n&&"deny"!==c){let e=await authorizeBrokeredReadOpen({request:{sessionId:i,toolCallId:a},inspectionPath:d.inspectionPath??d.path,runtime:"bash",sessionId:i,forceSensitiveDetection:!0===d.approvedByUser,deps:t});if(e?.kind==="deny")return rememberSensitiveAccessDenial(e,i,a,t),t.logger?.info?.(`[BrokeredShell] phase=ipc-sensitive-open | runtime=bash | result=deny | reason=${e.code}`),"DENY"}let h=[],p=createFileTokenStageRecorder(s,h);if("write"===n&&"deny"!==c){try{await backupBeforeBrokeredWrite(i,s,t,a,p("backup"))}catch(e){c="deny",t.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-token-backup | result=deny | reason=modify-backup-failed | error=${e?.message??e}`)}"deny"!==c&&await rememberTextWriteAutoGrant({registry:t.textWriteAutoGrantRegistry,sessionId:i,toolCallId:a,targetPath:s,deps:t,logPhase:"ipc-token-auto-grant",onResult:p("autoGrant")})}return(t.logger?.info?.(`[BrokeredShell] phase=ipc-token | operation=${n} | sessionMatch=true | toolCallId=${a?"set":"none"} | path=${s}${h.length?` | ${h.join(" | ")}`:""} | result=${c}`),"deny"===c)?"DENY":!0===d.ok&&"string"==typeof d.token&&d.token?d.token:"sandbox"===d.decision?"SANDBOX":"DENY"}function createFileTokenStageRecorder(e,t){return r=>(o,s)=>{t.push(`${o.startsWith("continue:")?`${r}Check`:r}=${o}`),s!==e&&t.push(`${r}Path=${s}`)}}function denyFileWriteCompletedRequest(e,t,r){return denyBrokeredFileRequest(e,t,r,"write-completed")}function denyBrokeredFileRequest(e,t,r,o=e.operation??"unknown"){return{...e.id?{id:e.id}:{},ok:!1,operation:o,path:t,normalisedPath:t,decision:"deny",error:r}}async function backupBeforeBrokeredWrite(e,t,r,o,s){await (0,x.Z)({paths:[t],sessionId:e,excludedPathOptions:getModifyBackupExcludedPathOptions(),logPhase:"ipc-token-backup",onResult:s,sandboxTurnConfig:r.sandboxTurnConfig,sandboxLifecycle:r.sandboxLifecycle,sandboxCenterClient:r.sandboxCenterClient,logger:r.logger,isCurrentTurnCreatedPath:t=>r.textWriteAutoGrantRegistry?.hasCurrentTurnCreatedPath({sessionId:e,toolCallId:o,targetPath:t})??!1})}async function rememberTextWriteAutoGrant(e){try{await e.registry?.remember({onResult:e.onResult,sessionId:e.sessionId,toolCallId:e.toolCallId,targetPath:e.targetPath,deps:{logger:e.deps.logger,sandboxLifecycle:e.deps.sandboxLifecycle,sandboxCenterClient:e.deps.sandboxCenterClient,sessionManager:e.deps.sessionManager,sandboxTurnConfig:e.deps.sandboxTurnConfig,modifyBackupExcludedPathOptions:getModifyBackupExcludedPathOptions()}})}catch(t){e.deps.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=${e.logPhase} | result=skip | reason=remember-failed | path=${e.targetPath} | error=${t?.message??t}`)}}function getModifyBackupExcludedPathOptions(){return{homeDir:h().homedir(),codebuddyHome:R.P.getHomeDir()}}function classifyFileTokenResponse(e){return!0===e.ok&&"string"==typeof e.token&&e.token?"token":"sandbox"===e.decision?"sandbox":"deny"}function rememberSensitiveAccessDenial(e,t,r,o){"deny"===e.kind&&"sensitive_access_denied"===e.code&&r&&o.sensitiveAccessDenialRegistry?.remember(t,r)}async function authorizeBrokeredReadOpen(e){let t,{sensitiveContentMediation:r,sensitiveProtectionPolicy:o}=e.deps;if(o){try{t=await (0,v.i)(o.isEnabled({sessionId:e.sessionId,...e.deps.signal?{signal:e.deps.signal}:{}}),e.deps.signal)}catch{if(e.deps.signal?.aborted)return cancelledReadOpenDecision();e.deps.logger?.warn?.("[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-sensitive-open | result=allow | reason=policy-state-unavailable");return}if("boolean"!=typeof t)return void e.deps.logger?.warn?.("[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-sensitive-open | result=allow | reason=policy-state-invalid");if(t&&r){if(!isReadOpenRuntime(e.runtime))return{kind:"deny",code:"sensitive_open_runtime_invalid",message:"Sensitive open review requires a supported runtime."};if("string"!=typeof e.inspectionPath||!e.inspectionPath)return{kind:"deny",code:"sensitive_open_path_invalid",message:"Sensitive open review requires an inspection path."};try{let t="function"==typeof e.deps.sessionManager.get?await e.deps.sessionManager.get(e.sessionId):void 0,o=t?t.id:void 0;return await (0,v.i)(r.authorizeReadOpen({path:e.inspectionPath,runtime:e.runtime,sessionId:e.sessionId,...o?{runtimeKey:o}:{},toolCallId:e.request.toolCallId,brokerTraceId:e.request.brokerTraceId,...e.forceSensitiveDetection?{forceSensitiveDetection:!0}:{},...e.deps.signal?{signal:e.deps.signal}:{}}),e.deps.signal)}catch{if(e.deps.signal?.aborted)return cancelledReadOpenDecision();e.deps.logger?.warn?.("[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-sensitive-open | result=allow | reason=adapter-failed");return}}}}function cancelledReadOpenDecision(){return{kind:"deny",code:"sensitive_review_cancelled",message:"Sensitive content review was cancelled."}}function isReadOpenRuntime(e){return"bash"===e||"node"===e||"python"===e}async function isMissingPath(e,t){try{return await (0,n.lstat)(e),!1}catch(r){if(r?.code==="ENOENT"||r?.code==="ENOTDIR")return!0;return t.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredShell] phase=ipc-token-auto-grant | result=skip | reason=stat-failed | path=${e} | error=${r?.message??r}`),!1}}function getBrokeredTextWriteAutoGrantCandidateKey(e,t,r){return`${e}\0${t}\0${r}`}var O=r(57659);async function handleBrokeredHostOperationRequest(e,t){let r=e.brokerTraceId||"none";if(!(0,k.Y)(e.sessionId,e.toolCallId,t))return t.logger?.info?.(`[BrokeredShell] phase=ipc-host-op | operation=${e.operation??"<unknown>"} | sessionMatch=false | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | runtime=${e.runtime??"unknown"} | result=deny | reason=session-mismatch`),(0,w.H0)(e,"Brokered sandbox IPC session mismatch");let o=await t.bashSandboxManager.getConfig(),s=t.safeDeleteReportRegistry.get(e.sessionId,e.toolCallId);t.logger?.info?.(`[BrokeredShell] phase=ipc-host-op | operation=${e.operation??"<unknown>"} | sessionMatch=true | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | runtime=${e.runtime??"unknown"} | reportPath=${s?"resolved":"missing"} | result=dispatch`);let i=await (0,w.i5)({service:t.brokeredSandboxHostService,approvalCoordinator:t.approvalCoordinator,request:{...e,safeDeleteReportPath:s},orderedFileRules:o?.orderedRules?.file.rules,sandboxFilesystem:o?.filesystem});return t.logger?.info?.(`[BrokeredShell] phase=ipc-host-op-complete | operation=${e.operation??"<unknown>"} | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | runtime=${e.runtime??"unknown"} | decision=${String(i.decision??"unknown")} | ok=${String(!0===i.ok)}`),i}var P=r(51460);async function handleBrokeredIpcLine(e,t){let r;if(!e.startsWith("{"))return handleBrokeredToyboxTextLine(e,t);try{r=JSON.parse(e)}catch{return t.logger?.info?.("[BrokeredShell] phase=ipc-host-op | brokerTraceId=none | result=deny | reason=invalid-json"),{ok:!1,decision:"deny",error:"Invalid broker IPC JSON request"}}let o=r.brokerTraceId||"none";return r.command===w.yR?handleBrokeredJsonFileTokenRequest(r,t):r.command===I?handleBrokeredFileWriteCompletedRequest(r,t):r.command===P.$m?(0,P.Ad)(r,t):r.command!==w.rU?(t.logger?.info?.(`[BrokeredShell] phase=ipc-host-op | operation=${r.operation??"<unknown>"} | brokerTraceId=${o} | toolCallId=${r.toolCallId?"set":"none"} | runtime=${r.runtime??"unknown"} | result=deny | reason=unsupported-command`),(0,w.H0)(r,`Unsupported brokered host file operation: ${r.operation??"<unknown>"}`)):handleBrokeredHostOperationRequest(r,t)}let BrokeredSafeDeleteReportRegistry=class BrokeredSafeDeleteReportRegistry{constructor(){this.safeDeleteReportPaths=new Map}remember(e,t,r,o){if(o?.info?.(`[BrokeredShell] phase=report-register | sessionId=${e?"set":"none"} | toolCallId=${t?"set":"none"} | reportPath=${r?"set":"none"}`),!e||!t||!r)return;let s=this.safeDeleteReportKey(e,t);this.safeDeleteReportPaths.delete(s),this.safeDeleteReportPaths.set(s,r),this.prune(o)}get(e,t){return e&&t?this.safeDeleteReportPaths.get(this.safeDeleteReportKey(e,t)):void 0}clear(){this.safeDeleteReportPaths.clear()}safeDeleteReportKey(e,t){return`${e}\0${t}`}prune(e){for(;this.safeDeleteReportPaths.size>5e3;){let t=this.safeDeleteReportPaths.keys().next().value;if(!t)return;this.safeDeleteReportPaths.delete(t),e?.warn?.("[cbc-kw=PERMISSION] [BrokeredSandboxIpc] safe-delete report path evicted | limit=5000")}}};var __decorate=function(e,t,r,o){var s,i=arguments.length,a=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,o);else for(var n=e.length-1;n>=0;n--)(s=e[n])&&(a=(i<3?s(a):i>3?s(t,r,a):s(t,r))||a);return i>3&&a&&Object.defineProperty(t,r,a),a},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let D=Symbol("BrokeredSandboxIpcServer");function shellCallKey(e,t){return`${e}\0${t}`}let E=class{constructor(){this.sockets=new Set,this.safeDeleteReportRegistry=new BrokeredSafeDeleteReportRegistry,this.sensitiveAccessDenialRegistry=new BrokeredSensitiveAccessDenialRegistry,this.textWriteAutoGrantRegistry=new BrokeredTextWriteAutoGrantRegistry,this.programBlockRegistry=new P.jO,this.nextConnectionId=0,this.activeRequests=0,this.activeDataRequests=0,this.requestWaiters=new Set,this.activeShellCalls=new Map}registerShellCall(e,t,r){if(!t)return()=>void 0;let o=shellCallKey(e,t),s=this.activeShellCalls.get(o)??new Set;return s.add(r),this.activeShellCalls.set(o,s),()=>{s.delete(r),0===s.size&&this.activeShellCalls.get(o)===s&&this.activeShellCalls.delete(o)}}isActiveShellCall(e,t){return(0,g.W)()?!!t&&this.activeShellCalls.has(shellCallKey(e,t)):e===this.sessionManager.sessionSubject.value?.id}shellContextFor(e){let t,r;if(e.startsWith("{"))try{let o=JSON.parse(e);t=o?.sessionId,r=o?.toolCallId}catch{return}else{let o=e.split(" ");if(4!==o.length)return;[,,t,r]=o}if("string"!=typeof t||"string"!=typeof r)return;let o=this.activeShellCalls.get(shellCallKey(t,r));return o?.values().next().value}async ensureStarted(){return this.server&&this.socketPath?this.socketPath:(this.startPromise??=this.start().finally(()=>{this.startPromise=void 0}),this.startPromise)}async start(){let e=await (0,n.mkdtemp)((0,p.join)((0,c.tmpdir)(),"cbb-"));await (0,n.chmod)(e,448);let t=(0,p.join)(e,"broker.sock"),r=d().createServer(e=>{let t=`${process.pid}-${++this.nextConnectionId}`;if(this.sockets.size>=256){this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] connection rejected | connectionId=${t} | reason=connection-limit | connections=${this.sockets.size} | limit=256`),e.destroy();return}let r=new AbortController,o=Date.now(),s="peer-close",i="request=none",a=0,n=0,l="";this.sockets.add(e);let d=setTimeout(()=>{s="first-frame-timeout",e.destroy()},5e3);e.once("close",()=>{clearTimeout(d),this.sockets.delete(e),r.abort();let c=`[BrokeredSandboxIpc] connection closed | connectionId=${t} | firstFrame: ${i} | reason=${this.server?s:"server-stop"} | durationMs=${Date.now()-o} | received=${a} | responded=${n} | unfinished=${a-n}`;"first-frame-timeout"===s?this.logger?.warn?.(`[cbc-kw=PERMISSION] ${c} | bufferedBytes=${Buffer.byteLength(l,"utf8")}`):this.logger?.info?.(c)}),e.on("error",o=>{s="socket-error",this.sockets.delete(e),r.abort(),this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] socket error | connectionId=${t}: ${o?.message??o}`),e.destroy()});let c=Promise.resolve(),h=0,p=0;e.on("data",o=>{let u;for(l+=o.toString("utf8");-1!==(u=l.indexOf("\n"));){let o=l.slice(0,u),g=Buffer.byteLength(o,"utf8");if(g>1048576){s="oversized-frame",this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] socket closed | connectionId=${t} | reason=oversized-frame | limit=1048576`),e.destroy();return}let f=o.trim();if(l=l.slice(u+1),f){if(clearTimeout(d),1==++a&&(i=this.requestLogContext(f)),h>=128||p+g>1048576){s="request-backlog",this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] socket closed | connectionId=${t} | reason=request-backlog | pending=${h} | pendingBytes=${p}`),e.destroy();return}h++,p+=g,c=c.then(async()=>{!e.destroyed&&await this.writeLineResponse(e,f,r.signal)&&n++}).catch(e=>{this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] response error | connectionId=${t}: ${e?.message??e}`)}).finally(()=>{h--,p-=g})}}Buffer.byteLength(l,"utf8")>1048576&&(s="oversized-frame",this.logger?.warn?.(`[cbc-kw=PERMISSION] [BrokeredSandboxIpc] socket closed | connectionId=${t} | reason=oversized-frame | limit=1048576`),e.destroy())})});try{await new Promise((e,o)=>{r.once("error",o),r.listen(t,()=>{r.off("error",o),e()})}),await (0,n.chmod)(t,384)}catch(e){throw await this.closeServer(r).catch(()=>void 0),await this.removeSocketResources(t),e}return this.server=r,this.socketPath=t,this.logger?.info?.("[BrokeredSandboxIpc] listening | endpoint=unix-socket"),t}getSocketPath(){return this.socketPath}rememberSafeDeleteReportPath(e,t,r){this.safeDeleteReportRegistry.remember(e,t,r,this.logger)}consumeSensitiveAccessDenied(e,t){return this.sensitiveAccessDenialRegistry.consume(e,t)}async flushTextWriteAutoGrants(e,t,r){await this.textWriteAutoGrantRegistry.flush({sessionId:e,toolCallId:t,deps:r??{logger:this.logger,sandboxLifecycle:this.sandboxLifecycle,sandboxCenterClient:this.sandboxCenterClient,sessionManager:this.sessionManager}})}drainProgramBlocks(e,t){return this.programBlockRegistry.drain({sessionId:e,toolCallId:t})}async stop(){await this.startPromise?.catch(()=>void 0);let{server:e,socketPath:t}=this;for(let e of(this.server=void 0,this.socketPath=void 0,this.startPromise=void 0,this.safeDeleteReportRegistry.clear(),this.sensitiveAccessDenialRegistry.clear(),this.textWriteAutoGrantRegistry.clear(),this.programBlockRegistry.clear(),this.activeShellCalls.clear(),this.approvalCoordinator.clearSessionApprovals(),Array.from(this.sockets)))e.destroy();this.sockets.clear(),e&&await this.closeServer(e),await this.removeSocketResources(t)}async closeServer(e){await new Promise(t=>e.close(()=>t()))}async removeSocketResources(e){e&&await (0,n.rm)((0,p.dirname)(e),{recursive:!0,force:!0}).catch(()=>void 0)}requestLogContext(e){let t;if(e.startsWith("{"))try{t=JSON.parse(e)??{}}catch{return"request=invalid-json"}else{let r=e.split(" ");t={command:"toybox",sessionId:4===r.length?r[2]:void 0,toolCallId:4===r.length?r[3]:void 0}}let field=e=>"string"==typeof e?e.slice(0,128).replace(/[^a-zA-Z0-9_.:-]/g,"_"):"none";return`request=${field(t.command)} | sessionId=${field(t.sessionId)} | toolCallId=${field(t.toolCallId)}`}async writeLineResponse(e,t,r){let o,s=this.isDataRequest(t);await this.acquireRequestCapacity(s,r);try{o=await this.handleLine(t,r).catch(e=>({ok:!1,decision:"deny",error:e?.message??String(e)}))}finally{this.releaseRequestCapacity(s)}let i="string"==typeof o?o:JSON.stringify(o);return!e.destroyed&&(e.write(`${i}
|
|
2
2
|
`),!0)}acquireRequestCapacity(e,t){return this.canAdmitRequest(e)?(this.admitRequest(e),Promise.resolve()):new Promise((r,o)=>{let s={dataRequest:e,signal:t,resolve:r,onAbort:()=>{this.requestWaiters.delete(s)&&o(Error("Broker IPC request cancelled while waiting for capacity"))}};t.aborted?o(Error("Broker IPC request cancelled while waiting for capacity")):(t.addEventListener("abort",s.onAbort,{once:!0}),this.requestWaiters.add(s))})}canAdmitRequest(e){return this.activeRequests<128&&(!e||this.activeDataRequests<112)}admitRequest(e){this.activeRequests++,e&&this.activeDataRequests++}releaseRequestCapacity(e){e&&this.activeDataRequests--,this.activeRequests--,this.drainRequestWaiters()}drainRequestWaiters(){for(let e of this.requestWaiters){if(this.activeRequests>=128)return;this.canAdmitRequest(e.dataRequest)&&(this.requestWaiters.delete(e),e.signal.removeEventListener("abort",e.onAbort),this.admitRequest(e.dataRequest),e.resolve())}}isDataRequest(e){if(!e.startsWith("{"))return!0;try{let t=JSON.parse(e);return t.command===w.rU||t.command===w.yR||t.command===I}catch{return!1}}async handleLine(e,t){let dispatch=()=>handleBrokeredIpcLine(e,{logger:this.logger,signal:t,brokeredSandboxHostService:this.brokeredSandboxHostService,bashSandboxManager:this.bashSandboxManager,sandboxTurnConfig:this.sandboxTurnConfig,sandboxLifecycle:this.sandboxLifecycle,sandboxCenterClient:this.sandboxCenterClient,sessionManager:this.sessionManager,isActiveShellCall:(e,t)=>this.isActiveShellCall(e,t),settingsManager:this.settingsManager,approvalCoordinator:this.approvalCoordinator,sensitiveContentMediation:this.sensitiveContentMediation,sensitiveProtectionPolicy:this.sensitiveProtectionPolicy,safeDeleteReportRegistry:this.safeDeleteReportRegistry,sensitiveAccessDenialRegistry:this.sensitiveAccessDenialRegistry,programBlockRegistry:this.programBlockRegistry,textWriteAutoGrantRegistry:this.textWriteAutoGrantRegistry}),r=this.shellContextFor(e);return r?r(dispatch):dispatch()}};__decorate([(0,i.Autowired)(i.Logger),(0,i.Optional)(),__metadata("design:type","function"==typeof(o=void 0!==i.Logger&&i.Logger)?o:Object)],E.prototype,"logger",void 0),__decorate([(0,i.Autowired)(O.l),__metadata("design:type",Object)],E.prototype,"brokeredSandboxHostService",void 0),__decorate([(0,i.Autowired)(u.BashSandboxManager),__metadata("design:type",Object)],E.prototype,"bashSandboxManager",void 0),__decorate([(0,i.Autowired)(m.x),(0,i.Optional)(),__metadata("design:type",Object)],E.prototype,"sandboxTurnConfig",void 0),__decorate([(0,i.Autowired)(f.k),(0,i.Optional)(),__metadata("design:type",Object)],E.prototype,"sandboxLifecycle",void 0),__decorate([(0,i.Autowired)(y.SandboxCenterIpcClient),(0,i.Optional)(),__metadata("design:type",Object)],E.prototype,"sandboxCenterClient",void 0),__decorate([(0,i.Autowired)(a.SessionManager),__metadata("design:type","function"==typeof(s=void 0!==a.SessionManager&&a.SessionManager)?s:Object)],E.prototype,"sessionManager",void 0),__decorate([(0,i.Autowired)(S.yJ),(0,i.Optional)(),__metadata("design:type",Object)],E.prototype,"sensitiveContentMediation",void 0),__decorate([(0,i.Autowired)(S.iz),(0,i.Optional)(),__metadata("design:type",Object)],E.prototype,"sensitiveProtectionPolicy",void 0),__decorate([(0,i.Autowired)(_.Vr),(0,i.Optional)(),__metadata("design:type",Object)],E.prototype,"settingsManager",void 0),__decorate([(0,i.Autowired)(b.zW),__metadata("design:type",Object)],E.prototype,"approvalCoordinator",void 0),E=__decorate([(0,i.Component)(D)],E)},51460(e,t,r){r.d(t,{$m:()=>a,Ad:()=>handleBrokeredProgramPolicyRequest,jO:()=>BrokeredProgramBlockRegistry});var o=r(11581),s=r(29889),i=r(74262);let a="CheckProgramPolicy";let BrokeredProgramBlockRegistry=class BrokeredProgramBlockRegistry{constructor(){this.entries=[]}record(e,t){e.sessionId&&(this.prune(),this.entries.push({sessionId:e.sessionId,toolCallId:e.toolCallId,record:{path:t,actionMask:8,source:"brokered-sandbox",options:[],reason:o.yE,command:t,raw:{operation:"process-exec",runtime:e.runtime??"brokered-program-policy",...e.brokerTraceId?{brokerTraceId:e.brokerTraceId}:{}}},updatedAt:Date.now()}))}drain(e){this.prune();let t=[];for(let r=this.entries.length-1;r>=0;r--){let o=this.entries[r];e.sessionId&&o.sessionId===e.sessionId&&(o.toolCallId&&o.toolCallId!==e.toolCallId||(t.unshift(o.record),this.entries.splice(r,1)))}return t}clear(){this.entries.length=0}prune(){let e=Date.now()-3e5;for(let t=this.entries.length-1;t>=0;t--)this.entries[t].updatedAt<e&&this.entries.splice(t,1)}};async function handleBrokeredProgramPolicyRequest(e,t){let r=e.brokerTraceId||"none";if(!(0,i.Y)(e.sessionId,e.toolCallId,t))return t.logger?.info?.(`[BrokeredShell] phase=ipc-program-policy | sessionMatch=false | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=session-mismatch`),{...e.id?{id:e.id}:{},ok:!1,decision:"deny",reason:"session_mismatch",error:"Brokered sandbox IPC session mismatch"};let a="string"==typeof e.program?e.program.trim():"";if(!a)return t.logger?.info?.(`[BrokeredShell] phase=ipc-program-policy | sessionMatch=true | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=missing-program`),{...e.id?{id:e.id}:{},ok:!1,decision:"deny",reason:"invalid_request",error:"Brokered program policy request requires a program"};t.settingsManager?.clearCache(s.I7.USER);let n=await t.bashSandboxManager.getConfig();return(n?.programBlacklist??[]).some(e=>e.trim()===a)?(t.programBlockRegistry.record(e,a),t.logger?.info?.(`[BrokeredShell] phase=ipc-program-policy | program=${a} | sessionMatch=true | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | result=deny | reason=forbidden_program`),{...e.id?{id:e.id}:{},ok:!1,decision:"deny",reason:o.yE,program:a,error:`Program "${a}" is blocked by the configured Program Blacklist.`}):(t.logger?.info?.(`[BrokeredShell] phase=ipc-program-policy | program=${a} | sessionMatch=true | brokerTraceId=${r} | toolCallId=${e.toolCallId?"set":"none"} | result=allow`),{...e.id?{id:e.id}:{},ok:!0,decision:"allow",program:a})}},74262(e,t,r){r.d(t,{Y:()=>matchesBrokeredSession});function matchesBrokeredSession(e,t,r){return!!e&&(r.isActiveShellCall?r.isActiveShellCall(e,t):e===r.sessionManager.sessionSubject.value?.id)}},96142(e,t,r){r.d(t,{N:()=>n,P:()=>i.isSandboxCLIConnectTimeoutError});var o,s=r(88523),i=r(84283),a=r(11581),__decorate=function(e,t,r,o){var s,i=arguments.length,a=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,o);else for(var n=e.length-1;n>=0;n--)(s=e[n])&&(a=(i<3?s(a):i>3?s(t,r,a):s(t,r))||a);return i>3&&a&&Object.defineProperty(t,r,a),a},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let n=class extends i.SandboxCliClientImpl{init(){this.setLogger(this.injectedLogger)}};__decorate([(0,s.Autowired)(s.Logger),__metadata("design:type","function"==typeof(o=void 0!==s.Logger&&s.Logger)?o:Object)],n.prototype,"injectedLogger",void 0),__decorate([(0,s.PostConstruct)(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],n.prototype,"init",null),n=__decorate([(0,s.Component)(a.b9)],n)},79733(e,t,r){r.d(t,{w:()=>g});var o,s,i=r(88523),a=r(35317),n=r(79896),l=r(69278),d=r(16928),c=r(60075),h=r(96142),p=r(15526),u=r(11581),__decorate=function(e,t,r,o){var s,i=arguments.length,a=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,o);else for(var n=e.length-1;n>=0;n--)(s=e[n])&&(a=(i<3?s(a):i>3?s(t,r,a):s(t,r))||a);return i>3&&a&&Object.defineProperty(t,r,a),a},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let g=class{constructor(){this._readyGeneration=0,this._sessionReadyCallbacks=[],this._isRestarting=!1,this._startupStage="process-start"}static{o=this}static{this.ENSURE_READY_HARD_TIMEOUT_MS=3e4}static{this.SESSION_READY_CALLBACK_TIMEOUT_MS=5e3}ensureReady(e){let t;if(this._ensureReadyPromise)return this.logger.info?.(`[SandboxLifecycle] ensureReady called, hitting cached promise (sessionId=${e.sessionId}, readyGeneration=${this._readyGeneration})`),this._ensureReadyPromise;this.logger.info?.(`[SandboxLifecycle] ensureReady first call | sessionId=${e.sessionId} | appHomeDir=${e.appHomeDir} | appGroupId=${e.appGroupId??"<none>"} | showConsoleWindow=${e.showConsoleWindow??!1}`),this._bootstrapOptions=e,this._lastReadyError=void 0,this._startupAssetFailure=void 0;let r=!1,s=new Promise((e,s)=>{t=setTimeout(()=>{r=!0,s(Error(`[SandboxLifecycle] ensureReady hard timeout after ${o.ENSURE_READY_HARD_TIMEOUT_MS}ms`))},o.ENSURE_READY_HARD_TIMEOUT_MS)});this._startupStage="process-start";let i=this._isRestarting?"restart":"bootstrap",a=Date.now(),n=this._startAndConnect();return n.catch(()=>void 0),this._ensureReadyPromise=Promise.race([n,s]).then(()=>{if(t&&clearTimeout(t),this._lastReadyError=void 0,!this._isRestarting&&this._startupAssetFailure){let e=this._startupAssetFailure;this._scheduleDaemonFailureReport(()=>({...e,...this._daemonFailureContext()}))}this._startupAssetFailure=void 0,this._scheduleDaemonStartupFinishedReport(()=>({result:"success",startType:i,durationMs:Date.now()-a,...this._daemonStartupContext(i)}))}).catch(e=>{t&&clearTimeout(t),r&&this._cleanupAfterTimeout(n);let o=this._consumeProcessStartupFailure(),s=this._startupAssetFailure??o??(r?{phase:"startup-ensure-ready-timeout",errorCode:`SANDBOX_ENSURE_READY_TIMEOUT_${this._startupStage.toUpperCase().replace("-","_")}`,errorMsg:"string"==typeof e?.message?e.message:String(e)}:this._normalizeStartupFailure(e));throw this._isRestarting||this._scheduleDaemonFailureReport(()=>({...s,...this._daemonFailureContext()})),this._scheduleDaemonStartupFinishedReport(()=>({result:"failed",startType:i,phase:"restart"===i?"runtime-restart-failed":s.phase,errorCode:s.errorCode,durationMs:Date.now()-a,...this._daemonStartupContext(i)})),this.logger.error?.(`[SandboxLifecycle] ensureReady failed, clearing cache to allow retry: ${e?.message??e}`),this._ensureReadyPromise=void 0,this._bootstrapOptions=void 0,this._lastReadyError=e instanceof Error?e:Error(String(e)),this._startupAssetFailure=void 0,e}),this._ensureReadyPromise}waitReady(){return this._ensureReadyPromise?this._ensureReadyPromise:Promise.reject(this._lastReadyError??Error("sandbox ensureReady was never called"))}async ensureAlive(){try{await this.client.ping()}catch(e){if(this.logger.info?.(`[SandboxLifecycle] ping failed: ${e.message}, attempting restart...`),this.processManager.isRunning()?this._scheduleDaemonFailureReport(()=>{let t=this.processManager.getStartedAtMs?.();return{phase:"runtime-unresponsive",errorCode:"string"==typeof e?.code&&e.code.length>0?e.code:"SANDBOX_DAEMON_PING_FAILED",errorMsg:"string"==typeof e?.message?e.message:void 0,uptimeMs:t?Date.now()-t:void 0,...this._daemonFailureContext()}}):this.logger.info?.("[SandboxLifecycle] ping failed but process already stopped; skip runtime-unresponsive (process-manager close handler will report runtime-exit)"),this._restartPromise)return this.logger.info?.("[SandboxLifecycle] restart already in-flight, awaiting existing promise"),this._restartPromise;return this._restartPromise=this._restart().finally(()=>{this._restartPromise=void 0}),this._restartPromise}}getOpenedSessionId(){return this._openedSessionId}getClient(){return this.client}getReadyGeneration(){return this._readyGeneration}async stop(){this.logger.info?.(`[SandboxLifecycle] stop called | openedSessionId=${this._openedSessionId} | readyGeneration=${this._readyGeneration}`);try{await this.client.disconnect().catch(e=>{this.logger.info?.(`[SandboxLifecycle] client.disconnect failed during stop: ${e?.message??e}`)})}finally{await this.processManager.stop().catch(e=>{this.logger.info?.(`[SandboxLifecycle] processManager.stop failed: ${e?.message??e}`)}),this._ensureReadyPromise=void 0,this._openedSessionId=void 0,this.logger.info?.("[SandboxLifecycle] stop completed, state cleared")}}onSessionReady(e){return this._sessionReadyCallbacks.push(e),()=>{let t=this._sessionReadyCallbacks.indexOf(e);t>=0&&this._sessionReadyCallbacks.splice(t,1)}}async _fireSessionReadyCallbacks(e){let t={sessionId:this._openedSessionId,generation:this._readyGeneration,reason:e};for(let e of this._sessionReadyCallbacks)try{await Promise.race([e(t),new Promise((e,t)=>setTimeout(()=>t(Error("sessionReady callback timeout")),o.SESSION_READY_CALLBACK_TIMEOUT_MS))])}catch(e){this.logger.info?.(`[SandboxLifecycle] sessionReady callback failed (continuing): ${e?.message??e}`)}}_cleanupAfterTimeout(e){e.then(async()=>{this.logger.warn?.("[SandboxLifecycle] hard timeout fired but _startAndConnect later succeeded; tearing down orphan sandbox-cli to avoid leaked process"),await this._tearDownInflight()},async()=>{this.logger.info?.("[SandboxLifecycle] hard timeout cleanup: _startAndConnect rejected; still tearing down any partially-started state"),await this._tearDownInflight()})}_daemonFailureContext(){let e=[...this.client.getPendingConversationRequestIds()];return{conversationId:this._openedSessionId??this._bootstrapOptions?.sessionId,conversationRequestId:1===e.length?e[0]:void 0}}_daemonStartupContext(e){let t=[...this.client.getPendingConversationRequestIds()];return{conversationId:this._openedSessionId??this._bootstrapOptions?.sessionId,conversationRequestId:1===t.length?t[0]:"bootstrap"===e?this._bootstrapOptions?.conversationRequestId:void 0}}_scheduleDaemonStartupFinishedReport(e){let t;try{t=e()}catch(e){this._logTelemetryFailure(`build daemon startup finished payload failed: ${e?.message??e}`);return}setImmediate(()=>{try{this.telemetryReporter?.reportDaemonStartupFinished(t)}catch(e){this._logTelemetryFailure(`reportDaemonStartupFinished failed: ${e?.message??e}`)}})}_scheduleDaemonFailureReport(e){let t;try{t=e()}catch(e){this._logTelemetryFailure(`build daemon failure payload failed: ${e?.message??e}`);return}setImmediate(()=>{try{this.telemetryReporter?.reportDaemonFailure(t)}catch(e){this._logTelemetryFailure(`reportDaemonFailure failed: ${e?.message??e}`)}})}_consumeProcessStartupFailure(){try{return this.processManager.consumeStartupFailure?.()}catch(e){this._logTelemetryFailure(`consume startup failure failed: ${e?.message??e}`);return}}_markProcessSessionEstablished(){try{this.processManager.markSessionEstablished?.()}catch(e){this._logTelemetryFailure(`mark session established failed: ${e?.message??e}`)}}_logTelemetryFailure(e){try{this.logger.info?.(`[SandboxLifecycle] ${e}`)}catch{}}_normalizeStartupFailure(e){let t=e instanceof Error?e.message:String(e);return"handshake"===this._startupStage&&((0,h.P)(e)||e?.code==="ETIMEDOUT")?{phase:"startup-handshake-timeout",errorCode:"SANDBOX_HANDSHAKE_TIMEOUT",errorMsg:t}:({helper:{phase:"startup-helper-failed",errorCode:"SANDBOX_HELPER_START_FAILED",errorMsg:t},"process-start":{phase:"startup-spawn-error",errorCode:"SANDBOX_PROCESS_START_FAILED",errorMsg:t},handshake:{phase:"startup-handshake-failed",errorCode:"SANDBOX_IPC_CONNECT_FAILED",errorMsg:t},"open-session":{phase:"startup-open-session-failed",errorCode:"SANDBOX_OPEN_SESSION_FAILED",errorMsg:t}})[this._startupStage]}async _tearDownInflight(){try{await this.client.disconnect().catch(e=>{this.logger.info?.(`[SandboxLifecycle] timeout cleanup: client.disconnect failed (ignored): ${e?.message??e}`)}),await this.processManager.stop().catch(e=>{this.logger.info?.(`[SandboxLifecycle] timeout cleanup: processManager.stop failed (ignored): ${e?.message??e}`)}),this._openedSessionId=void 0}catch(e){this.logger.warn?.(`[SandboxLifecycle] timeout cleanup unexpected error: ${e?.message??e}`)}}async _startAndConnect(){let e=this._bootstrapOptions,t=e.sessionId;this.logger.info?.(`[SandboxLifecycle] _startAndConnect called, sessionId=${t}`),"darwin"===process.platform&&e.appGroupId&&(this._startupStage="helper",await this._ensureHelperRunning(e)),this._startupStage="process-start",this.logger.info?.("[SandboxLifecycle] Starting sandbox-cli process...");let r=await this.processManager.start({appHomeDir:e.appHomeDir,appGroupId:e.appGroupId,showConsoleWindow:e.showConsoleWindow,sessionId:e.sessionId,conversationRequestId:e.conversationRequestId});this.logger.info?.(`[SandboxLifecycle] Process started, ipcAddress=${r}`),this._startupStage="handshake",this.logger.info?.("[SandboxLifecycle] Connecting client..."),await this.client.connect({sessionId:t,address:r}),this.logger.info?.("[SandboxLifecycle] Client connected successfully");let o={name:t,workingDir:process.cwd()};this.logger.info?.(`[SandboxLifecycle] Sending OpenSession request | sessionId=${t} | workingDir=${o.workingDir}`),this._startupStage="open-session";let s=await this.client.sendRequest(t,u.lV.OPEN_SESSION,o);this._markProcessSessionEstablished(),this.logger.info?.(`[SandboxLifecycle] OpenSession response | workingDir=${s?.workingDir}`),this._openedSessionId=t,this._readyGeneration++,this.logger.info?.(`[SandboxLifecycle] bootstrap done | readyGeneration=${this._readyGeneration}`),await this._fireSessionReadyCallbacks(this._isRestarting?"restart":"bootstrap")}async _restart(){let e=this._openedSessionId,t=this._readyGeneration;this.logger.info?.(`[SandboxLifecycle] _restart begin | prevOpenedSid=${e} | prevReadyGeneration=${t}`),this._isRestarting=!0;try{this.logger.info?.("[SandboxLifecycle] _restart: disconnecting client"),await this.client.disconnect().catch(e=>{this.logger.info?.(`[SandboxLifecycle] _restart: client.disconnect failed (ignored): ${e?.message??e}`)}),this.logger.info?.("[SandboxLifecycle] _restart: stopping process"),await this.processManager.stop().catch(e=>{this.logger.info?.(`[SandboxLifecycle] _restart: processManager.stop failed (ignored): ${e?.message??e}`)}),this._ensureReadyPromise=void 0,this._openedSessionId=void 0,this.logger.info?.("[SandboxLifecycle] _restart: re-invoking ensureReady with original options"),await this.ensureReady(this._bootstrapOptions),this.logger.info?.(`[SandboxLifecycle] _restart succeeded | openedSessionId=${this._openedSessionId} | readyGeneration=${this._readyGeneration} (was ${t})`)}catch(t){this.logger.error?.(`[SandboxLifecycle] _restart failed: ${t.message}`);let e=this._normalizeStartupFailure(t);throw this._scheduleDaemonFailureReport(()=>({phase:"runtime-restart-failed",errorCode:e.errorCode,errorMsg:"string"==typeof t?.message?t.message:String(t),...this._daemonFailureContext()})),Error(`sandbox-cli restart failed: ${t.message}`)}finally{this._isRestarting=!1}}async _ensureHelperRunning(e){if("darwin"!==process.platform||!e.appGroupId)return;let t=d.join(process.env.HOME||"","Library","Group Containers",e.appGroupId),r=d.join(t,"sandbox-ext.sock"),o=d.join(t,"sandbox-helper.spawn.lock"),s=this._isHealthCheckEnabled();if(s?await this._isHelperHealthy(r):await this._isSocketListening(r))return void this.logger.info?.(`[SandboxLifecycle] Helper alive (healthCheck=${s}), skipping spawn`);if(s){let e=await this._isSocketListening(r);this.logger.warn?.(`[SandboxLifecycle] Helper unresponsive (socket listen=${e}, ping=false), will respawn`)}let i=this._tryAcquireSpawnLock(o);if(null===i){this.logger.info?.("[SandboxLifecycle] Another process is spawning Helper, waiting for its socket to come up..."),await this._waitForSocketListening(r,1e4);return}try{if(s?await this._isHelperHealthy(r):await this._isSocketListening(r))return void this.logger.info?.(`[SandboxLifecycle] Helper appeared while acquiring lock (healthCheck=${s}), skipping spawn`);await this._spawnHelper(e,r)}finally{try{n.closeSync(i)}catch{}try{n.unlinkSync(o)}catch{}}}async _spawnHelper(e,t){if(n.existsSync(t)){this.logger.info?.("[SandboxLifecycle] Stale socket found, removing...");try{n.unlinkSync(t)}catch{}}let r=this._resolveHelperPath();if(!r){this.logger.warn?.("[SandboxLifecycle] WorkBuddySandboxHelper not found, skipping"),this._startupAssetFailure={phase:"startup-helper-failed",errorCode:"SANDBOX_HELPER_NOT_FOUND",errorMsg:"WorkBuddySandboxHelper binary missing from host app bundle"};return}this._ensureFrameworksLink(r);let o=this._resolveNetworkExtensionBundleId(),s=["--app-group-id",e.appGroupId,"--network-extension-bundle-id",o];this.logger.info?.(`[SandboxLifecycle] Starting WorkBuddySandboxHelper: ${r} ${s.join(" ")}`);let i=(0,a.spawn)(r,s,{stdio:["ignore","pipe","pipe"],detached:!0});i.unref();let l="";i.stderr?.on("data",e=>{for(let t of(l+=e.toString(),e.toString().trim().split("\n")))t&&this.logger.debug?.(`[SandboxHelper] ${t}`)}),i.stdout?.on("data",e=>{for(let t of e.toString().trim().split("\n"))t&&this.logger.debug?.(`[SandboxHelper:stdout] ${t}`)}),i.on("error",e=>{this.logger.error?.(`[SandboxLifecycle] Helper process error: ${e.message}`)}),i.on("close",e=>{this.logger.info?.(`[SandboxLifecycle] Helper process exited with code ${e}`),l&&0!==e&&this.logger.warn?.(`[SandboxLifecycle] Helper stderr: ${l.slice(0,500)}`)}),await this._waitForSocketListening(t,5e3)}_tryAcquireSpawnLock(e){if(n.existsSync(e))try{let t=n.readFileSync(e,"utf8").trim(),r=parseInt(t,10);if(!isNaN(r))try{return process.kill(r,0),null}catch{this.logger.info?.(`[SandboxLifecycle] Removing stale spawn lock (pid ${r} no longer alive)`);try{n.unlinkSync(e)}catch{}}}catch{try{n.unlinkSync(e)}catch{}}try{let t=n.openSync(e,"wx");return n.writeSync(t,String(process.pid)),t}catch(e){if(e?.code==="EEXIST")return null;return this.logger.warn?.(`[SandboxLifecycle] Spawn lock acquire failed unexpectedly: ${e?.message??e}`),null}}_isSocketListening(e){return new Promise(t=>{if(!n.existsSync(e))return void t(!1);let r=new l.Socket,o=!1,finish=e=>{if(!o){o=!0;try{r.destroy()}catch{}t(e)}};r.setTimeout(500),r.once("connect",()=>finish(!0)),r.once("timeout",()=>finish(!1)),r.once("error",()=>finish(!1));try{r.connect(e)}catch{finish(!1)}})}_pingHelper(e,t=500){return new Promise(r=>{let o=new l.Socket,s=!1,i="",finish=e=>{if(!s){s=!0;try{o.destroy()}catch{}r(e)}};o.setTimeout(t),o.once("timeout",()=>finish(!1)),o.once("error",()=>finish(!1)),o.once("connect",()=>{let e=JSON.stringify({sessionId:"",messageId:`lifecycle-ping-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,command:"Ping"})+"\n";try{o.write(e)}catch{finish(!1);return}}),o.on("data",e=>{let t=(i+=e.toString()).indexOf("\n");if(t<0)return;let r=i.slice(0,t);try{let e=JSON.parse(r);finish(e?.success===!0)}catch{finish(!1)}});try{o.connect(e)}catch{finish(!1)}})}async _isHelperHealthy(e){return!!await this._isSocketListening(e)&&this._pingHelper(e,500)}_isHealthCheckEnabled(){let e=process.env.SANDBOX_HELPER_HEALTHCHECK_ENABLED;return"0"!==e&&"false"!==e}async _waitForSocketListening(e,t){let r=Date.now();for(;Date.now()-r<t;){if(await this._isSocketListening(e))return void this.logger.info?.(`[SandboxLifecycle] Helper IPC server ready (waited ${Date.now()-r}ms)`);await new Promise(e=>setTimeout(e,100))}this.logger.warn?.(`[SandboxLifecycle] Helper socket not ready after ${t}ms, proceeding anyway`)}_resolveHelperPath(){let e=process.env.SANDBOX_HELPER_PATH;if(e&&n.existsSync(e))return e;let t=process.env.SANDBOX_ELECTRON_APP_PATH;if(t){let e=d.join(t,"Contents","MacOS","WorkBuddySandboxHelper");if(n.existsSync(e))return this.logger.info?.(`[SandboxLifecycle] Found Helper in host app: ${e}`),e}}_resolveNetworkExtensionBundleId(){try{let{PathUtils:e}=r(64013),t=e.getRootPathSync(),o=d.join(t,"sandbox-config.json");if(n.existsSync(o)){let e=JSON.parse(n.readFileSync(o,"utf8"));if(e.networkExtensionBundleId)return e.networkExtensionBundleId}}catch{}return"com.tencent.workbuddy.mac.NetworkExtension"}_ensureFrameworksLink(e){try{let t=d.dirname(e),r=d.join(t,"..","Frameworks"),o=d.join(r,"SandboxExt.framework");if(!n.existsSync(o)){this.logger.warn?.(`[SandboxLifecycle] SandboxExt.framework not deployed at ${o}; Helper @rpath load will fail. Check apps/workbuddy-desktop/scripts/after-pack.js step 7b.`),this._startupAssetFailure={phase:"startup-helper-failed",errorCode:"SANDBOX_FRAMEWORK_NOT_DEPLOYED",errorMsg:`SandboxExt.framework missing at ${o}`};return}this.logger.info?.(`[SandboxLifecycle] SandboxExt.framework verified at ${o}`)}catch(e){this.logger.warn?.(`[SandboxLifecycle] Failed to verify Frameworks layout: ${e.message}`)}}};__decorate([(0,i.Autowired)(u.b9),__metadata("design:type",Object)],g.prototype,"client",void 0),__decorate([(0,i.Autowired)(u.oO),__metadata("design:type",Object)],g.prototype,"processManager",void 0),__decorate([(0,i.Autowired)(i.Logger),__metadata("design:type","function"==typeof(s=void 0!==i.Logger&&i.Logger)?s:Object)],g.prototype,"logger",void 0),__decorate([(0,i.Autowired)(c.U),(0,i.Optional)(),__metadata("design:type",Object)],g.prototype,"telemetryReporter",void 0),g=o=__decorate([(0,i.Component)(p.k)],g)},93185(e,t,r){r.d(t,{Y:()=>v});var o,s=r(88523),i=r(86482),a=r(43121),n=r(34094),l=r(35317),d=r(76982),c=r(79896),h=r(16928),p=r(8410),u=r(42331),g=r(68634),f=r(49340),m=r(51376),y=r(60075),S=r(9890);let _=new Set;function registerSandboxCliPid(e){"number"==typeof e&&e>0&&_.add(e)}function unregisterSandboxCliPid(e){"number"==typeof e&&_.delete(e)}var b=r(11581),__decorate=function(e,t,r,o){var s,i=arguments.length,a=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,o);else for(var n=e.length-1;n>=0;n--)(s=e[n])&&(a=(i<3?s(a):i>3?s(t,r,a):s(t,r))||a);return i>3&&a&&Object.defineProperty(t,r,a),a},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let v=class{constructor(){this._state="idle",this._process=null,this._ipcAddress=null,this._startPromise=null,this._sessionEstablished=!1,this._exitHandler=null}init(){}async start(e){if(this.logger.info?.(`[SandboxCLI] start() called, current state=${this._state}, hasIpcAddress=${!!this._ipcAddress}`),"running"===this._state&&this._ipcAddress)return this.logger.info?.(`[SandboxCLI] Already running, returning cached address: ${this._ipcAddress}`),this._ipcAddress;if("starting"===this._state&&this._startPromise)return this.logger.info?.("[SandboxCLI] Already starting, returning existing start promise"),this._startPromise;this._state="starting",this._sessionEstablished=!1,this._startupFailure=void 0,this.logger.info?.("[SandboxCLI] State changed to starting, spawning process..."),this._startPromise=this._doStart(e);try{let e=await this._startPromise;return this._state="running",this._startedAtMs=Date.now(),this._ipcAddress=e,this.logger.info?.(`[SandboxCLI] start() succeeded, address=${e}`),this._gcOldSandboxVersions(),e}catch(e){throw this._state="stopped",this._startPromise=null,this.logger.info?.(`[SandboxCLI] start() failed: ${e.message}`),e}}markSessionEstablished(){"running"===this._state&&(this._sessionEstablished=!0)}consumeStartupFailure(){let e=this._startupFailure;return this._startupFailure=void 0,e}async stop(){let e=this._process;e&&"stopped"!==this._state&&"idle"!==this._state&&(this._state="stopped",await new Promise(t=>{let r=setTimeout(()=>{try{e.kill("SIGKILL")}catch{}t()},5e3);e.once("close",()=>{clearTimeout(r),t()});try{e.kill("SIGTERM")}catch{clearTimeout(r),t()}})),this._cleanup()}isRunning(){return"running"===this._state}getStartedAtMs(){return"running"===this._state?this._startedAtMs:void 0}_doStart(e){return new Promise((t,r)=>{let o;this._startSessionId=e?.sessionId,this._startConversationRequestId=e?.conversationRequestId;let s=this._resolveSandboxCLIPath();this._resolvedExePath=s;let i=this._generateIpcAddress(),a=this._buildStartConfig(i);this.logger.info?.(`[SandboxCLI] Starting sandbox-cli: ${s}, ipcAddress=${i}`),this.logger.debug?.(`[SandboxCLI] Config: ${JSON.stringify(a)}`);let d=["--config",JSON.stringify(a)],c=this._resolveSandboxCenterUid();d.push("--rule_decision","center"),this.logger.info?.("[SandboxCLI] rule decision backend: center"),c&&(d.push("--uid",c),this.logger.info?.("[SandboxCLI] center UID passed via --uid")),e?.appHomeDir?(d.push("--app_home",e.appHomeDir),this.logger.info?.(`[SandboxCLI] app_home: ${e.appHomeDir}`)):this.logger.info?.("[SandboxCLI] No appHomeDir provided; sandbox-cli will fall back to platform default (Windows=%LOCALAPPDATA%\\WorkBuddy, other=$HOME/.local/share/WorkBuddy)"),e?.appGroupId&&"darwin"===process.platform&&(d.push("--app_group_id",e.appGroupId),this.logger.info?.(`[SandboxCLI] app_group_id: ${e.appGroupId}`));let h=e?.showConsoleWindow??"1"===process.env.SANDBOX_CLI_SHOW_CONSOLE;h&&(d.push("--console"),this.logger.info?.("[SandboxCLI] Console window requested (--console)"));let p=(0,u.wd)();c&&(p.SANDBOX_CENTER_UID=c);let f=process.env[n.SANDBOX_CENTER_IPC_ADDRESS_ENV]?.trim();if(f?p[n.SANDBOX_CENTER_IPC_ADDRESS_ENV]=f:(0,g.cP)()?this.logger.warn?.("[SandboxCLI] SANDBOX_CENTER_IPC_ADDRESS \u672A\u6CE8\u5165\uFF08Desktop \u62D3\u6251\u5E94\u7531\u4E3B\u8FDB\u7A0B ensureSandboxCenterEpochAddress \u5728 spawn \u524D\u63D0\u4F9B\uFF09\uFF1Bdaemon \u5C06\u56DE\u9000 hash(app_home) \u5730\u5740\uFF0C\u4E0E center \u7684\u7EAA\u5143\u5730\u5740\u4E0D\u4E00\u81F4 \u2192 center \u4E0D\u53EF\u8FBE"):p[n.SANDBOX_CENTER_IPC_ADDRESS_ENV]=(0,n.consumeEpochCenterAddress)(S.P.getHomeDir(),{deriveIfMissing:!0}),p[n.SANDBOX_CENTER_IPC_ADDRESS_ENV]&&this.logger.info?.(`[SandboxCLI] center IPC address: ${p[n.SANDBOX_CENTER_IPC_ADDRESS_ENV]} (source=${f?"env":"derived"})`),a.extraPath.length>0){let e="win32"===process.platform?";":":",t=p.PATH||p.Path||"";p.PATH=a.extraPath.join(e)+e+t,this.logger.info?.(`[SandboxCLI] Injected extraPath into PATH: ${a.extraPath.join(e)}`)}process.platform;let m=Object.fromEntries(["PATH","CODEBUDDY_CODE_GIT_BASH_PATH","CODEBUDDY_CODE_PYTHON_PATH","CODEBUDDY_CODE_NODE_PATH","SANDBOX_CLI_PATH","SANDBOX_CLI_SHOW_CONSOLE",n.SANDBOX_CENTER_IPC_ADDRESS_ENV].filter(e=>void 0!==process.env[e]).map(e=>[e,process.env[e]]));this.logger.info?.(`[SandboxCLI] Spawn args: exe=${s}, args=${JSON.stringify(d)}, showConsole=${h}, hostEnv=${JSON.stringify(m)}`);try{o=(0,l.spawn)(s,d,{stdio:["ignore","ignore","ignore"],env:p,windowsHide:!h,detached:h})}catch(e){this._startupFailure={phase:e?.code==="ENOENT"?"startup-cli-not-found":"startup-spawn-error",errorCode:"string"==typeof e?.code&&e.code?`SANDBOX_SPAWN_${e.code}`:"SANDBOX_SPAWN_THROW",errorMsg:`Failed to spawn sandbox-cli: ${e.message}`},r(Error(this._startupFailure.errorMsg));return}this._process=o;let y=!1;o.on("error",e=>{y?this.logger.info?.(`[SandboxCLI] Process error after startup: ${e.message}`):(y=!0,this._startupFailure={phase:e?.code==="ENOENT"?"startup-cli-not-found":"startup-spawn-error",errorCode:"string"==typeof e?.code&&e.code?`SANDBOX_SPAWN_${e.code}`:"SANDBOX_SPAWN_ERROR",errorMsg:`sandbox-cli process error: ${e.message}`},r(Error(this._startupFailure.errorMsg)))}),o.on("close",(e,t)=>{if(y){this.logger.info?.(`[SandboxCLI] Process exited with code ${e}, signal=${t??"null"}`),o.pid&&unregisterSandboxCliPid(o.pid);let r=this._sessionEstablished&&"stopped"!==this._state&&"idle"!==this._state?this._buildDaemonFailurePayloadSafely(()=>({phase:"runtime-exit",errorCode:`SANDBOX_DAEMON_CRASH_EXIT_${e??"NULL"}`,exitCode:e,signal:t??void 0,uptimeMs:this._startedAtMs?Date.now()-this._startedAtMs:void 0,...this._daemonFailureContext()})):void 0;this._sessionEstablished||(this._startupFailure={phase:"startup-window-exit",errorCode:`SANDBOX_STARTUP_EXIT_${e??"NULL"}`,errorMsg:`sandbox-cli exited before OpenSession was established (code: ${e}, signal: ${t??"null"})`,exitCode:e,signal:t??void 0}),this._startedAtMs=void 0,this._sessionEstablished=!1,this._state="stopped",r&&this._scheduleDaemonFailureReport(r);return}y=!0,o.pid&&unregisterSandboxCliPid(o.pid),this._startupFailure={phase:"startup-window-exit",errorCode:`SANDBOX_SPAWN_FAILED_EXIT_${e??"NULL"}`,errorMsg:`sandbox-cli exited unexpectedly during startup (code: ${e}, signal: ${t??"null"})`,exitCode:e,signal:t??void 0},r(Error(this._startupFailure.errorMsg))}),setTimeout(()=>{y||(y=!0,registerSandboxCliPid(o.pid),this._exitHandler=()=>{if(this._process){unregisterSandboxCliPid(this._process.pid);try{this._process.kill("SIGKILL")}catch{}}},process.on("exit",this._exitHandler),this.logger.info?.(`[SandboxCLI] Process alive after 500ms, ipcAddress=${i}`),t(i))},500)})}_resolveSandboxCenterUid(){let e=(0,f.l2)()?.uid;if(e)return e;try{let e=s.ContainerUtil.get(i.AuthenticationManager),t=e.currentSessionSubject.getValue()?.account?.uid?.trim();if(t)return t}catch{}return process.env.SANDBOX_CENTER_UID?.trim()||void 0}_resolveSandboxCLIPath(){let e="win32"===process.platform?"sandbox-cli.exe":"sandbox-cli",t=[],r=process.env.SANDBOX_CLI_PATH;if(r)return this.logger.info?.(`[SandboxCLI] Using SANDBOX_CLI_PATH: ${r}`),r;if(S.P.isBunCompiled()){let r=h.dirname(process.execPath),o=h.join(r,"vendor","sandbox"),s=this._resolveFromVersionedDir(o,e,t);if(s)return s;let i=h.join(o,e);if(t.push(i),c.existsSync(i))return this.logger.info?.(`[SandboxCLI] resolved via execPath vendor/sandbox/ (flat): ${i}`),i;let a=`sandbox-cli binary not found for ${process.platform}-${process.arch}. Tried: ${t.join(", ")}`;throw this._startupFailure={phase:"startup-cli-not-found",errorCode:"SANDBOX_CLI_NOT_FOUND",errorMsg:a},Error(a)}let o=S.P.getRootPathSync(),s=h.join(o,"vendor","sandbox"),i=this._readSandboxVersionFromPackageJson(o);if(i){let r=h.join(s,i,e);if(t.push(r),c.existsSync(r))return this.logger.info?.(`[SandboxCLI] resolved via vendor/sandbox/${i}/: ${r}`),r}let n=this._resolveFromVersionedDir(s,e,t);if(n)return n;let l=h.join(s,e);if(t.push(l),c.existsSync(l))return this.logger.info?.(`[SandboxCLI] resolved via vendor/sandbox/ (flat, legacy): ${l}`),l;let d=(0,a.getSandboxCliPath)(__dirname);if(d)return t.push(d),this.logger.info?.(`[SandboxCLI] resolved via @tencent-ai/sandbox-cli-<os>-<arch> platform pkg: ${d}`),d;let p=(0,a.getExpectedSandboxCliPath)(__dirname);p&&t.push(p);let u=`sandbox-cli binary not found for ${process.platform}-${process.arch}. Tried: ${t.join(", ")}`;throw this._startupFailure={phase:"startup-cli-not-found",errorCode:"SANDBOX_CLI_NOT_FOUND",errorMsg:u},Error(u)}_readSandboxVersionFromPackageJson(e){try{let t=h.join(e,"package.json");if(!c.existsSync(t))return;let r=JSON.parse(c.readFileSync(t,"utf-8")).optionalDependencies;if(!r)return;return r[`@tencent-ai/sandbox-cli-${process.platform}-${process.arch}`]||void 0}catch{return}}_resolveFromVersionedDir(e,t,r){try{if(!c.existsSync(e))return;let o=c.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(0,p.valid)(e.name)).map(e=>e.name);if(0===o.length)return;for(let s of(o.sort(p.rcompare),o)){let o=h.join(e,s,t);if(r.push(o),c.existsSync(o))return this.logger.info?.(`[SandboxCLI] resolved via vendor/sandbox/${s}/ (scanned): ${o}`),o}}catch{}}_gcOldSandboxVersions(){try{let e=S.P.isBunCompiled()?h.dirname(process.execPath):S.P.getRootPathSync(),t=h.join(e,"vendor","sandbox");if(!c.existsSync(t))return void this.logger.info?.("[SandboxCLI] GC: sandbox dir not found, skipped");let r=this._inferCurrentSandboxVersion(t);if(!r)return void this.logger.info?.("[SandboxCLI] GC: cannot determine current version, skipping to avoid self-deletion");let o=c.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(0,p.valid)(e.name));if(o.length<=1)return void this.logger.info?.(`[SandboxCLI] GC: ${o.length} version dir(s) found, nothing to collect`);this.logger.info?.(`[SandboxCLI] GC: found ${o.length} version dirs, current=${r}`);let s=0;for(let e of o){if(r&&e.name===r)continue;let o=h.join(t,e.name);try{c.rmSync(o,{recursive:!0,force:!0,maxRetries:3,retryDelay:100}),s++,this.logger.info?.(`[SandboxCLI] GC: removed old sandbox version directory: ${e.name}`)}catch(t){this.logger.info?.(`[SandboxCLI] GC: failed to remove ${e.name}: ${t.message}`)}}this.logger.info?.(`[SandboxCLI] GC: done, removed ${s}/${o.length} version dir(s)`)}catch(e){this.logger.info?.(`[SandboxCLI] GC: scan failed: ${e.message}`)}}_inferCurrentSandboxVersion(e){let t=h.resolve(e);if(this._resolvedExePath){let e=this._extractVersionFromExePath(this._resolvedExePath,t);if(e)return e}if(S.P.isBunCompiled()){let e=this._extractVersionFromExePath(process.execPath,t);return e||void 0}return this._readSandboxVersionFromPackageJson(S.P.getRootPathSync())}_extractVersionFromExePath(e,t){let r=h.dirname(h.resolve(e)),o=h.relative(t,r);if(!(!o||o.includes(h.sep)||o.startsWith("..")))return o=o.normalize("NFC"),"win32"===process.platform&&(o=o.toLowerCase()),(0,p.valid)(o)?o:void 0}_generateIpcAddress(){let e=d.randomBytes(8).toString("hex");return`WorkBuddy_${e}`}_buildStartConfig(e){let t=S.P.getRootPathSync(),r=[h.join(t,"bin","runtime","git","bin")];if((0,m.uF)())try{let e=(0,m.vg)();if("bash"===e.shell&&e.executable){let t=h.dirname(e.executable);r.includes(t)||r.push(t)}}catch{}return{extraPath:r,enableGlobalProjection:!1,ipcAddress:e}}_cleanup(){this._exitHandler&&(process.removeListener("exit",this._exitHandler),this._exitHandler=null),this._process?.pid&&unregisterSandboxCliPid(this._process.pid),this._process=null,this._ipcAddress=null,this._startPromise=null,this._state="idle",this._startedAtMs=void 0,this._sessionEstablished=!1,this._startupFailure=void 0,this._resolvedExePath=void 0,this._startSessionId=void 0,this._startConversationRequestId=void 0}_daemonFailureContext(){return{conversationId:this._startSessionId,conversationRequestId:this._startConversationRequestId}}_buildDaemonFailurePayloadSafely(e){try{return e()}catch(e){this._logTelemetryFailure(`build daemon failure payload failed: ${e?.message??e}`);return}}_scheduleDaemonFailureReport(e){setImmediate(()=>{try{this.telemetryReporter?.reportDaemonFailure(e)}catch(e){this._logTelemetryFailure(`reportDaemonFailure failed: ${e?.message??e}`)}})}_logTelemetryFailure(e){try{this.logger.info?.(`[SandboxCLI] ${e}`)}catch{}}};__decorate([(0,s.Autowired)(s.Logger),__metadata("design:type","function"==typeof(o=void 0!==s.Logger&&s.Logger)?o:Object)],v.prototype,"logger",void 0),__decorate([(0,s.Autowired)(y.U),(0,s.Optional)(),__metadata("design:type",Object)],v.prototype,"telemetryReporter",void 0),__decorate([(0,s.PostConstruct)(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],v.prototype,"init",null),v=__decorate([(0,s.Component)(b.oO)],v)},80023(e,t,r){r.d(t,{v:()=>et});var o,s,i,a,n,l=r(16698),d=r(88523),c=r(21215),h=r(79814),p=r(34094),u=r(76982),g=r(79896),f=r.n(g),m=r(70857),y=r.n(m),S=r(16928),_=r.n(S),b=r(89865),v=r(43391),R=r(94442),C=r(572),w=r(35550),x=r(57659),k=r(91168),I=r(51460),O=r(26743);r(36020);var P=r(32649),D=r(68634),E=r(737),$=r(22844),A=r(845),B=r(48073),T=r(19847),L=r(56589),M=r(51376),N=r(60075),H=r(3177),F=r(62925),q=r(29949),j=r(89390),U=r(68390),W=r(17874),G=r(97866),X=r(15526),Y=r(11581),V=r(66939),K=r(98718),z=r(26258),J=r(8401),__decorate=function(e,t,r,o){var s,i=arguments.length,a=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,o);else for(var n=e.length-1;n>=0;n--)(s=e[n])&&(a=(i<3?s(a):i>3?s(t,r,a):s(t,r))||a);return i>3&&a&&Object.defineProperty(t,r,a),a},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};function shouldUseSandboxPty(e,t=process.platform){return!e.directCommand&&"linux"!==t&&(e.usePty??!1)}let Z=["com.workbuddy.sandbox.read","com.workbuddy.sandbox.read-write"],Q="codebuddy-shell-payload-",ee=!1;function sweepStaleWindowsBashPayloads(){if(!ee){ee=!0;try{let e=Date.now()-864e5;for(let t of f().readdirSync(y().tmpdir(),{withFileTypes:!0})){if(!t.isDirectory()||!t.name.startsWith(Q))continue;let r=_().join(y().tmpdir(),t.name);f().statSync(r).mtimeMs<e&&f().rmSync(r,{recursive:!0,force:!0})}}catch{}}}function stageWindowsBashScript(e,t,r){sweepStaleWindowsBashPayloads();let o=f().mkdtempSync(_().join(y().tmpdir(),`${Q}${process.pid}-`)),s=_().join(o,"script.sh");try{f().writeFileSync(s,r,{encoding:"utf8",flag:"wx",mode:384})}catch(e){try{f().rmSync(o,{recursive:!0,force:!0})}catch{}throw e}let i=!1;return{args:[...e,'__codebuddy_payload=$1; shift; __codebuddy_script=$(<"$__codebuddy_payload") || exit 125; unset __codebuddy_payload; eval "$__codebuddy_script"',t,(0,M._V)(s)],cleanup:()=>{i||(f().rmSync(o,{recursive:!0,force:!0}),i=!0)}}}function deltaTypeToNetworkAction(e){return"inherit_user"===e?"allow":"deny"}function deltaTypeToFileAction(e){return"inherit_user"===e?W.Ax:W.bl}function normalizeFileBlockPath(e){if(/^[a-z]:[/\\]|^\\\\/i.test(e))return _().win32.normalize(e).replace(/\\/g,"/").toLowerCase();let t=_().posix.normalize(e);return/^\/private\/(tmp|var|etc)(\/|$)/.test(t)?t.slice(8):t}function mergeBrokeredPromptBlocks(e,t){let r=[...e.decisionRecords??[]],o=[...e.fileBlockRecords??[]];for(let e of t){let t=e[C.vw],s=o.findIndex(t=>"decision_record"===t.source&&t.actionMask===e.actionMask&&t.options.length>0==e.options.length>0&&normalizeFileBlockPath(t.path)===normalizeFileBlockPath(e.path));if(s>=0){o[s]=e;continue}o.push(e);let i=t?.detectionId!==void 0&&r.some(e=>e.detectionId===t.detectionId);t&&!i&&r.push(t)}e.fileBlockRecords=o,e.decisionRecords=r;let s=[],i=new Set;for(let r of[...e.sandboxBlockedPaths??[],...t.map(e=>e.path)]){let e=normalizeFileBlockPath(r);i.has(e)||(i.add(e),s.push(r))}e.sandboxBlockedPaths=s}let et=class{constructor(){this.activeHandles=new Set,this.processHandles=new Map,this.stagedScriptCleanups=new Set,this._reverseHandlerRegistered=!1}static{o=this}init(){this._registerReverseHandlers()}_registerReverseHandlers(){if(this._reverseHandlerRegistered)return;let e=this.lifecycle.getClient(),t=[Y.lV.PROCESS_OUTPUT,Y.lV.PROCESS_EXIT,Y.lV.REPORT_EVENT];(0,P.e5)()&&t.push(w.rU),e.addReverseListener({commands:t},e=>this._handleReverseRequest(e)),e.onDisconnect(()=>this._failAllProcessHandles("sandbox-cli connection lost")),this._reverseHandlerRegistered=!0,this.logger.info?.("[SandboxShell] reverse handler registered")}async _ensureBrokerIpcServer(){if("darwin"===process.platform&&(0,P.e5)())try{await this.brokeredSandboxIpcServer.ensureStarted()}catch(e){this.logger.info?.(`[SandboxShell] broker IPC server start failed (continuing): ${e.message}`)}}formatCommand(e,t,r){if("powershell"===t)return e.trim();let o=[];if(r)for(let[e,t]of Object.entries(r)){let r=t.replace(/'/g,"'\\''");o.push(`export ${e}='${r}'`)}return(0,T.L)({command:e,shell:t,initialParts:o,normalizeCommand:T.y,onEnvFileReadError:(e,t)=>this.logger.info?.(`[SandboxShell] Failed to read ENV_FILE ${e}: ${t}`)})}buildSandboxCommand(e,t={enabled:!0,bulkThreshold:A.Pt}){let r,o,s=this._withDefaultSandboxEnv(e.env,t,e.toolCallId,e.session),{executable:i,argsPrefix:a,shell:n}=this._resolveSandboxShellConfiguration(s,(0,M.vg)());if("bash"===n||"zsh"===n){for(let e of(r={},["NODE_OPTIONS","PYTHONPATH","PYTHONDONTWRITEBYTECODE","PYTHONIOENCODING","PYTHONUTF8","GENIE_TRASH_DIR","CODEBUDDY_SESSION_ID","CODEBUDDY_TOOL_CALL_ID","CODEBUDDY_CONVERSATION_REQUEST_ID","CODEBUDDY_CONVERSATION_MESSAGE_ID","TRACEPARENT","TRACESTATE","BAGGAGE","CODEBUDDY_MCP_CONFIG","CODEBUDDY_SERVICE_PROXY_URL","WORKBUDDY_CONFIG_DIR","CODEBUDDY_SAFE_DELETE_SANDBOX","CODEBUDDY_SAFE_DELETE_BIN_DIR","CODEBUDDY_SAFE_DELETE_BULK_GUARD","CODEBUDDY_SAFE_DELETE_BULK_STATE_DIR","CODEBUDDY_SAFE_DELETE_BULK_THRESHOLD","CODEBUDDY_SAFE_DELETE_BROKER_DELETE","CODEBUDDY_SANDBOX_BROKER_IPC_ADDRESS","CODEBUDDY_SANDBOX_BROKER_SESSION_ID","CODEBUDDY_SANDBOX_BROKER_TOOL_CALL_ID","CODEBUDDY_SANDBOX_BROKER_TRACE_ID","CODEBUDDY_SANDBOX_HOST_FILE_OPERATION_COMMAND","CODEBUDDY_SANDBOX_PROGRAM_POLICY_COMMAND","CODEBUDDY_TOYBOX_BIN","CODEBUDDY_TOYBOX_SANDBOX_PROFILE","CODEBUDDY_BROKERED_BIN_DIR","TOYBOX_SANDBOX_SOCK","CODEBUDDY_NODE_BIN","CODEBUDDY_NODE_RUN_AS_NODE",A.Th,F.i7,"BASH_ENV","TEMP","TMP","TMPDIR"]))s[e]&&(r[e]=s[e]);Object.assign(r,L.S)}let l=this.formatCommand(e.command,n,r),d=(0,M.D$)(l,n),c="win32"===process.platform&&"bash"===n?stageWindowsBashScript(a,i,d):{args:[...a,d],cleanup:void 0},{args:h}=c;if((0,M.uF)()&&"bash"===n){o=_().dirname(i);let e=(s.PATH??s.Path??process.env.PATH??"").split(";").filter(Boolean),t=_().resolve(o,"..","usr","bin"),r=[o];for(let o of(f().existsSync(_().join(t,"bash.exe"))&&r.push(t),r))e.some(e=>_().win32.normalize(e).toLowerCase()===_().win32.normalize(o).toLowerCase())||e.push(o);for(let e of Object.keys(s))"PATH"!==e&&"PATH"===e.toUpperCase()&&delete s[e];s.PATH=e.join(";")}return this.logger.info?.(`[SandboxShell] buildSandboxCommand | original="${e.command?.slice(0,100)}" | executable=${i} | argc=${h.length} | pathOverride=${o??"none"} | brokeredShell=${"zsh"===n&&!!s.CODEBUDDY_SANDBOX_BROKER_IPC_ADDRESS} | brokerIpc=${s.CODEBUDDY_SANDBOX_BROKER_IPC_ADDRESS?"set":"none"} | brokerTrace=${s.CODEBUDDY_SANDBOX_BROKER_TRACE_ID?"set":"none"} | brokeredBin=${s.CODEBUDDY_BROKERED_BIN_DIR?"set":"none"} | toybox=${s.CODEBUDDY_TOYBOX_BIN?"set":"none"} | sandboxExtensions=${this._resolveSandboxExtensionClasses(s)?.length??0}`),{executable:i,args:h,displayCommand:e.command,pathOverride:o,env:s,cleanup:c.cleanup}}_trackStagedScriptCleanup(e){if(!e)return;let t=!1,release=()=>{if(!t)try{e(),t=!0,this.stagedScriptCleanups.delete(release)}catch(e){this.logger.info?.(`[SandboxShell] staged script cleanup failed: ${e}`)}};return this.stagedScriptCleanups.add(release),release}_bindStagedScriptCleanup(e,t,r){if(!t)return;e.onExit(t);let o=e.kill.bind(e);e.kill=async e=>{try{await o(e)}finally{t()}},r?.aborted&&t()}_resolveSandboxShellConfiguration(e,t){return"darwin"===process.platform&&e.CODEBUDDY_SANDBOX_ZSH_BIN&&e.CODEBUDDY_SANDBOX_BROKER_IPC_ADDRESS?{executable:e.CODEBUDDY_SANDBOX_ZSH_BIN,argsPrefix:["-f","-c"],shell:"zsh"}:t}_withDefaultSandboxEnv(e,t={enabled:!0,bulkThreshold:A.Pt},r,o){let s=o??this.sessionManager.sessionSubject.value,i=(0,L.u)(e,{safeDeleteEnabled:t.enabled,sessionId:this.lifecycle.getOpenedSessionId(),conversationRequestId:s?.conversationRequestId,toolCallId:r,bulkThreshold:t.bulkThreshold,brokerIpcAddress:this.brokeredSandboxIpcServer.getSocketPath(),brokerTraceId:`broker-${(0,u.randomUUID)()}`,brokerHostFileOperationCommand:w.rU,brokerFileTokenOperationCommand:w.yR,brokerProgramPolicyCommand:I.$m}),a={...(0,M.E5)(process.platform,{...process.env,...i}),PYTHONDONTWRITEBYTECODE:"1",PYTHONIOENCODING:"utf-8",PYTHONUTF8:"1",NO_UPDATE_NOTIFIER:"1",AGENT_BROWSER_ARGS:"--no-sandbox",PLAYWRIGHT_MCP_NO_SANDBOX:"1",BROWSER_USE_CHROMIUM_SANDBOX:"false",IN_DOCKER:"1"};if(t.enabled&&(a.CODEBUDDY_SAFE_DELETE_SANDBOX="1"),(0,M.uF)()){let e=y().tmpdir();a.TEMP=e,a.TMP=e,a.TMPDIR=e}let n=(0,M._V)(this.workspace?.workspaceFolders?.[0]?.uri?.fsPath||process.cwd()),l=(0,H.Pz)({baseEnv:process.env,env:{...i,...a},projectDir:n,session:s});return l.NODE_OPTIONS=(0,R.fl)(i.NODE_OPTIONS),(0,A.MH)(this.logger,"sandbox-default-env",l,t.enabled),l}async execute(e){e.abortSignal?.throwIfAborted(),await (0,q.t7)();try{let t=await this.bashSandboxManager?.getConfig();if(!(0,D.cP)()&&t?.excludedCommands?.length){let r=this._getCommandRoot(e.command);if(r&&t.excludedCommands.includes(r))return this.logger.info?.(`[SandboxShell] Command excluded from sandbox: ${r}, falling back to local`),this.localShellService.execute(e)}}catch(e){this.logger.info?.(`[SandboxShell] Failed to check excluded commands: ${e.message}`)}let t=Date.now(),r=this.workspace.workspaceFolders?.[0]?.uri?.fsPath||process.cwd(),o=_().resolve(r,e.cwd||"");if(this.logger.info?.(`[SandboxShell] execute | cmd="${e.command?.slice(0,200)}" | cwd="${o}" | timeout=${e.timeout??"none"}`),!this.isValidDirectory(o))throw this.logger.info?.(`[SandboxShell] invalid cwd: ${o}`),Error(`Working directory does not exist or is not accessible: ${o}`);try{await this.lifecycle.waitReady(),await this.lifecycle.ensureAlive()}catch(t){return e.abortSignal?.throwIfAborted(),this.logger.warn?.(`[SandboxShell] sandbox not ready, falling back to local execution: ${t?.message??t}`),this.localShellService.execute(e)}let s=this.lifecycle.getOpenedSessionId();if(e.abortSignal?.throwIfAborted(),!s)return this.logger.warn?.("[SandboxShell] no opened sandbox session, falling back to local execution"),this.localShellService.execute(e);await this.sandboxRuleSyncService?.ensureFileApprovalRulesSettled(s),await this.syncThreatDatabaseBeforeExecute(s),await this._ensureBrokerIpcServer();let i=await (0,A.Xb)(this.settingsManager,this.logger,"SandboxShell"),a=this.brokeredSandboxIpcServer.registerShellCall(s,e.toolCallId,l.AsyncLocalStorage.snapshot());try{e.abortSignal?.throwIfAborted();let r=await this._createHandle(e,o,s,t,i);return r.onExit(a),r.isAlive||a(),r}catch(e){throw a(),e}}async syncThreatDatabaseBeforeExecute(e){if(!this.threatDomainChecker)return;let t=this.sessionManager.sessionSubject.value;try{await this.threatDomainChecker.syncReady({sessionId:t?.id??e,conversationRequestId:t?.conversationRequestId})}catch(e){this.logger.warn?.(`[SandboxShell] threat DB pre-execution sync failed and was ignored: ${e instanceof Error?e.message:String(e)}`)}}async _createHandle(e,t,r,o,s){let i,a=shouldUseSandboxPty(e);try{i=a?await this.createPtyHandle(e,t,r,s):await this.createPipeHandle(e,t,r,s)}catch(r){let e=r?.message??String(r),t=e.match(/SandboxError\(0x([0-9a-fA-F]+)\)/);if(t){let r=5===parseInt(t[1],16)?"executable not found in sandbox PATH, not a permission issue":`sandbox creation failed (code 0x${t[1]})`;throw Error(`[SandboxError] ${r}. Original: ${e}`)}throw r}this.logger.info?.(`[SandboxShell] execute OK | pid=${i.pid} | mode=Pipe | elapsed=${Date.now()-o}ms`),this.activeHandles.add(i),i.onExit(()=>{this.activeHandles.delete(i)});let n=i.wait.bind(i),l=this;return i.wait=async function(){let t=await n(),o=l.brokeredSandboxIpcServer.drainProgramBlocks?.(r,e.toolCallId)??[];o.length>0&&(t.fileBlockRecords=[...t.fileBlockRecords??[],...o],l.logger.info?.(`[BrokeredShell] phase=program-block-attach | count=${o.length} | sessionId=${r} | toolCallId=${e.toolCallId?"set":"none"}`)),l._enrichResult(t);let s=l.approvalCoordinator.drainPromptBlocks({sessionId:r,toolCallId:e.toolCallId});s.length>0&&(mergeBrokeredPromptBlocks(t,s),t.sandboxDenied=!0,l.logger.info?.(`[BrokeredShell] phase=prompt-block-attach | count=${s.length} | sessionId=${r} | toolCallId=${e.toolCallId?"set":"none"}`)),l.brokeredSandboxIpcServer.consumeSensitiveAccessDenied?.(r,e.toolCallId)&&(t.sandboxDenied=!0,t.sandboxEscalationDenied=!0),0===t.exitCode&&e.toolCallId&&await l.brokeredSandboxIpcServer.flushTextWriteAutoGrants(r,e.toolCallId,{logger:l.logger,sandboxLifecycle:l.lifecycle,sandboxCenterClient:l.sandboxCenterClient,sessionManager:l.sessionManager});let a=(0,A.n$)(t,i.safeDeleteReportPath,l.logger);return l.logger.info?.(`[BrokeredShell] phase=report-attach | reportPath=${i.safeDeleteReportPath?"set":"none"} | safeDeleteEvents=${a.safeDeleteEvents?.length??0}`),a},i}async createPtyHandle(e,t,r,o){let s,i,a,n=e.cols||process.stdout.columns||80,l=e.rows||process.stdout.rows||30,d=e.rawCommand?(a=(0,M.Du)(e.command),this._needsSafeDeleteShellWrap(a.exe)?(this.logger.info?.(`[SandboxShell] safe-delete wrap (pty) | exe=${a.exe} \u{2192} routing through bash shell`),this.buildSandboxCommand(e,o)):{executable:a.exe,args:a.args,displayCommand:e.command,pathOverride:void 0,env:this._withDefaultSandboxEnv(e.env,o,e.toolCallId,e.session)}):this.buildSandboxCommand(e,o),{executable:c,args:h,displayCommand:p,pathOverride:u,env:g}=d,f=this._trackStagedScriptCleanup("cleanup"in d?d.cleanup:void 0),m=g?.[A.Th],y=g?.CODEBUDDY_SANDBOX_BROKER_TRACE_ID;this.brokeredSandboxIpcServer.rememberSafeDeleteReportPath(r,e.toolCallId,m),this.logger.info?.(`[BrokeredShell] phase=report-register | mode=pty | sessionId=${r?"set":"none"} | toolCallId=${e.toolCallId?"set":"none"} | reportPath=${m?"set":"none"}`);let S={executable:c,args:h,displayCommand:p,cwdDir:t,timeoutMs:e.timeout,executionMode:"sandbox",env:g,stdoutMode:"pty",stdinMode:"pipe",cols:n,rows:l,pathOverride:u,sandboxExtensionClasses:this._resolveSandboxExtensionClasses(g),killProcessTree:!0},_=this.lifecycle.getClient();try{e.abortSignal?.throwIfAborted(),await (0,j.R)(),e.abortSignal?.throwIfAborted(),s=await _.sendRequest(r,Y.lV.RUN_EXECUTABLE,S,{onResponse:t=>{t?.processId&&((i=new V.ZI({processId:t.processId,pid:t.pid,command:e.command,client:_,sessionId:r,cols:n,rows:l,onOutput:e.onOutput,logger:this.logger,abortSignal:e.abortSignal,timeout:e.timeout})).safeDeleteReportPath=m,i.brokerTraceId=y,this.processHandles.set(t.processId,i),this._bindStagedScriptCleanup(i,f,e.abortSignal),i.onExit(()=>{this.processHandles.delete(t.processId)}))}})}catch(e){throw f?.(),e}if(this.logger.info?.(`[SandboxShell] RunExecutable pty response | processId=${s?.processId} | pid=${s?.pid}`),!i){let e=JSON.stringify(s??null).slice(0,500);throw f?.(),Error(`[SandboxError] sandbox-cli returned invalid PTY response. Raw: ${e}`)}return i}static{this.SAFE_DELETE_COMMANDS=new Set(["rm","unlink","rmdir"])}_needsSafeDeleteShellWrap(e){return!!(0,M.uF)()&&!!e&&o.SAFE_DELETE_COMMANDS.has(e)}_resolveSandboxExtensionClasses(e){return"darwin"===process.platform&&e?.CODEBUDDY_TOYBOX_BIN?[...Z]:void 0}async createPipeHandle(e,t,r,o){let s,i,a;if(e.directCommand)s={executable:e.directCommand.executable,args:[...e.directCommand.args],displayCommand:e.directCommand.displayCommand??e.command,pathOverride:e.directCommand.pathOverride,env:this._withDefaultSandboxEnv(e.env,o,e.toolCallId,e.session)};else if(e.rawCommand){let t=(0,M.Du)(e.command);this._needsSafeDeleteShellWrap(t.exe)?(this.logger.info?.(`[SandboxShell] safe-delete wrap | exe=${t.exe} \u{2192} routing through bash shell`),s=this.buildSandboxCommand(e,o)):s={executable:t.exe,args:t.args,displayCommand:e.command,pathOverride:void 0,env:this._withDefaultSandboxEnv(e.env,o,e.toolCallId,e.session)}}else s=this.buildSandboxCommand(e,o);let{executable:n,args:l,displayCommand:d,pathOverride:c,env:h}=s,p=this._trackStagedScriptCleanup(s.cleanup),u=h?.[A.Th],g=h?.CODEBUDDY_SANDBOX_BROKER_TRACE_ID;this.brokeredSandboxIpcServer.rememberSafeDeleteReportPath(r,e.toolCallId,u),this.logger.info?.(`[BrokeredShell] phase=report-register | mode=pipe | sessionId=${r?"set":"none"} | toolCallId=${e.toolCallId?"set":"none"} | reportPath=${u?"set":"none"}`);let f={executable:n,args:l,displayCommand:d,cwdDir:t,timeoutMs:e.timeout,executionMode:"sandbox",env:h,stdoutMode:"pipe",stdinMode:"pipe",pathOverride:c,sandboxExtensionClasses:this._resolveSandboxExtensionClasses(h),killProcessTree:!0};this.logger.info?.(`[SandboxShell] RunExecutable request | mode=pipe | executionMode=${f.executionMode} | cwd=${t} | executable=${n} | argc=${l.length} | timeoutMs=${f.timeoutMs}`);let m=this.lifecycle.getClient();try{e.abortSignal?.throwIfAborted(),i=await m.sendRequest(r,Y.lV.RUN_EXECUTABLE,f,{onResponse:t=>{t?.processId&&((a=new V.a8({processId:t.processId,pid:t.pid,command:e.command,client:m,sessionId:r,onOutput:e.onOutput,logger:this.logger,abortSignal:e.abortSignal,timeout:e.timeout})).safeDeleteReportPath=u,a.brokerTraceId=g,this.processHandles.set(t.processId,a),this._bindStagedScriptCleanup(a,p,e.abortSignal),a.onExit(()=>{this.processHandles.delete(t.processId)}))}})}catch(e){throw p?.(),e}if(this.logger.info?.(`[SandboxShell] RunExecutable response | raw=${JSON.stringify(i??null).slice(0,500)}`),i&&!i.processId&&void 0!==i.exitCode){this.logger.info?.(`[SandboxShell] sync response detected | exitCode=${i.exitCode} | output=${(i.output??"").slice(0,200)}`);let t=`sync-${Date.now()}`,o=new V.a8({processId:t,pid:0,command:e.command,client:m,sessionId:r,onOutput:e.onOutput,logger:this.logger,abortSignal:e.abortSignal});o.safeDeleteReportPath=u,o.brokerTraceId=g,this._bindStagedScriptCleanup(o,p,e.abortSignal);let s=i.output??i.stdout??"",a=i.stderr??"";return s&&o.handleOutput(Buffer.from(s,"utf-8").toString("base64"),"stdout"),a&&o.handleOutput(Buffer.from(a,"utf-8").toString("base64"),"stderr"),this.auditDecisionRecords(i.decisionRecords,r),o.handleExit(i.exitCode??0,void 0,i.decisionRecords),o}if(!a){let e=JSON.stringify(i??null).slice(0,500);throw this.logger.info?.(`[SandboxShell] RunExecutable returned unexpected response (no processId, not sync) | raw=${e}`),p?.(),Error(`[SandboxError] sandbox-cli returned invalid response. Raw: ${e}`)}return this.logger.info?.(`[SandboxShell] pipe-mode response | processId=${i.processId} | pid=${i.pid}`),a}async applyRulesDelta(e){if(!this.lifecycle.getClient().isConnected())return void this.logger.info?.("[SandboxShell] applyRulesDelta: sandbox not connected, skipping");let t=this.lifecycle.getOpenedSessionId();if(!t)return void this.logger.info?.("[SandboxShell] applyRulesDelta: no opened session, skipping");let r=[];if("boolean"==typeof e.network?.maliciousDomainProtectionEnabled&&this.threatDomainChecker){let e=this.sessionManager.sessionSubject.value;await this.threatDomainChecker.syncReady({sessionId:e?.id??t,conversationRequestId:e?.conversationRequestId})}let o=(e.file?.added?.length??0)+(e.file?.removed?.length??0)>0;if(e.refresh||o&&this.sandboxRuleSyncService?.hasFileDirectoryApprovals(t)){e.refresh||this.settingsManager.clearCache(),await this.sandboxRuleSyncService?.syncRulesOnConfigRefresh(t,this.turnConfig?.permissionMode),this.logger.info?.("[SandboxShell] applyRulesDelta: full rules refreshed");return}if(await this._applyProgramRulesDelta(t,e,r),void 0!==e.networkStrictMode)try{await this.sandboxRuleSyncService?.syncNetworkStrictMode(t,!0===e.networkStrictMode)}catch(e){r.push(Error(`SET_CONFIG_NETWORK_STRICT: ${e?.message??e}`))}if(this.isFullAccessRelaxedRules()){if(this.logger.info?.(`[SandboxShell] applyRulesDelta skipped for fullAccess-relaxed | sessionId=${t} | networkAdded=${e.network?.added?.length??0} | networkRemoved=${e.network?.removed?.length??0} | fileAdded=${e.file?.added?.length??0} | fileRemoved=${e.file?.removed?.length??0}`),r.length>0)throw new Y.b$(r);return}void 0!==e.httpIntercept&&this.settingsManager.clearCache();let s=[];for(let t of e.network?.added??[])for(let e of(0,O.expandDomainWithWildcard)(t.endpoint))s.push({endpoint:e,action:deltaTypeToNetworkAction(t.type),category:"global"});s.length>0&&await this.syncCenterNetworkDelta(t,s,[]).catch(e=>r.push(Error(`CENTER_ADD_NETWORK_RULE: ${e.message}`)));let i=[];for(let t of e.network?.removed??[])i.push(...(0,O.expandDomainWithWildcard)(t.endpoint));i.length>0&&await this.syncCenterNetworkDelta(t,[],i).catch(e=>r.push(Error(`CENTER_REMOVE_NETWORK_RULE: ${e.message}`))),o&&this.settingsManager.clearCache();let a=[];for(let t of e.file?.added??[]){let e=this.sandboxRuleSyncService?.expandSecurityCenterPath(t.path)??t.path,r=this.isValidDirectory(e);a.push({path:e,action:deltaTypeToFileAction(t.type),category:"global",...r?{isDirectory:!0}:{}})}a.length>0&&await this.syncCenterFileDelta(t,a,[]).catch(e=>r.push(Error(`CENTER_ADD_FILE_RULE: ${e.message}`)));let n=[];for(let t of e.file?.removed??[])n.push(this.sandboxRuleSyncService?.expandSecurityCenterPath(t.path)??t.path);if(n.length>0&&await this.syncCenterFileDelta(t,[],n).catch(e=>r.push(Error(`CENTER_REMOVE_FILE_RULE: ${e.message}`))),o&&this.sandboxRuleSyncService?.hasFileDirectoryApprovals(t)&&await this.sandboxRuleSyncService.syncRulesOnConfigRefresh(t,this.turnConfig?.permissionMode).catch(e=>r.push(Error(`FILE_RULES_REFRESH: ${e?.message??e}`))),void 0!==e.httpIntercept)try{await this.sandboxRuleSyncService?.syncHttpIntercept(t)}catch(e){r.push(Error(`SET_HTTP_INTERCEPT: ${e?.message??e}`))}if(r.length>0)throw new Y.b$(r);this.logger.info?.("[SandboxShell] applyRulesDelta: rules synced to sandbox")}async syncCenterNetworkDelta(e,t,r){let o=this.sandboxCenterClient;if(!o)throw Error("Sandbox Center client is unavailable");if(t.length>0){let r=t.map(e=>({endpoint:e.endpoint,action:e.action}));await o.request(p.SANDBOX_RULES_COMMANDS.ADD_NETWORK_RULE,{category:"global",rules:r},{sessionId:e})}r.length>0&&await o.request(p.SANDBOX_RULES_COMMANDS.REMOVE_NETWORK_RULE,{category:"global",endpoints:r},{sessionId:e})}async syncCenterFileDelta(e,t,r){let o=this.sandboxCenterClient;if(!o)throw Error("Sandbox Center client is unavailable");if(t.length>0){let r=t.map(e=>({path:e.path,action:e.action,isDirectory:!0===e.isDirectory||this.isValidDirectory(e.path)}));await o.request(p.SANDBOX_RULES_COMMANDS.ADD_FILE_RULE,{category:"global",rules:r},{sessionId:e})}r.length>0&&await o.request(p.SANDBOX_RULES_COMMANDS.REMOVE_FILE_RULE,{category:"global",paths:r},{sessionId:e})}async _applyProgramRulesDelta(e,t,r){let o=r.length,s=(0,G.n)(t.program?.added??[]),i=(0,G.n)(t.program?.removed??[]);if(0===s.length&&0===i.length)return;let a=this.sandboxCenterClient;if(!a)return void r.push(Error(`[${e}] Sandbox Center client is unavailable`));for(let t of s){let o={program:t,category:"session"};await a.request(p.SANDBOX_RULES_COMMANDS.ADD_FORBIDDEN_PROGRAM,o,{sessionId:e}).catch(t=>r.push(Error(`[${e}] ADD_FORBIDDEN_PROGRAM: ${t.message}`)))}0===i.length||r.length!==o||await a.request(p.SANDBOX_RULES_COMMANDS.REMOVE_FORBIDDEN_PROGRAM,{programs:i,category:"session"},{sessionId:e}).catch(t=>r.push(Error(`[${e}] REMOVE_FORBIDDEN_PROGRAM: ${t.message}`)))}isFullAccessRelaxedRules(){return this.turnConfig?.ruleProfile==="fullAccess-relaxed"||this.turnConfig?.permissionMode==="fullAccess"}async disposeAll(){let e=Array.from(this.activeHandles);for(let t of(this.activeHandles.clear(),await Promise.allSettled(e.map(async e=>{try{await e.kill("SIGTERM")}catch{}try{e.dispose()}catch{}})),this.processHandles.clear(),Array.from(this.stagedScriptCleanups)))t();try{await this.brokeredSandboxIpcServer.stop()}catch(e){this.logger.info?.(`[SandboxShell] broker IPC server stop failed (continuing): ${e?.message??String(e)}`)}}getActiveHandleCount(){return this.activeHandles.size}isValidDirectory(e){try{return f().statSync(e).isDirectory()}catch{return!1}}getNetworkDecisionTarget(e){let t="string"==typeof e.host?e.host.trim():"",r="string"==typeof e.scheme?e.scheme.trim().toLowerCase():"";return t?"http"===r||"https"===r?`${r}://${t}`:t:"unknown"}auditDecisionRecords(e,t){try{let r=new Set;for(let o of e??[]){if("network"===o.domain&&"network_strict"===o.reason){let e=`strict\0${(o.host??"").toLowerCase()}\0${o.port??""}`;if(r.has(e))continue;r.add(e),(0,U.w6)({blockType:"network",target:this.getNetworkDecisionTarget(o),malicious:!1,networkStrict:!0,sessionId:t});continue}if(!o.host||"network"!==o.domain||"dangerous_url"!==o.reason)continue;let e=`${o.host.toLowerCase()}\0${o.port??""}`;if(r.has(e))continue;r.add(e);let s=o.matchRule?.ruleHint?.trim()||void 0;(0,U.w6)({blockType:"network",target:this.getNetworkDecisionTarget(o),malicious:!0,riskType:s,sessionId:t}),this.reportMaliciousHit(o,s,t)}}catch(e){this.logger.warn?.(`[SandboxShell] \u{7F51}\u{7EDC}\u{62E6}\u{622A}\u{5BA1}\u{8BA1}\u{5199}\u{5165}\u{5931}\u{8D25}: ${e}`)}}reportMaliciousHit(e,t,r){let o=e.host?.trim();if(this.telemetryReporter&&o)try{let e=this.sessionManager.sessionSubject.value;this.telemetryReporter.reportThreatDatabaseHit({tool:"bash",domain:o,riskType:t,activeVersion:this.threatDomainChecker?.getLoadedVersion(),conversationId:r??e?.id,conversationRequestId:e?.conversationRequestId})}catch(e){this.logger.warn?.(`[SandboxShell] \u{6076}\u{610F}\u{57DF}\u{540D}\u{547D}\u{4E2D}\u{57CB}\u{70B9}\u{5931}\u{8D25}\u{FF08}\u{5DF2}\u{5FFD}\u{7565}\u{FF09}: ${e}`)}}_failAllProcessHandles(e){if(0===this.processHandles.size)return;let t=Array.from(this.processHandles.entries());for(let[r,o]of(this.processHandles.clear(),this.logger.info?.(`[SandboxShell] Force-exiting ${t.length} pending handle(s) due to: ${e}`),t))try{this.logger.info?.(`[SandboxShell] forcing exit | processId=${r} | reason=${e}`),o.handleExit(-1,!0,[])}catch(e){this.logger.info?.(`[SandboxShell] force-exit failed | processId=${r} | error=${e?.message??e}`)}}async _handleReverseRequest(e){let t=e.data;switch(e.command){case w.rU:return this._handleReverseHostOperationRequest(e);case Y.lV.PROCESS_OUTPUT:{let e=this.processHandles.get(t?.processId);e?e instanceof V.a8?e.handleOutput(t.data,t.stream??"stdout"):e.handleOutput(t.data):this.logger.info?.(`[SandboxShell] ProcessOutput for unknown processId: ${t?.processId}`);return}case Y.lV.PROCESS_EXIT:{let e=this.processHandles.get(t?.processId),r=e?.sessionId??this.lifecycle.getOpenedSessionId()??void 0;this.auditDecisionRecords(t.decisionRecords,r),e?(this.logger.info?.(`[SandboxShell] ProcessExit | processId=${t.processId} | exitCode=${t.exitCode} | killed=${t.killed??!1} | decisionRecords=${t.decisionRecords?.length??0}`),e.handleExit(t.exitCode,t.killed,t.decisionRecords)):this.logger.info?.(`[SandboxShell] ProcessExit for unknown processId: ${t?.processId} | audited decisionRecords=${t.decisionRecords?.length??0}`);return}case Y.lV.REPORT_EVENT:t&&this.telemetryReporter&&(this.logger.info?.(`[SandboxShell] ReportEvent | scene=${t.scene} action=${t.action} status=${t.status} costMs=${t.costMs??"-"}`),this.telemetryReporter.ingestRawEvent(t));return;default:this.logger.info?.(`[SandboxShell] Unhandled reverse request: ${e.command}`);return}}async _handleReverseHostOperationRequest(e){let t=e.data,r=await this.bashSandboxManager?.getConfig(),o=this.processHandles.get(t?.processId);this.logger.info?.(`[BrokeredShell] reverse host operation received | operation=${t?.operation??"<unknown>"} | path=${t?.path??t?.from??"<none>"} | processId=${t?.processId??"<none>"} | brokerTraceId=${o?.brokerTraceId??"none"} | reportPath=${o?.safeDeleteReportPath?"set":"none"}`);let s=await (0,w.i5)({service:this.brokeredSandboxHostService,approvalCoordinator:this.approvalCoordinator,request:{...t??{},id:e.messageId,sessionId:e.sessionId,safeDeleteReportPath:o?.safeDeleteReportPath},orderedFileRules:r?.orderedRules?.file.rules,sandboxFilesystem:r?.filesystem});return this.logger.info?.(`[BrokeredShell] reverse host operation complete | operation=${t?.operation??"<unknown>"} | path=${t?.path??t?.from??"<none>"} | processId=${t?.processId??"<none>"} | brokerTraceId=${o?.brokerTraceId??"none"} | decision=${String(s.decision??"unknown")} | ok=${String(!0===s.ok)}`),s}_getCommandRoot(e){try{if(!e||"string"!=typeof e)return;for(let t of(0,b.parse)(e.trim()))if(!("string"==typeof t&&/^[A-Za-z_]\w*=/.test(t))&&"string"==typeof t)return t.split(/[/\\]/).pop();return}catch{return}}_parseFileBlockRecords(e){return e&&Array.isArray(e)?e.filter(e=>{if("object"!=typeof e||null===e||!e.path||e.actionMask<=0)return!1;if((0,Y.AG)(e))return this.logger.info?.(`[SandboxShell] _parseFileBlockRecords: skipping forbidden program record | path=${e.path}`),!1;let t=e.raw?.operation;return!("string"==typeof t&&t.startsWith("process-exec"))||(this.logger.info?.(`[SandboxShell] _parseFileBlockRecords: skipping process-exec record | path=${e.path} | operation=${t}`),!1)}):[]}_enrichResult(e){if(void 0!==e.sandboxDenied)return;void 0===e.fileBlockRecords&&void 0===e.networkBlockRecords&&Object.assign(e,(0,V.sO)(e.decisionRecords));let t=this._parseFileBlockRecords(e.fileBlockRecords),r=(e.networkBlockRecords?.length??0)>0;!r&&0===e.exitCode&&t.length>0&&t.every(Y.aR)?this.logger.info?.(`[SandboxShell] successful metadata-only denial kept as non-escalating | count=${t.length}`):(t.length>0||r)&&(e.sandboxDenied=!0,t.length>0&&(e.sandboxBlockedPaths=t.map(e=>e.path)))}};__decorate([(0,d.Autowired)(X.k),__metadata("design:type",Object)],et.prototype,"lifecycle",void 0),__decorate([(0,d.Autowired)(d.Logger),__metadata("design:type","function"==typeof(s=void 0!==d.Logger&&d.Logger)?s:Object)],et.prototype,"logger",void 0),__decorate([(0,d.Autowired)(h.Workspace),__metadata("design:type","function"==typeof(i=void 0!==h.Workspace&&h.Workspace)?i:Object)],et.prototype,"workspace",void 0),__decorate([(0,d.Autowired)(c.SessionManager),__metadata("design:type","function"==typeof(a=void 0!==c.SessionManager&&c.SessionManager)?a:Object)],et.prototype,"sessionManager",void 0),__decorate([(0,d.Autowired)($.Vr),__metadata("design:type","function"==typeof(n=void 0!==$.Vr&&$.Vr)?n:Object)],et.prototype,"settingsManager",void 0),__decorate([(0,d.Autowired)(v.BashSandboxManager),(0,d.Optional)(),__metadata("design:type",Object)],et.prototype,"bashSandboxManager",void 0),__decorate([(0,d.Autowired)(x.l),__metadata("design:type",Object)],et.prototype,"brokeredSandboxHostService",void 0),__decorate([(0,d.Autowired)(C.zW),__metadata("design:type",Object)],et.prototype,"approvalCoordinator",void 0),__decorate([(0,d.Autowired)(k.t),__metadata("design:type",Object)],et.prototype,"brokeredSandboxIpcServer",void 0),__decorate([(0,d.Autowired)(B.nX),__metadata("design:type",Object)],et.prototype,"localShellService",void 0),__decorate([(0,d.Autowired)(N.U),(0,d.Optional)(),__metadata("design:type",Object)],et.prototype,"telemetryReporter",void 0),__decorate([(0,d.Autowired)(K.CE),(0,d.Optional)(),__metadata("design:type",Object)],et.prototype,"sandboxRuleSyncService",void 0),__decorate([(0,d.Autowired)(z.x),(0,d.Optional)(),__metadata("design:type",Object)],et.prototype,"turnConfig",void 0),__decorate([(0,d.Autowired)(E.SandboxCenterIpcClient),(0,d.Optional)(),__metadata("design:type",Object)],et.prototype,"sandboxCenterClient",void 0),__decorate([(0,d.Autowired)(J.cN),(0,d.Optional)(),__metadata("design:type",Object)],et.prototype,"threatDomainChecker",void 0),__decorate([(0,d.PostConstruct)(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],et.prototype,"init",null),et=o=__decorate([(0,d.Component)(Y.TN)],et)},36020(e,t,r){var o,s=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,s)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return(o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&s(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.isLoopbackHost=isLoopbackHost;let n=a(r(77030));function isLoopbackHost(e){let t=e.toLowerCase();return!!("localhost"===t||t.endsWith(".localhost"))||(n.isIPv4(e)?"127"===e.split(".")[0]:!!n.isIPv6(e)&&"::1"===t)}},84283(e,t,r){var o,s=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,s)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return(o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&s(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.SandboxCliClientImpl=void 0,t.isSandboxCLIConnectTimeoutError=isSandboxCLIConnectTimeoutError,t.createSandboxCliClient=createSandboxCliClient,t.resolveSandboxCliIpcPath=resolveSandboxCliIpcPath;let n=r(16698),l=a(r(77030)),d=r(68331),c=new WeakSet,h=new Set([d.SANDBOX_COMMANDS.PROCESS_OUTPUT,d.SANDBOX_COMMANDS.PROCESS_EXIT,d.SANDBOX_COMMANDS.REPORT_EVENT]),p={connectTimeoutMs:1e4,requestTimeoutMs:12e4,heartbeatIntervalMs:3e4,heartbeatTimeoutMs:5e3,autoReconnect:!0,maxReconnectAttempts:3};function isSandboxCLIConnectTimeoutError(e){return"object"==typeof e&&null!==e&&c.has(e)}function createSandboxCliClient(e){return new SandboxCliClientImpl(e)}function resolveSandboxCliIpcPath(e,t=process.platform){return"win32"===t?`\\\\.\\pipe\\${e}`:`/tmp/${e}.sock`}let SandboxCliClientImpl=class SandboxCliClientImpl{constructor(e){this._connected=!1,this._messageCounter=0,this._socket=null,this._lineBuffer="",this._config=null,this._pendingRequests=new Map,this._reverseListeners=[],this._disconnectListeners=new Set,this.logger=e}setLogger(e){this.logger=e}async connect(e){let t;if(this._connected)return void this.logger?.info?.("[SandboxCLIClient] Already connected, skipping");this._config={...p,...e};let r=this._config.connectTimeoutMs??p.connectTimeoutMs,o=resolveSandboxCliIpcPath(this._config.address);this.logger?.info?.(`[SandboxCLIClient] Connecting to ${o} (timeout=${r}ms)`);let s=Date.now()+r,i=0;for(;Date.now()<s;){i+=1;try{await this._tryConnect(o,Math.min(3e3,s-Date.now())),this.logger?.info?.(`[SandboxCLIClient] Connected successfully (attempt ${i})`);return}catch(e){if(!isRetryableConnectError(t=e instanceof Error?e:Error(String(e))))throw t;this.logger?.info?.(`[SandboxCLIClient] Pipe not ready (attempt ${i}), retrying in 200ms...`),await new Promise(e=>setTimeout(e,200))}}let a=Error(`IPC connect timeout after ${r}ms (${i} attempts): ${t?.message??"unknown"}`);throw c.add(a),a}async disconnect(){this.logger?.info?.("[SandboxCLIClient] Disconnecting...");let e=this._connected;this._rejectAllPending("Client disconnected"),this._cleanupSocket(),this._connected=!1,this._lineBuffer="",e&&this._fireDisconnectListeners()}isConnected(){return this._connected}async sendRequest(e,t,r,o){if(!this._connected||!this._socket)throw Error("Not connected to sandbox-cli");let s=`ts-msg-${this._messageCounter++}`,i=createIpcRequest(s,e,t,r),a=o?.timeoutMs??this._config?.requestTimeoutMs??p.requestTimeoutMs,l=t!==d.SANDBOX_COMMANDS.RUN_EXECUTABLE||null===r||"object"!=typeof r||Array.isArray(r)?void 0:r,c=l?.env,h=null===c||"object"!=typeof c||Array.isArray(c)?0:Object.keys(c).length,u=l?` | envCount=${h}`:"";this.logger?.info?.(`[SandboxCLIClient] sendRequest | id=${s} | cmd=${t} | timeout=${a}ms${u}`);let g=o?.onResponse&&n.AsyncLocalStorage.bind(o.onResponse);return new Promise((e,r)=>{let n=setTimeout(()=>{this._pendingRequests.delete(s)&&r(Error(`Request ${s} timed out after ${a}ms (command: ${t})`))},a);this._pendingRequests.set(s,{resolve:t=>{try{g?.(t),e(t)}catch(e){r(e)}},reject:r,timer:n,conversationRequestId:o?.conversationRequestId}),this._socket?.write(`${JSON.stringify(i)}
|
|
3
3
|
`,e=>{e&&(this._pendingRequests.delete(s),clearTimeout(n),r(Error(`Failed to write IPC message: ${e.message}`)))})})}getPendingConversationRequestIds(){let e=[];for(let t of this._pendingRequests.values())t.conversationRequestId&&e.push(t.conversationRequestId);return e}onReverseRequest(e){this._reverseRequestHandler=e}addReverseListener(e,t){let r={commands:new Set(e.commands),handler:t};return this._reverseListeners.push(r),()=>{let e=this._reverseListeners.indexOf(r);-1!==e&&this._reverseListeners.splice(e,1)}}onDisconnect(e){return this._disconnectListeners.add(e),()=>{this._disconnectListeners.delete(e)}}async ping(){let e=this._config?.heartbeatTimeoutMs??p.heartbeatTimeoutMs;this.logger?.info?.(`[SandboxCLIClient] ping | timeout=${e}ms`),await this.sendRequest("",d.SANDBOX_COMMANDS.PING,void 0,{timeoutMs:e})}_tryConnect(e,t){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{if(s)return;s=!0,this._cleanupSocket();let e=Error(`IPC connect attempt timeout after ${t}ms`);e.code="ETIMEDOUT",o(e)},t),a=l.createConnection(e);this._socket=a,a.on("connect",()=>{s||(s=!0,clearTimeout(i),this._connected=!0,r())}),a.on("error",e=>{if(!s){s=!0,clearTimeout(i),this._cleanupSocket(),o(e);return}this.logger?.info?.(`[SandboxCLIClient] Socket error: ${e.message}`),this._handleDisconnect()}),a.on("close",()=>{if(!s){s=!0,clearTimeout(i),o(Error("IPC connection closed before connect"));return}this.logger?.info?.("[SandboxCLIClient] Socket closed"),this._handleDisconnect()}),a.on("data",e=>{this._onSocketData(e)})})}_onSocketData(e){if(this._lineBuffer+=e.toString("utf-8"),this._lineBuffer.length>8388608){this.logger?.error?.(`[SandboxCLIClient] Line buffer exceeded 8388608 bytes (currentLen=${this._lineBuffer.length}) without newline, closing connection to force restart`),this._lineBuffer="",this._handleDisconnect();return}let t=this._lineBuffer.indexOf("\n");for(;-1!==t;){let e=this._lineBuffer.slice(0,t).trim();if(this._lineBuffer=this._lineBuffer.slice(t+1),e)try{this._handleMessage(JSON.parse(e))}catch(r){let t=r instanceof Error?r.message:String(r);this.logger?.info?.(`[SandboxCLIClient] Failed to parse IPC message: ${t}, line=${e.slice(0,200)}`)}t=this._lineBuffer.indexOf("\n")}}_handleMessage(e){if(isIpcResponse(e)){let t=this._pendingRequests.get(e.messageId);if(!t)return void this.logger?.info?.(`[SandboxCLIClient] Received response for unknown messageId: ${e.messageId}`);if(this._pendingRequests.delete(e.messageId),t.timer&&clearTimeout(t.timer),e.success){this.logger?.info?.(`[SandboxCLIClient] Response OK | id=${e.messageId} | cmd=${e.command} | data=${JSON.stringify(e.data??null).slice(0,500)}`),t.resolve(e.data);return}return this.logger?.info?.(`[SandboxCLIClient] Response ERR | id=${e.messageId} | error=${e.error}`),void t.reject(Error(e.error||`Request ${e.messageId} failed`))}e.command!==d.SANDBOX_COMMANDS.PROCESS_OUTPUT&&this.logger?.info?.(`[SandboxCLIClient] Reverse request | id=${e.messageId} | cmd=${e.command} | data=${JSON.stringify(e.data??null).slice(0,500)}`);let t=!1;for(let r of this._reverseListeners)if(r.commands.has(e.command)){t=!0;let onListenerError=t=>{let r=t instanceof Error?t.message:String(t);this.logger?.info?.(`[SandboxCLIClient] Listener error for ${e.command}: ${r}`)};try{Promise.resolve(r.handler(e)).catch(onListenerError)}catch(e){onListenerError(e)}}if(!t){if(!this._reverseRequestHandler)return void this._sendResponse(createIpcResponseErr(e.messageId,e.sessionId,e.command,"No reverse request handler registered"));if(h.has(e.command))return void this._reverseRequestHandler(e).catch(t=>{let r=t instanceof Error?t.message:String(t);this.logger?.info?.(`[SandboxCLIClient] Fire-and-forget handler error for ${e.command}: ${r}`)});this._reverseRequestHandler(e).then(t=>{this._sendResponse(createIpcResponseOk(e.messageId,e.sessionId,e.command,t))}).catch(t=>{let r=t instanceof Error?t.message:"Reverse request handler failed";this._sendResponse(createIpcResponseErr(e.messageId,e.sessionId,e.command,r))})}}_sendResponse(e){this._connected&&this._socket?this._socket.write(`${JSON.stringify(e)}
|
|
4
4
|
`,e=>{e&&this.logger?.info?.(`[SandboxCLIClient] Failed to send response: ${e.message}`)}):this.logger?.info?.("[SandboxCLIClient] Cannot send response: not connected")}_rejectAllPending(e){for(let[t,r]of this._pendingRequests)r.timer&&clearTimeout(r.timer),r.reject(Error(e)),this.logger?.info?.(`[SandboxCLIClient] Rejected pending request: ${t}`);this._pendingRequests.clear()}_cleanupSocket(){if(this._socket){this._socket.removeAllListeners();try{this._socket.destroy()}catch{}this._socket=null}}_handleDisconnect(){this._connected&&(this._connected=!1,this._rejectAllPending("Connection lost"),this._cleanupSocket(),this.logger?.info?.("[SandboxCLIClient] Disconnected from sandbox-cli"),this._fireDisconnectListeners())}_fireDisconnectListeners(){let e=[...this._disconnectListeners];for(let t of(e.length>0&&this.logger?.info?.(`[SandboxCLIClient] firing ${e.length} disconnect listener(s)`),e))try{t()}catch(t){let e=t instanceof Error?t.message:String(t);this.logger?.info?.(`[SandboxCLIClient] disconnect listener error: ${e}`)}}};function isIpcResponse(e){return void 0!==e.success&&!h.has(e.command)}function createIpcRequest(e,t,r,o){return{sessionId:t,messageId:e,command:r,data:o}}function createIpcResponseOk(e,t,r,o){return{sessionId:t,messageId:e,command:r,data:o,success:!0}}function createIpcResponseErr(e,t,r,o){return{sessionId:t,messageId:e,command:r,success:!1,error:o}}function isRetryableConnectError(e){let t=e.code;return"ENOENT"===t||"ECONNREFUSED"===t||e.message.includes("ENOENT")||e.message.includes("ECONNREFUSED")}t.SandboxCliClientImpl=SandboxCliClientImpl}};
|