@task-handoff/control-plane 0.0.41-alpha.6 → 0.0.41-alpha.7
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 +7 -1
- package/dist/cli.js +1 -1
- package/package.json +13 -1
- package/ui/assets/{CodeBlockNode-DOdQ8VfA.js → CodeBlockNode-CHAHxNT_.js} +1 -1
- package/ui/assets/{Tooltip-C6GltrtF.js → Tooltip-CEGimxW1.js} +1 -1
- package/ui/assets/{abnfDiagram-VRR7QNED-BUtxSvHN.js → abnfDiagram-VRR7QNED-RjcEM65i.js} +1 -1
- package/ui/assets/{arc-ZZE6To1e.js → arc-Ued-zKli.js} +1 -1
- package/ui/assets/{architectureDiagram-ZJ3FMSHR-lNlBhVw0.js → architectureDiagram-ZJ3FMSHR-CBOoUy1i.js} +1 -1
- package/ui/assets/{blockDiagram-677ZJIJ3-Z7N-RV0O.js → blockDiagram-677ZJIJ3-DqK4V1G7.js} +1 -1
- package/ui/assets/{c4Diagram-LMCZKHZV-Dnnn8NSc.js → c4Diagram-LMCZKHZV-DCh09lVs.js} +1 -1
- package/ui/assets/channel-B1DIt_X8.js +1 -0
- package/ui/assets/{chunk-2Q5K7J3B-BZwP3-a5.js → chunk-2Q5K7J3B-Icr_zCaS.js} +1 -1
- package/ui/assets/{chunk-32BRIVSS-0h6Latlg.js → chunk-32BRIVSS-C43Qy-Q4.js} +1 -1
- package/ui/assets/{chunk-5VM5RSS4-D6oj4ER0.js → chunk-5VM5RSS4-CcM_DH1L.js} +1 -1
- package/ui/assets/{chunk-EX3LRPZG-GNnk5OzJ.js → chunk-EX3LRPZG-BWDiKE02.js} +1 -1
- package/ui/assets/{chunk-JWPE2WC7-B6Da71mz.js → chunk-JWPE2WC7-DjchIfIw.js} +1 -1
- package/ui/assets/{chunk-MOJQB5TN-rcYRcb01.js → chunk-MOJQB5TN-BKWbxOo9.js} +1 -1
- package/ui/assets/{chunk-RYQCIY6F-CTuH9ihh.js → chunk-RYQCIY6F-BwYFZojb.js} +1 -1
- package/ui/assets/{chunk-V7JOEXUC-B9Bvp9Sz.js → chunk-V7JOEXUC-BuQTwxTN.js} +1 -1
- package/ui/assets/{chunk-VR4S4FIN-LNurwWh_.js → chunk-VR4S4FIN-Cgwej8nL.js} +1 -1
- package/ui/assets/{chunk-XXDRQBXY-Cisb8pay.js → chunk-XXDRQBXY-DxyGoSLr.js} +1 -1
- package/ui/assets/classDiagram-OUVF2IWQ-BAX9RjkF.js +1 -0
- package/ui/assets/classDiagram-v2-EOCWNBFH-BAX9RjkF.js +1 -0
- package/ui/assets/{cose-bilkent-JH36ORCC-D5_4d5Ek.js → cose-bilkent-JH36ORCC-BaZ6bMhu.js} +1 -1
- package/ui/assets/{cynefin-VYW2F7L2-C_fFxzLn.js → cynefin-VYW2F7L2-_GYlwwem.js} +1 -1
- package/ui/assets/{cynefinDiagram-TSTJHNR4-DFbkl7dw.js → cynefinDiagram-TSTJHNR4-XltKdNuZ.js} +1 -1
- package/ui/assets/{dagre-VKFMJZFB-Bnp7Reop.js → dagre-VKFMJZFB-BeftKww1.js} +1 -1
- package/ui/assets/{diagram-FQU43EPY-gbi1_Oxc.js → diagram-FQU43EPY-CLUjl06r.js} +1 -1
- package/ui/assets/{diagram-G47NLZAW-cmkB2qht.js → diagram-G47NLZAW-CzB5k6Nd.js} +1 -1
- package/ui/assets/{diagram-NH7WQ7WH-DTVzSHsG.js → diagram-NH7WQ7WH-BNXKxK6u.js} +1 -1
- package/ui/assets/{diagram-OA4YK3LP-CyQmZqnY.js → diagram-OA4YK3LP-Dkpt2SsB.js} +1 -1
- package/ui/assets/{diagram-WEI45ONY-CTrWAOYH.js → diagram-WEI45ONY-C8ESoZR7.js} +1 -1
- package/ui/assets/{ebnfDiagram-CCIWWBDH-B_zlEDzp.js → ebnfDiagram-CCIWWBDH-DhwkGoaG.js} +1 -1
- package/ui/assets/{erDiagram-Q63AITRT-D-nqHcaD.js → erDiagram-Q63AITRT-BneVfdmd.js} +1 -1
- package/ui/assets/{flowDiagram-23GEKE2U-CCXwe3b0.js → flowDiagram-23GEKE2U-C39FYayE.js} +1 -1
- package/ui/assets/{ganttDiagram-NO4QXBWP-CHuT55C3.js → ganttDiagram-NO4QXBWP-RZoJfsZh.js} +1 -1
- package/ui/assets/{gitGraphDiagram-IHSO6WYX-ncl78D9q.js → gitGraphDiagram-IHSO6WYX-DWHu8-p4.js} +1 -1
- package/ui/assets/{index-ovTe1MUg.js → index-JY9qUPUu.js} +5 -5
- package/ui/assets/{index10-1z0pFUSE.js → index10-BltLRpQ1.js} +1 -1
- package/ui/assets/{index11-BAXLo3Nw.js → index11-CDnNw9tS.js} +1 -1
- package/ui/assets/{index5-DdvvE0or.js → index5-1jJwjiE_.js} +1 -1
- package/ui/assets/{index6-Dx5Bbdeo.js → index6-DPjClPCs.js} +1 -1
- package/ui/assets/{index7-BlrlSUXg.js → index7-gQz7OpQP.js} +1 -1
- package/ui/assets/{index8-D-78Cgdk.js → index8-BsiuzSsR.js} +1 -1
- package/ui/assets/{infoDiagram-FWYZ7A6U-CvxSu4py.js → infoDiagram-FWYZ7A6U-Bp8-n-0l.js} +1 -1
- package/ui/assets/{ishikawaDiagram-FXEZZL3T-DiP7b79B.js → ishikawaDiagram-FXEZZL3T-DHYESpW0.js} +1 -1
- package/ui/assets/{journeyDiagram-5HDEW3XC-Cl0_ypYj.js → journeyDiagram-5HDEW3XC-CkiOr7KZ.js} +1 -1
- package/ui/assets/{kanban-definition-HUTT4EX6-BP-goXOi.js → kanban-definition-HUTT4EX6-BU8Hvnkf.js} +1 -1
- package/ui/assets/{linear-CBKXmxu_.js → linear-Bu_sOJ5z.js} +1 -1
- package/ui/assets/{mermaid.core-DHBLTfQ8.js → mermaid.core-C59XQJ8w.js} +4 -4
- package/ui/assets/{mhchem-dPq08_XM.js → mhchem-CEGuP5Ts.js} +1 -1
- package/ui/assets/{mindmap-definition-LN4V7U3C-CWsCwVOn.js → mindmap-definition-LN4V7U3C-DEOlN82P.js} +1 -1
- package/ui/assets/{pegDiagram-2B236MQR-DEE-3eKI.js → pegDiagram-2B236MQR-Itv02SDC.js} +1 -1
- package/ui/assets/{pieDiagram-ENE6RG2P-BPl1BLLT.js → pieDiagram-ENE6RG2P-DUZTt3KC.js} +1 -1
- package/ui/assets/{quadrantDiagram-ABIIQ3AL-DbBXL0S1.js → quadrantDiagram-ABIIQ3AL-SPbSFzRi.js} +1 -1
- package/ui/assets/{railroadDiagram-RFXS5EU6-MpSsZ136.js → railroadDiagram-RFXS5EU6-By3tXDTm.js} +1 -1
- package/ui/assets/{requirementDiagram-TGXJPOKE-DNpDVNZ3.js → requirementDiagram-TGXJPOKE-D9qQvWcc.js} +1 -1
- package/ui/assets/{sankeyDiagram-HTMAVEWB-knkeOful.js → sankeyDiagram-HTMAVEWB-CJBbBnHY.js} +1 -1
- package/ui/assets/{sequenceDiagram-DBY2YBRQ-CQ2Q6Prm.js → sequenceDiagram-DBY2YBRQ-Ba-OPEMF.js} +1 -1
- package/ui/assets/{sizeCapture-X5ZJPWSS-8y-gNhIr.js → sizeCapture-X5ZJPWSS-hXBwNnIs.js} +1 -1
- package/ui/assets/{stateDiagram-2N3HPSRC-E9wqj4K2.js → stateDiagram-2N3HPSRC-KUrZ7v0P.js} +1 -1
- package/ui/assets/stateDiagram-v2-6OUMAXLB-CxOrSiBs.js +1 -0
- package/ui/assets/{swimlanes-5IMT3BWC-BcqDzlcF.js → swimlanes-5IMT3BWC-CHHUPsKd.js} +2 -2
- package/ui/assets/swimlanesDiagram-G3AALYLV-B7z5jzD8.js +8 -0
- package/ui/assets/{timeline-definition-FHXFAJF6-CDEyGb88.js → timeline-definition-FHXFAJF6-BNyxBRn6.js} +1 -1
- package/ui/assets/{vennDiagram-L72KCM5P-DcMUx_F3.js → vennDiagram-L72KCM5P-DeqAXMed.js} +1 -1
- package/ui/assets/{wardleyDiagram-EHGQE667-B_oGitOF.js → wardleyDiagram-EHGQE667-Dh_aRAA_.js} +1 -1
- package/ui/assets/{xychartDiagram-FW5EYKEG-DoZLTxNs.js → xychartDiagram-FW5EYKEG-TjXK1kVB.js} +1 -1
- package/ui/index.html +1 -1
- package/ui/assets/channel-D--_gjIF.js +0 -1
- package/ui/assets/classDiagram-OUVF2IWQ-CT97E4mV.js +0 -1
- package/ui/assets/classDiagram-v2-EOCWNBFH-CT97E4mV.js +0 -1
- package/ui/assets/stateDiagram-v2-6OUMAXLB-CsbUK3nh.js +0 -1
- package/ui/assets/swimlanesDiagram-G3AALYLV-Ca6pdBOx.js +0 -8
package/README.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
1
|
# @task-handoff/control-plane
|
|
2
2
|
|
|
3
|
-
Prebuilt control
|
|
3
|
+
Prebuilt TaskHandoff control plane runtime. This package contains compiled JavaScript and built Web UI assets; it does not contain monorepo source code.
|
|
4
|
+
|
|
5
|
+
## Links
|
|
6
|
+
|
|
7
|
+
- Documentation: https://docs.thandoff.com
|
|
8
|
+
- Repository: https://github.com/edgestorage/task-handoff
|
|
9
|
+
- Issues: https://github.com/edgestorage/task-handoff/issues
|
package/dist/cli.js
CHANGED
|
@@ -433,4 +433,4 @@ echo "TaskHandoff node-agent is installed and running."
|
|
|
433
433
|
echo "Service: task-handoff-node-agent.service"
|
|
434
434
|
echo "Pairing token: sudo task-handoff-node-agent invite --ipc-path $IPC_PATH"
|
|
435
435
|
echo "Uninstall: sudo task-handoff-node-agent uninstall"
|
|
436
|
-
`)),o.get("/api/events",{websocket:!0},async(e,t)=>{const n=t.query,i="string"==typeof n.instanceId?n.instanceId.trim():"",s=vS(t),a="user"===s?.type?(await S.listControlledInstances()).filter(e=>uh(s.nodeScope,s.instanceScope,e.id,e.nodeId)):void 0,o=a?new Set(a.map(e=>e.id)):void 0;if(i&&o&&!o.has(i))return void e.close(4003,"The requested event scope is not visible.");const r=[];let c=!1;const d={get readyState(){return e.readyState},get bufferedAmount(){return e.bufferedAmount},OPEN:e.OPEN,send(t){c?e.send(t):r.push(t)},ping(){e.ping()},on(t,n){e.on(t,n)},close(t,n){e.close(t,n)}};l.connect(d,{instanceIds:i?[i]:void 0,expectsTransientSubscription:"1"===n.aiSessionTransient,expectsMetricSubscription:"1"===n.resourceMetricsScope,..."user"===s?.type?{authorization:{userId:s.userId,..."cookie"===Ak(t).source?{webSession:!0}:{},authorizationRevision:s.authorizationRevision,permissionIds:s.permissionIds,..."selected"===s.nodeScope.kind?{allowedNodeIds:new Set(s.nodeScope.nodeIds)}:{},..."selected"===s.instanceScope?.kind||"selected"===s.nodeScope.kind?{allowedInstanceIds:o}:{}}}:{}});const[p,u]=await Promise.all([j.streamDescriptors(),L.streamDescriptors()]);l.send(e,"streams.hello",{protocolVersion:1,streams:[...p,...u].filter(e=>(!o||o.has(e.instanceId))&&(!i||e.instanceId===i))}),c=!0;for(const t of r)e.send(t);for(const t of k.snapshots().filter(e=>(!o||o.has(e.instanceId))&&(!i||e.instanceId===i)))l.send(e,"image.pull.snapshot",t,{topic:"instances",scope:{instanceId:t.instanceId}});for(const t of O.snapshots().filter(e=>(!o||o.has(e.instanceId))&&(!i||e.instanceId===i)))l.send(e,"git.provisioning.snapshot",t,{topic:"instances",scope:{instanceId:t.instanceId}})}),o.get("/api/auth/session",{config:qS},async e=>{const t=Ak(e);return{data:await A.currentSession(t.token,t.clientTypes)}}),o.post("/api/auth/bootstrap-admin",{config:qS},async(e,t)=>{const n=await A.bootstrapAdmin(e.body);return t.code(201).send({data:n})}),o.post("/api/auth/login",{config:qS},async(e,t)=>{const n=await A.login(e.body,{sourceId:e.ip});return t.setCookie(Pg,n.sessionToken,{path:"/",httpOnly:!0,sameSite:"lax",expires:new Date(n.expiresAt)}),{data:{user:n.user}}}),o.post("/api/auth/mobile/login",{config:qS},async e=>({data:await A.loginMobile(e.body,{sourceId:e.ip})})),o.patch("/api/auth/password",async(e,t)=>{const n=await A.changePassword(e.cookies[Pg],e.body);return t.setCookie(Pg,n.sessionToken,{path:"/",httpOnly:!0,sameSite:"lax",expires:new Date(n.expiresAt)}),{data:{user:n.user}}}),o.post("/api/auth/mobile/logout",async e=>{const t=Ak(e,{allowCookie:!1,bearerClientTypes:["mobile"]});return{data:await A.logoutSession(t.token,t.clientTypes)}}),o.post("/api/auth/mobile/renew",async(e,t)=>{t.header("cache-control","no-store");const n=Ak(e,{allowCookie:!1,bearerClientTypes:["mobile"]}),i=await A.renewSession(n.token,n.clientTypes);return i?{data:i}:t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to renew the mobile session."}})}),o.get("/api/auth/mobile/sessions",async(e,t)=>{const n=Ak(e,{bearerClientTypes:["mobile"]}),i=await A.mobileSessions(n.token,n.clientTypes);return i?{data:i}:t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to access mobile sessions."}})}),o.delete("/api/auth/mobile/sessions/:id",async(e,t)=>{const n=f.z.object({id:f.z.string().trim().min(1)}).parse(e.params),i=Ak(e,{bearerClientTypes:["mobile"]}),s=await A.revokeMobileSession(i.token,n.id,i.clientTypes);return void 0===s?t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to revoke mobile sessions."}}):{data:{revoked:s}}}),o.post("/api/auth/logout",{config:qS},async(e,t)=>{const n=Ak(e),i=await A.logoutSession(n.token,n.clientTypes);return t.clearCookie(Pg,{path:"/"}),{data:i}});const ie=zk(S);return o.post("/api/auth/cli/authorize",{config:qS},async e=>({data:await A.createCliAuthorization(e.body,{publicOrigin:Tk(S,e),sourceId:e.ip})})),o.post("/api/auth/cli/token",{config:qS},async e=>({data:await A.exchangeCliToken(e.body,{sourceId:e.ip})})),o.post("/api/auth/cli/local",{config:qS},async e=>({data:await A.createLocalCliSession(e.body,{remoteAddress:e.socket.remoteAddress,sourceId:e.ip})})),o.get("/api/auth/cli/requests/:requestId",{preHandler:ie},async e=>zm.parse({data:A.cliAuthorizationRequest(f.z.object({requestId:f.z.string().trim().min(1)}).parse(e.params).requestId)})),o.get("/api/auth/cli/requests",{preHandler:ie},async e=>zm.parse({data:A.cliAuthorizationRequestByUserCode(f.z.object({userCode:f.z.string().trim().min(1).max(40)}).parse(e.query).userCode)})),o.post("/api/auth/cli/requests/:requestId/approve",{preHandler:ie},async e=>Nm.parse({data:await A.approveCliAuthorization(f.z.object({requestId:f.z.string().trim().min(1)}).parse(e.params).requestId,Nk(e))})),o.post("/api/auth/cli/requests/:requestId/deny",{preHandler:ie},async e=>Cm.parse({data:await A.denyCliAuthorization(f.z.object({requestId:f.z.string().trim().min(1)}).parse(e.params).requestId,Nk(e))})),o.post("/api/auth/cli/logout",async e=>{const t=Ak(e,{allowCookie:!1,bearerClientTypes:["cli"]});return{data:await A.logoutSession(t.token,t.clientTypes)}}),o.post("/api/auth/cli/renew",async(e,t)=>{t.header("cache-control","no-store");const n=Ak(e,{allowCookie:!1,bearerClientTypes:["cli"]}),i=await A.renewSession(n.token,n.clientTypes);return i?{data:i}:t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to renew the CLI session."}})}),o.get("/api/auth/cli/sessions",async(e,t)=>{const n=Ak(e,{allowCookie:!1,bearerClientTypes:["cli"]}),i=await A.cliSessions(n.token,n.clientTypes);return i?{data:i}:t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to access CLI sessions."}})}),o.delete("/api/auth/cli/sessions/:id",async(e,t)=>{const n=f.z.object({id:f.z.string().trim().min(1)}).parse(e.params),i=Ak(e,{allowCookie:!1,bearerClientTypes:["cli"]}),s=await A.revokeCliSession(i.token,n.id,i.clientTypes);return void 0===s?t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to revoke CLI sessions."}}):{data:{revoked:s}}}),o.get("/api/access/me",async(e,t)=>{const n=Ak(e),i=await A.currentAccess(n.token,n.clientTypes);return i?{data:i}:t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to read Control Plane access."}})}),function(e,t,n){e.get("/api/users",async e=>{const n=f.z.object({search:f.z.string().trim().max(160).optional(),includeArchived:f.z.coerce.boolean().optional()}).strict().parse(e.query);return{data:await t.users.list(n)}}),e.post("/api/users",async(e,n)=>n.code(201).send({data:await t.users.createLocalUser(e.body)})),e.get("/api/users/:id",async e=>({data:await t.users.detail(zR.parse(e.params).id)})),e.patch("/api/users/:id",async e=>{const n=zR.parse(e.params).id,i=await t.users.updateUser(n,e.body);return await t.notifyAuthorizationChanged(n),{data:i}}),e.put("/api/users/:id/access",async(e,i)=>{const s=zR.parse(e.params).id,a=Ag.parse(e.body);return TS(e,i,t,n,"user.access.set",s,a,[{field:"roleIds",value:a.roleIds.join(", ")},{field:"nodeScope",value:JSON.stringify(a.nodeScope)},...a.instanceScope?[{field:"instanceScope",value:JSON.stringify(a.instanceScope)}]:[]],async()=>{const e=await t.users.setAccess(s,a);return await t.notifyAuthorizationChanged(s),e})}),e.post("/api/users/:id/password-reset",async e=>{const n=f.z.object({password:f.z.string().min(8).max(4096),requirePasswordChange:f.z.boolean().optional()}).strict().parse(e.body),i=zR.parse(e.params).id,s=await t.users.resetLocalPassword(i,n.password,!1!==n.requirePasswordChange);return await t.notifyAuthorizationChanged(i),{data:s}}),e.get("/api/users/:id/sessions",async e=>{const n=NR(e);return{data:await t.sessions.listSessions(n.userId,zR.parse(e.params).id)}}),e.delete("/api/users/:id/sessions",async e=>{const n=zR.parse(e.params).id;return{data:{revokedSessions:await t.users.revokeSessions(n)}}}),e.delete("/api/users/:id/sessions/:sessionId",async e=>{const n=NR(e),i=f.z.object({id:f.z.string().trim().min(1),sessionId:f.z.string().trim().min(1)}).strict().parse(e.params);return{data:{revoked:await t.sessions.revokeSession(n.userId,i.sessionId)}}}),e.delete("/api/users/:id/identities/:identityId",async e=>{const n=f.z.object({id:f.z.string().trim().min(1),identityId:f.z.string().trim().min(1)}).strict().parse(e.params),i=await t.users.unbindExternalIdentity(n.id,n.identityId);return await t.notifyAuthorizationChanged(n.id),{data:i}}),e.get("/api/roles",async()=>({data:await t.users.roleSummaries()})),e.get("/api/permissions",async()=>({data:Qu})),e.post("/api/roles",async(e,n)=>n.code(201).send({data:await t.users.createRole(e.body)})),e.patch("/api/roles/:id",async(e,i)=>{const s=zR.parse(e.params).id,a=Tg.parse(e.body);return TS(e,i,t,n,"user.role.update",s,a,[{field:"changedFields",value:Object.keys(a).join(", ")},...a.permissionIds?[{field:"permissionIds",value:a.permissionIds.join(", ")}]:[]],async()=>{const e=(await t.users.store.grants.listByRole(s)).map(e=>e.userId),n=await t.users.updateRole(s,a);for(const n of e)await t.notifyAuthorizationChanged(n);return n})}),e.delete("/api/roles/:id",async(e,i)=>{const s=zR.parse(e.params).id;return TS(e,i,t,n,"user.role.remove",s,{},void 0,()=>t.users.archiveRole(s))}),e.get("/api/identity-providers",async()=>({data:await t.identityProviders.list()})),e.post("/api/identity-providers",async(e,n)=>n.code(201).send({data:await t.identityProviders.create(e.body)})),e.patch("/api/identity-providers/:id",async(e,i)=>{const s=zR.parse(e.params).id,a=Uh.parse(e.body);return TS(e,i,t,n,"identity-provider.update",s,a,[{field:"changedFields",value:Object.keys(a).join(", ")},...a.status?[{field:"status",value:a.status}]:[],...a.loginPolicy?[{field:"loginPolicy",value:a.loginPolicy}]:[]],()=>t.identityProviders.update(s,a))}),e.delete("/api/identity-providers/:id",async(e,i)=>{const s=zR.parse(e.params).id;return TS(e,i,t,n,"identity-provider.remove",s,{},void 0,async()=>({deleted:await t.identityProviders.remove(s)}))}),e.get("/api/external-identity-approvals",async()=>({data:await t.users.store.approvals.list()})),e.post("/api/external-identity-approvals/:id/approve",async e=>{const n=NR(e);return{data:await t.users.approveExternalIdentity(n.userId,zR.parse(e.params).id,e.body)}}),e.post("/api/external-identity-approvals/:id/reject",async e=>{const n=NR(e);return{data:await t.users.rejectExternalIdentity(n.userId,zR.parse(e.params).id)}}),e.post("/api/auth/external/:id/begin",{config:qS},async(e,n)=>(n.header("cache-control","no-store"),{data:await t.external.begin(zR.parse(e.params).id)})),e.post("/api/auth/external/callback",{config:qS},async(e,n)=>{n.header("cache-control","no-store");const i=await t.external.callback(e.body);return"session"===i.kind?(n.setCookie(Pg,i.sessionToken,{path:"/",httpOnly:!0,sameSite:"lax",expires:new Date(i.expiresAt)}),{data:{kind:i.kind,user:i.user,authorization:i.authorization}}):{data:i}})}(o,A,u),function(e,t,n,i){e.get("/api/git-credentials",async()=>({data:{items:t.gitCredentials.list()}})),e.post("/api/git-credentials",async(e,n)=>{const i=await t.gitCredentials.create(e.body);return n.code(201).send({data:i})}),e.get("/api/git-credentials/:id",async e=>{const n=CR.parse(e.params).id,i=t.gitCredentials.get(n);if(!i)throw Object.assign(new Error(`Git credential ${n} was not found.`),{code:"GIT_CREDENTIAL_NOT_FOUND",statusCode:404});return{data:i}}),e.patch("/api/git-credentials/:id",async e=>({data:await t.updateGitCredential(CR.parse(e.params).id,e.body)})),e.delete("/api/git-credentials/:id",async e=>({data:{deleted:await t.gitCredentials.remove(CR.parse(e.params).id)}})),e.get("/api/controlled-instances/:id/git-credential-assignments",async e=>{kR(e);const n=CR.parse(e.params).id;return await t.requireControlledInstance(n,!0),{data:t.listInstanceGitCredentialAssignments(n)}}),e.post("/api/controlled-instances/:id/git-credential-assignments",async(e,s)=>{kR(e);const a=CR.parse(e.params).id,o=f.z.object({credentialId:f.z.string().trim().min(1).max(120)}).strict().parse(e.body);return TS(e,s,n,i,"git-credential.assign",a,o,[{field:"credentialId",value:o.credentialId}],()=>t.authorizeInstanceGitCredential(a,o.credentialId),201)}),e.delete("/api/controlled-instances/:id/git-credential-assignments/:credentialId",async e=>{kR(e);const n=RR.parse(e.params);return{data:{revoked:await t.revokeInstanceGitCredential(n.id,n.credentialId)}}})}(o,S,A,u),o.get("/api/control-plane/status",async()=>({data:{protocolVersion:oc,build:vk(),storage:a}})),o.get("/api/control-plane/settings",async()=>({data:S.getSettings()})),o.patch("/api/control-plane/settings",async e=>{const t=S.updateSettings(e.body||{});return v=t.diagnosticLogs,{data:t}}),o.get("/api/control-plane/diagnostic-logs/export",async(e,i)=>{const s=await async function(e){const i=n.mkdtempSync(t.join(m.tmpdir(),"task-handoff-diagnostic-logs-")),s=t.resolve(e.nodeAgentDataDir||t.join(e.dataDir,"node-agent")),a=t.join(s,"local-instances"),o=n.existsSync(a)?n.readdirSync(a,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.isSymbolicLink()).map(e=>({label:t.join("local-instances",e.name),root:t.join(a,e.name,"logs")})):[],r=[{label:"control-plane",root:t.join(e.dataDir,"logs")},{label:"desktop",root:t.join(e.dataDir,"log")},{label:"node-agent",root:t.join(s,"logs")},...o],c=[];let d=0;for(const e of r)for(const s of FR(e.root)){if(d>=$R)break;const a=t.relative(e.root,s);if(!a||a.startsWith("..")||t.isAbsolute(a))continue;const o=t.join("logs",e.label,a),r=n.statSync(s).size,l=HR(s,t.join(i,o),$R-d);l&&(d+=l,c.push({source:s,archivePath:o,bytes:l,originalBytes:r}))}n.writeFileSync(t.join(i,"manifest.json"),`${JSON.stringify({createdAt:(new Date).toISOString(),diagnosticLogsEnabled:e.diagnosticLogsEnabled,limits:{perFileBytes:qR,totalBytes:$R},files:c.map(({archivePath:e,bytes:t,originalBytes:n})=>({archivePath:e,bytes:t,originalBytes:n,truncated:t<n}))},null,2)}\n`,{mode:384});const l=["manifest.json",...n.existsSync(t.join(i,"logs"))?["logs"]:[]],p=D.create({cwd:i,gzip:!0,portable:!0,noMtime:!0},l),u=()=>n.rmSync(i,{recursive:!0,force:!0});return p.once("close",u),p.once("error",u),{filename:`task-handoff-diagnostic-logs-${(new Date).toISOString().replace(/[:.]/g,"-")}.tar.gz`,stream:p}}({dataDir:a.dataDir,nodeAgentDataDir:process.env.TASK_HANDOFF_DESKTOP_NODE_AGENT_DATA_DIR||process.env.TASK_HANDOFF_NODE_AGENT_DATA_DIR,diagnosticLogsEnabled:v});return i.header("content-type","application/gzip"),i.header("content-disposition",`attachment; filename="${s.filename}"`),i.send(s.stream)}),o.post("/api/ai-session-attachments",{bodyLimit:33554432},async(e,t)=>{try{return t.code(201).send({data:q.upload(e.body)})}catch(e){return t.code(400).send({error:{code:"AI_SESSION_ATTACHMENT_INVALID",message:e instanceof Error?e.message:String(e)}})}}),oC({app:o,service:S,events:l,operationApprovals:u,auth:A,appSessionAggregator:L,aiSessionAggregator:j,chatGateway:Q,aiSessionAttachments:q,aiSessionAttachmentCache:U,nodeAgentTunnel:$,nodeEventSubscriber:Z,agentAggregator:M,errorPayload:Sk,onInstanceDeleted:async e=>{if(!A.enabled())return;const t=await A.users.removeInstanceFromAccessScopes(e);for(const e of t)await A.notifyAuthorizationChanged(e)}}),function(e,t,n,i){e.get("/api/operation-approvals/support",async e=>(await AS(e,t),{data:{supported:!0}})),e.get("/api/operation-approvals/:id/status",async e=>({data:n.status(await AS(e,t),wS.parse(e.params).id)})),e.delete("/api/operation-approvals/:id",async e=>({data:{cancelled:n.cancel(await AS(e,t),wS.parse(e.params).id)}})),e.get("/api/operation-approvals",async e=>({data:n.snapshot(ES(e,t))})),e.post("/api/operation-approvals/:id/decision",{preHandler:i},async i=>{const s=ES(i,t),a=xS.parse(i.body).decision,o=n.decide(s,wS.parse(i.params).id,a);return await zS(t,e,{action:`operation-approval.${a}`,userId:s,approvalId:o.id}),{data:o}})}(o,A,u,zk(S)),function(e){const{app:t,authority:n,resolveTarget:i,projectTarget:s,eventHub:a}=e,o=e.runtime??new QC,c=new WeakMap,d=(e,t)=>{const n=c.get(e);n&&(c.delete(e),n.tracked.release(),e.raw.removeListener("aborted",n.abort),t.raw.removeListener("close",n.abort))};t.all("/api/node-proxy/bindings/:bindingId/http/*",{config:BS,bodyLimit:o.maxRequestBodyBytes,logLevel:"silent",async onRequest(e,t){try{const i=rR.parse(e.params).bindingId,s=uR(n,i,e),a=function(e){const t=e.raw.url||e.url,n=/^\/api\/node-proxy\/bindings\/[^/]+\/http(\/[^#]*)$/.exec(t),i=n?.[1],s=i?.split("?",1)[0];if(!i||!s||/%(?:2f|5c)/i.test(s))throw bR(jo.RouteInvalid,"Proxy route is invalid.",400);const a=To.safeParse(i);if(!a.success)throw bR(jo.RouteInvalid,a.error.issues[0]?.message||"Proxy route is invalid.",400);return a.data}(e),r=gR(e.headers),l=o.reserveHttp(s.id),p=()=>{l.controller.abort(Object.assign(new Error("Proxy HTTP consumer disconnected."),{name:"AbortError",code:"ABORT_ERR"})),d(e,t)};c.set(e,{binding:s,route:a,forwardedHeaders:r,tracked:l,abort:p,startedAt:performance.now()}),e.raw.once("aborted",p),t.raw.once("close",p)}catch(n){return fR(t,n,e)}},async onError(e,t){d(e,t);const n=vR(e.headers);n&&t.header("x-request-id",n)},async onResponse(e,t){d(e,t)}},async(e,s)=>{try{const o=c.get(e);if(!o)throw bR(jo.TransportFailed,"Proxy request context is unavailable.",500,!0);const{binding:l,route:p,forwardedHeaders:u,tracked:m,abort:h,startedAt:g}=o;!function(e,t,n){const i=new URL(t,"https://node-agent.invalid").searchParams,s=[i.get("nodeId"),i.get("targetNodeId")];if(n&&"object"==typeof n&&!Array.isArray(n)){const e=n;"string"==typeof e.nodeId&&s.push(e.nodeId),"string"==typeof e.targetNodeId&&s.push(e.targetNodeId)}const a=s.find(t=>null!==t&&t!==e.targetNodeId);if(void 0!==a)throw bR(jo.TargetMismatch,"Proxy request attempts to select a target outside its binding.",409,!1,{bindingId:e.id,targetNodeId:e.targetNodeId})}(l,p,e.body);const f=null==(a=e.body)?void 0:Buffer.isBuffer(a)?a:a instanceof Uint8Array||"string"==typeof a?Buffer.from(a):Buffer.from(JSON.stringify(a));m.acceptRequestBody(f?.byteLength??0);try{const{node:a,transport:o}=await i(l.targetNodeId);mR(n,l,e),hR(l,a);const c=await o.requestStream(a,p,{method:e.method,headers:u,...f?{body:f}:{},signal:m.controller.signal}),d=performance.now()-g;return t.log.info({traceId:u[$y],requestId:u["x-request-id"],bindingId:l.id,targetNodeId:l.targetNodeId,routePath:new URL(p,"https://node-agent.invalid").pathname,statusCode:c.status,proxyForwardMs:d},"control-plane proxy request timing"),function(e,t,n,i,s,a,o,c){t.body&&n.beginResponseStream();const d=function(e,t){const n=Object.fromEntries([...No].flatMap(t=>{const n=e.headers.get(t);return null===n?[]:[[t,n]]}));return t&&(n["x-request-id"]=t),n}(t,a);d["server-timing"]=Hy(d["server-timing"],Fy("proxy_forward",c??0)),o&&!d[$y]&&(d[$y]=o);for(const[t,n]of Object.entries(d))e.header(t,n);const l=()=>{n.release(),s.raw.removeListener("aborted",i),e.raw.removeListener("close",i)};if(!t.body)return l(),e.code(t.status).send();const p=r.Readable.fromWeb(t.body);return n.controller.signal.addEventListener("abort",()=>{const e=n.controller.signal.reason;p.destroy(e instanceof Error?e:new Error("Proxy HTTP stream aborted."))},{once:!0}),p.on("data",e=>{try{n.acceptResponseChunk(e)}catch(e){p.destroy(e)}}),p.once("end",l),p.once("error",l),p.once("close",l),e.raw.once("close",()=>p.destroy()),e.code(t.status).send(p)}(s,c,m,h,e,u["x-request-id"],u[$y],d)}catch(t){throw d(e,s),t}}catch(t){return d(e,s),fR(s,t,e)}var a}),t.get("/api/node-proxy/bindings/:bindingId/websocket",{websocket:!0,logLevel:"silent",config:BS},async(e,t)=>{let s;try{const a=rR.parse(t.params).bindingId,r=uR(n,a,t),c=cR.parse(t.query).route,{node:d,transport:l}=await i(r.targetNodeId);mR(n,r,t),hR(r,d),s=o.openWebSocket(r.id,e),l.proxyWebSocket(d,s,c,function(e){const t=IR(e,"sec-websocket-protocol").split(",").map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}(t.headers),gR(t.headers))}catch(t){const n=yR(t);s?.close(1008,n.message),s||e.close(429===n.statusCode?1013:n.statusCode<500?1008:1011,wR(n.message))}}),t.get("/api/node-proxy/bindings/:bindingId/snapshot",{config:BS},async(e,t)=>{try{const t=rR.parse(e.params).bindingId,r=uR(n,t,e),{node:c}=await i(r.targetNodeId);mR(n,r,e),hR(r,c);const d=s(r.targetNodeId);if(!d)throw bR(jo.TargetUnavailable,"Proxy target no longer exists.",404,!1,{targetNodeId:r.targetNodeId});const l=a.cursor(r.targetNodeId),p=Wo.parse({protocolVersion:vo,binding:r,streamId:l.streamId,revision:l.revision,observedAt:(new Date).toISOString(),target:oR(d)});if(o=p,Buffer.byteLength(JSON.stringify(o),"utf8")>pR)throw bR(jo.ResourceLimit,"Proxy target snapshot byte limit exceeded.",429,!0,{bindingId:r.id,resource:"snapshot-bytes",limit:pR});return{data:p}}catch(n){return fR(t,n,e)}var o}),t.get("/api/node-proxy/bindings/:bindingId/events",{websocket:!0,logLevel:"silent",config:BS},async(e,t)=>{let s,r,c;try{const d=rR.parse(t.params).bindingId,l=uR(n,d,t),p=dR.parse(t.query),{node:u}=await i(l.targetNodeId);mR(n,l,t),hR(l,u),s=o.openWebSocket(l.id,e,()=>r?.()),s.on("message",()=>s?.close(1008,"Proxy event streams do not accept client messages."));const m=a.subscribe({bindingId:l.id,sourceControlPlaneId:l.sourceControlPlaneId,targetNodeId:l.targetNodeId},p.sinceRevision,e=>{s?.send(JSON.stringify(e))},()=>{s?.close(1011,"Proxy event delivery failed.")});r=m.close,c=o.registerBindingCleanup(l.id,r);const h=()=>{r?.(),c?.()};s.on("close",h),s.on("error",h),"snapshot-required"===m.kind?(r(),s.close(1008,"Proxy target snapshot is required.")):1!==s.readyState&&r()}catch(t){r?.(),c?.();const n=yR(t);s?.close(1008,n.message),s||e.close(429===n.statusCode?1013:n.statusCode<500?1008:1011,wR(n.message))}}),t.delete("/api/node-proxy/bindings/:bindingId",{config:BS},async(t,i)=>{try{const i=rR.parse(t.params).bindingId;uR(n,i,t);const s=n.revokeBinding(i),a=o.closeBinding(i);return e.onBindingRevoked?.(s),{data:{binding:s,closed:a}}}catch(e){return fR(i,e,t)}})}({app:o,authority:H,resolveTarget:e=>{const t=S.requireNode(e);return{node:t,transport:S.resolveNodeAgentTransport(t)}},projectTarget:F,runtime:G,eventHub:W,onBindingRevoked:e=>l.publish("control-plane-proxy.binding.updated",{binding:e,audit:{action:"binding.revoke",actor:`control-plane:${e.sourceControlPlaneId}`}},{topic:"control-plane-proxy",scope:{nodeId:e.targetNodeId}})}),function(e){const{app:t,service:n,proxy:i,runtime:s,events:a,syncNodeEvents:o,actorId:r}=e;t.get("/api/control-plane-proxy/invites",async()=>({data:i.listInvites()})),t.post("/api/control-plane-proxy/invites",async(e,t)=>{const n=await r(e),s=i.createInvite(e.body,n);return a.publish("control-plane-proxy.invite.created",{invite:s.invite,audit:{action:"invite.create",actor:n}},{topic:"control-plane-proxy",scope:{nodeId:s.invite.targetNodeId}}),t.code(201).send({data:s})}),t.delete("/api/control-plane-proxy/invites/:id",async e=>{const t=await r(e),n=i.revokeInvite(AR.parse(e.params).id);return a.publish("control-plane-proxy.invite.updated",{invite:n,audit:{action:"invite.revoke",actor:t}},{topic:"control-plane-proxy",scope:{nodeId:n.targetNodeId}}),{data:n}}),t.get("/api/control-plane-proxy/bindings",async()=>({data:i.listBindings()})),t.delete("/api/control-plane-proxy/bindings/:id",async e=>{const t=await r(e),n=AR.parse(e.params).id,o=i.revokeBinding(n),c=s.closeBinding(n);return a.publish("control-plane-proxy.binding.updated",{binding:o,audit:{action:"binding.revoke",actor:t}},{topic:"control-plane-proxy",scope:{nodeId:o.targetNodeId}}),{data:{binding:o,closed:c}}}),t.get("/api/control-plane-proxy/diagnostics",async()=>({data:s.diagnostics()})),t.post("/api/node-proxy/claims",{config:qS},async(e,t)=>{const n=i.claimInvite(e.body);return a.publish("control-plane-proxy.binding.created",{binding:n.binding,audit:{action:"binding.claim",actor:`control-plane:${n.binding.sourceControlPlaneId}`}},{topic:"control-plane-proxy",scope:{nodeId:n.binding.targetNodeId}}),t.code(201).send({data:n})}),t.get("/api/control-plane-proxy/pending-claims",async()=>({data:n.listPendingProxyClaims()})),t.post("/api/control-plane-proxy/claims",async(e,t)=>{const i=await n.claimProxyNode(e.body);return o?.(),a.publish("node.created",{nodeId:i.node.id}),t.code(201).send({data:i})}),t.post("/api/control-plane-proxy/pending-claims/:id/resume",async e=>{const t=AR.parse(e.params).id;ER.parse(e.body||{});const i=await n.resumeProxyClaim(t);return o?.(),a.publish("node.created",{nodeId:i.node.id}),{data:i}}),t.delete("/api/control-plane-proxy/pending-claims/:id",async e=>{const t=TR.parse(e.query||{});return{data:await n.cancelProxyClaim(AR.parse(e.params).id,"true"===t.force)}})}({app:o,service:S,proxy:H,runtime:G,events:l,syncNodeEvents:()=>Z.syncNow(),actorId:async e=>{const t=await Ek(A,Ak(e));return t?"user"===t.type?`user:${t.userId}`:"system"===t.type?`system:${t.reason}`:"cloud-account"===t.type?`cloud-account:${t.accountId}:${t.deviceSessionId}`:`chat-bridge:${t.bridgeId}`:"system:unknown"}}),function({app:e,service:t,auth:n,authorizationConnections:i}){!function(e){for(const t of["application/octet-stream","application/x-www-form-urlencoded"])fC(e,t);fC(e,/^multipart\/form-data(?:;.*)?$/i)}(e);const s=async(e,i,s="")=>{const a=await t.appAccessProxyTarget(e,i,s);return a.access.authorization&&await n.assertAppAccessAuthorization({...a.access.authorization,instanceId:a.instance.id,nodeId:a.instance.nodeId}),a},a=(e,t)=>{if(!t)return;const n=i.track(t,()=>e.close(4001,"Authorization changed."));e.on("close",n)};e.get("/api/app-access/session",{config:qS},async e=>{const t=yC(e.url),n="vnc"===e.query.mode?"vnc":"web"===e.query.mode?"web":"tty",i=await s(t,n);return{data:{mode:n,instance:{id:i.instance.id,name:i.instance.name,projectId:i.instance.projectId,projectName:"string"==typeof i.instance.sourceSnapshot.name?i.instance.sourceSnapshot.name:void 0},session:i.session,expiresAt:i.access.expiresAt,ttySocketPath:"tty"===n?`/apps/access/tty/ws?token=${encodeURIComponent(t)}`:void 0,vncFramePath:"vnc"===n?bC(t,i.access.sessionId,i.session):void 0}}}),e.get("/apps/access/tty/ws",{websocket:!0,config:qS},async(e,n)=>{try{const i=await s(yC(n.url),"tty");a(e,i.access.authorization),await t.proxyInstanceWebSocket(i.instance.id,e,i.path,kz(n.headers),lC(n.headers))}catch{e.close(1011,"TTY access link is invalid or expired.")}});const o=async(e,n)=>{const i=n.params;try{const o=await s(i.token||yC(n.url),"vnc",i["*"]||"");a(e,o.access.authorization),await t.proxyInstanceWebSocket(o.instance.id,e,o.path,kz(n.headers),lC(n.headers))}catch{e.close(1011,"VNC access link is invalid or expired.")}};e.route({method:"GET",url:"/apps/access/vnc/proxy/*",config:qS,wsHandler:o,handler:async(e,n)=>{const i=e.params,a=await s(yC(e.url),"vnc",i["*"]||"");return hC(n,await pC(t,n,a.instance.id,a.path,{method:e.method,headers:dC(e.headers)}),a.instance.id,a.path)}}),e.route({method:"GET",url:"/apps/access/vnc/:token/proxy/*",config:qS,wsHandler:o,handler:async(e,n)=>{const i=e.params,a=await s(i.token,"vnc",i["*"]||"");return hC(n,await pC(t,n,a.instance.id,a.path,{method:e.method,headers:dC(e.headers)}),a.instance.id,a.path)}}),e.all("/instances/:id",{bodyLimit:67108864},async(e,n)=>{const i=e.params;return"GET"===e.method||"HEAD"===e.method?n.redirect(`${mC(i.id)}/`):hC(n,await pC(t,n,i.id,"/",{method:e.method,headers:dC(e.headers),body:await gC(e.body)}),i.id,"/")}),e.route({method:"GET",url:"/instances/:id/*",wsHandler:async(e,n)=>{const i=n.params,s=i["*"]||"",o=n.url.indexOf("?"),r=o>=0?n.url.slice(o):"";try{const o=vS(n);a(e,"user"===o?.type?o:void 0),await t.proxyInstanceWebSocket(i.id,e,`/${s}${r}`,kz(n.headers),lC(n.headers))}catch{e.close(1011,"Instance websocket endpoint is not reachable.")}},handler:async(e,n)=>{const i=e.params,s=i["*"]||"",a=e.url.indexOf("?"),o=`/${s}${a>=0?e.url.slice(a):""}`;return hC(n,await pC(t,n,i.id,o,{method:e.method,headers:dC(e.headers)}),i.id,o)}}),e.route({method:["POST","PUT","PATCH","DELETE","OPTIONS"],url:"/instances/:id/*",bodyLimit:67108864,handler:async(e,n)=>{const i=e.params,s=i["*"]||"",a=e.url.indexOf("?"),o=a>=0?e.url.slice(a):"";return uC(n,await pC(t,n,i.id,`/${s}${o}`,{method:e.method,headers:dC(e.headers),body:await gC(e.body)}))}})}({app:o,service:S,auth:A,authorizationConnections:y}),function(e){const{app:t,service:n,auth:i,authorizationConnections:s,events:a}=e,o=e.browserAccess||new dk;t.post("/api/controlled-instances/:id/browser-access",async e=>{const{id:t}=KT.parse(e.params),s=function(e,t){const n=vS(e);if("user"===n?.type)return n;if(!1===t.enabled?.())return{type:"system",reason:"auth-disabled",userId:"system:auth-disabled",authorizationRevision:0};throw Object.assign(new Error("A signed-in Control Plane user is required."),{statusCode:403,code:"BROWSER_ACCESS_USER_REQUIRED"})}(e,i),a=await hz(n,e,t);if(hh(s,"interactive-access",{type:"instance",id:t,nodeId:a.nodeId}),!wc(a.capabilities).features.browserTunnel)throw Object.assign(new Error("The controlled instance does not support Browser Tunnel."),{statusCode:409,code:"BROWSER_TUNNEL_UNSUPPORTED"});const r=o.create({instanceId:t,authorization:{userId:s.userId,authorizationRevision:s.authorizationRevision}});return{data:ck.parse({accessId:r.accessId,token:r.token,expiresAt:r.expiresAt,relayPath:"/browser-relay"})}}),t.get("/browser-relay",{websocket:!0,config:qS},async(e,t)=>{let a,r;const c=[],d=(e,t=!1)=>c.push([e,Boolean(t)]);e.on("message",d);try{const p=o.consume("string"==typeof(l=t.headers.authorization)&&l.startsWith("Browser ")?l.slice(8).trim():"");!1!==i.enabled?.()&&await i.assertAppAccessAuthorization({...p.authorization,instanceId:p.instanceId,nodeId:(await n.requireControlledInstance(p.instanceId,!0)).nodeId});const u=()=>e.close(4001,"Browser access authorization ended.");a=o.track(p,u),r=s.track(p.authorization,u),e.on("close",()=>{a?.(),r?.()}),await n.proxyInstanceWebSocket(p.instanceId,e,"/api/browser-tunnel",[],{}),e.off("message",d);for(const[t,n]of c.splice(0))e.emit("message",t,n)}catch{e.off("message",d),c.length=0,a?.(),r?.(),e.close(1008,"Browser access is invalid or unavailable.")}var l}),a.on(e=>{if(!["instance.stopped","instance.deleted","instance.restarted"].includes(e.type))return;const t=e.payload&&"object"==typeof e.payload?e.payload:{};"string"==typeof t.instanceId&&o.closeInstance(t.instanceId)})}({app:o,service:S,auth:A,authorizationConnections:y,events:l,browserAccess:b}),o.get("*",{config:$S},async(e,t)=>n.existsSync(te)?_k(t,te,"index.html"):t.code(404).send({error:{code:"CONTROL_PLANE_UI_NOT_BUILT",message:"Control plane API is running, but the Web UI static directory was not found."}})),X=setInterval(()=>{J().catch(e=>o.log.warn({error:e},"pending node pairing recovery failed"))},3e4),X.unref(),Y=setInterval(()=>{S.runPersistenceMaintenance(),hT(c,d,a,{onWarning:e=>o.log.warn(e,"legacy Control Plane P0 persistence archive deferred")}).catch(e=>o.log.warn({error:e},"legacy Control Plane P0 persistence archive retry failed"))},216e5),Y.unref(),o}function Ok(e){const t=Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error("Port must be a valid TCP port.");return t}function jk(e){if("disabled"!==e&&"password"!==e)throw new Error("Auth mode must be disabled or password.");return e}function Pk(e,t){return{id:e,sql:t,checksum:i.createHash("sha256").update(t).digest("hex")}}(async function(){const n=new e.Command;n.name("task-handoff-control-plane").description("Run the TaskHandoff control plane.").version(q("@task-handoff/cli")).option("--host <host>","Control plane host",process.env.TASK_HANDOFF_CONTROL_PLANE_HOST||"127.0.0.1").option("-p, --port <port>","Control plane port",Ok,Number(process.env.TASK_HANDOFF_CONTROL_PLANE_PORT)||8081).option("--data-dir <path>","Control plane data directory").option("--static-dir <path>","Control plane Web UI static directory",process.env.TASK_HANDOFF_CONTROL_PLANE_STATIC_DIR||t.resolve(__dirname,"..","ui")).option("--auth-mode <mode>","Control plane auth mode: disabled or password",jk,process.env.TASK_HANDOFF_CONTROL_PLANE_AUTH_MODE||"password").action(async e=>{await async function(e){const t=ME(e.dataDir),n=BT($T(),{dataDir:t.dataDir,host:e.host,port:e.port});try{const t=await kk({...e,service:{...e.service,marketCatalog:e.service?.marketCatalog??bk()}});t.addHook("onClose",async()=>{n.release()}),await t.listen({host:e.host,port:e.port})}catch(t){if(n.release(),t&&"object"==typeof t&&"EADDRINUSE"===t.code)throw Object.assign(new Error(`Control plane port ${e.host}:${e.port} is already in use.`),{statusCode:409,code:"CONTROL_PLANE_PORT_IN_USE",cause:t});throw t}}({host:e.host,port:e.port,dataDir:e.dataDir,staticDir:e.staticDir,auth:{mode:e.authMode}})}),n.command("credentials").description("Initialize or replace Control Plane administrator credentials while the service is stopped.").requiredOption("--username <username>","New administrator username").requiredOption("--password-stdin","Read the new password from standard input").option("--user-id <userId>","Select the account by its local user ID").option("--target-username <username>","Select the account by its current username").option("--initialize-if-needed","Create the administrator only when none exists").option("--data-dir <path>","Control plane data directory").action(async e=>{if(process.stdin.isTTY)throw new Error("Pipe the new password to standard input when using --password-stdin.");const t=[];for await(const e of process.stdin)t.push(Buffer.isBuffer(e)?e:Buffer.from(e));const i=Buffer.concat(t).toString("utf8").replace(/\r?\n$/,""),s=e.dataDir??n.opts().dataDir;if(e.initializeIfNeeded){const t=await async function(e,t,n={}){const i=ME(e),s=BT(n.lockPath||$T(),{dataDir:i.dataDir}),a=new jg(i);try{return await a.init(),a.store.state().initialized&&(await a.store.users.list()).length>0?{created:!1}:{created:!0,user:await a.bootstrapAdmin(t)}}finally{try{await a.store.close()}finally{s.release()}}}(s,{username:e.username,password:i});return void console.log(t.created?"created":"unchanged")}const a=await async function(e,t,n={}){const i=ME(e),s=BT(n.lockPath||$T(),{dataDir:i.dataDir}),a=new jg(i);try{return await a.init(),await a.recoverLocalCredentials(t)}finally{try{await a.store.close()}finally{s.release()}}}(s,{username:e.username,password:i,userId:e.userId,targetUsername:e.targetUsername});console.log(`Updated Control Plane credentials for ${a.primaryUsername||a.displayName}. Existing sessions were revoked.`)}),await n.parseAsync(process.argv)})().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});const Lk=f.z.record(f.z.string(),f.z.union([f.z.string(),f.z.number(),f.z.boolean(),f.z.null(),f.z.array(f.z.union([f.z.string(),f.z.number(),f.z.boolean(),f.z.null()]))])),Dk=f.z.object({id:f.z.string().regex(/^(?:\d{4}|app_\d{4}|import_v\d+\.\d+\.\d+)_[a-z0-9_.-]+$/),checksum:f.z.string().regex(/^[a-f0-9]{64}$/),appliedAt:f.z.string().datetime(),details:Lk}).strict();function Mk(e,t,n){const i=n instanceof Error?n:new Error(String(n));return Object.assign(new Error(`Control Plane ${e} database ${t} failed: ${i.message}`,{cause:i}),{code:`CONTROL_PLANE_DATABASE_${t.toUpperCase()}_FAILED`,dialect:e,phase:t})}const Uk=[Pk("0001_user_access","\nCREATE TABLE cp_metadata (key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL);\nCREATE TABLE cp_users (\n id TEXT PRIMARY KEY NOT NULL, display_name TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('active','disabled','archived')),\n last_login_at TEXT, archived_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_login_identities (\n id TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n kind TEXT NOT NULL CHECK(kind IN ('local-password','oidc','oauth')), normalized_login_name TEXT, password_hash TEXT,\n requires_password_change INTEGER, provider_id TEXT, subject TEXT, verified_email TEXT, last_used_at TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_login_identities_login_name_uq ON cp_login_identities(normalized_login_name);\nCREATE UNIQUE INDEX cp_login_identities_provider_subject_uq ON cp_login_identities(provider_id, subject);\nCREATE INDEX cp_login_identities_user_idx ON cp_login_identities(user_id);\nCREATE TABLE cp_roles (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, description TEXT, system INTEGER NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('active','archived')), permission_ids TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_roles_active_name_uq ON cp_roles(lower(name)) WHERE status = 'active';\nCREATE TABLE cp_user_access_grants (\n user_id TEXT PRIMARY KEY NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n node_scope TEXT NOT NULL,\n instance_scope TEXT NOT NULL, authorization_revision INTEGER NOT NULL CHECK(authorization_revision > 0),\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_user_roles (\n user_id TEXT NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n role_id TEXT NOT NULL REFERENCES cp_roles(id) ON DELETE RESTRICT,\n PRIMARY KEY (user_id, role_id)\n);\nCREATE INDEX cp_user_roles_role_idx ON cp_user_roles(role_id);\nCREATE TABLE cp_user_sessions (\n id TEXT PRIMARY KEY NOT NULL, identity_id TEXT NOT NULL REFERENCES cp_login_identities(id) ON DELETE CASCADE,\n authorization_revision INTEGER NOT NULL,\n token_hash TEXT NOT NULL, expires_at TEXT NOT NULL, last_seen_at TEXT, client_type TEXT NOT NULL CHECK(client_type IN ('web','mobile')),\n device TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_user_sessions_token_hash_uq ON cp_user_sessions(token_hash);\nCREATE INDEX cp_user_sessions_identity_idx ON cp_user_sessions(identity_id);\nCREATE INDEX cp_user_sessions_expiry_idx ON cp_user_sessions(expires_at);\nCREATE TABLE cp_identity_providers (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('oidc','github')),\n status TEXT NOT NULL CHECK(status IN ('enabled','disabled')), login_policy TEXT NOT NULL,\n issuer TEXT, client_id TEXT NOT NULL, client_secret_ciphertext TEXT NOT NULL, callback_url TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_external_identity_approvals (\n id TEXT PRIMARY KEY NOT NULL, provider_id TEXT NOT NULL REFERENCES cp_identity_providers(id) ON DELETE CASCADE,\n subject TEXT NOT NULL, verified_email TEXT, display_name TEXT, status TEXT NOT NULL, expires_at TEXT NOT NULL,\n decided_at TEXT, decided_by_user_id TEXT REFERENCES cp_users(id), created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_external_identity_approvals_lookup_idx ON cp_external_identity_approvals(provider_id, subject, status);\nCREATE TABLE cp_user_audit (\n id TEXT PRIMARY KEY NOT NULL, action TEXT NOT NULL, actor_user_id TEXT, target_type TEXT NOT NULL,\n target_id TEXT, details TEXT NOT NULL, created_at TEXT NOT NULL\n);\nCREATE INDEX cp_user_audit_created_idx ON cp_user_audit(created_at);\n"),Pk("0002_p0_persistence","\nCREATE TABLE cp_nodes (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, connection_mode TEXT NOT NULL,\n connection_path TEXT NOT NULL, connection_enabled INTEGER NOT NULL,\n auth_mode TEXT NOT NULL, auth_key_id TEXT, auth_secret_ciphertext TEXT, auth_paired_at TEXT, auth_pairing_status TEXT,\n endpoint TEXT, control_endpoint TEXT, container_endpoint TEXT, public_web_base TEXT, labels TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_node_pairing_revocations (\n id TEXT PRIMARY KEY NOT NULL, endpoint TEXT NOT NULL, node_id TEXT NOT NULL, key_id TEXT NOT NULL,\n secret_ciphertext TEXT NOT NULL, paired_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_node_pairing_revocations_node_idx ON cp_node_pairing_revocations(node_id);\nCREATE TABLE cp_models (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, endpoint TEXT NOT NULL, key_ciphertext TEXT NOT NULL,\n model TEXT NOT NULL, model_names TEXT NOT NULL, protocols TEXT NOT NULL, app TEXT NOT NULL,\n enabled INTEGER NOT NULL, display_order INTEGER NOT NULL, labels TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_models_order_idx ON cp_models(display_order, name, id);\nCREATE TABLE cp_chat_bridges (\n id TEXT PRIMARY KEY NOT NULL, channel TEXT NOT NULL, name TEXT NOT NULL, enabled INTEGER NOT NULL,\n credential_ciphertext TEXT, default_chat_id TEXT, allowed_user_ids TEXT NOT NULL, poll_interval_ms INTEGER NOT NULL,\n settings TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_chat_session_bindings (\n id TEXT PRIMARY KEY NOT NULL, route_scope TEXT NOT NULL, channel TEXT NOT NULL,\n bridge_id TEXT REFERENCES cp_chat_bridges(id) ON DELETE CASCADE, chat_session_id TEXT NOT NULL,\n user_id TEXT, active_project_id TEXT, active_instance_id TEXT, active_ai_session_id TEXT, last_used_at TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_chat_session_bindings_route_uq ON cp_chat_session_bindings(channel, route_scope, chat_session_id);\nCREATE INDEX cp_chat_session_bindings_bridge_idx ON cp_chat_session_bindings(bridge_id);\nCREATE TABLE cp_git_credentials (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL, scope TEXT NOT NULL, status TEXT NOT NULL,\n revision INTEGER NOT NULL CHECK(revision >= 0), secret_ciphertext TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_git_credential_assignments (\n id TEXT PRIMARY KEY NOT NULL, instance_id TEXT NOT NULL,\n credential_id TEXT NOT NULL REFERENCES cp_git_credentials(id) ON DELETE RESTRICT,\n credential_revision INTEGER NOT NULL CHECK(credential_revision >= 0), assignment_revision INTEGER NOT NULL CHECK(assignment_revision >= 0),\n status TEXT NOT NULL, authorized_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_git_credential_assignments_identity_uq ON cp_git_credential_assignments(instance_id, credential_id);\nCREATE INDEX cp_git_credential_assignments_credential_idx ON cp_git_credential_assignments(credential_id, status);\nCREATE TABLE cp_git_provisioning_intents (\n id TEXT PRIMARY KEY NOT NULL, instance_id TEXT NOT NULL,\n credential_id TEXT NOT NULL REFERENCES cp_git_credentials(id) ON DELETE RESTRICT,\n operation_id TEXT NOT NULL, input_digest TEXT NOT NULL, remote_url TEXT NOT NULL, ref TEXT NOT NULL, clone TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_git_provisioning_intents_operation_uq ON cp_git_provisioning_intents(instance_id, operation_id);\nCREATE INDEX cp_git_provisioning_intents_credential_idx ON cp_git_provisioning_intents(credential_id);\nCREATE TABLE cp_git_audit (\n id TEXT PRIMARY KEY NOT NULL, action TEXT NOT NULL, credential_id TEXT NOT NULL, instance_id TEXT,\n credential_revision INTEGER, assignment_revision INTEGER, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_git_audit_created_idx ON cp_git_audit(created_at);\n"),Pk("0003_p0_pairing_revoke_phase","ALTER TABLE cp_node_pairing_revocations ADD COLUMN phase TEXT NOT NULL DEFAULT 'pending-compensation';"),Pk("0004_p0_chat_credential_metadata",'ALTER TABLE cp_chat_bridges ADD COLUMN credential_metadata TEXT NOT NULL DEFAULT \'{"tokenSet":false,"clientSecretSet":false,"appSecretSet":false}\';'),Pk("0005_model_legacy_projections","\nCREATE TABLE cp_model_legacy_projections (\n id TEXT PRIMARY KEY NOT NULL, model_id TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_model_legacy_projections_model_idx ON cp_model_legacy_projections(model_id);\n"),Pk("0006_cli_sessions","\nALTER TABLE cp_user_sessions RENAME TO cp_user_sessions_pre_cli;\nCREATE TABLE cp_user_sessions (\n id TEXT PRIMARY KEY NOT NULL, identity_id TEXT NOT NULL REFERENCES cp_login_identities(id) ON DELETE CASCADE,\n authorization_revision INTEGER NOT NULL,\n token_hash TEXT NOT NULL, expires_at TEXT NOT NULL, last_seen_at TEXT,\n client_type TEXT NOT NULL CHECK(client_type IN ('web','mobile','cli')),\n device TEXT, client_info TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nINSERT INTO cp_user_sessions (id, identity_id, authorization_revision, token_hash, expires_at, last_seen_at, client_type, device, client_info, created_at, updated_at)\n SELECT id, identity_id, authorization_revision, token_hash, expires_at, last_seen_at, client_type, device, NULL, created_at, updated_at\n FROM cp_user_sessions_pre_cli;\nDROP TABLE cp_user_sessions_pre_cli;\nCREATE UNIQUE INDEX cp_user_sessions_token_hash_uq ON cp_user_sessions(token_hash);\nCREATE INDEX cp_user_sessions_identity_idx ON cp_user_sessions(identity_id);\nCREATE INDEX cp_user_sessions_expiry_idx ON cp_user_sessions(expires_at);\n"),Pk("0007_local_trust_identities","\nALTER TABLE cp_user_sessions RENAME TO cp_user_sessions_pre_local_trust;\nALTER TABLE cp_login_identities RENAME TO cp_login_identities_pre_local_trust;\nCREATE TABLE cp_login_identities (\n id TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n kind TEXT NOT NULL CHECK(kind IN ('local-password','oidc','oauth','local-trust')), normalized_login_name TEXT, password_hash TEXT,\n requires_password_change INTEGER, provider_id TEXT, subject TEXT, verified_email TEXT, last_used_at TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nINSERT INTO cp_login_identities (id, user_id, kind, normalized_login_name, password_hash, requires_password_change, provider_id, subject, verified_email, last_used_at, created_at, updated_at)\n SELECT id, user_id, kind, normalized_login_name, password_hash, requires_password_change, provider_id, subject, verified_email, last_used_at, created_at, updated_at\n FROM cp_login_identities_pre_local_trust;\nCREATE TABLE cp_user_sessions (\n id TEXT PRIMARY KEY NOT NULL, identity_id TEXT NOT NULL REFERENCES cp_login_identities(id) ON DELETE CASCADE,\n authorization_revision INTEGER NOT NULL,\n token_hash TEXT NOT NULL, expires_at TEXT NOT NULL, last_seen_at TEXT,\n client_type TEXT NOT NULL CHECK(client_type IN ('web','mobile','cli')),\n device TEXT, client_info TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nINSERT INTO cp_user_sessions (id, identity_id, authorization_revision, token_hash, expires_at, last_seen_at, client_type, device, client_info, created_at, updated_at)\n SELECT id, identity_id, authorization_revision, token_hash, expires_at, last_seen_at, client_type, device, client_info, created_at, updated_at\n FROM cp_user_sessions_pre_local_trust;\nDROP TABLE cp_user_sessions_pre_local_trust;\nDROP TABLE cp_login_identities_pre_local_trust;\nCREATE UNIQUE INDEX cp_login_identities_login_name_uq ON cp_login_identities(normalized_login_name);\nCREATE UNIQUE INDEX cp_login_identities_provider_subject_uq ON cp_login_identities(provider_id, subject);\nCREATE INDEX cp_login_identities_user_idx ON cp_login_identities(user_id);\nCREATE UNIQUE INDEX cp_user_sessions_token_hash_uq ON cp_user_sessions(token_hash);\nCREATE INDEX cp_user_sessions_identity_idx ON cp_user_sessions(identity_id);\nCREATE INDEX cp_user_sessions_expiry_idx ON cp_user_sessions(expires_at);\n"),Pk("0008_model_request_mappings","ALTER TABLE cp_models ADD COLUMN mappings TEXT NOT NULL DEFAULT '[]';"),Pk("0009_drop_model_legacy_projections","DROP TABLE IF EXISTS cp_model_legacy_projections;")],qk=[Pk("0001_user_access","\nCREATE TABLE cp_metadata (key TEXT PRIMARY KEY NOT NULL, value JSONB NOT NULL);\nCREATE TABLE cp_users (\n id TEXT PRIMARY KEY NOT NULL, display_name TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('active','disabled','archived')),\n last_login_at TEXT, archived_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_login_identities (\n id TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n kind TEXT NOT NULL CHECK(kind IN ('local-password','oidc','oauth')), normalized_login_name TEXT, password_hash TEXT,\n requires_password_change BOOLEAN, provider_id TEXT, subject TEXT, verified_email TEXT, last_used_at TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_login_identities_login_name_uq ON cp_login_identities(normalized_login_name);\nCREATE UNIQUE INDEX cp_login_identities_provider_subject_uq ON cp_login_identities(provider_id, subject);\nCREATE INDEX cp_login_identities_user_idx ON cp_login_identities(user_id);\nCREATE TABLE cp_roles (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, description TEXT, system BOOLEAN NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('active','archived')), permission_ids JSONB NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_roles_active_name_uq ON cp_roles(lower(name)) WHERE status = 'active';\nCREATE TABLE cp_user_access_grants (\n user_id TEXT PRIMARY KEY NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n node_scope JSONB NOT NULL,\n instance_scope JSONB NOT NULL, authorization_revision INTEGER NOT NULL CHECK(authorization_revision > 0),\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_user_roles (\n user_id TEXT NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n role_id TEXT NOT NULL REFERENCES cp_roles(id) ON DELETE RESTRICT,\n PRIMARY KEY (user_id, role_id)\n);\nCREATE INDEX cp_user_roles_role_idx ON cp_user_roles(role_id);\nCREATE TABLE cp_user_sessions (\n id TEXT PRIMARY KEY NOT NULL, identity_id TEXT NOT NULL REFERENCES cp_login_identities(id) ON DELETE CASCADE,\n authorization_revision INTEGER NOT NULL,\n token_hash TEXT NOT NULL, expires_at TEXT NOT NULL, last_seen_at TEXT, client_type TEXT NOT NULL CHECK(client_type IN ('web','mobile')),\n device JSONB, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_user_sessions_token_hash_uq ON cp_user_sessions(token_hash);\nCREATE INDEX cp_user_sessions_identity_idx ON cp_user_sessions(identity_id);\nCREATE INDEX cp_user_sessions_expiry_idx ON cp_user_sessions(expires_at);\nCREATE TABLE cp_identity_providers (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('oidc','github')),\n status TEXT NOT NULL CHECK(status IN ('enabled','disabled')), login_policy TEXT NOT NULL,\n issuer TEXT, client_id TEXT NOT NULL, client_secret_ciphertext TEXT NOT NULL, callback_url TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_external_identity_approvals (\n id TEXT PRIMARY KEY NOT NULL, provider_id TEXT NOT NULL REFERENCES cp_identity_providers(id) ON DELETE CASCADE,\n subject TEXT NOT NULL, verified_email TEXT, display_name TEXT, status TEXT NOT NULL, expires_at TEXT NOT NULL,\n decided_at TEXT, decided_by_user_id TEXT REFERENCES cp_users(id), created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_external_identity_approvals_lookup_idx ON cp_external_identity_approvals(provider_id, subject, status);\nCREATE TABLE cp_user_audit (\n id TEXT PRIMARY KEY NOT NULL, action TEXT NOT NULL, actor_user_id TEXT, target_type TEXT NOT NULL,\n target_id TEXT, details JSONB NOT NULL, created_at TEXT NOT NULL\n);\nCREATE INDEX cp_user_audit_created_idx ON cp_user_audit(created_at);\n"),Pk("0002_p0_persistence","\nCREATE TABLE cp_nodes (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, connection_mode TEXT NOT NULL,\n connection_path JSONB NOT NULL, connection_enabled BOOLEAN NOT NULL,\n auth_mode TEXT NOT NULL, auth_key_id TEXT, auth_secret_ciphertext TEXT, auth_paired_at TEXT, auth_pairing_status TEXT,\n endpoint TEXT, control_endpoint TEXT, container_endpoint TEXT, public_web_base TEXT, labels JSONB NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_node_pairing_revocations (\n id TEXT PRIMARY KEY NOT NULL, endpoint TEXT NOT NULL, node_id TEXT NOT NULL, key_id TEXT NOT NULL,\n secret_ciphertext TEXT NOT NULL, paired_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_node_pairing_revocations_node_idx ON cp_node_pairing_revocations(node_id);\nCREATE TABLE cp_models (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, endpoint TEXT NOT NULL, key_ciphertext TEXT NOT NULL,\n model TEXT NOT NULL, model_names JSONB NOT NULL, protocols JSONB NOT NULL, app TEXT NOT NULL,\n enabled BOOLEAN NOT NULL, display_order INTEGER NOT NULL, labels JSONB NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_models_order_idx ON cp_models(display_order, name, id);\nCREATE TABLE cp_chat_bridges (\n id TEXT PRIMARY KEY NOT NULL, channel TEXT NOT NULL, name TEXT NOT NULL, enabled BOOLEAN NOT NULL,\n credential_ciphertext TEXT, default_chat_id TEXT, allowed_user_ids JSONB NOT NULL, poll_interval_ms INTEGER NOT NULL,\n settings JSONB NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_chat_session_bindings (\n id TEXT PRIMARY KEY NOT NULL, route_scope TEXT NOT NULL, channel TEXT NOT NULL,\n bridge_id TEXT REFERENCES cp_chat_bridges(id) ON DELETE CASCADE, chat_session_id TEXT NOT NULL,\n user_id TEXT, active_project_id TEXT, active_instance_id TEXT, active_ai_session_id TEXT, last_used_at TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_chat_session_bindings_route_uq ON cp_chat_session_bindings(channel, route_scope, chat_session_id);\nCREATE INDEX cp_chat_session_bindings_bridge_idx ON cp_chat_session_bindings(bridge_id);\nCREATE TABLE cp_git_credentials (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL, scope JSONB NOT NULL, status TEXT NOT NULL,\n revision INTEGER NOT NULL CHECK(revision >= 0), secret_ciphertext TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_git_credential_assignments (\n id TEXT PRIMARY KEY NOT NULL, instance_id TEXT NOT NULL,\n credential_id TEXT NOT NULL REFERENCES cp_git_credentials(id) ON DELETE RESTRICT,\n credential_revision INTEGER NOT NULL CHECK(credential_revision >= 0), assignment_revision INTEGER NOT NULL CHECK(assignment_revision >= 0),\n status TEXT NOT NULL, authorized_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_git_credential_assignments_identity_uq ON cp_git_credential_assignments(instance_id, credential_id);\nCREATE INDEX cp_git_credential_assignments_credential_idx ON cp_git_credential_assignments(credential_id, status);\nCREATE TABLE cp_git_provisioning_intents (\n id TEXT PRIMARY KEY NOT NULL, instance_id TEXT NOT NULL,\n credential_id TEXT NOT NULL REFERENCES cp_git_credentials(id) ON DELETE RESTRICT,\n operation_id TEXT NOT NULL, input_digest TEXT NOT NULL, remote_url TEXT NOT NULL, ref JSONB NOT NULL, clone JSONB NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_git_provisioning_intents_operation_uq ON cp_git_provisioning_intents(instance_id, operation_id);\nCREATE INDEX cp_git_provisioning_intents_credential_idx ON cp_git_provisioning_intents(credential_id);\nCREATE TABLE cp_git_audit (\n id TEXT PRIMARY KEY NOT NULL, action TEXT NOT NULL, credential_id TEXT NOT NULL, instance_id TEXT,\n credential_revision INTEGER, assignment_revision INTEGER, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_git_audit_created_idx ON cp_git_audit(created_at);\n"),Pk("0003_p0_pairing_revoke_phase","ALTER TABLE cp_node_pairing_revocations ADD COLUMN phase TEXT NOT NULL DEFAULT 'pending-compensation';"),Pk("0004_p0_chat_credential_metadata",'ALTER TABLE cp_chat_bridges ADD COLUMN credential_metadata JSONB NOT NULL DEFAULT \'{"tokenSet":false,"clientSecretSet":false,"appSecretSet":false}\'::jsonb;'),Pk("0005_model_legacy_projections","\nCREATE TABLE cp_model_legacy_projections (\n id TEXT PRIMARY KEY NOT NULL, model_id TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_model_legacy_projections_model_idx ON cp_model_legacy_projections(model_id);\n"),Pk("0006_cli_sessions","\nALTER TABLE cp_user_sessions DROP CONSTRAINT IF EXISTS cp_user_sessions_client_type_check;\nALTER TABLE cp_user_sessions ADD CONSTRAINT cp_user_sessions_client_type_check CHECK (client_type IN ('web','mobile','cli'));\nALTER TABLE cp_user_sessions ADD COLUMN IF NOT EXISTS client_info JSONB;\n"),Pk("0007_local_trust_identities","\nALTER TABLE cp_login_identities DROP CONSTRAINT IF EXISTS cp_login_identities_kind_check;\nALTER TABLE cp_login_identities ADD CONSTRAINT cp_login_identities_kind_check CHECK (kind IN ('local-password','oidc','oauth','local-trust'));\n"),Pk("0008_model_request_mappings","ALTER TABLE cp_models ADD COLUMN mappings JSONB NOT NULL DEFAULT '[]'::jsonb;"),Pk("0009_drop_model_legacy_projections","DROP TABLE IF EXISTS cp_model_legacy_projections;")],$k=f.z.object({id:f.z.string().trim().min(1),createdAt:f.z.string().datetime(),updatedAt:f.z.string().datetime()}),Bk=$k.extend({displayName:f.z.string().trim().min(1).max(160),status:$u,lastLoginAt:f.z.string().datetime().optional(),archivedAt:f.z.string().datetime().optional()}).strict().superRefine((e,t)=>{"archived"!==e.status||e.archivedAt||t.addIssue({code:"custom",path:["archivedAt"],message:"Archived users require archivedAt."}),"archived"!==e.status&&e.archivedAt&&t.addIssue({code:"custom",path:["archivedAt"],message:"Only archived users can have archivedAt."})}),Fk=$k.extend({userId:f.z.string().trim().min(1),kind:Bu,normalizedLoginName:f.z.string().trim().min(1).max(160).optional(),passwordHash:f.z.string().trim().min(1).optional(),requiresPasswordChange:f.z.boolean().optional(),providerId:f.z.string().trim().min(1).optional(),subject:f.z.string().trim().min(1).max(500).optional(),verifiedEmail:f.z.string().email().optional(),lastUsedAt:f.z.string().datetime().optional()}).strict().superRefine((e,t)=>{"local-password"===e.kind?(e.normalizedLoginName||t.addIssue({code:"custom",path:["normalizedLoginName"],message:"Local identity requires normalizedLoginName."}),e.passwordHash||t.addIssue({code:"custom",path:["passwordHash"],message:"Local identity requires passwordHash."}),(e.providerId||e.subject)&&t.addIssue({code:"custom",path:["providerId"],message:"Local identity cannot reference a provider."})):"local-trust"===e.kind?((e.passwordHash||e.normalizedLoginName)&&t.addIssue({code:"custom",path:["passwordHash"],message:"Local trust identity cannot contain local credentials."}),(e.providerId||e.subject||e.verifiedEmail)&&t.addIssue({code:"custom",path:["providerId"],message:"Local trust identity cannot reference an external provider."})):(e.providerId&&e.subject||t.addIssue({code:"custom",path:["providerId"],message:"External identity requires providerId and subject."}),(e.passwordHash||e.normalizedLoginName)&&t.addIssue({code:"custom",path:["passwordHash"],message:"External identity cannot contain local credentials."}))}),Hk=$k.extend({name:f.z.string().trim().min(1).max(120),description:f.z.string().trim().max(500).optional(),system:f.z.boolean(),status:Fu,permissionIds:f.z.array(qu)}).strict(),Gk=f.z.object({userId:f.z.string().trim().min(1),roleIds:f.z.array(f.z.string().trim().min(1)).min(1).max(100),nodeScope:Ku,instanceScope:Xu.default({kind:"inherit-node-scope"}),authorizationRevision:f.z.number().int().positive(),createdAt:f.z.string().datetime(),updatedAt:f.z.string().datetime()}).strict(),Wk=$k.extend({userId:f.z.string().trim().min(1),identityId:f.z.string().trim().min(1),authorizationRevision:f.z.number().int().positive(),tokenHash:f.z.string().trim().min(1),expiresAt:f.z.string().datetime(),lastSeenAt:f.z.string().datetime().optional(),clientType:f.z.enum(["web","mobile","cli"]),device:f.z.object({id:f.z.string().trim().min(1),name:f.z.string().trim().min(1),platform:f.z.enum(["ios","android"]),appVersion:f.z.string().trim().min(1).optional()}).strict().optional(),clientInfo:fm.optional()}).strict().refine(e=>"mobile"!==e.clientType||Boolean(e.device),{path:["device"],message:"Mobile sessions require device metadata."}).refine(e=>"cli"!==e.clientType||Boolean(e.clientInfo),{path:["clientInfo"],message:"CLI sessions require client metadata."}),Vk=$k.extend({name:f.z.string().trim().min(1).max(120),kind:Hu,status:Gu,loginPolicy:Wu,issuer:f.z.string().url().optional(),clientId:f.z.string().trim().min(1).max(500),clientSecretCiphertext:f.z.string().trim().min(1),callbackUrl:f.z.string().url()}).strict().superRefine((e,t)=>{"oidc"!==e.kind||e.issuer||t.addIssue({code:"custom",path:["issuer"],message:"OIDC provider requires issuer."})}),Kk={users:Bk,identities:Fk,roles:Hk,grants:Gk,sessions:Wk,providers:Vk,approvals:$k.extend({providerId:f.z.string().trim().min(1),subject:f.z.string().trim().min(1).max(500),verifiedEmail:f.z.string().email().optional(),displayName:f.z.string().trim().min(1).max(160).optional(),status:f.z.enum(["pending","approved","rejected","expired"]),expiresAt:f.z.string().datetime(),decidedAt:f.z.string().datetime().optional(),decidedByUserId:f.z.string().trim().min(1).optional()}).strict(),audit:f.z.object({id:f.z.string().trim().min(1),action:f.z.string().trim().min(1).max(160),actorUserId:f.z.string().trim().min(1).optional(),targetType:f.z.string().trim().min(1).max(120),targetId:f.z.string().trim().min(1).optional(),details:f.z.record(f.z.string(),f.z.unknown()),createdAt:f.z.string().datetime()}).strict()};function Xk(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,void 0===t?null:t]))}function Yk(e,t){return e.parse(Object.fromEntries(Object.entries(t).filter(([,e])=>null!==e)))}const Jk={createdAt:R.text("created_at").notNull(),updatedAt:R.text("updated_at").notNull()},Qk=R.pgTable("cp_metadata",{key:R.text("key").primaryKey(),value:R.jsonb("value").notNull()}),Zk=R.pgTable("cp_users",{id:R.text("id").primaryKey(),displayName:R.text("display_name").notNull(),status:R.text("status").notNull(),lastLoginAt:R.text("last_login_at"),archivedAt:R.text("archived_at"),...Jk}),eO=R.pgTable("cp_login_identities",{id:R.text("id").primaryKey(),userId:R.text("user_id").notNull().references(()=>Zk.id,{onDelete:"cascade"}),kind:R.text("kind").notNull(),normalizedLoginName:R.text("normalized_login_name"),passwordHash:R.text("password_hash"),requiresPasswordChange:R.boolean("requires_password_change"),providerId:R.text("provider_id"),subject:R.text("subject"),verifiedEmail:R.text("verified_email"),lastUsedAt:R.text("last_used_at"),...Jk},e=>[R.uniqueIndex("cp_login_identities_login_name_uq").on(e.normalizedLoginName),R.uniqueIndex("cp_login_identities_provider_subject_uq").on(e.providerId,e.subject),R.index("cp_login_identities_user_idx").on(e.userId)]),tO=R.pgTable("cp_roles",{id:R.text("id").primaryKey(),name:R.text("name").notNull(),description:R.text("description"),system:R.boolean("system").notNull(),status:R.text("status").notNull(),permissionIds:R.jsonb("permission_ids").$type().notNull(),...Jk},e=>[R.uniqueIndex("cp_roles_active_name_uq").on(z.sql`lower(${e.name})`).where(z.sql`${e.status} = 'active'`)]),nO=R.pgTable("cp_user_access_grants",{userId:R.text("user_id").primaryKey().references(()=>Zk.id,{onDelete:"cascade"}),nodeScope:R.jsonb("node_scope").$type().notNull(),instanceScope:R.jsonb("instance_scope").$type().notNull(),authorizationRevision:R.integer("authorization_revision").notNull(),...Jk}),iO=R.pgTable("cp_user_roles",{userId:R.text("user_id").notNull().references(()=>Zk.id,{onDelete:"cascade"}),roleId:R.text("role_id").notNull().references(()=>tO.id,{onDelete:"restrict"})},e=>[R.primaryKey({columns:[e.userId,e.roleId]}),R.index("cp_user_roles_role_idx").on(e.roleId)]),sO=R.pgTable("cp_user_sessions",{id:R.text("id").primaryKey(),identityId:R.text("identity_id").notNull().references(()=>eO.id,{onDelete:"cascade"}),authorizationRevision:R.integer("authorization_revision").notNull(),tokenHash:R.text("token_hash").notNull(),expiresAt:R.text("expires_at").notNull(),lastSeenAt:R.text("last_seen_at"),clientType:R.text("client_type").notNull(),device:R.jsonb("device").$type(),clientInfo:R.jsonb("client_info").$type(),...Jk},e=>[R.uniqueIndex("cp_user_sessions_token_hash_uq").on(e.tokenHash),R.index("cp_user_sessions_identity_idx").on(e.identityId),R.index("cp_user_sessions_expiry_idx").on(e.expiresAt)]),aO=R.pgTable("cp_identity_providers",{id:R.text("id").primaryKey(),name:R.text("name").notNull(),kind:R.text("kind").notNull(),status:R.text("status").notNull(),loginPolicy:R.text("login_policy").notNull(),issuer:R.text("issuer"),clientId:R.text("client_id").notNull(),clientSecretCiphertext:R.text("client_secret_ciphertext").notNull(),callbackUrl:R.text("callback_url").notNull(),...Jk}),oO=R.pgTable("cp_external_identity_approvals",{id:R.text("id").primaryKey(),providerId:R.text("provider_id").notNull().references(()=>aO.id,{onDelete:"cascade"}),subject:R.text("subject").notNull(),verifiedEmail:R.text("verified_email"),displayName:R.text("display_name"),status:R.text("status").notNull(),expiresAt:R.text("expires_at").notNull(),decidedAt:R.text("decided_at"),decidedByUserId:R.text("decided_by_user_id").references(()=>Zk.id),...Jk},e=>[R.index("cp_external_identity_approvals_lookup_idx").on(e.providerId,e.subject,e.status)]),rO=R.pgTable("cp_user_audit",{id:R.text("id").primaryKey(),action:R.text("action").notNull(),actorUserId:R.text("actor_user_id"),targetType:R.text("target_type").notNull(),targetId:R.text("target_id"),details:R.jsonb("details").$type().notNull(),createdAt:R.text("created_at").notNull()},e=>[R.index("cp_user_audit_created_idx").on(e.createdAt)]),cO=R.pgTable("cp_migration_ledger",{id:R.text("id").primaryKey(),checksum:R.text("checksum").notNull(),appliedAt:R.text("applied_at").notNull(),details:R.jsonb("details").$type().notNull()}),dO=R.pgTable("cp_nodes",{id:R.text("id").primaryKey(),name:R.text("name").notNull(),connectionMode:R.text("connection_mode").notNull(),connectionPath:R.jsonb("connection_path").notNull(),connectionEnabled:R.boolean("connection_enabled").notNull(),authMode:R.text("auth_mode").notNull(),authKeyId:R.text("auth_key_id"),authSecretCiphertext:R.text("auth_secret_ciphertext"),authPairedAt:R.text("auth_paired_at"),authPairingStatus:R.text("auth_pairing_status"),endpoint:R.text("endpoint"),controlEndpoint:R.text("control_endpoint"),containerEndpoint:R.text("container_endpoint"),publicWebBase:R.text("public_web_base"),labels:R.jsonb("labels").$type().notNull(),...Jk}),lO=R.pgTable("cp_node_pairing_revocations",{id:R.text("id").primaryKey(),endpoint:R.text("endpoint").notNull(),nodeId:R.text("node_id").notNull(),keyId:R.text("key_id").notNull(),secretCiphertext:R.text("secret_ciphertext").notNull(),pairedAt:R.text("paired_at").notNull(),phase:R.text("phase").notNull().default("pending-compensation"),...Jk},e=>[R.index("cp_node_pairing_revocations_node_idx").on(e.nodeId)]),pO=R.pgTable("cp_models",{id:R.text("id").primaryKey(),name:R.text("name").notNull(),endpoint:R.text("endpoint").notNull(),keyCiphertext:R.text("key_ciphertext").notNull(),model:R.text("model").notNull(),modelNames:R.jsonb("model_names").$type().notNull(),mappings:R.jsonb("mappings").$type().notNull(),protocols:R.jsonb("protocols").$type().notNull(),app:R.text("app").notNull(),enabled:R.boolean("enabled").notNull(),order:R.integer("display_order").notNull(),labels:R.jsonb("labels").$type().notNull(),...Jk},e=>[R.index("cp_models_order_idx").on(e.order,e.name,e.id)]),uO=R.pgTable("cp_chat_bridges",{id:R.text("id").primaryKey(),channel:R.text("channel").notNull(),name:R.text("name").notNull(),enabled:R.boolean("enabled").notNull(),credentialCiphertext:R.text("credential_ciphertext"),credentialMetadata:R.jsonb("credential_metadata").$type().notNull().default({tokenSet:!1,clientSecretSet:!1,appSecretSet:!1}),defaultChatId:R.text("default_chat_id"),allowedUserIds:R.jsonb("allowed_user_ids").$type().notNull(),pollIntervalMs:R.integer("poll_interval_ms").notNull(),settings:R.jsonb("settings").$type().notNull(),...Jk}),mO=R.pgTable("cp_chat_session_bindings",{id:R.text("id").primaryKey(),routeScope:R.text("route_scope").notNull(),channel:R.text("channel").notNull(),bridgeId:R.text("bridge_id").references(()=>uO.id,{onDelete:"cascade"}),chatSessionId:R.text("chat_session_id").notNull(),userId:R.text("user_id"),activeProjectId:R.text("active_project_id"),activeInstanceId:R.text("active_instance_id"),activeAiSessionId:R.text("active_ai_session_id"),lastUsedAt:R.text("last_used_at").notNull(),...Jk},e=>[R.uniqueIndex("cp_chat_session_bindings_route_uq").on(e.channel,e.routeScope,e.chatSessionId),R.index("cp_chat_session_bindings_bridge_idx").on(e.bridgeId)]),hO=R.pgTable("cp_git_credentials",{id:R.text("id").primaryKey(),name:R.text("name").notNull(),kind:R.text("kind").notNull(),scope:R.jsonb("scope").notNull(),status:R.text("status").notNull(),revision:R.integer("revision").notNull(),secretCiphertext:R.text("secret_ciphertext").notNull(),...Jk}),gO=R.pgTable("cp_git_credential_assignments",{id:R.text("id").primaryKey(),instanceId:R.text("instance_id").notNull(),credentialId:R.text("credential_id").notNull().references(()=>hO.id,{onDelete:"restrict"}),credentialRevision:R.integer("credential_revision").notNull(),assignmentRevision:R.integer("assignment_revision").notNull(),status:R.text("status").notNull(),authorizedAt:R.text("authorized_at").notNull(),...Jk},e=>[R.uniqueIndex("cp_git_credential_assignments_identity_uq").on(e.instanceId,e.credentialId),R.index("cp_git_credential_assignments_credential_idx").on(e.credentialId,e.status)]),fO=R.pgTable("cp_git_provisioning_intents",{id:R.text("id").primaryKey(),instanceId:R.text("instance_id").notNull(),credentialId:R.text("credential_id").notNull().references(()=>hO.id,{onDelete:"restrict"}),operationId:R.text("operation_id").notNull(),inputDigest:R.text("input_digest").notNull(),remoteUrl:R.text("remote_url").notNull(),ref:R.jsonb("ref").notNull(),clone:R.jsonb("clone").notNull(),...Jk},e=>[R.uniqueIndex("cp_git_provisioning_intents_operation_uq").on(e.instanceId,e.operationId),R.index("cp_git_provisioning_intents_credential_idx").on(e.credentialId)]),yO=R.pgTable("cp_git_audit",{id:R.text("id").primaryKey(),action:R.text("action").notNull(),credentialId:R.text("credential_id").notNull(),instanceId:R.text("instance_id"),credentialRevision:R.integer("credential_revision"),assignmentRevision:R.integer("assignment_revision"),...Jk},e=>[R.index("cp_git_audit_created_idx").on(e.createdAt)]);function bO(e){return`"${e.replaceAll('"','""')}"`}function IO(e,t,n){return{list:async()=>(await e.select().from(t).orderBy(z.asc(t.id))).map(e=>Yk(n,e)),async get(i){const s=await e.select().from(t).where(z.eq(t.id,i)).limit(1);return s[0]?Yk(n,s[0]):void 0},async put(i){const s=Xk(n.parse(i)),a=Object.fromEntries(Object.entries(s).filter(([e])=>"id"!==e));return await e.insert(t).values(s).onConflictDoUpdate({target:t.id,set:a}),Yk(n,s)},delete:async n=>(await e.delete(t).where(z.eq(t.id,n)).returning({id:t.id})).length>0}}function vO(e){const t=IO(e,eO,Kk.identities),n=async t=>{const n=await e.select().from(eO).where(t).limit(1);return n[0]?Yk(Kk.identities,n[0]):void 0};return{...t,findByLoginName:e=>n(z.eq(eO.normalizedLoginName,e)),findByProviderSubject:(e,t)=>n(z.and(z.eq(eO.providerId,e),z.eq(eO.subject,t))),listByUser:async t=>(await e.select().from(eO).where(z.eq(eO.userId,t))).map(e=>Yk(Kk.identities,e)),existsForProvider:async t=>(await e.select({id:eO.id}).from(eO).where(z.eq(eO.providerId,t)).limit(1)).length>0}}function wO(e){const t=new Map;for(const n of e){const e=n.grant.userId,i=t.get(e)||{grant:n.grant,roleIds:[]};i.roleIds.push(n.roleId),t.set(e,i)}return[...t.values()].map(({grant:e,roleIds:t})=>Kk.grants.parse({...e,roleIds:t.sort()}))}function xO(e,t,n){const i=t=>{const n=e.select({grant:nO,roleId:iO.roleId}).from(nO).innerJoin(iO,z.eq(nO.userId,iO.userId));return t?n.where(z.inArray(nO.userId,t)):n};return{list:async()=>wO(await i()),get:async e=>wO(await i([e]))[0],async listByRole(t){const n=(await e.select({userId:iO.userId}).from(iO).where(z.eq(iO.roleId,t))).map(e=>e.userId);return 0===n.length?[]:wO(await i(n))},put:i=>n?(async t=>{const n=Kk.grants.parse(t),{roleIds:i,...s}=n;return await e.insert(nO).values(s).onConflictDoUpdate({target:nO.userId,set:Object.fromEntries(Object.entries(s).filter(([e])=>"userId"!==e))}),await e.delete(iO).where(z.eq(iO.userId,n.userId)),await e.insert(iO).values(i.map(e=>({userId:n.userId,roleId:e}))),n})(i):t(e=>e.grants.put(i)),delete:async t=>(await e.delete(nO).where(z.eq(nO.userId,t)).returning({userId:nO.userId})).length>0}}function _O(e){const t=e=>e.map(e=>Yk(Kk.sessions,{...e.session,userId:e.userId})),n=()=>e.select({session:sO,userId:eO.userId}).from(sO).innerJoin(eO,z.eq(sO.identityId,eO.id));return{list:async()=>t(await n()),get:async e=>t(await n().where(z.eq(sO.id,e)).limit(1))[0],listByUser:async e=>t(await n().where(z.eq(eO.userId,e))),async put(t){const n=Kk.sessions.parse(t),i=await e.select({userId:eO.userId}).from(eO).where(z.eq(eO.id,n.identityId)).limit(1);if(i[0]?.userId!==n.userId)throw new Error("Session identity does not belong to the requested user.");const{userId:s,...a}=n;return await e.insert(sO).values(a).onConflictDoUpdate({target:sO.id,set:Object.fromEntries(Object.entries(a).filter(([e])=>"id"!==e))}),n},delete:async t=>(await e.delete(sO).where(z.eq(sO.id,t)).returning({id:sO.id})).length>0}}function SO(e){return{...IO(e,oO,Kk.approvals),async findActivePending(t,n,i){const s=await e.select().from(oO).where(z.and(z.eq(oO.providerId,t),z.eq(oO.subject,n),z.eq(oO.status,"pending"),z.gt(oO.expiresAt,i))).limit(1);return s[0]?Yk(Kk.approvals,s[0]):void 0},hasActivePendingForProvider:async(t,n)=>(await e.select({id:oO.id}).from(oO).where(z.and(z.eq(oO.providerId,t),z.eq(oO.status,"pending"),z.gt(oO.expiresAt,n))).limit(1)).length>0}}function AO(e){return{...IO(e,gO,iT.gitAssignments),async putIfRevision(t,n){const i=iT.gitAssignments.parse(t);if(void 0===n)return(await e.insert(gO).values(i).onConflictDoNothing().returning({id:gO.id})).length>0;const{id:s,...a}=i;return(await e.update(gO).set(a).where(z.and(z.eq(gO.id,i.id),z.eq(gO.assignmentRevision,n))).returning({id:gO.id})).length>0}}}function EO(e){return{...IO(e,fO,iT.gitProvisioningIntents),async insert(t){const n=iT.gitProvisioningIntents.parse(t);return(await e.insert(fO).values(n).onConflictDoNothing().returning({id:fO.id})).length>0}}}function TO(e){const t=IO(e,yO,iT.gitAudit);return{list:t.list,get:t.get,async append(t){const n=iT.gitAudit.parse(t);await e.insert(yO).values(n)}}}function zO(e,t,n=!1){let i;const s=async t=>n?t(i):e.transaction(async e=>t(zO(e,async()=>{},!0)));return i={dialect:"postgresql",users:IO(e,Zk,Kk.users),identities:vO(e),roles:IO(e,tO,Kk.roles),grants:xO(e,s,n),sessions:_O(e),providers:IO(e,aO,Kk.providers),approvals:SO(e),audit:IO(e,rO,Kk.audit),nodes:IO(e,dO,iT.nodes),pairingRevocations:IO(e,lO,iT.pairingRevocations),models:IO(e,pO,iT.models),chatBridges:IO(e,uO,iT.chatBridges),chatSessions:IO(e,mO,iT.chatSessions),gitCredentials:IO(e,hO,iT.gitCredentials),gitAssignments:AO(e),gitProvisioningIntents:EO(e),gitAudit:TO(e),async metadata(){const t=await e.select().from(Qk).where(z.eq(Qk.key,"user_store")).limit(1);return t[0]?.value||{schemaVersion:1}},async putMetadata(t){await e.insert(Qk).values({key:"user_store",value:t}).onConflictDoUpdate({target:Qk.key,set:{value:t}})},migration:async t=>(await e.select().from(cO).where(z.eq(cO.id,t)).limit(1))[0],async putMigration(t){t=Dk.parse(t),await e.insert(cO).values(t).onConflictDoUpdate({target:cO.id,set:{checksum:t.checksum,appliedAt:t.appliedAt,details:t.details}})},transaction:s,close:t},i}var NO=Object.freeze({__proto__:null,createPostgresqlUserRepository:async function(e){const t=new C.Pool({connectionString:e.connectionString,options:`-c search_path=${e.schema}`,application_name:"task-handoff-control-plane"});try{await t.query("SELECT 1")}catch(e){throw await t.end().catch(()=>{}),Mk("postgresql","connect",e)}try{return await async function(e,t){const n=await e.connect();try{await n.query("BEGIN"),await n.query("SELECT pg_advisory_xact_lock(hashtext($1))",[`task-handoff:user-access:${t}`]),await n.query(`CREATE SCHEMA IF NOT EXISTS ${bO(t)}`),await n.query(`SET LOCAL search_path TO ${bO(t)}`),await n.query("CREATE TABLE IF NOT EXISTS cp_migration_ledger (\n id TEXT PRIMARY KEY NOT NULL, checksum TEXT NOT NULL, applied_at TEXT NOT NULL, details JSONB NOT NULL\n )");for(const e of qk){const t=await n.query("SELECT checksum FROM cp_migration_ledger WHERE id = $1",[e.id]);if(t.rows[0]){if(t.rows[0].checksum!==e.checksum)throw new Error(`Migration checksum mismatch for ${e.id}.`)}else await n.query(e.sql),await n.query("INSERT INTO cp_migration_ledger (id, checksum, applied_at, details) VALUES ($1, $2, $3, $4)",[e.id,e.checksum,(new Date).toISOString(),{dialect:"postgresql"}])}await n.query("COMMIT")}catch(e){throw await n.query("ROLLBACK"),e}finally{n.release()}}(t,e.schema),zO(N.drizzle({client:t}),()=>t.end())}catch(e){throw await t.end().catch(()=>{}),Mk("postgresql","migrate",e)}}});const CO={createdAt:P.text("created_at").notNull(),updatedAt:P.text("updated_at").notNull()},RO=P.sqliteTable("cp_metadata",{key:P.text("key").primaryKey(),value:P.text("value",{mode:"json"}).notNull()}),kO=P.sqliteTable("cp_users",{id:P.text("id").primaryKey(),displayName:P.text("display_name").notNull(),status:P.text("status",{enum:["active","disabled","archived"]}).notNull(),lastLoginAt:P.text("last_login_at"),archivedAt:P.text("archived_at"),...CO}),OO=P.sqliteTable("cp_login_identities",{id:P.text("id").primaryKey(),userId:P.text("user_id").notNull().references(()=>kO.id,{onDelete:"cascade"}),kind:P.text("kind",{enum:["local-password","oidc","oauth"]}).notNull(),normalizedLoginName:P.text("normalized_login_name"),passwordHash:P.text("password_hash"),requiresPasswordChange:P.integer("requires_password_change",{mode:"boolean"}),providerId:P.text("provider_id"),subject:P.text("subject"),verifiedEmail:P.text("verified_email"),lastUsedAt:P.text("last_used_at"),...CO},e=>[P.uniqueIndex("cp_login_identities_login_name_uq").on(e.normalizedLoginName),P.uniqueIndex("cp_login_identities_provider_subject_uq").on(e.providerId,e.subject),P.index("cp_login_identities_user_idx").on(e.userId)]),jO=P.sqliteTable("cp_roles",{id:P.text("id").primaryKey(),name:P.text("name").notNull(),description:P.text("description"),system:P.integer("system",{mode:"boolean"}).notNull(),status:P.text("status",{enum:["active","archived"]}).notNull(),permissionIds:P.text("permission_ids",{mode:"json"}).$type().notNull(),...CO},e=>[P.uniqueIndex("cp_roles_active_name_uq").on(z.sql`lower(${e.name})`).where(z.sql`${e.status} = 'active'`)]),PO=P.sqliteTable("cp_user_access_grants",{userId:P.text("user_id").primaryKey().references(()=>kO.id,{onDelete:"cascade"}),nodeScope:P.text("node_scope",{mode:"json"}).$type().notNull(),instanceScope:P.text("instance_scope",{mode:"json"}).$type().notNull(),authorizationRevision:P.integer("authorization_revision").notNull(),...CO}),LO=P.sqliteTable("cp_user_roles",{userId:P.text("user_id").notNull().references(()=>kO.id,{onDelete:"cascade"}),roleId:P.text("role_id").notNull().references(()=>jO.id,{onDelete:"restrict"})},e=>[P.primaryKey({columns:[e.userId,e.roleId]}),P.index("cp_user_roles_role_idx").on(e.roleId)]),DO=P.sqliteTable("cp_user_sessions",{id:P.text("id").primaryKey(),identityId:P.text("identity_id").notNull().references(()=>OO.id,{onDelete:"cascade"}),authorizationRevision:P.integer("authorization_revision").notNull(),tokenHash:P.text("token_hash").notNull(),expiresAt:P.text("expires_at").notNull(),lastSeenAt:P.text("last_seen_at"),clientType:P.text("client_type",{enum:["web","mobile","cli"]}).notNull(),device:P.text("device",{mode:"json"}).$type(),clientInfo:P.text("client_info",{mode:"json"}).$type(),...CO},e=>[P.uniqueIndex("cp_user_sessions_token_hash_uq").on(e.tokenHash),P.index("cp_user_sessions_identity_idx").on(e.identityId),P.index("cp_user_sessions_expiry_idx").on(e.expiresAt)]),MO=P.sqliteTable("cp_identity_providers",{id:P.text("id").primaryKey(),name:P.text("name").notNull(),kind:P.text("kind",{enum:["oidc","github"]}).notNull(),status:P.text("status",{enum:["enabled","disabled"]}).notNull(),loginPolicy:P.text("login_policy",{enum:["existing-only","admin-approved-create"]}).notNull(),issuer:P.text("issuer"),clientId:P.text("client_id").notNull(),clientSecretCiphertext:P.text("client_secret_ciphertext").notNull(),callbackUrl:P.text("callback_url").notNull(),...CO}),UO=P.sqliteTable("cp_external_identity_approvals",{id:P.text("id").primaryKey(),providerId:P.text("provider_id").notNull().references(()=>MO.id,{onDelete:"cascade"}),subject:P.text("subject").notNull(),verifiedEmail:P.text("verified_email"),displayName:P.text("display_name"),status:P.text("status",{enum:["pending","approved","rejected","expired"]}).notNull(),expiresAt:P.text("expires_at").notNull(),decidedAt:P.text("decided_at"),decidedByUserId:P.text("decided_by_user_id").references(()=>kO.id),...CO},e=>[P.index("cp_external_identity_approvals_lookup_idx").on(e.providerId,e.subject,e.status)]),qO=P.sqliteTable("cp_user_audit",{id:P.text("id").primaryKey(),action:P.text("action").notNull(),actorUserId:P.text("actor_user_id"),targetType:P.text("target_type").notNull(),targetId:P.text("target_id"),details:P.text("details",{mode:"json"}).$type().notNull(),createdAt:P.text("created_at").notNull()},e=>[P.index("cp_user_audit_created_idx").on(e.createdAt)]),$O=P.sqliteTable("cp_migration_ledger",{id:P.text("id").primaryKey(),checksum:P.text("checksum").notNull(),appliedAt:P.text("applied_at").notNull(),details:P.text("details",{mode:"json"}).$type().notNull()}),BO=P.sqliteTable("cp_nodes",{id:P.text("id").primaryKey(),name:P.text("name").notNull(),connectionMode:P.text("connection_mode").notNull(),connectionPath:P.text("connection_path",{mode:"json"}).notNull(),connectionEnabled:P.integer("connection_enabled",{mode:"boolean"}).notNull(),authMode:P.text("auth_mode").notNull(),authKeyId:P.text("auth_key_id"),authSecretCiphertext:P.text("auth_secret_ciphertext"),authPairedAt:P.text("auth_paired_at"),authPairingStatus:P.text("auth_pairing_status"),endpoint:P.text("endpoint"),controlEndpoint:P.text("control_endpoint"),containerEndpoint:P.text("container_endpoint"),publicWebBase:P.text("public_web_base"),labels:P.text("labels",{mode:"json"}).$type().notNull(),...CO}),FO=P.sqliteTable("cp_node_pairing_revocations",{id:P.text("id").primaryKey(),endpoint:P.text("endpoint").notNull(),nodeId:P.text("node_id").notNull(),keyId:P.text("key_id").notNull(),secretCiphertext:P.text("secret_ciphertext").notNull(),pairedAt:P.text("paired_at").notNull(),phase:P.text("phase").notNull().default("pending-compensation"),...CO},e=>[P.index("cp_node_pairing_revocations_node_idx").on(e.nodeId)]),HO=P.sqliteTable("cp_models",{id:P.text("id").primaryKey(),name:P.text("name").notNull(),endpoint:P.text("endpoint").notNull(),keyCiphertext:P.text("key_ciphertext").notNull(),model:P.text("model").notNull(),modelNames:P.text("model_names",{mode:"json"}).$type().notNull(),mappings:P.text("mappings",{mode:"json"}).$type().notNull(),protocols:P.text("protocols",{mode:"json"}).$type().notNull(),app:P.text("app").notNull(),enabled:P.integer("enabled",{mode:"boolean"}).notNull(),order:P.integer("display_order").notNull(),labels:P.text("labels",{mode:"json"}).$type().notNull(),...CO},e=>[P.index("cp_models_order_idx").on(e.order,e.name,e.id)]),GO=P.sqliteTable("cp_chat_bridges",{id:P.text("id").primaryKey(),channel:P.text("channel").notNull(),name:P.text("name").notNull(),enabled:P.integer("enabled",{mode:"boolean"}).notNull(),credentialCiphertext:P.text("credential_ciphertext"),credentialMetadata:P.text("credential_metadata",{mode:"json"}).$type().notNull().default({tokenSet:!1,clientSecretSet:!1,appSecretSet:!1}),defaultChatId:P.text("default_chat_id"),allowedUserIds:P.text("allowed_user_ids",{mode:"json"}).$type().notNull(),pollIntervalMs:P.integer("poll_interval_ms").notNull(),settings:P.text("settings",{mode:"json"}).$type().notNull(),...CO}),WO=P.sqliteTable("cp_chat_session_bindings",{id:P.text("id").primaryKey(),routeScope:P.text("route_scope").notNull(),channel:P.text("channel").notNull(),bridgeId:P.text("bridge_id").references(()=>GO.id,{onDelete:"cascade"}),chatSessionId:P.text("chat_session_id").notNull(),userId:P.text("user_id"),activeProjectId:P.text("active_project_id"),activeInstanceId:P.text("active_instance_id"),activeAiSessionId:P.text("active_ai_session_id"),lastUsedAt:P.text("last_used_at").notNull(),...CO},e=>[P.uniqueIndex("cp_chat_session_bindings_route_uq").on(e.channel,e.routeScope,e.chatSessionId),P.index("cp_chat_session_bindings_bridge_idx").on(e.bridgeId)]),VO=P.sqliteTable("cp_git_credentials",{id:P.text("id").primaryKey(),name:P.text("name").notNull(),kind:P.text("kind").notNull(),scope:P.text("scope",{mode:"json"}).notNull(),status:P.text("status").notNull(),revision:P.integer("revision").notNull(),secretCiphertext:P.text("secret_ciphertext").notNull(),...CO}),KO=P.sqliteTable("cp_git_credential_assignments",{id:P.text("id").primaryKey(),instanceId:P.text("instance_id").notNull(),credentialId:P.text("credential_id").notNull().references(()=>VO.id,{onDelete:"restrict"}),credentialRevision:P.integer("credential_revision").notNull(),assignmentRevision:P.integer("assignment_revision").notNull(),status:P.text("status").notNull(),authorizedAt:P.text("authorized_at").notNull(),...CO},e=>[P.uniqueIndex("cp_git_credential_assignments_identity_uq").on(e.instanceId,e.credentialId),P.index("cp_git_credential_assignments_credential_idx").on(e.credentialId,e.status)]),XO=P.sqliteTable("cp_git_provisioning_intents",{id:P.text("id").primaryKey(),instanceId:P.text("instance_id").notNull(),credentialId:P.text("credential_id").notNull().references(()=>VO.id,{onDelete:"restrict"}),operationId:P.text("operation_id").notNull(),inputDigest:P.text("input_digest").notNull(),remoteUrl:P.text("remote_url").notNull(),ref:P.text("ref",{mode:"json"}).notNull(),clone:P.text("clone",{mode:"json"}).notNull(),...CO},e=>[P.uniqueIndex("cp_git_provisioning_intents_operation_uq").on(e.instanceId,e.operationId),P.index("cp_git_provisioning_intents_credential_idx").on(e.credentialId)]),YO=P.sqliteTable("cp_git_audit",{id:P.text("id").primaryKey(),action:P.text("action").notNull(),credentialId:P.text("credential_id").notNull(),instanceId:P.text("instance_id"),credentialRevision:P.integer("credential_revision"),assignmentRevision:P.integer("assignment_revision"),...CO},e=>[P.index("cp_git_audit_created_idx").on(e.createdAt)]);class JO{tail=Promise.resolve();run(e){const t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}}function QO(e,t,n,i){return{list:async()=>(await e.select().from(t).orderBy(z.asc(t.id))).map(e=>Yk(n,e)),async get(i){const s=await e.select().from(t).where(z.eq(t.id,i)).limit(1);return s[0]?Yk(n,s[0]):void 0},put:async s=>i(async()=>{const i=Xk(n.parse(s)),a=Object.fromEntries(Object.entries(i).filter(([e])=>"id"!==e));return await e.insert(t).values(i).onConflictDoUpdate({target:t.id,set:a}),Yk(n,i)}),delete:async n=>i(async()=>{const i=await e.delete(t).where(z.eq(t.id,n));return Number(i.changes)>0})}}function ZO(e,t){const n=QO(e,OO,Kk.identities,t),i=async t=>{const n=await e.select().from(OO).where(t).limit(1);return n[0]?Yk(Kk.identities,n[0]):void 0};return{...n,findByLoginName:e=>i(z.eq(OO.normalizedLoginName,e)),findByProviderSubject:(e,t)=>i(z.and(z.eq(OO.providerId,e),z.eq(OO.subject,t))),listByUser:async t=>(await e.select().from(OO).where(z.eq(OO.userId,t))).map(e=>Yk(Kk.identities,e)),existsForProvider:async t=>(await e.select({id:OO.id}).from(OO).where(z.eq(OO.providerId,t)).limit(1)).length>0}}function ej(e){const t=new Map;for(const n of e){const e=n.grant.userId,i=t.get(e)||{grant:n.grant,roleIds:[]};i.roleIds.push(n.roleId),t.set(e,i)}return[...t.values()].map(({grant:e,roleIds:t})=>Kk.grants.parse({...e,roleIds:t.sort()}))}function tj(e,t,n,i){const s=t=>{const n=e.select({grant:PO,roleId:LO.roleId}).from(PO).innerJoin(LO,z.eq(PO.userId,LO.userId));return t?n.where(z.inArray(PO.userId,t)):n};return{list:async()=>ej(await s()),get:async e=>ej(await s([e]))[0],async listByRole(t){const n=(await e.select({userId:LO.userId}).from(LO).where(z.eq(LO.roleId,t))).map(e=>e.userId);return 0===n.length?[]:ej(await s(n))},put:n=>i?(async t=>{const n=Kk.grants.parse(t),{roleIds:i,...s}=n;return await e.insert(PO).values(s).onConflictDoUpdate({target:PO.userId,set:Object.fromEntries(Object.entries(s).filter(([e])=>"userId"!==e))}),await e.delete(LO).where(z.eq(LO.userId,n.userId)),await e.insert(LO).values(i.map(e=>({userId:n.userId,roleId:e}))),n})(n):t(e=>e.grants.put(n)),delete:async t=>n(async()=>{const n=await e.delete(PO).where(z.eq(PO.userId,t));return Number(n.changes)>0})}}function nj(e,t){const n=e=>e.map(e=>Yk(Kk.sessions,{...e.session,userId:e.userId})),i=()=>e.select({session:DO,userId:OO.userId}).from(DO).innerJoin(OO,z.eq(DO.identityId,OO.id));return{list:async()=>n(await i()),get:async e=>n(await i().where(z.eq(DO.id,e)).limit(1))[0],listByUser:async e=>n(await i().where(z.eq(OO.userId,e))),put:async n=>t(async()=>{const t=Kk.sessions.parse(n),i=await e.select({userId:OO.userId}).from(OO).where(z.eq(OO.id,t.identityId)).limit(1);if(i[0]?.userId!==t.userId)throw new Error("Session identity does not belong to the requested user.");const{userId:s,...a}=t;return await e.insert(DO).values(a).onConflictDoUpdate({target:DO.id,set:Object.fromEntries(Object.entries(a).filter(([e])=>"id"!==e))}),t}),delete:async n=>t(async()=>{const t=await e.delete(DO).where(z.eq(DO.id,n));return Number(t.changes)>0})}}function ij(e,t){return{...QO(e,UO,Kk.approvals,t),async findActivePending(t,n,i){const s=await e.select().from(UO).where(z.and(z.eq(UO.providerId,t),z.eq(UO.subject,n),z.eq(UO.status,"pending"),z.gt(UO.expiresAt,i))).limit(1);return s[0]?Yk(Kk.approvals,s[0]):void 0},hasActivePendingForProvider:async(t,n)=>(await e.select({id:UO.id}).from(UO).where(z.and(z.eq(UO.providerId,t),z.eq(UO.status,"pending"),z.gt(UO.expiresAt,n))).limit(1)).length>0}}function sj(e,t){return{...QO(e,KO,iT.gitAssignments,t),putIfRevision:(n,i)=>t(async()=>{const t=iT.gitAssignments.parse(n);if(void 0===i){const n=await e.insert(KO).values(t).onConflictDoNothing();return Number(n.changes)>0}const{id:s,...a}=t,o=await e.update(KO).set(a).where(z.and(z.eq(KO.id,t.id),z.eq(KO.assignmentRevision,i)));return Number(o.changes)>0})}}function aj(e,t){return{...QO(e,XO,iT.gitProvisioningIntents,t),insert:n=>t(async()=>{const t=iT.gitProvisioningIntents.parse(n),i=await e.insert(XO).values(t).onConflictDoNothing();return Number(i.changes)>0})}}function oj(e,t){const n=QO(e,YO,iT.gitAudit,t);return{list:n.list,get:n.get,append:n=>t(async()=>{const t=iT.gitAudit.parse(n);await e.insert(YO).values(t)})}}function rj(e,t,n,i=!1,s=new JO){let a;const o=e=>i?e():s.run(e),r=async t=>i?t(a):o(async()=>{n.exec("BEGIN IMMEDIATE");try{const i=await t(rj(e,async()=>{},n,!0,s));return n.exec("COMMIT"),i}catch(e){throw n.exec("ROLLBACK"),e}});return a={dialect:"sqlite",users:QO(e,kO,Kk.users,o),identities:ZO(e,o),roles:QO(e,jO,Kk.roles,o),grants:tj(e,r,o,i),sessions:nj(e,o),providers:QO(e,MO,Kk.providers,o),approvals:ij(e,o),audit:QO(e,qO,Kk.audit,o),nodes:QO(e,BO,iT.nodes,o),pairingRevocations:QO(e,FO,iT.pairingRevocations,o),models:QO(e,HO,iT.models,o),chatBridges:QO(e,GO,iT.chatBridges,o),chatSessions:QO(e,WO,iT.chatSessions,o),gitCredentials:QO(e,VO,iT.gitCredentials,o),gitAssignments:sj(e,o),gitProvisioningIntents:aj(e,o),gitAudit:oj(e,o),async metadata(){const t=await e.select().from(RO).where(z.eq(RO.key,"user_store")).limit(1);return t[0]?.value||{schemaVersion:1}},async putMetadata(t){await o(()=>e.insert(RO).values({key:"user_store",value:t}).onConflictDoUpdate({target:RO.key,set:{value:t}}))},migration:async t=>(await e.select().from($O).where(z.eq($O.id,t)).limit(1))[0],async putMigration(t){t=Dk.parse(t),await o(()=>e.insert($O).values(t).onConflictDoUpdate({target:$O.id,set:{checksum:t.checksum,appliedAt:t.appliedAt,details:t.details}}))},transaction:r,close:t},a}var cj=Object.freeze({__proto__:null,createSqliteUserRepository:async function(e){try{n.mkdirSync(t.dirname(e),{recursive:!0,mode:448}),n.chmodSync(t.dirname(e),448);const i=new k.DatabaseSync(e);n.chmodSync(e,384);try{!function(e){e.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;"),e.exec("CREATE TABLE IF NOT EXISTS cp_migration_ledger (\n id TEXT PRIMARY KEY NOT NULL, checksum TEXT NOT NULL, applied_at TEXT NOT NULL, details TEXT NOT NULL\n )"),e.exec("BEGIN IMMEDIATE");try{const t=e.prepare("SELECT checksum FROM cp_migration_ledger WHERE id = ?"),n=e.prepare("INSERT INTO cp_migration_ledger (id, checksum, applied_at, details) VALUES (?, ?, ?, ?)");for(const i of Uk){const s=t.get(i.id);if(s){if(s.checksum!==i.checksum)throw new Error(`Migration checksum mismatch for ${i.id}.`)}else e.exec(i.sql),n.run(i.id,i.checksum,(new Date).toISOString(),JSON.stringify({dialect:"sqlite"}))}e.exec("COMMIT")}catch(t){throw e.exec("ROLLBACK"),t}}(i)}catch(e){throw i.close(),Mk("sqlite","migrate",e)}for(const t of[`${e}-wal`,`${e}-shm`])n.existsSync(t)&&n.chmodSync(t,384);return rj(O.drizzle({client:i}),async()=>i.close(),i)}catch(e){if("CONTROL_PLANE_DATABASE_MIGRATE_FAILED"===e.code)throw e;throw Mk("sqlite","connect",e)}}});
|
|
436
|
+
`)),o.get("/api/events",{websocket:!0},async(e,t)=>{const n=t.query,i="string"==typeof n.instanceId?n.instanceId.trim():"",s=vS(t),a="user"===s?.type?(await S.listControlledInstances()).filter(e=>uh(s.nodeScope,s.instanceScope,e.id,e.nodeId)):void 0,o=a?new Set(a.map(e=>e.id)):void 0;if(i&&o&&!o.has(i))return void e.close(4003,"The requested event scope is not visible.");const r=[];let c=!1;const d={get readyState(){return e.readyState},get bufferedAmount(){return e.bufferedAmount},OPEN:e.OPEN,send(t){c?e.send(t):r.push(t)},ping(){e.ping()},on(t,n){e.on(t,n)},close(t,n){e.close(t,n)}};l.connect(d,{instanceIds:i?[i]:void 0,expectsTransientSubscription:"1"===n.aiSessionTransient,expectsMetricSubscription:"1"===n.resourceMetricsScope,..."user"===s?.type?{authorization:{userId:s.userId,..."cookie"===Ak(t).source?{webSession:!0}:{},authorizationRevision:s.authorizationRevision,permissionIds:s.permissionIds,..."selected"===s.nodeScope.kind?{allowedNodeIds:new Set(s.nodeScope.nodeIds)}:{},..."selected"===s.instanceScope?.kind||"selected"===s.nodeScope.kind?{allowedInstanceIds:o}:{}}}:{}});const[p,u]=await Promise.all([j.streamDescriptors(),L.streamDescriptors()]);l.send(e,"streams.hello",{protocolVersion:1,streams:[...p,...u].filter(e=>(!o||o.has(e.instanceId))&&(!i||e.instanceId===i))}),c=!0;for(const t of r)e.send(t);for(const t of k.snapshots().filter(e=>(!o||o.has(e.instanceId))&&(!i||e.instanceId===i)))l.send(e,"image.pull.snapshot",t,{topic:"instances",scope:{instanceId:t.instanceId}});for(const t of O.snapshots().filter(e=>(!o||o.has(e.instanceId))&&(!i||e.instanceId===i)))l.send(e,"git.provisioning.snapshot",t,{topic:"instances",scope:{instanceId:t.instanceId}})}),o.get("/api/auth/session",{config:qS},async e=>{const t=Ak(e);return{data:await A.currentSession(t.token,t.clientTypes)}}),o.post("/api/auth/bootstrap-admin",{config:qS},async(e,t)=>{const n=await A.bootstrapAdmin(e.body);return t.code(201).send({data:n})}),o.post("/api/auth/login",{config:qS},async(e,t)=>{const n=await A.login(e.body,{sourceId:e.ip});return t.setCookie(Pg,n.sessionToken,{path:"/",httpOnly:!0,sameSite:"lax",expires:new Date(n.expiresAt)}),{data:{user:n.user}}}),o.post("/api/auth/mobile/login",{config:qS},async e=>({data:await A.loginMobile(e.body,{sourceId:e.ip})})),o.patch("/api/auth/password",async(e,t)=>{const n=await A.changePassword(e.cookies[Pg],e.body);return t.setCookie(Pg,n.sessionToken,{path:"/",httpOnly:!0,sameSite:"lax",expires:new Date(n.expiresAt)}),{data:{user:n.user}}}),o.post("/api/auth/mobile/logout",async e=>{const t=Ak(e,{allowCookie:!1,bearerClientTypes:["mobile"]});return{data:await A.logoutSession(t.token,t.clientTypes)}}),o.post("/api/auth/mobile/renew",async(e,t)=>{t.header("cache-control","no-store");const n=Ak(e,{allowCookie:!1,bearerClientTypes:["mobile"]}),i=await A.renewSession(n.token,n.clientTypes);return i?{data:i}:t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to renew the mobile session."}})}),o.get("/api/auth/mobile/sessions",async(e,t)=>{const n=Ak(e,{bearerClientTypes:["mobile"]}),i=await A.mobileSessions(n.token,n.clientTypes);return i?{data:i}:t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to access mobile sessions."}})}),o.delete("/api/auth/mobile/sessions/:id",async(e,t)=>{const n=f.z.object({id:f.z.string().trim().min(1)}).parse(e.params),i=Ak(e,{bearerClientTypes:["mobile"]}),s=await A.revokeMobileSession(i.token,n.id,i.clientTypes);return void 0===s?t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to revoke mobile sessions."}}):{data:{revoked:s}}}),o.post("/api/auth/logout",{config:qS},async(e,t)=>{const n=Ak(e),i=await A.logoutSession(n.token,n.clientTypes);return t.clearCookie(Pg,{path:"/"}),{data:i}});const ie=zk(S);return o.post("/api/auth/cli/authorize",{config:qS},async e=>({data:await A.createCliAuthorization(e.body,{publicOrigin:Tk(S,e),sourceId:e.ip})})),o.post("/api/auth/cli/token",{config:qS},async e=>({data:await A.exchangeCliToken(e.body,{sourceId:e.ip})})),o.post("/api/auth/cli/local",{config:qS},async e=>({data:await A.createLocalCliSession(e.body,{remoteAddress:e.socket.remoteAddress,sourceId:e.ip})})),o.get("/api/auth/cli/requests/:requestId",{preHandler:ie},async e=>zm.parse({data:A.cliAuthorizationRequest(f.z.object({requestId:f.z.string().trim().min(1)}).parse(e.params).requestId)})),o.get("/api/auth/cli/requests",{preHandler:ie},async e=>zm.parse({data:A.cliAuthorizationRequestByUserCode(f.z.object({userCode:f.z.string().trim().min(1).max(40)}).parse(e.query).userCode)})),o.post("/api/auth/cli/requests/:requestId/approve",{preHandler:ie},async e=>Nm.parse({data:await A.approveCliAuthorization(f.z.object({requestId:f.z.string().trim().min(1)}).parse(e.params).requestId,Nk(e))})),o.post("/api/auth/cli/requests/:requestId/deny",{preHandler:ie},async e=>Cm.parse({data:await A.denyCliAuthorization(f.z.object({requestId:f.z.string().trim().min(1)}).parse(e.params).requestId,Nk(e))})),o.post("/api/auth/cli/logout",async e=>{const t=Ak(e,{allowCookie:!1,bearerClientTypes:["cli"]});return{data:await A.logoutSession(t.token,t.clientTypes)}}),o.post("/api/auth/cli/renew",async(e,t)=>{t.header("cache-control","no-store");const n=Ak(e,{allowCookie:!1,bearerClientTypes:["cli"]}),i=await A.renewSession(n.token,n.clientTypes);return i?{data:i}:t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to renew the CLI session."}})}),o.get("/api/auth/cli/sessions",async(e,t)=>{const n=Ak(e,{allowCookie:!1,bearerClientTypes:["cli"]}),i=await A.cliSessions(n.token,n.clientTypes);return i?{data:i}:t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to access CLI sessions."}})}),o.delete("/api/auth/cli/sessions/:id",async(e,t)=>{const n=f.z.object({id:f.z.string().trim().min(1)}).parse(e.params),i=Ak(e,{allowCookie:!1,bearerClientTypes:["cli"]}),s=await A.revokeCliSession(i.token,n.id,i.clientTypes);return void 0===s?t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to revoke CLI sessions."}}):{data:{revoked:s}}}),o.get("/api/access/me",async(e,t)=>{const n=Ak(e),i=await A.currentAccess(n.token,n.clientTypes);return i?{data:i}:t.code(401).send({error:{code:"CONTROL_PLANE_AUTH_REQUIRED",message:"Sign in to read Control Plane access."}})}),function(e,t,n){e.get("/api/users",async e=>{const n=f.z.object({search:f.z.string().trim().max(160).optional(),includeArchived:f.z.coerce.boolean().optional()}).strict().parse(e.query);return{data:await t.users.list(n)}}),e.post("/api/users",async(e,n)=>n.code(201).send({data:await t.users.createLocalUser(e.body)})),e.get("/api/users/:id",async e=>({data:await t.users.detail(zR.parse(e.params).id)})),e.patch("/api/users/:id",async e=>{const n=zR.parse(e.params).id,i=await t.users.updateUser(n,e.body);return await t.notifyAuthorizationChanged(n),{data:i}}),e.put("/api/users/:id/access",async(e,i)=>{const s=zR.parse(e.params).id,a=Ag.parse(e.body);return TS(e,i,t,n,"user.access.set",s,a,[{field:"roleIds",value:a.roleIds.join(", ")},{field:"nodeScope",value:JSON.stringify(a.nodeScope)},...a.instanceScope?[{field:"instanceScope",value:JSON.stringify(a.instanceScope)}]:[]],async()=>{const e=await t.users.setAccess(s,a);return await t.notifyAuthorizationChanged(s),e})}),e.post("/api/users/:id/password-reset",async e=>{const n=f.z.object({password:f.z.string().min(8).max(4096),requirePasswordChange:f.z.boolean().optional()}).strict().parse(e.body),i=zR.parse(e.params).id,s=await t.users.resetLocalPassword(i,n.password,!1!==n.requirePasswordChange);return await t.notifyAuthorizationChanged(i),{data:s}}),e.get("/api/users/:id/sessions",async e=>{const n=NR(e);return{data:await t.sessions.listSessions(n.userId,zR.parse(e.params).id)}}),e.delete("/api/users/:id/sessions",async e=>{const n=zR.parse(e.params).id;return{data:{revokedSessions:await t.users.revokeSessions(n)}}}),e.delete("/api/users/:id/sessions/:sessionId",async e=>{const n=NR(e),i=f.z.object({id:f.z.string().trim().min(1),sessionId:f.z.string().trim().min(1)}).strict().parse(e.params);return{data:{revoked:await t.sessions.revokeSession(n.userId,i.sessionId)}}}),e.delete("/api/users/:id/identities/:identityId",async e=>{const n=f.z.object({id:f.z.string().trim().min(1),identityId:f.z.string().trim().min(1)}).strict().parse(e.params),i=await t.users.unbindExternalIdentity(n.id,n.identityId);return await t.notifyAuthorizationChanged(n.id),{data:i}}),e.get("/api/roles",async()=>({data:await t.users.roleSummaries()})),e.get("/api/permissions",async()=>({data:Qu})),e.post("/api/roles",async(e,n)=>n.code(201).send({data:await t.users.createRole(e.body)})),e.patch("/api/roles/:id",async(e,i)=>{const s=zR.parse(e.params).id,a=Tg.parse(e.body);return TS(e,i,t,n,"user.role.update",s,a,[{field:"changedFields",value:Object.keys(a).join(", ")},...a.permissionIds?[{field:"permissionIds",value:a.permissionIds.join(", ")}]:[]],async()=>{const e=(await t.users.store.grants.listByRole(s)).map(e=>e.userId),n=await t.users.updateRole(s,a);for(const n of e)await t.notifyAuthorizationChanged(n);return n})}),e.delete("/api/roles/:id",async(e,i)=>{const s=zR.parse(e.params).id;return TS(e,i,t,n,"user.role.remove",s,{},void 0,()=>t.users.archiveRole(s))}),e.get("/api/identity-providers",async()=>({data:await t.identityProviders.list()})),e.post("/api/identity-providers",async(e,n)=>n.code(201).send({data:await t.identityProviders.create(e.body)})),e.patch("/api/identity-providers/:id",async(e,i)=>{const s=zR.parse(e.params).id,a=Uh.parse(e.body);return TS(e,i,t,n,"identity-provider.update",s,a,[{field:"changedFields",value:Object.keys(a).join(", ")},...a.status?[{field:"status",value:a.status}]:[],...a.loginPolicy?[{field:"loginPolicy",value:a.loginPolicy}]:[]],()=>t.identityProviders.update(s,a))}),e.delete("/api/identity-providers/:id",async(e,i)=>{const s=zR.parse(e.params).id;return TS(e,i,t,n,"identity-provider.remove",s,{},void 0,async()=>({deleted:await t.identityProviders.remove(s)}))}),e.get("/api/external-identity-approvals",async()=>({data:await t.users.store.approvals.list()})),e.post("/api/external-identity-approvals/:id/approve",async e=>{const n=NR(e);return{data:await t.users.approveExternalIdentity(n.userId,zR.parse(e.params).id,e.body)}}),e.post("/api/external-identity-approvals/:id/reject",async e=>{const n=NR(e);return{data:await t.users.rejectExternalIdentity(n.userId,zR.parse(e.params).id)}}),e.post("/api/auth/external/:id/begin",{config:qS},async(e,n)=>(n.header("cache-control","no-store"),{data:await t.external.begin(zR.parse(e.params).id)})),e.post("/api/auth/external/callback",{config:qS},async(e,n)=>{n.header("cache-control","no-store");const i=await t.external.callback(e.body);return"session"===i.kind?(n.setCookie(Pg,i.sessionToken,{path:"/",httpOnly:!0,sameSite:"lax",expires:new Date(i.expiresAt)}),{data:{kind:i.kind,user:i.user,authorization:i.authorization}}):{data:i}})}(o,A,u),function(e,t,n,i){e.get("/api/git-credentials",async()=>({data:{items:t.gitCredentials.list()}})),e.post("/api/git-credentials",async(e,n)=>{const i=await t.gitCredentials.create(e.body);return n.code(201).send({data:i})}),e.get("/api/git-credentials/:id",async e=>{const n=CR.parse(e.params).id,i=t.gitCredentials.get(n);if(!i)throw Object.assign(new Error(`Git credential ${n} was not found.`),{code:"GIT_CREDENTIAL_NOT_FOUND",statusCode:404});return{data:i}}),e.patch("/api/git-credentials/:id",async e=>({data:await t.updateGitCredential(CR.parse(e.params).id,e.body)})),e.delete("/api/git-credentials/:id",async e=>({data:{deleted:await t.gitCredentials.remove(CR.parse(e.params).id)}})),e.get("/api/controlled-instances/:id/git-credential-assignments",async e=>{kR(e);const n=CR.parse(e.params).id;return await t.requireControlledInstance(n,!0),{data:t.listInstanceGitCredentialAssignments(n)}}),e.post("/api/controlled-instances/:id/git-credential-assignments",async(e,s)=>{kR(e);const a=CR.parse(e.params).id,o=f.z.object({credentialId:f.z.string().trim().min(1).max(120)}).strict().parse(e.body);return TS(e,s,n,i,"git-credential.assign",a,o,[{field:"credentialId",value:o.credentialId}],()=>t.authorizeInstanceGitCredential(a,o.credentialId),201)}),e.delete("/api/controlled-instances/:id/git-credential-assignments/:credentialId",async e=>{kR(e);const n=RR.parse(e.params);return{data:{revoked:await t.revokeInstanceGitCredential(n.id,n.credentialId)}}})}(o,S,A,u),o.get("/api/control-plane/status",async()=>({data:{protocolVersion:oc,build:vk(),storage:a}})),o.get("/api/control-plane/settings",async()=>({data:S.getSettings()})),o.patch("/api/control-plane/settings",async e=>{const t=S.updateSettings(e.body||{});return v=t.diagnosticLogs,{data:t}}),o.get("/api/control-plane/diagnostic-logs/export",async(e,i)=>{const s=await async function(e){const i=n.mkdtempSync(t.join(m.tmpdir(),"task-handoff-diagnostic-logs-")),s=t.resolve(e.nodeAgentDataDir||t.join(e.dataDir,"node-agent")),a=t.join(s,"local-instances"),o=n.existsSync(a)?n.readdirSync(a,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.isSymbolicLink()).map(e=>({label:t.join("local-instances",e.name),root:t.join(a,e.name,"logs")})):[],r=[{label:"control-plane",root:t.join(e.dataDir,"logs")},{label:"desktop",root:t.join(e.dataDir,"log")},{label:"node-agent",root:t.join(s,"logs")},...o],c=[];let d=0;for(const e of r)for(const s of FR(e.root)){if(d>=$R)break;const a=t.relative(e.root,s);if(!a||a.startsWith("..")||t.isAbsolute(a))continue;const o=t.join("logs",e.label,a),r=n.statSync(s).size,l=HR(s,t.join(i,o),$R-d);l&&(d+=l,c.push({source:s,archivePath:o,bytes:l,originalBytes:r}))}n.writeFileSync(t.join(i,"manifest.json"),`${JSON.stringify({createdAt:(new Date).toISOString(),diagnosticLogsEnabled:e.diagnosticLogsEnabled,limits:{perFileBytes:qR,totalBytes:$R},files:c.map(({archivePath:e,bytes:t,originalBytes:n})=>({archivePath:e,bytes:t,originalBytes:n,truncated:t<n}))},null,2)}\n`,{mode:384});const l=["manifest.json",...n.existsSync(t.join(i,"logs"))?["logs"]:[]],p=D.create({cwd:i,gzip:!0,portable:!0,noMtime:!0},l),u=()=>n.rmSync(i,{recursive:!0,force:!0});return p.once("close",u),p.once("error",u),{filename:`task-handoff-diagnostic-logs-${(new Date).toISOString().replace(/[:.]/g,"-")}.tar.gz`,stream:p}}({dataDir:a.dataDir,nodeAgentDataDir:process.env.TASK_HANDOFF_DESKTOP_NODE_AGENT_DATA_DIR||process.env.TASK_HANDOFF_NODE_AGENT_DATA_DIR,diagnosticLogsEnabled:v});return i.header("content-type","application/gzip"),i.header("content-disposition",`attachment; filename="${s.filename}"`),i.send(s.stream)}),o.post("/api/ai-session-attachments",{bodyLimit:33554432},async(e,t)=>{try{return t.code(201).send({data:q.upload(e.body)})}catch(e){return t.code(400).send({error:{code:"AI_SESSION_ATTACHMENT_INVALID",message:e instanceof Error?e.message:String(e)}})}}),oC({app:o,service:S,events:l,operationApprovals:u,auth:A,appSessionAggregator:L,aiSessionAggregator:j,chatGateway:Q,aiSessionAttachments:q,aiSessionAttachmentCache:U,nodeAgentTunnel:$,nodeEventSubscriber:Z,agentAggregator:M,errorPayload:Sk,onInstanceDeleted:async e=>{if(!A.enabled())return;const t=await A.users.removeInstanceFromAccessScopes(e);for(const e of t)await A.notifyAuthorizationChanged(e)}}),function(e,t,n,i){e.get("/api/operation-approvals/support",async e=>(await AS(e,t),{data:{supported:!0}})),e.get("/api/operation-approvals/:id/status",async e=>({data:n.status(await AS(e,t),wS.parse(e.params).id)})),e.delete("/api/operation-approvals/:id",async e=>({data:{cancelled:n.cancel(await AS(e,t),wS.parse(e.params).id)}})),e.get("/api/operation-approvals",async e=>({data:n.snapshot(ES(e,t))})),e.post("/api/operation-approvals/:id/decision",{preHandler:i},async i=>{const s=ES(i,t),a=xS.parse(i.body).decision,o=n.decide(s,wS.parse(i.params).id,a);return await zS(t,e,{action:`operation-approval.${a}`,userId:s,approvalId:o.id}),{data:o}})}(o,A,u,zk(S)),function(e){const{app:t,authority:n,resolveTarget:i,projectTarget:s,eventHub:a}=e,o=e.runtime??new QC,c=new WeakMap,d=(e,t)=>{const n=c.get(e);n&&(c.delete(e),n.tracked.release(),e.raw.removeListener("aborted",n.abort),t.raw.removeListener("close",n.abort))};t.all("/api/node-proxy/bindings/:bindingId/http/*",{config:BS,bodyLimit:o.maxRequestBodyBytes,logLevel:"silent",async onRequest(e,t){try{const i=rR.parse(e.params).bindingId,s=uR(n,i,e),a=function(e){const t=e.raw.url||e.url,n=/^\/api\/node-proxy\/bindings\/[^/]+\/http(\/[^#]*)$/.exec(t),i=n?.[1],s=i?.split("?",1)[0];if(!i||!s||/%(?:2f|5c)/i.test(s))throw bR(jo.RouteInvalid,"Proxy route is invalid.",400);const a=To.safeParse(i);if(!a.success)throw bR(jo.RouteInvalid,a.error.issues[0]?.message||"Proxy route is invalid.",400);return a.data}(e),r=gR(e.headers),l=o.reserveHttp(s.id),p=()=>{l.controller.abort(Object.assign(new Error("Proxy HTTP consumer disconnected."),{name:"AbortError",code:"ABORT_ERR"})),d(e,t)};c.set(e,{binding:s,route:a,forwardedHeaders:r,tracked:l,abort:p,startedAt:performance.now()}),e.raw.once("aborted",p),t.raw.once("close",p)}catch(n){return fR(t,n,e)}},async onError(e,t){d(e,t);const n=vR(e.headers);n&&t.header("x-request-id",n)},async onResponse(e,t){d(e,t)}},async(e,s)=>{try{const o=c.get(e);if(!o)throw bR(jo.TransportFailed,"Proxy request context is unavailable.",500,!0);const{binding:l,route:p,forwardedHeaders:u,tracked:m,abort:h,startedAt:g}=o;!function(e,t,n){const i=new URL(t,"https://node-agent.invalid").searchParams,s=[i.get("nodeId"),i.get("targetNodeId")];if(n&&"object"==typeof n&&!Array.isArray(n)){const e=n;"string"==typeof e.nodeId&&s.push(e.nodeId),"string"==typeof e.targetNodeId&&s.push(e.targetNodeId)}const a=s.find(t=>null!==t&&t!==e.targetNodeId);if(void 0!==a)throw bR(jo.TargetMismatch,"Proxy request attempts to select a target outside its binding.",409,!1,{bindingId:e.id,targetNodeId:e.targetNodeId})}(l,p,e.body);const f=null==(a=e.body)?void 0:Buffer.isBuffer(a)?a:a instanceof Uint8Array||"string"==typeof a?Buffer.from(a):Buffer.from(JSON.stringify(a));m.acceptRequestBody(f?.byteLength??0);try{const{node:a,transport:o}=await i(l.targetNodeId);mR(n,l,e),hR(l,a);const c=await o.requestStream(a,p,{method:e.method,headers:u,...f?{body:f}:{},signal:m.controller.signal}),d=performance.now()-g;return t.log.info({traceId:u[$y],requestId:u["x-request-id"],bindingId:l.id,targetNodeId:l.targetNodeId,routePath:new URL(p,"https://node-agent.invalid").pathname,statusCode:c.status,proxyForwardMs:d},"control-plane proxy request timing"),function(e,t,n,i,s,a,o,c){t.body&&n.beginResponseStream();const d=function(e,t){const n=Object.fromEntries([...No].flatMap(t=>{const n=e.headers.get(t);return null===n?[]:[[t,n]]}));return t&&(n["x-request-id"]=t),n}(t,a);d["server-timing"]=Hy(d["server-timing"],Fy("proxy_forward",c??0)),o&&!d[$y]&&(d[$y]=o);for(const[t,n]of Object.entries(d))e.header(t,n);const l=()=>{n.release(),s.raw.removeListener("aborted",i),e.raw.removeListener("close",i)};if(!t.body)return l(),e.code(t.status).send();const p=r.Readable.fromWeb(t.body);return n.controller.signal.addEventListener("abort",()=>{const e=n.controller.signal.reason;p.destroy(e instanceof Error?e:new Error("Proxy HTTP stream aborted."))},{once:!0}),p.on("data",e=>{try{n.acceptResponseChunk(e)}catch(e){p.destroy(e)}}),p.once("end",l),p.once("error",l),p.once("close",l),e.raw.once("close",()=>p.destroy()),e.code(t.status).send(p)}(s,c,m,h,e,u["x-request-id"],u[$y],d)}catch(t){throw d(e,s),t}}catch(t){return d(e,s),fR(s,t,e)}var a}),t.get("/api/node-proxy/bindings/:bindingId/websocket",{websocket:!0,logLevel:"silent",config:BS},async(e,t)=>{let s;try{const a=rR.parse(t.params).bindingId,r=uR(n,a,t),c=cR.parse(t.query).route,{node:d,transport:l}=await i(r.targetNodeId);mR(n,r,t),hR(r,d),s=o.openWebSocket(r.id,e),l.proxyWebSocket(d,s,c,function(e){const t=IR(e,"sec-websocket-protocol").split(",").map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}(t.headers),gR(t.headers))}catch(t){const n=yR(t);s?.close(1008,n.message),s||e.close(429===n.statusCode?1013:n.statusCode<500?1008:1011,wR(n.message))}}),t.get("/api/node-proxy/bindings/:bindingId/snapshot",{config:BS},async(e,t)=>{try{const t=rR.parse(e.params).bindingId,r=uR(n,t,e),{node:c}=await i(r.targetNodeId);mR(n,r,e),hR(r,c);const d=s(r.targetNodeId);if(!d)throw bR(jo.TargetUnavailable,"Proxy target no longer exists.",404,!1,{targetNodeId:r.targetNodeId});const l=a.cursor(r.targetNodeId),p=Wo.parse({protocolVersion:vo,binding:r,streamId:l.streamId,revision:l.revision,observedAt:(new Date).toISOString(),target:oR(d)});if(o=p,Buffer.byteLength(JSON.stringify(o),"utf8")>pR)throw bR(jo.ResourceLimit,"Proxy target snapshot byte limit exceeded.",429,!0,{bindingId:r.id,resource:"snapshot-bytes",limit:pR});return{data:p}}catch(n){return fR(t,n,e)}var o}),t.get("/api/node-proxy/bindings/:bindingId/events",{websocket:!0,logLevel:"silent",config:BS},async(e,t)=>{let s,r,c;try{const d=rR.parse(t.params).bindingId,l=uR(n,d,t),p=dR.parse(t.query),{node:u}=await i(l.targetNodeId);mR(n,l,t),hR(l,u),s=o.openWebSocket(l.id,e,()=>r?.()),s.on("message",()=>s?.close(1008,"Proxy event streams do not accept client messages."));const m=a.subscribe({bindingId:l.id,sourceControlPlaneId:l.sourceControlPlaneId,targetNodeId:l.targetNodeId},p.sinceRevision,e=>{s?.send(JSON.stringify(e))},()=>{s?.close(1011,"Proxy event delivery failed.")});r=m.close,c=o.registerBindingCleanup(l.id,r);const h=()=>{r?.(),c?.()};s.on("close",h),s.on("error",h),"snapshot-required"===m.kind?(r(),s.close(1008,"Proxy target snapshot is required.")):1!==s.readyState&&r()}catch(t){r?.(),c?.();const n=yR(t);s?.close(1008,n.message),s||e.close(429===n.statusCode?1013:n.statusCode<500?1008:1011,wR(n.message))}}),t.delete("/api/node-proxy/bindings/:bindingId",{config:BS},async(t,i)=>{try{const i=rR.parse(t.params).bindingId;uR(n,i,t);const s=n.revokeBinding(i),a=o.closeBinding(i);return e.onBindingRevoked?.(s),{data:{binding:s,closed:a}}}catch(e){return fR(i,e,t)}})}({app:o,authority:H,resolveTarget:e=>{const t=S.requireNode(e);return{node:t,transport:S.resolveNodeAgentTransport(t)}},projectTarget:F,runtime:G,eventHub:W,onBindingRevoked:e=>l.publish("control-plane-proxy.binding.updated",{binding:e,audit:{action:"binding.revoke",actor:`control-plane:${e.sourceControlPlaneId}`}},{topic:"control-plane-proxy",scope:{nodeId:e.targetNodeId}})}),function(e){const{app:t,service:n,proxy:i,runtime:s,events:a,syncNodeEvents:o,actorId:r}=e;t.get("/api/control-plane-proxy/invites",async()=>({data:i.listInvites()})),t.post("/api/control-plane-proxy/invites",async(e,t)=>{const n=await r(e),s=i.createInvite(e.body,n);return a.publish("control-plane-proxy.invite.created",{invite:s.invite,audit:{action:"invite.create",actor:n}},{topic:"control-plane-proxy",scope:{nodeId:s.invite.targetNodeId}}),t.code(201).send({data:s})}),t.delete("/api/control-plane-proxy/invites/:id",async e=>{const t=await r(e),n=i.revokeInvite(AR.parse(e.params).id);return a.publish("control-plane-proxy.invite.updated",{invite:n,audit:{action:"invite.revoke",actor:t}},{topic:"control-plane-proxy",scope:{nodeId:n.targetNodeId}}),{data:n}}),t.get("/api/control-plane-proxy/bindings",async()=>({data:i.listBindings()})),t.delete("/api/control-plane-proxy/bindings/:id",async e=>{const t=await r(e),n=AR.parse(e.params).id,o=i.revokeBinding(n),c=s.closeBinding(n);return a.publish("control-plane-proxy.binding.updated",{binding:o,audit:{action:"binding.revoke",actor:t}},{topic:"control-plane-proxy",scope:{nodeId:o.targetNodeId}}),{data:{binding:o,closed:c}}}),t.get("/api/control-plane-proxy/diagnostics",async()=>({data:s.diagnostics()})),t.post("/api/node-proxy/claims",{config:qS},async(e,t)=>{const n=i.claimInvite(e.body);return a.publish("control-plane-proxy.binding.created",{binding:n.binding,audit:{action:"binding.claim",actor:`control-plane:${n.binding.sourceControlPlaneId}`}},{topic:"control-plane-proxy",scope:{nodeId:n.binding.targetNodeId}}),t.code(201).send({data:n})}),t.get("/api/control-plane-proxy/pending-claims",async()=>({data:n.listPendingProxyClaims()})),t.post("/api/control-plane-proxy/claims",async(e,t)=>{const i=await n.claimProxyNode(e.body);return o?.(),a.publish("node.created",{nodeId:i.node.id}),t.code(201).send({data:i})}),t.post("/api/control-plane-proxy/pending-claims/:id/resume",async e=>{const t=AR.parse(e.params).id;ER.parse(e.body||{});const i=await n.resumeProxyClaim(t);return o?.(),a.publish("node.created",{nodeId:i.node.id}),{data:i}}),t.delete("/api/control-plane-proxy/pending-claims/:id",async e=>{const t=TR.parse(e.query||{});return{data:await n.cancelProxyClaim(AR.parse(e.params).id,"true"===t.force)}})}({app:o,service:S,proxy:H,runtime:G,events:l,syncNodeEvents:()=>Z.syncNow(),actorId:async e=>{const t=await Ek(A,Ak(e));return t?"user"===t.type?`user:${t.userId}`:"system"===t.type?`system:${t.reason}`:"cloud-account"===t.type?`cloud-account:${t.accountId}:${t.deviceSessionId}`:`chat-bridge:${t.bridgeId}`:"system:unknown"}}),function({app:e,service:t,auth:n,authorizationConnections:i}){!function(e){for(const t of["application/octet-stream","application/x-www-form-urlencoded"])fC(e,t);fC(e,/^multipart\/form-data(?:;.*)?$/i)}(e);const s=async(e,i,s="")=>{const a=await t.appAccessProxyTarget(e,i,s);return a.access.authorization&&await n.assertAppAccessAuthorization({...a.access.authorization,instanceId:a.instance.id,nodeId:a.instance.nodeId}),a},a=(e,t)=>{if(!t)return;const n=i.track(t,()=>e.close(4001,"Authorization changed."));e.on("close",n)};e.get("/api/app-access/session",{config:qS},async e=>{const t=yC(e.url),n="vnc"===e.query.mode?"vnc":"web"===e.query.mode?"web":"tty",i=await s(t,n);return{data:{mode:n,instance:{id:i.instance.id,name:i.instance.name,projectId:i.instance.projectId,projectName:"string"==typeof i.instance.sourceSnapshot.name?i.instance.sourceSnapshot.name:void 0},session:i.session,expiresAt:i.access.expiresAt,ttySocketPath:"tty"===n?`/apps/access/tty/ws?token=${encodeURIComponent(t)}`:void 0,vncFramePath:"vnc"===n?bC(t,i.access.sessionId,i.session):void 0}}}),e.get("/apps/access/tty/ws",{websocket:!0,config:qS},async(e,n)=>{try{const i=await s(yC(n.url),"tty");a(e,i.access.authorization),await t.proxyInstanceWebSocket(i.instance.id,e,i.path,kz(n.headers),lC(n.headers))}catch{e.close(1011,"TTY access link is invalid or expired.")}});const o=async(e,n)=>{const i=n.params;try{const o=await s(i.token||yC(n.url),"vnc",i["*"]||"");a(e,o.access.authorization),await t.proxyInstanceWebSocket(o.instance.id,e,o.path,kz(n.headers),lC(n.headers))}catch{e.close(1011,"VNC access link is invalid or expired.")}};e.route({method:"GET",url:"/apps/access/vnc/proxy/*",config:qS,wsHandler:o,handler:async(e,n)=>{const i=e.params,a=await s(yC(e.url),"vnc",i["*"]||"");return hC(n,await pC(t,n,a.instance.id,a.path,{method:e.method,headers:dC(e.headers)}),a.instance.id,a.path)}}),e.route({method:"GET",url:"/apps/access/vnc/:token/proxy/*",config:qS,wsHandler:o,handler:async(e,n)=>{const i=e.params,a=await s(i.token,"vnc",i["*"]||"");return hC(n,await pC(t,n,a.instance.id,a.path,{method:e.method,headers:dC(e.headers)}),a.instance.id,a.path)}}),e.all("/instances/:id",{bodyLimit:67108864},async(e,n)=>{const i=e.params;return"GET"===e.method||"HEAD"===e.method?n.redirect(`${mC(i.id)}/`):hC(n,await pC(t,n,i.id,"/",{method:e.method,headers:dC(e.headers),body:await gC(e.body)}),i.id,"/")}),e.route({method:"GET",url:"/instances/:id/*",wsHandler:async(e,n)=>{const i=n.params,s=i["*"]||"",o=n.url.indexOf("?"),r=o>=0?n.url.slice(o):"";try{const o=vS(n);a(e,"user"===o?.type?o:void 0),await t.proxyInstanceWebSocket(i.id,e,`/${s}${r}`,kz(n.headers),lC(n.headers))}catch{e.close(1011,"Instance websocket endpoint is not reachable.")}},handler:async(e,n)=>{const i=e.params,s=i["*"]||"",a=e.url.indexOf("?"),o=`/${s}${a>=0?e.url.slice(a):""}`;return hC(n,await pC(t,n,i.id,o,{method:e.method,headers:dC(e.headers)}),i.id,o)}}),e.route({method:["POST","PUT","PATCH","DELETE","OPTIONS"],url:"/instances/:id/*",bodyLimit:67108864,handler:async(e,n)=>{const i=e.params,s=i["*"]||"",a=e.url.indexOf("?"),o=a>=0?e.url.slice(a):"";return uC(n,await pC(t,n,i.id,`/${s}${o}`,{method:e.method,headers:dC(e.headers),body:await gC(e.body)}))}})}({app:o,service:S,auth:A,authorizationConnections:y}),function(e){const{app:t,service:n,auth:i,authorizationConnections:s,events:a}=e,o=e.browserAccess||new dk;t.post("/api/controlled-instances/:id/browser-access",async e=>{const{id:t}=KT.parse(e.params),s=function(e,t){const n=vS(e);if("user"===n?.type)return n;if(!1===t.enabled?.())return{type:"system",reason:"auth-disabled",userId:"system:auth-disabled",authorizationRevision:0};throw Object.assign(new Error("A signed-in Control Plane user is required."),{statusCode:403,code:"BROWSER_ACCESS_USER_REQUIRED"})}(e,i),a=await hz(n,e,t);if(hh(s,"interactive-access",{type:"instance",id:t,nodeId:a.nodeId}),!wc(a.capabilities).features.browserTunnel)throw Object.assign(new Error("The controlled instance does not support Browser Tunnel."),{statusCode:409,code:"BROWSER_TUNNEL_UNSUPPORTED"});const r=o.create({instanceId:t,authorization:{userId:s.userId,authorizationRevision:s.authorizationRevision}});return{data:ck.parse({accessId:r.accessId,token:r.token,expiresAt:r.expiresAt,relayPath:"/browser-relay"})}}),t.get("/browser-relay",{websocket:!0,config:qS},async(e,t)=>{let a,r;const c=[],d=(e,t=!1)=>c.push([e,Boolean(t)]);e.on("message",d);try{const p=o.consume("string"==typeof(l=t.headers.authorization)&&l.startsWith("Browser ")?l.slice(8).trim():"");!1!==i.enabled?.()&&await i.assertAppAccessAuthorization({...p.authorization,instanceId:p.instanceId,nodeId:(await n.requireControlledInstance(p.instanceId,!0)).nodeId});const u=()=>e.close(4001,"Browser access authorization ended.");a=o.track(p,u),r=s.track(p.authorization,u),e.on("close",()=>{a?.(),r?.()}),await n.proxyInstanceWebSocket(p.instanceId,e,"/api/browser-tunnel",[],{}),e.off("message",d);for(const[t,n]of c.splice(0))e.emit("message",t,n)}catch{e.off("message",d),c.length=0,a?.(),r?.(),e.close(1008,"Browser access is invalid or unavailable.")}var l}),a.on(e=>{if(!["instance.stopped","instance.deleted","instance.restarted"].includes(e.type))return;const t=e.payload&&"object"==typeof e.payload?e.payload:{};"string"==typeof t.instanceId&&o.closeInstance(t.instanceId)})}({app:o,service:S,auth:A,authorizationConnections:y,events:l,browserAccess:b}),o.get("*",{config:$S},async(e,t)=>n.existsSync(te)?_k(t,te,"index.html"):t.code(404).send({error:{code:"CONTROL_PLANE_UI_NOT_BUILT",message:"Control plane API is running, but the Web UI static directory was not found."}})),X=setInterval(()=>{J().catch(e=>o.log.warn({error:e},"pending node pairing recovery failed"))},3e4),X.unref(),Y=setInterval(()=>{S.runPersistenceMaintenance(),hT(c,d,a,{onWarning:e=>o.log.warn(e,"legacy Control Plane P0 persistence archive deferred")}).catch(e=>o.log.warn({error:e},"legacy Control Plane P0 persistence archive retry failed"))},216e5),Y.unref(),o}function Ok(e){const t=Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error("Port must be a valid TCP port.");return t}function jk(e){if("disabled"!==e&&"password"!==e)throw new Error("Auth mode must be disabled or password.");return e}function Pk(e,t){return{id:e,sql:t,checksum:i.createHash("sha256").update(t).digest("hex")}}(async function(){const n=new e.Command;n.name("task-handoff-control-plane").description("Run the TaskHandoff control plane.").version(q("@task-handoff/cli")).option("--host <host>","Control plane host",process.env.TASK_HANDOFF_CONTROL_PLANE_HOST||"127.0.0.1").option("-p, --port <port>","Control plane port",Ok,Number(process.env.TASK_HANDOFF_CONTROL_PLANE_PORT)||8081).option("--data-dir <path>","Control plane data directory").option("--static-dir <path>","Control plane Web UI static directory",process.env.TASK_HANDOFF_CONTROL_PLANE_STATIC_DIR||t.resolve(__dirname,"..","ui")).option("--auth-mode <mode>","Control plane auth mode: disabled or password",jk,process.env.TASK_HANDOFF_CONTROL_PLANE_AUTH_MODE||"password").action(async e=>{await async function(e){const t=function(e=Date.now()){return(t,n={})=>{try{process.stdout.write(`${JSON.stringify({level:30,time:Date.now(),pid:process.pid,...n,elapsedMs:Date.now()-e,msg:`control plane ${t}`})}\n`)}catch{}}}();t("starting",{host:e.host,port:e.port,version:process.env.TASK_HANDOFF_VERSION||""});const n=ME(e.dataDir),i=BT($T(),{dataDir:n.dataDir,host:e.host,port:e.port});t("singleton lease acquired",{lockPath:i.lockPath});try{const n=await kk({...e,service:{...e.service,marketCatalog:e.service?.marketCatalog??bk()}});n.addHook("onClose",async()=>{i.release()}),await n.listen({host:e.host,port:e.port}),t("http listener ready",{host:e.host,port:e.port})}catch(n){if(i.release(),t("startup failed",{error:n instanceof Error?n.message:String(n)}),n&&"object"==typeof n&&"EADDRINUSE"===n.code)throw Object.assign(new Error(`Control plane port ${e.host}:${e.port} is already in use.`),{statusCode:409,code:"CONTROL_PLANE_PORT_IN_USE",cause:n});throw n}}({host:e.host,port:e.port,dataDir:e.dataDir,staticDir:e.staticDir,auth:{mode:e.authMode}})}),n.command("credentials").description("Initialize or replace Control Plane administrator credentials while the service is stopped.").requiredOption("--username <username>","New administrator username").requiredOption("--password-stdin","Read the new password from standard input").option("--user-id <userId>","Select the account by its local user ID").option("--target-username <username>","Select the account by its current username").option("--initialize-if-needed","Create the administrator only when none exists").option("--data-dir <path>","Control plane data directory").action(async e=>{if(process.stdin.isTTY)throw new Error("Pipe the new password to standard input when using --password-stdin.");const t=[];for await(const e of process.stdin)t.push(Buffer.isBuffer(e)?e:Buffer.from(e));const i=Buffer.concat(t).toString("utf8").replace(/\r?\n$/,""),s=e.dataDir??n.opts().dataDir;if(e.initializeIfNeeded){const t=await async function(e,t,n={}){const i=ME(e),s=BT(n.lockPath||$T(),{dataDir:i.dataDir}),a=new jg(i);try{return await a.init(),a.store.state().initialized&&(await a.store.users.list()).length>0?{created:!1}:{created:!0,user:await a.bootstrapAdmin(t)}}finally{try{await a.store.close()}finally{s.release()}}}(s,{username:e.username,password:i});return void console.log(t.created?"created":"unchanged")}const a=await async function(e,t,n={}){const i=ME(e),s=BT(n.lockPath||$T(),{dataDir:i.dataDir}),a=new jg(i);try{return await a.init(),await a.recoverLocalCredentials(t)}finally{try{await a.store.close()}finally{s.release()}}}(s,{username:e.username,password:i,userId:e.userId,targetUsername:e.targetUsername});console.log(`Updated Control Plane credentials for ${a.primaryUsername||a.displayName}. Existing sessions were revoked.`)}),await n.parseAsync(process.argv)})().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});const Lk=f.z.record(f.z.string(),f.z.union([f.z.string(),f.z.number(),f.z.boolean(),f.z.null(),f.z.array(f.z.union([f.z.string(),f.z.number(),f.z.boolean(),f.z.null()]))])),Dk=f.z.object({id:f.z.string().regex(/^(?:\d{4}|app_\d{4}|import_v\d+\.\d+\.\d+)_[a-z0-9_.-]+$/),checksum:f.z.string().regex(/^[a-f0-9]{64}$/),appliedAt:f.z.string().datetime(),details:Lk}).strict();function Mk(e,t,n){const i=n instanceof Error?n:new Error(String(n));return Object.assign(new Error(`Control Plane ${e} database ${t} failed: ${i.message}`,{cause:i}),{code:`CONTROL_PLANE_DATABASE_${t.toUpperCase()}_FAILED`,dialect:e,phase:t})}const Uk=[Pk("0001_user_access","\nCREATE TABLE cp_metadata (key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL);\nCREATE TABLE cp_users (\n id TEXT PRIMARY KEY NOT NULL, display_name TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('active','disabled','archived')),\n last_login_at TEXT, archived_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_login_identities (\n id TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n kind TEXT NOT NULL CHECK(kind IN ('local-password','oidc','oauth')), normalized_login_name TEXT, password_hash TEXT,\n requires_password_change INTEGER, provider_id TEXT, subject TEXT, verified_email TEXT, last_used_at TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_login_identities_login_name_uq ON cp_login_identities(normalized_login_name);\nCREATE UNIQUE INDEX cp_login_identities_provider_subject_uq ON cp_login_identities(provider_id, subject);\nCREATE INDEX cp_login_identities_user_idx ON cp_login_identities(user_id);\nCREATE TABLE cp_roles (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, description TEXT, system INTEGER NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('active','archived')), permission_ids TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_roles_active_name_uq ON cp_roles(lower(name)) WHERE status = 'active';\nCREATE TABLE cp_user_access_grants (\n user_id TEXT PRIMARY KEY NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n node_scope TEXT NOT NULL,\n instance_scope TEXT NOT NULL, authorization_revision INTEGER NOT NULL CHECK(authorization_revision > 0),\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_user_roles (\n user_id TEXT NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n role_id TEXT NOT NULL REFERENCES cp_roles(id) ON DELETE RESTRICT,\n PRIMARY KEY (user_id, role_id)\n);\nCREATE INDEX cp_user_roles_role_idx ON cp_user_roles(role_id);\nCREATE TABLE cp_user_sessions (\n id TEXT PRIMARY KEY NOT NULL, identity_id TEXT NOT NULL REFERENCES cp_login_identities(id) ON DELETE CASCADE,\n authorization_revision INTEGER NOT NULL,\n token_hash TEXT NOT NULL, expires_at TEXT NOT NULL, last_seen_at TEXT, client_type TEXT NOT NULL CHECK(client_type IN ('web','mobile')),\n device TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_user_sessions_token_hash_uq ON cp_user_sessions(token_hash);\nCREATE INDEX cp_user_sessions_identity_idx ON cp_user_sessions(identity_id);\nCREATE INDEX cp_user_sessions_expiry_idx ON cp_user_sessions(expires_at);\nCREATE TABLE cp_identity_providers (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('oidc','github')),\n status TEXT NOT NULL CHECK(status IN ('enabled','disabled')), login_policy TEXT NOT NULL,\n issuer TEXT, client_id TEXT NOT NULL, client_secret_ciphertext TEXT NOT NULL, callback_url TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_external_identity_approvals (\n id TEXT PRIMARY KEY NOT NULL, provider_id TEXT NOT NULL REFERENCES cp_identity_providers(id) ON DELETE CASCADE,\n subject TEXT NOT NULL, verified_email TEXT, display_name TEXT, status TEXT NOT NULL, expires_at TEXT NOT NULL,\n decided_at TEXT, decided_by_user_id TEXT REFERENCES cp_users(id), created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_external_identity_approvals_lookup_idx ON cp_external_identity_approvals(provider_id, subject, status);\nCREATE TABLE cp_user_audit (\n id TEXT PRIMARY KEY NOT NULL, action TEXT NOT NULL, actor_user_id TEXT, target_type TEXT NOT NULL,\n target_id TEXT, details TEXT NOT NULL, created_at TEXT NOT NULL\n);\nCREATE INDEX cp_user_audit_created_idx ON cp_user_audit(created_at);\n"),Pk("0002_p0_persistence","\nCREATE TABLE cp_nodes (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, connection_mode TEXT NOT NULL,\n connection_path TEXT NOT NULL, connection_enabled INTEGER NOT NULL,\n auth_mode TEXT NOT NULL, auth_key_id TEXT, auth_secret_ciphertext TEXT, auth_paired_at TEXT, auth_pairing_status TEXT,\n endpoint TEXT, control_endpoint TEXT, container_endpoint TEXT, public_web_base TEXT, labels TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_node_pairing_revocations (\n id TEXT PRIMARY KEY NOT NULL, endpoint TEXT NOT NULL, node_id TEXT NOT NULL, key_id TEXT NOT NULL,\n secret_ciphertext TEXT NOT NULL, paired_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_node_pairing_revocations_node_idx ON cp_node_pairing_revocations(node_id);\nCREATE TABLE cp_models (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, endpoint TEXT NOT NULL, key_ciphertext TEXT NOT NULL,\n model TEXT NOT NULL, model_names TEXT NOT NULL, protocols TEXT NOT NULL, app TEXT NOT NULL,\n enabled INTEGER NOT NULL, display_order INTEGER NOT NULL, labels TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_models_order_idx ON cp_models(display_order, name, id);\nCREATE TABLE cp_chat_bridges (\n id TEXT PRIMARY KEY NOT NULL, channel TEXT NOT NULL, name TEXT NOT NULL, enabled INTEGER NOT NULL,\n credential_ciphertext TEXT, default_chat_id TEXT, allowed_user_ids TEXT NOT NULL, poll_interval_ms INTEGER NOT NULL,\n settings TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_chat_session_bindings (\n id TEXT PRIMARY KEY NOT NULL, route_scope TEXT NOT NULL, channel TEXT NOT NULL,\n bridge_id TEXT REFERENCES cp_chat_bridges(id) ON DELETE CASCADE, chat_session_id TEXT NOT NULL,\n user_id TEXT, active_project_id TEXT, active_instance_id TEXT, active_ai_session_id TEXT, last_used_at TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_chat_session_bindings_route_uq ON cp_chat_session_bindings(channel, route_scope, chat_session_id);\nCREATE INDEX cp_chat_session_bindings_bridge_idx ON cp_chat_session_bindings(bridge_id);\nCREATE TABLE cp_git_credentials (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL, scope TEXT NOT NULL, status TEXT NOT NULL,\n revision INTEGER NOT NULL CHECK(revision >= 0), secret_ciphertext TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_git_credential_assignments (\n id TEXT PRIMARY KEY NOT NULL, instance_id TEXT NOT NULL,\n credential_id TEXT NOT NULL REFERENCES cp_git_credentials(id) ON DELETE RESTRICT,\n credential_revision INTEGER NOT NULL CHECK(credential_revision >= 0), assignment_revision INTEGER NOT NULL CHECK(assignment_revision >= 0),\n status TEXT NOT NULL, authorized_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_git_credential_assignments_identity_uq ON cp_git_credential_assignments(instance_id, credential_id);\nCREATE INDEX cp_git_credential_assignments_credential_idx ON cp_git_credential_assignments(credential_id, status);\nCREATE TABLE cp_git_provisioning_intents (\n id TEXT PRIMARY KEY NOT NULL, instance_id TEXT NOT NULL,\n credential_id TEXT NOT NULL REFERENCES cp_git_credentials(id) ON DELETE RESTRICT,\n operation_id TEXT NOT NULL, input_digest TEXT NOT NULL, remote_url TEXT NOT NULL, ref TEXT NOT NULL, clone TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_git_provisioning_intents_operation_uq ON cp_git_provisioning_intents(instance_id, operation_id);\nCREATE INDEX cp_git_provisioning_intents_credential_idx ON cp_git_provisioning_intents(credential_id);\nCREATE TABLE cp_git_audit (\n id TEXT PRIMARY KEY NOT NULL, action TEXT NOT NULL, credential_id TEXT NOT NULL, instance_id TEXT,\n credential_revision INTEGER, assignment_revision INTEGER, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_git_audit_created_idx ON cp_git_audit(created_at);\n"),Pk("0003_p0_pairing_revoke_phase","ALTER TABLE cp_node_pairing_revocations ADD COLUMN phase TEXT NOT NULL DEFAULT 'pending-compensation';"),Pk("0004_p0_chat_credential_metadata",'ALTER TABLE cp_chat_bridges ADD COLUMN credential_metadata TEXT NOT NULL DEFAULT \'{"tokenSet":false,"clientSecretSet":false,"appSecretSet":false}\';'),Pk("0005_model_legacy_projections","\nCREATE TABLE cp_model_legacy_projections (\n id TEXT PRIMARY KEY NOT NULL, model_id TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_model_legacy_projections_model_idx ON cp_model_legacy_projections(model_id);\n"),Pk("0006_cli_sessions","\nALTER TABLE cp_user_sessions RENAME TO cp_user_sessions_pre_cli;\nCREATE TABLE cp_user_sessions (\n id TEXT PRIMARY KEY NOT NULL, identity_id TEXT NOT NULL REFERENCES cp_login_identities(id) ON DELETE CASCADE,\n authorization_revision INTEGER NOT NULL,\n token_hash TEXT NOT NULL, expires_at TEXT NOT NULL, last_seen_at TEXT,\n client_type TEXT NOT NULL CHECK(client_type IN ('web','mobile','cli')),\n device TEXT, client_info TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nINSERT INTO cp_user_sessions (id, identity_id, authorization_revision, token_hash, expires_at, last_seen_at, client_type, device, client_info, created_at, updated_at)\n SELECT id, identity_id, authorization_revision, token_hash, expires_at, last_seen_at, client_type, device, NULL, created_at, updated_at\n FROM cp_user_sessions_pre_cli;\nDROP TABLE cp_user_sessions_pre_cli;\nCREATE UNIQUE INDEX cp_user_sessions_token_hash_uq ON cp_user_sessions(token_hash);\nCREATE INDEX cp_user_sessions_identity_idx ON cp_user_sessions(identity_id);\nCREATE INDEX cp_user_sessions_expiry_idx ON cp_user_sessions(expires_at);\n"),Pk("0007_local_trust_identities","\nALTER TABLE cp_user_sessions RENAME TO cp_user_sessions_pre_local_trust;\nALTER TABLE cp_login_identities RENAME TO cp_login_identities_pre_local_trust;\nCREATE TABLE cp_login_identities (\n id TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n kind TEXT NOT NULL CHECK(kind IN ('local-password','oidc','oauth','local-trust')), normalized_login_name TEXT, password_hash TEXT,\n requires_password_change INTEGER, provider_id TEXT, subject TEXT, verified_email TEXT, last_used_at TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nINSERT INTO cp_login_identities (id, user_id, kind, normalized_login_name, password_hash, requires_password_change, provider_id, subject, verified_email, last_used_at, created_at, updated_at)\n SELECT id, user_id, kind, normalized_login_name, password_hash, requires_password_change, provider_id, subject, verified_email, last_used_at, created_at, updated_at\n FROM cp_login_identities_pre_local_trust;\nCREATE TABLE cp_user_sessions (\n id TEXT PRIMARY KEY NOT NULL, identity_id TEXT NOT NULL REFERENCES cp_login_identities(id) ON DELETE CASCADE,\n authorization_revision INTEGER NOT NULL,\n token_hash TEXT NOT NULL, expires_at TEXT NOT NULL, last_seen_at TEXT,\n client_type TEXT NOT NULL CHECK(client_type IN ('web','mobile','cli')),\n device TEXT, client_info TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nINSERT INTO cp_user_sessions (id, identity_id, authorization_revision, token_hash, expires_at, last_seen_at, client_type, device, client_info, created_at, updated_at)\n SELECT id, identity_id, authorization_revision, token_hash, expires_at, last_seen_at, client_type, device, client_info, created_at, updated_at\n FROM cp_user_sessions_pre_local_trust;\nDROP TABLE cp_user_sessions_pre_local_trust;\nDROP TABLE cp_login_identities_pre_local_trust;\nCREATE UNIQUE INDEX cp_login_identities_login_name_uq ON cp_login_identities(normalized_login_name);\nCREATE UNIQUE INDEX cp_login_identities_provider_subject_uq ON cp_login_identities(provider_id, subject);\nCREATE INDEX cp_login_identities_user_idx ON cp_login_identities(user_id);\nCREATE UNIQUE INDEX cp_user_sessions_token_hash_uq ON cp_user_sessions(token_hash);\nCREATE INDEX cp_user_sessions_identity_idx ON cp_user_sessions(identity_id);\nCREATE INDEX cp_user_sessions_expiry_idx ON cp_user_sessions(expires_at);\n"),Pk("0008_model_request_mappings","ALTER TABLE cp_models ADD COLUMN mappings TEXT NOT NULL DEFAULT '[]';"),Pk("0009_drop_model_legacy_projections","DROP TABLE IF EXISTS cp_model_legacy_projections;")],qk=[Pk("0001_user_access","\nCREATE TABLE cp_metadata (key TEXT PRIMARY KEY NOT NULL, value JSONB NOT NULL);\nCREATE TABLE cp_users (\n id TEXT PRIMARY KEY NOT NULL, display_name TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('active','disabled','archived')),\n last_login_at TEXT, archived_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_login_identities (\n id TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n kind TEXT NOT NULL CHECK(kind IN ('local-password','oidc','oauth')), normalized_login_name TEXT, password_hash TEXT,\n requires_password_change BOOLEAN, provider_id TEXT, subject TEXT, verified_email TEXT, last_used_at TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_login_identities_login_name_uq ON cp_login_identities(normalized_login_name);\nCREATE UNIQUE INDEX cp_login_identities_provider_subject_uq ON cp_login_identities(provider_id, subject);\nCREATE INDEX cp_login_identities_user_idx ON cp_login_identities(user_id);\nCREATE TABLE cp_roles (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, description TEXT, system BOOLEAN NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('active','archived')), permission_ids JSONB NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_roles_active_name_uq ON cp_roles(lower(name)) WHERE status = 'active';\nCREATE TABLE cp_user_access_grants (\n user_id TEXT PRIMARY KEY NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n node_scope JSONB NOT NULL,\n instance_scope JSONB NOT NULL, authorization_revision INTEGER NOT NULL CHECK(authorization_revision > 0),\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_user_roles (\n user_id TEXT NOT NULL REFERENCES cp_users(id) ON DELETE CASCADE,\n role_id TEXT NOT NULL REFERENCES cp_roles(id) ON DELETE RESTRICT,\n PRIMARY KEY (user_id, role_id)\n);\nCREATE INDEX cp_user_roles_role_idx ON cp_user_roles(role_id);\nCREATE TABLE cp_user_sessions (\n id TEXT PRIMARY KEY NOT NULL, identity_id TEXT NOT NULL REFERENCES cp_login_identities(id) ON DELETE CASCADE,\n authorization_revision INTEGER NOT NULL,\n token_hash TEXT NOT NULL, expires_at TEXT NOT NULL, last_seen_at TEXT, client_type TEXT NOT NULL CHECK(client_type IN ('web','mobile')),\n device JSONB, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_user_sessions_token_hash_uq ON cp_user_sessions(token_hash);\nCREATE INDEX cp_user_sessions_identity_idx ON cp_user_sessions(identity_id);\nCREATE INDEX cp_user_sessions_expiry_idx ON cp_user_sessions(expires_at);\nCREATE TABLE cp_identity_providers (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('oidc','github')),\n status TEXT NOT NULL CHECK(status IN ('enabled','disabled')), login_policy TEXT NOT NULL,\n issuer TEXT, client_id TEXT NOT NULL, client_secret_ciphertext TEXT NOT NULL, callback_url TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_external_identity_approvals (\n id TEXT PRIMARY KEY NOT NULL, provider_id TEXT NOT NULL REFERENCES cp_identity_providers(id) ON DELETE CASCADE,\n subject TEXT NOT NULL, verified_email TEXT, display_name TEXT, status TEXT NOT NULL, expires_at TEXT NOT NULL,\n decided_at TEXT, decided_by_user_id TEXT REFERENCES cp_users(id), created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_external_identity_approvals_lookup_idx ON cp_external_identity_approvals(provider_id, subject, status);\nCREATE TABLE cp_user_audit (\n id TEXT PRIMARY KEY NOT NULL, action TEXT NOT NULL, actor_user_id TEXT, target_type TEXT NOT NULL,\n target_id TEXT, details JSONB NOT NULL, created_at TEXT NOT NULL\n);\nCREATE INDEX cp_user_audit_created_idx ON cp_user_audit(created_at);\n"),Pk("0002_p0_persistence","\nCREATE TABLE cp_nodes (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, connection_mode TEXT NOT NULL,\n connection_path JSONB NOT NULL, connection_enabled BOOLEAN NOT NULL,\n auth_mode TEXT NOT NULL, auth_key_id TEXT, auth_secret_ciphertext TEXT, auth_paired_at TEXT, auth_pairing_status TEXT,\n endpoint TEXT, control_endpoint TEXT, container_endpoint TEXT, public_web_base TEXT, labels JSONB NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_node_pairing_revocations (\n id TEXT PRIMARY KEY NOT NULL, endpoint TEXT NOT NULL, node_id TEXT NOT NULL, key_id TEXT NOT NULL,\n secret_ciphertext TEXT NOT NULL, paired_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_node_pairing_revocations_node_idx ON cp_node_pairing_revocations(node_id);\nCREATE TABLE cp_models (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, endpoint TEXT NOT NULL, key_ciphertext TEXT NOT NULL,\n model TEXT NOT NULL, model_names JSONB NOT NULL, protocols JSONB NOT NULL, app TEXT NOT NULL,\n enabled BOOLEAN NOT NULL, display_order INTEGER NOT NULL, labels JSONB NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_models_order_idx ON cp_models(display_order, name, id);\nCREATE TABLE cp_chat_bridges (\n id TEXT PRIMARY KEY NOT NULL, channel TEXT NOT NULL, name TEXT NOT NULL, enabled BOOLEAN NOT NULL,\n credential_ciphertext TEXT, default_chat_id TEXT, allowed_user_ids JSONB NOT NULL, poll_interval_ms INTEGER NOT NULL,\n settings JSONB NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_chat_session_bindings (\n id TEXT PRIMARY KEY NOT NULL, route_scope TEXT NOT NULL, channel TEXT NOT NULL,\n bridge_id TEXT REFERENCES cp_chat_bridges(id) ON DELETE CASCADE, chat_session_id TEXT NOT NULL,\n user_id TEXT, active_project_id TEXT, active_instance_id TEXT, active_ai_session_id TEXT, last_used_at TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_chat_session_bindings_route_uq ON cp_chat_session_bindings(channel, route_scope, chat_session_id);\nCREATE INDEX cp_chat_session_bindings_bridge_idx ON cp_chat_session_bindings(bridge_id);\nCREATE TABLE cp_git_credentials (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL, scope JSONB NOT NULL, status TEXT NOT NULL,\n revision INTEGER NOT NULL CHECK(revision >= 0), secret_ciphertext TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE cp_git_credential_assignments (\n id TEXT PRIMARY KEY NOT NULL, instance_id TEXT NOT NULL,\n credential_id TEXT NOT NULL REFERENCES cp_git_credentials(id) ON DELETE RESTRICT,\n credential_revision INTEGER NOT NULL CHECK(credential_revision >= 0), assignment_revision INTEGER NOT NULL CHECK(assignment_revision >= 0),\n status TEXT NOT NULL, authorized_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_git_credential_assignments_identity_uq ON cp_git_credential_assignments(instance_id, credential_id);\nCREATE INDEX cp_git_credential_assignments_credential_idx ON cp_git_credential_assignments(credential_id, status);\nCREATE TABLE cp_git_provisioning_intents (\n id TEXT PRIMARY KEY NOT NULL, instance_id TEXT NOT NULL,\n credential_id TEXT NOT NULL REFERENCES cp_git_credentials(id) ON DELETE RESTRICT,\n operation_id TEXT NOT NULL, input_digest TEXT NOT NULL, remote_url TEXT NOT NULL, ref JSONB NOT NULL, clone JSONB NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX cp_git_provisioning_intents_operation_uq ON cp_git_provisioning_intents(instance_id, operation_id);\nCREATE INDEX cp_git_provisioning_intents_credential_idx ON cp_git_provisioning_intents(credential_id);\nCREATE TABLE cp_git_audit (\n id TEXT PRIMARY KEY NOT NULL, action TEXT NOT NULL, credential_id TEXT NOT NULL, instance_id TEXT,\n credential_revision INTEGER, assignment_revision INTEGER, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_git_audit_created_idx ON cp_git_audit(created_at);\n"),Pk("0003_p0_pairing_revoke_phase","ALTER TABLE cp_node_pairing_revocations ADD COLUMN phase TEXT NOT NULL DEFAULT 'pending-compensation';"),Pk("0004_p0_chat_credential_metadata",'ALTER TABLE cp_chat_bridges ADD COLUMN credential_metadata JSONB NOT NULL DEFAULT \'{"tokenSet":false,"clientSecretSet":false,"appSecretSet":false}\'::jsonb;'),Pk("0005_model_legacy_projections","\nCREATE TABLE cp_model_legacy_projections (\n id TEXT PRIMARY KEY NOT NULL, model_id TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX cp_model_legacy_projections_model_idx ON cp_model_legacy_projections(model_id);\n"),Pk("0006_cli_sessions","\nALTER TABLE cp_user_sessions DROP CONSTRAINT IF EXISTS cp_user_sessions_client_type_check;\nALTER TABLE cp_user_sessions ADD CONSTRAINT cp_user_sessions_client_type_check CHECK (client_type IN ('web','mobile','cli'));\nALTER TABLE cp_user_sessions ADD COLUMN IF NOT EXISTS client_info JSONB;\n"),Pk("0007_local_trust_identities","\nALTER TABLE cp_login_identities DROP CONSTRAINT IF EXISTS cp_login_identities_kind_check;\nALTER TABLE cp_login_identities ADD CONSTRAINT cp_login_identities_kind_check CHECK (kind IN ('local-password','oidc','oauth','local-trust'));\n"),Pk("0008_model_request_mappings","ALTER TABLE cp_models ADD COLUMN mappings JSONB NOT NULL DEFAULT '[]'::jsonb;"),Pk("0009_drop_model_legacy_projections","DROP TABLE IF EXISTS cp_model_legacy_projections;")],$k=f.z.object({id:f.z.string().trim().min(1),createdAt:f.z.string().datetime(),updatedAt:f.z.string().datetime()}),Bk=$k.extend({displayName:f.z.string().trim().min(1).max(160),status:$u,lastLoginAt:f.z.string().datetime().optional(),archivedAt:f.z.string().datetime().optional()}).strict().superRefine((e,t)=>{"archived"!==e.status||e.archivedAt||t.addIssue({code:"custom",path:["archivedAt"],message:"Archived users require archivedAt."}),"archived"!==e.status&&e.archivedAt&&t.addIssue({code:"custom",path:["archivedAt"],message:"Only archived users can have archivedAt."})}),Fk=$k.extend({userId:f.z.string().trim().min(1),kind:Bu,normalizedLoginName:f.z.string().trim().min(1).max(160).optional(),passwordHash:f.z.string().trim().min(1).optional(),requiresPasswordChange:f.z.boolean().optional(),providerId:f.z.string().trim().min(1).optional(),subject:f.z.string().trim().min(1).max(500).optional(),verifiedEmail:f.z.string().email().optional(),lastUsedAt:f.z.string().datetime().optional()}).strict().superRefine((e,t)=>{"local-password"===e.kind?(e.normalizedLoginName||t.addIssue({code:"custom",path:["normalizedLoginName"],message:"Local identity requires normalizedLoginName."}),e.passwordHash||t.addIssue({code:"custom",path:["passwordHash"],message:"Local identity requires passwordHash."}),(e.providerId||e.subject)&&t.addIssue({code:"custom",path:["providerId"],message:"Local identity cannot reference a provider."})):"local-trust"===e.kind?((e.passwordHash||e.normalizedLoginName)&&t.addIssue({code:"custom",path:["passwordHash"],message:"Local trust identity cannot contain local credentials."}),(e.providerId||e.subject||e.verifiedEmail)&&t.addIssue({code:"custom",path:["providerId"],message:"Local trust identity cannot reference an external provider."})):(e.providerId&&e.subject||t.addIssue({code:"custom",path:["providerId"],message:"External identity requires providerId and subject."}),(e.passwordHash||e.normalizedLoginName)&&t.addIssue({code:"custom",path:["passwordHash"],message:"External identity cannot contain local credentials."}))}),Hk=$k.extend({name:f.z.string().trim().min(1).max(120),description:f.z.string().trim().max(500).optional(),system:f.z.boolean(),status:Fu,permissionIds:f.z.array(qu)}).strict(),Gk=f.z.object({userId:f.z.string().trim().min(1),roleIds:f.z.array(f.z.string().trim().min(1)).min(1).max(100),nodeScope:Ku,instanceScope:Xu.default({kind:"inherit-node-scope"}),authorizationRevision:f.z.number().int().positive(),createdAt:f.z.string().datetime(),updatedAt:f.z.string().datetime()}).strict(),Wk=$k.extend({userId:f.z.string().trim().min(1),identityId:f.z.string().trim().min(1),authorizationRevision:f.z.number().int().positive(),tokenHash:f.z.string().trim().min(1),expiresAt:f.z.string().datetime(),lastSeenAt:f.z.string().datetime().optional(),clientType:f.z.enum(["web","mobile","cli"]),device:f.z.object({id:f.z.string().trim().min(1),name:f.z.string().trim().min(1),platform:f.z.enum(["ios","android"]),appVersion:f.z.string().trim().min(1).optional()}).strict().optional(),clientInfo:fm.optional()}).strict().refine(e=>"mobile"!==e.clientType||Boolean(e.device),{path:["device"],message:"Mobile sessions require device metadata."}).refine(e=>"cli"!==e.clientType||Boolean(e.clientInfo),{path:["clientInfo"],message:"CLI sessions require client metadata."}),Vk=$k.extend({name:f.z.string().trim().min(1).max(120),kind:Hu,status:Gu,loginPolicy:Wu,issuer:f.z.string().url().optional(),clientId:f.z.string().trim().min(1).max(500),clientSecretCiphertext:f.z.string().trim().min(1),callbackUrl:f.z.string().url()}).strict().superRefine((e,t)=>{"oidc"!==e.kind||e.issuer||t.addIssue({code:"custom",path:["issuer"],message:"OIDC provider requires issuer."})}),Kk={users:Bk,identities:Fk,roles:Hk,grants:Gk,sessions:Wk,providers:Vk,approvals:$k.extend({providerId:f.z.string().trim().min(1),subject:f.z.string().trim().min(1).max(500),verifiedEmail:f.z.string().email().optional(),displayName:f.z.string().trim().min(1).max(160).optional(),status:f.z.enum(["pending","approved","rejected","expired"]),expiresAt:f.z.string().datetime(),decidedAt:f.z.string().datetime().optional(),decidedByUserId:f.z.string().trim().min(1).optional()}).strict(),audit:f.z.object({id:f.z.string().trim().min(1),action:f.z.string().trim().min(1).max(160),actorUserId:f.z.string().trim().min(1).optional(),targetType:f.z.string().trim().min(1).max(120),targetId:f.z.string().trim().min(1).optional(),details:f.z.record(f.z.string(),f.z.unknown()),createdAt:f.z.string().datetime()}).strict()};function Xk(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,void 0===t?null:t]))}function Yk(e,t){return e.parse(Object.fromEntries(Object.entries(t).filter(([,e])=>null!==e)))}const Jk={createdAt:R.text("created_at").notNull(),updatedAt:R.text("updated_at").notNull()},Qk=R.pgTable("cp_metadata",{key:R.text("key").primaryKey(),value:R.jsonb("value").notNull()}),Zk=R.pgTable("cp_users",{id:R.text("id").primaryKey(),displayName:R.text("display_name").notNull(),status:R.text("status").notNull(),lastLoginAt:R.text("last_login_at"),archivedAt:R.text("archived_at"),...Jk}),eO=R.pgTable("cp_login_identities",{id:R.text("id").primaryKey(),userId:R.text("user_id").notNull().references(()=>Zk.id,{onDelete:"cascade"}),kind:R.text("kind").notNull(),normalizedLoginName:R.text("normalized_login_name"),passwordHash:R.text("password_hash"),requiresPasswordChange:R.boolean("requires_password_change"),providerId:R.text("provider_id"),subject:R.text("subject"),verifiedEmail:R.text("verified_email"),lastUsedAt:R.text("last_used_at"),...Jk},e=>[R.uniqueIndex("cp_login_identities_login_name_uq").on(e.normalizedLoginName),R.uniqueIndex("cp_login_identities_provider_subject_uq").on(e.providerId,e.subject),R.index("cp_login_identities_user_idx").on(e.userId)]),tO=R.pgTable("cp_roles",{id:R.text("id").primaryKey(),name:R.text("name").notNull(),description:R.text("description"),system:R.boolean("system").notNull(),status:R.text("status").notNull(),permissionIds:R.jsonb("permission_ids").$type().notNull(),...Jk},e=>[R.uniqueIndex("cp_roles_active_name_uq").on(z.sql`lower(${e.name})`).where(z.sql`${e.status} = 'active'`)]),nO=R.pgTable("cp_user_access_grants",{userId:R.text("user_id").primaryKey().references(()=>Zk.id,{onDelete:"cascade"}),nodeScope:R.jsonb("node_scope").$type().notNull(),instanceScope:R.jsonb("instance_scope").$type().notNull(),authorizationRevision:R.integer("authorization_revision").notNull(),...Jk}),iO=R.pgTable("cp_user_roles",{userId:R.text("user_id").notNull().references(()=>Zk.id,{onDelete:"cascade"}),roleId:R.text("role_id").notNull().references(()=>tO.id,{onDelete:"restrict"})},e=>[R.primaryKey({columns:[e.userId,e.roleId]}),R.index("cp_user_roles_role_idx").on(e.roleId)]),sO=R.pgTable("cp_user_sessions",{id:R.text("id").primaryKey(),identityId:R.text("identity_id").notNull().references(()=>eO.id,{onDelete:"cascade"}),authorizationRevision:R.integer("authorization_revision").notNull(),tokenHash:R.text("token_hash").notNull(),expiresAt:R.text("expires_at").notNull(),lastSeenAt:R.text("last_seen_at"),clientType:R.text("client_type").notNull(),device:R.jsonb("device").$type(),clientInfo:R.jsonb("client_info").$type(),...Jk},e=>[R.uniqueIndex("cp_user_sessions_token_hash_uq").on(e.tokenHash),R.index("cp_user_sessions_identity_idx").on(e.identityId),R.index("cp_user_sessions_expiry_idx").on(e.expiresAt)]),aO=R.pgTable("cp_identity_providers",{id:R.text("id").primaryKey(),name:R.text("name").notNull(),kind:R.text("kind").notNull(),status:R.text("status").notNull(),loginPolicy:R.text("login_policy").notNull(),issuer:R.text("issuer"),clientId:R.text("client_id").notNull(),clientSecretCiphertext:R.text("client_secret_ciphertext").notNull(),callbackUrl:R.text("callback_url").notNull(),...Jk}),oO=R.pgTable("cp_external_identity_approvals",{id:R.text("id").primaryKey(),providerId:R.text("provider_id").notNull().references(()=>aO.id,{onDelete:"cascade"}),subject:R.text("subject").notNull(),verifiedEmail:R.text("verified_email"),displayName:R.text("display_name"),status:R.text("status").notNull(),expiresAt:R.text("expires_at").notNull(),decidedAt:R.text("decided_at"),decidedByUserId:R.text("decided_by_user_id").references(()=>Zk.id),...Jk},e=>[R.index("cp_external_identity_approvals_lookup_idx").on(e.providerId,e.subject,e.status)]),rO=R.pgTable("cp_user_audit",{id:R.text("id").primaryKey(),action:R.text("action").notNull(),actorUserId:R.text("actor_user_id"),targetType:R.text("target_type").notNull(),targetId:R.text("target_id"),details:R.jsonb("details").$type().notNull(),createdAt:R.text("created_at").notNull()},e=>[R.index("cp_user_audit_created_idx").on(e.createdAt)]),cO=R.pgTable("cp_migration_ledger",{id:R.text("id").primaryKey(),checksum:R.text("checksum").notNull(),appliedAt:R.text("applied_at").notNull(),details:R.jsonb("details").$type().notNull()}),dO=R.pgTable("cp_nodes",{id:R.text("id").primaryKey(),name:R.text("name").notNull(),connectionMode:R.text("connection_mode").notNull(),connectionPath:R.jsonb("connection_path").notNull(),connectionEnabled:R.boolean("connection_enabled").notNull(),authMode:R.text("auth_mode").notNull(),authKeyId:R.text("auth_key_id"),authSecretCiphertext:R.text("auth_secret_ciphertext"),authPairedAt:R.text("auth_paired_at"),authPairingStatus:R.text("auth_pairing_status"),endpoint:R.text("endpoint"),controlEndpoint:R.text("control_endpoint"),containerEndpoint:R.text("container_endpoint"),publicWebBase:R.text("public_web_base"),labels:R.jsonb("labels").$type().notNull(),...Jk}),lO=R.pgTable("cp_node_pairing_revocations",{id:R.text("id").primaryKey(),endpoint:R.text("endpoint").notNull(),nodeId:R.text("node_id").notNull(),keyId:R.text("key_id").notNull(),secretCiphertext:R.text("secret_ciphertext").notNull(),pairedAt:R.text("paired_at").notNull(),phase:R.text("phase").notNull().default("pending-compensation"),...Jk},e=>[R.index("cp_node_pairing_revocations_node_idx").on(e.nodeId)]),pO=R.pgTable("cp_models",{id:R.text("id").primaryKey(),name:R.text("name").notNull(),endpoint:R.text("endpoint").notNull(),keyCiphertext:R.text("key_ciphertext").notNull(),model:R.text("model").notNull(),modelNames:R.jsonb("model_names").$type().notNull(),mappings:R.jsonb("mappings").$type().notNull(),protocols:R.jsonb("protocols").$type().notNull(),app:R.text("app").notNull(),enabled:R.boolean("enabled").notNull(),order:R.integer("display_order").notNull(),labels:R.jsonb("labels").$type().notNull(),...Jk},e=>[R.index("cp_models_order_idx").on(e.order,e.name,e.id)]),uO=R.pgTable("cp_chat_bridges",{id:R.text("id").primaryKey(),channel:R.text("channel").notNull(),name:R.text("name").notNull(),enabled:R.boolean("enabled").notNull(),credentialCiphertext:R.text("credential_ciphertext"),credentialMetadata:R.jsonb("credential_metadata").$type().notNull().default({tokenSet:!1,clientSecretSet:!1,appSecretSet:!1}),defaultChatId:R.text("default_chat_id"),allowedUserIds:R.jsonb("allowed_user_ids").$type().notNull(),pollIntervalMs:R.integer("poll_interval_ms").notNull(),settings:R.jsonb("settings").$type().notNull(),...Jk}),mO=R.pgTable("cp_chat_session_bindings",{id:R.text("id").primaryKey(),routeScope:R.text("route_scope").notNull(),channel:R.text("channel").notNull(),bridgeId:R.text("bridge_id").references(()=>uO.id,{onDelete:"cascade"}),chatSessionId:R.text("chat_session_id").notNull(),userId:R.text("user_id"),activeProjectId:R.text("active_project_id"),activeInstanceId:R.text("active_instance_id"),activeAiSessionId:R.text("active_ai_session_id"),lastUsedAt:R.text("last_used_at").notNull(),...Jk},e=>[R.uniqueIndex("cp_chat_session_bindings_route_uq").on(e.channel,e.routeScope,e.chatSessionId),R.index("cp_chat_session_bindings_bridge_idx").on(e.bridgeId)]),hO=R.pgTable("cp_git_credentials",{id:R.text("id").primaryKey(),name:R.text("name").notNull(),kind:R.text("kind").notNull(),scope:R.jsonb("scope").notNull(),status:R.text("status").notNull(),revision:R.integer("revision").notNull(),secretCiphertext:R.text("secret_ciphertext").notNull(),...Jk}),gO=R.pgTable("cp_git_credential_assignments",{id:R.text("id").primaryKey(),instanceId:R.text("instance_id").notNull(),credentialId:R.text("credential_id").notNull().references(()=>hO.id,{onDelete:"restrict"}),credentialRevision:R.integer("credential_revision").notNull(),assignmentRevision:R.integer("assignment_revision").notNull(),status:R.text("status").notNull(),authorizedAt:R.text("authorized_at").notNull(),...Jk},e=>[R.uniqueIndex("cp_git_credential_assignments_identity_uq").on(e.instanceId,e.credentialId),R.index("cp_git_credential_assignments_credential_idx").on(e.credentialId,e.status)]),fO=R.pgTable("cp_git_provisioning_intents",{id:R.text("id").primaryKey(),instanceId:R.text("instance_id").notNull(),credentialId:R.text("credential_id").notNull().references(()=>hO.id,{onDelete:"restrict"}),operationId:R.text("operation_id").notNull(),inputDigest:R.text("input_digest").notNull(),remoteUrl:R.text("remote_url").notNull(),ref:R.jsonb("ref").notNull(),clone:R.jsonb("clone").notNull(),...Jk},e=>[R.uniqueIndex("cp_git_provisioning_intents_operation_uq").on(e.instanceId,e.operationId),R.index("cp_git_provisioning_intents_credential_idx").on(e.credentialId)]),yO=R.pgTable("cp_git_audit",{id:R.text("id").primaryKey(),action:R.text("action").notNull(),credentialId:R.text("credential_id").notNull(),instanceId:R.text("instance_id"),credentialRevision:R.integer("credential_revision"),assignmentRevision:R.integer("assignment_revision"),...Jk},e=>[R.index("cp_git_audit_created_idx").on(e.createdAt)]);function bO(e){return`"${e.replaceAll('"','""')}"`}function IO(e,t,n){return{list:async()=>(await e.select().from(t).orderBy(z.asc(t.id))).map(e=>Yk(n,e)),async get(i){const s=await e.select().from(t).where(z.eq(t.id,i)).limit(1);return s[0]?Yk(n,s[0]):void 0},async put(i){const s=Xk(n.parse(i)),a=Object.fromEntries(Object.entries(s).filter(([e])=>"id"!==e));return await e.insert(t).values(s).onConflictDoUpdate({target:t.id,set:a}),Yk(n,s)},delete:async n=>(await e.delete(t).where(z.eq(t.id,n)).returning({id:t.id})).length>0}}function vO(e){const t=IO(e,eO,Kk.identities),n=async t=>{const n=await e.select().from(eO).where(t).limit(1);return n[0]?Yk(Kk.identities,n[0]):void 0};return{...t,findByLoginName:e=>n(z.eq(eO.normalizedLoginName,e)),findByProviderSubject:(e,t)=>n(z.and(z.eq(eO.providerId,e),z.eq(eO.subject,t))),listByUser:async t=>(await e.select().from(eO).where(z.eq(eO.userId,t))).map(e=>Yk(Kk.identities,e)),existsForProvider:async t=>(await e.select({id:eO.id}).from(eO).where(z.eq(eO.providerId,t)).limit(1)).length>0}}function wO(e){const t=new Map;for(const n of e){const e=n.grant.userId,i=t.get(e)||{grant:n.grant,roleIds:[]};i.roleIds.push(n.roleId),t.set(e,i)}return[...t.values()].map(({grant:e,roleIds:t})=>Kk.grants.parse({...e,roleIds:t.sort()}))}function xO(e,t,n){const i=t=>{const n=e.select({grant:nO,roleId:iO.roleId}).from(nO).innerJoin(iO,z.eq(nO.userId,iO.userId));return t?n.where(z.inArray(nO.userId,t)):n};return{list:async()=>wO(await i()),get:async e=>wO(await i([e]))[0],async listByRole(t){const n=(await e.select({userId:iO.userId}).from(iO).where(z.eq(iO.roleId,t))).map(e=>e.userId);return 0===n.length?[]:wO(await i(n))},put:i=>n?(async t=>{const n=Kk.grants.parse(t),{roleIds:i,...s}=n;return await e.insert(nO).values(s).onConflictDoUpdate({target:nO.userId,set:Object.fromEntries(Object.entries(s).filter(([e])=>"userId"!==e))}),await e.delete(iO).where(z.eq(iO.userId,n.userId)),await e.insert(iO).values(i.map(e=>({userId:n.userId,roleId:e}))),n})(i):t(e=>e.grants.put(i)),delete:async t=>(await e.delete(nO).where(z.eq(nO.userId,t)).returning({userId:nO.userId})).length>0}}function _O(e){const t=e=>e.map(e=>Yk(Kk.sessions,{...e.session,userId:e.userId})),n=()=>e.select({session:sO,userId:eO.userId}).from(sO).innerJoin(eO,z.eq(sO.identityId,eO.id));return{list:async()=>t(await n()),get:async e=>t(await n().where(z.eq(sO.id,e)).limit(1))[0],listByUser:async e=>t(await n().where(z.eq(eO.userId,e))),async put(t){const n=Kk.sessions.parse(t),i=await e.select({userId:eO.userId}).from(eO).where(z.eq(eO.id,n.identityId)).limit(1);if(i[0]?.userId!==n.userId)throw new Error("Session identity does not belong to the requested user.");const{userId:s,...a}=n;return await e.insert(sO).values(a).onConflictDoUpdate({target:sO.id,set:Object.fromEntries(Object.entries(a).filter(([e])=>"id"!==e))}),n},delete:async t=>(await e.delete(sO).where(z.eq(sO.id,t)).returning({id:sO.id})).length>0}}function SO(e){return{...IO(e,oO,Kk.approvals),async findActivePending(t,n,i){const s=await e.select().from(oO).where(z.and(z.eq(oO.providerId,t),z.eq(oO.subject,n),z.eq(oO.status,"pending"),z.gt(oO.expiresAt,i))).limit(1);return s[0]?Yk(Kk.approvals,s[0]):void 0},hasActivePendingForProvider:async(t,n)=>(await e.select({id:oO.id}).from(oO).where(z.and(z.eq(oO.providerId,t),z.eq(oO.status,"pending"),z.gt(oO.expiresAt,n))).limit(1)).length>0}}function AO(e){return{...IO(e,gO,iT.gitAssignments),async putIfRevision(t,n){const i=iT.gitAssignments.parse(t);if(void 0===n)return(await e.insert(gO).values(i).onConflictDoNothing().returning({id:gO.id})).length>0;const{id:s,...a}=i;return(await e.update(gO).set(a).where(z.and(z.eq(gO.id,i.id),z.eq(gO.assignmentRevision,n))).returning({id:gO.id})).length>0}}}function EO(e){return{...IO(e,fO,iT.gitProvisioningIntents),async insert(t){const n=iT.gitProvisioningIntents.parse(t);return(await e.insert(fO).values(n).onConflictDoNothing().returning({id:fO.id})).length>0}}}function TO(e){const t=IO(e,yO,iT.gitAudit);return{list:t.list,get:t.get,async append(t){const n=iT.gitAudit.parse(t);await e.insert(yO).values(n)}}}function zO(e,t,n=!1){let i;const s=async t=>n?t(i):e.transaction(async e=>t(zO(e,async()=>{},!0)));return i={dialect:"postgresql",users:IO(e,Zk,Kk.users),identities:vO(e),roles:IO(e,tO,Kk.roles),grants:xO(e,s,n),sessions:_O(e),providers:IO(e,aO,Kk.providers),approvals:SO(e),audit:IO(e,rO,Kk.audit),nodes:IO(e,dO,iT.nodes),pairingRevocations:IO(e,lO,iT.pairingRevocations),models:IO(e,pO,iT.models),chatBridges:IO(e,uO,iT.chatBridges),chatSessions:IO(e,mO,iT.chatSessions),gitCredentials:IO(e,hO,iT.gitCredentials),gitAssignments:AO(e),gitProvisioningIntents:EO(e),gitAudit:TO(e),async metadata(){const t=await e.select().from(Qk).where(z.eq(Qk.key,"user_store")).limit(1);return t[0]?.value||{schemaVersion:1}},async putMetadata(t){await e.insert(Qk).values({key:"user_store",value:t}).onConflictDoUpdate({target:Qk.key,set:{value:t}})},migration:async t=>(await e.select().from(cO).where(z.eq(cO.id,t)).limit(1))[0],async putMigration(t){t=Dk.parse(t),await e.insert(cO).values(t).onConflictDoUpdate({target:cO.id,set:{checksum:t.checksum,appliedAt:t.appliedAt,details:t.details}})},transaction:s,close:t},i}var NO=Object.freeze({__proto__:null,createPostgresqlUserRepository:async function(e){const t=new C.Pool({connectionString:e.connectionString,options:`-c search_path=${e.schema}`,application_name:"task-handoff-control-plane"});try{await t.query("SELECT 1")}catch(e){throw await t.end().catch(()=>{}),Mk("postgresql","connect",e)}try{return await async function(e,t){const n=await e.connect();try{await n.query("BEGIN"),await n.query("SELECT pg_advisory_xact_lock(hashtext($1))",[`task-handoff:user-access:${t}`]),await n.query(`CREATE SCHEMA IF NOT EXISTS ${bO(t)}`),await n.query(`SET LOCAL search_path TO ${bO(t)}`),await n.query("CREATE TABLE IF NOT EXISTS cp_migration_ledger (\n id TEXT PRIMARY KEY NOT NULL, checksum TEXT NOT NULL, applied_at TEXT NOT NULL, details JSONB NOT NULL\n )");for(const e of qk){const t=await n.query("SELECT checksum FROM cp_migration_ledger WHERE id = $1",[e.id]);if(t.rows[0]){if(t.rows[0].checksum!==e.checksum)throw new Error(`Migration checksum mismatch for ${e.id}.`)}else await n.query(e.sql),await n.query("INSERT INTO cp_migration_ledger (id, checksum, applied_at, details) VALUES ($1, $2, $3, $4)",[e.id,e.checksum,(new Date).toISOString(),{dialect:"postgresql"}])}await n.query("COMMIT")}catch(e){throw await n.query("ROLLBACK"),e}finally{n.release()}}(t,e.schema),zO(N.drizzle({client:t}),()=>t.end())}catch(e){throw await t.end().catch(()=>{}),Mk("postgresql","migrate",e)}}});const CO={createdAt:P.text("created_at").notNull(),updatedAt:P.text("updated_at").notNull()},RO=P.sqliteTable("cp_metadata",{key:P.text("key").primaryKey(),value:P.text("value",{mode:"json"}).notNull()}),kO=P.sqliteTable("cp_users",{id:P.text("id").primaryKey(),displayName:P.text("display_name").notNull(),status:P.text("status",{enum:["active","disabled","archived"]}).notNull(),lastLoginAt:P.text("last_login_at"),archivedAt:P.text("archived_at"),...CO}),OO=P.sqliteTable("cp_login_identities",{id:P.text("id").primaryKey(),userId:P.text("user_id").notNull().references(()=>kO.id,{onDelete:"cascade"}),kind:P.text("kind",{enum:["local-password","oidc","oauth"]}).notNull(),normalizedLoginName:P.text("normalized_login_name"),passwordHash:P.text("password_hash"),requiresPasswordChange:P.integer("requires_password_change",{mode:"boolean"}),providerId:P.text("provider_id"),subject:P.text("subject"),verifiedEmail:P.text("verified_email"),lastUsedAt:P.text("last_used_at"),...CO},e=>[P.uniqueIndex("cp_login_identities_login_name_uq").on(e.normalizedLoginName),P.uniqueIndex("cp_login_identities_provider_subject_uq").on(e.providerId,e.subject),P.index("cp_login_identities_user_idx").on(e.userId)]),jO=P.sqliteTable("cp_roles",{id:P.text("id").primaryKey(),name:P.text("name").notNull(),description:P.text("description"),system:P.integer("system",{mode:"boolean"}).notNull(),status:P.text("status",{enum:["active","archived"]}).notNull(),permissionIds:P.text("permission_ids",{mode:"json"}).$type().notNull(),...CO},e=>[P.uniqueIndex("cp_roles_active_name_uq").on(z.sql`lower(${e.name})`).where(z.sql`${e.status} = 'active'`)]),PO=P.sqliteTable("cp_user_access_grants",{userId:P.text("user_id").primaryKey().references(()=>kO.id,{onDelete:"cascade"}),nodeScope:P.text("node_scope",{mode:"json"}).$type().notNull(),instanceScope:P.text("instance_scope",{mode:"json"}).$type().notNull(),authorizationRevision:P.integer("authorization_revision").notNull(),...CO}),LO=P.sqliteTable("cp_user_roles",{userId:P.text("user_id").notNull().references(()=>kO.id,{onDelete:"cascade"}),roleId:P.text("role_id").notNull().references(()=>jO.id,{onDelete:"restrict"})},e=>[P.primaryKey({columns:[e.userId,e.roleId]}),P.index("cp_user_roles_role_idx").on(e.roleId)]),DO=P.sqliteTable("cp_user_sessions",{id:P.text("id").primaryKey(),identityId:P.text("identity_id").notNull().references(()=>OO.id,{onDelete:"cascade"}),authorizationRevision:P.integer("authorization_revision").notNull(),tokenHash:P.text("token_hash").notNull(),expiresAt:P.text("expires_at").notNull(),lastSeenAt:P.text("last_seen_at"),clientType:P.text("client_type",{enum:["web","mobile","cli"]}).notNull(),device:P.text("device",{mode:"json"}).$type(),clientInfo:P.text("client_info",{mode:"json"}).$type(),...CO},e=>[P.uniqueIndex("cp_user_sessions_token_hash_uq").on(e.tokenHash),P.index("cp_user_sessions_identity_idx").on(e.identityId),P.index("cp_user_sessions_expiry_idx").on(e.expiresAt)]),MO=P.sqliteTable("cp_identity_providers",{id:P.text("id").primaryKey(),name:P.text("name").notNull(),kind:P.text("kind",{enum:["oidc","github"]}).notNull(),status:P.text("status",{enum:["enabled","disabled"]}).notNull(),loginPolicy:P.text("login_policy",{enum:["existing-only","admin-approved-create"]}).notNull(),issuer:P.text("issuer"),clientId:P.text("client_id").notNull(),clientSecretCiphertext:P.text("client_secret_ciphertext").notNull(),callbackUrl:P.text("callback_url").notNull(),...CO}),UO=P.sqliteTable("cp_external_identity_approvals",{id:P.text("id").primaryKey(),providerId:P.text("provider_id").notNull().references(()=>MO.id,{onDelete:"cascade"}),subject:P.text("subject").notNull(),verifiedEmail:P.text("verified_email"),displayName:P.text("display_name"),status:P.text("status",{enum:["pending","approved","rejected","expired"]}).notNull(),expiresAt:P.text("expires_at").notNull(),decidedAt:P.text("decided_at"),decidedByUserId:P.text("decided_by_user_id").references(()=>kO.id),...CO},e=>[P.index("cp_external_identity_approvals_lookup_idx").on(e.providerId,e.subject,e.status)]),qO=P.sqliteTable("cp_user_audit",{id:P.text("id").primaryKey(),action:P.text("action").notNull(),actorUserId:P.text("actor_user_id"),targetType:P.text("target_type").notNull(),targetId:P.text("target_id"),details:P.text("details",{mode:"json"}).$type().notNull(),createdAt:P.text("created_at").notNull()},e=>[P.index("cp_user_audit_created_idx").on(e.createdAt)]),$O=P.sqliteTable("cp_migration_ledger",{id:P.text("id").primaryKey(),checksum:P.text("checksum").notNull(),appliedAt:P.text("applied_at").notNull(),details:P.text("details",{mode:"json"}).$type().notNull()}),BO=P.sqliteTable("cp_nodes",{id:P.text("id").primaryKey(),name:P.text("name").notNull(),connectionMode:P.text("connection_mode").notNull(),connectionPath:P.text("connection_path",{mode:"json"}).notNull(),connectionEnabled:P.integer("connection_enabled",{mode:"boolean"}).notNull(),authMode:P.text("auth_mode").notNull(),authKeyId:P.text("auth_key_id"),authSecretCiphertext:P.text("auth_secret_ciphertext"),authPairedAt:P.text("auth_paired_at"),authPairingStatus:P.text("auth_pairing_status"),endpoint:P.text("endpoint"),controlEndpoint:P.text("control_endpoint"),containerEndpoint:P.text("container_endpoint"),publicWebBase:P.text("public_web_base"),labels:P.text("labels",{mode:"json"}).$type().notNull(),...CO}),FO=P.sqliteTable("cp_node_pairing_revocations",{id:P.text("id").primaryKey(),endpoint:P.text("endpoint").notNull(),nodeId:P.text("node_id").notNull(),keyId:P.text("key_id").notNull(),secretCiphertext:P.text("secret_ciphertext").notNull(),pairedAt:P.text("paired_at").notNull(),phase:P.text("phase").notNull().default("pending-compensation"),...CO},e=>[P.index("cp_node_pairing_revocations_node_idx").on(e.nodeId)]),HO=P.sqliteTable("cp_models",{id:P.text("id").primaryKey(),name:P.text("name").notNull(),endpoint:P.text("endpoint").notNull(),keyCiphertext:P.text("key_ciphertext").notNull(),model:P.text("model").notNull(),modelNames:P.text("model_names",{mode:"json"}).$type().notNull(),mappings:P.text("mappings",{mode:"json"}).$type().notNull(),protocols:P.text("protocols",{mode:"json"}).$type().notNull(),app:P.text("app").notNull(),enabled:P.integer("enabled",{mode:"boolean"}).notNull(),order:P.integer("display_order").notNull(),labels:P.text("labels",{mode:"json"}).$type().notNull(),...CO},e=>[P.index("cp_models_order_idx").on(e.order,e.name,e.id)]),GO=P.sqliteTable("cp_chat_bridges",{id:P.text("id").primaryKey(),channel:P.text("channel").notNull(),name:P.text("name").notNull(),enabled:P.integer("enabled",{mode:"boolean"}).notNull(),credentialCiphertext:P.text("credential_ciphertext"),credentialMetadata:P.text("credential_metadata",{mode:"json"}).$type().notNull().default({tokenSet:!1,clientSecretSet:!1,appSecretSet:!1}),defaultChatId:P.text("default_chat_id"),allowedUserIds:P.text("allowed_user_ids",{mode:"json"}).$type().notNull(),pollIntervalMs:P.integer("poll_interval_ms").notNull(),settings:P.text("settings",{mode:"json"}).$type().notNull(),...CO}),WO=P.sqliteTable("cp_chat_session_bindings",{id:P.text("id").primaryKey(),routeScope:P.text("route_scope").notNull(),channel:P.text("channel").notNull(),bridgeId:P.text("bridge_id").references(()=>GO.id,{onDelete:"cascade"}),chatSessionId:P.text("chat_session_id").notNull(),userId:P.text("user_id"),activeProjectId:P.text("active_project_id"),activeInstanceId:P.text("active_instance_id"),activeAiSessionId:P.text("active_ai_session_id"),lastUsedAt:P.text("last_used_at").notNull(),...CO},e=>[P.uniqueIndex("cp_chat_session_bindings_route_uq").on(e.channel,e.routeScope,e.chatSessionId),P.index("cp_chat_session_bindings_bridge_idx").on(e.bridgeId)]),VO=P.sqliteTable("cp_git_credentials",{id:P.text("id").primaryKey(),name:P.text("name").notNull(),kind:P.text("kind").notNull(),scope:P.text("scope",{mode:"json"}).notNull(),status:P.text("status").notNull(),revision:P.integer("revision").notNull(),secretCiphertext:P.text("secret_ciphertext").notNull(),...CO}),KO=P.sqliteTable("cp_git_credential_assignments",{id:P.text("id").primaryKey(),instanceId:P.text("instance_id").notNull(),credentialId:P.text("credential_id").notNull().references(()=>VO.id,{onDelete:"restrict"}),credentialRevision:P.integer("credential_revision").notNull(),assignmentRevision:P.integer("assignment_revision").notNull(),status:P.text("status").notNull(),authorizedAt:P.text("authorized_at").notNull(),...CO},e=>[P.uniqueIndex("cp_git_credential_assignments_identity_uq").on(e.instanceId,e.credentialId),P.index("cp_git_credential_assignments_credential_idx").on(e.credentialId,e.status)]),XO=P.sqliteTable("cp_git_provisioning_intents",{id:P.text("id").primaryKey(),instanceId:P.text("instance_id").notNull(),credentialId:P.text("credential_id").notNull().references(()=>VO.id,{onDelete:"restrict"}),operationId:P.text("operation_id").notNull(),inputDigest:P.text("input_digest").notNull(),remoteUrl:P.text("remote_url").notNull(),ref:P.text("ref",{mode:"json"}).notNull(),clone:P.text("clone",{mode:"json"}).notNull(),...CO},e=>[P.uniqueIndex("cp_git_provisioning_intents_operation_uq").on(e.instanceId,e.operationId),P.index("cp_git_provisioning_intents_credential_idx").on(e.credentialId)]),YO=P.sqliteTable("cp_git_audit",{id:P.text("id").primaryKey(),action:P.text("action").notNull(),credentialId:P.text("credential_id").notNull(),instanceId:P.text("instance_id"),credentialRevision:P.integer("credential_revision"),assignmentRevision:P.integer("assignment_revision"),...CO},e=>[P.index("cp_git_audit_created_idx").on(e.createdAt)]);class JO{tail=Promise.resolve();run(e){const t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}}function QO(e,t,n,i){return{list:async()=>(await e.select().from(t).orderBy(z.asc(t.id))).map(e=>Yk(n,e)),async get(i){const s=await e.select().from(t).where(z.eq(t.id,i)).limit(1);return s[0]?Yk(n,s[0]):void 0},put:async s=>i(async()=>{const i=Xk(n.parse(s)),a=Object.fromEntries(Object.entries(i).filter(([e])=>"id"!==e));return await e.insert(t).values(i).onConflictDoUpdate({target:t.id,set:a}),Yk(n,i)}),delete:async n=>i(async()=>{const i=await e.delete(t).where(z.eq(t.id,n));return Number(i.changes)>0})}}function ZO(e,t){const n=QO(e,OO,Kk.identities,t),i=async t=>{const n=await e.select().from(OO).where(t).limit(1);return n[0]?Yk(Kk.identities,n[0]):void 0};return{...n,findByLoginName:e=>i(z.eq(OO.normalizedLoginName,e)),findByProviderSubject:(e,t)=>i(z.and(z.eq(OO.providerId,e),z.eq(OO.subject,t))),listByUser:async t=>(await e.select().from(OO).where(z.eq(OO.userId,t))).map(e=>Yk(Kk.identities,e)),existsForProvider:async t=>(await e.select({id:OO.id}).from(OO).where(z.eq(OO.providerId,t)).limit(1)).length>0}}function ej(e){const t=new Map;for(const n of e){const e=n.grant.userId,i=t.get(e)||{grant:n.grant,roleIds:[]};i.roleIds.push(n.roleId),t.set(e,i)}return[...t.values()].map(({grant:e,roleIds:t})=>Kk.grants.parse({...e,roleIds:t.sort()}))}function tj(e,t,n,i){const s=t=>{const n=e.select({grant:PO,roleId:LO.roleId}).from(PO).innerJoin(LO,z.eq(PO.userId,LO.userId));return t?n.where(z.inArray(PO.userId,t)):n};return{list:async()=>ej(await s()),get:async e=>ej(await s([e]))[0],async listByRole(t){const n=(await e.select({userId:LO.userId}).from(LO).where(z.eq(LO.roleId,t))).map(e=>e.userId);return 0===n.length?[]:ej(await s(n))},put:n=>i?(async t=>{const n=Kk.grants.parse(t),{roleIds:i,...s}=n;return await e.insert(PO).values(s).onConflictDoUpdate({target:PO.userId,set:Object.fromEntries(Object.entries(s).filter(([e])=>"userId"!==e))}),await e.delete(LO).where(z.eq(LO.userId,n.userId)),await e.insert(LO).values(i.map(e=>({userId:n.userId,roleId:e}))),n})(n):t(e=>e.grants.put(n)),delete:async t=>n(async()=>{const n=await e.delete(PO).where(z.eq(PO.userId,t));return Number(n.changes)>0})}}function nj(e,t){const n=e=>e.map(e=>Yk(Kk.sessions,{...e.session,userId:e.userId})),i=()=>e.select({session:DO,userId:OO.userId}).from(DO).innerJoin(OO,z.eq(DO.identityId,OO.id));return{list:async()=>n(await i()),get:async e=>n(await i().where(z.eq(DO.id,e)).limit(1))[0],listByUser:async e=>n(await i().where(z.eq(OO.userId,e))),put:async n=>t(async()=>{const t=Kk.sessions.parse(n),i=await e.select({userId:OO.userId}).from(OO).where(z.eq(OO.id,t.identityId)).limit(1);if(i[0]?.userId!==t.userId)throw new Error("Session identity does not belong to the requested user.");const{userId:s,...a}=t;return await e.insert(DO).values(a).onConflictDoUpdate({target:DO.id,set:Object.fromEntries(Object.entries(a).filter(([e])=>"id"!==e))}),t}),delete:async n=>t(async()=>{const t=await e.delete(DO).where(z.eq(DO.id,n));return Number(t.changes)>0})}}function ij(e,t){return{...QO(e,UO,Kk.approvals,t),async findActivePending(t,n,i){const s=await e.select().from(UO).where(z.and(z.eq(UO.providerId,t),z.eq(UO.subject,n),z.eq(UO.status,"pending"),z.gt(UO.expiresAt,i))).limit(1);return s[0]?Yk(Kk.approvals,s[0]):void 0},hasActivePendingForProvider:async(t,n)=>(await e.select({id:UO.id}).from(UO).where(z.and(z.eq(UO.providerId,t),z.eq(UO.status,"pending"),z.gt(UO.expiresAt,n))).limit(1)).length>0}}function sj(e,t){return{...QO(e,KO,iT.gitAssignments,t),putIfRevision:(n,i)=>t(async()=>{const t=iT.gitAssignments.parse(n);if(void 0===i){const n=await e.insert(KO).values(t).onConflictDoNothing();return Number(n.changes)>0}const{id:s,...a}=t,o=await e.update(KO).set(a).where(z.and(z.eq(KO.id,t.id),z.eq(KO.assignmentRevision,i)));return Number(o.changes)>0})}}function aj(e,t){return{...QO(e,XO,iT.gitProvisioningIntents,t),insert:n=>t(async()=>{const t=iT.gitProvisioningIntents.parse(n),i=await e.insert(XO).values(t).onConflictDoNothing();return Number(i.changes)>0})}}function oj(e,t){const n=QO(e,YO,iT.gitAudit,t);return{list:n.list,get:n.get,append:n=>t(async()=>{const t=iT.gitAudit.parse(n);await e.insert(YO).values(t)})}}function rj(e,t,n,i=!1,s=new JO){let a;const o=e=>i?e():s.run(e),r=async t=>i?t(a):o(async()=>{n.exec("BEGIN IMMEDIATE");try{const i=await t(rj(e,async()=>{},n,!0,s));return n.exec("COMMIT"),i}catch(e){throw n.exec("ROLLBACK"),e}});return a={dialect:"sqlite",users:QO(e,kO,Kk.users,o),identities:ZO(e,o),roles:QO(e,jO,Kk.roles,o),grants:tj(e,r,o,i),sessions:nj(e,o),providers:QO(e,MO,Kk.providers,o),approvals:ij(e,o),audit:QO(e,qO,Kk.audit,o),nodes:QO(e,BO,iT.nodes,o),pairingRevocations:QO(e,FO,iT.pairingRevocations,o),models:QO(e,HO,iT.models,o),chatBridges:QO(e,GO,iT.chatBridges,o),chatSessions:QO(e,WO,iT.chatSessions,o),gitCredentials:QO(e,VO,iT.gitCredentials,o),gitAssignments:sj(e,o),gitProvisioningIntents:aj(e,o),gitAudit:oj(e,o),async metadata(){const t=await e.select().from(RO).where(z.eq(RO.key,"user_store")).limit(1);return t[0]?.value||{schemaVersion:1}},async putMetadata(t){await o(()=>e.insert(RO).values({key:"user_store",value:t}).onConflictDoUpdate({target:RO.key,set:{value:t}}))},migration:async t=>(await e.select().from($O).where(z.eq($O.id,t)).limit(1))[0],async putMigration(t){t=Dk.parse(t),await o(()=>e.insert($O).values(t).onConflictDoUpdate({target:$O.id,set:{checksum:t.checksum,appliedAt:t.appliedAt,details:t.details}}))},transaction:r,close:t},a}var cj=Object.freeze({__proto__:null,createSqliteUserRepository:async function(e){try{n.mkdirSync(t.dirname(e),{recursive:!0,mode:448}),n.chmodSync(t.dirname(e),448);const i=new k.DatabaseSync(e);n.chmodSync(e,384);try{!function(e){e.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;"),e.exec("CREATE TABLE IF NOT EXISTS cp_migration_ledger (\n id TEXT PRIMARY KEY NOT NULL, checksum TEXT NOT NULL, applied_at TEXT NOT NULL, details TEXT NOT NULL\n )"),e.exec("BEGIN IMMEDIATE");try{const t=e.prepare("SELECT checksum FROM cp_migration_ledger WHERE id = ?"),n=e.prepare("INSERT INTO cp_migration_ledger (id, checksum, applied_at, details) VALUES (?, ?, ?, ?)");for(const i of Uk){const s=t.get(i.id);if(s){if(s.checksum!==i.checksum)throw new Error(`Migration checksum mismatch for ${i.id}.`)}else e.exec(i.sql),n.run(i.id,i.checksum,(new Date).toISOString(),JSON.stringify({dialect:"sqlite"}))}e.exec("COMMIT")}catch(t){throw e.exec("ROLLBACK"),t}}(i)}catch(e){throw i.close(),Mk("sqlite","migrate",e)}for(const t of[`${e}-wal`,`${e}-shm`])n.existsSync(t)&&n.chmodSync(t,384);return rj(O.drizzle({client:i}),async()=>i.close(),i)}catch(e){if("CONTROL_PLANE_DATABASE_MIGRATE_FAILED"===e.code)throw e;throw Mk("sqlite","connect",e)}}});
|
package/package.json
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@task-handoff/control-plane",
|
|
3
|
-
"version": "0.0.41-alpha.
|
|
3
|
+
"version": "0.0.41-alpha.7",
|
|
4
4
|
"description": "Prebuilt TaskHandoff control plane runtime.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "git+https://github.com/edgestorage/task-handoff.git"
|
|
8
8
|
},
|
|
9
9
|
"license": "Apache-2.0",
|
|
10
|
+
"homepage": "https://docs.thandoff.com",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/edgestorage/task-handoff/issues"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"task-handoff",
|
|
16
|
+
"control-plane",
|
|
17
|
+
"server",
|
|
18
|
+
"web-ui",
|
|
19
|
+
"ai-agents",
|
|
20
|
+
"agent-orchestration"
|
|
21
|
+
],
|
|
10
22
|
"type": "commonjs",
|
|
11
23
|
"bin": {
|
|
12
24
|
"task-handoff-control-plane": "bin/task-handoff-control-plane"
|