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MAAA,MAAA,CAAO,MAAA,CAAO,EAAE,OAAA,EAAS,KAAA,EAAO,QAAQ,gCAAA,EAAkC,MAAA,EAAQ,KAAA,EAAe,EAAG,SAAsB,CAAA;AAAA,IAC5H;AAAA,EACF,CAAC,CAAA;AACD,EAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,aAAa,OAAA,EAAS,MAAM,CAAC,GAAG,OAAA,CAAQ,MAAA,EAAQ,CAAA,EAAG,SAAS,MAAM;AAAE,IAAA,SAAA,CAAU,OAAA,CAAQ,CAAC,OAAA,KAAY,OAAA,EAAS,CAAA;AAAG,IAAA,gBAAA,EAAiB;AAAG,IAAA,aAAA,CAAc,KAAA,EAAM;AAAG,IAAA,OAAA,CAAQ,KAAA,EAAM;AAAA,EAAG,CAAA,EAAE;AAC1M","file":"bridges-tui.cjs","sourcesContent":["import {\n  type CallToolResult,\n  type JsonObject,\n  type JsonRpcMessage,\n  type JsonRpcRequest,\n  type JsonRpcId,\n  type RegisteredTool,\n  type ServerCapabilities,\n  type ServerInfo,\n  type ToolDefinition,\n  type ToolHandler,\n  JSONRPC_INTERNAL_ERROR,\n  JSONRPC_INVALID_PARAMS,\n  JSONRPC_METHOD_NOT_FOUND,\n  MCP_PROTOCOL_VERSION,\n} from \"./types\";\nimport { ToolRegistry } from \"./tool-host\";\n\nexport type McpServerOptions = {\n  info: ServerInfo;\n  /** Defaults to { tools: { listChanged: true } } */\n  capabilities?: ServerCapabilities;\n  /** Free-text instructions surfaced to clients during initialize. */\n  instructions?: string;\n  /**\n   * The protocol revisions this server speaks, NEWEST FIRST.\n   *\n   * `initialize` echoes the client's requested revision when it is in this\n   * list, and answers the first entry otherwise — the spec's rule, which leaves\n   * the client to decide whether it can live with the answer.\n   *\n   * Defaults to `[MCP_PROTOCOL_VERSION]`: one revision, answered whatever the\n   * client asks, which is exactly what this server did before the option\n   * existed. Only list a revision the tools you register are correct under.\n   */\n  protocolVersions?: readonly string[];\n};\n\nexport type Transport = {\n  /** Called by the server when it has a message to deliver to the client. */\n  send: (message: JsonRpcMessage) => void;\n  /** Called by the server when it's torn down so the transport can clean up. */\n  close?: () => void;\n};\n\n/**\n * MicroMcpServer — protocol-level MCP server, transport-agnostic.\n *\n * Use it like:\n *\n *   const server = new MicroMcpServer({ info: { name: \"session\", version: \"0.1\" } });\n *   server.registerTool({ name: \"...\", inputSchema: { type: \"object\" } }, async (args) => ({...}));\n *   const transport = new InProcessTransport();\n *   server.attach(transport);\n *   transport.deliver({ ... }); // client → server frames\n *\n * The same server can serve multiple transports (e.g. an in-process agent\n * AND a relayed external client) by attaching each one.\n */\nexport class MicroMcpServer extends ToolRegistry {\n  private transports = new Set<Transport>();\n  /**\n   * Transports owed a `tools/list_changed` at the end of this tick. Empty when\n   * none is scheduled. See {@link scheduleListChangedNotification}.\n   */\n  private listChangedOwed = new Set<Transport>();\n\n  readonly info: ServerInfo;\n  readonly capabilities: ServerCapabilities;\n  readonly instructions?: string;\n  readonly protocolVersions: readonly string[];\n\n  constructor(options: McpServerOptions) {\n    super();\n    this.info = options.info;\n    this.capabilities = options.capabilities ?? { tools: { listChanged: true } };\n    this.instructions = options.instructions;\n    if (options.protocolVersions && options.protocolVersions.length === 0) {\n      // No answer exists for a client's initialize. Fail here, next to the\n      // mistake, rather than in a handshake nobody is watching.\n      throw new Error(\"MicroMcpServer: protocolVersions is empty — a server must speak at least one protocol revision.\");\n    }\n    this.protocolVersions = options.protocolVersions ? [...options.protocolVersions] : [MCP_PROTOCOL_VERSION];\n  }\n\n  attach(transport: Transport): () => void {\n    this.transports.add(transport);\n    return () => this.detach(transport);\n  }\n\n  detach(transport: Transport): void {\n    if (this.transports.delete(transport)) {\n      transport.close?.();\n    }\n  }\n\n  unregisterTool(name: string): void {\n    if (this.tools.delete(name)) {\n      this.scheduleListChangedNotification();\n    }\n  }\n\n  protected onToolsChanged(): void {\n    this.scheduleListChangedNotification();\n  }\n\n  /**\n   * Receive a JSON-RPC frame from a client (called by the transport).\n   * The transport is responsible for sending the response back.\n   */\n  async receive(transport: Transport, message: JsonRpcMessage): Promise<void> {\n    if (!(\"method\" in message)) return; // It's a response, not a request — ignore.\n\n    const isNotification = !(\"id\" in message);\n    if (isNotification) {\n      // Notifications are fire-and-forget. We ignore unknown methods.\n      return;\n    }\n\n    const request = message as JsonRpcRequest;\n    try {\n      const result = await this.handle(request, transport);\n      transport.send({ jsonrpc: \"2.0\", id: request.id, result });\n    } catch (err) {\n      transport.send({\n        jsonrpc: \"2.0\",\n        id: request.id,\n        error: this.toRpcError(err),\n      });\n    }\n  }\n\n  private async handle(request: JsonRpcRequest, transport: Transport): Promise<any> {\n    const { method, params } = request;\n    switch (method) {\n      case \"initialize\":\n        return {\n          protocolVersion: this.negotiate(params?.protocolVersion),\n          capabilities: this.capabilities,\n          serverInfo: this.info,\n          ...(this.instructions ? { instructions: this.instructions } : {}),\n        };\n\n      case \"tools/list\":\n        return { tools: this.listTools() };\n\n      case \"tools/call\": {\n        const name = params?.name;\n        const args = (params?.arguments ?? {}) as JsonObject;\n        if (typeof name !== \"string\") {\n          throw rpcError(JSONRPC_INVALID_PARAMS, \"tools/call requires `name`\");\n        }\n        const tool = this.tools.get(name);\n        if (!tool) {\n          throw rpcError(JSONRPC_METHOD_NOT_FOUND, this.missingToolMessage(name));\n        }\n        const result = await tool.handler(args, { transport });\n        return result satisfies CallToolResult;\n      }\n\n      case \"ping\":\n        return {};\n\n      default:\n        throw rpcError(JSONRPC_METHOD_NOT_FOUND, `Unsupported method: ${method}`);\n    }\n  }\n\n  /** The revision to answer `initialize` with: the one asked for if spoken, else the newest. */\n  private negotiate(requested: unknown): string {\n    return typeof requested === \"string\" && this.protocolVersions.includes(requested)\n      ? requested\n      : this.protocolVersions[0];\n  }\n\n  /**\n   * Tell the transports that SAW the old tool list that it changed.\n   *\n   * Changes in one tick coalesce into one notification. The recipients are the\n   * transports attached at the moment of a change, not at the moment the\n   * notification goes out: a transport attached afterwards never had the old\n   * list, so \"your list is stale\" is noise to it — and on stdio, where a host\n   * builds the server and attaches stdin/stdout in the same tick, it was the\n   * first frame a client received, before it had even sent `initialize`.\n   */\n  private scheduleListChangedNotification(): void {\n    if (this.transports.size === 0) return;\n    const scheduled = this.listChangedOwed.size > 0;\n    for (const t of this.transports) this.listChangedOwed.add(t);\n    if (scheduled) return;\n    queueMicrotask(() => {\n      const owed = this.listChangedOwed;\n      this.listChangedOwed = new Set();\n      for (const t of owed) {\n        // Detached since the change: it is not listening any more.\n        if (this.transports.has(t)) t.send({ jsonrpc: \"2.0\", method: \"notifications/tools/list_changed\" });\n      }\n    });\n  }\n\n  /** Send an application notification to every client, or one attached transport. */\n  notify(message: JsonRpcMessage, transport?: Transport): void {\n    if (transport) transport.send(message);\n    else this.broadcast(message);\n  }\n\n  private broadcast(message: JsonRpcMessage): void {\n    for (const t of this.transports) t.send(message);\n  }\n\n  private toRpcError(err: unknown): { code: number; message: string; data?: any } {\n    if (err && typeof err === \"object\" && \"code\" in err && \"message\" in err) {\n      return err as any;\n    }\n    return {\n      code: JSONRPC_INTERNAL_ERROR,\n      message: err instanceof Error ? err.message : String(err),\n    };\n  }\n}\n\nexport function rpcError(code: number, message: string, data?: any) {\n  return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\n/**\n * Helper to build a CallToolResult from a string or structured value.\n */\nexport function textResult(text: string, structured?: any): CallToolResult {\n  return {\n    content: [{ type: \"text\", text }],\n    ...(structured !== undefined ? { structuredContent: structured } : {}),\n  };\n}\n\nexport function errorResult(text: string): CallToolResult {\n  return { content: [{ type: \"text\", text }], isError: true };\n}\n\n// Internal helper so the JsonRpcId import isn't dropped by tsup\ntype _KeepIdImport = JsonRpcId;\n","import { emitActivity } from \"../presence\";\nimport { errorResult, textResult, type MicroMcpServer, type Transport } from \"../mcp/server\";\nimport type { JsonObject, ToolCallContext } from \"../mcp/types\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { HumanPlusActor, HumanPlusEventStore, HumanPlusPriority } from \"../human-plus/events\";\n\nexport type TuiActionPolicy = \"observe\" | \"execute\" | \"propose\" | \"confirm\" | \"human-only\";\nexport interface TuiSurfaceCommandLike { name: string; description?: string; policy?: TuiActionPolicy; inputSchema?: Record<string, unknown>; invoke(input?: Record<string, unknown>): unknown | Promise<unknown>; }\nexport interface TuiSurfaceLike { id: string; kind: string; label?: string; read(): unknown; commands?: TuiSurfaceCommandLike[]; }\nexport interface TuiSurfaceRegistryLike { list(): TuiSurfaceLike[]; get(id: string): TuiSurfaceLike | undefined; }\nexport interface TuiBridgeOptions {\n  registry: TuiSurfaceRegistryLike;\n  eventStore: HumanPlusEventStore;\n  appId: string;\n  sessionId?: string;\n  actor?: HumanPlusActor;\n}\n\ntype Subscription = { consumerId: string; types?: string[]; surfaces?: string[] };\ntype PendingAction = { id: string; surfaceId: string; command: string; input: Record<string, unknown>; actor: HumanPlusActor };\n\nexport function registerTuiBridge(host: ToolHost, options: TuiBridgeOptions) {\n  const disposers: Array<() => void> = []; const subscriptions = new Map<unknown, Subscription>(); const pending = new Map<string, PendingAction>();\n  const defaultActor = options.actor ?? { kind: \"agent\" as const, id: \"agent\", name: \"Agent\" };\n  const serverCapabilities = (host as ToolHost & { capabilities?: { experimental?: Record<string, unknown> } }).capabilities;\n  if (serverCapabilities) serverCapabilities.experimental = { ...serverCapabilities.experimental, \"io.particle-academy/human-plus\": { version: \"1\", push: true, durableCursor: true, stagedActions: true, wakesAgent: false } };\n  const register = (name: string, description: string, properties: Record<string, unknown>, required: string[], handler: (args: JsonObject, context?: ToolCallContext) => unknown | Promise<unknown>) => {\n    disposers.push(host.registerTool({ name, description, inputSchema: { type: \"object\", properties: properties as never, required } }, async (args, context) => {\n      try { const result = await handler(args, context); return textResult(typeof result === \"string\" ? result : JSON.stringify(result), result); }\n      catch (error) { return errorResult(error instanceof Error ? error.message : String(error)); }\n    }, { owner: \"tui\" }));\n  };\n  const publish = async (surfaceId: string, type: string, payload: unknown, actor = defaultActor, priority: HumanPlusPriority = \"normal\") => options.eventStore.append({ appId: options.appId, sessionId: options.sessionId, surfaceId, type, payload, actor, priority });\n\n  register(\"tui_surfaces_list\", \"List addressable Fancy TUI surfaces and commands.\", {}, [], () => options.registry.list().map((surface) => ({ id: surface.id, kind: surface.kind, label: surface.label, commands: surface.commands?.map((command) => ({ name: command.name, description: command.description, policy: command.policy ?? \"execute\", inputSchema: command.inputSchema })) ?? [] })));\n  register(\"tui_surface_read\", \"Read a Fancy TUI surface by stable id.\", { id: { type: \"string\" } }, [\"id\"], (args) => {\n    const surface = options.registry.get(String(args.id)); if (!surface) throw new Error(`Unknown TUI surface: ${String(args.id)}`); return { id: surface.id, kind: surface.kind, state: surface.read() };\n  });\n  register(\"tui_action_invoke\", \"Invoke or propose an action on a Fancy TUI surface.\", { surfaceId: { type: \"string\" }, command: { type: \"string\" }, input: { type: \"object\" } }, [\"surfaceId\", \"command\"], async (args) => {\n    const surfaceId = String(args.surfaceId); const commandName = String(args.command); const surface = options.registry.get(surfaceId); if (!surface) throw new Error(`Unknown TUI surface: ${surfaceId}`);\n    const command = surface.commands?.find((value) => value.name === commandName); if (!command) throw new Error(`Unknown command '${commandName}' on ${surfaceId}`);\n    const policy = command.policy ?? \"execute\"; if (policy === \"observe\" || policy === \"human-only\") throw new Error(`Action ${surfaceId}.${commandName} is ${policy}`);\n    const input = (args.input && typeof args.input === \"object\" && !Array.isArray(args.input) ? args.input : {}) as Record<string, unknown>;\n    if (policy === \"propose\" || policy === \"confirm\") {\n      const id = globalThis.crypto.randomUUID(); pending.set(id, { id, surfaceId, command: commandName, input, actor: defaultActor });\n      await publish(surfaceId, \"action.proposed\", { id, command: commandName, input }, defaultActor, \"attention\"); return { pending: true, id };\n    }\n    const result = await command.invoke(input); await publish(surfaceId, \"action.executed\", { command: commandName, input, result });\n    emitActivity({ agentId: defaultActor.id, agentName: defaultActor.name, target: { kind: \"custom\", elementId: surfaceId }, action: `tui_${commandName}`, timestamp: Date.now(), meta: { surfaceId } });\n    return { executed: true, result };\n  });\n  register(\"tui_action_confirm\", \"Confirm and execute a pending TUI action.\", { id: { type: \"string\" } }, [\"id\"], async (args) => {\n    const id = String(args.id); const value = pending.get(id); if (!value) throw new Error(`Unknown pending action: ${id}`); const surface = options.registry.get(value.surfaceId); const command = surface?.commands?.find((x) => x.name === value.command); if (!command) throw new Error(\"Pending action target is no longer available\");\n    pending.delete(id); const result = await command.invoke(value.input); await publish(value.surfaceId, \"action.confirmed\", { id, command: value.command, result }, { kind: \"human\", id: \"human\" }); return { executed: true, result };\n  });\n  register(\"tui_action_reject\", \"Reject a pending TUI action.\", { id: { type: \"string\" } }, [\"id\"], async (args) => { const id = String(args.id); const value = pending.get(id); if (!value) throw new Error(`Unknown pending action: ${id}`); pending.delete(id); await publish(value.surfaceId, \"action.rejected\", { id, command: value.command }, { kind: \"human\", id: \"human\" }); return { rejected: true }; });\n  register(\"human_plus_events_list\", \"Pull durable Human+ events for a consumer.\", { consumerId: { type: \"string\" }, after: { type: \"number\" }, limit: { type: \"number\" }, unacknowledgedOnly: { type: \"boolean\" } }, [\"consumerId\"], (args) => options.eventStore.list({ consumerId: String(args.consumerId), after: typeof args.after === \"number\" ? args.after : undefined, limit: typeof args.limit === \"number\" ? args.limit : undefined, unacknowledgedOnly: args.unacknowledgedOnly === true }));\n  register(\"human_plus_events_ack\", \"Acknowledge durable Human+ events.\", { consumerId: { type: \"string\" }, eventIds: { type: \"array\", items: { type: \"string\" } }, disposition: { type: \"string\" } }, [\"consumerId\", \"eventIds\"], async (args) => { const ids = Array.isArray(args.eventIds) ? args.eventIds.map(String) : []; await options.eventStore.acknowledge(String(args.consumerId), ids, [\"seen\", \"handled\", \"rejected\", \"ignored\"].includes(String(args.disposition)) ? String(args.disposition) as any : \"handled\"); return { acknowledged: ids.length }; });\n  register(\"human_plus_events_subscribe\", \"Push matching Human+ events on this MCP transport while retaining them in the inbox.\", { consumerId: { type: \"string\" }, types: { type: \"array\" }, surfaces: { type: \"array\" } }, [\"consumerId\"], (args, context) => { if (!context?.transport) throw new Error(\"Subscriptions require an attached MCP transport\"); subscriptions.set(context.transport, { consumerId: String(args.consumerId), types: Array.isArray(args.types) ? args.types.map(String) : undefined, surfaces: Array.isArray(args.surfaces) ? args.surfaces.map(String) : undefined }); return { subscribed: true, delivery: \"at-least-once\", wakesAgent: false }; });\n\n  const unsubscribeStore = options.eventStore.subscribe((event) => {\n    const server = host as ToolHost & Pick<MicroMcpServer, \"notify\">;\n    if (typeof server.notify !== \"function\") return;\n    for (const [transport, subscription] of subscriptions) {\n      if (subscription.types?.length && !subscription.types.includes(event.type)) continue;\n      if (subscription.surfaces?.length && !subscription.surfaces.includes(event.surfaceId)) continue;\n      server.notify({ jsonrpc: \"2.0\", method: \"notifications/human_plus/event\", params: event as never }, transport as Transport);\n    }\n  });\n  return { id: \"tui\", title: \"Fancy TUI\", pending: () => [...pending.values()], dispose: () => { disposers.forEach((dispose) => dispose()); unsubscribeStore(); subscriptions.clear(); pending.clear(); } };\n}\n"]}