@burdenoff/microfe-botmanor 2026.1118.7 → 2026.1119.1

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.
Files changed (41) hide show
  1. package/dist/botlit/components/A2ATrustBadge.d.ts +9 -0
  2. package/dist/botlit/components/A2ATrustBadge.js +55 -0
  3. package/dist/botlit/components/A2ATrustBadge.js.map +1 -0
  4. package/dist/botlit/components/ChannelSelectorSheet.d.ts +9 -2
  5. package/dist/botlit/components/ChannelSelectorSheet.js.map +1 -1
  6. package/dist/botlit/hooks/index.d.ts +1 -1
  7. package/dist/botlit/hooks/index.js +14 -14
  8. package/dist/botlit/hooks/internal/globalWorkspaceScope.d.ts +15 -0
  9. package/dist/botlit/hooks/internal/globalWorkspaceScope.js +21 -0
  10. package/dist/botlit/hooks/internal/globalWorkspaceScope.js.map +1 -0
  11. package/dist/botlit/hooks/internal/workspaceGateway.d.ts +7 -0
  12. package/dist/botlit/hooks/internal/workspaceGateway.js +42 -22
  13. package/dist/botlit/hooks/internal/workspaceGateway.js.map +1 -1
  14. package/dist/botlit/hooks/useA2A.d.ts +107 -9
  15. package/dist/botlit/hooks/useA2A.js +215 -80
  16. package/dist/botlit/hooks/useA2A.js.map +1 -1
  17. package/dist/botlit/hooks/useChannelSetup.d.ts +2 -1
  18. package/dist/botlit/hooks/useChannelSetup.js +61 -52
  19. package/dist/botlit/hooks/useChannelSetup.js.map +1 -1
  20. package/dist/botlit/hooks/useChannels.d.ts +9 -0
  21. package/dist/botlit/hooks/useChannels.js +83 -73
  22. package/dist/botlit/hooks/useChannels.js.map +1 -1
  23. package/dist/botlit/hooks/useUserPlatformConnection.js +98 -78
  24. package/dist/botlit/hooks/useUserPlatformConnection.js.map +1 -1
  25. package/dist/botlit/pages/A2AAgentDetailPage.js +715 -503
  26. package/dist/botlit/pages/A2AAgentDetailPage.js.map +1 -1
  27. package/dist/botlit/pages/A2ARegistryPage.js +278 -179
  28. package/dist/botlit/pages/A2ARegistryPage.js.map +1 -1
  29. package/dist/botlit/pages/BotChannelsTab.js +457 -242
  30. package/dist/botlit/pages/BotChannelsTab.js.map +1 -1
  31. package/dist/botlit/pages/ExecutionsPage.js +1 -1
  32. package/dist/botlit/pages/InstalledPackagesPage.js +154 -154
  33. package/dist/botlit/pages/InstalledPackagesPage.js.map +1 -1
  34. package/dist/botlit/pages/PromptStudioPage.js +172 -172
  35. package/dist/botlit/pages/PromptStudioPage.js.map +1 -1
  36. package/dist/botlit/pages/StorePage.js +8 -8
  37. package/dist/botlit/pages/StorePage.js.map +1 -1
  38. package/dist/botlit/permissions/index.js +3 -3
  39. package/dist/botlit/permissions/useBotmanorPermissions.js +5 -2
  40. package/dist/botlit/permissions/useBotmanorPermissions.js.map +1 -1
  41. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"useA2A.js","names":["LIST_LIMIT","REGISTER_AGENT_FIELDS","fieldsOf","UPDATE_AGENT_FIELDS","NO_AGENTS","asRecord","value","asString","fallback","asBoolean","asStringArray","entry","asObjectArray","readAgentCard","source","card","capabilities","authentication","skill","index","readEntitlements","entitlements","maxHops","entitlement","a2aAgentSkillCount","skills","agent","validateAgentCard","errors","field","selectAgents","data","useA2AAgents","workspaceId","useWorkspaceId","search","filter","status","visibility","trustLevel","bucketId","variables","useMemo","select","useCallback","rows","row","useWorkspaceQuery","ListA2ARegistryEntriesDocument","useA2AAgent","agentId","GetA2ARegistryEntryDocument","useRegisterA2AAgent","buildMutationInput","input","useWorkspaceMutation","CreateA2ARegistryEntryDocument","useUpdateA2AAgent","UpdateA2ARegistryEntryDocument","useDeleteA2AAgent","DeleteA2ARegistryEntryDocument"],"sources":["../../../src/botlit/hooks/useA2A.ts"],"sourcesContent":["/**\n * A2A Registry Hooks\n * @module botlit/hooks\n *\n * Backed by the live `listA2ARegistryEntries` / `getA2ARegistryEntry`\n * operations and the create/update/delete mutations on wspace-botlit-svc.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport {\n CreateA2ARegistryEntryDocument,\n DeleteA2ARegistryEntryDocument,\n GetA2ARegistryEntryDocument,\n ListA2ARegistryEntriesDocument,\n UpdateA2ARegistryEntryDocument,\n type CreateA2ARegistryEntryMutation,\n type DeleteA2ARegistryEntryMutation,\n type GetA2ARegistryEntryQuery,\n type ListA2ARegistryEntriesQuery,\n type UpdateA2ARegistryEntryMutation,\n} from '../../generated/wspace-operations';\nimport type {\n CreateA2ARegistryEntryInput,\n UpdateA2ARegistryEntryInput,\n} from '../../generated/wspace-types';\nimport type { A2AAgentFilter } from '../types';\nimport { buildMutationInput, fieldsOf, type GraphQLInput } from './internal/mutationInput';\nimport {\n useWorkspaceId,\n useWorkspaceMutation,\n useWorkspaceQuery,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nconst LIST_LIMIT = 100;\n\nexport interface A2AAgentRecord {\n id: string;\n name: string;\n status: string;\n visibility: string;\n trustLevel: string;\n /** A2A agent card (the `/.well-known/agent.json` document). */\n agentCard: Record<string, unknown>;\n entitlements: Record<string, unknown> | unknown[];\n description?: string | null;\n wellKnownUrl?: string | null;\n bucketId?: string | null;\n metadata?: Record<string, unknown> | null;\n revision: number;\n tags: string[];\n createdAt: string;\n updatedAt: string;\n createdById: string;\n updatedById: string;\n workspaceId: string;\n}\n\n/** `CreateA2ARegistryEntryInput` minus the `workspaceId` the hook supplies. */\nexport type RegisterA2AAgentVariables = Omit<\n GraphQLInput<CreateA2ARegistryEntryInput>,\n 'workspaceId'\n>;\n\nexport interface UpdateA2AAgentVariables {\n agentId: string;\n input: GraphQLInput<UpdateA2ARegistryEntryInput>;\n}\n\nconst REGISTER_AGENT_FIELDS = fieldsOf<CreateA2ARegistryEntryInput>({\n agentCard: true,\n bucketId: true,\n description: true,\n entitlements: true,\n metadata: true,\n name: true,\n status: true,\n tags: true,\n trustLevel: true,\n visibility: true,\n wellKnownUrl: true,\n workspaceId: true,\n});\n\nconst UPDATE_AGENT_FIELDS = fieldsOf<UpdateA2ARegistryEntryInput>({\n agentCard: true,\n bucketId: true,\n description: true,\n entitlements: true,\n metadata: true,\n name: true,\n status: true,\n tags: true,\n trustLevel: true,\n visibility: true,\n wellKnownUrl: true,\n});\n\nexport interface AgentCardValidation {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * The agent-card fields the UI renders. `agentCard` is a free-form `JSON`\n * column on the service, so every field is read defensively — a card that is\n * missing `capabilities`, or that stores `skills` as an object instead of an\n * array, must render as \"not supported\"/\"none\" rather than throw.\n */\nexport interface A2AAgentCardView {\n url: string;\n version: string;\n providerOrganization: string;\n documentationUrl: string;\n capabilities: {\n streaming: boolean;\n pushNotifications: boolean;\n stateTransitionHistory: boolean;\n };\n authenticationSchemes: string[];\n defaultInputModes: string[];\n defaultOutputModes: string[];\n skills: A2AAgentCardSkill[];\n}\n\nexport interface A2AAgentCardSkill {\n id: string;\n name: string;\n description: string;\n tags: string[];\n examples: string[];\n}\n\n/** One row of the `entitlements` JSON, normalised for rendering. */\nexport interface A2AEntitlementView {\n id: string;\n sourceType: string;\n sourceId: string;\n allowedSkills: string[];\n disallowedSkills: string[];\n maxHops?: number;\n}\n\nconst NO_AGENTS: A2AAgentRecord[] = [];\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction asString(value: unknown, fallback = ''): string {\n return typeof value === 'string' ? value : fallback;\n}\n\nfunction asBoolean(value: unknown): boolean {\n return value === true;\n}\n\nfunction asStringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === 'string')\n : [];\n}\n\nfunction asObjectArray(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value) ? value.map(asRecord) : [];\n}\n\n/** Reads the renderable view of an A2A agent card out of its JSON document. */\nexport function readAgentCard(card: Record<string, unknown> | undefined): A2AAgentCardView {\n const source = asRecord(card);\n const capabilities = asRecord(source.capabilities);\n const authentication = asRecord(source.authentication);\n\n return {\n url: asString(source.url),\n version: asString(source.version),\n providerOrganization: asString(asRecord(source.provider).organization),\n documentationUrl: asString(source.documentationUrl),\n capabilities: {\n streaming: asBoolean(capabilities.streaming),\n pushNotifications: asBoolean(capabilities.pushNotifications),\n stateTransitionHistory: asBoolean(capabilities.stateTransitionHistory),\n },\n authenticationSchemes: asStringArray(authentication.schemes),\n defaultInputModes: asStringArray(source.defaultInputModes),\n defaultOutputModes: asStringArray(source.defaultOutputModes),\n skills: asObjectArray(source.skills).map((skill, index) => ({\n id: asString(skill.id, `skill-${index}`),\n name: asString(skill.name),\n description: asString(skill.description),\n tags: asStringArray(skill.tags),\n examples: asStringArray(skill.examples),\n })),\n };\n}\n\n/** Reads the entitlement rows out of the `entitlements` JSON column. */\nexport function readEntitlements(\n entitlements: Record<string, unknown> | unknown[] | null | undefined\n): A2AEntitlementView[] {\n return asObjectArray(entitlements).map((entitlement, index) => {\n const maxHops = entitlement.maxHops;\n return {\n id: asString(entitlement.id, `entitlement-${index}`),\n sourceType: asString(entitlement.sourceType, 'unknown'),\n sourceId: asString(entitlement.sourceId),\n allowedSkills: asStringArray(entitlement.allowedSkills),\n disallowedSkills: asStringArray(entitlement.disallowedSkills),\n maxHops: typeof maxHops === 'number' ? maxHops : undefined,\n };\n });\n}\n\n/** Number of skills the registered agent card advertises. */\nexport function a2aAgentSkillCount(agent: Pick<A2AAgentRecord, 'agentCard'>): number {\n const skills = agent.agentCard?.skills;\n return Array.isArray(skills) ? skills.length : 0;\n}\n\n/**\n * Structural check of an A2A agent card before it is registered. This validates\n * the document the caller supplies — it does NOT contact the remote agent.\n */\nexport function validateAgentCard(card: Record<string, unknown> | undefined): AgentCardValidation {\n const errors: string[] = [];\n if (!card) {\n return { valid: false, errors: ['An agent card is required'] };\n }\n for (const field of ['name', 'description', 'url', 'version'] as const) {\n if (typeof card[field] !== 'string' || (card[field] as string).trim() === '') {\n errors.push(`Agent card is missing \"${field}\"`);\n }\n }\n if (!Array.isArray(card.skills) || card.skills.length === 0) {\n errors.push('Agent card must advertise at least one skill');\n }\n return { valid: errors.length === 0, errors };\n}\n\nfunction selectAgents(data: ListA2ARegistryEntriesQuery | undefined): A2AAgentRecord[] {\n return data?.listA2ARegistryEntries ?? NO_AGENTS;\n}\n\nexport const a2aKeys = {\n all: ['a2a'] as const,\n lists: () => [...a2aKeys.all, 'list'] as const,\n list: (filter?: A2AAgentFilter) => [...a2aKeys.lists(), filter] as const,\n details: () => [...a2aKeys.all, 'detail'] as const,\n detail: (id: string) => [...a2aKeys.details(), id] as const,\n};\n\nexport function useA2AAgents(filter?: A2AAgentFilter): QueryResult<A2AAgentRecord[]> {\n const workspaceId = useWorkspaceId();\n const search = filter?.search?.trim().toLowerCase() ?? '';\n const status = filter?.status?.[0];\n const visibility = filter?.visibility?.[0];\n const trustLevel = filter?.trustLevel?.[0];\n const bucketId = filter?.bucketId;\n\n const variables = useMemo(\n () => ({\n // A2ARegistryEntryFilterInput has no free-text field — search is client-side.\n filters: { workspaceId, status, visibility, trustLevel, bucketId },\n pagination: { limit: LIST_LIMIT, offset: 0 },\n }),\n [workspaceId, status, visibility, trustLevel, bucketId]\n );\n\n const select = useCallback(\n (data: ListA2ARegistryEntriesQuery | undefined): A2AAgentRecord[] => {\n const rows = selectAgents(data);\n if (!search) return rows;\n return rows.filter(\n (row) =>\n row.name.toLowerCase().includes(search) ||\n (row.description ?? '').toLowerCase().includes(search)\n );\n },\n [search]\n );\n\n return useWorkspaceQuery<ListA2ARegistryEntriesQuery, A2AAgentRecord[]>({\n document: ListA2ARegistryEntriesDocument,\n variables,\n select,\n fallback: NO_AGENTS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load the A2A registry',\n });\n}\n\nexport function useA2AAgent(agentId: string | undefined): QueryResult<A2AAgentRecord | null> {\n const variables = useMemo(() => ({ id: agentId ?? '' }), [agentId]);\n\n return useWorkspaceQuery<GetA2ARegistryEntryQuery, A2AAgentRecord | null>({\n document: GetA2ARegistryEntryDocument,\n variables,\n select: (data) => data?.getA2ARegistryEntry ?? null,\n fallback: null,\n enabled: Boolean(agentId),\n errorMessage: 'Failed to load A2A agent',\n });\n}\n\nexport function useRegisterA2AAgent() {\n const workspaceId = useWorkspaceId();\n\n const variables = useCallback(\n (input: RegisterA2AAgentVariables) => ({\n input: buildMutationInput({ ...input, workspaceId }, REGISTER_AGENT_FIELDS),\n }),\n [workspaceId]\n );\n\n return useWorkspaceMutation<\n CreateA2ARegistryEntryMutation,\n RegisterA2AAgentVariables,\n A2AAgentRecord\n >({\n document: CreateA2ARegistryEntryDocument,\n variables,\n select: (data) => data?.createA2ARegistryEntry,\n errorMessage: 'Failed to register A2A agent',\n });\n}\n\nexport function useUpdateA2AAgent() {\n return useWorkspaceMutation<\n UpdateA2ARegistryEntryMutation,\n UpdateA2AAgentVariables,\n A2AAgentRecord\n >({\n document: UpdateA2ARegistryEntryDocument,\n variables: ({ agentId, input }) => ({\n id: agentId,\n input: buildMutationInput(input, UPDATE_AGENT_FIELDS),\n }),\n select: (data) => data?.updateA2ARegistryEntry,\n errorMessage: 'Failed to update A2A agent',\n });\n}\n\nexport function useDeleteA2AAgent() {\n return useWorkspaceMutation<DeleteA2ARegistryEntryMutation, string, boolean>({\n document: DeleteA2ARegistryEntryDocument,\n variables: (agentId) => ({ id: agentId }),\n select: (data) => data?.deleteA2ARegistryEntry,\n errorMessage: 'Failed to remove A2A agent',\n });\n}\n\n/**\n * Validates an agent card locally before registration. There is no server-side\n * validation operation, so this deliberately reports only what can be checked\n * from the document itself.\n */\nexport function useValidateA2AAgent() {\n const validate = useCallback(\n async (card: Record<string, unknown> | undefined): Promise<AgentCardValidation> =>\n validateAgentCard(card),\n []\n );\n\n return [validate, { loading: false, error: undefined }] as const;\n}\n"],"mappings":";;;;;AAkCA,IAAMA,IAAa,KAmCbC,IAAwBC,EAAsC;CAClE,WAAW;CACX,UAAU;CACV,aAAa;CACb,cAAc;CACd,UAAU;CACV,MAAM;CACN,QAAQ;CACR,MAAM;CACN,YAAY;CACZ,YA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,GAAM;EACxB,cAAc;CAChB,CAAC;AACH;AAEA,SAAgB0B,IAAoB;CAClC,OAAOF,EAIL;EACA,UAAUG;EACV,YAAY,EAAE,YAAS,gBAAa;GAClC,IAAIR;GACJ,OAAOG,EAAmBC,GAAOnD,CAAmB;EACtD;EACA,SAAS,MAAS4B,GAAM;EACxB,cAAc;CAChB,CAAC;AACH;AAEA,SAAgB4B,IAAoB;CAClC,OAAOJ,EAAsE;EAC3E,UAAUK;EACV,YAAY,OAAa,EAAE,IAAIV,EAAQ;EACvC,SAAS,MAASnB,GAAM;EACxB,cAAc;CAChB,CAAC;AACH"}
