{"version":3,"file":"protocolHubSocket.cjs","names":["isUpdateRequired","isPoProtocolError","PoHubAccessContract","qualifyHostId","PoHubLifecycleContract","localHostId","PoHubContract","PoHubRevisionsContract","hostRevisionTopic","workspaceRevisionTopic","PoChannelsContract","PoThreadContract","poPluginMountToWire"],"sources":["../../../src/web/lib/protocolHubSocket.ts"],"sourcesContent":["import { poPluginMountToWire, type PoPluginCall } from '@agimon-ai/po-core/pluginProtocol';\nimport {\n  isPoProtocolError,\n  isUpdateRequired,\n  PoChannelsContract,\n  PoHubAccessContract,\n  PoHubContract,\n  PoHubLifecycleContract,\n  PoHubRevisionsContract,\n  PoThreadContract,\n  type ChannelsRef,\n  type HomeRequest,\n  type HomeSnapshot,\n  type HubRef,\n  type HubLifecycleSnapshot,\n  type HubSessionView,\n  type HubWorkspaceView,\n  type PoRefStatus,\n  type ProtocolClient,\n} from '@agimon-ai/po-core/sessionProtocol';\nimport { hostRevisionTopic, setHubRevisions, workspaceRevisionTopic } from '@agimon-ai/po-core/web';\n\nimport { localHostId, qualifyHostId } from './hostIdentity';\n\ntype Frame = Record<string, unknown>;\n// A replaced socket must not restore rights or clear the replacement's current rights.\nconst accessOwners = new Map<string, object>();\nconst lifecycleOwners = new Map<string, object>();\n\nexport interface SessionSocket {\n  /** Holds the extension channels of exactly these sessions. */\n  watchSessions(sessionIds: Iterable<string>): void;\n  /** Follows one child thread until the returned function is called. */\n  watchThread(sessionId: string, threadId: string): () => void;\n  /** Sends one extension channel frame `{ type, sessionId, payload }` to its session. */\n  send(frame: object): void;\n  invokePlugin(call: PoPluginCall): Promise<unknown>;\n  readHome(request: HomeRequest, signal?: AbortSignal): Promise<HomeSnapshot>;\n  close(): void;\n}\n\nexport interface SessionSocketHandlers {\n  onSessions(sessions: HubSessionView[]): void;\n  onWorkspaces(workspaces: HubWorkspaceView[]): void;\n  /** Caller-specific rights, already qualified to this connection's host. Empty means unknown, not writable. */\n  onAccess?(interact: Readonly<Record<string, boolean>>): void;\n  /** Optional startup projection. Empty means unavailable, including on older servers. */\n  onLifecycle?(sessions: Readonly<Record<string, HubLifecycleSnapshot>>): void;\n  /** A notification entry or agent dialog of any visible session, delivered once. */\n  onNotice(sessionId: string, frame: Frame): void;\n  /** An extension channel frame `{ type, sessionId, payload }` of a watched session. */\n  onChannel(frame: Frame): void;\n  onThreadFrame(sessionId: string, threadId: string, frame: Frame): void;\n  onOpen(): void;\n  onClose(): void;\n  /** A global or workspace plugin composition changed on the server; not heard for the value a fresh hold opens with. */\n  onCompositions?(): void;\n  /** The server needs newer client code. Heard once, after `onClose`; the socket never reconnects. */\n  onUpdateRequired?(): void;\n}\n\ninterface Held {\n  readonly error: unknown;\n  onStatus(listener: (status: PoRefStatus) => void): () => void;\n  release(): void;\n}\n\n/**\n * Holds one object until the returned function is called. A reference the server forced\n * away after it was live (a Desktop claim) is held again. Transient refusals retry with backoff; permanent refusals stay released.\n * A refusal because this code is older than the server's stops the whole client instead.\n * Before the first link a hold has no route and is refused for good, so it waits for the link.\n */\nfunction keep<R extends Held>(client: ProtocolClient, hold: () => R, attach: (ref: R) => () => void): () => void {\n  let released = false;\n  let retry: ReturnType<typeof setTimeout> | undefined;\n  let delay = 700;\n  let detach = (): void => undefined;\n  const take = (): void => {\n    if (!client.connected) {\n      const stop = client.onConnectionStateChange(({ state }) => {\n        if (state !== 'connected') return;\n        stop();\n        if (!released) take();\n      });\n      detach = stop;\n      return;\n    }\n    const ref = hold();\n    let live = false;\n    const stopAttach = attach(ref);\n    const stopStatus = ref.onStatus((status) => {\n      if (status === 'live') {\n        live = true;\n        delay = 700;\n      }\n      if (status !== 'gone' || released) return;\n      detach();\n      if (isUpdateRequired(ref.error)) client.reportError(ref.error);\n      else if (\n        isPoProtocolError(ref.error) &&\n        ['unavailable', 'superseded', 'upgrade_conflict'].includes(ref.error.code)\n      ) {\n        retry = setTimeout(() => {\n          retry = undefined;\n          if (!released && !client.updateRequired) take();\n        }, delay);\n        delay = Math.min(delay * 2, 5_000);\n      } else if (live && ref.error === undefined) take();\n    });\n    detach = () => {\n      stopStatus();\n      stopAttach();\n      ref.release();\n    };\n  };\n  // A new link needs fresh objects even when the old references never leave live.\n  const stopConnection = client.onConnectionStateChange(({ state }) => {\n    if (state !== 'disconnected' || released || client.updateRequired) return;\n    if (retry) clearTimeout(retry);\n    retry = undefined;\n    detach();\n    take();\n  });\n  take();\n  return () => {\n    released = true;\n    if (retry) clearTimeout(retry);\n    stopConnection();\n    detach();\n  };\n}\n\n/** Caller-specific rights for a host connection, shared by sealed and cookie-admitted clients. */\nexport function watchHubAccess(\n  client: ProtocolClient,\n  onAccess: (rights: Readonly<Record<string, boolean>>) => void,\n  hostId?: string,\n): () => void {\n  const accessKey = hostId ?? '';\n  const accessOwner = {};\n  accessOwners.set(accessKey, accessOwner);\n  const access = (rights: Readonly<Record<string, boolean>>) => {\n    if (accessOwners.get(accessKey) === accessOwner) onAccess(rights);\n  };\n  access({});\n  const release = keep(\n    client,\n    () => client.hold(PoHubAccessContract, {}),\n    (ref) => {\n      let live = false;\n      const publish = (rights: Readonly<Record<string, boolean>> | undefined) => {\n        if (live && client.connected && rights)\n          access(\n            Object.fromEntries(\n              Object.entries(rights).map(([id, allowed]) => [\n                hostId === undefined ? id : qualifyHostId(hostId, id),\n                allowed,\n              ]),\n            ),\n          );\n      };\n      const stop = ref.interact.subscribe(publish);\n      const stopStatus = ref.onStatus((status) => {\n        live = client.connected && status === 'live';\n        if (live) publish(ref.interact.value);\n        else access({});\n      });\n      const stopConnection = client.onConnectionStateChange(({ state }) => {\n        if (state === 'connected') return;\n        live = false;\n        access({});\n      });\n      return () => {\n        live = false;\n        stop();\n        stopStatus();\n        stopConnection();\n        access({});\n      };\n    },\n  );\n  return () => {\n    release();\n    if (accessOwners.get(accessKey) === accessOwner) accessOwners.delete(accessKey);\n  };\n}\n\n/** Optional lifecycle snapshots for a host connection, shared by sealed and cookie-admitted clients. */\nexport function watchHubLifecycle(\n  client: ProtocolClient,\n  onLifecycle: (snapshots: Readonly<Record<string, HubLifecycleSnapshot>>) => void,\n  hostId?: string,\n): () => void {\n  const key = hostId ?? '';\n  const owner = {};\n  lifecycleOwners.set(key, owner);\n  const publishCurrent = (snapshots: Readonly<Record<string, HubLifecycleSnapshot>>) => {\n    if (lifecycleOwners.get(key) === owner) onLifecycle(snapshots);\n  };\n  publishCurrent({});\n  const release = keep(\n    client,\n    () => client.hold(PoHubLifecycleContract, {}),\n    (ref) => {\n      let live = false;\n      const publish = (snapshots: Readonly<Record<string, HubLifecycleSnapshot>> | undefined) => {\n        if (live && client.connected && snapshots)\n          publishCurrent(\n            Object.fromEntries(\n              Object.entries(snapshots).map(([id, snapshot]) => [\n                hostId === undefined ? id : qualifyHostId(hostId, id),\n                {\n                  ...snapshot,\n                  sessionId: hostId === undefined ? snapshot.sessionId : qualifyHostId(hostId, snapshot.sessionId),\n                },\n              ]),\n            ),\n          );\n      };\n      const stop = ref.sessions.subscribe(publish);\n      const stopStatus = ref.onStatus((status) => {\n        live = client.connected && status === 'live';\n        if (live) publish(ref.sessions.value);\n        else publishCurrent({});\n      });\n      const stopConnection = client.onConnectionStateChange(({ state }) => {\n        if (state === 'connected') return;\n        live = false;\n        publishCurrent({});\n      });\n      return () => {\n        live = false;\n        stop();\n        stopStatus();\n        stopConnection();\n        publishCurrent({});\n      };\n    },\n  );\n  return () => {\n    release();\n    if (lifecycleOwners.get(key) === owner) lifecycleOwners.delete(key);\n  };\n}\n\n/** Hub, channels and threads over the page's one protocol connection; references survive reconnects. */\nexport function createProtocolHubSocket(\n  client: ProtocolClient,\n  handlers: SessionSocketHandlers,\n  hostId?: string,\n): SessionSocket {\n  const qualify = (id: string): string => (hostId === undefined ? id : qualifyHostId(hostId, id));\n  const local = (id: string): string => (hostId === undefined ? id : localHostId(hostId, id));\n  let hub: HubRef | undefined;\n  let updateRequired = false;\n  let connectionClosed = false;\n  const closeConnection = () => {\n    if (connectionClosed) return;\n    connectionClosed = true;\n    handlers.onClose();\n  };\n  const acknowledged = new Set<string>();\n  const releaseHub = keep(\n    client,\n    () => client.hold(PoHubContract, {}),\n    (ref) => {\n      hub = ref;\n      let compositions: string | undefined;\n      const stops = [\n        ref.sessions.subscribe((sessions) => {\n          if (sessions)\n            handlers.onSessions(\n              Object.values(sessions).map((session) => ({\n                ...session,\n                id: qualify(session.id),\n                ...(session.workspaceId === undefined ? {} : { workspaceId: qualify(session.workspaceId) }),\n                ...(session.parentSessionId === undefined ? {} : { parentSessionId: qualify(session.parentSessionId) }),\n              })),\n            );\n        }),\n        ref.workspaces.subscribe((workspaces) => {\n          if (workspaces)\n            handlers.onWorkspaces(\n              Object.values(workspaces).map((workspace) => ({ ...workspace, id: qualify(workspace.id) })),\n            );\n        }),\n        ref.pending.subscribe((notices) => {\n          if (!notices) return;\n          const current = new Set(notices.map((notice) => notice.id));\n          for (const id of acknowledged) if (!current.has(id)) acknowledged.delete(id);\n          for (const notice of notices) {\n            if (acknowledged.has(notice.id)) continue;\n            acknowledged.add(notice.id);\n            handlers.onNotice(qualify(notice.sessionId), notice.frame);\n            // A stale client stops for good; any other failed ack leaves the notice pending on the server,\n            // which delivers it again on the next page load.\n            void ref.ackNotice({ id: notice.id }).catch((error: unknown) => client.reportError(error));\n          }\n        }),\n        ref.compositions.subscribe((revisions) => {\n          if (!revisions) return;\n          const next = JSON.stringify(revisions);\n          if (compositions !== undefined && compositions !== next) handlers.onCompositions?.();\n          compositions = next;\n        }),\n        ref.onStatus((status) => {\n          if (updateRequired) return;\n          if (status === 'live') {\n            connectionClosed = false;\n            handlers.onOpen();\n          } else if (status === 'loading' || status === 'gone') closeConnection();\n        }),\n      ];\n      return () => {\n        if (hub === ref) hub = undefined;\n        for (const stop of stops) stop();\n      };\n    },\n  );\n  // Revision topics push \"fetch again\" instead of every view polling. The workspace ids inside topics are\n  // qualified like every other id here, so a phone holding several hosts keeps them apart.\n  const releaseRevisions = keep(\n    client,\n    () => client.hold(PoHubRevisionsContract, {}),\n    (ref) =>\n      ref.revisions.subscribe((revisions) => {\n        if (!revisions) return;\n        const topics: Record<string, number> = {};\n        for (const [topic, value] of Object.entries(revisions)) {\n          // Host topics are namespaced by the connected host.\n          if (topic.startsWith('host:')) topics[hostRevisionTopic(topic.slice(5), hostId)] = value;\n          else if (topic.startsWith('workspace:')) {\n            const rest = topic.slice(10);\n            const split = rest.indexOf(':');\n            if (split > 0) topics[workspaceRevisionTopic(qualify(rest.slice(0, split)), rest.slice(split + 1))] = value;\n          }\n        }\n        setHubRevisions(hostId ?? '', topics);\n      }),\n  );\n\n  const releaseAccess = watchHubAccess(client, (rights) => handlers.onAccess?.(rights), hostId);\n  const releaseLifecycle = watchHubLifecycle(client, (sessions) => handlers.onLifecycle?.(sessions), hostId);\n\n  const channels = new Map<string, { ref: ChannelsRef | undefined; release: () => void }>();\n  // The client closes its link after this; the hub's own close is folded into this one.\n  const stopUpdateWatch = client.onConnectionStateChange(({ state }) => {\n    if (updateRequired) return;\n    if (state === 'disconnected') closeConnection();\n    else if (state === 'update_required') {\n      updateRequired = true;\n      closeConnection();\n      handlers.onUpdateRequired?.();\n    }\n  });\n  const watchChannels = (sessionId: string) => {\n    const entry: { ref: ChannelsRef | undefined; release: () => void } = { ref: undefined, release: () => undefined };\n    entry.release = keep(\n      client,\n      () => client.hold(PoChannelsContract, { sessionId }),\n      (ref) => {\n        entry.ref = ref;\n        let previous: Record<string, unknown> = {};\n        const stop = ref.latest.subscribe((latest) => {\n          if (!latest) return;\n          for (const [type, payload] of Object.entries(latest))\n            if (previous[type] !== payload) handlers.onChannel({ type, sessionId: qualify(sessionId), payload });\n          previous = latest;\n        });\n        return () => {\n          if (entry.ref === ref) entry.ref = undefined;\n          stop();\n        };\n      },\n    );\n    return entry;\n  };\n\n  return {\n    watchSessions(sessionIds) {\n      const wanted = new Set(Array.from(sessionIds, local));\n      for (const [sessionId, entry] of channels) {\n        if (wanted.has(sessionId)) continue;\n        channels.delete(sessionId);\n        entry.release();\n      }\n      for (const sessionId of wanted) if (!channels.has(sessionId)) channels.set(sessionId, watchChannels(sessionId));\n    },\n    watchThread(sessionId, threadId) {\n      sessionId = local(sessionId);\n      return keep(\n        client,\n        () => client.hold(PoThreadContract, { sessionId, threadId }),\n        (ref) =>\n          ref.frame.subscribe((frame) => {\n            if (frame) handlers.onThreadFrame(qualify(sessionId), threadId, frame);\n          }),\n      );\n    },\n    send(frame) {\n      const { type, sessionId, payload } = frame as { type?: unknown; sessionId?: unknown; payload?: unknown };\n      if (typeof type !== 'string' || typeof sessionId !== 'string') return;\n      const wireSessionId = local(sessionId);\n      const watched = channels.get(wireSessionId)?.ref;\n      if (watched !== undefined) {\n        // send() is fire-and-forget for the UI: a stale client stops for good, any other failure drops this one frame.\n        void watched.receive({ type, payload: payload as never }).catch((error: unknown) => client.reportError(error));\n        return;\n      }\n      // An unwatched session's channel is held just for this one frame.\n      const ref = client.hold(PoChannelsContract, { sessionId: wireSessionId });\n      void ref\n        .receive({ type, payload: payload as never })\n        .catch((error: unknown) => client.reportError(error))\n        .finally(() => ref.release());\n    },\n    async invokePlugin(call) {\n      if (!hub) throw new Error('The hub protocol is not connected.');\n      const mount =\n        call.mount.scope === 'host'\n          ? poPluginMountToWire(call.mount)\n          : call.mount.scope === 'workspace'\n            ? { ...call.mount, workspaceId: local(call.mount.workspaceId) }\n            : { ...call.mount, sessionId: local(call.mount.sessionId) };\n      return hub.invoke({ ...call, mount });\n    },\n    async readHome(request, signal) {\n      if (!hub) throw new Error('The hub protocol is not connected.');\n      signal?.throwIfAborted();\n      const result = await hub.readHome({\n        ...request,\n        ...(request.workspaceId === undefined ? {} : { workspaceId: local(request.workspaceId) }),\n      });\n      signal?.throwIfAborted();\n      if (hostId === undefined) return result;\n      const qualifyItem = <T extends { sessionId: string; workspaceId?: string }>(item: T): T => ({\n        ...item,\n        sessionId: qualify(item.sessionId),\n        ...(item.workspaceId === undefined ? {} : { workspaceId: qualify(item.workspaceId) }),\n      });\n      return {\n        ...result,\n        sources: result.sources.map((source) => ({\n          ...source,\n          ...(source.workspaceId === undefined ? {} : { workspaceId: qualify(source.workspaceId) }),\n        })),\n        items: result.items.map(qualifyItem),\n        ...(result.recent === undefined ? {} : { recent: result.recent.map(qualifyItem) }),\n      };\n    },\n    close() {\n      stopUpdateWatch();\n      for (const entry of channels.values()) entry.release();\n      channels.clear();\n      releaseHub();\n      releaseRevisions();\n      releaseAccess();\n      releaseLifecycle();\n    },\n  };\n}\n"],"mappings":";;;;;AA0BA,MAAM,+BAAe,IAAI,IAAoB;AAC7C,MAAM,kCAAkB,IAAI,IAAoB;;;;;;;AA8ChD,SAAS,KAAqB,QAAwB,MAAe,QAA4C;CAC/G,IAAI,WAAW;CACf,IAAI;CACJ,IAAI,QAAQ;CACZ,IAAI,eAAqB,KAAA;CACzB,MAAM,aAAmB;EACvB,IAAI,CAAC,OAAO,WAAW;GACrB,MAAM,OAAO,OAAO,yBAAyB,EAAE,YAAY;IACzD,IAAI,UAAU,aAAa;IAC3B,KAAK;IACL,IAAI,CAAC,UAAU,KAAK;GACtB,CAAC;GACD,SAAS;GACT;EACF;EACA,MAAM,MAAM,KAAK;EACjB,IAAI,OAAO;EACX,MAAM,aAAa,OAAO,GAAG;EAC7B,MAAM,aAAa,IAAI,UAAU,WAAW;GAC1C,IAAI,WAAW,QAAQ;IACrB,OAAO;IACP,QAAQ;GACV;GACA,IAAI,WAAW,UAAU,UAAU;GACnC,OAAO;GACP,KAAA,GAAIA,mCAAAA,iBAAAA,CAAiB,IAAI,KAAK,GAAG,OAAO,YAAY,IAAI,KAAK;QACxD,KAAA,GACHC,mCAAAA,kBAAAA,CAAkB,IAAI,KAAK,KAC3B;IAAC;IAAe;IAAc;GAAkB,CAAC,CAAC,SAAS,IAAI,MAAM,IAAI,GACzE;IACA,QAAQ,iBAAiB;KACvB,QAAQ,KAAA;KACR,IAAI,CAAC,YAAY,CAAC,OAAO,gBAAgB,KAAK;IAChD,GAAG,KAAK;IACR,QAAQ,KAAK,IAAI,QAAQ,GAAG,GAAK;GACnC,OAAO,IAAI,QAAQ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