@agimon-ai/po-cloudflare 0.0.2-alpha.4 → 0.0.2-alpha.41
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/README.md +30 -6
- package/container/Dockerfile +27 -0
- package/dist/{BrowserWebSocketTransport-C2SC2VeJ.js → BrowserWebSocketTransport-B4heNdrp.js} +1 -1
- package/dist/{NodeWebSocketTransport-CKilJesa.js → NodeWebSocketTransport-BCiOXUEz.js} +2 -2
- package/dist/{abort-signals-Bkmp_euQ.js → abort-signals-BPGaXWA5.js} +1 -1
- package/dist/agent-COvApaVM.js +3878 -0
- package/dist/{anthropic-messages-CkYm8M3V.js → anthropic-messages-BxS7qXqx.js} +291 -63
- package/dist/apiContracts-BCr_ULWJ.js +1603 -0
- package/dist/{approval-Eu7UgGL-.js → approval-Cg-PCa5M.js} +19 -3
- package/dist/{approvalPrompt-Bg1JrEEY.js → approvalPrompt-D7peArNh.js} +1 -2
- package/dist/artifactFiles-CbGIbj93.js +1 -0
- package/dist/assets/assets/{CodeEditorView-rEfljuRK.js → CodeEditorView-J2_5q1WT.js} +2 -2
- package/dist/assets/assets/{abnfDiagram-WEYOIA3C-J6Iu5p17.js → abnfDiagram-WEYOIA3C-_gWnN1r-.js} +2 -2
- package/dist/assets/assets/{architecture-WOLXFQ4H-DKj_xMR1.js → architecture-WOLXFQ4H-DOEVRwUT.js} +1 -1
- package/dist/assets/assets/{architectureDiagram-ZHVYKT53--D1MzuBo.js → architectureDiagram-ZHVYKT53-BI3jFrO0.js} +2 -2
- package/dist/assets/assets/{blockDiagram-RJAE7QA3-CrWO0t-Q.js → blockDiagram-RJAE7QA3-B_PkpROK.js} +2 -2
- package/dist/assets/assets/{c4Diagram-XDPPPE54-CBMOJREz.js → c4Diagram-XDPPPE54-DhSjpw5T.js} +2 -2
- package/dist/assets/assets/channel-CVgc46nD.js +2 -0
- package/dist/assets/assets/{chunk-2E7WHVMD-CR9NMk46.js → chunk-2E7WHVMD-BrDo2biY.js} +2 -2
- package/dist/assets/assets/{chunk-4EMNKR2T-B4D0falO.js → chunk-4EMNKR2T-CdlJ35FL.js} +2 -2
- package/dist/assets/assets/{chunk-55XCU76K-CKrttFen.js → chunk-55XCU76K-D9eb1FTZ.js} +2 -2
- package/dist/assets/assets/{chunk-7S6XSTFO-BPNrdjSb.js → chunk-7S6XSTFO-VVyUsBaV.js} +2 -2
- package/dist/assets/assets/{chunk-AQDTSKZB-Ddx2gPU_.js → chunk-AQDTSKZB-DJmW9j7o.js} +2 -2
- package/dist/assets/assets/{chunk-DSNLSHJZ-iQg3RbZ_.js → chunk-DSNLSHJZ-bQ4kpxiE.js} +2 -2
- package/dist/assets/assets/{chunk-HAGFOTED-CGlDRwnk.js → chunk-HAGFOTED-CXTtS6oc.js} +2 -2
- package/dist/assets/assets/{chunk-HNE4Q36P-CN7VMEsn.js → chunk-HNE4Q36P-CjJ9StOJ.js} +2 -2
- package/dist/assets/assets/{chunk-NQOKRVIF-DQKmIS4j.js → chunk-NQOKRVIF-CEttWQFT.js} +2 -2
- package/dist/assets/assets/{chunk-UHW7PFBP-BKSG_d1a.js → chunk-UHW7PFBP-CJZzmAtC.js} +2 -2
- package/dist/assets/assets/{chunk-VQ5W62QI-AbFHiDOg.js → chunk-VQ5W62QI-Bp76YSjS.js} +2 -2
- package/dist/assets/assets/{chunk-WQQL4CDK-C5a4DmCb.js → chunk-WQQL4CDK-wm0yUUcN.js} +2 -2
- package/dist/assets/assets/chunk-XXDRQBXY-BkEG_5cB.js +2 -0
- package/dist/assets/assets/{chunk-YZO67HFG-UbKezTdY.js → chunk-YZO67HFG-BmXRKyV5.js} +2 -2
- package/dist/assets/assets/{chunk-ZAUX2LTX-BShGGpRc.js → chunk-ZAUX2LTX-DJCmQeWP.js} +2 -2
- package/dist/assets/assets/{chunk-ZCHMQSOR-BmV-PDP0.js → chunk-ZCHMQSOR-D3pxm97L.js} +2 -2
- package/dist/assets/assets/{classDiagram-v2-4MYWR3UA-DB-cfBNq.js → classDiagram-v2-4MYWR3UA-DxMxFm6d.js} +2 -2
- package/dist/assets/assets/{cose-bilkent-JH36ORCC-Dprqh48h.js → cose-bilkent-JH36ORCC-Ck_lCjTR.js} +2 -2
- package/dist/assets/assets/{cynefin-EF2NZ3EQ-Bz4CND4n.js → cynefin-EF2NZ3EQ-CgjU58bC.js} +1 -1
- package/dist/assets/assets/{cynefinDiagram-WF24UDRP-Cv0Tq-0q.js → cynefinDiagram-WF24UDRP-CUP0NVKn.js} +2 -2
- package/dist/assets/assets/{dagre-NK4GIZVX-H4d8oeNm.js → dagre-NK4GIZVX-DkvcOoGp.js} +2 -2
- package/dist/assets/assets/{diagram-CBK3MWTC-D75OthTM.js → diagram-CBK3MWTC-CFl4wUVN.js} +2 -2
- package/dist/assets/assets/{diagram-I5XIIV2D-CB_W2jXU.js → diagram-I5XIIV2D-CldqmFr0.js} +2 -2
- package/dist/assets/assets/{diagram-ODIL2UCW-DPO0lYZ-.js → diagram-ODIL2UCW-CPieOVfl.js} +2 -2
- package/dist/assets/assets/{diagram-PFBEJUXE-DJ9olXAC.js → diagram-PFBEJUXE-DgTWsRKS.js} +2 -2
- package/dist/assets/assets/{diagram-RJA3I4VV-DL3974PI.js → diagram-RJA3I4VV-DmxD5RVL.js} +2 -2
- package/dist/assets/assets/{diagram-TYUNFSNR-ZuYESp4p.js → diagram-TYUNFSNR-DC_QoE9Q.js} +2 -2
- package/dist/assets/assets/{dist-CeotBqYt.js → dist-BoXKbh_9.js} +2 -2
- package/dist/assets/assets/{dist-CdrEbsAL.js → dist-C-aQ-0ab.js} +2 -2
- package/dist/assets/assets/{dist-CXqaT1wB.js → dist-CHKWIm0j.js} +2 -2
- package/dist/assets/assets/{dist-BnkGKHOV.js → dist-CeZ4Dyeb.js} +2 -2
- package/dist/assets/assets/{dist-C8iSs-hT.js → dist-DtfkqVX-.js} +2 -2
- package/dist/assets/assets/{dist-G3vL_xw7.js → dist-JVpnlOn0.js} +2 -2
- package/dist/assets/assets/{dist-DvCNYjgK.js → dist-L_xVrjFQ.js} +2 -2
- package/dist/assets/assets/{dist-zXhaMKmO.js → dist-_Q_eXWhh.js} +2 -2
- package/dist/assets/assets/{dist-D2iSi_lg.js → dist-m3yHSyxW.js} +2 -2
- package/dist/assets/assets/{ebnfDiagram-V4P3TTPT-DNfHKEsm.js → ebnfDiagram-V4P3TTPT-BdrqTmnC.js} +2 -2
- package/dist/assets/assets/{elk-QONTBCTQ-C0FX9D60.js → elk-QONTBCTQ-BBnxKz3T.js} +2 -2
- package/dist/assets/assets/{erDiagram-KYQIGQAA-BI1O9lW0.js → erDiagram-KYQIGQAA-DX45_hK2.js} +2 -2
- package/dist/assets/assets/{eventmodeling-K75KTNOO-BmWt-aOv.js → eventmodeling-K75KTNOO-EIuQjWpD.js} +1 -1
- package/dist/assets/assets/flowDiagram-IUGLLWBU-Bdol35Vj.js +1 -0
- package/dist/assets/assets/{ganttDiagram-R7GPNTJY-pM7PmQ6B.js → ganttDiagram-R7GPNTJY-CveiRngd.js} +2 -2
- package/dist/assets/assets/{gitGraph-VSP46ZUC-D0QXMQxv.js → gitGraph-VSP46ZUC-D4yRXN3j.js} +1 -1
- package/dist/assets/assets/{gitGraphDiagram-PDYL7XHY-BsMltgt3.js → gitGraphDiagram-PDYL7XHY-D5DsbgCK.js} +2 -2
- package/dist/assets/assets/index-BDUEIar6.css +1 -0
- package/dist/assets/assets/index-BfW-zJ-Y.js +200 -0
- package/dist/assets/assets/{info-OHQRW6UA-Dp5Eu5PX.js → info-OHQRW6UA-C0PnFIek.js} +1 -1
- package/dist/assets/assets/{infoDiagram-MVDRKAX5-TgXRfZiq.js → infoDiagram-MVDRKAX5-DpwE-14N.js} +2 -2
- package/dist/assets/assets/{ishikawaDiagram-HPEHV2GE-Qzrmih4p.js → ishikawaDiagram-HPEHV2GE-X1GxSc7S.js} +2 -2
- package/dist/assets/assets/{journeyDiagram-BOSHW7O7-BksI3QOT.js → journeyDiagram-BOSHW7O7-0cwzSgYT.js} +2 -2
- package/dist/assets/assets/{kanban-definition-FNSA4HC5-l_IuN5_k.js → kanban-definition-FNSA4HC5-C-U-zp3B.js} +2 -2
- package/dist/assets/assets/{line-BDKssGoM.js → line-CxMWkCyB.js} +2 -2
- package/dist/assets/assets/{linear-C9vmtzBC.js → linear-BpB8rX3C.js} +2 -2
- package/dist/assets/assets/{mermaid-parser.core-O1yFX7K_.js → mermaid-parser.core-CmAfQFuk.js} +4 -4
- package/dist/assets/assets/{mermaid.core-CIq57361.js → mermaid.core-BTk7Bw6z.js} +5 -5
- package/dist/assets/assets/{mindmap-definition-6OY57UG3-BkVuZ010.js → mindmap-definition-6OY57UG3-B2sMo2jC.js} +2 -2
- package/dist/assets/assets/{packet-JDAUHWVQ-PPNcSWeV.js → packet-JDAUHWVQ-BzzVSUon.js} +1 -1
- package/dist/assets/assets/{pegDiagram-ECIUJNBX-ClwrHXhM.js → pegDiagram-ECIUJNBX-VIiN2lIU.js} +2 -2
- package/dist/assets/assets/{pie-XZMESJXO-BAE4Cy9j.js → pie-XZMESJXO-B-jSi7x9.js} +1 -1
- package/dist/assets/assets/{pieDiagram-GNMPY74T-CvQ62Knb.js → pieDiagram-GNMPY74T-190bpqyE.js} +2 -2
- package/dist/assets/assets/{quadrantDiagram-D57K4MC3-CzAyT5ZB.js → quadrantDiagram-D57K4MC3-CHsQo88q.js} +2 -2
- package/dist/assets/assets/{radar-ABXABTNO-CoEe8B7b.js → radar-ABXABTNO-CW2EglFo.js} +1 -1
- package/dist/assets/assets/{railroad-I3PHUGI6-BbK5J8H5.js → railroad-I3PHUGI6-C1b0ftsy.js} +1 -1
- package/dist/assets/assets/{railroad-abnf-LNEFI6M7-DlGngfop.js → railroad-abnf-LNEFI6M7-DTT_CP-y.js} +1 -1
- package/dist/assets/assets/{railroad-ebnf-DWYD2UWJ-BRk4ifMx.js → railroad-ebnf-DWYD2UWJ-RCPkVVI9.js} +1 -1
- package/dist/assets/assets/{railroad-peg-JR7BVNR7-Rz-3vbj2.js → railroad-peg-JR7BVNR7-DixVu6c8.js} +1 -1
- package/dist/assets/assets/{railroadDiagram-Y72NRBL7-DQISBRHH.js → railroadDiagram-Y72NRBL7-DbdG32pF.js} +2 -2
- package/dist/assets/assets/{requirementDiagram-EQYSW5RA-DcK4FnTB.js → requirementDiagram-EQYSW5RA-U_x9QFHY.js} +2 -2
- package/dist/assets/assets/{sankeyDiagram-SY24JHO5-N2EXBOYb.js → sankeyDiagram-SY24JHO5-qfiLv1KI.js} +2 -2
- package/dist/assets/assets/{sequenceDiagram-BLEHNHQU-CMJ2EqC_.js → sequenceDiagram-BLEHNHQU-DMBomC37.js} +2 -2
- package/dist/assets/assets/{src-Df9VBjd7.js → src-DaNTNLrJ.js} +2 -2
- package/dist/assets/assets/{stateDiagram-v2-A6IESKWZ-D6Cxm8wj.js → stateDiagram-v2-A6IESKWZ-BgAnpbx_.js} +2 -2
- package/dist/assets/assets/{swimlanes-B3ENRKFQ-BybuzSPd.js → swimlanes-B3ENRKFQ-Dihe5c6o.js} +2 -2
- package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-Cgg-RsbC.js +9 -0
- package/dist/assets/assets/{timeline-definition-JXYKGLGB-BzjkWUdz.js → timeline-definition-JXYKGLGB-BISDYTXW.js} +2 -2
- package/dist/assets/assets/{treeView-D4JQ5SDB-DIDWwDtU.js → treeView-D4JQ5SDB-DMSWtiHi.js} +1 -1
- package/dist/assets/assets/{treemap-SAJKECNS-SWP4JszI.js → treemap-SAJKECNS-0SsdPE-3.js} +1 -1
- package/dist/assets/assets/{usecaseDiagram-WPOLBNNX-ZfCxSJdE.js → usecaseDiagram-WPOLBNNX-CY0WaaL_.js} +2 -2
- package/dist/assets/assets/{vennDiagram-Q3Y3IDCW-o44wkgGH.js → vennDiagram-Q3Y3IDCW-DXXcHfKI.js} +2 -2
- package/dist/assets/assets/{wardley-7MLQ67FV-0zKRsI4Z.js → wardley-7MLQ67FV-BzVdmZfO.js} +1 -1
- package/dist/assets/assets/{wardleyDiagram-IVAIDKWA-CyBVyB40.js → wardleyDiagram-IVAIDKWA-BiDG6ka7.js} +2 -2
- package/dist/assets/assets/{webpack-C4nkEwJD.js → webpack-CUCfmjk-.js} +2 -2
- package/dist/assets/assets/{xychartDiagram-4URNHDU4-BMvRihYC.js → xychartDiagram-4URNHDU4-DTR1zwTC.js} +2 -2
- package/dist/assets/bundle-asset-policy.json +1 -1
- package/dist/assets/index.html +8 -2
- package/dist/assets/plugins/assets/base-LmdY6uBA.css +2 -0
- package/dist/assets/plugins/assets/browserCaptureWorklet-Droj0fW0-Droj0fW0.js +13 -0
- package/dist/assets/plugins/assets/sileroVadWorker-D894njUe-DjN_BMWf.mjs +110 -0
- package/dist/assets/plugins/assets/silero_vad_v6.2.1-SjbCxFXk-SjbCxFXk.onnx +0 -0
- package/dist/assets/plugins/chunks/po-web-runtime-Ka6K4y6i.js +1 -0
- package/dist/assets/plugins/compositions.json +1 -1
- package/dist/assets/plugins/slots/approval.dd60ec90-D_Iw2VJn.js +2 -0
- package/dist/assets/plugins/slots/artifacts.a078f1a5-CS9a_zNA.js +1 -0
- package/dist/assets/plugins/slots/author.497633d0-BFa_H5ZE.js +93 -0
- package/dist/assets/plugins/slots/autocompact.86aeccf4-B0hGnck7.js +1 -0
- package/dist/assets/plugins/slots/browse.5fcf164c-CVRtiGzR.js +1 -0
- package/dist/assets/plugins/slots/builtin-tools.0a7f0b8e-CJTf-98P.js +7 -0
- package/dist/assets/plugins/slots/codemode.ff16ac06-BRYQKsyR.js +11 -0
- package/dist/assets/plugins/slots/domain.3ddea842-02QPrhJk.js +1 -0
- package/dist/assets/plugins/slots/edit.c5b0b072-CETRuGf0.js +7 -0
- package/dist/assets/plugins/slots/files.8ffcdcc0-DgGX5poR.js +2 -0
- package/dist/assets/plugins/slots/goal.423c7a26-D67j7FqW.js +1 -0
- package/dist/assets/plugins/slots/grep.95f470b3-CmhMD_DW.js +1 -0
- package/dist/assets/plugins/slots/help.03b9ba99-os14i52k.js +3 -0
- package/dist/assets/plugins/slots/log.19bda339-DvprmzHk.js +4 -0
- package/dist/assets/plugins/slots/mcp.ffbe405a-CcCIF5cJ.js +109 -0
- package/dist/assets/plugins/slots/plan.5eac6563-CqYx6E9R.js +3 -0
- package/dist/assets/plugins/slots/{profile.ab16dcec-Cu6ev2uW.js → profile.176710dd-BDgBh-Su.js} +1 -1
- package/dist/assets/plugins/slots/prompts.2c187969-Bls5s3m1.js +3 -0
- package/dist/assets/plugins/slots/read.1629d556-Bg9NIMAZ.js +1 -0
- package/dist/assets/plugins/slots/runner.962030e5-_04Fb699.js +8 -0
- package/dist/assets/plugins/slots/sessions.fc763f42-BaHBIWGm.js +1 -0
- package/dist/assets/plugins/slots/skill.f5396fde-MNxJbIRc.js +4 -0
- package/dist/assets/plugins/slots/subagents.d815a296-DNYKN2_3.js +7 -0
- package/dist/assets/plugins/slots/vault.57fd9047-C3YDx6j4.js +1 -0
- package/dist/assets/plugins/slots/voice.b709d05c-BT788wX1.js +1 -0
- package/dist/assets/pwa/pwa.js +12 -12
- package/dist/assets/pwa/sw.js +4 -4
- package/dist/{atomicJson-DwSqByUJ.js → atomicJson-CU27fWtF.js} +2 -3
- package/dist/{azure-openai-config-DHMgdIa-.js → azure-openai-config-DkmTos8T.js} +2 -2
- package/dist/{azure-openai-responses-CTgRdQ4m.js → azure-openai-responses-sm_U3omr.js} +13 -13
- package/dist/backgroundWork-C3TYOD5X.js +49 -0
- package/dist/browser-BWf8OMfl.js +3 -0
- package/dist/{browser-EJ5_ffnN.js → browser-IsHIcvFg.js} +1 -1
- package/dist/childSession-Cf2-kH4O.js +22 -0
- package/dist/{classifier-shared-jXm-plIK.js → classifier-shared-B7BdEyPa.js} +5 -5
- package/dist/{cloudflare-workers-ai-system-one-B0wH6HU5.js → cloudflare-workers-ai-system-one-DpnCKwVj.js} +3 -3
- package/dist/{codemode-yHAHBZO-.js → codemode-CU_gontV.js} +5 -2
- package/dist/contracts-B_eb2dl9.js +19 -0
- package/dist/contracts-mVtrvUmY.js +40 -0
- package/dist/{diagnostics-DPTP-yrt.js → diagnostics-C43OHsIc.js} +2 -2
- package/dist/{server-y9pjeHJM.js → dist-B-vqs6tA.js} +1 -546
- package/dist/{dist-Dvx5mlIR.js → dist-CLdzaXdw.js} +16 -3
- package/dist/{dist-BVBi6VMV.js → dist-CfOWb6f7.js} +1 -1
- package/dist/{dist-PDDFdqDX.js → dist-Dd6zUvjw.js} +1 -1
- package/dist/edge-accj222e.js +266 -0
- package/dist/{emscripten-module.cloudflare-D4Bc9Ykz.js → emscripten-module.cloudflare-B4fhfquU.js} +1 -1
- package/dist/{env-api-keys-CAnjjnsR.js → env-api-keys-CSPKWgJn.js} +1 -1
- package/dist/{error-body-DQZRsyL5.js → error-body-BvLDKbXN.js} +26 -4
- package/dist/esm-BKJy3O9-.js +1553 -0
- package/dist/{exports-CrJqsTU6.js → exports-BlsXYnB_.js} +27 -9
- package/dist/{remoteMcp-Ci8crSU9.js → exports-CHx8bsjQ.js} +1062 -176
- package/dist/exports-CUM-AowA.js +34 -0
- package/dist/extensionFile-Bf1PbYVu.js +121 -0
- package/dist/{factory-Cs8iaUtc.js → factory-DwoANAyi.js} +1 -1
- package/dist/{github-copilot-headers-DpQQAh-s.js → github-copilot-headers-CZIImZmD.js} +1 -1
- package/dist/{google-generative-ai-BTTOo5RQ.js → google-generative-ai-P4ubvgcU.js} +9 -9
- package/dist/{google-shared-S7bqOccz.js → google-shared-C8Kez75I.js} +6 -6
- package/dist/{google-vertex-BcMU_DMb.js → google-vertex-T1trcCEz.js} +10 -10
- package/dist/{domains-dHfk2U8X.js → harnessState-DMini_AN.js} +175 -16
- package/dist/{harnessStore-CRtlTdbI.js → harnessStore-CTomNyVl.js} +4 -5
- package/dist/{hash-B3RRpLS2.js → hash-CMLRVP3c.js} +1 -1
- package/dist/{headers-BEuxFxDI.js → headers-CX-ZuPIi.js} +1 -1
- package/dist/help-BxTDP41H.js +1 -0
- package/dist/help-C4aC-kWh.js +100 -0
- package/dist/http-4lVtjwa7.js +59 -0
- package/dist/{hubChannel-Cj1iF847.js → hubChannel-Bq4zyVgX.js} +12 -29
- package/dist/hubRevisions-BknPawK7.js +364 -0
- package/dist/{identity-BIeAyilV.js → identity-DEwhWpjw.js} +3 -3
- package/dist/index.edge-ClLTmPFz.js +191 -0
- package/dist/index.edge-CwcYQLj9.js +70 -0
- package/dist/index.edge-D2RirEwK.js +14 -0
- package/dist/index.edge-Dw11TL5F.js +56 -0
- package/dist/index.edge-DyUqSroq.js +67 -0
- package/dist/index.edge-Ts1NG9b4.js +937 -0
- package/dist/iso-BCXA5x1w.js +10 -0
- package/dist/{kysely-adapter-D51abb3q.js → kysely-adapter-D3TQ9BKb.js} +1 -1
- package/dist/{layeredConfig-BqIwPJ-I.js → layeredConfig-DVe-JMGQ.js} +217 -24
- package/dist/{majorModes-C-OD4PBc.js → majorModes-BBT0wftm.js} +4 -14
- package/dist/majorModes-BcA8pk7t.js +1 -0
- package/dist/{mcpProjection-BsP0IEnb.js → mcpProjection-BZoy_uKa.js} +1 -2
- package/dist/{mistral-conversations-DN8VSERk.js → mistral-conversations-jEBsA1Xz.js} +12 -12
- package/dist/modeDefinition-C3Zbrw48.js +44 -0
- package/dist/{models-D6d73jcW.js → models-BoBYu6VI.js} +41 -46
- package/dist/narration-BtGsZwE7.js +127 -0
- package/dist/{node-UuMT2C3q.js → node-CdIUdDAa.js} +2 -2
- package/dist/{node-DytJOfYf.js → node-CjBe953N.js} +2 -2
- package/dist/notification-BHaYyLJJ.js +101 -0
- package/dist/{openai-bt3ZRBZv.js → openai-69NOv-G_.js} +187 -187
- package/dist/{openai-codex-responses-cL36x0ml.js → openai-codex-responses-x01Vnd68.js} +21 -25
- package/dist/{openai-completions-BWsTNYyT.js → openai-completions-B81ryS-E.js} +26 -19
- package/dist/{openai-decisions-Dfn_KgQd.js → openai-decisions-Kybq6lsr.js} +3 -3
- package/dist/{openai-responses-aa0LoyCJ.js → openai-responses-BK5Zz1Ib.js} +17 -15
- package/dist/{openai-responses-shared-H-jH5SlM.js → openai-responses-shared-b4nN_ZS7.js} +7 -7
- package/dist/{openrouter-cost-D99Qqcs6.js → openrouter-cost-C4M4CjUF.js} +1 -1
- package/dist/{openrouter-images-BpwVpALC.js → openrouter-images-DMMiksXo.js} +7 -7
- package/dist/photon_rs_bg.wasm +0 -0
- package/dist/{pi-messages-BHAIkYBj.js → pi-messages-D3F6NGQb.js} +6 -6
- package/dist/piConfig-BeRtzEWI.js +126 -0
- package/dist/piSettings-CDcdxob2.js +1 -0
- package/dist/platform-CAhzdBhg.js +113 -0
- package/dist/pluginContributions-Be9EnCAW.js +16 -0
- package/dist/pluginProtocol-ZOY2-HIL.js +136 -0
- package/dist/{protocol-Xpm_mCNN.js → protocol-Db1l1xpe.js} +1 -2
- package/dist/{provider-env-DgfpjgTa.js → provider-env-C6KlbHmf.js} +2 -2
- package/dist/{provider-retry-ChD-K2Gv.js → provider-retry-C8AvzuUi.js} +1 -1
- package/dist/{puppeteer-cloudflare-B-GHrPGO.js → puppeteer-cloudflare-D4l8smMS.js} +3 -3
- package/dist/{rolldown-runtime-B-lAHAz2.js → rolldown-runtime-DbVrKiKs.js} +1 -1
- package/dist/{sanitize-unicode-Dl4ROF7y.js → sanitize-unicode-Di-31Zpn.js} +1 -1
- package/dist/{schemas-Vj8-rCR4.js → schemas-BMBR99Q5.js} +3 -2
- package/dist/server-4R5ZprW5.js +978 -0
- package/dist/server-B0PFs3Yl.js +288 -0
- package/dist/server-B4f5d7ka.js +1811 -0
- package/dist/server-BQ0I9oeZ.js +1359 -0
- package/dist/server-BZ_bk5i9.js +295 -0
- package/dist/{server-CUvohcAm.js → server-Ba7pnDkx.js} +54 -47
- package/dist/server-BayLsR7Z.js +343 -0
- package/dist/{server-BccTx_r6.js → server-BbNo0APc.js} +121 -19
- package/dist/server-Bi9VOAOP.js +833 -0
- package/dist/{server-De_PIOty.js → server-BkmcRLIT.js} +47 -27
- package/dist/{server-DwWTQg1J.js → server-BwtSRROE.js} +14 -5
- package/dist/server-BxzzL3_G.js +1883 -0
- package/dist/{server-CYQHzqaQ.js → server-By1ctEvA.js} +11 -9
- package/dist/server-CA5TuWDo.js +3125 -0
- package/dist/{server-C1ijZQp4.js → server-CBHlRlm4.js} +3 -10
- package/dist/server-CDypk2xJ.js +1296 -0
- package/dist/server-ChlBgWIn.js +1116 -0
- package/dist/server-CkMqSsYi.js +15105 -0
- package/dist/server-CnsLcuj-.js +1518 -0
- package/dist/server-CrqcdtBx.js +178 -0
- package/dist/server-CwlDZ2N-.js +491 -0
- package/dist/server-D3j7dywQ.js +576 -0
- package/dist/server-DXD7cbH0.js +679 -0
- package/dist/server-DesEguVZ.js +640 -0
- package/dist/server-Dqjcc8p0.js +2656 -0
- package/dist/{server-BPvd3Ya5.js → server-DrmY-Chg.js} +570 -127
- package/dist/{server-B2xd7WTP.js → server-DtCOCPGp.js} +9 -20
- package/dist/server-DuAckacI.js +1522 -0
- package/dist/server-EgPpwMaj.js +505 -0
- package/dist/server-h0TSZCjm.js +189 -0
- package/dist/serverPlugin-Cx6a5RT0.js +36624 -0
- package/dist/session-resources-DLg07yAP.js +10 -0
- package/dist/{sessionConfig-2a4LWInR.js → sessionConfig-6NVRcVwL.js} +615 -766
- package/dist/{simple-options-DWrW31_K.js → simple-options-DM-a_ljY.js} +13 -6
- package/dist/{streaming-json-t4rzNHEp.js → streaming-json-Bs_lERVE.js} +6 -6
- package/dist/{system-one-shared-DLVLdzYL.js → system-one-shared-B63vQ3Om.js} +3 -3
- package/dist/{notification-D76PSL7r.js → telemetry-CrTcxeA5.js} +2 -93
- package/dist/{transform-messages-CjTSwW9q.js → transform-messages-Bbr4sgbB.js} +3 -16
- package/dist/truncate-M3KbFyVj.js +89 -0
- package/dist/{server-DrZBZ17y.js → type-CuAiPMD4.js} +569 -1409
- package/dist/type-yokaDI_F.js +7 -0
- package/dist/{typesafe-system-one-DBVcjcUQ.js → typesafe-system-one-7g930h9C.js} +3 -3
- package/dist/{uuid-mkNGilLv.js → uuid-D5Z4Ivdo.js} +1 -1
- package/dist/{validation-D77NZBrx.js → validation-DesEfRe-.js} +8 -3
- package/dist/vaultSettings-BdkqnmJf.js +292 -0
- package/dist/voiceTools-Chad-LEE.js +246 -0
- package/dist/web-QeFwt_Vl.js +3 -0
- package/dist/worker.js +56560 -35339
- package/dist/workflow-BLBCriNp.js +113 -0
- package/package.json +44 -25
- package/wrangler.jsonc +13 -3
- package/dist/apiContracts-CHOiCbS_.js +0 -4451
- package/dist/assets/assets/channel-CNegK3Rr.js +0 -2
- package/dist/assets/assets/chunk-XXDRQBXY-BbVKQGnw.js +0 -2
- package/dist/assets/assets/flowDiagram-IUGLLWBU-DQj3H5a6.js +0 -1
- package/dist/assets/assets/index-BTHzc8EN.js +0 -155
- package/dist/assets/assets/index-DZM68mTk.css +0 -1
- package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-CXJkO6sc.js +0 -9
- package/dist/assets/plugins/assets/base-B5jpmLBl.css +0 -2
- package/dist/assets/plugins/chunks/po-web-runtime-D4qQFtJO.js +0 -1
- package/dist/assets/plugins/slots/approval.09e72f36-Cck_K9ex.js +0 -2
- package/dist/assets/plugins/slots/artifacts.50b639bb-BZM7uEbe.js +0 -1
- package/dist/assets/plugins/slots/builtin-tools.75108f21-EWWGTveL.js +0 -7
- package/dist/assets/plugins/slots/codemode.c58fb583-CgfTL6kt.js +0 -9
- package/dist/assets/plugins/slots/domain.753f9f92-BU0ilfwM.js +0 -1
- package/dist/assets/plugins/slots/mcp.82cc1ff5-BaCD2xZB.js +0 -109
- package/dist/assets/plugins/slots/skill.62a0a1b3-Bz20F1eA.js +0 -4
- package/dist/backgroundWork-bE3pc-R9.js +0 -25
- package/dist/build-2gFaVEfG.js +0 -3355
- package/dist/contextProjection-DVP2Vc5j.js +0 -188
- package/dist/extensionFile-CY4EFNHQ.js +0 -409
- package/dist/harnessState-gmzJcPGt.js +0 -88
- package/dist/harnessStore-DZ4lDIq6.js +0 -1
- package/dist/index.edge-BgSx_gRO.js +0 -45
- package/dist/majorModes-AYZvnOpU.js +0 -1
- package/dist/piSettings-B6fsgIBA.js +0 -1
- package/dist/platform-CNhm9zLi.js +0 -16
- package/dist/platformFiles-3rzOh9cg.js +0 -39
- package/dist/server-Bf3_VTkt.js +0 -592
- package/dist/server-BmAziQml.js +0 -657
- package/dist/server-BvV-GqDO.js +0 -280
- package/dist/server-xiuzwJ1C.js +0 -118
- package/dist/serverPlugin-H4T49sac.js +0 -3347
- package/dist/value-Djvc2foV.js +0 -2247
|
@@ -1,15 +1,266 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
6
|
-
import {
|
|
7
|
-
import "./
|
|
8
|
-
import { n as writePrivateAtomicJsonAsync } from "./atomicJson-DwSqByUJ.js";
|
|
9
|
-
import "./piSettings-B6fsgIBA.js";
|
|
1
|
+
import { A as Check, J as Optional, Lt as BACKGROUND_CONTEXT, R as String$1, ct as getOrThrow, it as nodeHost, nt as createSerialRunner, q as _Object_, tn as defineServiceContract, tt as poHomeDirectory } from "./serverPlugin-Cx6a5RT0.js";
|
|
2
|
+
import "./hubChannel-Bq4zyVgX.js";
|
|
3
|
+
import { s as readTextIfExists } from "./platform-CAhzdBhg.js";
|
|
4
|
+
import { n as writePrivateAtomicJsonAsync } from "./atomicJson-CU27fWtF.js";
|
|
5
|
+
import "./piSettings-CDcdxob2.js";
|
|
6
|
+
import { a as PO_BACKGROUND_WORK_SERVICE, i as PO_BACKGROUND_WORK_CHANGED_EVENT, r as BackgroundProviderWorkItemSchema } from "./backgroundWork-C3TYOD5X.js";
|
|
7
|
+
import { r as assertCodemodeNamespaceName } from "./codemode-CU_gontV.js";
|
|
10
8
|
import { ECDH, createCipheriv, createDecipheriv, createECDH, createHash, createHmac, hkdfSync, randomBytes, timingSafeEqual } from "node:crypto";
|
|
11
9
|
import path from "node:path";
|
|
12
|
-
|
|
10
|
+
/**
|
|
11
|
+
* Rekey well before the counter could wrap.
|
|
12
|
+
*
|
|
13
|
+
* A repeated nonce under one AES-GCM key is catastrophic, not merely weak: it
|
|
14
|
+
* leaks the XOR of two plaintexts and the authentication subkey. The counter is
|
|
15
|
+
* 64 bits, so this bound is nowhere near it; the point is that the bound exists
|
|
16
|
+
* and is enforced rather than assumed.
|
|
17
|
+
*/
|
|
18
|
+
const MAX_MESSAGES_PER_KEY = 2 ** 32;
|
|
19
|
+
/**
|
|
20
|
+
* HKDF info strings, one per direction.
|
|
21
|
+
*
|
|
22
|
+
* Separate keys per direction, not one shared key, so a message the server sent
|
|
23
|
+
* can never be replayed back at it as though the client had sent it.
|
|
24
|
+
*/
|
|
25
|
+
const CLIENT_TO_SERVER_INFO = "po/sealed/c2s/v1";
|
|
26
|
+
const SERVER_TO_CLIENT_INFO = "po/sealed/s2c/v1";
|
|
27
|
+
function infoFor(direction) {
|
|
28
|
+
return direction === "c2s" ? CLIENT_TO_SERVER_INFO : SERVER_TO_CLIENT_INFO;
|
|
29
|
+
}
|
|
30
|
+
function isSealedEnvelope(value) {
|
|
31
|
+
if (typeof value !== "object" || value === null) return false;
|
|
32
|
+
const candidate = value;
|
|
33
|
+
return candidate.v === 1 && typeof candidate.n === "string" && typeof candidate.c === "string";
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region ../../foundations/po-session/src/services/backgroundWorkService/index.ts
|
|
37
|
+
/** Creates the generation-bound, pull-based coordinator shared by session extensions. */
|
|
38
|
+
function createBackgroundWorkService(ctx) {
|
|
39
|
+
const registrations = /* @__PURE__ */ new Map();
|
|
40
|
+
const generation = `po-background-work:${crypto.randomUUID()}`;
|
|
41
|
+
const changed = (provider, providerGeneration, kind) => {
|
|
42
|
+
ctx.emit(PO_BACKGROUND_WORK_CHANGED_EVENT, {
|
|
43
|
+
provider,
|
|
44
|
+
generation: providerGeneration,
|
|
45
|
+
kind
|
|
46
|
+
});
|
|
47
|
+
};
|
|
48
|
+
return Object.freeze({
|
|
49
|
+
generation,
|
|
50
|
+
register(provider) {
|
|
51
|
+
if (!provider || typeof provider !== "object" || typeof provider.listActiveWork !== "function") throw new TypeError("A background-work provider must expose listActiveWork().");
|
|
52
|
+
const name = provider.provider.trim();
|
|
53
|
+
if (!name || name !== provider.provider) throw new TypeError("A background-work provider requires a trimmed, non-empty name.");
|
|
54
|
+
const token = Symbol(name);
|
|
55
|
+
const providerGeneration = `${name}:${crypto.randomUUID()}`;
|
|
56
|
+
registrations.set(name, {
|
|
57
|
+
token,
|
|
58
|
+
generation: providerGeneration,
|
|
59
|
+
provider
|
|
60
|
+
});
|
|
61
|
+
changed(name, providerGeneration, "registered");
|
|
62
|
+
let disposed = false;
|
|
63
|
+
return Object.freeze({
|
|
64
|
+
provider: name,
|
|
65
|
+
generation: providerGeneration,
|
|
66
|
+
update() {
|
|
67
|
+
if (!disposed && registrations.get(name)?.token === token) changed(name, providerGeneration, "updated");
|
|
68
|
+
},
|
|
69
|
+
dispose() {
|
|
70
|
+
if (disposed) return;
|
|
71
|
+
disposed = true;
|
|
72
|
+
if (registrations.get(name)?.token !== token) return;
|
|
73
|
+
registrations.delete(name);
|
|
74
|
+
changed(name, providerGeneration, "unregistered");
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
},
|
|
78
|
+
snapshot(sessionId) {
|
|
79
|
+
const items = [];
|
|
80
|
+
const errors = [];
|
|
81
|
+
for (const [provider, registration] of registrations) try {
|
|
82
|
+
const current = registration.provider.listActiveWork();
|
|
83
|
+
if (!Array.isArray(current)) throw new TypeError("listActiveWork() must return an array.");
|
|
84
|
+
for (const item of current) {
|
|
85
|
+
if (!Check(BackgroundProviderWorkItemSchema, item)) throw new TypeError("listActiveWork() returned an invalid item.");
|
|
86
|
+
if (sessionId === void 0 || item.sessionId === sessionId) items.push({
|
|
87
|
+
provider,
|
|
88
|
+
...item
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
} catch (error) {
|
|
92
|
+
errors.push({
|
|
93
|
+
provider,
|
|
94
|
+
message: error instanceof Error ? error.message : String(error)
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return Object.freeze({
|
|
98
|
+
items: Object.freeze(items),
|
|
99
|
+
errors: Object.freeze(errors)
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
/** Installs one coordinator in the current session service context. */
|
|
105
|
+
function provideBackgroundWorkService(context) {
|
|
106
|
+
context.provide(PO_BACKGROUND_WORK_SERVICE, createBackgroundWorkService(context));
|
|
107
|
+
}
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region ../../foundations/po-session/src/schemas/startSession.ts
|
|
110
|
+
/** Input shared by start_session and the Session code-mode namespace. */
|
|
111
|
+
const StartSessionParamsSchema = _Object_({
|
|
112
|
+
name: String$1({
|
|
113
|
+
minLength: 1,
|
|
114
|
+
description: "The session name the person sees."
|
|
115
|
+
}),
|
|
116
|
+
brief: String$1({
|
|
117
|
+
minLength: 1,
|
|
118
|
+
description: "The first prompt: goal, context, and what done looks like."
|
|
119
|
+
}),
|
|
120
|
+
workspaceId: Optional(String$1({
|
|
121
|
+
minLength: 1,
|
|
122
|
+
description: "Home coordinators only: an admitted workspace without its own coordinator."
|
|
123
|
+
}))
|
|
124
|
+
}, { additionalProperties: false });
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region ../../foundations/po-session/src/services/coordinatorSessions/index.ts
|
|
127
|
+
const START_SESSION_TOOL_NAME = "start_session";
|
|
128
|
+
function field(params, key) {
|
|
129
|
+
const value = params[key];
|
|
130
|
+
if (typeof value !== "string" || !value.trim()) throw new Error(`${key} must be non-empty text.`);
|
|
131
|
+
return value.trim();
|
|
132
|
+
}
|
|
133
|
+
/** Validate at every public entry, including compatibility forwarders. */
|
|
134
|
+
function parseStartSessionInput(raw) {
|
|
135
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("startSession input must be an object.");
|
|
136
|
+
const params = raw;
|
|
137
|
+
const extra = Object.keys(params).filter((key) => ![
|
|
138
|
+
"name",
|
|
139
|
+
"brief",
|
|
140
|
+
"workspaceId"
|
|
141
|
+
].includes(key));
|
|
142
|
+
if (extra.length) throw new Error(`Unknown field: ${extra.join(", ")}.`);
|
|
143
|
+
return {
|
|
144
|
+
name: field(params, "name"),
|
|
145
|
+
brief: field(params, "brief"),
|
|
146
|
+
...params.workspaceId === void 0 ? {} : { workspaceId: field(params, "workspaceId") }
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
async function startCoordinatedSession(options, raw, signal) {
|
|
150
|
+
signal?.throwIfAborted();
|
|
151
|
+
if (options.provenance() !== "coordinator") throw new Error("Only a coordinator session can start sessions.");
|
|
152
|
+
const coordination = options.coordination();
|
|
153
|
+
if (!coordination) throw new Error("This host cannot start sessions.");
|
|
154
|
+
const request = parseStartSessionInput(raw);
|
|
155
|
+
const result = await coordination.startSession(request);
|
|
156
|
+
return {
|
|
157
|
+
sessionId: String(result.sessionId),
|
|
158
|
+
...result.promptError === void 0 ? {} : { promptError: String(result.promptError) }
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
function createStartSessionTool(options) {
|
|
162
|
+
return {
|
|
163
|
+
name: START_SESSION_TOOL_NAME,
|
|
164
|
+
label: "Start session",
|
|
165
|
+
mainAgentOnly: true,
|
|
166
|
+
description: "Coordinators only: start briefed independent work in your scope. Home may target an uncoordinated workspace. Limited to 5 an hour.",
|
|
167
|
+
parameters: StartSessionParamsSchema,
|
|
168
|
+
promptGuidelines: ["Use sessions.start only for independent work the person will follow on its own. Use a subagent for work you will wait on, and network.send for an existing session."],
|
|
169
|
+
executionMode: "serial",
|
|
170
|
+
async execute(_id, parameters, signal) {
|
|
171
|
+
const result = await startCoordinatedSession(options, parameters, signal);
|
|
172
|
+
return {
|
|
173
|
+
content: [{
|
|
174
|
+
type: "text",
|
|
175
|
+
text: result.promptError ? `Created session ${result.sessionId}, but its first prompt failed: ${result.promptError}. Do not start it again.` : `Started session ${result.sessionId}. Reach it with network.send.`
|
|
176
|
+
}],
|
|
177
|
+
details: result
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
//#endregion
|
|
183
|
+
//#region ../../foundations/po-session/src/services/sessionsNamespace/index.ts
|
|
184
|
+
const detach = (value) => JSON.parse(JSON.stringify(value ?? null));
|
|
185
|
+
function fields(raw, keys) {
|
|
186
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("Expected an object.");
|
|
187
|
+
const input = raw;
|
|
188
|
+
if (Object.keys(input).some((key) => !keys.includes(key))) throw new Error("Unknown operation field.");
|
|
189
|
+
const parsed = {};
|
|
190
|
+
for (const key of keys) {
|
|
191
|
+
const value = input[key];
|
|
192
|
+
if (typeof value !== "string" || !value.trim()) throw new Error(`${key} must be non-empty text.`);
|
|
193
|
+
parsed[key] = value.trim();
|
|
194
|
+
}
|
|
195
|
+
return parsed;
|
|
196
|
+
}
|
|
197
|
+
function createSessionsNamespace(options) {
|
|
198
|
+
assertCodemodeNamespaceName("sessions");
|
|
199
|
+
return {
|
|
200
|
+
name: "sessions",
|
|
201
|
+
summary: "List related sessions and start briefed work as a coordinator. Message them with network. No stop or delete.",
|
|
202
|
+
portable: true,
|
|
203
|
+
declarations: `declare const sessions: {
|
|
204
|
+
list(): Promise<unknown>;
|
|
205
|
+
start(input: { name: string; brief: string; workspaceId?: string }): Promise<{ sessionId: string; promptError?: string }>;
|
|
206
|
+
${options.operations.read ? "read(input: { sessionId: string }): Promise<unknown>;" : ""}
|
|
207
|
+
};`,
|
|
208
|
+
bind(run) {
|
|
209
|
+
if (run.sessionId !== options.sessionId) throw new Error("Session namespace belongs to another session.");
|
|
210
|
+
const lifetime = new AbortController();
|
|
211
|
+
const signal = AbortSignal.any([run.signal, lifetime.signal]);
|
|
212
|
+
run.onDispose(() => lifetime.abort(/* @__PURE__ */ new Error("Session code-mode run is disposed.")));
|
|
213
|
+
const check = () => {
|
|
214
|
+
if (run.caller !== "main") throw new Error("Session operations require the main agent.");
|
|
215
|
+
signal.throwIfAborted();
|
|
216
|
+
options.assertAvailable();
|
|
217
|
+
};
|
|
218
|
+
const methods = Object.create(null);
|
|
219
|
+
methods.list = async () => {
|
|
220
|
+
check();
|
|
221
|
+
const result = await options.operations.list(signal);
|
|
222
|
+
check();
|
|
223
|
+
return detach(result);
|
|
224
|
+
};
|
|
225
|
+
if (options.operations.read) methods.read = async (raw) => {
|
|
226
|
+
check();
|
|
227
|
+
const { sessionId } = fields(raw, ["sessionId"]);
|
|
228
|
+
const result = await options.operations.read(sessionId, signal);
|
|
229
|
+
check();
|
|
230
|
+
return detach(result);
|
|
231
|
+
};
|
|
232
|
+
methods.start = async (raw) => {
|
|
233
|
+
check();
|
|
234
|
+
const input = parseStartSessionInput(raw);
|
|
235
|
+
const startedAt = Date.now();
|
|
236
|
+
try {
|
|
237
|
+
const result = await createStartSessionTool(options).execute(run.toolCallId ?? "", input, signal, void 0, void 0);
|
|
238
|
+
run.record?.({
|
|
239
|
+
name: "sessions.start",
|
|
240
|
+
tool: START_SESSION_TOOL_NAME,
|
|
241
|
+
args: { ...input },
|
|
242
|
+
ok: true,
|
|
243
|
+
ms: Date.now() - startedAt,
|
|
244
|
+
result
|
|
245
|
+
});
|
|
246
|
+
return detach(result.details);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
run.record?.({
|
|
249
|
+
name: "sessions.start",
|
|
250
|
+
tool: START_SESSION_TOOL_NAME,
|
|
251
|
+
args: { ...input },
|
|
252
|
+
ok: false,
|
|
253
|
+
ms: Date.now() - startedAt,
|
|
254
|
+
error: error instanceof Error ? error.message : String(error)
|
|
255
|
+
});
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
return methods;
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
//#endregion
|
|
13
264
|
//#region ../../core/po-web-security/src/services/nodeSealedChannel/index.ts
|
|
14
265
|
const CURVE = "prime256v1";
|
|
15
266
|
const CIPHER = "aes-256-gcm";
|
|
@@ -487,7 +738,7 @@ function verifyPeerRequest(config, request, body, now = Date.now()) {
|
|
|
487
738
|
const actual = Buffer.from(supplied);
|
|
488
739
|
return actual.byteLength === expected.byteLength && timingSafeEqual(actual, expected) ? peer : void 0;
|
|
489
740
|
}
|
|
490
|
-
function envelopeOf
|
|
741
|
+
function envelopeOf(value) {
|
|
491
742
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
492
743
|
const record = value;
|
|
493
744
|
return validId(record.sourceSessionId) && validId(record.targetSessionId) && typeof record.type === "string" && record.type !== "" ? {
|
|
@@ -498,7 +749,7 @@ function envelopeOf$1(value) {
|
|
|
498
749
|
} : void 0;
|
|
499
750
|
}
|
|
500
751
|
function parseSessionPeerEnvelope(value) {
|
|
501
|
-
return envelopeOf
|
|
752
|
+
return envelopeOf(value);
|
|
502
753
|
}
|
|
503
754
|
/** Adds asynchronous tunnel publication to a host-bound local communication endpoint. */
|
|
504
755
|
function createPeerCommunication(options) {
|
|
@@ -543,277 +794,133 @@ function createPeerCommunication(options) {
|
|
|
543
794
|
};
|
|
544
795
|
}
|
|
545
796
|
//#endregion
|
|
546
|
-
//#region ../../foundations/po-session/src/services/
|
|
547
|
-
const
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
const
|
|
561
|
-
const
|
|
562
|
-
const
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
if (!current) await options.groups.create(id, "session-group-bridge", members);
|
|
578
|
-
else {
|
|
579
|
-
if (current.ownerAuthority !== "session-group-bridge") throw new Error("Named group authority conflict.");
|
|
580
|
-
await options.groups.mutate({
|
|
581
|
-
groupId: id,
|
|
582
|
-
authority: current.ownerAuthority,
|
|
583
|
-
expectedRevision: current.revision,
|
|
584
|
-
add: members,
|
|
585
|
-
remove: current.members.filter((reference) => !members.includes(reference))
|
|
586
|
-
});
|
|
587
|
-
}
|
|
588
|
-
knownGroups.add(id);
|
|
589
|
-
}
|
|
590
|
-
changed();
|
|
797
|
+
//#region ../../foundations/po-session/src/services/sessionDirectory/index.ts
|
|
798
|
+
const UNKNOWN_FACTS = Object.freeze({
|
|
799
|
+
reachability: "unknown",
|
|
800
|
+
runtime: "unknown",
|
|
801
|
+
activity: "unknown",
|
|
802
|
+
voice: Object.freeze({
|
|
803
|
+
eligible: "unknown",
|
|
804
|
+
readiness: "unknown"
|
|
805
|
+
})
|
|
806
|
+
});
|
|
807
|
+
function keyOf(observation) {
|
|
808
|
+
return peerSessionReference(observation.hostId, observation.sessionId);
|
|
809
|
+
}
|
|
810
|
+
function publicEntry(observation, now, label, capabilities) {
|
|
811
|
+
const freshUntil = observation.observedAt + observation.staleAfterMs;
|
|
812
|
+
const fresh = now <= freshUntil;
|
|
813
|
+
const facts = fresh ? observation : UNKNOWN_FACTS;
|
|
814
|
+
return Object.freeze({
|
|
815
|
+
reference: keyOf(observation),
|
|
816
|
+
...label === void 0 ? {} : { label },
|
|
817
|
+
capabilities: Object.freeze([...capabilities]),
|
|
818
|
+
hostIncarnation: observation.hostIncarnation,
|
|
819
|
+
sessionIncarnation: observation.sessionIncarnation,
|
|
820
|
+
sequence: observation.sequence,
|
|
821
|
+
observedAt: observation.observedAt,
|
|
822
|
+
freshUntil,
|
|
823
|
+
fresh,
|
|
824
|
+
reachability: facts.reachability,
|
|
825
|
+
runtime: facts.runtime,
|
|
826
|
+
activity: facts.activity,
|
|
827
|
+
voice: Object.freeze({ ...facts.voice })
|
|
591
828
|
});
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
timer = void 0;
|
|
608
|
-
} else if (timer === void 0) {
|
|
609
|
-
timer = setInterval(() => {
|
|
610
|
-
refresh().catch(options.onError);
|
|
611
|
-
}, 6e4);
|
|
612
|
-
timer.unref?.();
|
|
829
|
+
}
|
|
830
|
+
/** In-memory authenticated presence cache. Restart deliberately forgets every observation. */
|
|
831
|
+
function createSessionDirectory(options) {
|
|
832
|
+
const now = options.now ?? Date.now;
|
|
833
|
+
const observations = /* @__PURE__ */ new Map();
|
|
834
|
+
const snapshotRequired = /* @__PURE__ */ new Set();
|
|
835
|
+
const subscribers = /* @__PURE__ */ new Set();
|
|
836
|
+
const discover = async (callerReference, allowedReferences) => {
|
|
837
|
+
const result = [];
|
|
838
|
+
for (const observation of Array.from(observations.values())) {
|
|
839
|
+
const reference = keyOf(observation);
|
|
840
|
+
if (allowedReferences && !allowedReferences.has(reference)) continue;
|
|
841
|
+
const grant = await options.authorizeDiscovery(callerReference, observation);
|
|
842
|
+
if (!grant) continue;
|
|
843
|
+
result.push(publicEntry(observation, now(), grant.label ?? observation.label, grant.capabilities));
|
|
613
844
|
}
|
|
845
|
+
return result.sort((left, right) => left.reference.localeCompare(right.reference));
|
|
614
846
|
};
|
|
615
|
-
const
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
const
|
|
619
|
-
if (
|
|
620
|
-
|
|
621
|
-
const normalized = [...new Set(groups.map(normalizeSessionGroupName).filter(Boolean))];
|
|
622
|
-
const current = snapshots.get(hostId)?.find((member) => member.reference === reference);
|
|
623
|
-
if (current?.name === clean(name) && JSON.stringify(current.groups) === JSON.stringify(normalized)) return;
|
|
624
|
-
snapshots.set(hostId, [...(snapshots.get(hostId) ?? []).filter((member) => member.reference !== reference), {
|
|
625
|
-
reference,
|
|
626
|
-
name: clean(name),
|
|
627
|
-
groups: normalized
|
|
628
|
-
}]);
|
|
629
|
-
await mirror();
|
|
630
|
-
await refresh();
|
|
631
|
-
},
|
|
632
|
-
async removeLocal(sessionId) {
|
|
633
|
-
const hostId = localHost();
|
|
634
|
-
if (!hostId) return;
|
|
635
|
-
snapshots.set(hostId, (snapshots.get(hostId) ?? []).filter((member) => parseRemoteSessionReference(member.reference)?.sessionId !== sessionId));
|
|
636
|
-
await mirror();
|
|
637
|
-
await refresh();
|
|
638
|
-
},
|
|
639
|
-
async merge(hostId, value) {
|
|
640
|
-
if (!linked(hostId) || !Array.isArray(value) || value.length > 256) return false;
|
|
641
|
-
const members = [];
|
|
642
|
-
const references = /* @__PURE__ */ new Set();
|
|
643
|
-
for (const candidate of value) {
|
|
644
|
-
if (!candidate || typeof candidate !== "object") return false;
|
|
645
|
-
const member = candidate;
|
|
646
|
-
if (typeof member.reference !== "string" || parseRemoteSessionReference(member.reference)?.hostId !== hostId || references.has(member.reference) || typeof member.name !== "string" || member.name.length > 256 || !Array.isArray(member.groups) || member.groups.length > 64 || member.groups.some((name) => typeof name !== "string" || !normalizeSessionGroupName(name) || name.length > 256)) return false;
|
|
647
|
-
references.add(member.reference);
|
|
648
|
-
members.push({
|
|
649
|
-
reference: member.reference,
|
|
650
|
-
name: clean(member.name),
|
|
651
|
-
groups: [...new Set(member.groups.map(normalizeSessionGroupName))]
|
|
652
|
-
});
|
|
653
|
-
}
|
|
654
|
-
snapshots.set(hostId, members);
|
|
655
|
-
await mirror();
|
|
656
|
-
return true;
|
|
657
|
-
},
|
|
658
|
-
advert: () => snapshots.get(localHost() ?? "") ?? [],
|
|
659
|
-
peersFor(sessionId) {
|
|
660
|
-
const own = snapshots.get(localHost() ?? "")?.find((member) => parseRemoteSessionReference(member.reference)?.sessionId === sessionId);
|
|
661
|
-
if (!own) return [];
|
|
662
|
-
return entries().filter((member) => parseRemoteSessionReference(member.reference)?.hostId !== localHost()).flatMap((member) => {
|
|
663
|
-
const sharedGroups = own.groups.filter((name) => member.groups.includes(name));
|
|
664
|
-
const hostId = parseRemoteSessionReference(member.reference).hostId;
|
|
665
|
-
return sharedGroups.length ? [{
|
|
666
|
-
sessionId: member.reference,
|
|
667
|
-
name: `${clean(hostId)}/${member.name || parseRemoteSessionReference(member.reference).sessionId}`,
|
|
668
|
-
sharedGroups
|
|
669
|
-
}] : [];
|
|
670
|
-
});
|
|
671
|
-
},
|
|
672
|
-
metadataFor(sessionId, target) {
|
|
673
|
-
const peer = api.peersFor(sessionId).find((member) => member.sessionId === target);
|
|
674
|
-
const hostId = localHost();
|
|
675
|
-
if (!peer || !hostId) return void 0;
|
|
676
|
-
return {
|
|
677
|
-
sourceReference: peerSessionReference(hostId, sessionId),
|
|
678
|
-
targetReference: target,
|
|
679
|
-
groupId: namedSessionGroupId(peer.sharedGroups[0])
|
|
680
|
-
};
|
|
681
|
-
},
|
|
682
|
-
subscribe(listener) {
|
|
683
|
-
listeners.add(listener);
|
|
684
|
-
return () => {
|
|
685
|
-
listeners.delete(listener);
|
|
686
|
-
};
|
|
687
|
-
},
|
|
688
|
-
refresh,
|
|
689
|
-
async close() {
|
|
690
|
-
closed = true;
|
|
691
|
-
syncRefreshTimer();
|
|
692
|
-
releasePeers();
|
|
693
|
-
await serialize(async () => void 0);
|
|
694
|
-
listeners.clear();
|
|
695
|
-
await options.groups.close();
|
|
696
|
-
}
|
|
847
|
+
const push = (subscriber) => {
|
|
848
|
+
subscriber.queue = subscriber.queue.then(async () => {
|
|
849
|
+
if (!subscribers.has(subscriber)) return;
|
|
850
|
+
const sessions = await discover(subscriber.callerReference);
|
|
851
|
+
if (subscribers.has(subscriber)) subscriber.listener(sessions);
|
|
852
|
+
}).catch(() => void 0);
|
|
697
853
|
};
|
|
698
|
-
const
|
|
699
|
-
|
|
700
|
-
for (const hostId of snapshots.keys()) if (hostId !== localHost() && !linked(hostId)) snapshots.delete(hostId);
|
|
701
|
-
changed();
|
|
702
|
-
mirror().then(refresh).catch(options.onError);
|
|
703
|
-
});
|
|
704
|
-
syncRefreshTimer();
|
|
705
|
-
return api;
|
|
706
|
-
}
|
|
707
|
-
function readSessionGroupBridge(context) {
|
|
708
|
-
return context.get(PO_SESSION_GROUP_BRIDGE_SERVICE);
|
|
709
|
-
}
|
|
710
|
-
//#endregion
|
|
711
|
-
//#region ../../foundations/po-session/src/services/sessionGroups/type.ts
|
|
712
|
-
var SessionGroupRevisionError = class extends Error {
|
|
713
|
-
constructor(groupId, expected, actual) {
|
|
714
|
-
super(`Session group '${groupId}' revision conflict: expected ${expected}, current ${actual}.`);
|
|
715
|
-
this.name = "SessionGroupRevisionError";
|
|
716
|
-
}
|
|
717
|
-
};
|
|
718
|
-
//#endregion
|
|
719
|
-
//#region ../../foundations/po-session/src/services/sessionGroups/index.ts
|
|
720
|
-
const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
721
|
-
const REFERENCE_PATTERN = /^peer\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
722
|
-
function validateGroupId(value) {
|
|
723
|
-
if (!ID_PATTERN.test(value)) throw new TypeError("Session group IDs must be safe opaque IDs.");
|
|
724
|
-
}
|
|
725
|
-
function validateReference(value) {
|
|
726
|
-
if (!REFERENCE_PATTERN.test(value)) throw new TypeError(`Session group member '${value}' is not a qualified reference.`);
|
|
727
|
-
}
|
|
728
|
-
const SCHEMA$1 = `
|
|
729
|
-
CREATE TABLE IF NOT EXISTS session_groups (
|
|
730
|
-
group_id TEXT PRIMARY KEY,
|
|
731
|
-
owner_authority TEXT NOT NULL,
|
|
732
|
-
revision INTEGER NOT NULL
|
|
733
|
-
);
|
|
734
|
-
CREATE TABLE IF NOT EXISTS session_group_members (
|
|
735
|
-
group_id TEXT NOT NULL REFERENCES session_groups(group_id) ON DELETE CASCADE,
|
|
736
|
-
member_reference TEXT NOT NULL,
|
|
737
|
-
PRIMARY KEY (group_id, member_reference)
|
|
738
|
-
);
|
|
739
|
-
`;
|
|
740
|
-
async function readGroup(database, groupId) {
|
|
741
|
-
const row = await database.get("SELECT * FROM session_groups WHERE group_id = ?", groupId);
|
|
742
|
-
if (!row) return void 0;
|
|
743
|
-
const members = await database.all("SELECT member_reference FROM session_group_members WHERE group_id = ? ORDER BY member_reference", groupId);
|
|
744
|
-
return Object.freeze({
|
|
745
|
-
id: row.group_id,
|
|
746
|
-
ownerAuthority: row.owner_authority,
|
|
747
|
-
revision: Number(row.revision),
|
|
748
|
-
members: Object.freeze(members.map((member) => member.member_reference))
|
|
749
|
-
});
|
|
750
|
-
}
|
|
751
|
-
/** Opens a revisioned SQLite registry for communication-only group membership. */
|
|
752
|
-
async function createSessionGroupStore(options) {
|
|
753
|
-
const { database } = options;
|
|
754
|
-
try {
|
|
755
|
-
await database.exec("PRAGMA foreign_keys = ON");
|
|
756
|
-
} catch {}
|
|
757
|
-
await database.exec(SCHEMA$1);
|
|
758
|
-
const enroll = async (transaction, groupId, members) => {
|
|
759
|
-
for (const member of new Set(members)) {
|
|
760
|
-
validateReference(member);
|
|
761
|
-
if (options.validateEnrollment?.(groupId, member) === false) throw new Error(`Session group enrollment policy rejected '${member}'.`);
|
|
762
|
-
await transaction.run("INSERT OR IGNORE INTO session_group_members (group_id, member_reference) VALUES (?, ?)", groupId, member);
|
|
763
|
-
}
|
|
854
|
+
const notify = () => {
|
|
855
|
+
for (const subscriber of subscribers) push(subscriber);
|
|
764
856
|
};
|
|
765
857
|
return {
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
for (const member of new Set(mutation.remove ?? [])) {
|
|
783
|
-
validateReference(member);
|
|
784
|
-
await transaction.run("DELETE FROM session_group_members WHERE group_id = ? AND member_reference = ?", mutation.groupId, member);
|
|
858
|
+
observe(observation) {
|
|
859
|
+
const key = keyOf(observation);
|
|
860
|
+
const current = observations.get(key);
|
|
861
|
+
if (snapshotRequired.has(observation.hostId)) return false;
|
|
862
|
+
if (current?.hostIncarnation === observation.hostIncarnation) {
|
|
863
|
+
if (current.sessionIncarnation === observation.sessionIncarnation && observation.sequence <= current.sequence) return false;
|
|
864
|
+
if (observation.sequence !== current.sequence + 1) {
|
|
865
|
+
snapshotRequired.add(observation.hostId);
|
|
866
|
+
for (const [reference, candidate] of observations) if (candidate.hostId === observation.hostId) observations.set(reference, {
|
|
867
|
+
...candidate,
|
|
868
|
+
...UNKNOWN_FACTS,
|
|
869
|
+
observedAt: now(),
|
|
870
|
+
staleAfterMs: 0
|
|
871
|
+
});
|
|
872
|
+
notify();
|
|
873
|
+
return false;
|
|
785
874
|
}
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
875
|
+
}
|
|
876
|
+
observations.set(key, Object.freeze({
|
|
877
|
+
...observation,
|
|
878
|
+
voice: Object.freeze({ ...observation.voice })
|
|
879
|
+
}));
|
|
880
|
+
notify();
|
|
881
|
+
return true;
|
|
882
|
+
},
|
|
883
|
+
replaceHostSnapshot(hostId, hostIncarnation, replacements) {
|
|
884
|
+
if (replacements.some((observation) => observation.hostId !== hostId || observation.hostIncarnation !== hostIncarnation)) throw new TypeError("A presence snapshot must contain only the declared host incarnation.");
|
|
885
|
+
for (const [reference, observation] of observations) if (observation.hostId === hostId) observations.delete(reference);
|
|
886
|
+
for (const observation of replacements) observations.set(keyOf(observation), Object.freeze({
|
|
887
|
+
...observation,
|
|
888
|
+
voice: Object.freeze({ ...observation.voice })
|
|
889
|
+
}));
|
|
890
|
+
snapshotRequired.delete(hostId);
|
|
891
|
+
notify();
|
|
789
892
|
},
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
for (const row of rows) {
|
|
798
|
-
const group = await readGroup(database, row.group_id);
|
|
799
|
-
if (group) groups.push(group);
|
|
893
|
+
hostDisconnected(hostId) {
|
|
894
|
+
for (const [reference, observation] of observations) {
|
|
895
|
+
if (observation.hostId !== hostId) continue;
|
|
896
|
+
observations.set(reference, {
|
|
897
|
+
...observation,
|
|
898
|
+
reachability: "unreachable"
|
|
899
|
+
});
|
|
800
900
|
}
|
|
801
|
-
|
|
901
|
+
notify();
|
|
802
902
|
},
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
WHERE group_id = ? AND member_reference IN (?, ?)`, groupId, sourceReference, targetReference);
|
|
808
|
-
return Number(row?.count ?? 0) === (sourceReference === targetReference ? 1 : 2);
|
|
903
|
+
discover,
|
|
904
|
+
async resolveDeliveryTarget(callerReference, reference) {
|
|
905
|
+
const observation = observations.get(reference);
|
|
906
|
+
return observation && await options.authorizeDiscovery(callerReference, observation) ? observation.deliveryTarget : void 0;
|
|
809
907
|
},
|
|
810
|
-
|
|
908
|
+
subscribe(callerReference, listener) {
|
|
909
|
+
const subscriber = {
|
|
910
|
+
callerReference,
|
|
911
|
+
listener,
|
|
912
|
+
queue: Promise.resolve()
|
|
913
|
+
};
|
|
914
|
+
subscribers.add(subscriber);
|
|
915
|
+
push(subscriber);
|
|
916
|
+
return () => subscribers.delete(subscriber);
|
|
917
|
+
}
|
|
811
918
|
};
|
|
812
919
|
}
|
|
813
920
|
//#endregion
|
|
814
921
|
//#region ../../foundations/po-session/src/services/sessionPeers/index.ts
|
|
815
922
|
const PO_SESSION_PEERS_SERVICE = "po/session-peers";
|
|
816
|
-
const PO_SESSION_PEERS_CONTRACT = defineServiceContract(PO_SESSION_PEERS_SERVICE, { scope: "
|
|
923
|
+
const PO_SESSION_PEERS_CONTRACT = defineServiceContract(PO_SESSION_PEERS_SERVICE, { scope: "host" });
|
|
817
924
|
/** Link URLs are routing hints, never identity or authorization. */
|
|
818
925
|
function peerOrigin(value) {
|
|
819
926
|
const url = new URL(value);
|
|
@@ -868,909 +975,49 @@ async function createSessionPeers(options) {
|
|
|
868
975
|
hostId,
|
|
869
976
|
linkGeneration
|
|
870
977
|
}]
|
|
871
|
-
});
|
|
872
|
-
}),
|
|
873
|
-
rebind: (hostId, url, urlGeneration) => serialize(async () => {
|
|
874
|
-
const config = initial();
|
|
875
|
-
const peer = config.peers.find((entry) => entry.hostId === hostId);
|
|
876
|
-
if (!peer || !Number.isSafeInteger(urlGeneration) || urlGeneration <= (peer.urlGeneration ?? 0)) return false;
|
|
877
|
-
const origin = peerOrigin(url);
|
|
878
|
-
await write({
|
|
879
|
-
...config,
|
|
880
|
-
peers: config.peers.map((entry) => entry === peer ? {
|
|
881
|
-
...peer,
|
|
882
|
-
url: origin,
|
|
883
|
-
urlGeneration
|
|
884
|
-
} : entry)
|
|
885
|
-
});
|
|
886
|
-
return true;
|
|
887
|
-
}),
|
|
888
|
-
announce: (url) => serialize(async () => {
|
|
889
|
-
const config = initial();
|
|
890
|
-
const announcedUrl = peerOrigin(url);
|
|
891
|
-
if (config.self?.announcedUrl !== announcedUrl) await write({
|
|
892
|
-
...config,
|
|
893
|
-
self: {
|
|
894
|
-
announcedUrl,
|
|
895
|
-
urlGeneration: (config.self?.urlGeneration ?? 0) + 1
|
|
896
|
-
}
|
|
897
|
-
});
|
|
898
|
-
return structuredClone(current);
|
|
899
|
-
}),
|
|
900
|
-
subscribe(listener) {
|
|
901
|
-
listeners.add(listener);
|
|
902
|
-
return () => {
|
|
903
|
-
listeners.delete(listener);
|
|
904
|
-
};
|
|
905
|
-
}
|
|
906
|
-
};
|
|
907
|
-
}
|
|
908
|
-
function requireSessionPeers(context) {
|
|
909
|
-
const service = context.get(PO_SESSION_PEERS_SERVICE);
|
|
910
|
-
if (!service) throw new Error("The host links service is unavailable.");
|
|
911
|
-
return service;
|
|
912
|
-
}
|
|
913
|
-
//#endregion
|
|
914
|
-
//#region ../../foundations/po-session/src/extensions/(backend)/root.server.ts
|
|
915
|
-
var root_server_default$1 = defineRoot((plugin) => ({
|
|
916
|
-
value: void 0,
|
|
917
|
-
services: [async (context) => {
|
|
918
|
-
await context.inject([
|
|
919
|
-
PO_FS_SERVICE,
|
|
920
|
-
PO_SQLITE_SERVICE,
|
|
921
|
-
PO_SERVER_SCOPE_SERVICE
|
|
922
|
-
], async (scoped) => {
|
|
923
|
-
const homeDirectory = plugin.host.context.homeDirectory;
|
|
924
|
-
if (!homeDirectory) throw new Error("Host links require an explicit host home directory.");
|
|
925
|
-
const peers = await createSessionPeers({
|
|
926
|
-
fs: requirePoFs(scoped),
|
|
927
|
-
homeDirectory
|
|
928
|
-
});
|
|
929
|
-
await peers.identity();
|
|
930
|
-
const directory = path.join(poHomeDirectory(homeDirectory), "session");
|
|
931
|
-
await ensurePrivateDirectory(requirePoFs(scoped), directory, BACKGROUND_CONTEXT);
|
|
932
|
-
const database = await requirePoSqlite(scoped).open(path.join(directory, "groups.sqlite"), BACKGROUND_CONTEXT);
|
|
933
|
-
const groups = await createSessionGroupStore({ database });
|
|
934
|
-
await database.run("DELETE FROM session_group_members WHERE group_id IN (SELECT group_id FROM session_groups WHERE owner_authority = 'session-group-bridge')");
|
|
935
|
-
await database.run("DELETE FROM session_groups WHERE owner_authority = 'session-group-bridge'");
|
|
936
|
-
const bridge = createSessionGroupBridge({
|
|
937
|
-
groups,
|
|
938
|
-
peers,
|
|
939
|
-
onError: (error) => plugin.host.context.onNotice(`Group bridge failed: ${String(error)}`),
|
|
940
|
-
send: async (hostId, advert) => {
|
|
941
|
-
const config = peers.current();
|
|
942
|
-
const peer = config?.peers.find((entry) => entry.hostId === hostId);
|
|
943
|
-
if (!config || !peer) return;
|
|
944
|
-
await authenticatedPeerPost({
|
|
945
|
-
config,
|
|
946
|
-
peer,
|
|
947
|
-
path: "/api/plugins/session-peer/control",
|
|
948
|
-
value: {
|
|
949
|
-
type: "groups",
|
|
950
|
-
groups: advert
|
|
951
|
-
}
|
|
952
|
-
});
|
|
953
|
-
}
|
|
954
|
-
});
|
|
955
|
-
const scope = requirePoServerScope(scoped);
|
|
956
|
-
const releasePeers = plugin.host.scope === "global" ? await scope.provide(PO_SESSION_PEERS_CONTRACT, peers) : scoped.provide(PO_SESSION_PEERS_SERVICE, peers);
|
|
957
|
-
let releaseBridge;
|
|
958
|
-
try {
|
|
959
|
-
releaseBridge = plugin.host.scope === "global" ? await scope.provide(PO_SESSION_GROUP_BRIDGE_CONTRACT, bridge) : scoped.provide(PO_SESSION_GROUP_BRIDGE_SERVICE, bridge);
|
|
960
|
-
} catch (error) {
|
|
961
|
-
await Promise.resolve(releasePeers());
|
|
962
|
-
await bridge.close();
|
|
963
|
-
throw error;
|
|
964
|
-
}
|
|
965
|
-
return async () => {
|
|
966
|
-
await releaseBridge();
|
|
967
|
-
await Promise.resolve(releasePeers());
|
|
968
|
-
await bridge.close();
|
|
969
|
-
};
|
|
970
|
-
});
|
|
971
|
-
}]
|
|
972
|
-
}));
|
|
973
|
-
//#endregion
|
|
974
|
-
//#region ../../foundations/po-session/src/services/backgroundWorkService/index.ts
|
|
975
|
-
/** Creates the generation-bound, pull-based coordinator shared by session extensions. */
|
|
976
|
-
function createBackgroundWorkService(ctx) {
|
|
977
|
-
const registrations = /* @__PURE__ */ new Map();
|
|
978
|
-
const generation = `po-background-work:${crypto.randomUUID()}`;
|
|
979
|
-
const changed = (provider, providerGeneration, kind) => {
|
|
980
|
-
ctx.emit(PO_BACKGROUND_WORK_CHANGED_EVENT, {
|
|
981
|
-
provider,
|
|
982
|
-
generation: providerGeneration,
|
|
983
|
-
kind
|
|
984
|
-
});
|
|
985
|
-
};
|
|
986
|
-
return Object.freeze({
|
|
987
|
-
generation,
|
|
988
|
-
register(provider) {
|
|
989
|
-
if (!provider || typeof provider !== "object" || typeof provider.listActiveWork !== "function") throw new TypeError("A background-work provider must expose listActiveWork().");
|
|
990
|
-
const name = provider.provider.trim();
|
|
991
|
-
if (!name || name !== provider.provider) throw new TypeError("A background-work provider requires a trimmed, non-empty name.");
|
|
992
|
-
const token = Symbol(name);
|
|
993
|
-
const providerGeneration = `${name}:${crypto.randomUUID()}`;
|
|
994
|
-
registrations.set(name, {
|
|
995
|
-
token,
|
|
996
|
-
generation: providerGeneration,
|
|
997
|
-
provider
|
|
998
|
-
});
|
|
999
|
-
changed(name, providerGeneration, "registered");
|
|
1000
|
-
let disposed = false;
|
|
1001
|
-
return Object.freeze({
|
|
1002
|
-
provider: name,
|
|
1003
|
-
generation: providerGeneration,
|
|
1004
|
-
update() {
|
|
1005
|
-
if (!disposed && registrations.get(name)?.token === token) changed(name, providerGeneration, "updated");
|
|
1006
|
-
},
|
|
1007
|
-
dispose() {
|
|
1008
|
-
if (disposed) return;
|
|
1009
|
-
disposed = true;
|
|
1010
|
-
if (registrations.get(name)?.token !== token) return;
|
|
1011
|
-
registrations.delete(name);
|
|
1012
|
-
changed(name, providerGeneration, "unregistered");
|
|
1013
|
-
}
|
|
1014
|
-
});
|
|
1015
|
-
},
|
|
1016
|
-
snapshot(sessionId) {
|
|
1017
|
-
const items = [];
|
|
1018
|
-
const errors = [];
|
|
1019
|
-
for (const [provider, registration] of registrations) try {
|
|
1020
|
-
const current = registration.provider.listActiveWork();
|
|
1021
|
-
if (!Array.isArray(current)) throw new TypeError("listActiveWork() must return an array.");
|
|
1022
|
-
for (const item of current) {
|
|
1023
|
-
if (!Check(BackgroundProviderWorkItemSchema, item)) throw new TypeError("listActiveWork() returned an invalid item.");
|
|
1024
|
-
if (sessionId === void 0 || item.sessionId === sessionId) items.push({
|
|
1025
|
-
provider,
|
|
1026
|
-
...item
|
|
1027
|
-
});
|
|
1028
|
-
}
|
|
1029
|
-
} catch (error) {
|
|
1030
|
-
errors.push({
|
|
1031
|
-
provider,
|
|
1032
|
-
message: error instanceof Error ? error.message : String(error)
|
|
1033
|
-
});
|
|
1034
|
-
}
|
|
1035
|
-
return Object.freeze({
|
|
1036
|
-
items: Object.freeze(items),
|
|
1037
|
-
errors: Object.freeze(errors)
|
|
1038
|
-
});
|
|
1039
|
-
}
|
|
1040
|
-
});
|
|
1041
|
-
}
|
|
1042
|
-
/** Installs one coordinator in the current session service context. */
|
|
1043
|
-
function provideBackgroundWorkService(context) {
|
|
1044
|
-
context.provide(PO_BACKGROUND_WORK_SERVICE, createBackgroundWorkService(context));
|
|
1045
|
-
}
|
|
1046
|
-
//#endregion
|
|
1047
|
-
//#region ../../foundations/po-session/src/services/peerInbox/index.ts
|
|
1048
|
-
const inboxes = /* @__PURE__ */ new Map();
|
|
1049
|
-
/**
|
|
1050
|
-
* Registers one live session-owned peer inbox. This registry is reachable only by the Session route.
|
|
1051
|
-
* The newest registration wins: a Durable Object evicted without disposal leaves its entry in the
|
|
1052
|
-
* isolate's module state, and the restarted session must replace it. The hub still rejects two live
|
|
1053
|
-
* sessions with one id, and an older unregister cannot remove a newer inbox.
|
|
1054
|
-
*/
|
|
1055
|
-
function registerSessionPeerInbox(sessionId, inbox) {
|
|
1056
|
-
inboxes.set(sessionId, inbox);
|
|
1057
|
-
return () => {
|
|
1058
|
-
if (inboxes.get(sessionId) === inbox) inboxes.delete(sessionId);
|
|
1059
|
-
};
|
|
1060
|
-
}
|
|
1061
|
-
async function deliverSessionPeerEnvelope(targetSessionId, sourceKey, type, payload) {
|
|
1062
|
-
return inboxes.get(targetSessionId)?.(sourceKey, type, payload);
|
|
1063
|
-
}
|
|
1064
|
-
//#endregion
|
|
1065
|
-
//#region ../../foundations/po-session/src/services/sessionDelivery/type.ts
|
|
1066
|
-
const PO_SESSION_DELIVERY_SERVICE = "po/session-delivery";
|
|
1067
|
-
//#endregion
|
|
1068
|
-
//#region ../../foundations/po-session/src/services/sessionDelivery/index.ts
|
|
1069
|
-
const DELIVERY_EVENT = "po/session-delivery/envelope";
|
|
1070
|
-
const ACK_EVENT = "po/session-delivery/ack";
|
|
1071
|
-
const DEFAULT_DELIVERY = "prompt";
|
|
1072
|
-
const INBOX_STATES = /* @__PURE__ */ new Set([
|
|
1073
|
-
"accepted",
|
|
1074
|
-
"admitting",
|
|
1075
|
-
"admitted",
|
|
1076
|
-
"recovery_required",
|
|
1077
|
-
"revoked"
|
|
1078
|
-
]);
|
|
1079
|
-
function isRecord(value) {
|
|
1080
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1081
|
-
}
|
|
1082
|
-
function isMode(value) {
|
|
1083
|
-
return value === "prompt" || value === "steer" || value === "followUp";
|
|
1084
|
-
}
|
|
1085
|
-
function metadataOf(value) {
|
|
1086
|
-
if (!isRecord(value)) return void 0;
|
|
1087
|
-
const metadata = {};
|
|
1088
|
-
for (const [key, item] of Object.entries(value)) {
|
|
1089
|
-
if (typeof item !== "string") return void 0;
|
|
1090
|
-
metadata[key] = item;
|
|
1091
|
-
}
|
|
1092
|
-
return metadata;
|
|
1093
|
-
}
|
|
1094
|
-
function envelopeOf(value) {
|
|
1095
|
-
if (!isRecord(value)) return void 0;
|
|
1096
|
-
const metadata = metadataOf(value.metadata);
|
|
1097
|
-
if (typeof value.deliveryId !== "string" || !value.deliveryId || typeof value.kind !== "string" || !value.kind || typeof value.prompt !== "string" || !isMode(value.delivery) || metadata === void 0) return;
|
|
1098
|
-
return {
|
|
1099
|
-
deliveryId: value.deliveryId,
|
|
1100
|
-
kind: value.kind,
|
|
1101
|
-
prompt: value.prompt,
|
|
1102
|
-
delivery: value.delivery,
|
|
1103
|
-
metadata
|
|
1104
|
-
};
|
|
1105
|
-
}
|
|
1106
|
-
function ackOf(value) {
|
|
1107
|
-
if (!isRecord(value)) return void 0;
|
|
1108
|
-
if (typeof value.deliveryId !== "string" || typeof value.state !== "string" || !INBOX_STATES.has(value.state)) return;
|
|
1109
|
-
return value;
|
|
1110
|
-
}
|
|
1111
|
-
function normalizedMetadata(metadata) {
|
|
1112
|
-
const normalized = {};
|
|
1113
|
-
for (const [key, value] of Object.entries(metadata ?? {})) if (value !== void 0) normalized[key] = value;
|
|
1114
|
-
return normalized;
|
|
1115
|
-
}
|
|
1116
|
-
function matchesMetadata(entry, query) {
|
|
1117
|
-
return Object.entries(query ?? {}).every(([key, value]) => value === void 0 || entry[key] === value);
|
|
1118
|
-
}
|
|
1119
|
-
function sameMetadata(left, right) {
|
|
1120
|
-
return matchesMetadata(left, right) && matchesMetadata(right, left);
|
|
1121
|
-
}
|
|
1122
|
-
const SCHEMA = `
|
|
1123
|
-
CREATE TABLE IF NOT EXISTS session_delivery_outbox (
|
|
1124
|
-
delivery_id TEXT PRIMARY KEY,
|
|
1125
|
-
recipient_key TEXT NOT NULL,
|
|
1126
|
-
kind TEXT NOT NULL,
|
|
1127
|
-
prompt TEXT NOT NULL,
|
|
1128
|
-
delivery_mode TEXT NOT NULL,
|
|
1129
|
-
metadata_json TEXT NOT NULL,
|
|
1130
|
-
state TEXT NOT NULL,
|
|
1131
|
-
recipient_state TEXT,
|
|
1132
|
-
created_at INTEGER NOT NULL,
|
|
1133
|
-
acknowledged_at INTEGER
|
|
1134
|
-
);
|
|
1135
|
-
CREATE TABLE IF NOT EXISTS session_delivery_inbox (
|
|
1136
|
-
delivery_id TEXT PRIMARY KEY,
|
|
1137
|
-
sender_key TEXT NOT NULL,
|
|
1138
|
-
recipient_key TEXT NOT NULL,
|
|
1139
|
-
kind TEXT NOT NULL,
|
|
1140
|
-
prompt TEXT NOT NULL,
|
|
1141
|
-
delivery_mode TEXT NOT NULL,
|
|
1142
|
-
metadata_json TEXT NOT NULL,
|
|
1143
|
-
state TEXT NOT NULL,
|
|
1144
|
-
created_at INTEGER NOT NULL,
|
|
1145
|
-
updated_at INTEGER NOT NULL,
|
|
1146
|
-
consumed_at INTEGER
|
|
1147
|
-
);
|
|
1148
|
-
`;
|
|
1149
|
-
const SET_INBOX_STATE = "UPDATE session_delivery_inbox SET state = ?, updated_at = ? WHERE delivery_id = ?";
|
|
1150
|
-
const UNSETTLED_OUTBOX = "state != 'revoked' AND (recipient_state IS NULL OR recipient_state NOT IN ('admitted', 'recovery_required', 'revoked'))";
|
|
1151
|
-
/** Opens and starts one durable delivery endpoint. */
|
|
1152
|
-
async function createSessionDeliveryService(options) {
|
|
1153
|
-
if (!options.recipientKey.trim() || options.recipientKey !== options.recipientKey.trim()) throw new TypeError("Session delivery requires a trimmed, non-empty recipient key.");
|
|
1154
|
-
const database = options.database;
|
|
1155
|
-
try {
|
|
1156
|
-
await database.exec(SCHEMA);
|
|
1157
|
-
await database.run("UPDATE session_delivery_inbox SET state = 'accepted', updated_at = ? WHERE state = 'admitting'", Date.now());
|
|
1158
|
-
} catch (error) {
|
|
1159
|
-
await database.close();
|
|
1160
|
-
throw error;
|
|
1161
|
-
}
|
|
1162
|
-
let closed = false;
|
|
1163
|
-
const scheduled = /* @__PURE__ */ new Set();
|
|
1164
|
-
let admissionQueue = Promise.resolve();
|
|
1165
|
-
const pending = /* @__PURE__ */ new Set();
|
|
1166
|
-
/** Tracks fire-and-forget work so close() can wait for it before the database closes. */
|
|
1167
|
-
const track = (work) => {
|
|
1168
|
-
const settled = work.catch(() => void 0);
|
|
1169
|
-
pending.add(settled);
|
|
1170
|
-
settled.finally(() => pending.delete(settled));
|
|
1171
|
-
};
|
|
1172
|
-
const authorized = async (peerKey, metadata) => await options.authorizePeer(peerKey, metadata) === true;
|
|
1173
|
-
const publishAck = (deliveryId, senderKey, state) => {
|
|
1174
|
-
options.communication.publish(senderKey, ACK_EVENT, {
|
|
1175
|
-
deliveryId,
|
|
1176
|
-
state
|
|
1177
|
-
});
|
|
1178
|
-
};
|
|
1179
|
-
const readInboxRow = (deliveryId) => database.get("SELECT * FROM session_delivery_inbox WHERE delivery_id = ?", deliveryId);
|
|
1180
|
-
const scheduleAdmission = (deliveryId) => {
|
|
1181
|
-
if (closed || scheduled.has(deliveryId)) return;
|
|
1182
|
-
scheduled.add(deliveryId);
|
|
1183
|
-
admissionQueue = admissionQueue.then(async () => {
|
|
1184
|
-
try {
|
|
1185
|
-
if (closed) return;
|
|
1186
|
-
const row = await database.get("UPDATE session_delivery_inbox SET state = 'admitting', updated_at = ? WHERE delivery_id = ? AND state = 'accepted' RETURNING *", Date.now(), deliveryId);
|
|
1187
|
-
if (!row) return;
|
|
1188
|
-
publishAck(deliveryId, row.sender_key, "admitting");
|
|
1189
|
-
try {
|
|
1190
|
-
if (!await authorized(row.sender_key, JSON.parse(row.metadata_json))) {
|
|
1191
|
-
await database.run(SET_INBOX_STATE, "revoked", Date.now(), deliveryId);
|
|
1192
|
-
publishAck(deliveryId, row.sender_key, "revoked");
|
|
1193
|
-
return;
|
|
1194
|
-
}
|
|
1195
|
-
await options.admitPrompt(row.prompt, row.delivery_mode, deliveryId, JSON.parse(row.metadata_json));
|
|
1196
|
-
} catch {
|
|
1197
|
-
await database.run(SET_INBOX_STATE, "recovery_required", Date.now(), deliveryId);
|
|
1198
|
-
publishAck(deliveryId, row.sender_key, "recovery_required");
|
|
1199
|
-
return;
|
|
1200
|
-
}
|
|
1201
|
-
await database.run(SET_INBOX_STATE, "admitted", Date.now(), deliveryId);
|
|
1202
|
-
publishAck(deliveryId, row.sender_key, "admitted");
|
|
1203
|
-
} finally {
|
|
1204
|
-
scheduled.delete(deliveryId);
|
|
1205
|
-
}
|
|
1206
|
-
}).catch(async () => {
|
|
1207
|
-
scheduled.delete(deliveryId);
|
|
1208
|
-
try {
|
|
1209
|
-
const row = await readInboxRow(deliveryId);
|
|
1210
|
-
if (row?.state !== "admitting") return;
|
|
1211
|
-
await database.run(SET_INBOX_STATE, "recovery_required", Date.now(), deliveryId);
|
|
1212
|
-
try {
|
|
1213
|
-
publishAck(deliveryId, row.sender_key, "recovery_required");
|
|
1214
|
-
} catch {}
|
|
1215
|
-
} catch {}
|
|
1216
|
-
});
|
|
1217
|
-
};
|
|
1218
|
-
const receiveEnvelope = async (senderKey, value) => {
|
|
1219
|
-
if (closed) return void 0;
|
|
1220
|
-
const envelope = envelopeOf(value);
|
|
1221
|
-
if (!envelope || !await authorized(senderKey, envelope.metadata) || closed) return void 0;
|
|
1222
|
-
await database.run(`INSERT OR IGNORE INTO session_delivery_inbox
|
|
1223
|
-
(delivery_id, sender_key, recipient_key, kind, prompt, delivery_mode, metadata_json, state, created_at, updated_at)
|
|
1224
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, 'accepted', ?, ?)`, envelope.deliveryId, senderKey, options.recipientKey, envelope.kind, envelope.prompt, envelope.delivery, JSON.stringify(envelope.metadata), Date.now(), Date.now());
|
|
1225
|
-
const current = await readInboxRow(envelope.deliveryId);
|
|
1226
|
-
if (!current) return void 0;
|
|
1227
|
-
if (!(current.sender_key === senderKey && current.recipient_key === options.recipientKey && current.kind === envelope.kind && current.prompt === envelope.prompt && current.delivery_mode === envelope.delivery && sameMetadata(JSON.parse(current.metadata_json), envelope.metadata))) return void 0;
|
|
1228
|
-
publishAck(envelope.deliveryId, current.sender_key, current.state);
|
|
1229
|
-
if (current.state === "accepted") scheduleAdmission(envelope.deliveryId);
|
|
1230
|
-
return current.state;
|
|
1231
|
-
};
|
|
1232
|
-
const receiveAck = async (recipientKey, value) => {
|
|
1233
|
-
const ack = ackOf(value);
|
|
1234
|
-
if (closed || !ack) return;
|
|
1235
|
-
await database.run(`UPDATE session_delivery_outbox
|
|
1236
|
-
SET state = CASE WHEN ? = 'revoked' THEN 'revoked' ELSE 'acknowledged' END, recipient_state = ?, acknowledged_at = ?
|
|
1237
|
-
WHERE delivery_id = ? AND recipient_key = ? AND state != 'revoked'
|
|
1238
|
-
AND (recipient_state IS NULL
|
|
1239
|
-
OR (recipient_state = 'accepted' AND ? != 'accepted')
|
|
1240
|
-
OR (recipient_state = 'admitting' AND ? IN ('admitted', 'recovery_required', 'revoked')))`, ack.state, ack.state, Date.now(), ack.deliveryId, recipientKey, ack.state, ack.state);
|
|
1241
|
-
};
|
|
1242
|
-
const publishOutbox = async (deliveryId) => {
|
|
1243
|
-
if (closed) return;
|
|
1244
|
-
const row = await database.get(`SELECT * FROM session_delivery_outbox WHERE delivery_id = ? AND ${UNSETTLED_OUTBOX}`, deliveryId);
|
|
1245
|
-
if (!row) return;
|
|
1246
|
-
const metadata = JSON.parse(row.metadata_json);
|
|
1247
|
-
if (!await authorized(row.recipient_key, metadata)) {
|
|
1248
|
-
await database.run("UPDATE session_delivery_outbox SET state = 'revoked', recipient_state = 'revoked' WHERE delivery_id = ? AND " + UNSETTLED_OUTBOX, deliveryId);
|
|
1249
|
-
return;
|
|
1250
|
-
}
|
|
1251
|
-
if (closed) return;
|
|
1252
|
-
options.communication.publish(row.recipient_key, DELIVERY_EVENT, {
|
|
1253
|
-
deliveryId: row.delivery_id,
|
|
1254
|
-
kind: row.kind,
|
|
1255
|
-
prompt: row.prompt,
|
|
1256
|
-
delivery: row.delivery_mode,
|
|
1257
|
-
metadata
|
|
1258
|
-
});
|
|
1259
|
-
};
|
|
1260
|
-
const publishQueued = async (recipientKey) => {
|
|
1261
|
-
if (closed) return;
|
|
1262
|
-
for (const row of await database.all(`SELECT delivery_id FROM session_delivery_outbox WHERE recipient_key = ? AND ${UNSETTLED_OUTBOX}`, recipientKey)) await publishOutbox(row.delivery_id);
|
|
1263
|
-
};
|
|
1264
|
-
let retryTimer;
|
|
1265
|
-
const startRetry = () => {
|
|
1266
|
-
if (closed || retryTimer) return;
|
|
1267
|
-
retryTimer = setInterval$1(() => track(publishAllQueued()), 1e3);
|
|
1268
|
-
retryTimer.unref?.();
|
|
1269
|
-
};
|
|
1270
|
-
const stopRetry = () => {
|
|
1271
|
-
if (retryTimer) clearInterval$1(retryTimer);
|
|
1272
|
-
retryTimer = void 0;
|
|
1273
|
-
};
|
|
1274
|
-
let retrying;
|
|
1275
|
-
const publishAllQueued = () => {
|
|
1276
|
-
retrying ??= (async () => {
|
|
1277
|
-
try {
|
|
1278
|
-
if (closed) return;
|
|
1279
|
-
const rows = await database.all(`SELECT delivery_id FROM session_delivery_outbox WHERE ${UNSETTLED_OUTBOX}`);
|
|
1280
|
-
if (rows.length === 0) stopRetry();
|
|
1281
|
-
else startRetry();
|
|
1282
|
-
for (const row of rows) await publishOutbox(row.delivery_id);
|
|
1283
|
-
} finally {
|
|
1284
|
-
retrying = void 0;
|
|
1285
|
-
}
|
|
1286
|
-
})();
|
|
1287
|
-
return retrying;
|
|
1288
|
-
};
|
|
1289
|
-
const releaseEnvelope = options.communication.subscribe(DELIVERY_EVENT, (senderKey, payload) => {
|
|
1290
|
-
track(receiveEnvelope(senderKey, payload));
|
|
1291
|
-
});
|
|
1292
|
-
const releaseAck = options.communication.subscribe(ACK_EVENT, (recipientKey, payload) => {
|
|
1293
|
-
track(receiveAck(recipientKey, payload));
|
|
1294
|
-
});
|
|
1295
|
-
const releaseReady = options.communication.onPeerReady((recipientKey) => {
|
|
1296
|
-
track(publishQueued(recipientKey));
|
|
1297
|
-
});
|
|
1298
|
-
for (const row of await database.all("SELECT delivery_id, sender_key FROM session_delivery_inbox WHERE state = 'recovery_required'")) publishAck(row.delivery_id, row.sender_key, "recovery_required");
|
|
1299
|
-
for (const row of await database.all("SELECT delivery_id FROM session_delivery_inbox WHERE state = 'accepted'")) scheduleAdmission(row.delivery_id);
|
|
1300
|
-
track(publishAllQueued());
|
|
1301
|
-
return Object.freeze({
|
|
1302
|
-
recipientKey: options.recipientKey,
|
|
1303
|
-
async deliver(request) {
|
|
1304
|
-
if (closed) throw new Error("Session delivery service is closed.");
|
|
1305
|
-
const deliveryId = request.deliveryId ?? crypto.randomUUID();
|
|
1306
|
-
const mode = request.delivery ?? DEFAULT_DELIVERY;
|
|
1307
|
-
if (!deliveryId.trim() || !request.recipientKey.trim() || !request.kind.trim() || !isMode(mode)) throw new TypeError("Delivery id, recipient key, kind, and mode must be valid.");
|
|
1308
|
-
if (!await authorized(request.recipientKey, request.metadata)) throw new Error(`Session '${request.recipientKey}' is not an authorized communication peer.`);
|
|
1309
|
-
if (closed) throw new Error("Session delivery service is closed.");
|
|
1310
|
-
const metadata = normalizedMetadata(request.metadata);
|
|
1311
|
-
await database.run(`INSERT OR IGNORE INTO session_delivery_outbox
|
|
1312
|
-
(delivery_id, recipient_key, kind, prompt, delivery_mode, metadata_json, state, created_at)
|
|
1313
|
-
VALUES (?, ?, ?, ?, ?, ?, 'queued', ?)`, deliveryId, request.recipientKey, request.kind, request.prompt, mode, JSON.stringify(metadata), Date.now());
|
|
1314
|
-
const current = await database.get("SELECT * FROM session_delivery_outbox WHERE delivery_id = ?", deliveryId);
|
|
1315
|
-
if (!current || current.recipient_key !== request.recipientKey || current.kind !== request.kind || current.prompt !== request.prompt || current.delivery_mode !== mode || !sameMetadata(JSON.parse(current.metadata_json), metadata)) throw new TypeError(`Delivery id '${deliveryId}' is already bound to another envelope.`);
|
|
1316
|
-
startRetry();
|
|
1317
|
-
await publishOutbox(deliveryId);
|
|
1318
|
-
return { deliveryId };
|
|
1319
|
-
},
|
|
1320
|
-
async waitForAdmission(deliveryId, timeoutMs = 5e3) {
|
|
1321
|
-
const deadline = Date.now() + Math.max(0, timeoutMs);
|
|
1322
|
-
let state;
|
|
1323
|
-
do {
|
|
1324
|
-
state = (await database.get("SELECT recipient_state FROM session_delivery_outbox WHERE delivery_id = ?", deliveryId))?.recipient_state ?? void 0;
|
|
1325
|
-
if (state === "admitted" || state === "recovery_required" || state === "revoked") return state;
|
|
1326
|
-
if (Date.now() >= deadline) return state;
|
|
1327
|
-
await new Promise((resolve) => setTimeout(resolve, Math.min(10, deadline - Date.now())));
|
|
1328
|
-
} while (!closed);
|
|
1329
|
-
return state;
|
|
1330
|
-
},
|
|
1331
|
-
async receive(senderKey, kind, payload) {
|
|
1332
|
-
if (kind === DELIVERY_EVENT) return receiveEnvelope(senderKey, payload);
|
|
1333
|
-
if (kind === ACK_EVENT) {
|
|
1334
|
-
await receiveAck(senderKey, payload);
|
|
1335
|
-
return "accepted";
|
|
1336
|
-
}
|
|
1337
|
-
},
|
|
1338
|
-
async inbox(query = {}) {
|
|
1339
|
-
return (await database.all("SELECT * FROM session_delivery_inbox ORDER BY created_at, delivery_id")).map((row) => {
|
|
1340
|
-
const metadata = JSON.parse(row.metadata_json);
|
|
1341
|
-
return {
|
|
1342
|
-
deliveryId: row.delivery_id,
|
|
1343
|
-
senderKey: row.sender_key,
|
|
1344
|
-
recipientKey: row.recipient_key,
|
|
1345
|
-
kind: row.kind,
|
|
1346
|
-
prompt: row.prompt,
|
|
1347
|
-
delivery: row.delivery_mode,
|
|
1348
|
-
metadata,
|
|
1349
|
-
state: row.state,
|
|
1350
|
-
consumed: row.consumed_at !== null
|
|
1351
|
-
};
|
|
1352
|
-
}).filter((entry) => (query.kind === void 0 || entry.kind === query.kind) && (query.state === void 0 || entry.state === query.state) && (query.consumed === void 0 || entry.consumed === query.consumed) && matchesMetadata(entry.metadata, query.metadata));
|
|
1353
|
-
},
|
|
1354
|
-
async consume(deliveryId) {
|
|
1355
|
-
return await database.get("UPDATE session_delivery_inbox SET consumed_at = ? WHERE delivery_id = ? AND state IN ('admitted', 'recovery_required') AND consumed_at IS NULL RETURNING delivery_id", Date.now(), deliveryId) !== void 0;
|
|
1356
|
-
},
|
|
1357
|
-
async outbox(deliveryId) {
|
|
1358
|
-
const row = await database.get("SELECT delivery_id, recipient_key, kind, metadata_json, state, recipient_state FROM session_delivery_outbox WHERE delivery_id = ?", deliveryId);
|
|
1359
|
-
if (!row) return void 0;
|
|
1360
|
-
return {
|
|
1361
|
-
deliveryId: row.delivery_id,
|
|
1362
|
-
recipientKey: row.recipient_key,
|
|
1363
|
-
kind: row.kind,
|
|
1364
|
-
metadata: JSON.parse(row.metadata_json),
|
|
1365
|
-
state: row.state,
|
|
1366
|
-
...row.recipient_state === null ? {} : { recipientState: row.recipient_state }
|
|
1367
|
-
};
|
|
1368
|
-
},
|
|
1369
|
-
reauthorize: publishAllQueued,
|
|
1370
|
-
async close() {
|
|
1371
|
-
if (closed) return;
|
|
1372
|
-
closed = true;
|
|
1373
|
-
stopRetry();
|
|
1374
|
-
releaseEnvelope();
|
|
1375
|
-
releaseAck();
|
|
1376
|
-
releaseReady();
|
|
1377
|
-
try {
|
|
1378
|
-
await admissionQueue;
|
|
1379
|
-
await Promise.all(pending);
|
|
1380
|
-
} finally {
|
|
1381
|
-
await database.close();
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
});
|
|
1385
|
-
}
|
|
1386
|
-
/**
|
|
1387
|
-
* Installs a provider-owned endpoint in the current Cordis context.
|
|
1388
|
-
*
|
|
1389
|
-
* Returns the instance because a provider cannot read its own service back out:
|
|
1390
|
-
* `ctx.get` is strict and hides an implementation while its providing fiber is
|
|
1391
|
-
* LOADING, which is the whole of that fiber's own callback.
|
|
1392
|
-
*/
|
|
1393
|
-
async function provideSessionDeliveryService(context, options) {
|
|
1394
|
-
const service = await createSessionDeliveryService(options);
|
|
1395
|
-
const unprovide = context.provide(PO_SESSION_DELIVERY_SERVICE, service);
|
|
1396
|
-
context.effect(() => () => service.close(), "session delivery database");
|
|
1397
|
-
return {
|
|
1398
|
-
service,
|
|
1399
|
-
close: async () => {
|
|
1400
|
-
unprovide();
|
|
1401
|
-
await service.close();
|
|
1402
|
-
}
|
|
1403
|
-
};
|
|
1404
|
-
}
|
|
1405
|
-
//#endregion
|
|
1406
|
-
//#region ../../foundations/po-session/src/services/sessionDirectory/index.ts
|
|
1407
|
-
const UNKNOWN_FACTS = Object.freeze({
|
|
1408
|
-
reachability: "unknown",
|
|
1409
|
-
runtime: "unknown",
|
|
1410
|
-
activity: "unknown",
|
|
1411
|
-
voice: Object.freeze({
|
|
1412
|
-
eligible: "unknown",
|
|
1413
|
-
readiness: "unknown"
|
|
1414
|
-
})
|
|
1415
|
-
});
|
|
1416
|
-
function keyOf(observation) {
|
|
1417
|
-
return peerSessionReference(observation.hostId, observation.sessionId);
|
|
1418
|
-
}
|
|
1419
|
-
function publicEntry(observation, now, label, capabilities) {
|
|
1420
|
-
const freshUntil = observation.observedAt + observation.staleAfterMs;
|
|
1421
|
-
const fresh = now <= freshUntil;
|
|
1422
|
-
const facts = fresh ? observation : UNKNOWN_FACTS;
|
|
1423
|
-
return Object.freeze({
|
|
1424
|
-
reference: keyOf(observation),
|
|
1425
|
-
...label === void 0 ? {} : { label },
|
|
1426
|
-
capabilities: Object.freeze([...capabilities]),
|
|
1427
|
-
hostIncarnation: observation.hostIncarnation,
|
|
1428
|
-
sessionIncarnation: observation.sessionIncarnation,
|
|
1429
|
-
sequence: observation.sequence,
|
|
1430
|
-
observedAt: observation.observedAt,
|
|
1431
|
-
freshUntil,
|
|
1432
|
-
fresh,
|
|
1433
|
-
reachability: facts.reachability,
|
|
1434
|
-
runtime: facts.runtime,
|
|
1435
|
-
activity: facts.activity,
|
|
1436
|
-
voice: Object.freeze({ ...facts.voice })
|
|
1437
|
-
});
|
|
1438
|
-
}
|
|
1439
|
-
/** In-memory authenticated presence cache. Restart deliberately forgets every observation. */
|
|
1440
|
-
function createSessionDirectory(options) {
|
|
1441
|
-
const now = options.now ?? Date.now;
|
|
1442
|
-
const observations = /* @__PURE__ */ new Map();
|
|
1443
|
-
const snapshotRequired = /* @__PURE__ */ new Set();
|
|
1444
|
-
const subscribers = /* @__PURE__ */ new Set();
|
|
1445
|
-
const discover = async (callerReference, allowedReferences) => {
|
|
1446
|
-
const result = [];
|
|
1447
|
-
for (const observation of Array.from(observations.values())) {
|
|
1448
|
-
const reference = keyOf(observation);
|
|
1449
|
-
if (allowedReferences && !allowedReferences.has(reference)) continue;
|
|
1450
|
-
const grant = await options.authorizeDiscovery(callerReference, observation);
|
|
1451
|
-
if (!grant) continue;
|
|
1452
|
-
result.push(publicEntry(observation, now(), grant.label ?? observation.label, grant.capabilities));
|
|
1453
|
-
}
|
|
1454
|
-
return result.sort((left, right) => left.reference.localeCompare(right.reference));
|
|
1455
|
-
};
|
|
1456
|
-
const push = (subscriber) => {
|
|
1457
|
-
subscriber.queue = subscriber.queue.then(async () => {
|
|
1458
|
-
if (!subscribers.has(subscriber)) return;
|
|
1459
|
-
const sessions = await discover(subscriber.callerReference);
|
|
1460
|
-
if (subscribers.has(subscriber)) subscriber.listener(sessions);
|
|
1461
|
-
}).catch(() => void 0);
|
|
1462
|
-
};
|
|
1463
|
-
const notify = () => {
|
|
1464
|
-
for (const subscriber of subscribers) push(subscriber);
|
|
1465
|
-
};
|
|
1466
|
-
return {
|
|
1467
|
-
observe(observation) {
|
|
1468
|
-
const key = keyOf(observation);
|
|
1469
|
-
const current = observations.get(key);
|
|
1470
|
-
if (snapshotRequired.has(observation.hostId)) return false;
|
|
1471
|
-
if (current?.hostIncarnation === observation.hostIncarnation) {
|
|
1472
|
-
if (current.sessionIncarnation === observation.sessionIncarnation && observation.sequence <= current.sequence) return false;
|
|
1473
|
-
if (observation.sequence !== current.sequence + 1) {
|
|
1474
|
-
snapshotRequired.add(observation.hostId);
|
|
1475
|
-
for (const [reference, candidate] of observations) if (candidate.hostId === observation.hostId) observations.set(reference, {
|
|
1476
|
-
...candidate,
|
|
1477
|
-
...UNKNOWN_FACTS,
|
|
1478
|
-
observedAt: now(),
|
|
1479
|
-
staleAfterMs: 0
|
|
1480
|
-
});
|
|
1481
|
-
notify();
|
|
1482
|
-
return false;
|
|
1483
|
-
}
|
|
1484
|
-
}
|
|
1485
|
-
observations.set(key, Object.freeze({
|
|
1486
|
-
...observation,
|
|
1487
|
-
voice: Object.freeze({ ...observation.voice })
|
|
1488
|
-
}));
|
|
1489
|
-
notify();
|
|
1490
|
-
return true;
|
|
1491
|
-
},
|
|
1492
|
-
replaceHostSnapshot(hostId, hostIncarnation, replacements) {
|
|
1493
|
-
if (replacements.some((observation) => observation.hostId !== hostId || observation.hostIncarnation !== hostIncarnation)) throw new TypeError("A presence snapshot must contain only the declared host incarnation.");
|
|
1494
|
-
for (const [reference, observation] of observations) if (observation.hostId === hostId) observations.delete(reference);
|
|
1495
|
-
for (const observation of replacements) observations.set(keyOf(observation), Object.freeze({
|
|
1496
|
-
...observation,
|
|
1497
|
-
voice: Object.freeze({ ...observation.voice })
|
|
1498
|
-
}));
|
|
1499
|
-
snapshotRequired.delete(hostId);
|
|
1500
|
-
notify();
|
|
1501
|
-
},
|
|
1502
|
-
hostDisconnected(hostId) {
|
|
1503
|
-
for (const [reference, observation] of observations) {
|
|
1504
|
-
if (observation.hostId !== hostId) continue;
|
|
1505
|
-
observations.set(reference, {
|
|
1506
|
-
...observation,
|
|
1507
|
-
reachability: "unreachable"
|
|
1508
|
-
});
|
|
1509
|
-
}
|
|
1510
|
-
notify();
|
|
1511
|
-
},
|
|
1512
|
-
discover,
|
|
1513
|
-
async resolveDeliveryTarget(callerReference, reference) {
|
|
1514
|
-
const observation = observations.get(reference);
|
|
1515
|
-
return observation && await options.authorizeDiscovery(callerReference, observation) ? observation.deliveryTarget : void 0;
|
|
1516
|
-
},
|
|
1517
|
-
subscribe(callerReference, listener) {
|
|
1518
|
-
const subscriber = {
|
|
1519
|
-
callerReference,
|
|
1520
|
-
listener,
|
|
1521
|
-
queue: Promise.resolve()
|
|
978
|
+
});
|
|
979
|
+
}),
|
|
980
|
+
rebind: (hostId, url, urlGeneration) => serialize(async () => {
|
|
981
|
+
const config = initial();
|
|
982
|
+
const peer = config.peers.find((entry) => entry.hostId === hostId);
|
|
983
|
+
if (!peer || !Number.isSafeInteger(urlGeneration) || urlGeneration <= (peer.urlGeneration ?? 0)) return false;
|
|
984
|
+
const origin = peerOrigin(url);
|
|
985
|
+
await write({
|
|
986
|
+
...config,
|
|
987
|
+
peers: config.peers.map((entry) => entry === peer ? {
|
|
988
|
+
...peer,
|
|
989
|
+
url: origin,
|
|
990
|
+
urlGeneration
|
|
991
|
+
} : entry)
|
|
992
|
+
});
|
|
993
|
+
return true;
|
|
994
|
+
}),
|
|
995
|
+
announce: (url) => serialize(async () => {
|
|
996
|
+
const config = initial();
|
|
997
|
+
const announcedUrl = peerOrigin(url);
|
|
998
|
+
if (config.self?.announcedUrl !== announcedUrl) await write({
|
|
999
|
+
...config,
|
|
1000
|
+
self: {
|
|
1001
|
+
announcedUrl,
|
|
1002
|
+
urlGeneration: (config.self?.urlGeneration ?? 0) + 1
|
|
1003
|
+
}
|
|
1004
|
+
});
|
|
1005
|
+
return structuredClone(current);
|
|
1006
|
+
}),
|
|
1007
|
+
subscribe(listener) {
|
|
1008
|
+
listeners.add(listener);
|
|
1009
|
+
return () => {
|
|
1010
|
+
listeners.delete(listener);
|
|
1522
1011
|
};
|
|
1523
|
-
subscribers.add(subscriber);
|
|
1524
|
-
push(subscriber);
|
|
1525
|
-
return () => subscribers.delete(subscriber);
|
|
1526
1012
|
}
|
|
1527
1013
|
};
|
|
1528
1014
|
}
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
//#region ../../foundations/po-session/src/services/sessionIntercom/index.ts
|
|
1534
|
-
const MESSAGE_KIND = "session-message";
|
|
1535
|
-
const REPORT_KIND = "session-report";
|
|
1536
|
-
async function metadataFor(options, request, reportStatus) {
|
|
1537
|
-
const group = await options.groups.get(request.groupId);
|
|
1538
|
-
if (!group || !await options.groups.canMessage(request.groupId, options.selfReference, request.targetReference)) throw new Error(`Session group '${request.groupId}' does not authorize this message.`);
|
|
1539
|
-
return {
|
|
1540
|
-
sourceReference: options.selfReference,
|
|
1541
|
-
targetReference: request.targetReference,
|
|
1542
|
-
groupId: request.groupId,
|
|
1543
|
-
groupRevision: String(group.revision),
|
|
1544
|
-
...request.correlationId === void 0 ? {} : { correlationId: request.correlationId },
|
|
1545
|
-
...reportStatus === void 0 ? {} : { reportStatus }
|
|
1546
|
-
};
|
|
1547
|
-
}
|
|
1548
|
-
/** The group IDs, among those given, whose current membership includes this session. */
|
|
1549
|
-
async function groupMembership(options, groupIds) {
|
|
1550
|
-
const memberOf = /* @__PURE__ */ new Set();
|
|
1551
|
-
for (const groupId of new Set(groupIds)) {
|
|
1552
|
-
if (groupId === void 0) continue;
|
|
1553
|
-
if ((await options.groups.get(groupId))?.members.includes(options.selfReference) === true) memberOf.add(groupId);
|
|
1554
|
-
}
|
|
1555
|
-
return memberOf;
|
|
1556
|
-
}
|
|
1557
|
-
/** Agent-facing intercom operations. A composition may acquire this service without gaining session controls. */
|
|
1558
|
-
function createSessionIntercom(options) {
|
|
1559
|
-
const deliver = async (request, kind, status) => {
|
|
1560
|
-
const recipientKey = await options.directory.resolveDeliveryTarget(options.selfReference, request.targetReference);
|
|
1561
|
-
if (!recipientKey) throw new Error(`Session '${request.targetReference}' is not discoverable.`);
|
|
1562
|
-
const metadata = await metadataFor(options, request, status);
|
|
1563
|
-
return options.delivery.deliver({
|
|
1564
|
-
...request.deliveryId === void 0 ? {} : { deliveryId: request.deliveryId },
|
|
1565
|
-
recipientKey,
|
|
1566
|
-
kind,
|
|
1567
|
-
prompt: `[Session ${status === void 0 ? "message" : `report: ${status}`} from ${options.selfReference}] ${request.text}`,
|
|
1568
|
-
metadata
|
|
1569
|
-
});
|
|
1570
|
-
};
|
|
1571
|
-
return Object.freeze({
|
|
1572
|
-
async discover() {
|
|
1573
|
-
const members = new Set((await options.groups.groupsFor(options.selfReference)).flatMap((group) => group.members).filter((reference) => reference !== options.selfReference));
|
|
1574
|
-
return options.directory.discover(options.selfReference, members);
|
|
1575
|
-
},
|
|
1576
|
-
send: (request) => deliver(request, MESSAGE_KIND),
|
|
1577
|
-
report: (request) => deliver(request, REPORT_KIND, request.status),
|
|
1578
|
-
async messages() {
|
|
1579
|
-
const entries = (await options.delivery.inbox()).filter((entry) => entry.kind === MESSAGE_KIND || entry.kind === REPORT_KIND);
|
|
1580
|
-
const memberOf = await groupMembership(options, entries.map((entry) => entry.metadata.groupId));
|
|
1581
|
-
return entries.filter((entry) => {
|
|
1582
|
-
const groupId = entry.metadata.groupId;
|
|
1583
|
-
return groupId !== void 0 && memberOf.has(groupId);
|
|
1584
|
-
}).flatMap((entry) => {
|
|
1585
|
-
const sourceReference = entry.metadata.sourceReference;
|
|
1586
|
-
const targetReference = entry.metadata.targetReference;
|
|
1587
|
-
const groupId = entry.metadata.groupId;
|
|
1588
|
-
if (!sourceReference || !targetReference || !groupId) return [];
|
|
1589
|
-
const reportStatus = entry.metadata.reportStatus;
|
|
1590
|
-
return [{
|
|
1591
|
-
deliveryId: entry.deliveryId,
|
|
1592
|
-
sourceReference,
|
|
1593
|
-
targetReference,
|
|
1594
|
-
groupId,
|
|
1595
|
-
...entry.metadata.correlationId === void 0 ? {} : { correlationId: entry.metadata.correlationId },
|
|
1596
|
-
text: entry.prompt,
|
|
1597
|
-
...reportStatus === "done" || reportStatus === "blocked" || reportStatus === "failed" ? { reportStatus } : {},
|
|
1598
|
-
state: entry.state,
|
|
1599
|
-
consumed: entry.consumed
|
|
1600
|
-
}];
|
|
1601
|
-
});
|
|
1602
|
-
},
|
|
1603
|
-
async delivery(deliveryId) {
|
|
1604
|
-
const entry = await options.delivery.outbox(deliveryId);
|
|
1605
|
-
const groupId = entry?.metadata.groupId;
|
|
1606
|
-
return entry && groupId !== void 0 && (await groupMembership(options, [groupId])).has(groupId) ? entry : void 0;
|
|
1607
|
-
}
|
|
1608
|
-
});
|
|
1609
|
-
}
|
|
1610
|
-
/** Builds the dynamic delivery check used before every send, retry, and recipient acceptance. */
|
|
1611
|
-
function createSessionGroupDeliveryAuthorizer(options) {
|
|
1612
|
-
return async (peerKey, metadata) => {
|
|
1613
|
-
const sourceReference = metadata?.sourceReference;
|
|
1614
|
-
const targetReference = metadata?.targetReference;
|
|
1615
|
-
const groupId = metadata?.groupId;
|
|
1616
|
-
if (sourceReference && targetReference && groupId) {
|
|
1617
|
-
const peerReference = options.peerReference(peerKey);
|
|
1618
|
-
if (!peerReference) return false;
|
|
1619
|
-
return (sourceReference === options.selfReference && targetReference === peerReference || targetReference === options.selfReference && sourceReference === peerReference) && await options.groups.canMessage(groupId, sourceReference, targetReference);
|
|
1620
|
-
}
|
|
1621
|
-
return await options.fallback?.(peerKey, metadata) === true;
|
|
1622
|
-
};
|
|
1015
|
+
function requireSessionPeers(context) {
|
|
1016
|
+
const service = context.get(PO_SESSION_PEERS_SERVICE);
|
|
1017
|
+
if (!service) throw new Error("The host links service is unavailable.");
|
|
1018
|
+
return service;
|
|
1623
1019
|
}
|
|
1624
1020
|
//#endregion
|
|
1625
|
-
//#region ../../foundations/po-session/src/extensions/workspaces/sessions/(backend)/root.server.ts
|
|
1626
|
-
var root_server_default = defineRoot((pluginContext) => ({
|
|
1627
|
-
value: void 0,
|
|
1628
|
-
services: [provideBackgroundWorkService, (owner) => {
|
|
1629
|
-
owner.inject([
|
|
1630
|
-
PO_SESSION_PEERS_SERVICE,
|
|
1631
|
-
PO_SESSION_GROUP_BRIDGE_SERVICE,
|
|
1632
|
-
PO_FS_SERVICE,
|
|
1633
|
-
PO_SQLITE_SERVICE
|
|
1634
|
-
], async (context) => {
|
|
1635
|
-
const agent = pluginContext.agent;
|
|
1636
|
-
const session = agent?.context.session;
|
|
1637
|
-
const communication = pluginContext.host.context.sessionCommunication;
|
|
1638
|
-
const homeDirectory = pluginContext.host.context.homeDirectory;
|
|
1639
|
-
const sessionService = pluginContext.host.context.sessionService;
|
|
1640
|
-
if (!agent || !session?.admitPrompt || !communication || !homeDirectory || !sessionService?.canCommunicate) throw new Error("Session delivery requires the headless agent, authenticated session communication, host home directory, and communication policy.");
|
|
1641
|
-
const fs = requirePoFs(context);
|
|
1642
|
-
const sqlite = requirePoSqlite(context);
|
|
1643
|
-
const io = BACKGROUND_CONTEXT;
|
|
1644
|
-
const sessionDirectory = path.join(poHomeDirectory(homeDirectory), "session");
|
|
1645
|
-
const deliveryDirectory = path.join(sessionDirectory, "delivery");
|
|
1646
|
-
await ensurePrivateDirectory(fs, deliveryDirectory, io);
|
|
1647
|
-
const peers = requireSessionPeers(context);
|
|
1648
|
-
const peerConfig = peers.current();
|
|
1649
|
-
const peerCommunication = createPeerCommunication({
|
|
1650
|
-
local: communication,
|
|
1651
|
-
config: () => peers.current(),
|
|
1652
|
-
canPublish: (target, type, payload) => {
|
|
1653
|
-
if (type === "po/session-delivery/ack") return true;
|
|
1654
|
-
const metadata = payload?.metadata;
|
|
1655
|
-
return bridge?.peersFor(agent.context.sessionId).some((peer) => peer.sessionId === target && peer.sharedGroups.some((name) => namedSessionGroupId(name) === metadata?.groupId)) === true;
|
|
1656
|
-
},
|
|
1657
|
-
onError: (error) => pluginContext.host.context.onNotice(`Peer delivery failed: ${String(error)}`)
|
|
1658
|
-
});
|
|
1659
|
-
const remotePeerIsGranted = (peerKey) => {
|
|
1660
|
-
const peer = parseRemoteSessionReference(peerKey);
|
|
1661
|
-
return peer !== void 0 && peers.current()?.peers.some((candidate) => candidate.hostId === peer.hostId && candidate.allowedSessionIds.includes(agent.context.sessionId)) === true;
|
|
1662
|
-
};
|
|
1663
|
-
const fallbackAuthorization = (peerKey) => sessionService.canCommunicate?.(agent.context.sessionId, peerKey) === true || remotePeerIsGranted(peerKey);
|
|
1664
|
-
const bridge = readSessionGroupBridge(context);
|
|
1665
|
-
const groups = bridge?.groups;
|
|
1666
|
-
await bridge?.updateLocal(agent.context.sessionId, communication.sessionName ?? agent.context.sessionId, communication.groups ?? []);
|
|
1667
|
-
const localHostId = peerConfig?.hostId;
|
|
1668
|
-
const selfReference = localHostId ? peerSessionReference(localHostId, agent.context.sessionId) : void 0;
|
|
1669
|
-
const groupAuthorization = groups && selfReference && localHostId ? createSessionGroupDeliveryAuthorizer({
|
|
1670
|
-
selfReference,
|
|
1671
|
-
groups,
|
|
1672
|
-
peerReference: (peerKey) => parseRemoteSessionReference(peerKey) === void 0 ? peerSessionReference(localHostId, peerKey) : peerKey,
|
|
1673
|
-
fallback: fallbackAuthorization
|
|
1674
|
-
}) : void 0;
|
|
1675
|
-
let delivery;
|
|
1676
|
-
try {
|
|
1677
|
-
delivery = await provideSessionDeliveryService(context, {
|
|
1678
|
-
database: await sqlite.open(path.join(deliveryDirectory, `${agent.context.sessionId}.sqlite`), io),
|
|
1679
|
-
recipientKey: agent.context.sessionId,
|
|
1680
|
-
communication: peerCommunication,
|
|
1681
|
-
authorizePeer: (peerKey, metadata) => {
|
|
1682
|
-
const remote = parseRemoteSessionReference(peerKey);
|
|
1683
|
-
if (remote && !peers.current()?.peers.some((peer) => peer.hostId === remote.hostId)) return false;
|
|
1684
|
-
if (remote) {
|
|
1685
|
-
if (!bridge?.metadataFor(agent.context.sessionId, peerKey) || !metadata?.groupId || !bridge?.peersFor(agent.context.sessionId).find((peer) => peer.sessionId === peerKey)?.sharedGroups.some((name) => namedSessionGroupId(name) === metadata.groupId)) return false;
|
|
1686
|
-
return groupAuthorization ? groupAuthorization(peerKey, metadata) : false;
|
|
1687
|
-
}
|
|
1688
|
-
return groupAuthorization ? groupAuthorization(peerKey, metadata) : fallbackAuthorization(peerKey);
|
|
1689
|
-
},
|
|
1690
|
-
admitPrompt: async (prompt, admission, requestId, metadata) => {
|
|
1691
|
-
if (!metadata.customType) {
|
|
1692
|
-
await session.admitPrompt(prompt, admission, void 0, requestId);
|
|
1693
|
-
return;
|
|
1694
|
-
}
|
|
1695
|
-
if (!session.admitMessage) throw new Error("The session cannot admit a custom delivery.");
|
|
1696
|
-
await session.admitMessage({
|
|
1697
|
-
type: metadata.customType,
|
|
1698
|
-
text: prompt,
|
|
1699
|
-
display: true,
|
|
1700
|
-
details: metadata.customDetails === void 0 ? void 0 : JSON.parse(metadata.customDetails)
|
|
1701
|
-
}, admission === "steer" ? "steer" : "followUp", requestId);
|
|
1702
|
-
}
|
|
1703
|
-
});
|
|
1704
|
-
} catch (error) {
|
|
1705
|
-
await bridge?.removeLocal(agent.context.sessionId);
|
|
1706
|
-
throw error;
|
|
1707
|
-
}
|
|
1708
|
-
const { service, close: closeDelivery } = delivery;
|
|
1709
|
-
const unprovide = [];
|
|
1710
|
-
if (groups && selfReference && peerConfig) {
|
|
1711
|
-
const directory = createSessionDirectory({ authorizeDiscovery: (_caller, subject) => {
|
|
1712
|
-
const reference = peerSessionReference(subject.hostId, subject.sessionId);
|
|
1713
|
-
return bridge?.peersFor(agent.context.sessionId).some((peer) => peer.sessionId === reference) ? { capabilities: ["message"] } : void 0;
|
|
1714
|
-
} });
|
|
1715
|
-
const observedHosts = /* @__PURE__ */ new Set();
|
|
1716
|
-
let sequence = 0;
|
|
1717
|
-
const observeRemote = () => {
|
|
1718
|
-
const remotePeers = bridge?.peersFor(agent.context.sessionId) ?? [];
|
|
1719
|
-
for (const peer of remotePeers) observedHosts.add(parseRemoteSessionReference(peer.sessionId).hostId);
|
|
1720
|
-
sequence += 1;
|
|
1721
|
-
for (const hostId of observedHosts) directory.replaceHostSnapshot(hostId, "linked", remotePeers.flatMap((peer) => {
|
|
1722
|
-
const remote = parseRemoteSessionReference(peer.sessionId);
|
|
1723
|
-
return remote.hostId !== hostId ? [] : [{
|
|
1724
|
-
hostId,
|
|
1725
|
-
sessionId: remote.sessionId,
|
|
1726
|
-
label: peer.name,
|
|
1727
|
-
hostIncarnation: "linked",
|
|
1728
|
-
sessionIncarnation: "live",
|
|
1729
|
-
sequence,
|
|
1730
|
-
observedAt: Date.now(),
|
|
1731
|
-
staleAfterMs: 12e4,
|
|
1732
|
-
deliveryTarget: peer.sessionId,
|
|
1733
|
-
reachability: "unknown",
|
|
1734
|
-
runtime: "unknown",
|
|
1735
|
-
activity: "unknown",
|
|
1736
|
-
voice: {
|
|
1737
|
-
eligible: "unknown",
|
|
1738
|
-
readiness: "unknown"
|
|
1739
|
-
}
|
|
1740
|
-
}];
|
|
1741
|
-
}));
|
|
1742
|
-
};
|
|
1743
|
-
observeRemote();
|
|
1744
|
-
unprovide.push(bridge.subscribe(() => {
|
|
1745
|
-
observeRemote();
|
|
1746
|
-
service.reauthorize?.().catch((error) => pluginContext.host.context.onNotice(`Delivery reauthorization failed: ${String(error)}`));
|
|
1747
|
-
}));
|
|
1748
|
-
unprovide.push(context.provide(PO_SESSION_INTERCOM_SERVICE, createSessionIntercom({
|
|
1749
|
-
selfReference,
|
|
1750
|
-
directory,
|
|
1751
|
-
groups,
|
|
1752
|
-
delivery: service
|
|
1753
|
-
})));
|
|
1754
|
-
}
|
|
1755
|
-
const releaseGroups = pluginContext.host.context.directEvents?.subscribe(PO_SESSION_ATTENTION_EVENT, agent.context.sessionId, () => {
|
|
1756
|
-
bridge?.updateLocal(agent.context.sessionId, communication.sessionName ?? agent.context.sessionId, communication.groups ?? []).catch((error) => pluginContext.host.context.onNotice(`Group update failed: ${String(error)}`));
|
|
1757
|
-
});
|
|
1758
|
-
const unregister = registerSessionPeerInbox(agent.context.sessionId, (sourceKey, kind, payload) => service.receive?.(sourceKey, kind, payload));
|
|
1759
|
-
return async () => {
|
|
1760
|
-
unregister();
|
|
1761
|
-
releaseGroups?.();
|
|
1762
|
-
await bridge?.removeLocal(agent.context.sessionId);
|
|
1763
|
-
for (const release of unprovide.reverse()) release();
|
|
1764
|
-
await closeDelivery();
|
|
1765
|
-
};
|
|
1766
|
-
});
|
|
1767
|
-
}]
|
|
1768
|
-
}));
|
|
1769
|
-
//#endregion
|
|
1770
|
-
//#region ../../core/po-core/src/schemas/remoteOrigin.ts
|
|
1771
|
-
const PO_REMOTE_ORIGIN_SERVICE = "po/remote-origin";
|
|
1772
|
-
defineServiceContract(PO_REMOTE_ORIGIN_SERVICE, { scope: "global" });
|
|
1773
|
-
//#endregion
|
|
1774
1021
|
//#region ../../foundations/po-session/src/services/peerLink/index.ts
|
|
1775
1022
|
const INVITE_TTL_MS = 6e4;
|
|
1776
1023
|
const MAX_INVITES = 64;
|
|
@@ -2017,260 +1264,173 @@ function createPeerLink(options) {
|
|
|
2017
1264
|
};
|
|
2018
1265
|
}
|
|
2019
1266
|
//#endregion
|
|
2020
|
-
//#region ../../foundations/po-session/src/services/
|
|
2021
|
-
const
|
|
2022
|
-
const
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
}
|
|
2026
|
-
/**
|
|
2027
|
-
function
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
1267
|
+
//#region ../../foundations/po-session/src/services/sessionGroupBridge/index.ts
|
|
1268
|
+
const PO_SESSION_GROUP_BRIDGE_SERVICE = "po/session-group-bridge";
|
|
1269
|
+
const PO_SESSION_GROUP_BRIDGE_CONTRACT = defineServiceContract(PO_SESSION_GROUP_BRIDGE_SERVICE, { scope: "host" });
|
|
1270
|
+
const normalizeSessionGroupName = (name) => name.normalize("NFC").trim();
|
|
1271
|
+
const namedSessionGroupId = (name) => `g${createHash("sha256").update(normalizeSessionGroupName(name)).digest("hex")}`;
|
|
1272
|
+
const clean = (name) => name.replace(/[\p{Cc}\p{Cf}]/gu, "").replace(/\s+/gu, " ").trim().slice(0, 160);
|
|
1273
|
+
/** One host owns the mirror. Remote snapshots never become outbound adverts. */
|
|
1274
|
+
function createSessionGroupBridge(options) {
|
|
1275
|
+
const snapshots = /* @__PURE__ */ new Map();
|
|
1276
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1277
|
+
const knownGroups = /* @__PURE__ */ new Set();
|
|
1278
|
+
const serialize = createSerialRunner().forKey("group-mirror");
|
|
1279
|
+
let closed = false;
|
|
1280
|
+
const localHost = () => options.peers.current()?.hostId;
|
|
1281
|
+
const linked = (hostId) => options.peers.current()?.peers.some((peer) => peer.hostId === hostId) === true;
|
|
1282
|
+
const entries = () => [...snapshots].flatMap(([hostId, members]) => hostId === localHost() || linked(hostId) ? members : []);
|
|
1283
|
+
const changed = () => {
|
|
1284
|
+
for (const listener of listeners) listener();
|
|
1285
|
+
};
|
|
1286
|
+
const mirror = () => serialize(async () => {
|
|
1287
|
+
if (closed) return;
|
|
1288
|
+
const desired = /* @__PURE__ */ new Map();
|
|
1289
|
+
for (const member of entries()) for (const name of member.groups) {
|
|
1290
|
+
const id = namedSessionGroupId(name);
|
|
1291
|
+
const members = desired.get(id) ?? /* @__PURE__ */ new Set();
|
|
1292
|
+
members.add(member.reference);
|
|
1293
|
+
desired.set(id, members);
|
|
1294
|
+
}
|
|
1295
|
+
for (const id of /* @__PURE__ */ new Set([...knownGroups, ...desired.keys()])) {
|
|
1296
|
+
const members = [...desired.get(id) ?? []];
|
|
1297
|
+
const current = await options.groups.get(id);
|
|
1298
|
+
if (!current) await options.groups.create(id, "session-group-bridge", members);
|
|
1299
|
+
else {
|
|
1300
|
+
if (current.ownerAuthority !== "session-group-bridge") throw new Error("Named group authority conflict.");
|
|
1301
|
+
await options.groups.mutate({
|
|
1302
|
+
groupId: id,
|
|
1303
|
+
authority: current.ownerAuthority,
|
|
1304
|
+
expectedRevision: current.revision,
|
|
1305
|
+
add: members,
|
|
1306
|
+
remove: current.members.filter((reference) => !members.includes(reference))
|
|
2041
1307
|
});
|
|
2042
|
-
}
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
1308
|
+
}
|
|
1309
|
+
knownGroups.add(id);
|
|
1310
|
+
}
|
|
1311
|
+
changed();
|
|
1312
|
+
});
|
|
1313
|
+
const refresh = async () => {
|
|
1314
|
+
const config = options.peers.current();
|
|
1315
|
+
if (closed || !config) return;
|
|
1316
|
+
await Promise.all(config.peers.map(async (peer) => {
|
|
1317
|
+
try {
|
|
1318
|
+
await options.send(peer.hostId, snapshots.get(config.hostId) ?? []);
|
|
1319
|
+
} catch (error) {
|
|
1320
|
+
options.onError(error);
|
|
1321
|
+
}
|
|
1322
|
+
}));
|
|
1323
|
+
};
|
|
1324
|
+
let timer;
|
|
1325
|
+
const syncRefreshTimer = () => {
|
|
1326
|
+
if (closed || !options.peers.current()?.peers.length) {
|
|
1327
|
+
if (timer !== void 0) clearInterval(timer);
|
|
1328
|
+
timer = void 0;
|
|
1329
|
+
} else if (timer === void 0) {
|
|
1330
|
+
timer = setInterval(() => {
|
|
1331
|
+
refresh().catch(options.onError);
|
|
1332
|
+
}, 6e4);
|
|
1333
|
+
timer.unref?.();
|
|
1334
|
+
}
|
|
1335
|
+
};
|
|
1336
|
+
const api = {
|
|
1337
|
+
groups: options.groups,
|
|
1338
|
+
async updateLocal(sessionId, name, groups) {
|
|
1339
|
+
const hostId = localHost();
|
|
1340
|
+
if (!hostId || closed) return;
|
|
1341
|
+
const reference = peerSessionReference(hostId, sessionId);
|
|
1342
|
+
const normalized = [...new Set(groups.map(normalizeSessionGroupName).filter(Boolean))];
|
|
1343
|
+
const current = snapshots.get(hostId)?.find((member) => member.reference === reference);
|
|
1344
|
+
if (current?.name === clean(name) && JSON.stringify(current.groups) === JSON.stringify(normalized)) return;
|
|
1345
|
+
snapshots.set(hostId, [...(snapshots.get(hostId) ?? []).filter((member) => member.reference !== reference), {
|
|
1346
|
+
reference,
|
|
1347
|
+
name: clean(name),
|
|
1348
|
+
groups: normalized
|
|
1349
|
+
}]);
|
|
1350
|
+
await mirror();
|
|
1351
|
+
await refresh();
|
|
1352
|
+
},
|
|
1353
|
+
async removeLocal(sessionId) {
|
|
1354
|
+
const hostId = localHost();
|
|
1355
|
+
if (!hostId) return;
|
|
1356
|
+
snapshots.set(hostId, (snapshots.get(hostId) ?? []).filter((member) => parseRemoteSessionReference(member.reference)?.sessionId !== sessionId));
|
|
1357
|
+
await mirror();
|
|
1358
|
+
await refresh();
|
|
1359
|
+
},
|
|
1360
|
+
async merge(hostId, value) {
|
|
1361
|
+
if (!linked(hostId) || !Array.isArray(value) || value.length > 256) return false;
|
|
1362
|
+
const members = [];
|
|
1363
|
+
const references = /* @__PURE__ */ new Set();
|
|
1364
|
+
for (const candidate of value) {
|
|
1365
|
+
if (!candidate || typeof candidate !== "object") return false;
|
|
1366
|
+
const member = candidate;
|
|
1367
|
+
if (typeof member.reference !== "string" || parseRemoteSessionReference(member.reference)?.hostId !== hostId || references.has(member.reference) || typeof member.name !== "string" || member.name.length > 256 || !Array.isArray(member.groups) || member.groups.length > 64 || member.groups.some((name) => typeof name !== "string" || !normalizeSessionGroupName(name) || name.length > 256)) return false;
|
|
1368
|
+
references.add(member.reference);
|
|
1369
|
+
members.push({
|
|
1370
|
+
reference: member.reference,
|
|
1371
|
+
name: clean(member.name),
|
|
1372
|
+
groups: [...new Set(member.groups.map(normalizeSessionGroupName))]
|
|
2064
1373
|
});
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
1374
|
+
}
|
|
1375
|
+
snapshots.set(hostId, members);
|
|
1376
|
+
await mirror();
|
|
1377
|
+
return true;
|
|
1378
|
+
},
|
|
1379
|
+
advert: () => snapshots.get(localHost() ?? "") ?? [],
|
|
1380
|
+
peersFor(sessionId) {
|
|
1381
|
+
const own = snapshots.get(localHost() ?? "")?.find((member) => parseRemoteSessionReference(member.reference)?.sessionId === sessionId);
|
|
1382
|
+
if (!own) return [];
|
|
1383
|
+
return entries().filter((member) => parseRemoteSessionReference(member.reference)?.hostId !== localHost()).flatMap((member) => {
|
|
1384
|
+
const sharedGroups = own.groups.filter((name) => member.groups.includes(name));
|
|
1385
|
+
const hostId = parseRemoteSessionReference(member.reference).hostId;
|
|
1386
|
+
return sharedGroups.length ? [{
|
|
1387
|
+
sessionId: member.reference,
|
|
1388
|
+
name: `${clean(hostId)}/${member.name || parseRemoteSessionReference(member.reference).sessionId}`,
|
|
1389
|
+
sharedGroups
|
|
1390
|
+
}] : [];
|
|
2073
1391
|
});
|
|
2074
|
-
|
|
1392
|
+
},
|
|
1393
|
+
metadataFor(sessionId, target) {
|
|
1394
|
+
const peer = api.peersFor(sessionId).find((member) => member.sessionId === target);
|
|
1395
|
+
const hostId = localHost();
|
|
1396
|
+
if (!peer || !hostId) return void 0;
|
|
2075
1397
|
return {
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
peers: config?.peers.map(({ hostId, url, urlGeneration }) => ({
|
|
2086
|
-
hostId,
|
|
2087
|
-
url,
|
|
2088
|
-
urlGeneration
|
|
2089
|
-
})) ?? []
|
|
2090
|
-
});
|
|
2091
|
-
}
|
|
2092
|
-
if (request.method !== "POST" || ![
|
|
2093
|
-
"/inbox",
|
|
2094
|
-
"/control",
|
|
2095
|
-
"/link/prepare",
|
|
2096
|
-
"/link/accept",
|
|
2097
|
-
"/link/unlink",
|
|
2098
|
-
"/link/hint"
|
|
2099
|
-
].includes(pathname)) return response(404, "Not found.");
|
|
2100
|
-
const length = request.headers.get("content-length");
|
|
2101
|
-
if (length !== null && (!/^\d+$/u.test(length) || Number(length) > MAX_BODY_BYTES)) return response(413, "Request body is too large.");
|
|
2102
|
-
const body = await request.text();
|
|
2103
|
-
if (Buffer.byteLength(body) > MAX_BODY_BYTES) return response(413, "Request body is too large.");
|
|
2104
|
-
if (pathname.startsWith("/link/")) {
|
|
2105
|
-
const caller = poApiCallerFrom(request.headers);
|
|
2106
|
-
if (!caller || caller.locality === "remote" && pathname !== "/link/hint" && caller.stepUp !== "verified") return response(403, "Linking hosts needs a fresh peer.link step-up.");
|
|
2107
|
-
if (!link) return response(503, "Host links are unavailable.");
|
|
2108
|
-
try {
|
|
2109
|
-
const input = body === "" ? {} : JSON.parse(body);
|
|
2110
|
-
if (pathname === "/link/prepare") return Response.json(await link.prepare());
|
|
2111
|
-
if (pathname === "/link/accept") {
|
|
2112
|
-
await link.accept(input.invite);
|
|
2113
|
-
return Response.json({ linked: true });
|
|
2114
|
-
}
|
|
2115
|
-
if (typeof input.hostId !== "string") return response(400, "A host identity is required.");
|
|
2116
|
-
if (pathname === "/link/unlink") {
|
|
2117
|
-
await link.unlink(input.hostId);
|
|
2118
|
-
return Response.json({ unlinked: true });
|
|
2119
|
-
}
|
|
2120
|
-
if (typeof input.url !== "string") return response(400, "A URL hint is required.");
|
|
2121
|
-
return Response.json({ rebound: await link.hint(input.hostId, input.url) });
|
|
2122
|
-
} catch (error) {
|
|
2123
|
-
return response(400, error instanceof Error ? error.message : "Host link failed.");
|
|
2124
|
-
}
|
|
2125
|
-
}
|
|
2126
|
-
if (pathname === "/control") {
|
|
2127
|
-
if (!link) return response(503, "Host links are unavailable.");
|
|
2128
|
-
try {
|
|
2129
|
-
return await link.control(request, body);
|
|
2130
|
-
} catch (error) {
|
|
2131
|
-
return response(400, error instanceof Error ? error.message : "Invalid peer control.");
|
|
2132
|
-
}
|
|
2133
|
-
}
|
|
2134
|
-
if (!config) return response(503, "Paired Session delivery is not configured.");
|
|
2135
|
-
const peer = verifyPeerRequest(config, request, body);
|
|
2136
|
-
if (!peer) return response(401, "Paired Session request is unauthorized.");
|
|
2137
|
-
if (!await replay?.admit(request)) return response(409, "Paired Session request was already received.");
|
|
2138
|
-
let parsed;
|
|
2139
|
-
try {
|
|
2140
|
-
parsed = JSON.parse(body);
|
|
2141
|
-
} catch {
|
|
2142
|
-
return response(400, "Paired Session request is malformed.");
|
|
2143
|
-
}
|
|
2144
|
-
let peerChannel;
|
|
2145
|
-
if (peer.linkGeneration) {
|
|
2146
|
-
const sealed = parsed;
|
|
2147
|
-
peerChannel = typeof sealed?.epochId === "string" ? channels.take(peer, sealed.epochId) : void 0;
|
|
2148
|
-
const opened = peerChannel?.open(sealed?.envelope);
|
|
2149
|
-
if (!opened?.ok) return response(401, "A fresh sealed peer channel is required.");
|
|
2150
|
-
try {
|
|
2151
|
-
parsed = JSON.parse(Buffer.from(opened.plaintext).toString("utf8"));
|
|
2152
|
-
} catch {
|
|
2153
|
-
return response(400, "Invalid sealed peer envelope.");
|
|
2154
|
-
}
|
|
2155
|
-
}
|
|
2156
|
-
const envelope = parseSessionPeerEnvelope(parsed);
|
|
2157
|
-
if (!envelope || !DELIVERY_TYPES.has(envelope.type)) return response(400, "Paired Session envelope is invalid.");
|
|
2158
|
-
if (!peer.linkGeneration && !peer.allowedSessionIds.includes(envelope.targetSessionId)) return response(403, "Peer is not granted this session.");
|
|
2159
|
-
const state = await deliverSessionPeerEnvelope(envelope.targetSessionId, peerSessionReference(peer.hostId, envelope.sourceSessionId), envelope.type, envelope.payload);
|
|
2160
|
-
if (state !== void 0 && peerChannel) {
|
|
2161
|
-
const sealed = peerChannel.seal(Buffer.from(JSON.stringify({
|
|
2162
|
-
accepted: true,
|
|
2163
|
-
state
|
|
2164
|
-
})));
|
|
2165
|
-
if (!sealed.ok) return response(503, "Peer acknowledgement could not be sealed.");
|
|
2166
|
-
const text = JSON.stringify(sealed.envelope);
|
|
2167
|
-
return new Response(text, { headers: peerRequestHeaders(config.hostId, peer, "RESPONSE", "/inbox", text) });
|
|
2168
|
-
}
|
|
2169
|
-
return state === void 0 ? response(404, "Target Session is unavailable.") : Response.json({
|
|
2170
|
-
accepted: true,
|
|
2171
|
-
state
|
|
2172
|
-
}, { status: 202 });
|
|
2173
|
-
},
|
|
2174
|
-
async close() {
|
|
2175
|
-
if (timer) clearInterval(timer);
|
|
2176
|
-
const state = await opened?.catch(() => void 0);
|
|
2177
|
-
link?.close();
|
|
2178
|
-
await state?.replay?.close();
|
|
2179
|
-
}
|
|
1398
|
+
sourceReference: peerSessionReference(hostId, sessionId),
|
|
1399
|
+
targetReference: target,
|
|
1400
|
+
groupId: namedSessionGroupId(peer.sharedGroups[0])
|
|
1401
|
+
};
|
|
1402
|
+
},
|
|
1403
|
+
subscribe(listener) {
|
|
1404
|
+
listeners.add(listener);
|
|
1405
|
+
return () => {
|
|
1406
|
+
listeners.delete(listener);
|
|
2180
1407
|
};
|
|
1408
|
+
},
|
|
1409
|
+
refresh,
|
|
1410
|
+
async close() {
|
|
1411
|
+
closed = true;
|
|
1412
|
+
syncRefreshTimer();
|
|
1413
|
+
releasePeers();
|
|
1414
|
+
await serialize(async () => void 0);
|
|
1415
|
+
listeners.clear();
|
|
1416
|
+
await options.groups.close();
|
|
2181
1417
|
}
|
|
2182
1418
|
};
|
|
1419
|
+
const releasePeers = options.peers.subscribe(() => {
|
|
1420
|
+
syncRefreshTimer();
|
|
1421
|
+
for (const hostId of snapshots.keys()) if (hostId !== localHost() && !linked(hostId)) snapshots.delete(hostId);
|
|
1422
|
+
changed();
|
|
1423
|
+
mirror().then(refresh).catch(options.onError);
|
|
1424
|
+
});
|
|
1425
|
+
syncRefreshTimer();
|
|
1426
|
+
return api;
|
|
1427
|
+
}
|
|
1428
|
+
function readSessionGroupBridge(context) {
|
|
1429
|
+
return context.get(PO_SESSION_GROUP_BRIDGE_SERVICE);
|
|
2183
1430
|
}
|
|
2184
1431
|
//#endregion
|
|
2185
1432
|
//#region ../../foundations/po-session/src/services/peerLink/type.ts
|
|
2186
1433
|
const PO_ROSTER_PEER_SERVICE = "po/roster-peer";
|
|
2187
|
-
defineServiceContract(PO_ROSTER_PEER_SERVICE, { scope: "
|
|
2188
|
-
//#endregion
|
|
2189
|
-
//#region ../../foundations/po-session/src/extensions/(backend)/api/session-peer/route.server.ts
|
|
2190
|
-
var route_server_default = defineRoute(({ context }) => {
|
|
2191
|
-
let origin;
|
|
2192
|
-
let network;
|
|
2193
|
-
context.inject([PO_ROSTER_PEER_SERVICE], (scoped) => {
|
|
2194
|
-
network = scoped.get(PO_ROSTER_PEER_SERVICE);
|
|
2195
|
-
return () => {
|
|
2196
|
-
network = void 0;
|
|
2197
|
-
};
|
|
2198
|
-
});
|
|
2199
|
-
context.inject([PO_REMOTE_ORIGIN_SERVICE], (scoped) => {
|
|
2200
|
-
origin = scoped.get(PO_REMOTE_ORIGIN_SERVICE);
|
|
2201
|
-
return () => {
|
|
2202
|
-
origin = void 0;
|
|
2203
|
-
};
|
|
2204
|
-
});
|
|
2205
|
-
const hasOrigin = origin !== void 0;
|
|
2206
|
-
return createPeerInboxApi({
|
|
2207
|
-
fs: requirePoFs(context),
|
|
2208
|
-
sqlite: requirePoSqlite(context),
|
|
2209
|
-
peers: requireSessionPeers(context),
|
|
2210
|
-
network,
|
|
2211
|
-
groups: () => readSessionGroupBridge(context),
|
|
2212
|
-
...hasOrigin ? { origin: () => origin?.current() } : {}
|
|
2213
|
-
});
|
|
2214
|
-
});
|
|
2215
|
-
//#endregion
|
|
2216
|
-
//#region ../../foundations/po-session/generated/server.ts
|
|
2217
|
-
const at = (value, context) => typeof value === "function" ? value(context) : value;
|
|
2218
|
-
/* v8 ignore next -- generated normalization branch */
|
|
2219
|
-
const defined = (values) => values.filter((value) => value !== void 0);
|
|
2220
|
-
const serverPlugin = defineServerPlugin({
|
|
2221
|
-
name: "@agimon-ai/po-session",
|
|
2222
|
-
providerOverrides: composeServerProviderOverrides(root_server_default$1, root_server_default),
|
|
2223
|
-
injects: composeRootInjects({
|
|
2224
|
-
global: [root_server_default$1],
|
|
2225
|
-
workspace: [root_server_default$1],
|
|
2226
|
-
session: [root_server_default$1, root_server_default]
|
|
2227
|
-
}),
|
|
2228
|
-
global: async (context) => {
|
|
2229
|
-
const scopeGlobal = await context.scopeRoot("global", root_server_default$1, context);
|
|
2230
|
-
const contextGlobal = {
|
|
2231
|
-
...context,
|
|
2232
|
-
root: scopeGlobal.value
|
|
2233
|
-
};
|
|
2234
|
-
return {
|
|
2235
|
-
...composeRootHooks(scopeGlobal),
|
|
2236
|
-
get api() {
|
|
2237
|
-
return [at(route_server_default, contextGlobal)];
|
|
2238
|
-
},
|
|
2239
|
-
services: [...scopeGlobal.services ?? []]
|
|
2240
|
-
};
|
|
2241
|
-
},
|
|
2242
|
-
workspace: async (context) => {
|
|
2243
|
-
const scopeGlobal = await context.scopeRoot("global", root_server_default$1, context);
|
|
2244
|
-
const contextGlobal = {
|
|
2245
|
-
...context,
|
|
2246
|
-
root: scopeGlobal.value
|
|
2247
|
-
};
|
|
2248
|
-
return {
|
|
2249
|
-
...composeRootHooks(scopeGlobal),
|
|
2250
|
-
get api() {
|
|
2251
|
-
return defined([context.hosted("global") ? void 0 : at(route_server_default, contextGlobal)]);
|
|
2252
|
-
},
|
|
2253
|
-
services: [...scopeGlobal.services ?? []]
|
|
2254
|
-
};
|
|
2255
|
-
},
|
|
2256
|
-
session: async (context) => {
|
|
2257
|
-
const scopeGlobal = await context.scopeRoot("global", root_server_default$1, context);
|
|
2258
|
-
const contextGlobal = {
|
|
2259
|
-
...context,
|
|
2260
|
-
root: scopeGlobal.value
|
|
2261
|
-
};
|
|
2262
|
-
const scopeSession = await context.scopeRoot("session", root_server_default, contextGlobal);
|
|
2263
|
-
return {
|
|
2264
|
-
...composeRootHooks(scopeGlobal, scopeSession),
|
|
2265
|
-
get api() {
|
|
2266
|
-
return defined([context.hosted("global") ? void 0 : at(route_server_default, contextGlobal)]);
|
|
2267
|
-
},
|
|
2268
|
-
services: [...scopeGlobal.services ?? [], ...scopeSession.services ?? []],
|
|
2269
|
-
get activities() {
|
|
2270
|
-
return [...scopeGlobal.activities ?? [], ...scopeSession.activities ?? []];
|
|
2271
|
-
}
|
|
2272
|
-
};
|
|
2273
|
-
}
|
|
2274
|
-
});
|
|
1434
|
+
defineServiceContract(PO_ROSTER_PEER_SERVICE, { scope: "host" });
|
|
2275
1435
|
//#endregion
|
|
2276
|
-
export {
|
|
1436
|
+
export { createStartSessionTool as A, createSealedPeerChannels as C, detach as D, createSessionsNamespace as E, isSealedEnvelope as M, fields as O, authenticatedPeerPost as S, sessionPeerConfigPath as T, parseSessionPeerEnvelope as _, namedSessionGroupId as a, readSessionPeerConfigAsync as b, PO_SESSION_PEERS_CONTRACT as c, requireSessionPeers as d, createSessionDirectory as f, parseRemoteSessionReference as g, ensurePrivateDirectory as h, createSessionGroupBridge as i, provideBackgroundWorkService as j, START_SESSION_TOOL_NAME as k, PO_SESSION_PEERS_SERVICE as l, createPeerReplayGuardAsync as m, PO_SESSION_GROUP_BRIDGE_CONTRACT as n, readSessionGroupBridge as o, createPeerCommunication as p, PO_SESSION_GROUP_BRIDGE_SERVICE as r, createPeerLink as s, PO_ROSTER_PEER_SERVICE as t, createSessionPeers as u, peerRequestHeaders as v, PEER_REPLAY_DATABASE_FILE as w, verifyPeerRequest as x, peerSessionReference as y };
|