1
+ {"version":3,"file":"useA2A.js","names":["A2A_DESCRIPTION_MAX","A2A_URL_MAX","A2A_AGENT_CARD_MAX_BYTES","REGISTER_AGENT_FIELDS","fieldsOf","UPDATE_AGENT_FIELDS","A2A_ENTITLEMENT_PERMISSIONS","NO_AGENTS","asRecord","value","asString","fallback","asBoolean","asStringArray","entry","asObjectArray","readAgentCard","source","card","capabilities","authentication","skill","index","UNENFORCED_SCOPE_KEYS","unenforcedFields","scope","entitlement","fields","key","readEntitlements","entitlements","permission","validFrom","validUntil","toDateInput","parsed","isEntitlementPermission","toEntitlementDrafts","rows","view","unmanagedEntitlements","toEntitlementsInput","drafts","row","draft","original","keep","stored","field","unmanaged","entitlementDraftError","entitlementsAllowConnections","isActive","from","until","now","a2aAgentSkillCount","skills","agent","validateAgentCard","errors","isHttpsUrl","url","parseAgentCardJson","json","effectiveEntryName","typed","values","cardName","effectiveEntryDescription","cardDescription","validateRegistryForm","issues","cardCheck","name","wellKnownUrl","identityRows","selectAgents","data","useA2AAgents","workspaceId","useWorkspaceId","search","filter","status","visibility","trustLevel","bucketId","variables","useMemo","result","useWorkspacePaginatedQuery","ListA2ARegistryEntriesDocument","useA2AAgent","agentId","useWorkspaceQuery","GetA2ARegistryEntryDocument","useRegisterA2AAgent","useCallback","buildMutationInput","input","useWorkspaceMutation","CreateA2ARegistryEntryDocument","useUpdateA2AAgent","UpdateA2ARegistryEntryDocument","useDeleteA2AAgent","DeleteA2ARegistryEntryDocument"],"sources":["../../../src/botlit/hooks/useA2A.ts"],"sourcesContent":["/**\n * A2A Registry Hooks\n * @module botlit/hooks\n *\n * Backed by the live `listA2ARegistryEntries` / `getA2ARegistryEntry`\n * operations and the create/update/delete mutations on wspace-botlit-svc.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport {\n CreateA2ARegistryEntryDocument,\n DeleteA2ARegistryEntryDocument,\n GetA2ARegistryEntryDocument,\n ListA2ARegistryEntriesDocument,\n UpdateA2ARegistryEntryDocument,\n type CreateA2ARegistryEntryMutation,\n type DeleteA2ARegistryEntryMutation,\n type GetA2ARegistryEntryQuery,\n type ListA2ARegistryEntriesQuery,\n type UpdateA2ARegistryEntryMutation,\n} from '../../generated/wspace-operations';\nimport type {\n CreateA2ARegistryEntryInput,\n UpdateA2ARegistryEntryInput,\n} from '../../generated/wspace-types';\nimport type { A2AAgentFilter } from '../types';\nimport { buildMutationInput, fieldsOf, type GraphQLInput } from './internal/mutationInput';\nimport {\n useWorkspaceId,\n useWorkspaceMutation,\n useWorkspacePaginatedQuery,\n useWorkspaceQuery,\n type PaginatedQueryResult,\n type QueryResult,\n} from './internal/workspaceGateway';\n\n/** Page size for the registry list; further pages load on demand (BOFF-12509). */\nexport const A2A_LIST_PAGE_SIZE = 50;\n\n/** Field limits for a registry entry (BOFF-12508). The name column is VARCHAR(255). */\nexport const A2A_NAME_MAX = 255;\nexport const A2A_DESCRIPTION_MAX = 2000;\nexport const A2A_URL_MAX = 2048;\n/** The service refuses an agent card larger than 1 MiB. */\nexport const A2A_AGENT_CARD_MAX_BYTES = 1024 * 1024;\n\nexport interface A2AAgentRecord {\n id: string;\n name: string;\n status: string;\n visibility: string;\n trustLevel: string;\n /** A2A agent card (the `/.well-known/agent.json` document). */\n agentCard: Record<string, unknown>;\n entitlements: Record<string, unknown> | unknown[];\n description?: string | null;\n wellKnownUrl?: string | null;\n bucketId?: string | null;\n metadata?: Record<string, unknown> | null;\n revision: number;\n tags: string[];\n createdAt: string;\n updatedAt: string;\n createdById: string;\n updatedById: string;\n workspaceId: string;\n}\n\n/** `CreateA2ARegistryEntryInput` minus the `workspaceId` the hook supplies. */\nexport type RegisterA2AAgentVariables = Omit<\n GraphQLInput<CreateA2ARegistryEntryInput>,\n 'workspaceId'\n>;\n\nexport interface UpdateA2AAgentVariables {\n agentId: string;\n input: GraphQLInput<UpdateA2ARegistryEntryInput>;\n}\n\nconst REGISTER_AGENT_FIELDS = fieldsOf<CreateA2ARegistryEntryInput>({\n agentCard: true,\n bucketId: true,\n description: true,\n entitlements: true,\n metadata: true,\n name: true,\n status: true,\n tags: true,\n trustLevel: true,\n visibility: true,\n wellKnownUrl: true,\n workspaceId: true,\n});\n\nconst UPDATE_AGENT_FIELDS = fieldsOf<UpdateA2ARegistryEntryInput>({\n agentCard: true,\n bucketId: true,\n description: true,\n entitlements: true,\n metadata: true,\n name: true,\n status: true,\n tags: true,\n trustLevel: true,\n visibility: true,\n wellKnownUrl: true,\n});\n\n/** One validation problem, as a translation key plus its English fallback. */\nexport interface A2AValidationIssue {\n key: string;\n fallback: string;\n params?: Record<string, string | number>;\n}\n\nexport interface AgentCardValidation {\n valid: boolean;\n errors: A2AValidationIssue[];\n}\n\n/**\n * The agent-card fields the UI renders. `agentCard` is a free-form `JSON`\n * column on the service, so every field is read defensively — a card that is\n * missing `capabilities`, or that stores `skills` as an object instead of an\n * array, must render as \"not supported\"/\"none\" rather than throw.\n */\nexport interface A2AAgentCardView {\n url: string;\n version: string;\n providerOrganization: string;\n documentationUrl: string;\n capabilities: {\n streaming: boolean;\n pushNotifications: boolean;\n stateTransitionHistory: boolean;\n };\n authenticationSchemes: string[];\n defaultInputModes: string[];\n defaultOutputModes: string[];\n skills: A2AAgentCardSkill[];\n}\n\nexport interface A2AAgentCardSkill {\n id: string;\n name: string;\n description: string;\n tags: string[];\n examples: string[];\n}\n\n/**\n * The permissions the service checks on a registry entry's entitlements\n * (`A2AEntitlementService`): a connection needs `agent:delegate` or\n * `task:create`, and a task sent to the entry needs `task:create`.\n */\nexport const A2A_ENTITLEMENT_PERMISSIONS = ['agent:delegate', 'task:create'] as const;\nexport type A2AEntitlementPermission = (typeof A2A_ENTITLEMENT_PERMISSIONS)[number];\n\n/**\n * One row of the `entitlements` JSON in the shape the service enforces\n * (BOFF-12506): a permission, an optional list of local sender agents it is\n * limited to, and an optional validity window. A row without a permission is\n * ignored by the service, so it is flagged `recognised: false` instead of\n * being shown as if it granted anything.\n */\nexport interface A2AEntitlementView {\n id: string;\n recognised: boolean;\n permission: string;\n /** Local agents that may use this grant; empty means every agent in the workspace. */\n agentIds: string[];\n validFrom?: string;\n validUntil?: string;\n /**\n * Fields the service stores but does not enforce on an A2A call (bucket, app\n * and knowledge-base scope, rate limits). Kept on save, listed read-only.\n */\n unenforced: string[];\n}\n\n/** Editable form of one entitlement. Dates are `YYYY-MM-DD` (empty = open-ended). */\nexport interface A2AEntitlementDraft {\n permission: A2AEntitlementPermission;\n agentIds: string[];\n validFrom: string;\n validUntil: string;\n /** The original JSON row, so fields the editor does not show survive a save. */\n original?: Record<string, unknown>;\n}\n\nconst NO_AGENTS: A2AAgentRecord[] = [];\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction asString(value: unknown, fallback = ''): string {\n return typeof value === 'string' ? value : fallback;\n}\n\nfunction asBoolean(value: unknown): boolean {\n return value === true;\n}\n\nfunction asStringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === 'string')\n : [];\n}\n\nfunction asObjectArray(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value) ? value.map(asRecord) : [];\n}\n\n/** Reads the renderable view of an A2A agent card out of its JSON document. */\nexport function readAgentCard(card: Record<string, unknown> | undefined): A2AAgentCardView {\n const source = asRecord(card);\n const capabilities = asRecord(source.capabilities);\n const authentication = asRecord(source.authentication);\n\n return {\n url: asString(source.url),\n version: asString(source.version),\n providerOrganization: asString(asRecord(source.provider).organization),\n documentationUrl: asString(source.documentationUrl),\n capabilities: {\n streaming: asBoolean(capabilities.streaming),\n pushNotifications: asBoolean(capabilities.pushNotifications),\n stateTransitionHistory: asBoolean(capabilities.stateTransitionHistory),\n },\n authenticationSchemes: asStringArray(authentication.schemes),\n defaultInputModes: asStringArray(source.defaultInputModes),\n defaultOutputModes: asStringArray(source.defaultOutputModes),\n skills: asObjectArray(source.skills).map((skill, index) => ({\n id: asString(skill.id, `skill-${index}`),\n name: asString(skill.name),\n description: asString(skill.description),\n tags: asStringArray(skill.tags),\n examples: asStringArray(skill.examples),\n })),\n };\n}\n\nconst UNENFORCED_SCOPE_KEYS = ['bucketIds', 'appIds', 'knowledgeBaseIds'] as const;\n\nfunction unenforcedFields(entitlement: Record<string, unknown>): string[] {\n const scope = asRecord(entitlement.scope);\n const fields: string[] = UNENFORCED_SCOPE_KEYS.filter(\n (key) => asStringArray(scope[key]).length > 0\n ).map((key) => `scope.${key}`);\n if (Object.keys(asRecord(entitlement.rateLimit)).length > 0) fields.push('rateLimit');\n return fields;\n}\n\n/** Reads the entitlement rows out of the `entitlements` JSON column. */\nexport function readEntitlements(\n entitlements: Record<string, unknown> | unknown[] | null | undefined\n): A2AEntitlementView[] {\n return asObjectArray(entitlements).map((entitlement, index) => {\n const permission = asString(entitlement.permission).trim().toLowerCase();\n const validFrom = asString(entitlement.validFrom);\n const validUntil = asString(entitlement.validUntil);\n return {\n id: `entitlement-${index}`,\n recognised: permission.length > 0,\n permission,\n agentIds: asStringArray(asRecord(entitlement.scope).agentIds),\n validFrom: validFrom || undefined,\n validUntil: validUntil || undefined,\n unenforced: unenforcedFields(entitlement),\n };\n });\n}\n\nfunction toDateInput(value: string | undefined): string {\n if (!value) return '';\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? new Date(parsed).toISOString().slice(0, 10) : '';\n}\n\nfunction isEntitlementPermission(value: string): value is A2AEntitlementPermission {\n return (A2A_ENTITLEMENT_PERMISSIONS as readonly string[]).includes(value);\n}\n\n/**\n * Editable drafts for the entitlements the service recognises. Rows it ignores\n * (no permission, or a permission it never checks) are not editable here;\n * `toEntitlementsInput` keeps them untouched.\n */\nexport function toEntitlementDrafts(\n entitlements: Record<string, unknown> | unknown[] | null | undefined\n): A2AEntitlementDraft[] {\n const rows = asObjectArray(entitlements);\n return readEntitlements(entitlements).flatMap((view, index) =>\n view.recognised && isEntitlementPermission(view.permission)\n ? [\n {\n permission: view.permission,\n agentIds: view.agentIds,\n validFrom: toDateInput(view.validFrom),\n validUntil: toDateInput(view.validUntil),\n original: rows[index],\n },\n ]\n : []\n );\n}\n\n/**\n * Rows of the stored JSON the editor does not manage, so a save from the\n * editor does not silently drop them.\n */\nexport function unmanagedEntitlements(\n entitlements: Record<string, unknown> | unknown[] | null | undefined\n): Record<string, unknown>[] {\n const rows = asObjectArray(entitlements);\n return readEntitlements(entitlements).flatMap((view, index) =>\n view.recognised && isEntitlementPermission(view.permission) ? [] : [rows[index]]\n );\n}\n\n/**\n * Serialises edited entitlements to the JSON the service enforces. A newly\n * chosen start date begins at 00:00 UTC and an end date runs to the end of\n * that UTC day; an unchanged stored timestamp is kept as it was.\n */\nexport function toEntitlementsInput(\n drafts: A2AEntitlementDraft[],\n unmanaged: Record<string, unknown>[] = []\n): Record<string, unknown>[] {\n const edited = drafts.map((draft) => {\n const row: Record<string, unknown> = { ...(draft.original ?? {}) };\n row.permission = draft.permission;\n const scope = { ...asRecord(row.scope) };\n if (draft.agentIds.length > 0) scope.agentIds = draft.agentIds;\n else delete scope.agentIds;\n if (Object.keys(scope).length > 0) row.scope = scope;\n else delete row.scope;\n // A stored timestamp whose day was not changed is kept exactly: the editor\n // works in days, and rewriting 12:00 as 23:59:59 would quietly extend it.\n const original = draft.original ?? {};\n const keep = (field: 'validFrom' | 'validUntil') => {\n const stored = asString(original[field]);\n return stored && toDateInput(stored) === draft[field] ? stored : undefined;\n };\n if (draft.validFrom) row.validFrom = keep('validFrom') ?? `${draft.validFrom}T00:00:00.000Z`;\n else delete row.validFrom;\n if (draft.validUntil)\n row.validUntil = keep('validUntil') ?? `${draft.validUntil}T23:59:59.999Z`;\n else delete row.validUntil;\n return row;\n });\n return [...edited, ...unmanaged];\n}\n\n/** Per-draft validation: an end date must not come before the start date. */\nexport function entitlementDraftError(draft: A2AEntitlementDraft): 'validityOrder' | undefined {\n if (draft.validFrom && draft.validUntil && draft.validUntil < draft.validFrom) {\n return 'validityOrder';\n }\n return undefined;\n}\n\n/**\n * True when at least one entitlement, valid now, lets a connection be made —\n * the service refuses every connection to an entry without one (default deny).\n */\nexport function entitlementsAllowConnections(\n entitlements: Record<string, unknown> | unknown[] | null | undefined,\n now: number = Date.now()\n): boolean {\n const isActive = (view: A2AEntitlementView) => {\n const from = view.validFrom ? Date.parse(view.validFrom) : NaN;\n const until = view.validUntil ? Date.parse(view.validUntil) : NaN;\n return !(Number.isFinite(from) && now < from) && !(Number.isFinite(until) && now > until);\n };\n return readEntitlements(entitlements).some(\n (view) => view.recognised && isEntitlementPermission(view.permission) && isActive(view)\n );\n}\n\n/** Number of skills the registered agent card advertises. */\nexport function a2aAgentSkillCount(agent: Pick<A2AAgentRecord, 'agentCard'>): number {\n const skills = agent.agentCard?.skills;\n return Array.isArray(skills) ? skills.length : 0;\n}\n\n/**\n * Structural check of an A2A agent card before it is registered. This validates\n * the document the caller supplies — it does NOT contact the remote agent.\n */\nexport function validateAgentCard(card: Record<string, unknown> | undefined): AgentCardValidation {\n const errors: A2AValidationIssue[] = [];\n if (!card) {\n return {\n valid: false,\n errors: [\n {\n key: 'botlit.a2aRegistry.validation.cardRequired',\n fallback: 'An agent card is required',\n },\n ],\n };\n }\n for (const field of ['name', 'description', 'url', 'version'] as const) {\n if (typeof card[field] !== 'string' || (card[field] as string).trim() === '') {\n errors.push({\n key: 'botlit.a2aRegistry.validation.cardMissingField',\n fallback: 'Agent card is missing \"{{field}}\"',\n params: { field },\n });\n }\n }\n if (typeof card.url === 'string' && card.url.trim() !== '' && !isHttpsUrl(card.url)) {\n errors.push({\n key: 'botlit.a2aRegistry.validation.cardUrlHttps',\n fallback: 'The card\\'s \"url\" must be an https:// address',\n });\n }\n if (!Array.isArray(card.skills) || card.skills.length === 0) {\n errors.push({\n key: 'botlit.a2aRegistry.validation.cardNoSkills',\n fallback: 'Agent card must advertise at least one skill',\n });\n }\n return { valid: errors.length === 0, errors };\n}\n\n/** True for an absolute `https://` URL with a host. */\nexport function isHttpsUrl(value: string): boolean {\n try {\n const url = new URL(value.trim());\n return url.protocol === 'https:' && url.hostname.length > 0;\n } catch {\n return false;\n }\n}\n\n/** The registry form as the page edits it. */\nexport interface A2ARegistryFormValues {\n name: string;\n description: string;\n wellKnownUrl: string;\n agentCardJson: string;\n}\n\nexport type A2ARegistryFormField = 'name' | 'description' | 'wellKnownUrl' | 'agentCardJson';\n\n/** Parses the edited agent card; returns undefined when the JSON is malformed. */\nexport function parseAgentCardJson(json: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(json);\n return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The name the entry is saved with: the typed name, or the card's own name\n * when the field is left empty (BOFF-12510), so the list and the card agree\n * unless the user deliberately overrides it.\n */\nexport function effectiveEntryName(values: A2ARegistryFormValues): string {\n const typed = values.name.trim();\n if (typed) return typed;\n const cardName = parseAgentCardJson(values.agentCardJson)?.name;\n return typeof cardName === 'string' ? cardName.trim() : '';\n}\n\n/** The description the entry is saved with (typed, else the card's). */\nexport function effectiveEntryDescription(values: A2ARegistryFormValues): string {\n const typed = values.description.trim();\n if (typed) return typed;\n const cardDescription = parseAgentCardJson(values.agentCardJson)?.description;\n return typeof cardDescription === 'string' ? cardDescription.trim() : '';\n}\n\n/**\n * Field-level validation for the register/edit form (BOFF-12508). Returns at\n * most one issue per field, so each can be shown inline next to its input.\n */\nexport function validateRegistryForm(\n values: A2ARegistryFormValues\n): Partial<Record<A2ARegistryFormField, A2AValidationIssue>> {\n const issues: Partial<Record<A2ARegistryFormField, A2AValidationIssue>> = {};\n\n const card = parseAgentCardJson(values.agentCardJson);\n if (!values.agentCardJson.trim()) {\n issues.agentCardJson = {\n key: 'botlit.a2aRegistry.validation.cardRequired',\n fallback: 'An agent card is required',\n };\n } else if (new TextEncoder().encode(values.agentCardJson).length > A2A_AGENT_CARD_MAX_BYTES) {\n issues.agentCardJson = {\n key: 'botlit.a2aRegistry.validation.cardTooLarge',\n fallback: 'The agent card must be at most 1 MiB',\n };\n } else if (!card) {\n issues.agentCardJson = {\n key: 'botlit.a2aRegistry.validation.cardInvalidJson',\n fallback: 'Agent card must be a valid JSON object',\n };\n } else {\n const cardCheck = validateAgentCard(card);\n if (!cardCheck.valid) issues.agentCardJson = cardCheck.errors[0];\n }\n\n const name = effectiveEntryName(values);\n if (!name) {\n issues.name = {\n key: 'botlit.a2aRegistry.validation.nameRequired',\n fallback: 'Enter a name, or paste a card that has one',\n };\n } else if (name.length > A2A_NAME_MAX) {\n issues.name = {\n key: 'botlit.a2aRegistry.validation.nameTooLong',\n fallback: 'Name must be at most {{max}} characters',\n params: { max: A2A_NAME_MAX },\n };\n }\n\n if (effectiveEntryDescription(values).length > A2A_DESCRIPTION_MAX) {\n issues.description = {\n key: 'botlit.a2aRegistry.validation.descriptionTooLong',\n fallback: 'Description must be at most {{max}} characters',\n params: { max: A2A_DESCRIPTION_MAX },\n };\n }\n\n const wellKnownUrl = values.wellKnownUrl.trim();\n if (wellKnownUrl) {\n if (wellKnownUrl.length > A2A_URL_MAX) {\n issues.wellKnownUrl = {\n key: 'botlit.a2aRegistry.validation.urlTooLong',\n fallback: 'URL must be at most {{max}} characters',\n params: { max: A2A_URL_MAX },\n };\n } else if (!isHttpsUrl(wellKnownUrl)) {\n issues.wellKnownUrl = {\n key: 'botlit.a2aRegistry.validation.wellKnownHttps',\n fallback: 'Enter an https:// URL, e.g. https://agent.example.com/.well-known/agent.json',\n };\n }\n }\n\n return issues;\n}\n\nfunction identityRows(rows: A2AAgentRecord[]): A2AAgentRecord[] {\n return rows;\n}\n\nfunction selectAgents(data: ListA2ARegistryEntriesQuery | undefined): A2AAgentRecord[] {\n return data?.listA2ARegistryEntries ?? NO_AGENTS;\n}\n\nexport const a2aKeys = {\n all: ['a2a'] as const,\n lists: () => [...a2aKeys.all, 'list'] as const,\n list: (filter?: A2AAgentFilter) => [...a2aKeys.lists(), filter] as const,\n details: () => [...a2aKeys.all, 'detail'] as const,\n detail: (id: string) => [...a2aKeys.details(), id] as const,\n};\n\n/**\n * The registry list, one page at a time (BOFF-12509). Status, trust level,\n * visibility and bucket filter on the server. The service has no free-text\n * filter, so `search` narrows the rows loaded so far; the page keeps loading\n * further pages while a search is active, so a match is never hidden behind\n * an unloaded page.\n */\nexport function useA2AAgents(filter?: A2AAgentFilter): PaginatedQueryResult<A2AAgentRecord[]> {\n const workspaceId = useWorkspaceId();\n const search = filter?.search?.trim().toLowerCase() ?? '';\n const status = filter?.status?.[0];\n const visibility = filter?.visibility?.[0];\n const trustLevel = filter?.trustLevel?.[0];\n const bucketId = filter?.bucketId;\n\n const variables = useMemo(\n () => ({ filters: { workspaceId, status, visibility, trustLevel, bucketId } }),\n [workspaceId, status, visibility, trustLevel, bucketId]\n );\n\n const result = useWorkspacePaginatedQuery<\n ListA2ARegistryEntriesQuery,\n A2AAgentRecord,\n A2AAgentRecord[]\n >({\n document: ListA2ARegistryEntriesDocument,\n variables,\n pageSize: A2A_LIST_PAGE_SIZE,\n extractRows: selectAgents,\n select: identityRows,\n fallback: NO_AGENTS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load the A2A registry',\n });\n\n // Narrowed here, not in `select`: the paginated hook applies `select` only\n // when a page arrives, and a new search term must re-filter the loaded rows.\n const rows = result.data;\n const data = useMemo(\n () =>\n search\n ? rows.filter(\n (row) =>\n row.name.toLowerCase().includes(search) ||\n (row.description ?? '').toLowerCase().includes(search)\n )\n : rows,\n [rows, search]\n );\n\n return { ...result, data };\n}\n\nexport function useA2AAgent(agentId: string | undefined): QueryResult<A2AAgentRecord | null> {\n const variables = useMemo(() => ({ id: agentId ?? '' }), [agentId]);\n\n return useWorkspaceQuery<GetA2ARegistryEntryQuery, A2AAgentRecord | null>({\n document: GetA2ARegistryEntryDocument,\n variables,\n select: (data) => data?.getA2ARegistryEntry ?? null,\n fallback: null,\n enabled: Boolean(agentId),\n errorMessage: 'Failed to load A2A agent',\n });\n}\n\nexport function useRegisterA2AAgent() {\n const workspaceId = useWorkspaceId();\n\n const variables = useCallback(\n (input: RegisterA2AAgentVariables) => ({\n input: buildMutationInput({ ...input, workspaceId }, REGISTER_AGENT_FIELDS),\n }),\n [workspaceId]\n );\n\n return useWorkspaceMutation<\n CreateA2ARegistryEntryMutation,\n RegisterA2AAgentVariables,\n A2AAgentRecord\n >({\n document: CreateA2ARegistryEntryDocument,\n variables,\n select: (data) => data?.createA2ARegistryEntry,\n errorMessage: 'Failed to register A2A agent',\n });\n}\n\nexport function useUpdateA2AAgent() {\n return useWorkspaceMutation<\n UpdateA2ARegistryEntryMutation,\n UpdateA2AAgentVariables,\n A2AAgentRecord\n >({\n document: UpdateA2ARegistryEntryDocument,\n variables: ({ agentId, input }) => ({\n id: agentId,\n input: buildMutationInput(input, UPDATE_AGENT_FIELDS),\n }),\n select: (data) => data?.updateA2ARegistryEntry,\n errorMessage: 'Failed to update A2A agent',\n });\n}\n\nexport function useDeleteA2AAgent() {\n return useWorkspaceMutation<DeleteA2ARegistryEntryMutation, string, boolean>({\n document: DeleteA2ARegistryEntryDocument,\n variables: (agentId) => ({ id: agentId }),\n select: (data) => data?.deleteA2ARegistryEntry,\n errorMessage: 'Failed to remove A2A agent',\n });\n}\n\n/**\n * Validates an agent card locally before registration. There is no server-side\n * validation operation, so this deliberately reports only what can be checked\n * from the document itself.\n */\nexport function useValidateA2AAgent() {\n const validate = useCallback(\n async (card: Record<string, unknown> | undefined): Promise<AgentCardValidation> =>\n validateAgentCard(card),\n []\n );\n\n return [validate, { loading: false, error: undefined }] as const;\n}\n"],"mappings":";;;;AAyCA,IAAaA,IAAsB,KACtBC,IAAc,MAEdC,IAA2B,SAmClCC,IAAwBC,EAAsC;CAClE,WAAW;CACX,UAAU;CACV,aAAa;CACb,cAAc;CACd,UAAU;CACV,MAAM;CACN,QAAQ;CACR,MAAM;CACN,YAAY;CACZ,YAAY;CACZ,cAAc;CACd,aAAa;AACf,CAAC,GAEKC,IAAsBD,EAAsC;CAChE,WAAW;CACX,UAAU;CACV,aAAa;CACb,cAAc;CACd,UAAU;CACV,MAAM;CACN,QAAQ;CACR,MAAM;CACN,YAAY;CACZ,YAAY;CACZ,cAAc;AAChB,CAAC,GAiDYE,IAA8B,CAAC,kBAAkB,aAAa,GAmCrEC,IAA8B,CAAC;AAErC,SAASC,EAAS,GAAyC;CACzD,OAAO,OAAOC,KAAU,YAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK,IACrEA,IACD,CAAC;AACP;AAEA,SAASC,EAAS,GAAgB,IAAW,IAAY;CACvD,OAAO,OAAOD,KAAU,WAAWA,IAAQE;AAC7C;AAEA,SAASC,EAAU,GAAyB;CAC1C,OAAOH,MAAU;AACnB;AAEA,SAASI,EAAc,GAA0B;CAC/C,OAAO,MAAM,QAAQJ,CAAK,IACtBA,EAAM,QAAQ,MAA2B,OAAOK,KAAU,QAAQ,IAClE,CAAC;AACP;AAEA,SAASC,EAAc,GAA2C;CAChE,OAAO,MAAM,QAAQN,CAAK,IAAIA,EAAM,IAAID,CAAQ,IAAI,CAAC;AACvD;AAGA,SAAgBQ,EAAc,GAA6D;CACzF,IAAMC,IAAST,EAASU,CAAI,GACtBC,IAAeX,EAASS,EAAO,YAAY,GAC3CG,IAAiBZ,EAASS,EAAO,cAAc;CAErD,OAAO;EACL,KAAKP,EAASO,EAAO,GAAG;EACxB,SAASP,EAASO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EAIL;EACA,UAAUC;EACV;EACA,SAAS,MAASxB,GAAM;EACxB,cAAc;CAChB,CAAC;AACH;AAEA,SAAgByB,IAAoB;CAClC,OAAOF,EAIL;EACA,UAAUG;EACV,YAAY,EAAE,YAAS,gBAAa;GAClC,IAAIV;GACJ,OAAOK,EAAmBC,GAAO/F,CAAmB;EACtD;EACA,SAAS,MAASyE,GAAM;EACxB,cAAc;CAChB,CAAC;AACH;AAEA,SAAgB2B,IAAoB;CAClC,OAAOJ,EAAsE;EAC3E,UAAUK;EACV,YAAY,OAAa,EAAE,IAAIZ,EAAQ;EACvC,SAAS,MAAShB,GAAM;EACxB,cAAc;CAChB,CAAC;AACH"}
@@ -11,7 +11,8 @@
11
11
  *
