@agimon-ai/po-session 0.0.0-alpha.13 → 0.0.0-alpha.131

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.
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":["rootSession","apiRoute"],"sources":["../../src/services/peerInbox/index.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/services/peerInboxApi/index.ts","../../src/extensions/(backend)/api/session-peer/route.server.ts","../../generated/server.ts"],"sourcesContent":["import type { PoSessionDeliveryInboxState } from '../sessionDelivery';\n\nexport type SessionPeerInbox = (\n sourceKey: string,\n type: string,\n payload: unknown,\n) => Promise<PoSessionDeliveryInboxState | undefined> | undefined;\n\nconst inboxes = new Map<string, SessionPeerInbox>();\n\n/**\n * Registers one live session-owned peer inbox. This registry is reachable only by the Session route.\n * The newest registration wins: a Durable Object evicted without disposal leaves its entry in the\n * isolate's module state, and the restarted session must replace it. The hub still rejects two live\n * sessions with one id, and an older unregister cannot remove a newer inbox.\n */\nexport function registerSessionPeerInbox(sessionId: string, inbox: SessionPeerInbox): () => void {\n inboxes.set(sessionId, inbox);\n return () => {\n if (inboxes.get(sessionId) === inbox) inboxes.delete(sessionId);\n };\n}\n\nexport async function deliverSessionPeerEnvelope(\n targetSessionId: string,\n sourceKey: string,\n type: string,\n payload: unknown,\n): Promise<PoSessionDeliveryInboxState | undefined> {\n return inboxes.get(targetSessionId)?.(sourceKey, type, payload);\n}\n","import path from 'node:path';\n\nimport { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport { poHomeDirectory } from '@agimon-ai/po-core/piSettings';\nimport { BACKGROUND_CONTEXT, requirePoFs, requirePoSqlite } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverFacet';\n\nimport { provideBackgroundWorkService } from '../../../../services/backgroundWorkService';\nimport { registerSessionPeerInbox } from '../../../../services/peerInbox';\nimport {\n createPeerCommunication,\n ensurePrivateDirectory,\n parseRemoteSessionReference,\n peerSessionReference,\n readSessionPeerConfigAsync,\n} from '../../../../services/peerTransport';\nimport { provideSessionDeliveryService } from '../../../../services/sessionDelivery';\nimport { createSessionDirectory } from '../../../../services/sessionDirectory';\nimport { createSessionGroupStore } from '../../../../services/sessionGroups';\nimport {\n PO_SESSION_INTERCOM_SERVICE,\n createSessionGroupDeliveryAuthorizer,\n createSessionIntercom,\n} from '../../../../services/sessionIntercom';\n\nexport default defineRoot((pluginContext: PoServerPluginContext) => ({\n value: undefined,\n services: [\n provideBackgroundWorkService,\n async (context) => {\n const agent = pluginContext.agent;\n const session = agent?.context.session;\n const communication = pluginContext.host.context.sessionCommunication;\n const homeDirectory = pluginContext.host.context.homeDirectory;\n const sessionService = pluginContext.host.context.sessionService;\n if (!agent || !session?.admitPrompt || !communication || !homeDirectory || !sessionService?.canCommunicate) {\n throw new Error(\n 'Session delivery requires the headless agent, authenticated session communication, host home directory, and communication policy.',\n );\n }\n const fs = requirePoFs(pluginContext.context);\n const sqlite = requirePoSqlite(pluginContext.context);\n const io = BACKGROUND_CONTEXT;\n const sessionDirectory = path.join(poHomeDirectory(homeDirectory), 'session');\n const deliveryDirectory = path.join(sessionDirectory, 'delivery');\n await ensurePrivateDirectory(fs, deliveryDirectory, io);\n const peerConfig = await readSessionPeerConfigAsync(fs, homeDirectory, io);\n const peerCommunication = createPeerCommunication({ local: communication, config: peerConfig });\n const remotePeerIsGranted = (peerKey: string): boolean => {\n const peer = parseRemoteSessionReference(peerKey);\n return (\n peer !== undefined &&\n peerConfig?.peers.some(\n (candidate) =>\n candidate.hostId === peer.hostId && candidate.allowedSessionIds.includes(agent.context.sessionId),\n ) === true\n );\n };\n const fallbackAuthorization = (peerKey: string): boolean =>\n sessionService.canCommunicate?.(agent.context.sessionId, peerKey) === true || remotePeerIsGranted(peerKey);\n const groups = peerConfig\n ? await createSessionGroupStore({\n database: await sqlite.open(path.join(sessionDirectory, 'groups.sqlite'), io),\n })\n : undefined;\n const localHostId = peerConfig?.hostId;\n const selfReference = localHostId ? peerSessionReference(localHostId, agent.context.sessionId) : undefined;\n const groupAuthorization =\n groups && selfReference && localHostId\n ? createSessionGroupDeliveryAuthorizer({\n selfReference,\n groups,\n peerReference: (peerKey) =>\n parseRemoteSessionReference(peerKey) === undefined\n ? peerSessionReference(localHostId, peerKey)\n : peerKey,\n fallback: fallbackAuthorization,\n })\n : undefined;\n let delivery: Awaited<ReturnType<typeof provideSessionDeliveryService>>;\n try {\n delivery = await provideSessionDeliveryService(context, {\n database: await sqlite.open(path.join(deliveryDirectory, `${agent.context.sessionId}.sqlite`), io),\n recipientKey: agent.context.sessionId,\n communication: peerCommunication,\n authorizePeer: (peerKey, metadata) =>\n groupAuthorization ? groupAuthorization(peerKey, metadata) : fallbackAuthorization(peerKey),\n admitPrompt: (prompt, admission, requestId) => session.admitPrompt!(prompt, admission, undefined, requestId),\n });\n } catch (error) {\n await groups?.close();\n throw error;\n }\n const { service, close: closeDelivery } = delivery;\n const unprovide: (() => void)[] = [];\n if (groups && selfReference && peerConfig) {\n const directory = createSessionDirectory({\n authorizeDiscovery: async (caller, subject) => {\n const reference = peerSessionReference(subject.hostId, subject.sessionId);\n const permitted = (await groups.groupsFor(caller)).some((group) => group.members.includes(reference));\n return permitted ? { capabilities: ['message'] } : undefined;\n },\n });\n for (const peer of peerConfig.peers)\n for (const sessionId of peer.allowedSessionIds)\n directory.observe({\n hostId: peer.hostId,\n sessionId,\n hostIncarnation: 'unknown',\n sessionIncarnation: 'unknown',\n sequence: 0,\n observedAt: 0,\n staleAfterMs: 0,\n deliveryTarget: peerSessionReference(peer.hostId, sessionId),\n reachability: 'unknown',\n runtime: 'unknown',\n activity: 'unknown',\n voice: { eligible: 'unknown', readiness: 'unknown' },\n });\n unprovide.push(\n context.provide(\n PO_SESSION_INTERCOM_SERVICE,\n createSessionIntercom({ selfReference, directory, groups, delivery: service }),\n ),\n );\n }\n const unregister = registerSessionPeerInbox(agent.context.sessionId, (sourceKey, kind, payload) =>\n service.receive?.(sourceKey, kind, payload),\n );\n return async () => {\n unregister();\n for (const release of unprovide.reverse()) release();\n await closeDelivery();\n await groups?.close();\n };\n },\n ],\n}));\n","import path from 'node:path';\n\nimport type { PoApi, PoApiHandler } from '@agimon-ai/po-core/packageApi';\nimport { BACKGROUND_CONTEXT, type PoSqliteService, type FileSystem } from '@agimon-ai/po-core/platform';\n\nimport { deliverSessionPeerEnvelope } from '../peerInbox';\nimport {\n PEER_REPLAY_DATABASE_FILE,\n createPeerReplayGuardAsync,\n ensurePrivateDirectory,\n parseSessionPeerEnvelope,\n peerSessionReference,\n readSessionPeerConfigAsync,\n sessionPeerConfigPath,\n verifyPeerRequest,\n type SessionPeerConfig,\n type SessionPeerReplayGuardAsync,\n} from '../peerTransport';\n\nconst MAX_BODY_BYTES = 64 * 1024;\nconst DELIVERY_TYPES = new Set(['po/session-delivery/envelope', 'po/session-delivery/ack']);\n\nfunction response(status: number, error: string): Response {\n return Response.json({ error }, { status });\n}\n\ninterface PeerInboxState {\n readonly config: SessionPeerConfig | undefined;\n readonly replay: SessionPeerReplayGuardAsync | undefined;\n}\n\n/** Narrow HMAC-authenticated endpoint that a trusted tunnel may forward without device authentication. */\nexport function createPeerInboxApi(platform: { readonly fs: FileSystem; readonly sqlite: PoSqliteService }): PoApi {\n return {\n basePath: 'session-peer',\n start(context): PoApiHandler {\n const homeDirectory = context.homeDirectory;\n // Opened once on first use: the handler starts synchronously, the platform services are async.\n let opened: Promise<PeerInboxState> | undefined;\n const open = (): Promise<PeerInboxState> =>\n (opened ??= (async () => {\n if (homeDirectory === undefined) return { config: undefined, replay: undefined };\n const config = await readSessionPeerConfigAsync(platform.fs, homeDirectory, BACKGROUND_CONTEXT);\n const file = path.join(path.dirname(sessionPeerConfigPath(homeDirectory)), PEER_REPLAY_DATABASE_FILE);\n await ensurePrivateDirectory(platform.fs, path.dirname(file), BACKGROUND_CONTEXT);\n const replay = await createPeerReplayGuardAsync(await platform.sqlite.open(file, BACKGROUND_CONTEXT));\n return { config, replay };\n })().catch((error: unknown) => {\n // A failed open is retried by the next request rather than cached.\n opened = undefined;\n throw error;\n }));\n return {\n async fetch(request) {\n if (request.method !== 'POST' || new URL(request.url).pathname !== '/inbox')\n return response(404, 'Not found.');\n const { config, replay } = await open();\n if (!config) return response(503, 'Paired Session delivery is not configured.');\n const length = request.headers.get('content-length');\n if (length !== null && (!/^\\d+$/u.test(length) || Number(length) > MAX_BODY_BYTES))\n return response(413, 'Request body is too large.');\n const body = await request.text();\n if (Buffer.byteLength(body) > MAX_BODY_BYTES) return response(413, 'Request body is too large.');\n const peer = verifyPeerRequest(config, request, body);\n if (!peer) return response(401, 'Paired Session request is unauthorized.');\n if (!(await replay?.admit(request))) return response(409, 'Paired Session request was already received.');\n let parsed: unknown;\n try {\n parsed = JSON.parse(body) as unknown;\n } catch {\n return response(400, 'Paired Session request is malformed.');\n }\n const envelope = parseSessionPeerEnvelope(parsed);\n if (!envelope || !DELIVERY_TYPES.has(envelope.type))\n return response(400, 'Paired Session envelope is invalid.');\n if (!peer.allowedSessionIds.includes(envelope.targetSessionId))\n return response(403, 'Peer is not granted this session.');\n const state = await deliverSessionPeerEnvelope(\n envelope.targetSessionId,\n peerSessionReference(peer.hostId, envelope.sourceSessionId),\n envelope.type,\n envelope.payload,\n );\n return state === undefined\n ? response(404, 'Target Session is unavailable.')\n : Response.json({ accepted: true, state }, { status: 202 });\n },\n async close() {\n const state = await opened?.catch(() => undefined);\n await state?.replay?.close();\n },\n };\n },\n };\n}\n","import { defineRoute } from '@agimon-ai/po-core/extensionFile';\nimport { requirePoFs, requirePoSqlite } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverFacet';\n\nimport { createPeerInboxApi } from '../../../../services/peerInboxApi';\n\nexport default defineRoute(({ context }: PoServerPluginContext) =>\n createPeerInboxApi({ fs: requirePoFs(context), sqlite: requirePoSqlite(context) }),\n);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverFacet';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';\nimport { composeRootHooks } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport apiRoute from '../src/extensions/(backend)/api/session-peer/route.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\n\nexport const facet = defineServerPlugin({\n name: '@agimon-ai/po-session',\n providerOverrides: composeServerProviderOverrides(rootSession),\n global: (context) => ({\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, context)]; },\n }),\n workspace: (context) => ({\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, context)]; },\n }),\n session: async (context) => {\n const scopeSession = await rootSession(context);\n return {\n ...composeRootHooks(scopeSession),\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, context)]; },\n services: [...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default facet;\n"],"mappings":";;;;;;;AAQA,MAAM,0BAAU,IAAI,IAA8B;;;;;;;AAQlD,SAAgB,yBAAyB,WAAmB,OAAqC;CAC/F,QAAQ,IAAI,WAAW,KAAK;CAC5B,aAAa;EACX,IAAI,QAAQ,IAAI,SAAS,MAAM,OAAO,QAAQ,OAAO,SAAS;CAChE;AACF;AAEA,eAAsB,2BACpB,iBACA,WACA,MACA,SACkD;CAClD,OAAO,QAAQ,IAAI,eAAe,CAAC,GAAG,WAAW,MAAM,OAAO;AAChE;;;ACLA,IAAA,sBAAe,YAAY,mBAA0C;CACnE,OAAO,KAAA;CACP,UAAU,CACR,8BACA,OAAO,YAAY;EACjB,MAAM,QAAQ,cAAc;EAC5B,MAAM,UAAU,OAAO,QAAQ;EAC/B,MAAM,gBAAgB,cAAc,KAAK,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ACCA,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AAEpE,MAAa,QAAQ,mBAAmB;CACtC,MAAM;CACN,mBAAmB,+BAA+BA,mBAAW;CAC7D,SAAS,aAAa,EACpB,IAAI,MAAoC;EAAE,OAAO,CAAC,GAAGC,sBAAU,OAAO,CAAC;CAAG,EAC5E;CACA,YAAY,aAAa,EACvB,IAAI,MAAoC;EAAE,OAAO,CAAC,GAAGA,sBAAU,OAAO,CAAC;CAAG,EAC5E;CACA,SAAS,OAAO,YAAY;EAC1B,MAAM,eAAe,MAAMD,oBAAY,OAAO;EAC9C,OAAO;GACL,GAAG,iBAAiB,YAAY;GAChC,IAAI,MAAoC;IAAE,OAAO,CAAC,GAAGC,sBAAU,OAAO,CAAC;GAAG;GAC1E,UAAU,CAAC,GAAI,aAAa,YAAY,CAAC,CAAE;GAC3C,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EACvG;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"server.mjs","names":["rootGlobal","rootSession","apiRoute","resourceCodemodeHowToSession"],"sources":["../../src/extensions/(backend)/root.server.ts","../../src/services/peerInbox/index.ts","../../src/services/sessionsNamespace/nodeOperations.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/services/peerInboxApi/index.ts","../../src/extensions/(backend)/api/session-peer/route.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-session.server.ts","../../generated/server.ts"],"sourcesContent":["import path from 'node:path';\n\nimport { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport { poHomeDirectory } from '@agimon-ai/po-core/piSettings';\nimport {\n PO_FS_SERVICE,\n PO_SQLITE_SERVICE,\n requirePoFs,\n requirePoSqlite,\n BACKGROUND_CONTEXT,\n} from '@agimon-ai/po-core/platform';\nimport {\n PO_SERVER_SCOPE_SERVICE,\n requirePoServerScope,\n type PoServerPluginContext,\n} from '@agimon-ai/po-core/serverPlugin';\n\nimport { ensurePrivateDirectory } from '../../services/peerTransport';\nimport { authenticatedPeerPost } from '../../services/sealedPeerChannel';\nimport {\n createSessionGroupBridge,\n PO_SESSION_GROUP_BRIDGE_CONTRACT,\n PO_SESSION_GROUP_BRIDGE_SERVICE,\n} from '../../services/sessionGroupBridge';\nimport { createSessionGroupStore } from '../../services/sessionGroups';\nimport { createSessionPeers, PO_SESSION_PEERS_CONTRACT, PO_SESSION_PEERS_SERVICE } from '../../services/sessionPeers';\n\nexport default defineRoot((plugin: PoServerPluginContext) => ({\n value: undefined,\n services: [\n async (context) => {\n // Routes require these bindings as soon as the service plugin finishes loading.\n await context.inject([PO_FS_SERVICE, PO_SQLITE_SERVICE, PO_SERVER_SCOPE_SERVICE], async (scoped) => {\n const homeDirectory = plugin.host.context.homeDirectory;\n if (!homeDirectory) throw new Error('Host links require an explicit host home directory.');\n const peers = await createSessionPeers({ fs: requirePoFs(scoped), homeDirectory });\n await peers.identity();\n const directory = path.join(poHomeDirectory(homeDirectory), 'session');\n await ensurePrivateDirectory(requirePoFs(scoped), directory, BACKGROUND_CONTEXT);\n const database = await requirePoSqlite(scoped).open(path.join(directory, 'groups.sqlite'), BACKGROUND_CONTEXT);\n const groups = await createSessionGroupStore({ database });\n // Snapshots are rebuilt from live sessions and fresh authenticated adverts after a restart.\n await database.run(\n \"DELETE FROM session_group_members WHERE group_id IN (SELECT group_id FROM session_groups WHERE owner_authority = 'session-group-bridge')\",\n );\n await database.run(\"DELETE FROM session_groups WHERE owner_authority = 'session-group-bridge'\");\n const bridge = createSessionGroupBridge({\n groups,\n peers,\n onError: (error) => plugin.host.context.onNotice(`Group bridge failed: ${String(error)}`),\n send: async (hostId, advert) => {\n const config = peers.current();\n const peer = config?.peers.find((entry) => entry.hostId === hostId);\n if (!config || !peer) return;\n await authenticatedPeerPost({\n config,\n peer,\n path: '/api/plugins/session-peer/control',\n value: { type: 'groups', groups: advert },\n });\n },\n });\n const scope = requirePoServerScope(scoped);\n const releasePeers =\n plugin.host.scope === 'global'\n ? await scope.provide(PO_SESSION_PEERS_CONTRACT, peers)\n : scoped.provide(PO_SESSION_PEERS_SERVICE, peers);\n let releaseBridge: () => void | Promise<void>;\n try {\n releaseBridge =\n plugin.host.scope === 'global'\n ? await scope.provide(PO_SESSION_GROUP_BRIDGE_CONTRACT, bridge)\n : scoped.provide(PO_SESSION_GROUP_BRIDGE_SERVICE, bridge);\n } catch (error) {\n await Promise.resolve(releasePeers());\n await bridge.close();\n throw error;\n }\n return async () => {\n await releaseBridge();\n await Promise.resolve(releasePeers());\n await bridge.close();\n };\n });\n },\n ],\n}));\n","import type { PoSessionDeliveryInboxState } from '../sessionDelivery';\n\nexport type SessionPeerInbox = (\n sourceKey: string,\n type: string,\n payload: unknown,\n) => Promise<PoSessionDeliveryInboxState | undefined> | undefined;\n\nconst inboxes = new Map<string, SessionPeerInbox>();\n\n/**\n * Registers one live session-owned peer inbox. This registry is reachable only by the Session route.\n * The newest registration wins: a Durable Object evicted without disposal leaves its entry in the\n * isolate's module state, and the restarted session must replace it. The hub still rejects two live\n * sessions with one id, and an older unregister cannot remove a newer inbox.\n */\nexport function registerSessionPeerInbox(sessionId: string, inbox: SessionPeerInbox): () => void {\n inboxes.set(sessionId, inbox);\n return () => {\n if (inboxes.get(sessionId) === inbox) inboxes.delete(sessionId);\n };\n}\n\nexport async function deliverSessionPeerEnvelope(\n targetSessionId: string,\n sourceKey: string,\n type: string,\n payload: unknown,\n): Promise<PoSessionDeliveryInboxState | undefined> {\n return inboxes.get(targetSessionId)?.(sourceKey, type, payload);\n}\n","import type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { readPoSessionDelivery } from '../sessionDelivery';\nimport { readSessionGroupBridge } from '../sessionGroupBridge';\nimport type { SessionOperations } from './type';\n\n/** Reuses the same authorized peers and durable delivery as Team's peer messaging. */\nexport function createNodeSessionOperations(\n host: PoServerPluginContext['host'],\n context: Context,\n sessionId: string,\n): SessionOperations {\n const peers = () => [\n ...(host.context.sessionCommunication?.listPeers?.() ?? []),\n ...(readSessionGroupBridge(context)?.peersFor(sessionId) ?? []),\n ];\n return {\n async list(signal) {\n signal.throwIfAborted();\n return peers();\n },\n async send(to, text, signal) {\n signal.throwIfAborted();\n const current = peers();\n const exact = current.find((peer) => peer.sessionId === to);\n const matching = current.filter((peer) => peer.name === to);\n if (!exact && matching.length > 1) throw new Error('Ambiguous session name. Use its session ID.');\n const recipient = exact?.sessionId ?? matching[0]?.sessionId ?? to;\n const remote = recipient.startsWith('peer/');\n const metadata = remote ? readSessionGroupBridge(context)?.metadataFor(sessionId, recipient) : undefined;\n if (remote ? !metadata : host.context.sessionService?.canCommunicate?.(sessionId, recipient) !== true)\n throw new Error('Session is outside your communication scope.');\n const delivery = readPoSessionDelivery(context);\n if (!delivery) throw new Error('Session delivery is unavailable.');\n const sender = host.context.sessionCommunication?.sessionName?.trim() || sessionId;\n const receipt = await delivery.deliver({\n deliveryId: `sessions:${sessionId}:${crypto.randomUUID()}`,\n recipientKey: recipient,\n kind: 'session-message',\n prompt: `Message from session ${sender}.\\n\\n${text}`,\n delivery: 'steer',\n metadata,\n });\n return { ...receipt, to: recipient, sender };\n },\n };\n}\n","import path from 'node:path';\n\nimport { PO_CODEMODE_SERVICE, readPoCodemode } from '@agimon-ai/po-core/codemode';\nimport { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport { COORDINATOR_SESSION_PROVENANCE, PO_SESSION_ATTENTION_EVENT } from '@agimon-ai/po-core/hubChannel';\nimport { poHomeDirectory } from '@agimon-ai/po-core/piSettings';\nimport {\n BACKGROUND_CONTEXT,\n PO_FS_SERVICE,\n PO_SQLITE_SERVICE,\n requirePoFs,\n requirePoSqlite,\n} from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { provideBackgroundWorkService } from '../../../../services/backgroundWorkService';\nimport { createStartSessionTool, START_SESSION_TOOL_NAME } from '../../../../services/coordinatorSessions';\nimport { registerSessionPeerInbox } from '../../../../services/peerInbox';\nimport {\n createPeerCommunication,\n ensurePrivateDirectory,\n parseRemoteSessionReference,\n peerSessionReference,\n} from '../../../../services/peerTransport';\nimport { provideSessionDeliveryService } from '../../../../services/sessionDelivery';\nimport { createSessionDirectory } from '../../../../services/sessionDirectory';\nimport {\n PO_SESSION_GROUP_BRIDGE_SERVICE,\n readSessionGroupBridge,\n namedSessionGroupId,\n} from '../../../../services/sessionGroupBridge';\nimport {\n PO_SESSION_INTERCOM_SERVICE,\n createSessionGroupDeliveryAuthorizer,\n createSessionIntercom,\n} from '../../../../services/sessionIntercom';\nimport { PO_SESSION_PEERS_SERVICE, requireSessionPeers } from '../../../../services/sessionPeers';\nimport { createSessionsNamespace, readSessionOperations } from '../../../../services/sessionsNamespace';\nimport { createNodeSessionOperations } from '../../../../services/sessionsNamespace/nodeOperations';\n\nexport default defineRoot((pluginContext: PoServerPluginContext) => ({\n value: undefined,\n services: [\n provideBackgroundWorkService,\n (owner) => {\n const agent = pluginContext.agent;\n if (!agent) return;\n const options = {\n sessionId: agent.context.sessionId,\n provenance: () => pluginContext.host.context.sessionContext?.provenance,\n coordination: () => pluginContext.host.context.coordination,\n operations:\n readSessionOperations(owner) ??\n createNodeSessionOperations(pluginContext.host, owner, agent.context.sessionId),\n assertAvailable: () => pluginContext.signal.throwIfAborted(),\n };\n const tool = agent.registerTool(createStartSessionTool(options));\n const eligibility =\n options.provenance() === COORDINATOR_SESSION_PROVENANCE\n ? undefined\n : agent.registerToolRestriction({ excludedTools: [START_SESSION_TOOL_NAME] });\n const injection = owner.inject([PO_CODEMODE_SERVICE], (context) => {\n const registration = readPoCodemode(context)?.register(\n '@agimon-ai/po-session',\n createSessionsNamespace(options),\n );\n const restriction = registration\n ? agent.registerToolRestriction({\n excludedTools: [\n START_SESSION_TOOL_NAME,\n ...(options.operations.fallbackToolName ? [options.operations.fallbackToolName] : []),\n ],\n })\n : undefined;\n return () => {\n restriction?.dispose();\n registration?.dispose();\n };\n });\n return async () => {\n await injection.dispose();\n eligibility?.dispose();\n tool.dispose();\n };\n },\n (owner) => {\n owner.inject(\n [PO_SESSION_PEERS_SERVICE, PO_SESSION_GROUP_BRIDGE_SERVICE, PO_FS_SERVICE, PO_SQLITE_SERVICE],\n async (context) => {\n const agent = pluginContext.agent;\n const session = agent?.context.session;\n const communication = pluginContext.host.context.sessionCommunication;\n const homeDirectory = pluginContext.host.context.homeDirectory;\n const sessionService = pluginContext.host.context.sessionService;\n if (!agent || !session?.admitPrompt || !communication || !homeDirectory || !sessionService?.canCommunicate) {\n throw new Error(\n 'Session delivery requires the headless agent, authenticated session communication, host home directory, and communication policy.',\n );\n }\n const fs = requirePoFs(context);\n const sqlite = requirePoSqlite(context);\n const io = BACKGROUND_CONTEXT;\n const sessionDirectory = path.join(poHomeDirectory(homeDirectory), 'session');\n const deliveryDirectory = path.join(sessionDirectory, 'delivery');\n await ensurePrivateDirectory(fs, deliveryDirectory, io);\n const peers = requireSessionPeers(context);\n const peerConfig = peers.current();\n const peerCommunication = createPeerCommunication({\n local: communication,\n config: () => peers.current(),\n canPublish: (target, type, payload) => {\n if (type === 'po/session-delivery/ack') return true;\n const metadata = (payload as { metadata?: { groupId?: string } } | null)?.metadata;\n return (\n bridge\n ?.peersFor(agent.context.sessionId)\n .some(\n (peer) =>\n peer.sessionId === target &&\n peer.sharedGroups.some((name) => namedSessionGroupId(name) === metadata?.groupId),\n ) === true\n );\n },\n onError: (error) => pluginContext.host.context.onNotice(`Peer delivery failed: ${String(error)}`),\n });\n const remotePeerIsGranted = (peerKey: string): boolean => {\n const peer = parseRemoteSessionReference(peerKey);\n return (\n peer !== undefined &&\n peers\n .current()\n ?.peers.some(\n (candidate) =>\n candidate.hostId === peer.hostId && candidate.allowedSessionIds.includes(agent.context.sessionId),\n ) === true\n );\n };\n const fallbackAuthorization = (peerKey: string): boolean =>\n sessionService.canCommunicate?.(agent.context.sessionId, peerKey) === true || remotePeerIsGranted(peerKey);\n const bridge = readSessionGroupBridge(context);\n const groups = bridge?.groups;\n await bridge?.updateLocal(\n agent.context.sessionId,\n communication.sessionName ?? agent.context.sessionId,\n communication.groups ?? [],\n );\n const localHostId = peerConfig?.hostId;\n const selfReference = localHostId ? peerSessionReference(localHostId, agent.context.sessionId) : undefined;\n const groupAuthorization =\n groups && selfReference && localHostId\n ? createSessionGroupDeliveryAuthorizer({\n selfReference,\n groups,\n peerReference: (peerKey) =>\n parseRemoteSessionReference(peerKey) === undefined\n ? peerSessionReference(localHostId, peerKey)\n : peerKey,\n fallback: fallbackAuthorization,\n })\n : undefined;\n let delivery: Awaited<ReturnType<typeof provideSessionDeliveryService>>;\n try {\n delivery = await provideSessionDeliveryService(context, {\n database: await sqlite.open(path.join(deliveryDirectory, `${agent.context.sessionId}.sqlite`), io),\n recipientKey: agent.context.sessionId,\n communication: peerCommunication,\n authorizePeer: (peerKey, metadata) => {\n const remote = parseRemoteSessionReference(peerKey);\n if (remote && !peers.current()?.peers.some((peer) => peer.hostId === remote.hostId)) return false;\n if (remote) {\n // Local membership is authoritative even before the SQLite mirror update finishes.\n const expected = bridge?.metadataFor(agent.context.sessionId, peerKey);\n if (\n !expected ||\n !metadata?.groupId ||\n !bridge\n ?.peersFor(agent.context.sessionId)\n .find((peer) => peer.sessionId === peerKey)\n ?.sharedGroups.some((name) => namedSessionGroupId(name) === metadata.groupId)\n )\n return false;\n return groupAuthorization ? groupAuthorization(peerKey, metadata) : false;\n }\n return groupAuthorization ? groupAuthorization(peerKey, metadata) : fallbackAuthorization(peerKey);\n },\n admitPrompt: async (prompt, admission, requestId, metadata) => {\n if (!metadata.customType) {\n await session.admitPrompt!(prompt, admission, undefined, requestId);\n return;\n }\n if (!session.admitMessage) throw new Error('The session cannot admit a custom delivery.');\n await session.admitMessage(\n {\n type: metadata.customType,\n text: prompt,\n display: true,\n details: metadata.customDetails === undefined ? undefined : JSON.parse(metadata.customDetails),\n },\n admission === 'steer' ? 'steer' : 'followUp',\n requestId,\n );\n },\n });\n } catch (error) {\n await bridge?.removeLocal(agent.context.sessionId);\n throw error;\n }\n const { service, close: closeDelivery } = delivery;\n const unprovide: (() => void)[] = [];\n if (groups && selfReference && peerConfig) {\n const directory = createSessionDirectory({\n authorizeDiscovery: (_caller, subject) => {\n const reference = peerSessionReference(subject.hostId, subject.sessionId);\n return bridge?.peersFor(agent.context.sessionId).some((peer) => peer.sessionId === reference)\n ? { capabilities: ['message'] }\n : undefined;\n },\n });\n const observedHosts = new Set<string>();\n let sequence = 0;\n const observeRemote = (): void => {\n const remotePeers = bridge?.peersFor(agent.context.sessionId) ?? [];\n for (const peer of remotePeers) observedHosts.add(parseRemoteSessionReference(peer.sessionId)!.hostId);\n sequence += 1;\n for (const hostId of observedHosts)\n directory.replaceHostSnapshot(\n hostId,\n 'linked',\n remotePeers.flatMap((peer) => {\n const remote = parseRemoteSessionReference(peer.sessionId)!;\n return remote.hostId !== hostId\n ? []\n : [\n {\n hostId,\n sessionId: remote.sessionId,\n label: peer.name,\n hostIncarnation: 'linked',\n sessionIncarnation: 'live',\n sequence,\n observedAt: Date.now(),\n staleAfterMs: 120_000,\n deliveryTarget: peer.sessionId,\n reachability: 'unknown' as const,\n runtime: 'unknown' as const,\n activity: 'unknown' as const,\n voice: { eligible: 'unknown' as const, readiness: 'unknown' as const },\n },\n ];\n }),\n );\n };\n observeRemote();\n unprovide.push(\n bridge!.subscribe(() => {\n observeRemote();\n void service\n .reauthorize?.()\n .catch((error: unknown) =>\n pluginContext.host.context.onNotice(`Delivery reauthorization failed: ${String(error)}`),\n );\n }),\n );\n unprovide.push(\n context.provide(\n PO_SESSION_INTERCOM_SERVICE,\n createSessionIntercom({ selfReference, directory, groups, delivery: service }),\n ),\n );\n }\n const releaseGroups = pluginContext.host.context.directEvents?.subscribe(\n PO_SESSION_ATTENTION_EVENT,\n agent.context.sessionId,\n () => {\n void bridge\n ?.updateLocal(\n agent.context.sessionId,\n communication.sessionName ?? agent.context.sessionId,\n communication.groups ?? [],\n )\n .catch((error: unknown) =>\n pluginContext.host.context.onNotice(`Group update failed: ${String(error)}`),\n );\n },\n );\n const unregister = registerSessionPeerInbox(agent.context.sessionId, (sourceKey, kind, payload) =>\n service.receive?.(sourceKey, kind, payload),\n );\n return async () => {\n unregister();\n releaseGroups?.();\n await bridge?.removeLocal(agent.context.sessionId);\n for (const release of unprovide.reverse()) release();\n await closeDelivery();\n };\n },\n );\n },\n ],\n}));\n","import path from 'node:path';\n\nimport { poApiCallerFrom, type PoApi, type PoApiHandler } from '@agimon-ai/po-core/packageApi';\nimport { BACKGROUND_CONTEXT, type PoSqliteService, type FileSystem } from '@agimon-ai/po-core/platform';\n\nimport { deliverSessionPeerEnvelope } from '../peerInbox';\nimport { createPeerLink, type PeerLinkControl } from '../peerLink';\nimport type { RosterPeerLinks } from '../peerLink/type';\nimport {\n PEER_REPLAY_DATABASE_FILE,\n createPeerReplayGuardAsync,\n ensurePrivateDirectory,\n parseSessionPeerEnvelope,\n peerSessionReference,\n peerRequestHeaders,\n readSessionPeerConfigAsync,\n sessionPeerConfigPath,\n verifyPeerRequest,\n type SessionPeerConfig,\n type SessionPeerReplayGuardAsync,\n} from '../peerTransport';\nimport { createSealedPeerChannels } from '../sealedPeerChannel';\nimport type { SessionGroupBridge } from '../sessionGroupBridge';\nimport type { SessionPeers } from '../sessionPeers';\n\nconst MAX_BODY_BYTES = 64 * 1024;\nconst DELIVERY_TYPES = new Set(['po/session-delivery/envelope', 'po/session-delivery/ack']);\n\nfunction response(status: number, error: string): Response {\n return Response.json({ error }, { status });\n}\n\ninterface PeerInboxState {\n readonly config: SessionPeerConfig | undefined;\n readonly replay: SessionPeerReplayGuardAsync | undefined;\n}\n\n/** Narrow HMAC-authenticated endpoint that a trusted tunnel may forward without device authentication. */\nexport function createPeerInboxApi(platform: {\n readonly fs: FileSystem;\n readonly sqlite: PoSqliteService;\n readonly peers?: SessionPeers;\n readonly network?: RosterPeerLinks;\n readonly groups?: () => SessionGroupBridge | undefined;\n readonly origin?: () => string | undefined;\n readonly fetch?: typeof fetch;\n}): PoApi {\n return {\n basePath: 'session-peer',\n start(context): PoApiHandler {\n const homeDirectory = context.homeDirectory;\n // Opened once on first use: the handler starts synchronously, the platform services are async.\n let opened: Promise<PeerInboxState> | undefined;\n const channels = createSealedPeerChannels();\n let link: PeerLinkControl | undefined;\n let announcing = false;\n const announce = (): void => {\n if (!link || announcing) return;\n announcing = true;\n void link\n .announce()\n .catch((error: unknown) => context.onNotice(`Peer URL announcement failed: ${String(error)}`))\n .finally(() => {\n announcing = false;\n });\n };\n // Retry announcements as well as detecting origin revisions. A peer may be offline at rotation.\n const timer =\n platform.peers && platform.origin\n ? setInterval(() => {\n void open()\n .then(announce)\n .catch((error: unknown) => context.onNotice(`Host links could not start: ${String(error)}`));\n }, 1_000)\n : undefined;\n timer?.unref?.();\n const open = (): Promise<PeerInboxState> =>\n (opened ??= (async () => {\n if (homeDirectory === undefined) return { config: undefined, replay: undefined };\n const config = platform.peers\n ? platform.peers.current()\n : await readSessionPeerConfigAsync(platform.fs, homeDirectory, BACKGROUND_CONTEXT);\n const file = path.join(path.dirname(sessionPeerConfigPath(homeDirectory)), PEER_REPLAY_DATABASE_FILE);\n await ensurePrivateDirectory(platform.fs, path.dirname(file), BACKGROUND_CONTEXT);\n const replay = await createPeerReplayGuardAsync(await platform.sqlite.open(file, BACKGROUND_CONTEXT));\n if (platform.peers)\n link = createPeerLink({\n peers: platform.peers,\n network: platform.network,\n groups: platform.groups,\n replay,\n channels,\n origin: platform.origin ?? (() => undefined),\n fetch: platform.fetch,\n });\n announce();\n return { config, replay };\n })().catch((error: unknown) => {\n // A failed open is retried by the next request rather than cached.\n opened = undefined;\n throw error;\n }));\n if (platform.peers)\n void open().catch((error: unknown) => context.onNotice(`Host links could not start: ${String(error)}`));\n return {\n async fetch(request) {\n const pathname = new URL(request.url).pathname;\n const openedState = await open();\n const config = platform.peers ? platform.peers.current() : openedState.config;\n const replay = openedState.replay;\n if (request.method === 'GET' && pathname === '/links' && platform.peers) {\n if (!poApiCallerFrom(request.headers)) return response(403, 'An authenticated caller is required.');\n return Response.json({\n hostId: config?.hostId,\n peers: config?.peers.map(({ hostId, url, urlGeneration }) => ({ hostId, url, urlGeneration })) ?? [],\n });\n }\n if (\n request.method !== 'POST' ||\n !['/inbox', '/control', '/link/prepare', '/link/accept', '/link/unlink', '/link/hint'].includes(pathname)\n )\n return response(404, 'Not found.');\n const length = request.headers.get('content-length');\n if (length !== null && (!/^\\d+$/u.test(length) || Number(length) > MAX_BODY_BYTES))\n return response(413, 'Request body is too large.');\n const body = await request.text();\n if (Buffer.byteLength(body) > MAX_BODY_BYTES) return response(413, 'Request body is too large.');\n if (pathname.startsWith('/link/')) {\n const caller = poApiCallerFrom(request.headers);\n if (!caller || (caller.locality === 'remote' && pathname !== '/link/hint' && caller.stepUp !== 'verified'))\n return response(403, 'Linking hosts needs a fresh peer.link step-up.');\n if (!link) return response(503, 'Host links are unavailable.');\n try {\n const input = (body === '' ? {} : JSON.parse(body)) as {\n invite?: unknown;\n hostId?: unknown;\n url?: unknown;\n };\n if (pathname === '/link/prepare') return Response.json(await link.prepare());\n if (pathname === '/link/accept') {\n await link.accept(input.invite as Parameters<PeerLinkControl['accept']>[0]);\n return Response.json({ linked: true });\n }\n if (typeof input.hostId !== 'string') return response(400, 'A host identity is required.');\n if (pathname === '/link/unlink') {\n await link.unlink(input.hostId);\n return Response.json({ unlinked: true });\n }\n if (typeof input.url !== 'string') return response(400, 'A URL hint is required.');\n return Response.json({ rebound: await link.hint(input.hostId, input.url) });\n } catch (error) {\n return response(400, error instanceof Error ? error.message : 'Host link failed.');\n }\n }\n if (pathname === '/control') {\n if (!link) return response(503, 'Host links are unavailable.');\n try {\n return await link.control(request, body);\n } catch (error) {\n return response(400, error instanceof Error ? error.message : 'Invalid peer control.');\n }\n }\n if (!config) return response(503, 'Paired Session delivery is not configured.');\n const peer = verifyPeerRequest(config, request, body);\n if (!peer) return response(401, 'Paired Session request is unauthorized.');\n if (!(await replay?.admit(request))) return response(409, 'Paired Session request was already received.');\n let parsed: unknown;\n try {\n parsed = JSON.parse(body) as unknown;\n } catch {\n return response(400, 'Paired Session request is malformed.');\n }\n let peerChannel: ReturnType<typeof channels.take>;\n if (peer.linkGeneration) {\n const sealed = parsed as { epochId?: unknown; envelope?: unknown } | null;\n peerChannel = typeof sealed?.epochId === 'string' ? channels.take(peer, sealed.epochId) : undefined;\n const opened = peerChannel?.open(sealed?.envelope);\n if (!opened?.ok) return response(401, 'A fresh sealed peer channel is required.');\n try {\n parsed = JSON.parse(Buffer.from(opened.plaintext).toString('utf8')) as unknown;\n } catch {\n return response(400, 'Invalid sealed peer envelope.');\n }\n }\n const envelope = parseSessionPeerEnvelope(parsed);\n if (!envelope || !DELIVERY_TYPES.has(envelope.type))\n return response(400, 'Paired Session envelope is invalid.');\n if (!peer.linkGeneration && !peer.allowedSessionIds.includes(envelope.targetSessionId))\n return response(403, 'Peer is not granted this session.');\n const state = await deliverSessionPeerEnvelope(\n envelope.targetSessionId,\n peerSessionReference(peer.hostId, envelope.sourceSessionId),\n envelope.type,\n envelope.payload,\n );\n if (state !== undefined && peerChannel) {\n const sealed = peerChannel.seal(Buffer.from(JSON.stringify({ accepted: true, state })));\n if (!sealed.ok) return response(503, 'Peer acknowledgement could not be sealed.');\n const text = JSON.stringify(sealed.envelope);\n return new Response(text, { headers: peerRequestHeaders(config.hostId, peer, 'RESPONSE', '/inbox', text) });\n }\n return state === undefined\n ? response(404, 'Target Session is unavailable.')\n : Response.json({ accepted: true, state }, { status: 202 });\n },\n async close() {\n if (timer) clearInterval(timer);\n const state = await opened?.catch(() => undefined);\n link?.close();\n await state?.replay?.close();\n },\n };\n },\n };\n}\n","import { defineRoute } from '@agimon-ai/po-core/extensionFile';\nimport { requirePoFs, requirePoSqlite } from '@agimon-ai/po-core/platform';\nimport { PO_REMOTE_ORIGIN_SERVICE, type RemoteOrigin } from '@agimon-ai/po-core/remoteOrigin';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport { createPeerInboxApi } from '../../../../services/peerInboxApi';\nimport { PO_ROSTER_PEER_SERVICE, type RosterPeerLinks } from '../../../../services/peerLink/type';\nimport { readSessionGroupBridge } from '../../../../services/sessionGroupBridge';\nimport { requireSessionPeers } from '../../../../services/sessionPeers';\n\nexport default defineRoute(({ context }: PoServerPluginContext) => {\n let origin: RemoteOrigin | undefined;\n let network: RosterPeerLinks | undefined;\n context.inject([PO_ROSTER_PEER_SERVICE], (scoped) => {\n network = scoped.get(PO_ROSTER_PEER_SERVICE);\n return () => {\n network = undefined;\n };\n });\n context.inject([PO_REMOTE_ORIGIN_SERVICE], (scoped) => {\n origin = scoped.get(PO_REMOTE_ORIGIN_SERVICE);\n return () => {\n origin = undefined;\n };\n });\n // Hosts without public routing have nothing to announce and must not keep a polling timer alive.\n const hasOrigin = origin !== undefined;\n return createPeerInboxApi({\n fs: requirePoFs(context),\n sqlite: requirePoSqlite(context),\n peers: requireSessionPeers(context),\n network,\n groups: () => readSessionGroupBridge(context),\n ...(hasOrigin ? { origin: () => origin?.current() } : {}),\n });\n});\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'codemode-how-to-session',\n description:\n 'List related sessions, send guidance, and start briefed independent work as a coordinator through the sessions namespace. No stop or delete capability.',\n kind: 'skill' as const,\n pinned: true,\n path: packageResourcePath(import.meta.url, 'src/prompts/codemode-how-to-session/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/codemode-how-to-session/SKILL.md'),\n});\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootGlobal from '../src/extensions/(backend)/root.server';\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport apiRoute from '../src/extensions/(backend)/api/session-peer/route.server';\nimport resourceCodemodeHowToSession from '../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-session.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\n/* v8 ignore next -- generated normalization branch */\nconst defined = <T>(values: readonly (T | undefined)[]): T[] =>\n values.filter((value): value is T => value !== undefined);\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-session',\n providerOverrides: composeServerProviderOverrides(rootGlobal, rootSession),\n injects: composeRootInjects({ global: [rootGlobal], workspace: [rootGlobal], session: [rootGlobal, rootSession] }),\n global: async (context) => {\n const scopeGlobal = await context.scopeRoot('global', rootGlobal, context);\n const contextGlobal = { ...context, root: scopeGlobal.value };\n return {\n ...composeRootHooks(scopeGlobal),\n get api(): PoServerSessionPlugin['api'] { return [at(apiRoute, contextGlobal)]; },\n services: [...(scopeGlobal.services ?? [])],\n };\n },\n workspace: async (context) => {\n const scopeGlobal = await context.scopeRoot('global', rootGlobal, context);\n const contextGlobal = { ...context, root: scopeGlobal.value };\n return {\n ...composeRootHooks(scopeGlobal),\n get api(): PoServerSessionPlugin['api'] { return defined([context.hosted('global') ? undefined : at(apiRoute, contextGlobal)]); },\n services: [...(scopeGlobal.services ?? [])],\n };\n },\n session: async (context) => {\n const scopeGlobal = await context.scopeRoot('global', rootGlobal, context);\n const contextGlobal = { ...context, root: scopeGlobal.value };\n const scopeSession = await context.scopeRoot('session', rootSession, contextGlobal);\n const contextSession = { ...contextGlobal, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeGlobal, scopeSession),\n get api(): PoServerSessionPlugin['api'] { return defined([context.hosted('global') ? undefined : at(apiRoute, contextGlobal)]); },\n get resources(): PoServerSessionPlugin['resources'] { return [at(resourceCodemodeHowToSession, contextSession)]; },\n services: [...(scopeGlobal.services ?? []), ...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeGlobal.activities ?? []), ...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;;AA2BA,IAAA,wBAAe,YAAY,YAAmC;CAC5D,OAAO,KAAA;CACP,UAAU,CACR,OAAO,YAAY;EAEjB,MAAM,QAAQ,OAAO;GAAC;GAAe;GAAmB;EAAuB,GAAG,OAAO,WAAW;GAClG,MAAM,gBAAgB,OAAO,KAAK,QAAQ;GAC1C,IAAI,CAAC,eAAe,MAAM,IAAI,MAAM,qDAAqD;GACzF,MAAM,QAAQ,MAAM,mBAAmB;IAAE,IAAI,YAAY,MAAM;IAAG;GAAc,CAAC;GACjF,MAAM,MAAM,SAAS;GACrB,MAAM,YAAY,KAAK,KAAK,gBAAgB,aAAa,GAAG,SAAS;GACrE,MAAM,uBAAuB,YAAY,MAAM,GAAG,WAAW,kBAAkB;GAC/E,MAAM,WAAW,MAAM,gBAAgB,MAAM,CAAC,CAAC,KAAK,KAAK,KAAK,WAAW,eAAe,GAAG,kBAAkB;GAC7G,MAAM,SAAS,MAAM,wBAAwB,EAAE,SAAS,CAAC;GAEzD,MAAM,SAAS,IACb,0IACF;GACA,MAAM,SAAS,IAAI,2EAA2E;GAC9F,MAAM,SAAS,yBAAyB;IACtC;IACA;IACA,UAAU,UAAU,OAAO,KAAK,QAAQ,SAAS,wBAAwB,OAAO,KAAK,GAAG;IACxF,MAAM,OAAO,QAAQ,WAAW;KAC9B,MAAM,SAAS,MAAM,QAAQ;KAC7B,MAAM,OAAO,QAAQ,MAAM,MAAM,UAAU,MAAM,WAAW,MAAM;KAClE,IAAI,CAAC,UAAU,CAAC,MAAM;KACtB,MAAM,sBAAsB;MAC1B;MACA;MACA,MAAM;MACN,OAAO;OAAE,MAAM;OAAU,QAAQ;MAAO;KAC1C,CA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;EAC1B,MAAM,cAAc,MAAM,QAAQ,UAAU,UAAUF,uBAAY,OAAO;EACzE,MAAM,gBAAgB;GAAE,GAAG;GAAS,MAAM,YAAY;EAAM;EAC5D,MAAM,eAAe,MAAM,QAAQ,UAAU,WAAWC,qBAAa,aAAa;EAClF,MAAM,iBAAiB;GAAE,GAAG;GAAe,MAAM,aAAa;EAAM;EACpE,OAAO;GACL,GAAG,iBAAiB,aAAa,YAAY;GAC7C,IAAI,MAAoC;IAAE,OAAO,QAAQ,CAAC,QAAQ,OAAO,QAAQ,IAAI,KAAA,IAAY,GAAGC,sBAAU,aAAa,CAAC,CAAC;GAAG;GAChI,IAAI,YAAgD;IAAE,OAAO,CAAC,GAAGC,wCAA8B,cAAc,CAAC;GAAG;GACjH,UAAU,CAAC,GAAI,YAAY,YAAY,CAAC,GAAI,GAAI,aAAa,YAAY,CAAC,CAAE;GAC5E,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,YAAY,cAAc,CAAC,GAAI,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EAC1I;CACF;AACF,CAAC"}
package/dist/index.cjs CHANGED
@@ -1,26 +1,405 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_sessionDelivery = require("./sessionDelivery-CGWuQyLV.cjs");
3
- exports.PO_SESSION_DELIVERY_SERVICE = require_sessionDelivery.PO_SESSION_DELIVERY_SERVICE;
4
- exports.PO_SESSION_INTERCOM_SERVICE = require_sessionDelivery.PO_SESSION_INTERCOM_SERVICE;
5
- exports.SessionGroupRevisionError = require_sessionDelivery.SessionGroupRevisionError;
6
- exports.createBackgroundWorkService = require_sessionDelivery.createBackgroundWorkService;
7
- exports.createPeerCommunication = require_sessionDelivery.createPeerCommunication;
8
- exports.createPeerReplayGuard = require_sessionDelivery.createPeerReplayGuard;
9
- exports.createPeerReplayGuardAsync = require_sessionDelivery.createPeerReplayGuardAsync;
10
- exports.createSessionDeliveryService = require_sessionDelivery.createSessionDeliveryService;
11
- exports.createSessionDirectory = require_sessionDelivery.createSessionDirectory;
12
- exports.createSessionGroupDeliveryAuthorizer = require_sessionDelivery.createSessionGroupDeliveryAuthorizer;
13
- exports.createSessionGroupStore = require_sessionDelivery.createSessionGroupStore;
14
- exports.createSessionIntercom = require_sessionDelivery.createSessionIntercom;
15
- exports.parseRemoteSessionReference = require_sessionDelivery.parseRemoteSessionReference;
16
- exports.peerRequestHeaders = require_sessionDelivery.peerRequestHeaders;
17
- exports.peerSessionReference = require_sessionDelivery.peerSessionReference;
18
- exports.provideBackgroundWorkService = require_sessionDelivery.provideBackgroundWorkService;
19
- exports.provideSessionDeliveryService = require_sessionDelivery.provideSessionDeliveryService;
20
- exports.readPoSessionDelivery = require_sessionDelivery.readPoSessionDelivery;
21
- exports.readSessionIntercom = require_sessionDelivery.readSessionIntercom;
22
- exports.readSessionPeerConfig = require_sessionDelivery.readSessionPeerConfig;
23
- exports.readSessionPeerConfigAsync = require_sessionDelivery.readSessionPeerConfigAsync;
24
- exports.requireSessionIntercom = require_sessionDelivery.requireSessionIntercom;
25
- exports.sessionPeerConfigPath = require_sessionDelivery.sessionPeerConfigPath;
26
- exports.verifyPeerRequest = require_sessionDelivery.verifyPeerRequest;
2
+ const require_type = require("./type-Bzv_vxKC.cjs");
3
+ let _agimon_ai_po_core_hubChannel = require("@agimon-ai/po-core/hubChannel");
4
+ let _agimon_ai_po_web_security_nodeSealedChannel = require("@agimon-ai/po-web-security/nodeSealedChannel");
5
+ let _agimon_ai_po_web_security_deviceProof = require("@agimon-ai/po-web-security/deviceProof");
6
+ //#region src/services/sessionCoordination/policy.ts
7
+ /** ponytail: a fixed per-coordinator budget; add configuration only when another number is needed. */
8
+ const COORDINATOR_STARTS_PER_HOUR = 5;
9
+ const COORDINATOR_START_WINDOW_MS = 36e5;
10
+ function assertCoordinatorStartBudget(count) {
11
+ if (count >= 5) throw new Error(`A coordinator can start at most 5 sessions an hour.`);
12
+ }
13
+ function assertCoordinatorStartScope(callerWorkspaceId, homeWorkspaceId, workspace, hasCoordinator) {
14
+ if (workspace === void 0 || workspace.available === false || workspace.sandbox !== void 0) throw new Error("The target workspace is unavailable.");
15
+ if (workspace.id === callerWorkspaceId) return;
16
+ if (callerWorkspaceId === void 0 || callerWorkspaceId !== homeWorkspaceId || workspace.kind === "session") throw new Error("Only the home coordinator can target another workspace.");
17
+ if (hasCoordinator) throw new Error("This workspace has a coordinator. Ask it to start the session.");
18
+ }
19
+ /** Communication is symmetric. A message grant never grants lifecycle authority. */
20
+ const canSessionsCommunicate = (input) => {
21
+ const { source, target } = input;
22
+ if (source.id === target.id) return false;
23
+ if (source.parentSessionId === target.id || target.parentSessionId === source.id) return true;
24
+ if (source.sessionProvenance === _agimon_ai_po_core_hubChannel.REMOTE_CONVERSATION_SESSION_PROVENANCE || target.sessionProvenance === _agimon_ai_po_core_hubChannel.REMOTE_CONVERSATION_SESSION_PROVENANCE) return false;
25
+ const coordinates = (session) => session.sessionProvenance === _agimon_ai_po_core_hubChannel.COORDINATOR_SESSION_PROVENANCE;
26
+ const home = (session) => coordinates(session) && session.workspaceId !== void 0 && input.workspaces.some((workspace) => workspace.id === session.workspaceId && workspace.kind === "session");
27
+ const homeFallback = (coordinator, peer) => {
28
+ if (!home(coordinator) || peer.workspaceId === void 0) return false;
29
+ const workspace = input.workspaces.find((entry) => entry.id === peer.workspaceId);
30
+ if (!workspace || workspace.kind === "session" || workspace.sandbox !== void 0 || workspace.available === false) return false;
31
+ return !input.sessions.some((session) => session.workspaceId === workspace.id && coordinates(session)) && !input.dormantSessions.some((record) => record.workspaceId === workspace.id && record.sessionProvenance === _agimon_ai_po_core_hubChannel.COORDINATOR_SESSION_PROVENANCE && !input.sessions.some((session) => session.id === record.sessionId));
32
+ };
33
+ if ((coordinates(source) || coordinates(target)) && source.workspaceId !== void 0 && source.workspaceId === target.workspaceId) return true;
34
+ if (coordinates(source) && coordinates(target) && (home(source) || home(target))) return true;
35
+ if (homeFallback(source, target) || homeFallback(target, source)) return true;
36
+ if (source.workspaceId !== void 0 && source.workspaceId === target.workspaceId && input.filesOverlap) return true;
37
+ return (source.groups ?? []).some((group) => target.groups?.includes(group) === true);
38
+ };
39
+ //#endregion
40
+ //#region src/services/sessionCoordination/index.ts
41
+ const FALLBACK_SLUG = "workspace";
42
+ /** Kebab-case from the workspace name, else its folder name. */
43
+ function workspaceSlug(workspace) {
44
+ return (workspace.name?.trim() || workspace.root.split(/[\\/]/u).filter(Boolean).pop() || "").toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "") || FALLBACK_SLUG;
45
+ }
46
+ function createCoordinatorService(options) {
47
+ const opening = /* @__PURE__ */ new Map();
48
+ const starts = /* @__PURE__ */ new Map();
49
+ const now = () => options.now?.() ?? Date.now();
50
+ const homeWorkspace = () => options.workspaces().find((workspace) => workspace.kind === "session");
51
+ /** Live sessions first, so a live coordinator's record is never mistaken for a dormant one. Oldest wins. */
52
+ const coordinatorsIn = (workspaceId) => {
53
+ const liveSessions = options.liveSessions();
54
+ const live = liveSessions.filter((session) => session.sessionProvenance === _agimon_ai_po_core_hubChannel.COORDINATOR_SESSION_PROVENANCE && session.workspaceId === workspaceId).map((session) => ({
55
+ sessionId: session.id,
56
+ createdAt: session.createdAt,
57
+ live: true
58
+ }));
59
+ const dormant = options.records().filter((record) => record.sessionProvenance === _agimon_ai_po_core_hubChannel.COORDINATOR_SESSION_PROVENANCE && record.workspaceId === workspaceId && !liveSessions.some((session) => session.id === record.sessionId)).map((record) => ({
60
+ sessionId: record.sessionId,
61
+ createdAt: record.createdAt,
62
+ live: false
63
+ }));
64
+ return [...live, ...dormant].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
65
+ };
66
+ const oldestCoordinator = (workspaceId) => {
67
+ const found = coordinatorsIn(workspaceId);
68
+ if (found.length > 1) options.notice(`Workspace '${workspaceId}' has ${found.length} coordinators; using the oldest, '${found[0]?.sessionId}'.`);
69
+ return found[0];
70
+ };
71
+ const open = async (target, settings) => {
72
+ const workspace = target === "home" ? homeWorkspace() : options.workspaces().find((entry) => entry.id === target);
73
+ if (target !== "home") {
74
+ if (workspace === void 0) throw new Error(`Workspace '${target}' not found.`);
75
+ if (workspace.kind === "session") throw new Error("The home workspace takes the home coordinator.");
76
+ if (!coordinated(workspace)) throw new Error("This workspace cannot have a coordinator.");
77
+ }
78
+ if (workspace?.sandbox !== void 0) throw new Error("This workspace cannot have a coordinator.");
79
+ const existing = workspace === void 0 ? void 0 : oldestCoordinator(workspace.id);
80
+ if (existing !== void 0) {
81
+ if (!existing.live) {
82
+ const record = options.records().find((entry) => entry.sessionId === existing.sessionId);
83
+ if (record === void 0) throw new Error("The coordinator record disappeared while reviving it.");
84
+ await options.revive(record);
85
+ }
86
+ return {
87
+ sessionId: existing.sessionId,
88
+ created: false
89
+ };
90
+ }
91
+ const request = {
92
+ name: settings.name,
93
+ sessionProvenance: _agimon_ai_po_core_hubChannel.COORDINATOR_SESSION_PROVENANCE,
94
+ selection: { profile: settings.profile },
95
+ ...settings.model === void 0 ? {} : { model: settings.model }
96
+ };
97
+ const { sessionId } = workspace === void 0 || target === "home" ? await options.createGeneral(request) : await options.createInWorkspace(workspace, request);
98
+ const record = options.records().find((entry) => entry.sessionId === sessionId);
99
+ const coordinator = {
100
+ profile: settings.profile,
101
+ name: settings.name,
102
+ ...settings.model === void 0 ? {} : { model: settings.model }
103
+ };
104
+ if (record === void 0 || !options.saveRecord({
105
+ ...record,
106
+ coordinator
107
+ })) options.notice(`Coordinator '${sessionId}' persona could not be recorded.`);
108
+ return {
109
+ sessionId,
110
+ created: true
111
+ };
112
+ };
113
+ const ensureCoordinator = (target, settings) => {
114
+ const pending = opening.get(target);
115
+ if (pending !== void 0) return pending;
116
+ const run = open(target, settings).finally(() => opening.delete(target));
117
+ opening.set(target, run);
118
+ return run;
119
+ };
120
+ const workspaceSettings = (workspace, home) => ({
121
+ profile: home.profile,
122
+ name: `${home.name}-${workspaceSlug(workspace)}`,
123
+ ...home.model === void 0 ? {} : { model: home.model }
124
+ });
125
+ const coordinated = (workspace) => workspace.kind !== "session" && workspace.available !== false && workspace.sandbox === void 0;
126
+ const homePersona = () => {
127
+ const general = homeWorkspace();
128
+ const home = general === void 0 ? void 0 : oldestCoordinator(general.id);
129
+ return home === void 0 ? void 0 : options.records().find((record) => record.sessionId === home.sessionId)?.coordinator;
130
+ };
131
+ const recordPersona = (sessionId, coordinator) => {
132
+ const record = options.records().find((entry) => entry.sessionId === sessionId);
133
+ if (record === void 0) return;
134
+ const { coordinator: _dropped, ...rest } = record;
135
+ if (!options.saveRecord(coordinator === void 0 ? rest : {
136
+ ...rest,
137
+ coordinator
138
+ })) options.notice(`Coordinator '${sessionId}' persona could not be recorded.`);
139
+ };
140
+ const demote = async (sessionId) => {
141
+ if (options.liveSessions().some((session) => session.id === sessionId)) await options.reopen(sessionId, {});
142
+ else {
143
+ const record = options.records().find((entry) => entry.sessionId === sessionId);
144
+ if (record === void 0) return;
145
+ const { sessionProvenance: _dropped, ...rest } = record;
146
+ if (!options.saveRecord(rest)) throw new Error(`Session '${sessionId}' could not be made regular.`);
147
+ }
148
+ recordPersona(sessionId, void 0);
149
+ };
150
+ const ensureHome = async (settings) => {
151
+ const home = await ensureCoordinator("home", settings);
152
+ const outcomes = await Promise.allSettled(options.workspaces().filter(coordinated).map((workspace) => ensureCoordinator(workspace.id, workspaceSettings(workspace, settings))));
153
+ for (const outcome of outcomes) if (outcome.status === "rejected") options.notice(`A workspace coordinator could not be opened: ${String(outcome.reason)}`);
154
+ return home;
155
+ };
156
+ return {
157
+ ensureCoordinator,
158
+ ensureHome,
159
+ async workspaceAdmitted(workspaceId) {
160
+ const workspace = options.workspaces().find((entry) => entry.id === workspaceId);
161
+ const general = homeWorkspace();
162
+ if (workspace === void 0 || general === void 0 || !coordinated(workspace)) return;
163
+ const home = oldestCoordinator(general.id);
164
+ if (home === void 0) return;
165
+ const persona = options.records().find((record) => record.sessionId === home.sessionId)?.coordinator;
166
+ if (persona === void 0) {
167
+ options.notice(`Home coordinator '${home.sessionId}' has no recorded persona; workspace '${workspaceId}' gets none.`);
168
+ return;
169
+ }
170
+ await ensureCoordinator(workspaceId, workspaceSettings(workspace, persona));
171
+ },
172
+ async startSession(coordinatorSessionId, request) {
173
+ const caller = options.liveSessions().find((session) => session.id === coordinatorSessionId);
174
+ if (caller?.sessionProvenance !== _agimon_ai_po_core_hubChannel.COORDINATOR_SESSION_PROVENANCE) throw new Error("Only a coordinator can start sessions.");
175
+ const name = request.name.trim();
176
+ const brief = request.brief.trim();
177
+ if (name === "" || brief === "") throw new Error("A started session needs a name and a brief.");
178
+ if (request.workspaceId !== void 0 && (typeof request.workspaceId !== "string" || request.workspaceId.trim() === "")) throw new Error("A target workspace ID must be non-empty text.");
179
+ const workspace = options.workspaces().find((entry) => entry.id === (request.workspaceId ?? caller.workspaceId));
180
+ assertCoordinatorStartScope(caller.workspaceId, homeWorkspace()?.id, workspace, workspace !== void 0 && oldestCoordinator(workspace.id) !== void 0);
181
+ const at = now();
182
+ const recent = (starts.get(coordinatorSessionId) ?? []).filter((time) => at - time < COORDINATOR_START_WINDOW_MS);
183
+ assertCoordinatorStartBudget(recent.length);
184
+ starts.set(coordinatorSessionId, [...recent, at]);
185
+ const { sessionId } = workspace.kind === "session" ? await options.createGeneral({ name }) : await options.createInWorkspace(workspace, { name });
186
+ try {
187
+ await options.prompt(sessionId, brief);
188
+ } catch (error) {
189
+ return {
190
+ sessionId,
191
+ promptError: error instanceof Error ? error.message : String(error)
192
+ };
193
+ }
194
+ return { sessionId };
195
+ },
196
+ async add(workspaceId, profile) {
197
+ if (profile !== void 0 && (typeof profile !== "string" || profile.trim() === "")) throw new Error("A coordinator profile must be non-empty text.");
198
+ const workspace = workspaceId === void 0 ? homeWorkspace() : options.workspaces().find((entry) => entry.id === workspaceId);
199
+ if (workspaceId !== void 0) {
200
+ if (workspace === void 0) throw new Error(`Workspace '${workspaceId}' not found.`);
201
+ if (!coordinated(workspace)) throw new Error("This workspace cannot have a coordinator.");
202
+ }
203
+ const existing = workspace === void 0 ? void 0 : oldestCoordinator(workspace.id);
204
+ const inherited = homePersona();
205
+ const selected = profile?.trim() ?? inherited?.profile ?? options.defaultProfile(workspaceId === void 0 ? void 0 : workspace?.root);
206
+ if (selected === void 0 && existing === void 0) return {
207
+ profileRequired: true,
208
+ error: "Choose a profile before adding a coordinator."
209
+ };
210
+ if (selected === void 0 && existing !== void 0) {
211
+ if (!existing.live) {
212
+ const record = options.records().find((entry) => entry.sessionId === existing.sessionId);
213
+ if (record === void 0) throw new Error("The coordinator record disappeared while reviving it.");
214
+ await options.revive(record);
215
+ }
216
+ return {
217
+ sessionId: existing.sessionId,
218
+ created: false
219
+ };
220
+ }
221
+ const settings = profile !== void 0 ? {
222
+ profile: selected,
223
+ name: selected
224
+ } : inherited ?? {
225
+ profile: selected ?? "",
226
+ name: selected ?? ""
227
+ };
228
+ if (profile !== void 0 && existing === void 0) await options.validateProfile?.(selected, workspaceId === void 0 ? void 0 : workspace);
229
+ return workspaceId === void 0 ? ensureHome(settings) : ensureCoordinator(workspaceId, workspaceSettings(workspace, settings));
230
+ },
231
+ async setRole(sessionId, coordinator) {
232
+ let live = options.liveSessions().find((session) => session.id === sessionId);
233
+ const record = options.records().find((entry) => entry.sessionId === sessionId);
234
+ const current = live ?? (record === void 0 ? void 0 : {
235
+ ...record,
236
+ id: record.sessionId
237
+ });
238
+ if (current?.workspaceId === void 0) throw new Error("Session not found.");
239
+ if (current.sessionProvenance === _agimon_ai_po_core_hubChannel.COORDINATOR_SESSION_PROVENANCE === coordinator) return;
240
+ if (!coordinator) return demote(sessionId);
241
+ if (current.parentSessionId !== void 0) throw new Error("A nested session cannot become a coordinator.");
242
+ if (current.sessionProvenance !== void 0) throw new Error(`A ${current.sessionProvenance} session cannot become a coordinator.`);
243
+ const workspace = options.workspaces().find((entry) => entry.id === current.workspaceId);
244
+ if (workspace === void 0 || workspace.sandbox !== void 0 || workspace.kind !== "session" && !coordinated(workspace)) throw new Error("This workspace cannot have a coordinator.");
245
+ for (const other of coordinatorsIn(workspace.id)) await demote(other.sessionId);
246
+ if (live === void 0) {
247
+ await options.revive(record);
248
+ live = options.liveSessions().find((session) => session.id === sessionId);
249
+ }
250
+ const profile = live?.profile?.name ?? options.defaultProfile(workspace.root);
251
+ await options.reopen(sessionId, {
252
+ sessionProvenance: _agimon_ai_po_core_hubChannel.COORDINATOR_SESSION_PROVENANCE,
253
+ ...live?.profile === void 0 && profile !== void 0 ? { profile } : {}
254
+ });
255
+ if (profile !== void 0) recordPersona(sessionId, {
256
+ profile,
257
+ name: current.name ?? profile
258
+ });
259
+ else options.notice(`Coordinator '${sessionId}' has no profile; new workspaces will not copy its persona.`);
260
+ }
261
+ };
262
+ }
263
+ //#endregion
264
+ //#region src/services/peerLink/roster.ts
265
+ const LINK_TTL = 6e4;
266
+ /** Account links are separate from legacy session-peer secrets and permissions.
267
+ * A fresh signed ephemeral exchange uses the host key in the verified C6 roster.
268
+ * Coordinator availability is irrelevant. Roster removal or rotation fences all
269
+ * existing channel uses; applications must sync and persist C6 before exposing it.
270
+ */
271
+ function createRosterPeerLink(ports) {
272
+ const consumed = /* @__PURE__ */ new Map();
273
+ function check(proof) {
274
+ const snapshot = ports.roster();
275
+ const payload = proof.payload;
276
+ const host = snapshot.hosts.find((h) => h.hostId === payload.hostId);
277
+ if (!host || payload.hostId === ports.hostId || payload.destinationHostId !== ports.hostId || payload.networkId !== snapshot.networkId || payload.epoch !== snapshot.epoch || !payload.publicKey || !payload.challenge || typeof payload.echo !== "string" || payload.expiresAt - payload.issuedAt > LINK_TTL || !(0, _agimon_ai_po_web_security_deviceProof.verifyEnvelope)(host.publicKey, "po/host-request/v1", proof, ports.now())) throw new Error("Roster link refused");
278
+ return payload;
279
+ }
280
+ function wrap(channel, hostId, epoch) {
281
+ const snapshot = ports.roster();
282
+ const remote = snapshot.hosts.find((h) => h.hostId === hostId)?.publicKey;
283
+ const local = snapshot.hosts.find((h) => h.hostId === ports.hostId)?.publicKey;
284
+ const valid = () => {
285
+ const current = ports.roster();
286
+ return !!remote && !!local && current.networkId === snapshot.networkId && current.epoch === epoch && current.hosts.some((h) => h.hostId === hostId && h.publicKey === remote) && current.hosts.some((h) => h.hostId === ports.hostId && h.publicKey === local);
287
+ };
288
+ return {
289
+ seal(plaintext) {
290
+ if (!valid()) return {
291
+ ok: false,
292
+ failure: "auth"
293
+ };
294
+ return channel.seal(plaintext);
295
+ },
296
+ async open(envelope) {
297
+ if (!valid()) return void 0;
298
+ const opened = channel.open(envelope);
299
+ if (!opened.ok || !await ports.verifyRequest(opened.plaintext, hostId) || !valid()) return void 0;
300
+ return opened.plaintext;
301
+ }
302
+ };
303
+ }
304
+ return {
305
+ async connect(hostId, token, exchange) {
306
+ const snapshot = ports.roster();
307
+ if (!snapshot.hosts.some((h) => h.hostId === ports.hostId) || !snapshot.hosts.some((h) => h.hostId === hostId)) throw new Error("Host is not in roster");
308
+ const handshake = (0, _agimon_ai_po_web_security_nodeSealedChannel.createClientHandshake)();
309
+ const payload = {
310
+ networkId: snapshot.networkId,
311
+ epoch: snapshot.epoch,
312
+ hostId: ports.hostId,
313
+ destinationHostId: hostId,
314
+ publicKey: handshake.publicKey,
315
+ challenge: crypto.randomUUID(),
316
+ echo: "",
317
+ issuedAt: ports.now(),
318
+ expiresAt: ports.now() + LINK_TTL
319
+ };
320
+ const reply = check(await exchange(ports.sign(payload), token));
321
+ if (reply.hostId !== hostId || reply.challenge !== payload.challenge || reply.echo !== payload.publicKey || reply.epoch !== payload.epoch) throw new Error("Roster link response mismatch");
322
+ const channel = handshake.accept(reply.publicKey);
323
+ if (!channel) throw new Error("Invalid roster channel");
324
+ return wrap(channel, hostId, payload.epoch);
325
+ },
326
+ async accept(proof, token) {
327
+ const payload = check(proof);
328
+ if (payload.echo !== "" || !await ports.authorize(token, payload.hostId, payload.networkId)) throw new Error("Roster link denied");
329
+ check(proof);
330
+ for (const [id, expiry] of consumed) if (expiry <= ports.now()) consumed.delete(id);
331
+ const id = JSON.stringify([payload.hostId, payload.challenge]);
332
+ if (consumed.has(id) || consumed.size >= 1024) throw new Error("Roster link replayed");
333
+ consumed.set(id, payload.expiresAt);
334
+ const handshake = (0, _agimon_ai_po_web_security_nodeSealedChannel.createHostHandshake)();
335
+ const channel = handshake.accept(payload.publicKey);
336
+ if (!channel) throw new Error("Invalid roster channel");
337
+ return {
338
+ proof: ports.sign({
339
+ ...payload,
340
+ hostId: ports.hostId,
341
+ destinationHostId: payload.hostId,
342
+ publicKey: handshake.publicKey,
343
+ echo: payload.publicKey,
344
+ issuedAt: ports.now(),
345
+ expiresAt: ports.now() + LINK_TTL
346
+ }),
347
+ channel: wrap(channel, payload.hostId, payload.epoch)
348
+ };
349
+ }
350
+ };
351
+ }
352
+ //#endregion
353
+ exports.COORDINATOR_STARTS_PER_HOUR = COORDINATOR_STARTS_PER_HOUR;
354
+ exports.COORDINATOR_START_WINDOW_MS = COORDINATOR_START_WINDOW_MS;
355
+ exports.PO_ROSTER_PEER_CONTRACT = require_type.PO_ROSTER_PEER_CONTRACT;
356
+ exports.PO_ROSTER_PEER_SERVICE = require_type.PO_ROSTER_PEER_SERVICE;
357
+ exports.PO_SESSION_DELIVERY_SERVICE = require_type.PO_SESSION_DELIVERY_SERVICE;
358
+ exports.PO_SESSION_GROUP_BRIDGE_SERVICE = require_type.PO_SESSION_GROUP_BRIDGE_SERVICE;
359
+ exports.PO_SESSION_INTERCOM_SERVICE = require_type.PO_SESSION_INTERCOM_SERVICE;
360
+ exports.PO_SESSION_OPERATIONS_SERVICE = require_type.PO_SESSION_OPERATIONS_SERVICE;
361
+ exports.PO_SESSION_PEERS_CONTRACT = require_type.PO_SESSION_PEERS_CONTRACT;
362
+ exports.PO_SESSION_PEERS_SERVICE = require_type.PO_SESSION_PEERS_SERVICE;
363
+ exports.START_SESSION_TOOL_NAME = require_type.START_SESSION_TOOL_NAME;
364
+ exports.SessionGroupRevisionError = require_type.SessionGroupRevisionError;
365
+ exports.StartSessionParamsSchema = require_type.StartSessionParamsSchema;
366
+ exports.assertCoordinatorStartBudget = assertCoordinatorStartBudget;
367
+ exports.assertCoordinatorStartScope = assertCoordinatorStartScope;
368
+ exports.canSessionsCommunicate = canSessionsCommunicate;
369
+ exports.createBackgroundWorkService = require_type.createBackgroundWorkService;
370
+ exports.createCoordinatorService = createCoordinatorService;
371
+ exports.createPeerCommunication = require_type.createPeerCommunication;
372
+ exports.createPeerLink = require_type.createPeerLink;
373
+ exports.createPeerReplayGuard = require_type.createPeerReplayGuard;
374
+ exports.createPeerReplayGuardAsync = require_type.createPeerReplayGuardAsync;
375
+ exports.createRosterPeerLink = createRosterPeerLink;
376
+ exports.createSessionDeliveryService = require_type.createSessionDeliveryService;
377
+ exports.createSessionDirectory = require_type.createSessionDirectory;
378
+ exports.createSessionGroupDeliveryAuthorizer = require_type.createSessionGroupDeliveryAuthorizer;
379
+ exports.createSessionGroupStore = require_type.createSessionGroupStore;
380
+ exports.createSessionIntercom = require_type.createSessionIntercom;
381
+ exports.createSessionPeers = require_type.createSessionPeers;
382
+ exports.createSessionsNamespace = require_type.createSessionsNamespace;
383
+ exports.createStartSessionTool = require_type.createStartSessionTool;
384
+ exports.namedSessionGroupId = require_type.namedSessionGroupId;
385
+ exports.parseRemoteSessionReference = require_type.parseRemoteSessionReference;
386
+ exports.parseStartSessionInput = require_type.parseStartSessionInput;
387
+ exports.peerOrigin = require_type.peerOrigin;
388
+ exports.peerRequestHeaders = require_type.peerRequestHeaders;
389
+ exports.peerSessionReference = require_type.peerSessionReference;
390
+ exports.provideBackgroundWorkService = require_type.provideBackgroundWorkService;
391
+ exports.provideSessionDeliveryService = require_type.provideSessionDeliveryService;
392
+ exports.readPoSessionDelivery = require_type.readPoSessionDelivery;
393
+ exports.readSessionGroupBridge = require_type.readSessionGroupBridge;
394
+ exports.readSessionIntercom = require_type.readSessionIntercom;
395
+ exports.readSessionOperations = require_type.readSessionOperations;
396
+ exports.readSessionPeerConfig = require_type.readSessionPeerConfig;
397
+ exports.readSessionPeerConfigAsync = require_type.readSessionPeerConfigAsync;
398
+ exports.requireSessionIntercom = require_type.requireSessionIntercom;
399
+ exports.requireSessionPeers = require_type.requireSessionPeers;
400
+ exports.sessionPeerConfigPath = require_type.sessionPeerConfigPath;
401
+ exports.startCoordinatedSession = require_type.startCoordinatedSession;
402
+ exports.verifyPeerRequest = require_type.verifyPeerRequest;
403
+ exports.workspaceSlug = workspaceSlug;
404
+
405
+ //# sourceMappingURL=index.cjs.map