12
12
  * These hooks let the connector form create that channel with its credentials
13
13
  * and the detail page show its inbound URL, all through the shell's global
14
- * gateway client. The documents are written inline, like `GetChannels` in
14
+ * gateway client, scoped to the active workspace's organization (see
15
+ * `internal/globalWorkspaceScope`). The documents are written inline, like `GetChannels` in
15
16
  * `useUserPlatformConnection`: `inboundWebhookUrl` / `inboundWorkspaceId` are
16
17
  * newer than the checked-in `graphql/global.graphql`, which cannot be
17
18
  * re-pulled while gateway introspection is disabled.
@@ -1,8 +1,8 @@
1
1
  import { useBotlit as e } from "../providers/BotlitProvider.js";
2
2
  import { extractGraphqlFailureMessage as t } from "../utils/errors.js";
3
- import { useCallback as n, useEffect as r, useRef as i, useState as a } from "react";
4
- import { gql as o } from "@apollo/client";
5
- import { useGatewayClient as s } from "@burdenoff/fe-libs/shared/graphql";
3
+ import { useWorkspaceScopedGlobalClient as n } from "./internal/globalWorkspaceScope.js";
4
+ import { useCallback as r, useEffect as i, useRef as a, useState as o } from "react";
5
+ import { gql as s } from "@apollo/client";
6
6
  // src/botlit/hooks/useChannelSetup.ts
7
7
  var c = {
8
8
  SLACK: {
@@ -76,7 +76,7 @@ function f(e, t) {
76
76
  function p() {
77
77
  return e().organizationId || null;
78
78
  }
79
- var m = o`
79
+ var m = s`
80
80
  query BotmanorInboundChannel($id: ID!) {
81
81
  getChannel(id: $id) {
82
82
  id
@@ -88,19 +88,19 @@ var m = o`
88
88
  inboundWebhookUrl
89
89
  }
90
90
  }
91
- `, h = o`
91
+ `, h = s`
92
92
  mutation BotmanorCreateSetupChannel($input: CreateChannelInput!) {
93
93
  createChannel(input: $input) {
94
94
  id
95
95
  }
96
96
  }
97
- `, g = o`
97
+ `, g = s`
98
98
  mutation BotmanorCreateSetupConnection($input: CreateConnectionInput!) {
99
99
  createConnection(input: $input) {
100
100
  id
101
101
  }
102
102
  }
103
- `, _ = o`
103
+ `, _ = s`
104
104
  mutation BotmanorDeleteSetupChannel($id: ID!) {
105
105
  deleteChannel(id: $id)
106
106
  }
@@ -113,87 +113,96 @@ function y(e, t) {
113
113
  let n = e.error;
114
114
  if (n != null) throw v(n, t);
115
115
  }
116
- function b() {
117
- return s("global");
118
- }
119
- function x(e) {
120
- let t = b(), [o, s] = a(null), [c, l] = a(!1), [u, d] = a(void 0), f = i(0), p = n(async () => {
121
- let n = ++f.current, r = () => n === f.current;
122
- if (s(null), d(void 0), e) {
123
- l(!0);
116
+ function b(e) {
117
+ let { client: t, context: s } = n(), [c, l] = o(null), [u, d] = o(!1), [f, p] = o(void 0), h = a(0), g = r(async () => {
118
+ let n = ++h.current, r = () => n === h.current;
119
+ if (l(null), p(void 0), e) {
120
+ d(!0);
124
121
  try {
125
122
  let n = await t.query({
126
123
  query: m,
127
124
  variables: { id: e },
128
- fetchPolicy: "network-only"
125
+ fetchPolicy: "network-only",
126
+ context: s
129
127
  });
130
- y(n, "Failed to load the channel"), r() && s(n.data?.getChannel ?? null);
128
+ y(n, "Failed to load the channel"), r() && l(n.data?.getChannel ?? null);
131
129
  } catch (e) {
132
- r() && d(v(e, "Failed to load the channel"));
130
+ r() && p(v(e, "Failed to load the channel"));
133
131
  } finally {
134
- r() && l(!1);
132
+ r() && d(!1);
135
133
  }
136
134
  }
137
- }, [e, t]);
138
- return r(() => {
139
- p();
140
- }, [p]), {
141
- data: o,
142
- loading: c,
143
- error: u,
144
- refetch: p
135
+ }, [
136
+ e,
137
+ t,
138
+ s
139
+ ]);
140
+ return i(() => {
141
+ g();
142
+ }, [g]), {
143
+ data: c,
144
+ loading: u,
145
+ error: f,
146
+ refetch: g
145
147
  };
146
148
  }
147
- function S() {
148
- let e = b(), [t, r] = a(!1), i = n(async (t) => {
149
+ function x() {
150
+ let { client: e, context: t } = n(), [i, a] = o(!1), s = r(async (n) => {
149
151
  y(await e.mutate({
150
152
  mutation: _,
151
- variables: { id: t }
153
+ variables: { id: n },
154
+ context: t
152
155
  }), "Failed to delete the channel");
153
- }, [e]);
156
+ }, [e, t]);
154
157
  return {
155
- provision: n(async ({ name: t, description: n, organizationId: a, definition: o, credentials: s }) => {
156
- r(!0);
158
+ provision: r(async ({ name: n, description: r, organizationId: i, definition: o, credentials: c }) => {
159
+ a(!0);
157
160
  try {
158
- let r;
161
+ let a;
159
162
  try {
160
- let i = await e.mutate({
163
+ let s = await e.mutate({
161
164
  mutation: h,
162
165
  variables: { input: {
163
- name: t,
164
- description: n || void 0,
166
+ name: n,
167
+ description: r || void 0,
165
168
  platform: o.platform,
166
169
  channelType: "COMMUNICATION",
167
- organizationId: a
168
- } }
170
+ organizationId: i
171
+ } },
172
+ context: t
169
173
  });
170
- y(i, "Failed to create the channel"), r = i.data?.createChannel?.id;
174
+ y(s, "Failed to create the channel"), a = s.data?.createChannel?.id;
171
175
  } catch (e) {
172
176
  throw v(e, "Failed to create the channel");
173
177
  }
174
- if (!r) throw Error("Failed to create the channel");
175
- let c = Object.fromEntries(o.fields.map((e) => [e.key, s[e.key]?.trim() ?? ""]));
178
+ if (!a) throw Error("Failed to create the channel");
179
+ let l = Object.fromEntries(o.fields.map((e) => [e.key, c[e.key]?.trim() ?? ""]));
176
180
  try {
177
181
  y(await e.mutate({
178
182
  mutation: g,
179
183
  variables: { input: {
180
- channelId: r,
184
+ channelId: a,
181
185
  authType: o.authType,
182
- credentials: c
183
- } }
186
+ credentials: l
187
+ } },
188
+ context: t
184
189
  }), "Failed to save the channel credentials");
185
190
  } catch (e) {
186
- throw await i(r).catch(() => void 0), v(e, "Failed to save the channel credentials");
191
+ throw await s(a).catch(() => void 0), v(e, "Failed to save the channel credentials");
187
192
  }
188
- return r;
193
+ return a;
189
194
  } finally {
190
- r(!1);
195
+ a(!1);
191
196
  }
192
- }, [e, i]),
193
- discard: i,
194
- loading: t
197
+ }, [
198
+ e,
199
+ t,
200
+ s
201
+ ]),
202
+ discard: s,
203
+ loading: i
195
204
  };
196
205
  }
197
- export { c as PLATFORM_CREDENTIALS, u as connectorPlatform, d as generateSigningSecret, p as useActiveOrganizationId, x as useInboundChannel, S as useProvisionChannel, f as validateCredentials };
206
+ export { c as PLATFORM_CREDENTIALS, u as connectorPlatform, d as generateSigningSecret, p as useActiveOrganizationId, b as useInboundChannel, x as useProvisionChannel, f as validateCredentials };
198
207
 
199
208
  //# sourceMappingURL=useChannelSetup.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useChannelSetup.js","names":["PLATFORM_CREDENTIALS","CONNECTOR_PLATFORM","connectorPlatform","connectorType","generateSigningSecret","bytes","byte","validateCredentials","field","definition","value","values","parsed","useActiveOrganizationId","useBotlit","GetInboundChannelDocument","CreateSetupChannelDocument","CreateSetupConnectionDocument","DeleteSetupChannelDocument","toError","message","extractGraphqlFailureMessage","cause","fallback","throwIfOperationFailed","operationError","result","useGlobalClient","useGatewayClient","useInboundChannel","client","data","setData","useState","loading","setLoading","error","setError","latestRequest","useRef","refetch","useCallback","request","isLatest","channelId","useEffect","useProvisionChannel","discard","created","description","trimmed","credentials"],"sources":["../../../src/botlit/hooks/useChannelSetup.ts"],"sourcesContent":["/**\n * Channel setup hooks (BOFF-15360)\n * @module botlit/hooks\n *\n * A BotManor channel connector names a channel on global-channel-svc through\n * `credentialsRefId`. That global channel holds the platform credentials (a\n * Slack bot token and signing secret, a webhook's signing secret and reply\n * URL, …) and publishes the public URL the platform must call with inbound\n * events (`Channel.inboundWebhookUrl`, set once an ACTIVE connector binds the\n * channel to this workspace).\n *\n * These hooks let the connector form create that channel with its credentials\n * and the detail page show its inbound URL, all through the shell's global\n * gateway client. The documents are written inline, like `GetChannels` in\n * `useUserPlatformConnection`: `inboundWebhookUrl` / `inboundWorkspaceId` are\n * newer than the checked-in `graphql/global.graphql`, which cannot be\n * re-pulled while gateway introspection is disabled.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { gql, type ApolloClient } from '@apollo/client';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\n\nimport { useBotlit } from '../providers/BotlitProvider';\nimport { extractGraphqlFailureMessage } from '../utils/errors';\n\n// ============================================================================\n// Platform credential definitions\n// ============================================================================\n\n/** Global-channel platforms a connector type delivers through. */\nexport type ChannelSetupPlatform = 'SLACK' | 'TEAMS' | 'DISCORD' | 'WHATSAPP' | 'WEBHOOK';\n\n/** `ChannelAuthType` values the setup form sends. */\ntype ChannelSetupAuthType = 'BOT_TOKEN' | 'WEBHOOK';\n\nexport interface CredentialFieldDefinition {\n /** Key stored on the channel connection's credentials. */\n key: string;\n label: string;\n description: string;\n placeholder: string;\n /** Rendered as a password input and never shown again after saving. */\n secret: boolean;\n /** Offer a \"Generate\" button producing a random 64-hex-character secret. */\n generatable?: boolean;\n /** Must be an absolute https URL. */\n url?: boolean;\n}\n\nexport interface PlatformCredentialDefinition {\n platform: ChannelSetupPlatform;\n authType: ChannelSetupAuthType;\n fields: CredentialFieldDefinition[];\n /** Where to paste the inbound webhook URL on the platform side. */\n inboundHint: string;\n}\n\n/**\n * Connector types whose credentials the form can collect directly. The keys\n * are the ones global-channel-svc reads: Slack sends with `botToken` and\n * verifies inbound requests with `signingSecret`; a generic webhook verifies\n * with `webhookSecret` (HMAC-SHA256 hex in `X-Signature`) and POSTs replies\n * to `targetUrl`.\n */\nexport const PLATFORM_CREDENTIALS: Readonly<Record<string, PlatformCredentialDefinition>> = {\n SLACK: {\n platform: 'SLACK',\n authType: 'BOT_TOKEN',\n fields: [\n {\n key: 'botToken',\n label: 'Bot User OAuth Token',\n description: 'Slack app → OAuth & Permissions. Starts with xoxb-.',\n placeholder: 'xoxb-…',\n secret: true,\n },\n {\n key: 'signingSecret',\n label: 'Signing Secret',\n description: 'Slack app → Basic Information → App Credentials.',\n placeholder: 'Signing secret',\n secret: true,\n },\n ],\n inboundHint:\n 'In your Slack app, open Event Subscriptions, turn events on and paste this as the Request URL. Subscribe the bot to message.channels, message.im and app_mention, then reinstall the app.',\n },\n WEBHOOK: {\n platform: 'WEBHOOK',\n authType: 'WEBHOOK',\n fields: [\n {\n key: 'targetUrl',\n label: 'Reply URL',\n description: 'The bot POSTs its replies to this https URL.',\n placeholder: 'https://example.com/bot-replies',\n secret: false,\n url: true,\n },\n {\n key: 'webhookSecret',\n label: 'Signing Secret',\n description:\n 'Your sender signs each request body with HMAC-SHA256 using this secret and sends the hex digest in the X-Signature header.',\n placeholder: 'Generate or paste a secret',\n secret: true,\n generatable: true,\n },\n ],\n inboundHint:\n 'POST each inbound message here as JSON ({\"event\":\"message\",\"id\",\"sender_id\",\"text\",\"conversation_id\"}), signed with the signing secret in the X-Signature header.',\n },\n};\n\n/** Connector type → the global-channel platform it uses (none for widget/custom). */\nconst CONNECTOR_PLATFORM: Readonly<Record<string, ChannelSetupPlatform>> = {\n SLACK: 'SLACK',\n TEAMS: 'TEAMS',\n DISCORD: 'DISCORD',\n WHATSAPP: 'WHATSAPP',\n WEBHOOK: 'WEBHOOK',\n};\n\nexport function connectorPlatform(connectorType: string): ChannelSetupPlatform | undefined {\n return CONNECTOR_PLATFORM[connectorType];\n}\n\n/** A random 32-byte secret, hex encoded, from the browser's CSPRNG. */\nexport function generateSigningSecret(): string {\n const bytes = new Uint8Array(32);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Returns the first problem with the entered credentials, or null when they\n * are complete. Every field is required.\n */\nexport function validateCredentials(\n definition: PlatformCredentialDefinition,\n values: Record<string, string>\n): string | null {\n for (const field of definition.fields) {\n const value = values[field.key]?.trim() ?? '';\n if (!value) return `${field.label} is required`;\n if (field.url) {\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n return `${field.label} must be a valid URL`;\n }\n if (parsed.protocol !== 'https:') return `${field.label} must use https`;\n }\n }\n return null;\n}\n\n// ============================================================================\n// Organization\n// ============================================================================\n\n/**\n * The shell's active organization (the host passes it with the workspace).\n * Global channels belong to an organization, so creating one needs it.\n */\nexport function useActiveOrganizationId(): string | null {\n return useBotlit().organizationId || null;\n}\n\n// ============================================================================\n// Documents\n// ============================================================================\n\nconst GetInboundChannelDocument = gql`\n query BotmanorInboundChannel($id: ID!) {\n getChannel(id: $id) {\n id\n name\n platform\n status\n isConnected\n inboundWorkspaceId\n inboundWebhookUrl\n }\n }\n`;\n\nconst CreateSetupChannelDocument = gql`\n mutation BotmanorCreateSetupChannel($input: CreateChannelInput!) {\n createChannel(input: $input) {\n id\n }\n }\n`;\n\nconst CreateSetupConnectionDocument = gql`\n mutation BotmanorCreateSetupConnection($input: CreateConnectionInput!) {\n createConnection(input: $input) {\n id\n }\n }\n`;\n\nconst DeleteSetupChannelDocument = gql`\n mutation BotmanorDeleteSetupChannel($id: ID!) {\n deleteChannel(id: $id)\n }\n`;\n\nexport interface InboundChannelData {\n id: string;\n name: string;\n platform: string;\n status: string;\n isConnected: boolean;\n inboundWorkspaceId: string | null;\n inboundWebhookUrl: string | null;\n}\n\nfunction toError(cause: unknown, fallback: string): Error {\n const message = extractGraphqlFailureMessage(cause);\n if (message) return new Error(message, { cause });\n return cause instanceof Error ? cause : new Error(fallback, { cause });\n}\n\n/**\n * Apollo v4 resolves (rather than rejects) with `error` set when the server\n * answers with GraphQL errors; surface those as a failure like a rejection.\n */\nfunction throwIfOperationFailed(result: unknown, fallback: string): void {\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) throw toError(operationError, fallback);\n}\n\nfunction useGlobalClient(): ApolloClient {\n return useGatewayClient('global');\n}\n\n// ============================================================================\n// Hook: useInboundChannel\n// ============================================================================\n\ninterface UseInboundChannelResult {\n data: InboundChannelData | null;\n loading: boolean;\n error: Error | undefined;\n refetch: () => Promise<void>;\n}\n\n/** The global channel a connector names, with its inbound webhook URL. */\nexport function useInboundChannel(channelId: string | null | undefined): UseInboundChannelResult {\n const client = useGlobalClient();\n const [data, setData] = useState<InboundChannelData | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n /** Only the latest request may set state: a slower answer for a previous channel is dropped. */\n const latestRequest = useRef(0);\n\n const refetch = useCallback(async () => {\n const request = ++latestRequest.current;\n const isLatest = () => request === latestRequest.current;\n setData(null);\n setError(undefined);\n if (!channelId) return;\n setLoading(true);\n try {\n const result = await client.query<{ getChannel: InboundChannelData | null }>({\n query: GetInboundChannelDocument,\n variables: { id: channelId },\n fetchPolicy: 'network-only',\n });\n throwIfOperationFailed(result, 'Failed to load the channel');\n if (isLatest()) setData(result.data?.getChannel ?? null);\n } catch (cause) {\n if (isLatest()) setError(toError(cause, 'Failed to load the channel'));\n } finally {\n if (isLatest()) setLoading(false);\n }\n }, [channelId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\n// ============================================================================\n// Hook: useProvisionChannel\n// ============================================================================\n\nexport interface ProvisionChannelInput {\n name: string;\n description?: string;\n organizationId: string;\n definition: PlatformCredentialDefinition;\n credentials: Record<string, string>;\n}\n\ninterface UseProvisionChannelResult {\n /** Creates the global channel and its connection; resolves to the channel id. */\n provision: (input: ProvisionChannelInput) => Promise<string>;\n /** Deletes a channel `provision` created (rollback when the connector fails). */\n discard: (channelId: string) => Promise<void>;\n loading: boolean;\n}\n\nexport function useProvisionChannel(): UseProvisionChannelResult {\n const client = useGlobalClient();\n const [loading, setLoading] = useState(false);\n\n const discard = useCallback(\n async (channelId: string) => {\n const result = await client.mutate({\n mutation: DeleteSetupChannelDocument,\n variables: { id: channelId },\n });\n throwIfOperationFailed(result, 'Failed to delete the channel');\n },\n [client]\n );\n\n const provision = useCallback(\n async ({\n name,\n description,\n organizationId,\n definition,\n credentials,\n }: ProvisionChannelInput): Promise<string> => {\n setLoading(true);\n try {\n let channelId: string | undefined;\n try {\n const created = await client.mutate<{ createChannel: { id: string } | null }>({\n mutation: CreateSetupChannelDocument,\n variables: {\n input: {\n name,\n description: description || undefined,\n platform: definition.platform,\n channelType: 'COMMUNICATION',\n organizationId,\n },\n },\n });\n throwIfOperationFailed(created, 'Failed to create the channel');\n channelId = created.data?.createChannel?.id;\n } catch (cause) {\n throw toError(cause, 'Failed to create the channel');\n }\n if (!channelId) throw new Error('Failed to create the channel');\n\n const trimmed = Object.fromEntries(\n definition.fields.map((field) => [field.key, credentials[field.key]?.trim() ?? ''])\n );\n try {\n const connected = await client.mutate({\n mutation: CreateSetupConnectionDocument,\n variables: {\n input: { channelId, authType: definition.authType, credentials: trimmed },\n },\n });\n throwIfOperationFailed(connected, 'Failed to save the channel credentials');\n } catch (cause) {\n // A channel without its credentials can never deliver: remove it so\n // a retry starts clean instead of leaving an orphan behind.\n await discard(channelId).catch(() => undefined);\n throw toError(cause, 'Failed to save the channel credentials');\n }\n return channelId;\n } finally {\n setLoading(false);\n }\n },\n [client, discard]\n );\n\n return { provision, discard, loading };\n}\n"],"mappings":";;;;;;AAiEA,IAAaA,IAA+E;CAC1F,OAAO;EACL,UAAU;EACV,UAAU;EACV,QAAQ,CACN;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,aAAa;GACb,QAAQ;EACV,GACA;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,aAAa;GACb,QAAQ;EACV,CACF;EACA,aACE;CACJ;CACA,SAAS;EACP,UAAU;EACV,UAAU;EACV,QAAQ,CACN;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,aAAa;GACb,QAAQ;GACR,KAAK;EACP,GACA;GACE,KAAK;GACL,OAAO;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,GACA,CAACd,CAAM,CACT;CA0DA,OAAO;EAAE,WAxDSW,EAChB,OAAO,EACL,SACA,gBACA,mBACA,eACA,qBAC4C;GAC5C,EAAW,EAAI;GACf,IAAI;IACF,IAAIG;IACJ,IAAI;KACF,IAAMI,IAAU,MAAMlB,EAAO,OAAiD;MAC5E,UAAUd;MACV,WAAW,EACT,OAAO;OACL;OACA,aAAaiC,KAAe,KAAA;OAC5B,UAAUxC,EAAW;OACrB,aAAa;OACb;MACF,EACF;KACF,CAAC;KAED,AADAe,EAAuBwB,GAAS,8BAA8B,GAC9D,IAAYA,EAAQ,MAAM,eAAe;IAC3C,SAAS1B,GAAO;KACd,MAAMH,EAAQG,GAAO,8BAA8B;IACrD;IACA,IAAI,CAACsB,GAAW,MAAU,MAAM,8BAA8B;IAE9D,IAAMM,IAAU,OAAO,YACrBzC,EAAW,OAAO,KAAK,MAAU,CAACD,EAAM,KAAK2C,EAAY3C,EAAM,IAAI,EAAE,KAAK,KAAK,EAAE,CAAC,CACpF;IACA,IAAI;KAOF,EAAuB,MANCsB,EAAO,OAAO;MACpC,UAAUb;MACV,WAAW,EACT,OAAO;OAAE;OAAW,UAAUR,EAAW;OAAU,aAAayC;MAAQ,EAC1E;KACF,CAAC,GACiC,wCAAwC;IAC5E,SAAS5B,GAAO;KAId,MADA,MAAMyB,EAAQH,CAAS,CAAC,CAAC,YAAY,KAAA,CAAS,GACxCzB,EAAQG,GAAO,wCAAwC;IAC/D;IACA,OAAOsB;GACT,UAAU;IACR,EAAW,EAAK;GAClB;EACF,GACA,CAACd,GAAQiB,CAAO,CAGT;EAAW;EAAS;CAAQ;AACvC"}
1
+ {"version":3,"file":"useChannelSetup.js","names":["PLATFORM_CREDENTIALS","CONNECTOR_PLATFORM","connectorPlatform","connectorType","generateSigningSecret","bytes","byte","validateCredentials","field","definition","value","values","parsed","useActiveOrganizationId","useBotlit","GetInboundChannelDocument","CreateSetupChannelDocument","CreateSetupConnectionDocument","DeleteSetupChannelDocument","toError","message","extractGraphqlFailureMessage","cause","fallback","throwIfOperationFailed","operationError","result","useInboundChannel","useWorkspaceScopedGlobalClient","data","setData","useState","loading","setLoading","error","setError","latestRequest","useRef","refetch","useCallback","request","isLatest","channelId","client","context","useEffect","useProvisionChannel","discard","created","description","trimmed","credentials"],"sources":["../../../src/botlit/hooks/useChannelSetup.ts"],"sourcesContent":["/**\n * Channel setup hooks (BOFF-15360)\n * @module botlit/hooks\n *\n * A BotManor channel connector names a channel on global-channel-svc through\n * `credentialsRefId`. That global channel holds the platform credentials (a\n * Slack bot token and signing secret, a webhook's signing secret and reply\n * URL, …) and publishes the public URL the platform must call with inbound\n * events (`Channel.inboundWebhookUrl`, set once an ACTIVE connector binds the\n * channel to this workspace).\n *\n * These hooks let the connector form create that channel with its credentials\n * and the detail page show its inbound URL, all through the shell's global\n * gateway client, scoped to the active workspace's organization (see\n * `internal/globalWorkspaceScope`). The documents are written inline, like `GetChannels` in\n * `useUserPlatformConnection`: `inboundWebhookUrl` / `inboundWorkspaceId` are\n * newer than the checked-in `graphql/global.graphql`, which cannot be\n * re-pulled while gateway introspection is disabled.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { gql } from '@apollo/client';\n\nimport { useBotlit } from '../providers/BotlitProvider';\nimport { extractGraphqlFailureMessage } from '../utils/errors';\nimport { useWorkspaceScopedGlobalClient } from './internal/globalWorkspaceScope';\n\n// ============================================================================\n// Platform credential definitions\n// ============================================================================\n\n/** Global-channel platforms a connector type delivers through. */\nexport type ChannelSetupPlatform = 'SLACK' | 'TEAMS' | 'DISCORD' | 'WHATSAPP' | 'WEBHOOK';\n\n/** `ChannelAuthType` values the setup form sends. */\ntype ChannelSetupAuthType = 'BOT_TOKEN' | 'WEBHOOK';\n\nexport interface CredentialFieldDefinition {\n /** Key stored on the channel connection's credentials. */\n key: string;\n label: string;\n description: string;\n placeholder: string;\n /** Rendered as a password input and never shown again after saving. */\n secret: boolean;\n /** Offer a \"Generate\" button producing a random 64-hex-character secret. */\n generatable?: boolean;\n /** Must be an absolute https URL. */\n url?: boolean;\n}\n\nexport interface PlatformCredentialDefinition {\n platform: ChannelSetupPlatform;\n authType: ChannelSetupAuthType;\n fields: CredentialFieldDefinition[];\n /** Where to paste the inbound webhook URL on the platform side. */\n inboundHint: string;\n}\n\n/**\n * Connector types whose credentials the form can collect directly. The keys\n * are the ones global-channel-svc reads: Slack sends with `botToken` and\n * verifies inbound requests with `signingSecret`; a generic webhook verifies\n * with `webhookSecret` (HMAC-SHA256 hex in `X-Signature`) and POSTs replies\n * to `targetUrl`.\n */\nexport const PLATFORM_CREDENTIALS: Readonly<Record<string, PlatformCredentialDefinition>> = {\n SLACK: {\n platform: 'SLACK',\n authType: 'BOT_TOKEN',\n fields: [\n {\n key: 'botToken',\n label: 'Bot User OAuth Token',\n description: 'Slack app → OAuth & Permissions. Starts with xoxb-.',\n placeholder: 'xoxb-…',\n secret: true,\n },\n {\n key: 'signingSecret',\n label: 'Signing Secret',\n description: 'Slack app → Basic Information → App Credentials.',\n placeholder: 'Signing secret',\n secret: true,\n },\n ],\n inboundHint:\n 'In your Slack app, open Event Subscriptions, turn events on and paste this as the Request URL. Subscribe the bot to message.channels, message.im and app_mention, then reinstall the app.',\n },\n WEBHOOK: {\n platform: 'WEBHOOK',\n authType: 'WEBHOOK',\n fields: [\n {\n key: 'targetUrl',\n label: 'Reply URL',\n description: 'The bot POSTs its replies to this https URL.',\n placeholder: 'https://example.com/bot-replies',\n secret: false,\n url: true,\n },\n {\n key: 'webhookSecret',\n label: 'Signing Secret',\n description:\n 'Your sender signs each request body with HMAC-SHA256 using this secret and sends the hex digest in the X-Signature header.',\n placeholder: 'Generate or paste a secret',\n secret: true,\n generatable: true,\n },\n ],\n inboundHint:\n 'POST each inbound message here as JSON ({\"event\":\"message\",\"id\",\"sender_id\",\"text\",\"conversation_id\"}), signed with the signing secret in the X-Signature header.',\n },\n};\n\n/** Connector type → the global-channel platform it uses (none for widget/custom). */\nconst CONNECTOR_PLATFORM: Readonly<Record<string, ChannelSetupPlatform>> = {\n SLACK: 'SLACK',\n TEAMS: 'TEAMS',\n DISCORD: 'DISCORD',\n WHATSAPP: 'WHATSAPP',\n WEBHOOK: 'WEBHOOK',\n};\n\nexport function connectorPlatform(connectorType: string): ChannelSetupPlatform | undefined {\n return CONNECTOR_PLATFORM[connectorType];\n}\n\n/** A random 32-byte secret, hex encoded, from the browser's CSPRNG. */\nexport function generateSigningSecret(): string {\n const bytes = new Uint8Array(32);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Returns the first problem with the entered credentials, or null when they\n * are complete. Every field is required.\n */\nexport function validateCredentials(\n definition: PlatformCredentialDefinition,\n values: Record<string, string>\n): string | null {\n for (const field of definition.fields) {\n const value = values[field.key]?.trim() ?? '';\n if (!value) return `${field.label} is required`;\n if (field.url) {\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n return `${field.label} must be a valid URL`;\n }\n if (parsed.protocol !== 'https:') return `${field.label} must use https`;\n }\n }\n return null;\n}\n\n// ============================================================================\n// Organization\n// ============================================================================\n\n/**\n * The shell's active organization (the host passes it with the workspace).\n * Global channels belong to an organization, so creating one needs it.\n */\nexport function useActiveOrganizationId(): string | null {\n return useBotlit().organizationId || null;\n}\n\n// ============================================================================\n// Documents\n// ============================================================================\n\nconst GetInboundChannelDocument = gql`\n query BotmanorInboundChannel($id: ID!) {\n getChannel(id: $id) {\n id\n name\n platform\n status\n isConnected\n inboundWorkspaceId\n inboundWebhookUrl\n }\n }\n`;\n\nconst CreateSetupChannelDocument = gql`\n mutation BotmanorCreateSetupChannel($input: CreateChannelInput!) {\n createChannel(input: $input) {\n id\n }\n }\n`;\n\nconst CreateSetupConnectionDocument = gql`\n mutation BotmanorCreateSetupConnection($input: CreateConnectionInput!) {\n createConnection(input: $input) {\n id\n }\n }\n`;\n\nconst DeleteSetupChannelDocument = gql`\n mutation BotmanorDeleteSetupChannel($id: ID!) {\n deleteChannel(id: $id)\n }\n`;\n\nexport interface InboundChannelData {\n id: string;\n name: string;\n platform: string;\n status: string;\n isConnected: boolean;\n inboundWorkspaceId: string | null;\n inboundWebhookUrl: string | null;\n}\n\nfunction toError(cause: unknown, fallback: string): Error {\n const message = extractGraphqlFailureMessage(cause);\n if (message) return new Error(message, { cause });\n return cause instanceof Error ? cause : new Error(fallback, { cause });\n}\n\n/**\n * Apollo v4 resolves (rather than rejects) with `error` set when the server\n * answers with GraphQL errors; surface those as a failure like a rejection.\n */\nfunction throwIfOperationFailed(result: unknown, fallback: string): void {\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) throw toError(operationError, fallback);\n}\n\n// ============================================================================\n// Hook: useInboundChannel\n// ============================================================================\n\ninterface UseInboundChannelResult {\n data: InboundChannelData | null;\n loading: boolean;\n error: Error | undefined;\n refetch: () => Promise<void>;\n}\n\n/** The global channel a connector names, with its inbound webhook URL. */\nexport function useInboundChannel(channelId: string | null | undefined): UseInboundChannelResult {\n const { client, context } = useWorkspaceScopedGlobalClient();\n const [data, setData] = useState<InboundChannelData | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n /** Only the latest request may set state: a slower answer for a previous channel is dropped. */\n const latestRequest = useRef(0);\n\n const refetch = useCallback(async () => {\n const request = ++latestRequest.current;\n const isLatest = () => request === latestRequest.current;\n setData(null);\n setError(undefined);\n if (!channelId) return;\n setLoading(true);\n try {\n const result = await client.query<{ getChannel: InboundChannelData | null }>({\n query: GetInboundChannelDocument,\n variables: { id: channelId },\n fetchPolicy: 'network-only',\n context,\n });\n throwIfOperationFailed(result, 'Failed to load the channel');\n if (isLatest()) setData(result.data?.getChannel ?? null);\n } catch (cause) {\n if (isLatest()) setError(toError(cause, 'Failed to load the channel'));\n } finally {\n if (isLatest()) setLoading(false);\n }\n }, [channelId, client, context]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\n// ============================================================================\n// Hook: useProvisionChannel\n// ============================================================================\n\nexport interface ProvisionChannelInput {\n name: string;\n description?: string;\n organizationId: string;\n definition: PlatformCredentialDefinition;\n credentials: Record<string, string>;\n}\n\ninterface UseProvisionChannelResult {\n /** Creates the global channel and its connection; resolves to the channel id. */\n provision: (input: ProvisionChannelInput) => Promise<string>;\n /** Deletes a channel `provision` created (rollback when the connector fails). */\n discard: (channelId: string) => Promise<void>;\n loading: boolean;\n}\n\nexport function useProvisionChannel(): UseProvisionChannelResult {\n const { client, context } = useWorkspaceScopedGlobalClient();\n const [loading, setLoading] = useState(false);\n\n const discard = useCallback(\n async (channelId: string) => {\n const result = await client.mutate({\n mutation: DeleteSetupChannelDocument,\n variables: { id: channelId },\n context,\n });\n throwIfOperationFailed(result, 'Failed to delete the channel');\n },\n [client, context]\n );\n\n const provision = useCallback(\n async ({\n name,\n description,\n organizationId,\n definition,\n credentials,\n }: ProvisionChannelInput): Promise<string> => {\n setLoading(true);\n try {\n let channelId: string | undefined;\n try {\n const created = await client.mutate<{ createChannel: { id: string } | null }>({\n mutation: CreateSetupChannelDocument,\n variables: {\n input: {\n name,\n description: description || undefined,\n platform: definition.platform,\n channelType: 'COMMUNICATION',\n organizationId,\n },\n },\n context,\n });\n throwIfOperationFailed(created, 'Failed to create the channel');\n channelId = created.data?.createChannel?.id;\n } catch (cause) {\n throw toError(cause, 'Failed to create the channel');\n }\n if (!channelId) throw new Error('Failed to create the channel');\n\n const trimmed = Object.fromEntries(\n definition.fields.map((field) => [field.key, credentials[field.key]?.trim() ?? ''])\n );\n try {\n const connected = await client.mutate({\n mutation: CreateSetupConnectionDocument,\n variables: {\n input: { channelId, authType: definition.authType, credentials: trimmed },\n },\n context,\n });\n throwIfOperationFailed(connected, 'Failed to save the channel credentials');\n } catch (cause) {\n // A channel without its credentials can never deliver: remove it so\n // a retry starts clean instead of leaving an orphan behind.\n await discard(channelId).catch(() => undefined);\n throw toError(cause, 'Failed to save the channel credentials');\n }\n return channelId;\n } finally {\n setLoading(false);\n }\n },\n [client, context, discard]\n );\n\n return { provision, discard, loading };\n}\n"],"mappings":";;;;;;AAkEA,IAAaA,IAA+E;CAC1F,OAAO;EACL,UAAU;EACV,UAAU;EACV,QAAQ,CACN;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,aAAa;GACb,QAAQ;EACV,GACA;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,aAAa;GACb,QAAQ;EACV,CACF;EACA,aACE;CACJ;CACA,SAAS;EACP,UAAU;EACV,UAAU;EACV,QAAQ,CACN;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,aAAa;GACb,QAAQ;GACR,KAAK;EACP,GACA;GACE,KAAK;GACL,OAAO;GACP,aACE;GACF,aAAa;GACb,QAAQ;GACR,aAAa;EACf,CACF;EACA,aACE;CACJ;AACF,GAGMC,IAAqE;CACzE,OAAO;CACP,OAAO;CACP,SAAS;CACT,UAAU;CACV,SAAS;AACX;AAEA,SAAgBC,EAAkB,GAAyD;CACzF,OAAOD,EAAmBE;AAC5B;AAGA,SAAgBC,IAAgC;CAC9C,IAAMC,oBAAQ,IAAI,WAAW,EAAE;CAE/B,OADA,OAAO,gBAAgBA,CAAK,GACrB,MAAM,KAAKA,IAAQ,MAASC,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AAChF;AAMA,SAAgBC,EACd,GACA,GACe;CACf,KAAK,IAAMC,KAASC,EAAW,QAAQ;EACrC,IAAMC,IAAQC,EAAOH,EAAM,IAAI,EAAE,KAAK,KAAK;EAC3C,IAAI,CAACE,GAAO,OAAO,GAAGF,EAAM,MAAM;EAClC,IAAIA,EAAM,KAAK;GACb,IAAII;GACJ,IAAI;IACF,IAAS,IAAI,IAAIF,CAAK;GACxB,QAAQ;IACN,OAAO,GAAGF,EAAM,MAAM;GACxB;GACA,IAAII,EAAO,aAAa,UAAU,OAAO,GAAGJ,EAAM,MAAM;EAC1D;CACF;CAC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wC;IAC5E,SAAS5B,GAAO;KAId,MADA,MAAMyB,EAAQL,CAAS,CAAC,CAAC,YAAY,KAAA,CAAS,GACxCvB,EAAQG,GAAO,wCAAwC;IAC/D;IACA,OAAOoB;GACT,UAAU;IACR,EAAW,EAAK;GAClB;EACF,GACA;GAACC;GAAQC;GAASG;EAAO,CAGlB;EAAW;EAAS;CAAQ;AACvC"}
@@ -75,6 +75,11 @@ export declare const channelKeys: {
75
75
  };
76
76
  export declare function useChannelConnectors(filter?: ChannelFilter): QueryResult<ChannelConnectorRecord[]>;
77
77
  export declare function useChannelConnector(connectorId: string | undefined): QueryResult<ChannelConnectorRecord | null>;
78
+ /**
79
+ * Every connector of the workspace, all pages (BOFF-15360). For pickers that
80
+ * must offer each connector: `useChannelConnectors` stops at the first page.
81
+ */
82
+ export declare function useAllChannelConnectors(): QueryResult<ChannelConnectorRecord[]>;
78
83
  /**
79
84
  * Looks up whether this workspace already has a connector naming a global
80
85
  * channel. Resolves to the connector, null when there is none, and rejects
@@ -86,6 +91,10 @@ export declare function useUpdateChannelConnector(): readonly [(input: UpdateCha
86
91
  export declare function useDeleteChannelConnector(): readonly [(input: string) => Promise<boolean>, import('./internal/workspaceGateway').MutationState<boolean>];
87
92
  export declare function useChannelRoutes(connectorId?: string): QueryResult<ChannelRouteRecord[]>;
88
93
  /** Routes bound to a specific bot app (Bot Detail → Channels tab). */
94
+ /**
95
+ * Every route of one bot, all pages: the Channels tab derives which
96
+ * connectors are already routed from it, so a later page must not be missed.
97
+ */
89
98
  export declare function useBotChannelRoutes(botId: string | undefined): QueryResult<ChannelRouteRecord[]>;
90
99
  export declare function useChannelRoute(routeId: string | undefined): QueryResult<ChannelRouteRecord | null>;
91
100
  export declare function useCreateChannelRoute(): readonly [(input: CreateChannelRouteVariables) => Promise<ChannelRouteRecord>, import('./internal/workspaceGateway').MutationState<ChannelRouteRecord>];