@flexkit/studio 0.2.32 → 0.2.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/activity-nav-button-ZHQOZBCC.js +2 -0
- package/dist/{activity-nav-button-E4I4YC3X.js.map → activity-nav-button-ZHQOZBCC.js.map} +1 -1
- package/dist/astro.js +1 -1
- package/dist/chat-page-7XT4K75G.js +4 -0
- package/dist/chat-page-7XT4K75G.js.map +1 -0
- package/dist/chunk-2FCVATRT.js +4 -0
- package/dist/{chunk-R2O4WC3H.js.map → chunk-2FCVATRT.js.map} +1 -1
- package/dist/{chunk-ERCVR23U.js → chunk-36DLIVZF.js} +2 -2
- package/dist/{chunk-ERCVR23U.js.map → chunk-36DLIVZF.js.map} +1 -1
- package/dist/{chunk-ONB3FWK5.js → chunk-3OBELKJU.js} +2 -2
- package/dist/{chunk-ONB3FWK5.js.map → chunk-3OBELKJU.js.map} +1 -1
- package/dist/chunk-4ZWQ44NZ.js +2 -0
- package/dist/{chunk-2NXQF2F7.js.map → chunk-4ZWQ44NZ.js.map} +1 -1
- package/dist/chunk-5JUG4BEF.js +2 -0
- package/dist/chunk-5JUG4BEF.js.map +1 -0
- package/dist/{chunk-XV7U33XQ.js → chunk-6AJRQSFO.js} +3 -3
- package/dist/{chunk-XV7U33XQ.js.map → chunk-6AJRQSFO.js.map} +1 -1
- package/dist/chunk-7JA6SI5H.js +2 -0
- package/dist/{chunk-5AJXR47U.js.map → chunk-7JA6SI5H.js.map} +1 -1
- package/dist/{chunk-SZEGGBOC.js → chunk-A4DPLZZF.js} +2 -2
- package/dist/{chunk-SZEGGBOC.js.map → chunk-A4DPLZZF.js.map} +1 -1
- package/dist/{chunk-C4XLDODU.js → chunk-C2KPTRYM.js} +3 -1
- package/dist/{chunk-GSGPULRL.js → chunk-CHNQZU2P.js} +2 -2
- package/dist/{chunk-GSGPULRL.js.map → chunk-CHNQZU2P.js.map} +1 -1
- package/dist/chunk-DFBG7PUJ.js +10 -0
- package/dist/{chunk-JAPZBEBZ.js.map → chunk-DFBG7PUJ.js.map} +1 -1
- package/dist/{chunk-V7C4EHK3.js → chunk-DSLPTDZX.js} +2 -2
- package/dist/{chunk-V7C4EHK3.js.map → chunk-DSLPTDZX.js.map} +1 -1
- package/dist/{chunk-EMFHKTAV.js → chunk-EUWIIL3X.js} +2 -2
- package/dist/{chunk-EMFHKTAV.js.map → chunk-EUWIIL3X.js.map} +1 -1
- package/dist/chunk-G5N6HEPW.js +2 -0
- package/dist/chunk-G5N6HEPW.js.map +1 -0
- package/dist/chunk-HR4QZ5TD.js +3 -0
- package/dist/chunk-HR4QZ5TD.js.map +1 -0
- package/dist/chunk-KO2JLLUJ.js +2 -0
- package/dist/chunk-KO2JLLUJ.js.map +1 -0
- package/dist/chunk-MBBE4RND.js +3 -0
- package/dist/chunk-MBBE4RND.js.map +1 -0
- package/dist/{chunk-USNXQOMJ.js → chunk-N33S7BSG.js} +2 -2
- package/dist/{chunk-USNXQOMJ.js.map → chunk-N33S7BSG.js.map} +1 -1
- package/dist/{chunk-KN7OJFEX.js → chunk-N52JTYBJ.js} +2 -2
- package/dist/{chunk-KN7OJFEX.js.map → chunk-N52JTYBJ.js.map} +1 -1
- package/dist/{chunk-KR27GOH6.js → chunk-PC5Z37LT.js} +3 -3
- package/dist/{chunk-KR27GOH6.js.map → chunk-PC5Z37LT.js.map} +1 -1
- package/dist/{chunk-2NQ2RZ2M.js → chunk-PSECMZJC.js} +3 -3
- package/dist/{chunk-2NQ2RZ2M.js.map → chunk-PSECMZJC.js.map} +1 -1
- package/dist/chunk-RBGXXVF4.js +7 -0
- package/dist/{chunk-NNISUDZX.js.map → chunk-RBGXXVF4.js.map} +1 -1
- package/dist/chunk-RULCANNM.js +7 -0
- package/dist/chunk-RULCANNM.js.map +1 -0
- package/dist/chunk-S7Z6KKIN.js +2 -0
- package/dist/chunk-S7Z6KKIN.js.map +1 -0
- package/dist/{chunk-AY2RXJWS.js → chunk-U6NFYYTF.js} +2 -2
- package/dist/{chunk-AY2RXJWS.js.map → chunk-U6NFYYTF.js.map} +1 -1
- package/dist/chunk-VFV44YZB.js +2 -0
- package/dist/{chunk-54AXLGAK.js.map → chunk-VFV44YZB.js.map} +1 -1
- package/dist/chunk-VRDTHLA3.js +3 -0
- package/dist/chunk-VRDTHLA3.js.map +1 -0
- package/dist/chunk-WU2KCXBC.js +2 -0
- package/dist/{chunk-5LGIALCK.js.map → chunk-WU2KCXBC.js.map} +1 -1
- package/dist/chunk-X3SHNHHM.js +2 -0
- package/dist/chunk-X3SHNHHM.js.map +1 -0
- package/dist/chunk-XYFS6X74.js +2 -0
- package/dist/{chunk-JWJJZVP3.js.map → chunk-XYFS6X74.js.map} +1 -1
- package/dist/chunk-YC7PBLTK.js +2 -0
- package/dist/{chunk-MRHZN4G4.js.map → chunk-YC7PBLTK.js.map} +1 -1
- package/dist/electron.js +1 -1
- package/dist/{entry-CA2QAEHN.js → entry-APJ4V7PW.js} +2 -2
- package/dist/{entry-CA2QAEHN.js.map → entry-APJ4V7PW.js.map} +1 -1
- package/dist/index.css +43 -0
- package/dist/index.d.ts +10 -1
- package/dist/index.js +8 -8
- package/dist/index.js.map +1 -1
- package/dist/list-7IHDJM54.js +3 -0
- package/dist/{list-Q2KAEJ26.js.map → list-7IHDJM54.js.map} +1 -1
- package/dist/list-7WFALOUT.js +2 -0
- package/dist/{list-UMMVRYVD.js.map → list-7WFALOUT.js.map} +1 -1
- package/dist/nextjs.js +1 -1
- package/dist/pages-BV3ABSFQ.js +5 -0
- package/dist/{pages-KZ66JVNU.js.map → pages-BV3ABSFQ.js.map} +1 -1
- package/dist/plugin-pages-OWGJPPWV.js +2 -0
- package/dist/{plugin-pages-SR2WSUKZ.js.map → plugin-pages-OWGJPPWV.js.map} +1 -1
- package/dist/project-selector-V5N2724B.js +2 -0
- package/dist/project-selector-V5N2724B.js.map +1 -0
- package/dist/record-links-3P3XSW66.js +2 -0
- package/dist/{record-links-3WZGSVFU.js.map → record-links-3P3XSW66.js.map} +1 -1
- package/dist/root-F2GTYDJM.js +2 -0
- package/dist/{root-6QTQUYK4.js.map → root-F2GTYDJM.js.map} +1 -1
- package/dist/root-GBBZ3DX5.js +31 -0
- package/dist/{root-7BUVDOMV.js.map → root-GBBZ3DX5.js.map} +1 -1
- package/dist/root-J62PBDZ2.js +2 -0
- package/dist/{root-2VBLPRG7.js.map → root-J62PBDZ2.js.map} +1 -1
- package/dist/root-LYRL7VPN.js +14 -0
- package/dist/{root-LFJ5BQSY.js.map → root-LYRL7VPN.js.map} +1 -1
- package/dist/root-NIL2UHKS.js +2 -0
- package/dist/{root-OXS3QQX6.js.map → root-NIL2UHKS.js.map} +1 -1
- package/dist/root-RGZZYETM.js +23 -0
- package/dist/{root-FZLKYL5W.js.map → root-RGZZYETM.js.map} +1 -1
- package/dist/search-IIGNCQEZ.js +2 -0
- package/dist/{search-AZK3Q2KX.js.map → search-IIGNCQEZ.js.map} +1 -1
- package/dist/skills-pages-T52MF4DO.js +2 -0
- package/dist/{skills-pages-7IYBJ4QI.js.map → skills-pages-T52MF4DO.js.map} +1 -1
- package/dist/source-IJAAJDGW.js +2 -0
- package/dist/{source-4BP5PJ2N.js.map → source-IJAAJDGW.js.map} +1 -1
- package/dist/spec-renderer-Z6GVHLFU.js +2 -0
- package/dist/{spec-renderer-3GAVSV52.js.map → spec-renderer-Z6GVHLFU.js.map} +1 -1
- package/dist/tanstack-start.js +1 -1
- package/dist/ui.js +1 -1
- package/dist/user-nav-ZH63YHX7.js +2 -0
- package/dist/{user-nav-OWTTAXZS.js.map → user-nav-ZH63YHX7.js.map} +1 -1
- package/package.json +2 -2
- package/dist/activity-nav-button-E4I4YC3X.js +0 -2
- package/dist/chat-page-7UB3BMBF.js +0 -4
- package/dist/chat-page-7UB3BMBF.js.map +0 -1
- package/dist/chunk-2NXQF2F7.js +0 -2
- package/dist/chunk-32ZU4MLE.js +0 -2
- package/dist/chunk-32ZU4MLE.js.map +0 -1
- package/dist/chunk-54AXLGAK.js +0 -2
- package/dist/chunk-5AJXR47U.js +0 -2
- package/dist/chunk-5LGIALCK.js +0 -2
- package/dist/chunk-6NRQMG26.js +0 -2
- package/dist/chunk-6NRQMG26.js.map +0 -1
- package/dist/chunk-AKQ6ELDX.js +0 -2
- package/dist/chunk-AKQ6ELDX.js.map +0 -1
- package/dist/chunk-DGIY4SKN.js +0 -7
- package/dist/chunk-DGIY4SKN.js.map +0 -1
- package/dist/chunk-HDOIOXMP.js +0 -2
- package/dist/chunk-HDOIOXMP.js.map +0 -1
- package/dist/chunk-HZOD2HOF.js +0 -3
- package/dist/chunk-HZOD2HOF.js.map +0 -1
- package/dist/chunk-JAPZBEBZ.js +0 -10
- package/dist/chunk-JWJJZVP3.js +0 -2
- package/dist/chunk-MRHZN4G4.js +0 -2
- package/dist/chunk-NNISUDZX.js +0 -7
- package/dist/chunk-O2QMYUPS.js +0 -2
- package/dist/chunk-O2QMYUPS.js.map +0 -1
- package/dist/chunk-R2O4WC3H.js +0 -4
- package/dist/chunk-WPCPL2TQ.js +0 -3
- package/dist/chunk-WPCPL2TQ.js.map +0 -1
- package/dist/list-Q2KAEJ26.js +0 -3
- package/dist/list-UMMVRYVD.js +0 -2
- package/dist/pages-KZ66JVNU.js +0 -5
- package/dist/plugin-pages-SR2WSUKZ.js +0 -2
- package/dist/project-selector-72VM6SUI.js +0 -2
- package/dist/project-selector-72VM6SUI.js.map +0 -1
- package/dist/record-links-3WZGSVFU.js +0 -2
- package/dist/root-2VBLPRG7.js +0 -2
- package/dist/root-6QTQUYK4.js +0 -2
- package/dist/root-7BUVDOMV.js +0 -31
- package/dist/root-FZLKYL5W.js +0 -23
- package/dist/root-LFJ5BQSY.js +0 -14
- package/dist/root-OXS3QQX6.js +0 -2
- package/dist/search-AZK3Q2KX.js +0 -2
- package/dist/skills-pages-7IYBJ4QI.js +0 -2
- package/dist/source-4BP5PJ2N.js +0 -2
- package/dist/spec-renderer-3GAVSV52.js +0 -2
- package/dist/user-nav-OWTTAXZS.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/apps/knowledge/api.ts","../src/apps/knowledge/shared.tsx"],"names":["KnowledgeApiError","status","message","code","FetcherError","fetcher","url","response","knowledgePaths","projectId","basePath","entity","sourceId","jobId","from","to","recordId","options","limit","offset","search","params","trimmedSearch","isKnowledgeListKey","key","isKnowledgeLinkKey","readError","fallback","data","createKnowledgeApi","request","init","requestInit","register","body","file","tokenResponse","tokenData","put","title","filename","target","patch","STATUS_TONE_CLASSES","useProjectKnowledge","currentProjectId","useConfig","useMemo","invalidateKnowledgeLists","mutateGlobal","invalidateKnowledgeLinks","describeApiError","error","announceRegistered","result","name","toast","PageMessage","children","jsx","StatusBadge","label","tone","jsxs","Badge","LoaderCircle","FILE_ICONS","Document","Docx","Html","Pdf","Pptx","Txt","KnowledgeTypeIcon","className","size","source","format","getKnowledgeFormat","Icon","SourceIcon","InfiniteScrollSentinel","onVisible","sentinelRef","useRef","onVisibleRef","useEffect","node","observer","entries","entry","SourceActionsMenu","isBusy","onOpen","onRemoved","trigger","api","canMutate","useCanMutate","isConfirmingRemoval","setIsConfirmingRemoval","useState","isRemoving","setIsRemoving","knowledgeApi","remove","removeError","Fragment","DropdownMenu","DropdownMenuTrigger","Button","EllipsisVerticalIcon","DropdownMenuContent","DropdownMenuItem","DownloadIcon","ExternalLinkIcon","DropdownMenuSeparator","Trash2Icon","DropdownMenuLabel","AlertDialog","AlertDialogContent","AlertDialogHeader","AlertDialogTitle","AlertDialogDescription","AlertDialogFooter","AlertDialogCancel","AlertDialogAction","event"],"mappings":"0gCAYO,IAAMA,CAAAA,CAAN,cAAgC,KAAM,CAC3C,IAAA,CACA,MAAA,CAEA,YAAYC,CAAAA,CAAgBC,CAAAA,CAAiBC,EAAsB,IAAA,CAAM,CACvE,MAAMD,CAAO,CAAA,CACb,IAAA,CAAK,IAAA,CAAO,oBACZ,IAAA,CAAK,IAAA,CAAOC,CAAAA,CACZ,IAAA,CA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ACpB/C,EAAO,KAAA,CAAM,qJAAA,CAAA,CAEjB,CAAA,CAAA,CACF,CAAA,CACAb,KAAC6D,GAAAA,CAAA,CACC,QAAA,CAAA,CAAAjE,GAAAA,CAACkE,EAAA,CAAkB,QAAA,CAAUvB,CAAAA,CAAY,QAAA,CAAA,QAAA,CAAM,EAC/CvC,IAAAA,CAAC+D,GAAAA,CAAA,CACC,QAAA,CAAUxB,CAAAA,CACV,QAAUyB,CAAAA,EAAsB,CAC9BA,CAAAA,CAAM,cAAA,GACDtB,CAAAA,GACP,EAEC,QAAA,CAAA,CAAAH,CAAAA,CAAa3C,IAACM,YAAAA,CAAA,CAAa,SAAA,CAAU,iBAAA,CAAkB,EAAK,IAAA,CAAK,iBAAA,CAAA,CAEpE,GACF,CAAA,CAAA,CACF,CAAA,CACF,GACF,CAEJ","file":"chunk-GSGPULRL.js","sourcesContent":["import { put } from '@vercel/blob/client';\nimport type {\n KnowledgeJob,\n KnowledgeLinkTarget,\n KnowledgeRecordRef,\n KnowledgeSource,\n KnowledgeSourcePatch,\n KnowledgeSourceStatus,\n RegisterKnowledgeSourceResult,\n} from './knowledge';\n\n/** The platform refused a knowledge request; `code` lets the UI tailor the message. */\nexport class KnowledgeApiError extends Error {\n code: string | null;\n status: number;\n\n constructor(status: number, message: string, code: string | null = null) {\n super(message);\n this.name = 'KnowledgeApiError';\n this.code = code;\n this.status = status;\n }\n}\n\nexport interface ProjectSpace {\n code: string;\n id: string;\n label: string;\n}\n\nexport interface KnowledgeApi {\n /** Uploads a document to the file store, then registers it; resolves once indexing is queued or the file was already there. */\n addFile: (_file: File, _options?: { signal?: AbortSignal }) => Promise<RegisterKnowledgeSourceResult>;\n addUrl: (_input: { title?: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n /** Promotes a file the caller attached to a chat: the platform copies it into the knowledge folder. */\n addChatAttachment: (_input: { filename: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n deleteSource: (_sourceId: string) => Promise<{ deleted: true }>;\n /** Attaches the document to a record, or to every record of an entity type; `linked` is false when it already was. */\n linkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ linked: boolean }>;\n reingestSource: (_sourceId: string) => Promise<{ job: KnowledgeJob }>;\n unlinkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ unlinked: boolean }>;\n updateSource: (_sourceId: string, _patch: KnowledgeSourcePatch) => Promise<{ source: KnowledgeSource }>;\n}\n\nexport class FetcherError extends Error {\n status: number;\n\n constructor(status: number, message = 'Request failed') {\n super(message);\n this.name = 'FetcherError';\n this.status = status;\n }\n}\n\nexport const fetcher = async <T>(url: string): Promise<T> => {\n const response = await fetch(url, { credentials: 'include' });\n\n if (!response.ok) {\n throw new FetcherError(response.status);\n }\n\n return (await response.json()) as T;\n};\n\nexport function knowledgePaths(projectId: string): {\n /** The documents attached to every record of an entity type. */\n entitySources: (_entity: string) => string;\n /** The original file of an uploaded document, served under its name. */\n file: (_sourceId: string) => string;\n job: (_jobId: string) => string;\n /** The records a document is attached to, and the entity types it applies to. */\n links: (_sourceId: string) => string;\n passages: (_sourceId: string, _options: { from: number; to: number }) => string;\n /** The documents attached to a record. */\n recordSources: (_record: KnowledgeRecordRef) => string;\n source: (_sourceId: string) => string;\n sources: (_options?: { limit?: number; offset?: number; search?: string; status?: KnowledgeSourceStatus }) => string;\n spaces: string;\n} {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n return {\n entitySources: (entity) => `${basePath}/entities/${encodeURIComponent(entity)}/sources`,\n file: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/file`,\n job: (jobId) => `${basePath}/jobs/${encodeURIComponent(jobId)}`,\n links: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/links`,\n passages: (sourceId, { from, to }) =>\n `${basePath}/sources/${encodeURIComponent(sourceId)}/passages?from=${String(from)}&to=${String(to)}`,\n recordSources: ({ entity, recordId }) =>\n `${basePath}/records/${encodeURIComponent(entity)}/${encodeURIComponent(recordId)}/sources`,\n source: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}`,\n sources: (options = {}) => {\n const { limit = 25, offset = 0, search, status } = options;\n const params = new URLSearchParams({ limit: limit.toString(), offset: offset.toString() });\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n if (status) {\n params.set('status', status);\n }\n\n return `${basePath}/sources?${params.toString()}`;\n },\n spaces: `/api/flexkit/${projectId}/spaces`,\n };\n}\n\n/** Whether an SWR key is a page of the document list, whatever its filters. */\nexport function isKnowledgeListKey(key: unknown): boolean {\n return typeof key === 'string' && key.includes('/knowledge/sources?');\n}\n\n/** Whether an SWR key lists the documents of a record or an entity type, or the links of a document. */\nexport function isKnowledgeLinkKey(key: unknown): boolean {\n return (\n typeof key === 'string' &&\n (key.includes('/knowledge/records/') ||\n key.includes('/knowledge/entities/') ||\n (key.includes('/knowledge/sources/') && key.endsWith('/links')))\n );\n}\n\nasync function readError(response: Response, fallback: string): Promise<KnowledgeApiError> {\n let data: { code?: string; error?: string } = {};\n\n try {\n data = (await response.json()) as { code?: string; error?: string };\n } catch {\n // Non-JSON error bodies keep the fallback message.\n }\n\n return new KnowledgeApiError(response.status, data.error ? String(data.error) : fallback, data.code ?? null);\n}\n\nexport function createKnowledgeApi(projectId: string): KnowledgeApi {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n async function request<T>(url: string, init: RequestInit & { fallback: string }): Promise<T> {\n const { fallback, ...requestInit } = init;\n const response = await fetch(url, {\n credentials: 'include',\n headers: { 'Content-Type': 'application/json', ...(requestInit.headers ?? {}) },\n ...requestInit,\n });\n\n if (!response.ok) {\n throw await readError(response, fallback);\n }\n\n return (await response.json()) as T;\n }\n\n function register(body: Record<string, unknown>): Promise<RegisterKnowledgeSourceResult> {\n return request<RegisterKnowledgeSourceResult>(`${basePath}/sources`, {\n body: JSON.stringify(body),\n fallback: 'The document could not be added.',\n method: 'POST',\n });\n }\n\n return {\n addFile: async (file, options) => {\n // The platform issues a token pinned to one pathname, type and size; the\n // browser writes the bytes to the store itself, so a 20 MB document never\n // crosses the API function body limit. Registration then hashes the blob.\n const tokenResponse = await fetch(`${basePath}/uploads`, {\n body: JSON.stringify({ filename: file.name, mediaType: file.type || null, sizeBytes: file.size }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n signal: options?.signal,\n });\n\n if (!tokenResponse.ok) {\n throw await readError(tokenResponse, 'The file could not be uploaded.');\n }\n\n const tokenData = (await tokenResponse.json()) as { mediaType?: string; pathname?: string; token?: string };\n\n if (!tokenData.pathname || !tokenData.token || !tokenData.mediaType) {\n throw new KnowledgeApiError(tokenResponse.status, 'The file could not be uploaded.');\n }\n\n await put(tokenData.pathname, file, {\n abortSignal: options?.signal,\n access: 'public',\n contentType: tokenData.mediaType,\n token: tokenData.token,\n });\n\n return register({ kind: 'upload', pathname: tokenData.pathname });\n },\n addUrl: ({ title, url }) => register({ kind: 'url', url, ...(title ? { title } : {}) }),\n addChatAttachment: ({ filename, url }) => register({ filename, kind: 'chat-attachment', url }),\n deleteSource: (sourceId) =>\n request<{ deleted: true }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n fallback: 'The document could not be removed.',\n method: 'DELETE',\n }),\n linkSource: (sourceId, target) =>\n request<{ linked: boolean }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/links`, {\n body: JSON.stringify(target),\n fallback: 'The document could not be attached.',\n method: 'POST',\n }),\n reingestSource: (sourceId) =>\n request<{ job: KnowledgeJob }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/reingest`, {\n fallback: 'The document could not be re-indexed.',\n method: 'POST',\n }),\n unlinkSource: (sourceId, { entity, recordId }) =>\n request<{ unlinked: boolean }>(\n `${basePath}/sources/${encodeURIComponent(sourceId)}/links/${encodeURIComponent(entity)}${\n recordId === undefined ? '' : `/${encodeURIComponent(recordId)}`\n }`,\n { fallback: 'The document could not be detached.', method: 'DELETE' }\n ),\n updateSource: (sourceId, patch) =>\n request<{ source: KnowledgeSource }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n body: JSON.stringify(patch),\n fallback: 'The document could not be updated.',\n method: 'PATCH',\n }),\n };\n}\n","import type { JSX, MouseEvent } from 'react';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { DownloadIcon, EllipsisVerticalIcon, ExternalLinkIcon, LoaderCircle, Trash2Icon } from 'lucide-react';\nimport { mutate as mutateGlobal } from 'swr';\n// File type icons: Untitled UI's free file icons, Solid variant. The set is\n// published as the MIT package `@untitledui/file-icons`; the page below shows\n// every icon and offers each as SVG or JSX should another format need one.\n// https://www.untitledui.com/resources/file-icons\nimport { Document } from '@untitledui/file-icons/dist/solid/document.mjs';\nimport { Docx } from '@untitledui/file-icons/dist/solid/docx.mjs';\nimport { Html } from '@untitledui/file-icons/dist/solid/html.mjs';\nimport { Pdf } from '@untitledui/file-icons/dist/solid/pdf.mjs';\nimport { Pptx } from '@untitledui/file-icons/dist/solid/pptx.mjs';\nimport { Txt } from '@untitledui/file-icons/dist/solid/txt.mjs';\nimport { useConfig } from '../../core/config/config-context';\nimport { useCanMutate } from '../../core/permissions';\nimport {\n Badge,\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n toast,\n} from '../../ui';\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from '../../ui/primitives/alert-dialog';\nimport {\n createKnowledgeApi,\n isKnowledgeLinkKey,\n isKnowledgeListKey,\n KnowledgeApiError,\n knowledgePaths,\n type KnowledgeApi,\n} from './api';\nimport {\n getKnowledgeFormat,\n type KnowledgeFileIcon,\n type KnowledgeSource,\n type KnowledgeStatusTone,\n type RegisterKnowledgeSourceResult,\n} from './knowledge';\n\nconst STATUS_TONE_CLASSES: { [tone in KnowledgeStatusTone]: string } = {\n busy: 'fk:bg-amber-500/15 fk:text-amber-700 fk:dark:text-amber-400',\n error: 'fk:bg-destructive/15 fk:text-destructive',\n muted: 'fk:bg-muted fk:text-muted-foreground',\n ready: 'fk:bg-emerald-500/15 fk:text-emerald-700 fk:dark:text-emerald-400',\n};\n\nexport function useProjectKnowledge(): { api: KnowledgeApi | null; projectId: string | undefined } {\n const { currentProjectId } = useConfig();\n const api = useMemo(() => (currentProjectId ? createKnowledgeApi(currentProjectId) : null), [currentProjectId]);\n\n return { api, projectId: currentProjectId };\n}\n\n/** Drops every cached page of the document list, so the next visit fetches it afresh. */\nexport function invalidateKnowledgeLists(): Promise<unknown> {\n return mutateGlobal(isKnowledgeListKey, undefined, { revalidate: true });\n}\n\n/** Drops every cached link listing (a record's documents, a document's records) after a link changed. */\nexport function invalidateKnowledgeLinks(): Promise<unknown> {\n return mutateGlobal(isKnowledgeLinkKey, undefined, { revalidate: true });\n}\n\nexport function describeApiError(error: unknown, fallback: string): string {\n if (error instanceof KnowledgeApiError) {\n return error.message;\n }\n\n return error instanceof Error ? error.message : fallback;\n}\n\n/** What the user hears once a document was registered. */\nexport function announceRegistered(result: RegisterKnowledgeSourceResult, name: string): void {\n if (result.duplicate) {\n toast.info(`\"${result.source.title}\" is already in Knowledge.`);\n\n return;\n }\n\n toast.success(`Added ${name}. Indexing starts now.`);\n}\n\nexport function PageMessage({ children }: { children: string }): JSX.Element {\n return (\n <div className=\"fk:rounded-md fk:border fk:border-dashed fk:p-8 fk:text-center fk:text-sm fk:text-muted-foreground fk:corner-squircle\">\n {children}\n </div>\n );\n}\n\nexport function StatusBadge({ label, tone }: { label: string; tone: KnowledgeStatusTone }): JSX.Element {\n return (\n <Badge className={`fk:border-none fk:corner-squircle ${STATUS_TONE_CLASSES[tone]}`} variant=\"outline\">\n {tone === 'busy' ? <LoaderCircle className=\"fk:size-3 fk:animate-spin\" /> : null}\n {label}\n </Badge>\n );\n}\n\nconst FILE_ICONS: { [icon in KnowledgeFileIcon]: typeof Pdf } = {\n document: Document,\n docx: Docx,\n html: Html,\n pdf: Pdf,\n pptx: Pptx,\n txt: Txt,\n};\n\n/** The document's format as its file icon; the format's name is what a screen reader hears. */\nexport function KnowledgeTypeIcon({\n className = '',\n size = 24,\n source,\n}: {\n className?: string;\n size?: number;\n source: Pick<KnowledgeSource, 'kind' | 'mimeType'>;\n}): JSX.Element {\n const format = getKnowledgeFormat(source);\n const Icon = FILE_ICONS[format.icon];\n\n return (\n <span\n aria-label={format.label}\n className={`fk:flex fk:shrink-0 fk:items-center fk:justify-center ${className}`}\n data-knowledge-type={format.icon}\n role=\"img\"\n >\n <Icon size={size} />\n </span>\n );\n}\n\n/** The larger file icon of the document page and the record panel: the same icon as the list, at 40px. */\nexport function SourceIcon({ source }: { source: Pick<KnowledgeSource, 'kind' | 'mimeType'> }): JSX.Element {\n return <KnowledgeTypeIcon size={40} source={source} />;\n}\n\nexport function InfiniteScrollSentinel({ onVisible }: { onVisible: () => void }): JSX.Element {\n const sentinelRef = useRef<HTMLDivElement>(null);\n const onVisibleRef = useRef(onVisible);\n\n onVisibleRef.current = onVisible;\n\n useEffect(() => {\n const node = sentinelRef.current;\n\n if (!node) {\n return;\n }\n\n const observer = new IntersectionObserver((entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n onVisibleRef.current();\n }\n });\n\n observer.observe(node);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n return <div aria-hidden className=\"fk:h-px\" ref={sentinelRef} />;\n}\n\n/**\n * The actions of one document, behind a three-dots button: open (lists\n * only), download the original file (web pages open their address instead)\n * and remove, behind one confirmation. The list and the document page share\n * it so the copy, the download link and the busy rules stay the same.\n */\nexport function SourceActionsMenu({\n isBusy = false,\n onOpen,\n onRemoved,\n source,\n trigger = 'row',\n}: {\n /** Another action on the document is in flight; removing waits for it. */\n isBusy?: boolean;\n /** Offered as the first item when given (the document page is already open). */\n onOpen?: () => void;\n /** The document is gone: drop it from the list, or leave its page. The list invalidation is done here. */\n onRemoved: () => void;\n source: KnowledgeSource;\n /** How the button looks: a quiet icon in a row or card, an outlined one next to page actions. */\n trigger?: 'row' | 'page';\n}): JSX.Element | null {\n const { api, projectId } = useProjectKnowledge();\n const canMutate = useCanMutate();\n const [isConfirmingRemoval, setIsConfirmingRemoval] = useState(false);\n const [isRemoving, setIsRemoving] = useState(false);\n\n if (!api || !projectId) {\n return null;\n }\n\n const knowledgeApi = api;\n\n async function remove(): Promise<void> {\n setIsRemoving(true);\n\n try {\n await knowledgeApi.deleteSource(source.id);\n toast.success(`Removed \"${source.title}\".`);\n setIsConfirmingRemoval(false);\n onRemoved();\n void invalidateKnowledgeLists();\n } catch (removeError) {\n toast.error(describeApiError(removeError, 'The document could not be removed.'));\n } finally {\n setIsRemoving(false);\n }\n }\n\n return (\n <>\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n aria-label={`Actions for ${source.title}`}\n className={trigger === 'row' ? 'fk:size-8 fk:shrink-0 fk:text-muted-foreground' : undefined}\n data-knowledge-menu\n size=\"icon-sm\"\n variant={trigger === 'row' ? 'ghost' : 'outline'}\n >\n <EllipsisVerticalIcon className=\"fk:size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {onOpen ? <DropdownMenuItem onSelect={onOpen}>Open</DropdownMenuItem> : null}\n {source.path ? (\n <DropdownMenuItem asChild>\n <a href={knowledgePaths(projectId).file(source.id)}>\n <DownloadIcon />\n Download\n </a>\n </DropdownMenuItem>\n ) : null}\n {source.originUrl ? (\n <DropdownMenuItem asChild>\n <a href={source.originUrl} rel=\"noreferrer\" target=\"_blank\">\n <ExternalLinkIcon />\n Open page\n </a>\n </DropdownMenuItem>\n ) : null}\n {onOpen || source.path || source.originUrl ? <DropdownMenuSeparator /> : null}\n <DropdownMenuItem\n disabled={!canMutate || isBusy}\n variant=\"destructive\"\n onSelect={() => setIsConfirmingRemoval(true)}\n >\n <Trash2Icon />\n Remove\n </DropdownMenuItem>\n {canMutate ? null : (\n <DropdownMenuLabel className=\"fk:max-w-56 fk:whitespace-normal fk:text-xs fk:font-normal fk:text-muted-foreground\">\n Your member role cannot remove documents.\n </DropdownMenuLabel>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n <AlertDialog open={isConfirmingRemoval} onOpenChange={setIsConfirmingRemoval}>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>Remove this document?</AlertDialogTitle>\n <AlertDialogDescription>\n \"{source.title}\" and its indexed passages are deleted for everyone. Answers the agent gave earlier keep\n their citations, but the document can no longer be opened.\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel disabled={isRemoving}>Cancel</AlertDialogCancel>\n <AlertDialogAction\n disabled={isRemoving}\n onClick={(event: MouseEvent) => {\n event.preventDefault();\n void remove();\n }}\n >\n {isRemoving ? <LoaderCircle className=\"fk:animate-spin\" /> : null}\n Remove document\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n </>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/apps/knowledge/api.ts","../src/apps/knowledge/shared.tsx"],"names":["KnowledgeApiError","status","message","code","FetcherError","fetcher","url","response","knowledgePaths","projectId","basePath","entity","sourceId","jobId","from","to","recordId","options","limit","offset","search","params","trimmedSearch","isKnowledgeListKey","key","isKnowledgeLinkKey","readError","fallback","data","createKnowledgeApi","request","init","requestInit","register","body","file","tokenResponse","tokenData","put","title","filename","target","patch","STATUS_TONE_CLASSES","useProjectKnowledge","currentProjectId","useConfig","useMemo","invalidateKnowledgeLists","mutateGlobal","invalidateKnowledgeLinks","describeApiError","error","announceRegistered","result","name","toast","PageMessage","children","jsx","StatusBadge","label","tone","jsxs","Badge","LoaderCircle","FILE_ICONS","Document","Docx","Html","Pdf","Pptx","Txt","KnowledgeTypeIcon","className","size","source","format","getKnowledgeFormat","Icon","SourceIcon","InfiniteScrollSentinel","onVisible","sentinelRef","useRef","onVisibleRef","useEffect","node","observer","entries","entry","SourceActionsMenu","isBusy","onOpen","onRemoved","trigger","api","canMutate","useCanMutate","isConfirmingRemoval","setIsConfirmingRemoval","useState","isRemoving","setIsRemoving","knowledgeApi","remove","removeError","Fragment","DropdownMenu","DropdownMenuTrigger","Button","EllipsisVerticalIcon","DropdownMenuContent","DropdownMenuItem","DownloadIcon","ExternalLinkIcon","DropdownMenuSeparator","Trash2Icon","DropdownMenuLabel","AlertDialog","AlertDialogContent","AlertDialogHeader","AlertDialogTitle","AlertDialogDescription","AlertDialogFooter","AlertDialogCancel","AlertDialogAction","event"],"mappings":"0gCAYO,IAAMA,CAAAA,CAAN,cAAgC,KAAM,CAC3C,IAAA,CACA,MAAA,CAEA,YAAYC,CAAAA,CAAgBC,CAAAA,CAAiBC,EAAsB,IAAA,CAAM,CACvE,MAAMD,CAAO,CAAA,CACb,IAAA,CAAK,IAAA,CAAO,oBACZ,IAAA,CAAK,IAAA,CAAOC,CAAAA,CACZ,IAAA,CAAK,OAASF,EAChB,CACF,CAAA,CAsBaG,CAAAA,CAAN,cAA2B,KAAM,CACtC,OAEA,WAAA,CAAYH,CAAAA,CAAgBC,EAAU,gBAAA,CAAkB,CACtD,KAAA,CAAMA,CAAO,EACb,IAAA,CAAK,IAAA,CAAO,cAAA,CACZ,IAAA,CAAK,OAASD,EAChB,CACF,CAAA,CAEaI,EAAAA,CAAU,MAAUC,CAAAA,EAA4B,CAC3D,IAAMC,CAAAA,CAAW,MAAM,MAAMD,CAAAA,CAAK,CAAE,WAAA,CAAa,SAAU,CAAC,CAAA,CAE5D,GAAI,CAACC,CAAAA,CAAS,EAAA,CACZ,MAAM,IAAIH,CAAAA,CAAaG,CAAAA,CAAS,MAAM,EAGxC,OAAQ,MAAMA,EAAS,IAAA,EACzB,EAEO,SAASC,CAAAA,CAAeC,CAAAA,CAc7B,CACA,IAAMC,CAAAA,CAAW,CAAA,aAAA,EAAgBD,CAAS,CAAA,UAAA,CAAA,CAE1C,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\n KnowledgeRecordRef,\n KnowledgeSource,\n KnowledgeSourcePatch,\n KnowledgeSourceStatus,\n RegisterKnowledgeSourceResult,\n} from './knowledge';\n\n/** The platform refused a knowledge request; `code` lets the UI tailor the message. */\nexport class KnowledgeApiError extends Error {\n code: string | null;\n status: number;\n\n constructor(status: number, message: string, code: string | null = null) {\n super(message);\n this.name = 'KnowledgeApiError';\n this.code = code;\n this.status = status;\n }\n}\n\nexport interface ProjectSpace {\n code: string;\n id: string;\n label: string;\n}\n\nexport interface KnowledgeApi {\n /** Uploads a document to the file store, then registers it; resolves once indexing is queued or the file was already there. */\n addFile: (_file: File, _options?: { signal?: AbortSignal }) => Promise<RegisterKnowledgeSourceResult>;\n addUrl: (_input: { title?: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n /** Promotes a file the caller attached to a chat: the platform copies it into the knowledge folder. */\n addChatAttachment: (_input: { filename: string; url: string }) => Promise<RegisterKnowledgeSourceResult>;\n deleteSource: (_sourceId: string) => Promise<{ deleted: true }>;\n /** Attaches the document to a record, or to every record of an entity type; `linked` is false when it already was. */\n linkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ linked: boolean }>;\n reingestSource: (_sourceId: string) => Promise<{ job: KnowledgeJob }>;\n unlinkSource: (_sourceId: string, _target: KnowledgeLinkTarget) => Promise<{ unlinked: boolean }>;\n updateSource: (_sourceId: string, _patch: KnowledgeSourcePatch) => Promise<{ source: KnowledgeSource }>;\n}\n\nexport class FetcherError extends Error {\n status: number;\n\n constructor(status: number, message = 'Request failed') {\n super(message);\n this.name = 'FetcherError';\n this.status = status;\n }\n}\n\nexport const fetcher = async <T>(url: string): Promise<T> => {\n const response = await fetch(url, { credentials: 'include' });\n\n if (!response.ok) {\n throw new FetcherError(response.status);\n }\n\n return (await response.json()) as T;\n};\n\nexport function knowledgePaths(projectId: string): {\n /** The documents attached to every record of an entity type. */\n entitySources: (_entity: string) => string;\n /** The original file of an uploaded document, served under its name. */\n file: (_sourceId: string) => string;\n job: (_jobId: string) => string;\n /** The records a document is attached to, and the entity types it applies to. */\n links: (_sourceId: string) => string;\n passages: (_sourceId: string, _options: { from: number; to: number }) => string;\n /** The documents attached to a record. */\n recordSources: (_record: KnowledgeRecordRef) => string;\n source: (_sourceId: string) => string;\n sources: (_options?: { limit?: number; offset?: number; search?: string; status?: KnowledgeSourceStatus }) => string;\n spaces: string;\n} {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n return {\n entitySources: (entity) => `${basePath}/entities/${encodeURIComponent(entity)}/sources`,\n file: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/file`,\n job: (jobId) => `${basePath}/jobs/${encodeURIComponent(jobId)}`,\n links: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}/links`,\n passages: (sourceId, { from, to }) =>\n `${basePath}/sources/${encodeURIComponent(sourceId)}/passages?from=${String(from)}&to=${String(to)}`,\n recordSources: ({ entity, recordId }) =>\n `${basePath}/records/${encodeURIComponent(entity)}/${encodeURIComponent(recordId)}/sources`,\n source: (sourceId) => `${basePath}/sources/${encodeURIComponent(sourceId)}`,\n sources: (options = {}) => {\n const { limit = 25, offset = 0, search, status } = options;\n const params = new URLSearchParams({ limit: limit.toString(), offset: offset.toString() });\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n if (status) {\n params.set('status', status);\n }\n\n return `${basePath}/sources?${params.toString()}`;\n },\n spaces: `/api/flexkit/${projectId}/spaces`,\n };\n}\n\n/** Whether an SWR key is a page of the document list, whatever its filters. */\nexport function isKnowledgeListKey(key: unknown): boolean {\n return typeof key === 'string' && key.includes('/knowledge/sources?');\n}\n\n/** Whether an SWR key lists the documents of a record or an entity type, or the links of a document. */\nexport function isKnowledgeLinkKey(key: unknown): boolean {\n return (\n typeof key === 'string' &&\n (key.includes('/knowledge/records/') ||\n key.includes('/knowledge/entities/') ||\n (key.includes('/knowledge/sources/') && key.endsWith('/links')))\n );\n}\n\nasync function readError(response: Response, fallback: string): Promise<KnowledgeApiError> {\n let data: { code?: string; error?: string } = {};\n\n try {\n data = (await response.json()) as { code?: string; error?: string };\n } catch {\n // Non-JSON error bodies keep the fallback message.\n }\n\n return new KnowledgeApiError(response.status, data.error ? String(data.error) : fallback, data.code ?? null);\n}\n\nexport function createKnowledgeApi(projectId: string): KnowledgeApi {\n const basePath = `/api/flexkit/${projectId}/knowledge`;\n\n async function request<T>(url: string, init: RequestInit & { fallback: string }): Promise<T> {\n const { fallback, ...requestInit } = init;\n const response = await fetch(url, {\n credentials: 'include',\n headers: { 'Content-Type': 'application/json', ...(requestInit.headers ?? {}) },\n ...requestInit,\n });\n\n if (!response.ok) {\n throw await readError(response, fallback);\n }\n\n return (await response.json()) as T;\n }\n\n function register(body: Record<string, unknown>): Promise<RegisterKnowledgeSourceResult> {\n return request<RegisterKnowledgeSourceResult>(`${basePath}/sources`, {\n body: JSON.stringify(body),\n fallback: 'The document could not be added.',\n method: 'POST',\n });\n }\n\n return {\n addFile: async (file, options) => {\n // The platform issues a token pinned to one pathname, type and size; the\n // browser writes the bytes to the store itself, so a 20 MB document never\n // crosses the API function body limit. Registration then hashes the blob.\n const tokenResponse = await fetch(`${basePath}/uploads`, {\n body: JSON.stringify({ filename: file.name, mediaType: file.type || null, sizeBytes: file.size }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n signal: options?.signal,\n });\n\n if (!tokenResponse.ok) {\n throw await readError(tokenResponse, 'The file could not be uploaded.');\n }\n\n const tokenData = (await tokenResponse.json()) as { mediaType?: string; pathname?: string; token?: string };\n\n if (!tokenData.pathname || !tokenData.token || !tokenData.mediaType) {\n throw new KnowledgeApiError(tokenResponse.status, 'The file could not be uploaded.');\n }\n\n await put(tokenData.pathname, file, {\n abortSignal: options?.signal,\n access: 'public',\n contentType: tokenData.mediaType,\n token: tokenData.token,\n });\n\n return register({ kind: 'upload', pathname: tokenData.pathname });\n },\n addUrl: ({ title, url }) => register({ kind: 'url', url, ...(title ? { title } : {}) }),\n addChatAttachment: ({ filename, url }) => register({ filename, kind: 'chat-attachment', url }),\n deleteSource: (sourceId) =>\n request<{ deleted: true }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n fallback: 'The document could not be removed.',\n method: 'DELETE',\n }),\n linkSource: (sourceId, target) =>\n request<{ linked: boolean }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/links`, {\n body: JSON.stringify(target),\n fallback: 'The document could not be attached.',\n method: 'POST',\n }),\n reingestSource: (sourceId) =>\n request<{ job: KnowledgeJob }>(`${basePath}/sources/${encodeURIComponent(sourceId)}/reingest`, {\n fallback: 'The document could not be re-indexed.',\n method: 'POST',\n }),\n unlinkSource: (sourceId, { entity, recordId }) =>\n request<{ unlinked: boolean }>(\n `${basePath}/sources/${encodeURIComponent(sourceId)}/links/${encodeURIComponent(entity)}${\n recordId === undefined ? '' : `/${encodeURIComponent(recordId)}`\n }`,\n { fallback: 'The document could not be detached.', method: 'DELETE' }\n ),\n updateSource: (sourceId, patch) =>\n request<{ source: KnowledgeSource }>(`${basePath}/sources/${encodeURIComponent(sourceId)}`, {\n body: JSON.stringify(patch),\n fallback: 'The document could not be updated.',\n method: 'PATCH',\n }),\n };\n}\n","import type { JSX, MouseEvent } from 'react';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { DownloadIcon, EllipsisVerticalIcon, ExternalLinkIcon, LoaderCircle, Trash2Icon } from 'lucide-react';\nimport { mutate as mutateGlobal } from 'swr';\n// File type icons: Untitled UI's free file icons, Solid variant. The set is\n// published as the MIT package `@untitledui/file-icons`; the page below shows\n// every icon and offers each as SVG or JSX should another format need one.\n// https://www.untitledui.com/resources/file-icons\nimport { Document } from '@untitledui/file-icons/dist/solid/document.mjs';\nimport { Docx } from '@untitledui/file-icons/dist/solid/docx.mjs';\nimport { Html } from '@untitledui/file-icons/dist/solid/html.mjs';\nimport { Pdf } from '@untitledui/file-icons/dist/solid/pdf.mjs';\nimport { Pptx } from '@untitledui/file-icons/dist/solid/pptx.mjs';\nimport { Txt } from '@untitledui/file-icons/dist/solid/txt.mjs';\nimport { useConfig } from '../../core/config/config-context';\nimport { useCanMutate } from '../../core/permissions';\nimport {\n Badge,\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n toast,\n} from '../../ui';\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from '../../ui/primitives/alert-dialog';\nimport {\n createKnowledgeApi,\n isKnowledgeLinkKey,\n isKnowledgeListKey,\n KnowledgeApiError,\n knowledgePaths,\n type KnowledgeApi,\n} from './api';\nimport {\n getKnowledgeFormat,\n type KnowledgeFileIcon,\n type KnowledgeSource,\n type KnowledgeStatusTone,\n type RegisterKnowledgeSourceResult,\n} from './knowledge';\n\nconst STATUS_TONE_CLASSES: { [tone in KnowledgeStatusTone]: string } = {\n busy: 'fk:bg-amber-500/15 fk:text-amber-700 fk:dark:text-amber-400',\n error: 'fk:bg-destructive/15 fk:text-destructive',\n muted: 'fk:bg-muted fk:text-muted-foreground',\n ready: 'fk:bg-emerald-500/15 fk:text-emerald-700 fk:dark:text-emerald-400',\n};\n\nexport function useProjectKnowledge(): { api: KnowledgeApi | null; projectId: string | undefined } {\n const { currentProjectId } = useConfig();\n const api = useMemo(() => (currentProjectId ? createKnowledgeApi(currentProjectId) : null), [currentProjectId]);\n\n return { api, projectId: currentProjectId };\n}\n\n/** Drops every cached page of the document list, so the next visit fetches it afresh. */\nexport function invalidateKnowledgeLists(): Promise<unknown> {\n return mutateGlobal(isKnowledgeListKey, undefined, { revalidate: true });\n}\n\n/** Drops every cached link listing (a record's documents, a document's records) after a link changed. */\nexport function invalidateKnowledgeLinks(): Promise<unknown> {\n return mutateGlobal(isKnowledgeLinkKey, undefined, { revalidate: true });\n}\n\nexport function describeApiError(error: unknown, fallback: string): string {\n if (error instanceof KnowledgeApiError) {\n return error.message;\n }\n\n return error instanceof Error ? error.message : fallback;\n}\n\n/** What the user hears once a document was registered. */\nexport function announceRegistered(result: RegisterKnowledgeSourceResult, name: string): void {\n if (result.duplicate) {\n toast.info(`\"${result.source.title}\" is already in Knowledge.`);\n\n return;\n }\n\n toast.success(`Added ${name}. Indexing starts now.`);\n}\n\nexport function PageMessage({ children }: { children: string }): JSX.Element {\n return (\n <div className=\"fk:rounded-md fk:border fk:border-dashed fk:p-8 fk:text-center fk:text-sm fk:text-muted-foreground fk:corner-squircle\">\n {children}\n </div>\n );\n}\n\nexport function StatusBadge({ label, tone }: { label: string; tone: KnowledgeStatusTone }): JSX.Element {\n return (\n <Badge className={`fk:border-none fk:corner-squircle ${STATUS_TONE_CLASSES[tone]}`} variant=\"outline\">\n {tone === 'busy' ? <LoaderCircle className=\"fk:size-3 fk:animate-spin\" /> : null}\n {label}\n </Badge>\n );\n}\n\nconst FILE_ICONS: { [icon in KnowledgeFileIcon]: typeof Pdf } = {\n document: Document,\n docx: Docx,\n html: Html,\n pdf: Pdf,\n pptx: Pptx,\n txt: Txt,\n};\n\n/** The document's format as its file icon; the format's name is what a screen reader hears. */\nexport function KnowledgeTypeIcon({\n className = '',\n size = 24,\n source,\n}: {\n className?: string;\n size?: number;\n source: Pick<KnowledgeSource, 'kind' | 'mimeType'>;\n}): JSX.Element {\n const format = getKnowledgeFormat(source);\n const Icon = FILE_ICONS[format.icon];\n\n return (\n <span\n aria-label={format.label}\n className={`fk:flex fk:shrink-0 fk:items-center fk:justify-center ${className}`}\n data-knowledge-type={format.icon}\n role=\"img\"\n >\n <Icon size={size} />\n </span>\n );\n}\n\n/** The larger file icon of the document page and the record panel: the same icon as the list, at 40px. */\nexport function SourceIcon({ source }: { source: Pick<KnowledgeSource, 'kind' | 'mimeType'> }): JSX.Element {\n return <KnowledgeTypeIcon size={40} source={source} />;\n}\n\nexport function InfiniteScrollSentinel({ onVisible }: { onVisible: () => void }): JSX.Element {\n const sentinelRef = useRef<HTMLDivElement>(null);\n const onVisibleRef = useRef(onVisible);\n\n onVisibleRef.current = onVisible;\n\n useEffect(() => {\n const node = sentinelRef.current;\n\n if (!node) {\n return;\n }\n\n const observer = new IntersectionObserver((entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n onVisibleRef.current();\n }\n });\n\n observer.observe(node);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n return <div aria-hidden className=\"fk:h-px\" ref={sentinelRef} />;\n}\n\n/**\n * The actions of one document, behind a three-dots button: open (lists\n * only), download the original file (web pages open their address instead)\n * and remove, behind one confirmation. The list and the document page share\n * it so the copy, the download link and the busy rules stay the same.\n */\nexport function SourceActionsMenu({\n isBusy = false,\n onOpen,\n onRemoved,\n source,\n trigger = 'row',\n}: {\n /** Another action on the document is in flight; removing waits for it. */\n isBusy?: boolean;\n /** Offered as the first item when given (the document page is already open). */\n onOpen?: () => void;\n /** The document is gone: drop it from the list, or leave its page. The list invalidation is done here. */\n onRemoved: () => void;\n source: KnowledgeSource;\n /** How the button looks: a quiet icon in a row or card, an outlined one next to page actions. */\n trigger?: 'row' | 'page';\n}): JSX.Element | null {\n const { api, projectId } = useProjectKnowledge();\n const canMutate = useCanMutate();\n const [isConfirmingRemoval, setIsConfirmingRemoval] = useState(false);\n const [isRemoving, setIsRemoving] = useState(false);\n\n if (!api || !projectId) {\n return null;\n }\n\n const knowledgeApi = api;\n\n async function remove(): Promise<void> {\n setIsRemoving(true);\n\n try {\n await knowledgeApi.deleteSource(source.id);\n toast.success(`Removed \"${source.title}\".`);\n setIsConfirmingRemoval(false);\n onRemoved();\n void invalidateKnowledgeLists();\n } catch (removeError) {\n toast.error(describeApiError(removeError, 'The document could not be removed.'));\n } finally {\n setIsRemoving(false);\n }\n }\n\n return (\n <>\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n aria-label={`Actions for ${source.title}`}\n className={trigger === 'row' ? 'fk:size-8 fk:shrink-0 fk:text-muted-foreground' : undefined}\n data-knowledge-menu\n size=\"icon-sm\"\n variant={trigger === 'row' ? 'ghost' : 'outline'}\n >\n <EllipsisVerticalIcon className=\"fk:size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {onOpen ? <DropdownMenuItem onSelect={onOpen}>Open</DropdownMenuItem> : null}\n {source.path ? (\n <DropdownMenuItem asChild>\n <a href={knowledgePaths(projectId).file(source.id)}>\n <DownloadIcon />\n Download\n </a>\n </DropdownMenuItem>\n ) : null}\n {source.originUrl ? (\n <DropdownMenuItem asChild>\n <a href={source.originUrl} rel=\"noreferrer\" target=\"_blank\">\n <ExternalLinkIcon />\n Open page\n </a>\n </DropdownMenuItem>\n ) : null}\n {onOpen || source.path || source.originUrl ? <DropdownMenuSeparator /> : null}\n <DropdownMenuItem\n disabled={!canMutate || isBusy}\n variant=\"destructive\"\n onSelect={() => setIsConfirmingRemoval(true)}\n >\n <Trash2Icon />\n Remove\n </DropdownMenuItem>\n {canMutate ? null : (\n <DropdownMenuLabel className=\"fk:max-w-56 fk:whitespace-normal fk:text-xs fk:font-normal fk:text-muted-foreground\">\n Your member role cannot remove documents.\n </DropdownMenuLabel>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n <AlertDialog open={isConfirmingRemoval} onOpenChange={setIsConfirmingRemoval}>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>Remove this document?</AlertDialogTitle>\n <AlertDialogDescription>\n \"{source.title}\" and its indexed passages are deleted for everyone. Answers the agent gave earlier keep\n their citations, but the document can no longer be opened.\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel disabled={isRemoving}>Cancel</AlertDialogCancel>\n <AlertDialogAction\n disabled={isRemoving}\n onClick={(event: MouseEvent) => {\n event.preventDefault();\n void remove();\n }}\n >\n {isRemoving ? <LoaderCircle className=\"fk:animate-spin\" /> : null}\n Remove document\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n </>\n );\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import'./index.css';import {a}from'./chunk-QSTWBKPN.js';import {d as d$4}from'./chunk-WU2KCXBC.js';import {g,f as f$1,d}from'./chunk-U6VZY3V2.js';import {d as d$2,i,f as f$2,h}from'./chunk-CHNQZU2P.js';import {b as b$4}from'./chunk-DSLPTDZX.js';import {o,e as e$1}from'./chunk-7KLXWCDS.js';import {f,d as d$3}from'./chunk-VRDTHLA3.js';import {b as b$3}from'./chunk-5CVDMZUI.js';import {la as la$1,Lb,Ob,mb,Cc,Dc,Ec,ma as ma$1,n,ra as ra$1,Y,Z,aa as aa$1,ba as ba$1,_,ca as ca$1}from'./chunk-RULCANNM.js';import {t as t$1}from'./chunk-A4DPLZZF.js';import {d as d$1,b as b$5}from'./chunk-G5N6HEPW.js';import {b as b$1}from'./chunk-5JUG4BEF.js';import {k,p,q,s,t,r,n as n$1}from'./chunk-S7Z6KKIN.js';import {b as b$2,c,e}from'./chunk-N33S7BSG.js';import {c as c$1}from'./chunk-X3SHNHHM.js';import {lazy,createContext,useCallback,useState,useRef,useEffect,useMemo,useContext,useTransition,useId,Suspense,useSyncExternalStore}from'react';import qa,{useSWRConfig}from'swr';import {formatDistance,format}from'date-fns';import {RadarIcon,BotIcon,XIcon,PlugIcon,XCircleIcon,LoaderCircle,CheckIcon,CloudUploadIcon,FileTextIcon,DownloadIcon,LinkIcon,MessageSquareIcon,SendIcon,LibraryIcon,ChevronDownIcon,BookOpenIcon,CheckCircle2Icon,CircleSlashIcon,ShieldIcon,DatabaseZapIcon,MessageCircleQuestionIcon,ShieldCheckIcon,TriangleAlertIcon,PlayIcon,ArrowRightIcon,FileIcon,BookOpenTextIcon,CornerDownRightIcon,CircleAlertIcon,MoveRightIcon}from'lucide-react';import {Link,useNavigate}from'react-router-dom';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {pipeJsonRender}from'@json-render/core';import {readUIMessageStream,parseJsonEventStream,uiMessageChunkSchema}from'ai';function St(){let{currentProjectId:e}=f(),{mutate:t}=useSWRConfig();return useCallback(n=>{if(!e)return;let a=g(e).approvalsCount;n?t(a,n,{revalidate:true}):t(a),t(g(e).activitySummary());},[e,t])}function Nt(e,t){let n=e.split(`
|
|
2
|
+
`),a=t.split(`
|
|
3
|
+
`);if(n.length*a.length>25e5)return null;let s=a.length+1,r=new Uint32Array((n.length+1)*s);for(let f=n.length-1;f>=0;f--)for(let c=a.length-1;c>=0;c--)r[f*s+c]=n[f]===a[c]?r[(f+1)*s+c+1]+1:Math.max(r[(f+1)*s+c],r[f*s+c+1]);let i=[],d=0,u=0;for(;d<n.length&&u<a.length;)n[d]===a[u]?(i.push({kind:"same",text:n[d]}),d++,u++):r[(d+1)*s+u]>=r[d*s+u+1]?(i.push({kind:"removed",text:n[d]}),d++):(i.push({kind:"added",text:a[u]}),u++);for(;d<n.length;d++)i.push({kind:"removed",text:n[d]});for(;u<a.length;u++)i.push({kind:"added",text:a[u]});return i}var jn=5e3,On=150,Fe=new Set;function Fn(e){return async()=>{let t=await fetch(e,{credentials:"include",mode:"cors"});return t.status===404?"missing":t.ok?(await t.json()).approval??"missing":null}}function Un(e,t,n=d$3){return !e||e.kind!=="schema"||e.status!=="approved"||e.error?false:e.executedAt?(n(t),false):true}function Ne({approvalId:e,approvalUrl:t,fetchApproval:n,projectId:a,revalidate:s=d$3,sleep:r=i=>new Promise(d=>setTimeout(d,i))}){let i=`${a}:${e}`,d=n??(t?Fn(t):null);!d||Fe.has(i)||(Fe.add(i),(async()=>{try{for(let u=0;u<On;u+=1){let f=null;try{f=await d();}catch{f=null;}if(f==="missing"||f!==null&&!Un(f,a,s))return;await r(jn);}}finally{Fe.delete(i);}})());}var Yn=lazy(()=>import('./skills-pages-T52MF4DO.js').then(e=>({default:e.SkillContentPane}))),Vn={approved:"fk:bg-success/20 fk:text-success",cancelled:"fk:bg-secondary fk:text-secondary-foreground",expired:"fk:bg-secondary fk:text-secondary-foreground",pending:"fk:bg-amber-500/20 fk:text-amber-600",rejected:"fk:bg-destructive/15 fk:text-destructive"};function Wn({status:e}){return jsx(b$1,{className:`fk:border-none fk:h-4.75 fk:text-[0.6875rem] fk:leading-4.5 fk:tracking-wide ${Vn[e]}`,variant:"secondary",children:e})}function U(e){return e==null?"\u2014":typeof e=="object"?JSON.stringify(e):String(e)}function Dt({after:e,before:t}){let n=U(t),a=U(e);return n===a?jsx("span",{className:"fk:text-muted-foreground",children:n}):jsxs("span",{className:"fk:inline-flex fk:flex-wrap fk:items-center fk:gap-1.5",children:[jsx("span",{className:"fk:rounded fk:bg-destructive/10 fk:px-1 fk:text-destructive fk:line-through fk:corner-squircle",children:n}),jsx(MoveRightIcon,{className:"fk:size-3 fk:shrink-0 fk:text-muted-foreground"}),jsx("span",{className:"fk:rounded fk:bg-success/15 fk:px-1 fk:text-success fk:corner-squircle",children:a})]})}function Gn(e){let t=e.entity??"entities",n=e.affectedCount!==null?` \xB7 ${e.affectedCount.toString()} affected`:"";return e.kind==="create"?`Create ${t}${n}`:e.kind==="update"?`Update ${t}${n}`:e.kind==="delete"?`Delete ${t}${n}`:`Mutation on ${t}${n}`}function Zn({operation:e}){if(e.rows.length===0)return null;let t=(e.contextColumns??[]).filter(a=>a!=="_id");if(e.kind==="delete")return jsxs(Y,{children:[jsx(Z,{children:jsxs(aa$1,{children:[jsx(ba$1,{children:"Records to delete"}),t.map(a=>jsx(ba$1,{children:a},a))]})}),jsx(_,{children:e.rows.map((a,s)=>jsxs(aa$1,{className:"fk:bg-destructive/5",children:[jsx(ca$1,{className:"fk:font-mono fk:text-xs fk:text-destructive",children:a.id??U(a.before?._id)}),t.map(r=>jsx(ca$1,{className:"fk:text-xs fk:text-muted-foreground",children:U(a.before?.[r])},r))]},a.id??s.toString()))})]});let n=e.columns.filter(a=>a!=="_id"&&!t.includes(a));return jsxs(Y,{children:[jsx(Z,{children:jsxs(aa$1,{children:[jsx(ba$1,{children:"ID"}),t.map(a=>jsx(ba$1,{children:a},a)),n.map(a=>jsx(ba$1,{children:a},a))]})}),jsx(_,{children:e.rows.map((a,s)=>jsxs(aa$1,{children:[jsx(ca$1,{className:"fk:font-mono fk:text-xs fk:text-muted-foreground",children:a.id??"\u2014"}),t.map(r=>jsx(ca$1,{className:"fk:max-w-72 fk:text-xs fk:text-muted-foreground",children:jsx("span",{className:"fk:line-clamp-3",children:U(a.before?.[r])})},r)),n.map(r=>jsx(ca$1,{className:"fk:text-xs",children:e.kind==="create"?jsx("span",{className:"fk:rounded fk:bg-success/15 fk:px-1 fk:text-success fk:corner-squircle",children:U(a.after?.[r])}):jsx(Dt,{after:a.after?.[r],before:a.before?.[r]})},r))]},a.id??s.toString()))})]})}function ea({operations:e,plugin:t,chat:n,title:a}){return jsxs("details",{className:"fk:rounded-md fk:border fk:border-border fk:corner-squircle",children:[jsx("summary",{className:"fk:cursor-pointer fk:px-3 fk:py-2 fk:text-xs fk:font-medium fk:text-muted-foreground",children:a??(n?"Action details":t?"Plugin tool and arguments":`GraphQL documents (${e.length})`)}),jsx("div",{className:"fk:space-y-3 fk:border-t fk:border-border fk:p-3",children:e.map((s,r)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("pre",{className:"fk:overflow-x-auto fk:rounded-md fk:bg-muted fk:p-3 fk:text-xs fk:corner-squircle",children:s.query}),s.variables&&Object.keys(s.variables).length>0?jsx("pre",{className:"fk:overflow-x-auto fk:rounded-md fk:bg-muted/60 fk:p-3 fk:text-xs fk:corner-squircle",children:JSON.stringify(s.variables,null,2)}):null]},r.toString()))})]})}function It(e){if(e.kind!=="plugin")return null;let n=e.operations[0]?.query.split(`
|
|
4
|
+
`)[0]?.trim()?.split("/"),a=n?.at(-1),s=n?.[0];if(!a||!s||n?.length<2)return null;let r=a.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase(),i=s.replace(/[_-]+/g," ").replace(/\b\w/g,c=>c.toUpperCase()),d=e.operations[0]?.query??"",u=/^Connection:\s*(Project|Personal)\s+—\s+(.+)$/m.exec(d);if(u?.[1]&&u[2])return {action:r,app:i,account:u[2].trim(),scope:u[1]==="Project"?"project":"personal"};let f=/^Connection:.*?([^\s<>]+@[^\s<>]+)\s*$/m.exec(d)?.[1];return {action:r,app:i,account:f}}function ta(e){let t=It(e);if(t)return `${t.action.charAt(0).toUpperCase()}${t.action.slice(1)} in ${t.app}`;if(e.kind==="exec")return "Run a sandbox command";if(e.kind==="schema")return e.operationsSummary.replace(/^Schema: /,"");if(e.kind==="automation"&&e.preview?.automation)return `Create the automation \u201C${e.preview.automation.name}\u201D`;if(e.kind==="automation"&&e.preview?.automationChange)return `Change the automation \u201C${e.preview.automationChange.name}\u201D`;if(e.kind==="skill"&&e.preview?.skill){let{before:n,name:a}=e.preview.skill;return n?`Change the skill \u201C${n.name}\u201D`:`Create the skill \u201C${a}\u201D`}return e.kind==="plugin"?"Use a connected app":e.operationsSummary}function na({operation:e}){if(e.rows.length===0)return null;let t=a=>a!=null&&a!==false,n=e.columns.filter(a=>e.rows.some(r=>t(r.before?.[a])||t(r.after?.[a]))?e.kind!=="update"?true:e.rows.some(r=>U(r.before?.[a])!==U(r.after?.[a])):false);return jsx("div",{className:"fk:overflow-x-auto fk:rounded-md fk:border fk:border-border fk:corner-squircle",children:jsxs(Y,{className:"fk:text-xs",children:[jsx(Z,{children:jsxs(aa$1,{children:[jsx(ba$1,{className:"fk:h-8",children:e.entity==="scopes"||e.entity==="spaces"||e.entity==="studio"?"Setting":"Attribute"}),n.map(a=>jsx(ba$1,{className:"fk:h-8",children:a},a))]})}),jsx(_,{children:e.rows.map((a,s)=>jsxs(aa$1,{children:[jsxs(ca$1,{className:"fk:py-1.5 fk:font-mono fk:text-[0.7rem]",children:[e.kind==="delete"?jsx("span",{className:"fk:line-through fk:text-destructive",children:a.id}):a.id,e.kind==="update"&&a.before===null?jsx(b$1,{className:"fk:ml-2",variant:"secondary",children:"new"}):null,e.kind==="update"&&a.after===null?jsx(b$1,{className:"fk:ml-2",variant:"destructive",children:"removed"}):null]}),n.map(r=>jsx(ca$1,{className:"fk:py-1.5",children:e.kind==="create"?jsx("span",{children:U(a.after?.[r])}):e.kind==="delete"?jsx("span",{className:"fk:text-muted-foreground",children:U(a.before?.[r])}):jsx(Dt,{after:a.after?.[r],before:a.before?.[r]})},r))]},a.id??s.toString()))})]})})}function aa(e){let t=e.entity??"schema";return t==="scopes"||t==="spaces"||t==="studio"?`Change ${t==="studio"?"Studio settings":t}`:e.kind==="create"?`Add entity ${t} \xB7 ${e.rows.length.toString()} attribute${e.rows.length===1?"":"s"}`:e.kind==="delete"?`Remove entity ${t}`:`Change entity ${t}`}function sa({preview:e}){let t=e.schema;return jsxs("div",{className:"fk:space-y-4",children:[t&&t.breakingChanges.length>0?jsxs("div",{className:"fk:rounded-md fk:border fk:border-destructive/30 fk:bg-destructive/5 fk:p-3 fk:text-sm fk:corner-squircle",children:[jsxs("div",{className:"fk:mb-1 fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-destructive",children:[jsx(TriangleAlertIcon,{className:"fk:size-4"}),"Breaking changes: existing data becomes inaccessible"]}),jsx("ul",{className:"fk:list-disc fk:pl-5 fk:text-destructive",children:t.breakingChanges.map(n=>jsx("li",{children:n},n))})]}):null,t&&t.warnings.length>0?jsx("div",{className:"fk:rounded-md fk:border fk:border-amber-500/40 fk:bg-amber-500/10 fk:p-3 fk:text-sm fk:corner-squircle",children:jsx("ul",{className:"fk:list-disc fk:pl-5",children:t.warnings.map(n=>jsx("li",{children:n},n))})}):null,e.operations.map((n,a)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("div",{className:`fk:text-sm fk:font-medium ${n.kind==="delete"?"fk:text-destructive":""}`,children:aa(n)}),jsx(na,{operation:n})]},`${n.entity??""}-${a.toString()}`)),e.operations.length===0?jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-3 fk:text-xs fk:text-muted-foreground fk:corner-squircle",children:"No visible entity changes. Review the operations below."}):null]})}function ra(e,t){return e.id===t.id&&e.status===t.status&&e.decidedAt===t.decidedAt&&e.decidedBy===t.decidedBy&&e.executedAt===t.executedAt&&e.error===t.error&&e.reason===t.reason&&e.expiresAt===t.expiresAt&&e.operationsSummary===t.operationsSummary&&e.affectedCount===t.affectedCount&&JSON.stringify(e.preview)===JSON.stringify(t.preview)}function Et({api:e,approval:t,onDecided:n}){let[a,s]=useState(t),[r,i]=useState(t),[d,u]=useState(""),[f,c]=useTransition(),[p,x]=useState(false),[v,k]=useState(false),[g$1,w]=useState(""),y=St();t!==r&&(i(t),ra(t,r)||a.id===t.id&&a.status!=="pending"&&t.status==="pending"||s(t));function C(S){s(S),y(),S.kind==="schema"&&S.status==="approved"&&Ne({approvalId:S.id,approvalUrl:g(S.projectId).approval(S.id),projectId:S.projectId}),n?.(S);}function _({approved:S,automationEdits:R,force:$=false,reason:E,remember:Y=false,skillEdits:L}){c(async()=>{u("");try{let I=await e.decideApproval(a.id,{approved:S,...R?{automationEdits:R}:{},force:$,reason:E,remember:Y,...L?{skillEdits:L}:{}});if(I.errorCode==="stale_preview"){k(!0),I.approval&&s(I.approval);return}if(k(!1),x(!1),I.approval?C(I.approval):I.success?C({...a,decidedAt:a.decidedAt??new Date().toISOString(),reason:E??a.reason,status:S?"approved":"rejected"}):I.errorCode==="already_decided"&&n?.(a),!I.success&&(I.errorCode!=="already_decided"||!I.approval)){let ke=Array.isArray(I.errorMessage)?I.errorMessage.join(", "):I.errorMessage;u(ke||"Failed to submit the decision.");}}catch(I){u(I instanceof Error?I.message:"Failed to submit the decision.");}});}return {approval:a,decide:_,errorMessage:d,isDeciding:f,isPending:a.status==="pending",isRejectDialogOpen:p,isStale:v,rejectReason:g$1,setIsRejectDialogOpen:x,setRejectReason:w}}function Mt({allowRemember:e=false,askForRejectionReason:t$1,decide:n$1,isDeciding:a,isRejectDialogOpen:s$1,isStale:r$1,rejectReason:i,setIsRejectDialogOpen:d,setRejectReason:u,variant:f}){let c=f==="header",p$1=c?"fk:px-8 fk:min-w-32":void 0,x=c?"default":"sm",[v,k$1]=useState(false),g=useId();return jsxs(Fragment,{children:[jsxs("div",{className:"fk:flex fk:flex-nowrap fk:items-center fk:gap-2",children:[jsxs(c$1,{className:p$1,disabled:a,size:x,onClick:()=>n$1({approved:true,force:r$1,remember:e&&v}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),r$1?"Approve anyway":"Approve"]}),jsxs(c$1,{className:p$1,disabled:a,size:x,variant:"outline",onClick:()=>{t$1?(u(""),d(true)):n$1({approved:false});},children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]}),e?jsxs("label",{className:"fk:ml-1 fk:flex fk:cursor-pointer fk:items-center fk:gap-1.5 fk:whitespace-nowrap fk:text-xs fk:text-muted-foreground",htmlFor:g,children:[jsx(n,{checked:v,id:g,onCheckedChange:w=>k$1(w===true)}),"Always allow this tool for this automation"]}):null]}),t$1?jsx(k,{open:s$1,onOpenChange:d,children:jsxs(p,{children:[jsxs(q,{children:[jsx(s,{children:"Reject this proposal?"}),jsx(t,{children:"The mutation will not be executed. The agent receives your reason and can adapt its plan."})]}),jsx(d$1,{placeholder:"Optional reason for the agent...",value:i,onChange:w=>u(w.target.value)}),jsxs(r,{children:[jsx(c$1,{disabled:a,size:"sm",variant:"outline",onClick:()=>d(false),children:"Cancel"}),jsxs(c$1,{disabled:a,size:"sm",variant:"destructive",onClick:()=>n$1({approved:false,reason:i.trim()||void 0}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(ArrowRightIcon,{className:"fk:size-4"}),"Reject proposal"]})]})]})}):null]})}var oa={always:"Every finished run",failures:"Failures only",never:"Never",when_flagged:"Results that need attention"};function $t(e){return e.visibility==="personal"?"Only you":e.visibility==="space"?`Space: ${e.spaceLabel??"unknown"}`:"Everyone in the project"}function ia({approval:e,instructions:t,isPending:n,proposal:a,onInstructionsChange:s}){let r=useId(),i=e.createdAutomation??null,d=[...a.replacesMonitor?[{label:"Replaces",value:`The monitor \u201C${a.replacesMonitor}\u201D, which stops once this exists`}]:[],{label:"Runs",value:a.triggers.join(`
|
|
5
|
+
`)},{label:"Visible to",value:$t(a)},{label:"Data changes",value:a.mutationPolicy==="auto_approve"?"Applied without review":"Wait for approval"},{label:"Notifications",value:`${oa[a.notifyRule]}${a.notifyCreator?", to you":""}${a.subscribers.length>0?` and ${a.subscribers.join(", ")}`:""}`},...a.plugins.length>0?[{label:"Plugins",value:a.plugins.map(u=>[u.account?`${u.name} as ${u.account}`:u.name,u.deliveryChannels.length>0?`posting to ${u.deliveryChannels.join(", ")}`:""].filter(Boolean).join(", ")).join(`
|
|
6
|
+
`)}]:[],...a.skills.length>0?[{label:"Skills",value:a.skills.join(", ")}]:[],...a.customTools.length>0?[{label:"Custom tools",value:a.customTools.join(", ")}]:[],{label:"Model",value:a.modelLabel}];return jsxs("div",{className:"fk:space-y-4",children:[a.mutationPolicy==="auto_approve"?jsxs("div",{className:"fk:flex fk:items-start fk:gap-2 fk:rounded-md fk:border fk:border-amber-500/40 fk:bg-amber-500/10 fk:p-3 fk:text-sm fk:corner-squircle",role:"status",children:[jsx(TriangleAlertIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0 fk:text-amber-600"}),jsxs("span",{children:["Every run will change data",a.plugins.length>0?" and call these plugins":""," without asking anyone first. Reject and ask for review if that is not what you want."]})]}):null,jsx("dl",{className:"fk:grid fk:grid-cols-[max-content_1fr] fk:gap-x-4 fk:gap-y-1.5 fk:text-sm",children:d.map(u=>jsxs("div",{className:"fk:contents",children:[jsx("dt",{className:"fk:text-muted-foreground",children:u.label}),jsx("dd",{className:"fk:whitespace-pre-line",children:u.value})]},u.label))}),jsxs("div",{className:"fk:space-y-1.5",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:r,children:"Instructions"}),n&&s?jsxs(Fragment,{children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"The automation never sees this chat, so these instructions are all it has to go on. Edit them before creating it."}),jsx(d$1,{className:"fk:min-h-40 fk:text-sm",id:r,value:t,onChange:u=>s(u.target.value)})]}):jsx("p",{className:"fk:whitespace-pre-wrap fk:rounded-md fk:border fk:p-3 fk:text-sm fk:corner-squircle",id:r,children:t})]}),i?jsxs("div",{className:"fk:flex fk:flex-wrap fk:gap-2",children:[jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${i.automationId}`,children:"Open the automation"})}),i.runId?jsx(c$1,{asChild:true,size:"sm",variant:"ghost",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${i.automationId}/runs/${i.runId}`,children:"View its first run"})}):null]}):null]})}function la({approval:e,change:t}){let n=t.changes.filter(s=>s.field!=="instructions"),a=t.changes.find(s=>s.field==="instructions");return jsxs("div",{className:"fk:space-y-4",children:[n.length>0?jsx("dl",{className:"fk:grid fk:grid-cols-[max-content_1fr] fk:gap-x-4 fk:gap-y-2 fk:text-sm",children:n.map(s=>jsxs("div",{className:"fk:contents",children:[jsx("dt",{className:"fk:text-muted-foreground",children:s.label}),jsxs("dd",{className:"fk:space-y-0.5",children:[jsx("div",{className:"fk:whitespace-pre-line fk:text-muted-foreground fk:line-through",children:s.before}),jsx("div",{className:"fk:whitespace-pre-line",children:s.after})]})]},s.field))}):null,a?jsx("div",{className:"fk:grid fk:gap-3 fk:md:grid-cols-2",children:[{label:"Current instructions",muted:true,text:a.before},{label:"New instructions",muted:false,text:a.after}].map(s=>jsxs("div",{className:"fk:min-w-0 fk:space-y-1.5",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:s.label}),jsx("p",{className:`fk:whitespace-pre-wrap fk:rounded-md fk:border fk:p-3 fk:text-sm fk:corner-squircle${s.muted?" fk:text-muted-foreground":""}`,children:s.text})]},s.label))}):null,jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${t.automationId}`,children:"Open the automation"})})]})}function zt({decide:e,instructions:t,isDeciding:n,proposal:a}){let s=t.trim(),r=s!==a.instructions.trim()?{instructions:s}:{};return jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(c$1,{disabled:n||s.length===0,size:"sm",variant:a.runOnceAfterCreate?"outline":"default",onClick:()=>e({approved:true,automationEdits:{...r,runOnce:false}}),children:[n?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),"Create"]}),jsxs(c$1,{disabled:n||s.length===0,size:"sm",variant:a.runOnceAfterCreate?"default":"outline",onClick:()=>e({approved:true,automationEdits:{...r,runOnce:true}}),children:[jsx(PlayIcon,{className:"fk:size-4"}),"Create and run once now"]}),jsxs(c$1,{disabled:n,size:"sm",variant:"outline",onClick:()=>e({approved:false}),children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]})]})}var Pt=3;function ua(e){let t=[],n=0;for(;n<e.length;){if(e[n].kind!=="same"){t.push(e[n]),n++;continue}let a=n;for(;a<e.length&&e[a].kind==="same";)a++;let s=e.slice(n,a),r=n===0?0:Pt,i=a===e.length?0:Pt;s.length>r+i+1?t.push(...s.slice(0,r),{count:s.length-r-i,kind:"folded"},...s.slice(s.length-i)):t.push(...s),n=a;}return t}var Rt={added:{className:"fk:bg-success/10",marker:"+"},removed:{className:"fk:bg-destructive/10 fk:text-muted-foreground",marker:"\u2212"},same:{className:"",marker:" "}};function da({after:e,before:t}){let n=useMemo(()=>Nt(t,e),[e,t]);if(!n)return jsx("p",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-3 fk:text-xs fk:text-muted-foreground fk:corner-squircle",children:"The skill is too long to compare line by line. Review the new content below."});let a=n.filter(r=>r.kind==="added").length,s=n.filter(r=>r.kind==="removed").length;return jsxs("div",{className:"fk:space-y-1.5",children:[jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[jsxs("span",{className:"fk:text-success",children:["+",a.toString()]})," ",jsxs("span",{className:"fk:text-destructive",children:["\u2212",s.toString()]})," lines"]}),jsx("div",{className:"fk:max-h-96 fk:overflow-auto fk:rounded-md fk:border fk:py-1 fk:font-mono fk:text-xs fk:corner-squircle",children:ua(n).map((r,i)=>r.kind==="folded"?jsxs("div",{className:"fk:px-3 fk:py-0.5 fk:text-muted-foreground",children:["\u22EF ",r.count.toString()," unchanged ",r.count===1?"line":"lines"]},i.toString()):jsxs("div",{className:`fk:flex fk:gap-2 fk:px-3 ${Rt[r.kind].className}`,children:[jsx("span",{"aria-hidden":true,className:"fk:w-2 fk:shrink-0 fk:select-none fk:text-muted-foreground",children:Rt[r.kind].marker}),jsx("span",{className:"fk:min-w-0 fk:whitespace-pre-wrap fk:break-words",children:r.text||" "})]},i.toString()))})]})}function Tt({after:e,before:t,label:n}){return e===t?null:jsxs("div",{className:"fk:contents",children:[jsx("dt",{className:"fk:text-muted-foreground",children:n}),jsxs("dd",{className:"fk:space-y-0.5",children:[jsx("div",{className:"fk:whitespace-pre-line fk:text-muted-foreground fk:line-through",children:t}),jsx("div",{className:"fk:whitespace-pre-line",children:e})]})]})}function ca({approval:e,fields:t,isPending:n,proposal:a,onFieldsChange:s}){let r=useId(),i=useId(),{before:d}=a,u=e.savedSkillId??a.skillId,f=n&&s;return jsxs("div",{className:"fk:space-y-4",children:[jsxs("dl",{className:"fk:grid fk:grid-cols-[max-content_1fr] fk:gap-x-4 fk:gap-y-2 fk:text-sm",children:[jsx("dt",{className:"fk:text-muted-foreground",children:"Visible to"}),jsx("dd",{children:$t(a)}),d?jsxs(Fragment,{children:[jsx(Tt,{after:t.name,before:d.name,label:"Name"}),jsx(Tt,{after:t.description,before:d.description,label:"Description"})]}):null]}),d?d.content===t.content?jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:"The content stays the same."}):jsxs("div",{className:"fk:space-y-1.5",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:"Changes to the content"}),jsx(da,{after:t.content,before:d.content})]}):null,f?jsxs("div",{className:"fk:space-y-3",children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"Every chat and automation that can see this skill picks it by its description and follows its content. Edit them before saving."}),jsxs("div",{className:"fk:space-y-1.5",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:r,children:"Name"}),jsx(b$5,{id:r,maxLength:120,value:t.name,onChange:c=>s({...t,name:c.target.value})})]}),jsxs("div",{className:"fk:space-y-1.5",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:i,children:"Description"}),jsx(d$1,{className:"fk:min-h-16 fk:text-sm",id:i,maxLength:1024,value:t.description,onChange:c=>s({...t,description:c.target.value})})]}),jsx("div",{className:"fk:flex fk:h-96 fk:min-w-0 fk:flex-col",children:jsx(Suspense,{fallback:jsx(t$1,{className:"fk:min-h-0 fk:flex-1 fk:rounded-md"}),children:jsx(Yn,{content:t.content,onChange:c=>s({...t,content:c})})})})]}):jsxs("div",{className:"fk:space-y-3 fk:text-sm",children:[d?null:jsxs("div",{className:"fk:space-y-0.5",children:[jsx("div",{className:"fk:font-medium",children:"Description"}),jsx("p",{className:"fk:whitespace-pre-line fk:text-muted-foreground",children:t.description})]}),jsxs("details",{className:"fk:rounded-md fk:border fk:corner-squircle",children:[jsx("summary",{className:"fk:cursor-pointer fk:px-3 fk:py-2 fk:font-medium",children:"Content"}),jsx("pre",{className:"fk:max-h-96 fk:overflow-auto fk:whitespace-pre-wrap fk:border-t fk:p-3 fk:font-mono fk:text-xs",children:t.content})]})]}),u&&(!n||d)?jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/skills/${u}`,children:"Open the skill"})}):null]})}function _t({decide:e,fields:t,isDeciding:n,proposal:a}){let s={content:t.content.trim(),description:t.description.trim(),name:t.name.trim()},r=!s.name||!s.description||!s.content,i=Object.fromEntries(Object.keys(s).filter(d=>s[d]!==a[d].trim()).map(d=>[d,s[d]]));return jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(c$1,{disabled:n||r,size:"sm",onClick:()=>e({approved:true,...Object.keys(i).length>0?{skillEdits:i}:{}}),children:[n?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),a.before?"Save changes":"Save skill"]}),jsxs(c$1,{disabled:n,size:"sm",variant:"outline",onClick:()=>e({approved:false}),children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]})]})}function Lt(e){let t=e.kind==="skill"?e.preview?.skill??null:null,[n,a]=useState(null);return {fields:n?.approvalId===e.id?n.fields:t?{content:t.content,description:t.description,name:t.name}:null,proposal:t,setFields:r=>a({approvalId:e.id,fields:r})}}function jt({approval:e,automationInstructions:t,chat:n,errorMessage:a,isPending:s,isStale:r,onAutomationInstructionsChange:i,onSkillFieldsChange:d,skillFields:u}){let{preview:f}=e,c=n?It(e):null;return jsxs("div",{className:"fk:min-w-0 fk:max-w-full fk:space-y-4",children:[jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsx(Wn,{status:e.status}),e.kind==="schema"?jsx(b$1,{variant:"outline",children:"Schema change"}):null,e.kind==="automation"?jsx(b$1,{variant:"outline",children:f?.automationChange?"Automation change":"New automation"}):null,e.kind==="skill"?jsx(b$1,{variant:"outline",children:f?.skill?.before?"Skill change":"New skill"}):null,jsx("span",{className:"fk:text-sm fk:font-medium",children:n?ta(e):e.operationsSummary})]}),jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[e.automationName?`${e.automationName} \xB7 `:"","requested ",formatDistance(new Date(e.requestedAt),new Date,{addSuffix:true}),s?` \xB7 expires ${formatDistance(new Date(e.expiresAt),new Date,{addSuffix:true})}`:"",e.decidedAt?` \xB7 decided ${format(new Date(e.decidedAt),"PPpp")}`:""]}),r?jsxs("div",{className:"fk:flex fk:items-start fk:gap-2 fk:rounded-md fk:border fk:border-amber-500/40 fk:bg-amber-500/10 fk:p-3 fk:text-sm fk:corner-squircle",children:[jsx(TriangleAlertIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0 fk:text-amber-600"}),jsx("span",{children:"The affected data changed since this proposal was created. The preview below has been refreshed \u2014 review it and approve again to proceed."})]}):null,e.kind==="automation"&&f?.automation?jsx(ia,{approval:e,instructions:t??f.automation.instructions,isPending:s,proposal:f.automation,onInstructionsChange:i}):e.kind==="automation"&&f?.automationChange?jsx(la,{approval:e,change:f.automationChange}):e.kind==="skill"&&f?.skill?jsx(ca,{approval:e,fields:u??f.skill,isPending:s,proposal:f.skill,onFieldsChange:d}):e.kind==="schema"&&f?jsx(sa,{preview:f}):f&&f.operations.length>0?jsx("div",{className:"fk:space-y-4",children:f.operations.map((p,x)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:Gn(p)}),p.kind==="delete"&&p.affectedCount!==null?jsxs("div",{className:"fk:rounded-md fk:border fk:border-destructive/30 fk:bg-destructive/5 fk:p-3 fk:text-sm fk:text-destructive fk:corner-squircle",children:[p.affectedCount.toString()," record",p.affectedCount===1?"":"s"," will be permanently deleted."]}):null,jsx(Zn,{operation:p}),p.truncated?jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:["Preview limited to the first ",p.rows.length.toString()," rows."]}):null]},x.toString()))}):jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-3 fk:text-xs fk:text-muted-foreground fk:corner-squircle",children:n?c?`This action uses ${c.scope==="project"?"the project's":"your"} ${c.app} account${c.account?` (${c.account})`:""}. Check the details before deciding.`:"The assistant wants to make this change. Check the details before deciding.":e.kind==="plugin"?"Review the account, tool, and arguments before allowing this external call.":e.kind==="exec"?"This command runs inside the run's ephemeral sandbox but may send data out or reach other hosts. Review the command line before allowing it.":"No structured preview is available for this proposal. Review the raw GraphQL documents below."}),e.kind==="automation"||e.kind==="skill"?null:jsx(ea,{chat:n,operations:e.operations,plugin:e.kind==="plugin"||e.kind==="exec",title:e.kind==="exec"?"Command and options":e.kind==="schema"?"Operations":void 0}),e.reason?jsxs("div",{className:"fk:text-sm",children:[jsx("span",{className:"fk:font-medium",children:"Reason:"})," ",e.reason]}):null,e.error?jsxs("div",{className:"fk:rounded-md fk:border fk:border-destructive/30 fk:bg-destructive/5 fk:p-3 fk:text-sm fk:corner-squircle",children:["Execution failed: ",e.error]}):null,e.executedAt&&!e.error?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-sm fk:text-success",children:[jsx(CheckIcon,{className:"fk:size-4"}),"Executed ",format(new Date(e.executedAt),"PPpp")]}):null,a?jsx("div",{className:"fk:text-sm fk:text-destructive",children:a}):null]})}function Ot({api:e,approval:t,chat:n,onDecided:a}){let{approval:s,decide:r,errorMessage:i,isDeciding:d,isPending:u,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v}=Et({api:e,approval:t,onDecided:a}),k=s.kind==="automation"?s.preview?.automation??null:null,[g,w]=useState(k?.instructions??""),y=Lt(s);return jsxs(Fragment,{children:[jsx(jt,{approval:s,automationInstructions:k?g:void 0,chat:n,errorMessage:i,isPending:u,isStale:c,onAutomationInstructionsChange:k?w:void 0,onSkillFieldsChange:y.proposal?y.setFields:void 0,skillFields:y.fields??void 0}),u&&y.proposal&&y.fields?jsx("div",{className:"fk:mt-4",children:jsx(_t,{decide:r,fields:y.fields,isDeciding:d,proposal:y.proposal})}):u&&k?jsx("div",{className:"fk:mt-4",children:jsx(zt,{decide:r,instructions:g,isDeciding:d,proposal:k})}):u?jsx("div",{className:"fk:mt-4",children:jsx(Mt,{allowRemember:!n&&s.kind==="plugin"&&!!s.automationId,askForRejectionReason:!n,decide:r,isDeciding:d,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v,variant:"inline"})}):null]})}function Sr({api:e,approval:t,onClose:n,onDecided:a}){let{approval:s,decide:r,errorMessage:i,isDeciding:d,isPending:u,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v}=Et({api:e,approval:t,onDecided:a}),k=s.kind==="automation"?s.preview?.automation??null:null,[g,w]=useState(k?.instructions??""),y=Lt(s);return jsx(la$1,{actions:u&&y.proposal&&y.fields?jsx(_t,{decide:r,fields:y.fields,isDeciding:d,proposal:y.proposal}):u&&k?jsx(zt,{decide:r,instructions:g,isDeciding:d,proposal:k}):u?jsx(Mt,{allowRemember:s.kind==="plugin"&&!!s.automationId,askForRejectionReason:true,decide:r,isDeciding:d,isRejectDialogOpen:f,isStale:c,rejectReason:p,setIsRejectDialogOpen:x,setRejectReason:v,variant:"header"}):null,depth:0,isFocused:true,onClose:n,title:k?"Automation proposal":s.preview?.automationChange?"Automation change":y.proposal?y.proposal.before?"Skill change":"Skill proposal":"Mutation proposal",children:jsx(jt,{approval:s,automationInstructions:k?g:void 0,chat:false,errorMessage:i,isPending:u,isStale:c,onAutomationInstructionsChange:k?w:void 0,onSkillFieldsChange:y.proposal?y.setFields:void 0,skillFields:y.fields??void 0})})}var fa="Approved by Flexkit Jev policy",pa="Approved by automation tool allow rule",ma=new Set(["data-create-sandbox","data-execute-graphql","data-export-records","data-load-skill","data-plan","data-plugin-call","data-read-source","data-run-command","data-search-schema","data-update-memory","data-validate-graphql","data-web-search"]);function me(e){return ma.has(e)}function b(e){return e.data}function Be(e){return !e.decidedBy&&!!(e.reason?.startsWith(fa)||e.reason?.startsWith(pa))}function H(e,t=72){let n=e.trim();if(n.length<=t)return n;let a=n.slice(0,t),s=a.lastIndexOf(" ");return `${(s>=Math.floor(t*.6)?a.slice(0,s):a).trimEnd()}\u2026`}function ka(e){return e.replace(/^#{1,6}\s+/,"").replace(/^(?:[-*+]|\d+[.)])\s+/,"").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/(\*\*|__)(.*?)\1/g,"$2").replace(/(\*|_)(.*?)\1/g,"$2").replace(/`([^`]*)`/g,"$1").replace(/[*_`#>]/g,"").replace(/\s+/g," ").trim().replace(/[.:]+$/,"")}function ga(e){let t=e.lastIndexOf(`
|
|
7
|
+
`),n=-1,a=/[.!?](?=\s)/g,s;for(;(s=a.exec(e))!==null;)n=s.index;let r=Math.max(t,n);return r<0?"":e.slice(0,r+1)}function va(e,t){let a=(ga(e)).split(/\r?\n/).map(u=>u.trim()).filter(Boolean),s=a[a.length-1];if(!s)return null;let i=/^\*\*(.+?)\*\*:?$/.exec(s)?.[1]??/^#{1,6}\s+(.+)$/.exec(s)?.[1]??/^(.+?[.!?])(?:\s|$)/.exec(s)?.[1]??s,d=ka(i);return !d||/^reasoning$/i.test(d)?null:H(d)}function Ft(e){return e.replace(/[_-]+/g," ").trim()}function ha(e){if(e.type==="data-load-skill"){let t=b(e);return t.status!=="loading"?null:t.skillName?H(`Loading skill "${t.skillName}"`):"Loading skill"}if(e.type==="data-search-schema")return b(e).status==="loading"?"Searching schema":null;if(e.type==="data-validate-graphql")return b(e).status==="loading"?"Validating GraphQL query":null;if(e.type==="data-execute-graphql"){let t=b(e);return t.status!=="loading"?null:t.operationType==="mutation"?"Executing GraphQL mutation":"Executing GraphQL query"}if(e.type==="data-export-records"){let t=b(e);return t.status!=="loading"?null:t.rowCount>0?`Exporting records (${t.rowCount.toLocaleString("en-US")} so far)`:"Exporting records"}if(e.type==="data-update-memory")return b(e).status==="loading"?"Updating memory":null;if(e.type==="data-web-search"){let t=b(e);return t.status!=="loading"?null:t.query?H(`Searching the web for "${t.query}"`):"Searching the web"}if(e.type==="data-run-command"){let t=b(e);return ["executing","running","waiting"].includes(t.status)?H(`Running ${[t.command,...t.args].join(" ")}`):null}if(e.type==="data-create-sandbox")return b(e).status==="loading"?"Creating sandbox":null;if(e.type==="data-plugin-call"){let t=b(e);return t.status!=="loading"?null:H(`Calling ${t.pluginId}: ${Ft(t.tool)}`)}if(e.type==="data-subtask"){let t=b(e);return t.status==="running"?H(`Running subtask: ${t.title}`):null}if(e.type==="data-knowledge-search"){let t=b(e);return t.status!=="loading"?null:t.query?H(`Searching knowledge for "${t.query}"`):"Searching knowledge"}if(e.type==="data-read-source"){let t=b(e);return t.status!=="loading"?null:t.sourceTitle?H(`Reading "${t.sourceTitle}"`):"Reading a document"}return null}var ya=new Set(["data-execute-graphql","data-read-source","data-search-schema","data-validate-graphql"]);function De(e){if(!me(e.type)||e.type==="data-plan"||ya.has(e.type))return null;let t=b(e);if(t.status!=="error")return null;if(t.error?.message)return t.error.message;switch(e.type){case "data-web-search":return "Failed to search the web";case "data-run-command":return `Command failed: ${String(t.command??"")}`.trim();case "data-create-sandbox":return "Failed to create sandbox";case "data-load-skill":return "Failed to load skill";case "data-update-memory":return "Failed to update memory";case "data-plugin-call":return `Plugin call failed: ${String(t.pluginId??"")}: ${Ft(String(t.tool??""))}`;default:return "The tool call failed"}}function Ie(e){if(e.type==="step-start"||e.type==="reasoning")return true;if(me(e.type))return De(e)===null;if(e.type==="data-knowledge-search")return b(e).status==="loading";if(e.type==="data-mutation-approval"){let t=b(e);return Be(t)&&t.status!=="error"}return false}function pe(e){if(!e)return null;for(let t=e.parts.length-1;t>=0;t--){let n=e.parts[t];if(n?.type!=="data-plan")continue;let a=b(n),s=a.steps.findIndex(r=>r.status==="in_progress");return s<0?null:H(`Step ${(s+1).toString()} of ${a.steps.length.toString()}: ${a.steps[s].step}`)}return null}function ba(e){if(!e)return null;for(let t=e.parts.length-1;t>=0;t--){let n=e.parts[t];if(!(!n||n.type==="step-start"))return n.type==="reasoning"?n.state==="streaming"?va(n.text)??pe(e):pe(e):n.type==="data-mutation-approval"?b(n).status==="pending"?"Awaiting approval":pe(e):n.type==="data-user-question"?b(n).status==="pending"?"Waiting for your answer":pe(e):n.type==="text"?null:ha(n)??pe(e)}return null}function Xe(e){return e?e.parts.some(t=>t.type!=="data-mutation-approval"?false:b(t).status==="pending"):false}function Je(e,t={}){let n=false,a=[];for(let s of e.parts){if(s.type!=="data-mutation-approval"){a.push(s);continue}let r=b(s);if(r.status!=="pending"){a.push(s);continue}n=true;let i=t[r.approvalId];i&&i!=="pending"&&a.push({...s,data:{...r,status:i}});}return n?{...e,parts:a}:e}function Ut(e,t){if(!e)return [];let n=[],a=t?.pendingOnly??false;for(let s of e.parts){if(s.type!=="data-mutation-approval")continue;let r=b(s);a&&r.status!=="pending"||n.push(r.approvalId);}return n}function xa(e){return Ut(e,{pendingOnly:true})}function Qe(e){return !!e?.parts.some(t=>t.type==="data-user-question"&&b(t).status==="pending")}function qt(e){return e.map(()=>({other:"",selected:[]}))}function Bt(e,t,n){return e.multiSelect?{...t,selected:t.selected.includes(n)?t.selected.filter(a=>a!==n):[...t.selected,n]}:{other:"",selected:[n]}}function Xt(e,t,n){return e.multiSelect?{...t,other:n}:{other:n,selected:n.trim()?[]:t.selected}}function Jt(e){let t=[];for(let n of e){let a=n.other.trim();if(n.selected.length===0&&!a)return null;t.push(a?{other:a,selected:n.selected}:{selected:n.selected});}return t}function Qt(e){return e&&[...e.selected,...e.other?[`\u201C${e.other}\u201D`]:[]].join(", ")||"\u2014"}function wa(e){return Array.isArray(e)?e.filter(t=>t.type==="file"&&typeof t.url=="string").map(t=>({filename:t.filename??"file",mediaType:t.mediaType??"application/octet-stream",sizeBytes:t.sizeBytes??0,url:t.url??"",...t.sha256?{sha256:t.sha256}:{},...t.knowledgeSourceId!==void 0?{knowledgeSourceId:t.knowledgeSourceId}:{}})):[]}function Ht(e,t){return e.kind!=="idle"?e:t.knowledgeSourceId?{kind:"added",sourceId:t.knowledgeSourceId}:e}function Da(e){return typeof e=="string"&&e.includes("/agent/chats/")}function Kt({attachment:e$2}){let{currentProjectId:t}=f(),n=b$4(),a=useNavigate(),{mutate:s}=useSWRConfig(),r=useMemo(()=>t?d$2(t):null,[t]),[i$1,d]=useState({kind:"idle"}),u=Ht(i$1,e$2),f$1=e$1({name:e$2.filename,size:e$2.sizeBytes})===null;if(!r||!t||!n||!f$1)return null;let c$1=r,p=t;async function x(){d({kind:"adding"});try{let g=await c$1.addChatAttachment({filename:e$2.filename,url:e$2.url});i(g,e$2.filename),d({kind:"added",sourceId:g.source.id}),f$2(),s(Da);}catch(g){ma$1.error(h(g,`${e$2.filename} could not be added to Knowledge.`)),d({kind:"idle"});}}let v="Add to Knowledge",k=jsx(BookOpenTextIcon,{className:"fk:size-3"});return u.kind==="adding"?k=jsx(LoaderCircle,{className:"fk:size-3 fk:animate-spin"}):u.kind==="added"&&(v="Open in Knowledge",k=jsx(CheckIcon,{className:"fk:size-3"})),jsxs(b$2,{children:[jsx(c,{asChild:true,children:jsx("button",{"aria-disabled":u.kind==="adding","aria-label":`${v}: ${e$2.filename}`,className:"fk:absolute fk:top-1 fk:right-1 fk:z-10 fk:flex fk:size-5 fk:items-center fk:justify-center fk:rounded-full fk:border fk:border-border fk:bg-background fk:text-foreground fk:shadow-sm fk:transition-colors fk:hover:bg-accent fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:aria-disabled:cursor-default fk:aria-disabled:hover:bg-background fk:corner-squircle","data-knowledge-state":u.kind,type:"button",onClick:g=>{g.stopPropagation(),g.preventDefault(),u.kind==="idle"?x():u.kind==="added"&&a(o(p,u.sourceId));},children:k})}),jsx(e,{children:v})]})}var Yt=20*1024*1024,Yr=10,Wt=new Set(["css","csv","gif","gql","graphql","htm","html","jpeg","jpg","js","json","jsx","log","markdown","md","mjs","ndjson","pdf","png","py","sql","ts","tsv","tsx","txt","webp","xml","yaml","yml"]),Gt=new Set(["application/pdf","image/gif","image/jpeg","image/png","image/webp"]),Vr=[...[...Wt].map(e=>`.${e}`),...Gt].join(",");function Zt(e){let t=e.lastIndexOf(".");return t<=0?"":e.slice(t+1).toLowerCase()}function za(e){let t=Zt(e.name);return (t?Wt.has(t):Gt.has(e.type))?e.size===0?`"${e.name}" is empty.`:e.size>Yt?`"${e.name}" exceeds the ${String(Math.round(Yt/(1024*1024)))} MB limit.`:null:`"${e.name}" is not supported. Attach images, PDFs, or text files.`}async function _a(e){let n=await(await fetch(e.url)).blob();return new File([n],e.filename??"file",{type:e.mediaType||n.type})}function Wr(e,t){let{attachments:n}=Lb(),a=useRef({}),[,s]=useState(0),r=useCallback(()=>s(f=>f+1),[]),i=useRef(n.remove);i.current=n.remove;let d=useRef(t);d.current=t,useEffect(()=>{let f=new Set(n.files.map(c=>c.id));for(let[c,p]of Object.entries(a.current))f.has(c)||(p.controller.abort(),delete a.current[c]);for(let c of n.files){if(a.current[c.id])continue;let p=new AbortController,x={controller:p,status:"uploading"};a.current[c.id]=x,(async()=>{try{let v=await _a(c),k=za(v);if(k)throw new Error(k);let g=await e.uploadAgentChatAttachment(v,p.signal);if(p.signal.aborted)return;x.attachment=g,x.status="done";}catch(v){if(p.signal.aborted)return;x.status="error",delete a.current[c.id],i.current(c.id),d.current(v instanceof Error?v.message:"The file could not be uploaded.");}finally{r();}})();}r();},[e,n.files,r]);let u=Object.values(a.current).some(f=>f.status==="uploading");return {getUploaded:f=>f.map(c=>a.current[c]?.attachment).filter(c=>!!c),isUploading:u,isUploadingFile:f=>a.current[f]?.status==="uploading"}}function Ke(e){return !!e?.startsWith("image/")}function en({image:e,onClose:t}){return jsx(k,{onOpenChange:n=>n?void 0:t(),open:e!==null,children:jsxs(p,{className:"fk:h-dvh fk:w-dvw fk:max-w-none fk:sm:max-w-none fk:rounded-none fk:border-0 fk:bg-black/90 fk:p-4 fk:shadow-none fk:flex fk:items-center fk:justify-center fk:corner-squircle",showCloseButton:false,children:[jsx(s,{className:"fk:sr-only",children:e?.filename??"Image preview"}),e?jsx("img",{alt:e.filename,className:"fk:block fk:h-auto fk:w-auto fk:max-h-full fk:max-w-full fk:object-contain",src:e.url}):null,jsx(n$1,{"aria-label":"Close preview",className:"fk:absolute fk:top-4 fk:right-4 fk:flex fk:size-9 fk:items-center fk:justify-center fk:rounded-full fk:bg-white/10 fk:text-white fk:transition-colors fk:hover:bg-white/20 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-white/60 fk:corner-squircle",children:jsx(XIcon,{className:"fk:size-5"})})]})})}function tn({label:e,onRemove:t}){return jsx("button",{"aria-label":e,className:"fk:absolute fk:top-1 fk:right-1 fk:z-10 fk:flex fk:size-5 fk:items-center fk:justify-center fk:rounded-full fk:border fk:border-border fk:bg-background fk:text-foreground fk:shadow-sm fk:transition-colors fk:hover:bg-accent fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:corner-squircle",onClick:n=>{n.stopPropagation(),t();},type:"button",children:jsx(XIcon,{className:"fk:size-3"})})}function nn({image:e,isUploading:t=false,onOpen:n,onRemove:a,sizeClassName:s}){return jsxs("div",{className:`fk:relative fk:shrink-0 fk:overflow-hidden fk:rounded-xl fk:bg-muted ${s} fk:corner-squircle`,children:[jsx("button",{"aria-label":`Preview ${e.filename}`,className:"fk:block fk:size-full fk:cursor-zoom-in fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring",onClick:n,type:"button",children:jsx("img",{alt:e.filename,className:"fk:size-full fk:object-cover",src:e.url})}),t?jsx("div",{className:"fk:pointer-events-none fk:absolute fk:inset-0 fk:flex fk:items-center fk:justify-center fk:bg-background/60",children:jsx(ra$1,{className:"fk:size-4"})}):null,a?jsx(tn,{label:`Remove ${e.filename}`,onRemove:a}):null]})}function La(e,t){let n=Zt(e);if(n)return n.toUpperCase();let a=t?.split("/")[1]?.split("+")[0];return a?a.toUpperCase():"FILE"}function an({action:e,file:t,href:n,isUploading:a=false,onRemove:s}){let r=jsxs(Fragment,{children:[jsx("div",{className:"fk:flex fk:size-10 fk:shrink-0 fk:items-center fk:justify-center fk:rounded-lg fk:bg-muted fk:text-muted-foreground fk:corner-squircle",children:a?jsx(ra$1,{className:"fk:size-4"}):jsx(FileIcon,{className:"fk:size-5"})}),jsxs("div",{className:"fk:min-w-0 fk:pr-4 fk:text-left",children:[jsx("div",{className:"fk:truncate fk:text-sm fk:font-medium fk:text-foreground",children:t.filename}),jsx("div",{className:"fk:truncate fk:text-xs fk:text-muted-foreground",children:La(t.filename,t.mediaType)})]})]}),i="fk:flex fk:h-14 fk:max-w-64 fk:items-center fk:gap-2.5 fk:rounded-xl fk:border fk:border-border fk:bg-background fk:px-2 fk:corner-squircle";return jsxs("div",{className:"fk:relative fk:shrink-0",children:[n?jsx("a",{className:`${i} fk:transition-colors fk:hover:bg-accent/50 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring`,href:n,rel:"noreferrer",target:"_blank",children:r}):jsx("div",{className:i,children:r}),s?jsx(tn,{label:`Remove ${t.filename}`,onRemove:s}):null,e]})}function Gr({uploads:e}){let t=Ob(),[n,a]=useState(null);return t.files.length===0?null:jsxs(Fragment,{children:[jsx("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:t.files.map(s=>{if(Ke(s.mediaType)&&s.url){let r={filename:s.filename??"Image",url:s.url};return jsx(nn,{image:r,isUploading:e.isUploadingFile(s.id),onOpen:()=>a(r),onRemove:()=>t.remove(s.id),sizeClassName:"fk:size-14"},s.id)}return jsx(an,{file:{filename:s.filename??"file",mediaType:s.mediaType},isUploading:e.isUploadingFile(s.id),onRemove:()=>t.remove(s.id)},s.id)})}),jsx(en,{image:n,onClose:()=>a(null)})]})}function sn({attachments:e}){let[t,n]=useState(null);if(e.length===0)return null;let a=e.filter(r=>Ke(r.mediaType)),s=e.filter(r=>!Ke(r.mediaType));return jsxs("div",{className:"fk:flex fk:flex-col fk:items-end fk:gap-2",children:[a.length>0?jsx("div",{className:"fk:flex fk:flex-wrap fk:justify-end fk:gap-2",children:a.map(r=>jsx(nn,{image:r,onOpen:()=>n(r),sizeClassName:"fk:size-24"},r.url))}):null,jsx(en,{image:t,onClose:()=>n(null)}),s.length>0?jsx("div",{className:"fk:flex fk:flex-wrap fk:justify-end fk:gap-2",children:s.map(r=>jsx(an,{action:jsx(Kt,{attachment:r}),file:r,href:r.url},r.url))}):null]})}function lo(e){let t=(Array.isArray(e.parts)?e.parts:[]).find(n=>n.type==="data-monitor-event");return t&&typeof t.data=="object"&&t.data!==null?t.data:null}function ln({data:e,error:t}){let n=e.total-e.events.length;return jsxs("div",{className:"fk:mr-auto fk:w-full fk:max-w-[85%] fk:space-y-1.5 fk:rounded-lg fk:border fk:border-border fk:bg-muted/40 fk:px-3.5 fk:py-2.5 fk:text-sm fk:corner-squircle",children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-xs fk:text-muted-foreground",children:[jsx(RadarIcon,{className:"fk:size-3.5 fk:shrink-0"}),jsxs("span",{className:"fk:truncate",children:["Monitor \xB7 ",e.description]})]}),jsxs("ul",{className:"fk:space-y-0.5",children:[e.events.map(a=>jsx("li",{children:a.summary},a.id)),n>0?jsxs("li",{className:"fk:text-muted-foreground",children:["\u2026and ",n.toString()," more"]}):null]}),t?jsx("p",{className:"fk:text-xs fk:text-destructive",children:t}):null]})}function uo({api:e$1,chatId:t,onTurnIntoAutomation:n,projectId:a,sending:s=false}){let{data:r,mutate:i}=qa(g(a).agentChat(t),f$1,{revalidateOnMount:false}),[d,u]=useState(null),f=r?.monitors??[];if(f.length===0)return null;async function c$2(p){u(p.id);try{await e$1.stopAgentChatMonitor(t,p.id),await i();}catch{ma$1.error("Unable to stop the monitor.");}finally{u(null);}}return jsx("div",{className:"fk:mx-auto fk:mb-2 fk:flex fk:max-w-4xl fk:flex-wrap fk:gap-2",children:f.map(p=>jsxs("div",{className:"fk:flex fk:max-w-full fk:items-center fk:gap-2 fk:rounded-full fk:border fk:border-border fk:py-1 fk:pl-3 fk:pr-1 fk:text-xs fk:text-muted-foreground",children:[jsx(RadarIcon,{className:"fk:size-3.5 fk:shrink-0 fk:animate-pulse"}),jsxs("span",{className:"fk:truncate",children:["Watching: ",p.description," \xB7 expires ",formatDistance(new Date(p.expiresAt),new Date,{addSuffix:true})]}),n&&p.sourceType&&p.sourceType!=="job"?jsxs(b$2,{children:[jsx(c,{asChild:true,children:jsx(c$1,{"aria-label":`Turn ${p.description} into an automation`,className:"fk:size-6 fk:rounded-full",disabled:s,size:"icon",variant:"ghost",onClick:()=>n(p),children:jsx(BotIcon,{className:"fk:size-3.5"})})}),jsx(e,{children:"Turn into automation"})]}):null,jsxs(b$2,{children:[jsx(c,{asChild:true,children:jsx(c$1,{"aria-label":`Stop watching ${p.description}`,className:"fk:size-6 fk:rounded-full",disabled:d===p.id,size:"icon",variant:"ghost",onClick:()=>{c$2(p);},children:jsx(XIcon,{className:"fk:size-3.5"})})}),jsx(e,{children:"Stop watching"})]})]},p.id))})}function dn(e,t){let n=t.trim();return !n||/window was closed|not completed/i.test(n)?`${e} authorization didn't finish`:/popups|different account/i.test(n)?n:`${e} authorization didn't finish: ${n.replace(/\.$/,"")}`}function Ba(e){let t=e.connections.filter(n=>n.isPrimary&&n.status==="connected");return t.find(n=>n.scope==="personal")??t.find(n=>n.scope==="project")??null}function un(e,t,n){return n==="personal"?e.allowPersonal:t}function cn(e,t,n){if(!e.enabled)return {kind:"disabled"};let a=n?e.connections.find(i=>i.id===n&&i.status==="needs_auth"):void 0;if(a)return un(e,t,a.scope)?{kind:"reconnect",connection:a}:{kind:"not_permitted"};let s=Ba(e);if(s)return {kind:"connected",connection:s};let r=e.scopes.filter(i=>un(e,t,i));return r.length>0?{kind:"connect",scopes:r}:{kind:"not_permitted"}}var Wa=createContext(null),Ee=new Map,We=new Set;function Ve(e,t){t?Ee.set(e,t):Ee.delete(e),We.forEach(n=>n());}function Ga(e){return We.add(e),()=>We.delete(e)}function Za(e){return useSyncExternalStore(Ga,()=>Ee.get(e)??null,()=>null)}var mn={personal:{description:"Only you can use this connection in this project.",title:"Personal"},project:{description:"Shared with project members who can use this plugin.",title:"Project"}};function es({busy:e,logoUrl:t$1,name:n,onContinue:a$1,onOpenChange:s$1,open:r,scopes:i,connect:d}){let[u,f]=useState(i.length===1?i[0]??null:null),c=[...ts(n,d),{description:`Remove the connection to ${n} at any time.`,title:"You stay in control"}];return jsx(k,{onOpenChange:s$1,open:r,children:jsxs(p,{className:"fk:sm:max-w-md",children:[jsxs("div",{className:"fk:flex fk:flex-col fk:items-center fk:gap-3 fk:pt-2 fk:text-center",children:[jsx(a,{className:"fk:size-16 fk:rounded-xl",src:t$1}),jsxs(s,{className:"fk:text-xl",children:["Connect to ",n]}),jsxs(t,{children:["Let the Flexkit agent access and use ",n," on your behalf."]})]}),jsx("ul",{className:"fk:space-y-3 fk:rounded-xl fk:bg-muted/60 fk:p-4 fk:corner-squircle",children:c.map(p=>jsxs("li",{className:"fk:flex fk:gap-3",children:[jsx(CheckIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0"}),jsxs("span",{children:[jsx("span",{className:"fk:block fk:text-sm fk:font-medium",children:p.title}),jsx("span",{className:"fk:block fk:text-sm fk:text-muted-foreground",children:p.description})]})]},p.title))}),i.length>1?jsx("div",{className:"fk:space-y-1.5",role:"radiogroup","aria-label":"Connection",children:i.map(p=>jsxs("button",{"aria-checked":u===p,className:`fk:flex fk:w-full fk:flex-col fk:rounded-lg fk:border fk:px-3 fk:py-2 fk:text-left fk:corner-squircle ${u===p?"fk:border-primary fk:bg-primary/5":"fk:border-border fk:hover:bg-muted/60"}`,onClick:()=>f(p),role:"radio",type:"button",children:[jsx("span",{className:"fk:text-sm fk:font-medium",children:mn[p].title}),jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:mn[p].description})]},p))}):null,jsx("p",{className:"fk:text-center fk:text-xs fk:text-muted-foreground",children:"You can manage connections anytime in AI \u2192 Plugins."}),jsx(c$1,{className:"fk:w-full",disabled:e||!u,onClick:()=>u&&a$1(u),type:"button",children:"Continue"})]})})}function ts(e,t){switch(t?.type){case "api-token":return [{title:`Paste a ${t.tokenLabel}`,description:`Flexkit stores it encrypted and sends it only to ${e}. The agent never sees it.`},{title:"You decide what the agent can do",description:"The agent only gets the access the token has."}];case "credentials":return [{title:`Enter the credentials of your ${e} app`,description:`Flexkit checks them with ${e}, stores them encrypted and never shows them to the agent.`},{title:"You decide what the agent can do",description:`The agent only gets the access scopes you give the app in ${e}.`}];default:return [{title:`Sign in securely to your ${e} account`,description:"Flexkit never sees your password."},{title:"You decide what the agent can do",description:`The agent only gets the access you approve on ${e}'s sign-in page.`}]}}function ns(e,t,n){if(!n)return `Let the Flexkit agent use ${e}`;switch(t?.type){case "api-token":return `Add a new ${t.tokenLabel} so the agent can keep using ${e}`;case "credentials":return `Enter the credentials again so the agent can keep using ${e}`;default:return `Sign in again so the agent can keep using ${e}`}}function vn({connectionId:e,pluginId:t}){let{currentProjectId:n}=f(),a$1=useMemo(()=>n?d(n):null,[n]),s=n?`/api/flexkit/${n}`:null,r=s?`${s}/plugins/${encodeURIComponent(t)}`:null,{data:i,error:d$1,mutate:u}=qa(r,f$1),{mutate:f$2}=useSWRConfig(),c=useContext(Wa),[p,x]=useState(false),v=`${n??""}:${t}:${e??""}`,k=Za(v),g=k?.status==="connecting",w=k?.status==="failed"?k:null;if(!i)return jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:rounded-2xl fk:border fk:border-border fk:p-4 fk:text-sm fk:text-muted-foreground fk:corner-squircle",children:[d$1?jsx(CircleAlertIcon,{className:"fk:size-4"}):jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}),d$1?`${t} could not be loaded.`:`Loading ${t}\u2026`]});let{plugin:y}=i,C=cn(y,i.canManage,e),_=C.kind==="reconnect"?C.connection:null;function S(E){!a$1||Ee.get(v)?.status==="connecting"||(x(false),Ve(v,{status:"connecting"}),d$4(a$1,y,E,_?{connectionId:_.id}:void 0).then(Y=>{Ve(v,null),Y&&(u().catch(()=>{}),s&&f$2(`${s}/plugins`).catch(()=>{}),c?.onConnected(t));},Y=>{let L=Y instanceof Error?Y.message:"";Ve(v,{message:dn(y.name,L),scope:E,status:"failed"});}));}let R=null,$=null;return C.kind==="connected"?R=jsxs("span",{className:"fk:flex fk:items-center fk:gap-1.5 fk:text-sm fk:text-muted-foreground",children:[jsx(CheckIcon,{className:"fk:size-4 fk:text-green-700"}),"Connected \xB7 ",C.connection.displayName]}):C.kind==="disabled"?R=jsxs("span",{className:"fk:text-sm fk:text-muted-foreground",children:["An owner turned ",y.name," off for this project."]}):C.kind==="not_permitted"?R=jsxs("span",{className:"fk:text-sm fk:text-muted-foreground",children:["Ask a project owner or developer to connect ",y.name,"."]}):w?(R=jsxs("span",{className:"fk:flex fk:items-center fk:gap-1.5 fk:text-sm fk:text-muted-foreground",children:[jsx(CircleAlertIcon,{className:"fk:size-4 fk:shrink-0 fk:text-amber-600"}),w.message]}),$=jsx(c$1,{disabled:g,onClick:()=>S(w.scope),size:"sm",type:"button",variant:"secondary",children:"Retry"})):$=jsxs(c$1,{disabled:g,onClick:()=>_?S(_.scope):x(true),size:"sm",type:"button",children:[g?jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}):null,_?"Reconnect":"Authorize"]}),jsxs("div",{className:"fk:space-y-2",children:[jsxs("div",{className:"fk:space-y-3 fk:rounded-2xl fk:border fk:border-border fk:bg-background fk:p-4 fk:corner-squircle",children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-3",children:[jsx(a,{className:"fk:size-11 fk:rounded-lg",src:y.logoUrl}),jsxs("div",{className:"fk:min-w-0 fk:flex-1",children:[jsx("div",{className:"fk:truncate fk:font-medium",children:y.name}),jsx("div",{className:"fk:truncate fk:text-sm fk:text-muted-foreground",children:ns(y.name,y.connect,!!_)})]}),$&&!w?$:null]}),R?jsxs("div",{className:"fk:flex fk:items-center fk:justify-between fk:gap-3",children:[R,w?$:null]}):null]}),C.kind==="connect"||C.kind==="reconnect"?jsx("p",{className:"fk:px-1 fk:text-xs fk:text-muted-foreground",children:"Plugin actions follow your project's approval rules. Disconnect any time in AI \u2192 Plugins."}):null,C.kind==="connect"?jsx(es,{busy:g,logoUrl:y.logoUrl,name:y.name,onContinue:S,onOpenChange:x,open:p,scopes:C.scopes,connect:y.connect}):null]})}function So({data:e,error:t,label:n}){return jsxs("div",{className:"fk:mr-auto fk:flex fk:max-w-[85%] fk:flex-wrap fk:items-center fk:gap-x-2 fk:gap-y-1 fk:text-sm fk:text-muted-foreground",children:[jsx(PlugIcon,{className:"fk:size-3.5 fk:shrink-0"}),jsxs("span",{children:["Connected ",jsx("span",{className:"fk:font-medium fk:text-foreground",children:e.pluginName}),e.accountName?` \xB7 ${e.accountName}`:""]}),n?jsxs("span",{className:"fk:text-xs",children:["\xB7 ",n]}):null,t?jsx("span",{className:"fk:text-xs fk:text-destructive",children:t}):null]})}function No(e){let t=(Array.isArray(e)?e:[]).find(n=>n.type==="data-plugin-connected");return t&&typeof t.data=="object"&&t.data!==null?t.data:null}var ie=class extends Error{},Me=class extends Error{};function hn({url:e,signal:t,state:n,onState:a,wake:s,fetchStream:r=fetch,retryMs:i=2e3}){let d=0,u=0,f=new TransformStream,c=f.writable.getWriter(),p=new AbortController;c.closed.catch(g=>p.abort(g));let x=()=>{p.abort(t.reason),c.abort(t.reason).catch(()=>{});};t.addEventListener("abort",x,{once:true}),t.aborted&&x();let v=()=>new Promise(g=>{let w=()=>{clearTimeout(y),p.signal.removeEventListener("abort",w),s?.removeEventListener("wake",w),g();},y=setTimeout(w,i);p.signal.addEventListener("abort",w,{once:true}),s?.addEventListener("wake",w,{once:true}),p.signal.aborted&&w();});async function k(){try{for(await c.write({type:"start"});!p.signal.aborted;){try{let g=await r(`${e}${e.includes("?")?"&":"?"}wire=2&startIndex=${d}`,{credentials:"include",signal:p.signal});if(g.status===404){a("unavailable"),await c.close();return}if(g.status===401||g.status===403)throw new Me("Stream access denied");if(!g.ok||!g.body)throw new Error(`Stream request failed: ${g.status}`);if(g.headers.get("x-flexkit-stream-version")!=="2")throw await g.body.cancel(),new ie("Backend uses legacy replay");a("streaming");let w=g.body.pipeThrough(new TextDecoderStream).getReader(),y="",C=!1;try{for(;!p.signal.aborted;){let{value:_,done:S}=await w.read();if(S)break;y+=_;let R;for(;(R=y.indexOf(`
|
|
8
|
+
`))>=0;){let $=y.slice(0,R);if(y=y.slice(R+1),!$)continue;let E=JSON.parse($);if(!Number.isSafeInteger(E.index)||E.index<0)throw new Error("Invalid replay cursor");if(!(E.index<d)){if(E.index!==d)throw new Error("Replay cursor gap");E.chunk&&await c.write(E.chunk),d=E.index+1,u=0,E.chunk?.type==="finish"&&E.chunk.messageMetadata?.flexkitTerminal&&(C=!0);}}if(y.length>2e6)throw new Error("Oversized replay frame");if(C)break}}finally{await w.cancel().catch(()=>{}),w.releaseLock();}if(C||n().terminal&&!y){await c.write({type:"finish"}),await c.close(),a("finished");return}}catch(g){if(p.signal.aborted||g instanceof ie||g instanceof Me||++u>=5)throw g}do a(n().paused?"paused":"streaming"),await v();while(!p.signal.aborted&&n().paused&&!n().terminal)}}catch(g){await c.abort(g).catch(()=>{});}finally{t.removeEventListener("abort",x),c.releaseLock();}}return k(),pipeJsonRender(f.readable)}var rs={pending:"Waiting for an answer.",cancelled:"The turn was stopped before you answered.",dismissed:"You skipped these questions.",expired:"Nobody answered in time."};function os({description:e,label:t,multiSelect:n,onClick:a,selected:s}){return jsxs("button",{"aria-checked":s,className:`fk:flex fk:w-full fk:items-start fk:gap-2.5 fk:rounded-lg fk:border fk:px-3 fk:py-2 fk:text-left fk:transition-colors fk:corner-squircle ${s?"fk:border-primary fk:bg-primary/5":"fk:border-border fk:hover:bg-muted/60"}`,onClick:a,role:n?"checkbox":"radio",type:"button",children:[jsx("span",{className:`fk:mt-0.5 fk:flex fk:size-4 fk:shrink-0 fk:items-center fk:justify-center fk:border ${n?"fk:rounded-sm":"fk:rounded-full"} ${s?"fk:border-primary fk:bg-primary fk:text-primary-foreground":"fk:border-muted-foreground/50"}`,children:s?jsx(CheckIcon,{className:"fk:size-3"}):null}),jsxs("span",{className:"fk:min-w-0",children:[jsx("span",{className:"fk:block fk:text-sm fk:font-medium",children:t}),e?jsx("span",{className:"fk:block fk:text-xs fk:text-muted-foreground",children:e}):null]})]})}function is({disabled:e,draft:t,onChange:n,question:a}){return jsxs("fieldset",{className:"fk:space-y-2",disabled:e,children:[jsxs("legend",{className:"fk:mb-2 fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsx(b$1,{variant:"outline",children:a.header}),jsx("span",{className:"fk:text-sm fk:font-medium",children:a.question}),a.multiSelect?jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:"Pick any"}):null]}),jsxs("div",{className:"fk:space-y-1.5",role:a.multiSelect?"group":"radiogroup",children:[a.options.map(s=>jsx(os,{description:s.description,label:s.label,multiSelect:a.multiSelect,onClick:()=>n(Bt(a,t,s.label)),selected:t.selected.includes(s.label)},s.label)),jsx(b$5,{"aria-label":`Your own answer to: ${a.question}`,className:"fk:h-9",maxLength:4e3,onChange:s=>n(Xt(a,t,s.target.value)),placeholder:"Other \u2014 type your own answer",value:t.other})]})]})}function ls({data:e}){return e.status==="answered"&&e.message!==void 0?jsxs("div",{className:"fk:space-y-1",children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:e.questions.map(t=>t.question).join(" \xB7 ")}),jsxs("p",{className:"fk:text-sm",children:["You replied: ",jsxs("span",{className:"fk:whitespace-pre-wrap",children:["\u201C",e.message,"\u201D"]})]})]}):e.status!=="answered"?jsxs("div",{className:"fk:space-y-1",children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:e.questions.map(t=>t.question).join(" \xB7 ")}),jsx("p",{className:"fk:text-sm fk:text-muted-foreground",children:rs[e.status]})]}):jsx("dl",{className:"fk:space-y-1.5",children:e.questions.map((t,n)=>jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-baseline fk:gap-x-2",children:[jsx("dt",{className:"fk:text-xs fk:text-muted-foreground",children:t.question}),jsx("dd",{className:"fk:text-sm fk:font-medium",children:Qt(e.answers?.[n])})]},n))})}function bn({answer:e,data:t}){let[n,a]=useState(()=>qt(t.questions)),[s,r]=useState(null),[i,d]=useState(null),[u,f]=useState(""),c=t.status==="pending"&&s?s:t;if(c.status!=="pending"||!e)return jsx(ls,{data:c});let p=Jt(n);async function x(v){if(e){d(v.action),f("");try{let k=await e(t.questionId,v);k&&r({...k.answers?{answers:k.answers}:{},...k.message!==null?{message:k.message}:{},questionId:k.id,questions:k.questions,status:k.status});}catch(k){f(k instanceof Error?k.message:"Could not send the answer.");}finally{d(null);}}}return jsxs("form",{className:"fk:space-y-5",onSubmit:v=>{v.preventDefault(),p&&x({action:"answer",answers:p});},children:[t.questions.map((v,k)=>jsx(is,{disabled:i!==null,draft:n[k]??{other:"",selected:[]},onChange:g=>a(w=>w.map((y,C)=>C===k?g:y)),question:v},k)),u?jsx("p",{className:"fk:text-xs fk:text-destructive",children:u}):null,jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(c$1,{disabled:!p||i!==null,size:"sm",type:"submit",children:[i==="answer"?jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}):null,"Submit"]}),jsxs(c$1,{disabled:i!==null,onClick:()=>{x({action:"dismiss"});},size:"sm",type:"button",variant:"ghost",children:[i==="dismiss"?jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}):null,"Skip"]}),jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:"or reply in the chat"})]})]})}function us(e){let t=[];return e.page!==void 0&&t.push(`p. ${String(e.page)}`),e.slide!==void 0&&t.push(`slide ${String(e.slide)}`),e.headingPath&&e.headingPath.length>0&&t.push(e.headingPath.join(" \u203A ")),t.join(" \xB7 ")}function xn(e){let t=new Map;for(let n of e??[]){let a=t.get(n.sourceId);a||(a={passages:[],sourceId:n.sourceId,sourceTitle:n.sourceTitle},t.set(n.sourceId,a)),!a.passages.some(s=>s.passageId===n.passageId)&&a.passages.push({excerpt:n.excerpt,locator:us(n.locator),passageId:n.passageId});}return [...t.values()]}function wn(e,t){let n=t.reduce((a,s)=>a+s.passages.length,0);return n===0?`No passages matched "${e}"`:`${String(n)} ${n===1?"passage":"passages"} from ${String(t.length)} ${t.length===1?"document":"documents"} for "${e}"`}var Ds=lazy(()=>import('./spec-renderer-Z6GVHLFU.js').then(e=>({default:e.RunSpecPart})));function Is(e){return jsx(Suspense,{fallback:null,children:jsx(Ds,{...e})})}function Es(){let{currentProjectId:e}=f();return {api:useMemo(()=>e?d(e):null,[e]),projectId:e}}var An=5,In=2e3,En=120,Ge="data-spec",Mn=createContext(null),Ms=createContext(false);function $s(e){return new Promise(t=>window.setTimeout(t,e))}function zs(e){return e instanceof Error?e.name==="AbortError"||e.message.toLowerCase().includes("aborted"):false}function _s(e){return e.some(t=>!Ie(t))}function Ls(e){let t=new Set;for(let n of e)for(let a of n.parts)a.type==="data-user-message"&&a.id&&t.add(a.id);return t}function js(e){let t=Ls(e),n=[];for(let a of e){if(a.role==="user"){t.has(a.id)||n.push(a);continue}if(a.role!=="assistant"){n.push(a);continue}let s=[],r=0,i=()=>{_s(s)&&n.push({...a,id:`${a.id}-${r.toString()}`,parts:s}),r++,s=[];};for(let d of a.parts){if(d.type==="data-user-message"){let u=b(d);i(),n.push({id:d.id??crypto.randomUUID(),parts:u.parts,role:"user"});continue}s.push(d);}i();}return n}function si(e){return useMemo(()=>js(e),[e])}function le(e){return e==="success"||e==="failed"||e==="cancelled"||e==="skipped"}function $n({latestMessage:e,recordStatus:t,suppressApprovalPause:n}){return le(t)||n||t==="running"?false:t==="awaiting_approval"?true:Xe(e)||Qe(e)}function ri(e,t){let[n,a]=useState(false),s=Os(n?e:"",t),[r,i]=useState(),[d,u]=useState("streaming"),f=useRef(t);f.current=t;let c=useRef(null);c.current||(c.current=new EventTarget);let p=c.current,x=t?.resumeToken;return useEffect(()=>{p.dispatchEvent(new Event("wake"));},[x,p]),useEffect(()=>{if(a(false),i(void 0),!e){u("unavailable");return}let v=new AbortController,k,g,w=()=>{k=void 0,g&&!v.signal.aborted&&i({...g});},y=hn({url:e,signal:v.signal,state:()=>({terminal:le(f.current?.recordStatus),paused:$n({latestMessage:g,recordStatus:f.current?.recordStatus,suppressApprovalPause:f.current?.suppressApprovalPause??false})}),onState:C=>{v.signal.aborted||u(C);},wake:p});return (async()=>{try{for await(let C of readUIMessageStream({stream:y,terminateOnError:!0}))g=C,k||(k=setTimeout(w,En));w();}catch(C){if(v.signal.aborted)return;C instanceof ie?a(true):(console.error("Run stream error",C),u("error"));}})(),()=>{v.abort(),k&&clearTimeout(k);}},[e,p]),n?s:{message:r?Je(r,t?.decidedApprovals??{}):void 0,status:d}}function Os(e,t){let[n,a]=useState(),[s,r]=useState("streaming"),i=t?.recordStatus,d=t?.resumeToken??0,u=useRef(t?.decidedApprovals??{});u.current=t?.decidedApprovals??{};let f=useRef(t?.suppressApprovalPause??false);f.current=t?.suppressApprovalPause??false;let c=useRef(e),p=useRef(n);return p.current=n,useEffect(()=>{let x=c.current!==e;if(c.current=e,!e){a(void 0),r("unavailable");return}let v=new AbortController,k=x?void 0:p.current,g=x?0:k?.parts.length??0;if(x)a(void 0);else if(k&&(i==="running"||le(i))){let S=Je(k,u.current);S!==k&&(k=S,a(S));}r("streaming");let w=e.includes("?")?"&":"?",y=async()=>{let S=await fetch(`${e}${w}startIndex=0`,{credentials:"include",signal:v.signal});if(S.status===404)return "unavailable";if(!S.ok||!S.body)throw new Error(`Failed to fetch the run stream (status ${S.status.toString()})`);let R=false,E=parseJsonEventStream({schema:uiMessageChunkSchema,stream:S.body}).pipeThrough(new TransformStream({transform:(j,zn)=>{if(!j.success)throw j.error;j.value.type==="finish"&&(R=true),zn.enqueue(j.value);}})),Y=readUIMessageStream({onError:j=>{v.signal.aborted||console.error("Run stream chunk error",j);},stream:E}),L=null,I=g===0,ke=(j=false)=>{v.signal.aborted||!k||!I&&(I=j||k.parts.length>=g,!I)||a({...k});};try{for await(let j of Y){if(v.signal.aborted)break;k=j,L===null&&(L=window.setTimeout(()=>{L=null,ke();},En));}}finally{L!==null&&(window.clearTimeout(L),L=null),ke(true);}return R?"finished":"incomplete"},C=async()=>{let S=0;for(;!v.signal.aborted;){S>0&&await $s(In);try{let R=await y();if(v.signal.aborted)return;if(R==="unavailable"){r("unavailable");return}if(R==="finished"&&le(i)){r("finished");return}if(le(i)){r("finished");return}if($n({latestMessage:k,recordStatus:i,suppressApprovalPause:f.current})){r("paused");return}if(!(i==="running"||f.current)&&S>=An-1){r("error");return}}catch(R){if(v.signal.aborted||zs(R))return;if(console.error("Run stream error",R),le(i)){r("finished");return}if(!(i==="running"||f.current)&&S>=An-1){r("error");return}}S+=1;}},_=window.setTimeout(()=>{C();},0);return ()=>{window.clearTimeout(_),v.abort("Run replay unmounted");}},[i,d,e]),{message:n,status:s}}function oi(e){return {affectedCount:e.affectedCount,approvalId:e.id,decidedBy:e.decidedBy??void 0,operationsSummary:e.operationsSummary,reason:e.reason??void 0,status:e.status}}function Fs(e){let t=e.trim();return t?t.split(`
|
|
9
|
+
`).every(n=>/^`{3,}[\w-]*$/.test(n.trim())):false}function Us({attachments:e,text:t}){return jsxs("div",{className:"fk:ml-auto fk:flex fk:w-fit fk:max-w-[70%] fk:flex-col fk:items-end fk:gap-1",children:[jsx(sn,{attachments:e}),t.trim()?jsx("div",{className:"fk:whitespace-pre-wrap fk:rounded-xl fk:bg-muted fk:dark:bg-white/20 fk:px-3.5 fk:py-2 fk:text-base fk:corner-squircle",children:t}):null,jsxs("span",{className:"fk:inline-flex fk:items-center fk:gap-1 fk:text-xs fk:text-muted-foreground",children:[jsx(CornerDownRightIcon,{className:"fk:size-3 fk:shrink-0"}),"Added while the agent was working"]})]})}function ii({api:e,part:t,partIndex:n,parts:a}){if(Ie(t))return null;if(me(t.type)){let s=De(t);return s?jsx(Bs,{message:s}):null}if(t.type==="text")return Fs(t.text)&&a.some(r=>r.type===Ge)?null:jsx(qs,{part:t});if(t.type==="data-knowledge-search")return jsx(Ws,{message:b(t)});if(t.type==="data-generating-files")return jsx(Ks,{message:b(t)});if(t.type==="data-run-artifact")return jsx(Ys,{api:e,message:b(t)});if(t.type==="data-tool-delivery")return jsx(Vs,{message:b(t)});if(t.type==="data-run-summary")return jsx(Gs,{message:b(t)});if(t.type==="data-subtask"){let s=b(t),r=s.status==="running"?`Running "${s.title}"`:s.status==="done"?`Completed "${s.title}"${typeof s.stepsUsed=="number"?` in ${s.stepsUsed.toString()} steps`:""}`:`"${s.title}" failed: ${s.error?.message??"unknown error"}`;return jsxs(B,{children:[jsxs(X,{children:[jsx(BotIcon,{className:"fk:size-3.5"}),"Subtask"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:s.status==="error",loading:s.status==="running"})}),jsx("span",{className:"fk:text-xs",children:r}),s.resultPreview?jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:s.resultPreview}):null]})]})}if(t.type==="data-mid-turn-message"){let s=b(t);return s.monitorEvent?jsx(ln,{data:s.monitorEvent}):jsx(Us,{attachments:s.attachments,text:s.text})}if(t.type==="data-context-compaction"){let s=b(t);return jsxs("p",{className:"fk:text-xs fk:text-muted-foreground",children:["Earlier messages (",s.summarizedMessageCount.toString(),") were summarized to keep this conversation within the model's context. Details may need to be re-fetched."]})}if(t.type==="data-plugin-connection"){let s=b(t);return jsx(vn,{connectionId:s.connectionId,pluginId:s.pluginId})}if(t.type==="data-suggested-prompt")return null;if(t.type==="data-turn-error"){let s=b(t);return jsxs(B,{className:"fk:border-red-700/40",children:[jsxs(X,{children:[jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),jsx("span",{children:"Turn failed"})]}),jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:s.message})]})}if(t.type==="data-mutation-approval"){let s=b(t);return Be(s)?jsx(tr,{message:s}):jsx(Zs,{api:e,message:s})}return t.type==="data-user-question"?jsx(er,{data:b(t)}):t.type==="data-bulk-graphql-action"?jsx(nr,{message:b(t)}):t.type===Ge?a.slice(n+1).find(r=>r.type===Ge)?null:jsx(Is,{parts:a}):t.type.startsWith("data-")?jsx(ar,{part:t}):null}function qs({part:e}){return jsx(mb,{className:"fk:min-w-0 fk:max-w-full fk:overflow-x-auto fk:text-base fk:leading-relaxed fk:text-foreground",isAnimating:e.state==="streaming",children:e.text})}function Bs({message:e}){return jsxs("div",{className:"fk:flex fk:items-start fk:gap-2 fk:rounded-xl fk:border fk:border-red-700/40 fk:bg-destructive/5 fk:px-3.5 fk:py-3 fk:text-sm fk:corner-squircle",children:[jsx(XCircleIcon,{className:"fk:mt-0.5 fk:size-3.5 fk:shrink-0 fk:text-red-700"}),jsx("span",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e})]})}var Xs=1e3;function Js({text:e}){let t=useRef(typeof performance>"u"?0:performance.now()),n=()=>-(((typeof performance>"u"?0:performance.now())-t.current)%Xs),[a,s]=useState({current:e,currentDelayMs:0,key:0,previous:null,previousDelayMs:0});return useEffect(()=>{s(r=>r.current===e?r:{current:e,currentDelayMs:n(),key:r.key+1,previous:r.current,previousDelayMs:r.currentDelayMs});},[e]),jsxs("span",{className:"fk:relative fk:block fk:h-5 fk:min-w-0 fk:flex-1 fk:overflow-hidden",children:[a.previous?jsx("span",{"aria-hidden":true,className:"fk:absolute fk:inset-x-0 fk:top-0 fk:block fk:animate-roll-up-out",children:jsx("span",{className:"fk:block fk:truncate fk:shimmer fk:shimmer-duration-1000",style:{animationDelay:`${a.previousDelayMs.toString()}ms`},children:a.previous})},`previous-${a.key.toString()}`):null,jsx("span",{className:a.previous?"fk:block fk:animate-roll-up-in":"fk:block",role:"status",children:jsx("span",{className:"fk:block fk:truncate fk:shimmer fk:shimmer-duration-1000",style:{animationDelay:`${a.currentDelayMs.toString()}ms`},children:a.current})},`current-${a.key.toString()}`)]})}var Qs=1e3;function Hs(e,t){let n=Qs,[a,s]=useState(e),r=useRef(Date.now()),i=useRef(e);return i.current=e,useEffect(()=>{if(e===a)return;let d=Math.max(0,n-(Date.now()-r.current)),u=window.setTimeout(()=>{r.current=Date.now(),s(i.current);},d);return ()=>{window.clearTimeout(u);}},[a,e,n]),a}function li({label:e,visible:t}){let n=Hs(e);return jsx("div",{"aria-hidden":!t,className:`fk:flex fk:h-9 fk:items-center fk:text-sm fk:text-muted-foreground fk:transition-[opacity,visibility] fk:duration-200 ${t?"fk:visible fk:opacity-100":"fk:invisible fk:opacity-0"}`,children:jsx(Js,{text:n})})}function B({children:e,className:t=""}){return jsx("div",{className:`fk:min-w-0 fk:max-w-full fk:overflow-x-auto fk:rounded-xl fk:border fk:border-border fk:bg-background fk:px-3.5 fk:py-3 fk:text-sm ${t} fk:corner-squircle`,children:e})}function X({children:e}){return jsx("div",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-muted-foreground",children:e})}function ze({isError:e,loading:t}){return t?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):e?jsx(XIcon,{className:"fk:size-4 fk:text-red-700"}):jsx(CheckIcon,{className:"fk:size-4"})}function _e({error:e,icon:t,loading:n,message:a,title:s}){return jsxs(B,{children:[jsxs(X,{children:[t,s]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:!!e,loading:n})}),jsx("span",{className:"fk:text-xs",children:a})]})]})}function Ks({message:e}){let t=["error","uploading","generating"].includes(e.status),n=t?e.paths.slice(0,e.paths.length-1):e.paths,a=t?e.paths[e.paths.length-1]??"":null;return jsxs(B,{children:[jsxs(X,{children:[jsx(CloudUploadIcon,{className:"fk:size-3.5"}),jsx("span",{children:e.status==="done"?"Uploaded files":"Generating files"})]}),jsxs("div",{className:"fk:space-y-1 fk:text-sm",children:[n.map((s,r)=>jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(CheckIcon,{className:"fk:size-4"}),jsx("span",{className:"fk:whitespace-pre-wrap",children:s})]},`${s}-${r.toString()}`)),typeof a=="string"?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(ze,{isError:e.status==="error",loading:e.status!=="error"}),jsx("span",{children:e.status==="error"?e.error?.message??a:a})]}):null]})]})}function Ys({api:e,message:t}){let n=t.status==="done"&&t.artifactId,a=n?b$3()&&t.url||e.getArtifactUrl(t.artifactId??""):"",s=n?e.getArtifactUrl(t.artifactId??"",{download:true}):"",r=sr(t.sizeBytes);return jsxs(B,{children:[jsxs(X,{children:[jsx(FileTextIcon,{className:"fk:size-3.5"}),t.kind==="csv"||t.kind==="json"?"Exported file":t.status==="done"?"Published artifact":"Publishing artifact"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ze,{isError:t.status==="error",loading:t.status==="uploading"})}),jsxs("div",{className:"fk:min-w-0 fk:space-y-2",children:[jsxs("div",{className:"fk:min-w-0",children:[jsx("div",{className:"fk:truncate fk:font-medium",children:t.filename}),jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[t.status==="uploading"&&"Uploading to artifacts",t.status==="done"&&[rr(t),r].filter(Boolean).join(" \xB7 "),t.status==="error"&&(t.error?.message??"Failed to publish artifact")]})]}),n?jsxs("div",{className:"fk:flex fk:flex-wrap fk:gap-2",children:[t.kind==="csv"?null:jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsx("a",{href:a,rel:"noreferrer",target:"_blank",children:"Preview"})}),jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:s,children:[jsx(DownloadIcon,{className:"fk:size-3"}),"Download"]})}),t.url?jsx(c$1,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:t.url,rel:"noreferrer",target:"_blank",children:[jsx(LinkIcon,{className:"fk:size-3"}),"Permanent link"]})}):null]}):null]})]})]})}function Vs({message:e}){let t=e.provider==="slack"?"Slack":"Microsoft Teams",n=e.provider==="slack"?jsx(MessageSquareIcon,{className:"fk:size-3.5"}):jsx(SendIcon,{className:"fk:size-3.5"});return jsx(_e,{error:e.error?.message,icon:n,loading:e.status==="loading",message:e.status==="error"?e.error?.message??`Failed to send result to ${e.channelName}`:`${e.status==="done"?"Sent":"Sending"} result to ${e.channelName}`,title:`${t} Delivery`})}function Ws({message:e}){let{currentProjectId:t}=f(),n=useMemo(()=>xn(e.results),[e.results]);return e.status==="error"?jsx(_e,{error:e.error?.message??"The knowledge search failed",icon:jsx(LibraryIcon,{className:"fk:size-3.5"}),loading:false,message:e.error?.message??"The knowledge search failed",title:"Knowledge search"}):jsxs(B,{children:[jsxs(X,{children:[jsx(LibraryIcon,{className:"fk:size-3.5"}),jsx("span",{children:"Knowledge search"})]}),jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:wn(e.query,n)}),n.length>0?jsxs(Cc,{className:"fk:mb-0 fk:mt-2",children:[jsxs(Dc,{count:n.length,children:[jsx("p",{className:"fk:font-medium",children:n.length===1?"Show the cited passages":`Show passages from ${String(n.length)} documents`}),jsx(ChevronDownIcon,{className:"fk:size-4"})]}),jsx(Ec,{className:"fk:w-full",children:n.map(a=>jsxs("div",{className:"fk:flex fk:flex-col fk:gap-1.5",children:[t?jsxs(Link,{className:"fk:flex fk:w-fit fk:items-center fk:gap-2 fk:font-medium fk:text-foreground fk:underline-offset-2 fk:hover:underline",to:o(t,a.sourceId),children:[jsx(BookOpenIcon,{className:"fk:size-4"}),jsx("span",{children:a.sourceTitle})]}):jsxs("span",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-foreground",children:[jsx(BookOpenIcon,{className:"fk:size-4"}),jsx("span",{children:a.sourceTitle})]}),jsx("ul",{className:"fk:flex fk:flex-col fk:gap-1.5 fk:pl-6",children:a.passages.map(s=>jsxs("li",{className:"fk:text-xs fk:text-muted-foreground",children:[s.locator?jsxs("span",{className:"fk:mr-1 fk:font-medium fk:text-foreground/80",children:[s.locator,":"]}):null,jsxs("span",{className:"fk:italic",children:["\u201C",s.excerpt,"\u201D"]})]},s.passageId))})]},a.sourceId))})]}):null]})}function Gs({message:e}){let t=e.status==="success"?jsx(CheckCircle2Icon,{className:"fk:size-3.5 fk:text-green-700"}):e.status==="skipped"?jsx(CircleSlashIcon,{className:"fk:size-3.5"}):jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),n=e.status==="success"?"Run completed":e.status==="skipped"?"Run skipped":"Run failed";return jsxs(B,{className:e.status==="failed"?"fk:border-red-700/40":"fk:border-green-700/40",children:[jsxs(X,{children:[t,jsx("span",{children:n})]}),e.status==="failed"?jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e.summary}):null]})}function Zs({api:e,message:t}){let{projectId:n}=Es(),a=useContext(Mn),s=useContext(Ms),r=useRef(void 0),{data:i,error:d,isValidating:u,mutate:f}=qa(n?g(n).approval(t.approvalId):null,f$1,{refreshInterval:g=>t.status!=="pending"||g?.approval?.status&&g.approval.status!=="pending"?0:In}),c=i?.approval?.status,p=(c??t.status)==="pending",x=i?.approval?.kind==="schema"&&i.approval.status==="approved";useEffect(()=>{!x||!n||Ne({approvalId:t.approvalId,approvalUrl:g(n).approval(t.approvalId),projectId:n});},[x,t.approvalId,n]),useEffect(()=>{f();},[t.status,f]),useEffect(()=>{let g=r.current;r.current=c,!(t.status!=="pending"||!c||c==="pending")&&g==="pending"&&a?.onApprovalDecided(i?.approval?.id??t.approvalId,c);},[c,i?.approval?.id,t.approvalId,t.status,a]);function v(g){g.status!=="pending"&&(r.current=g.status),f(),a?.onApprovalDecided(g.id,g.status);}let k;if(i?.approval)k=jsx(Ot,{api:e,approval:i.approval,chat:s,onDecided:v},i.approval.status);else if(d&&!u){let g=d instanceof Error&&d.message?d.message:"Request failed";k=jsxs("div",{className:"fk:space-y-2",children:[jsxs("p",{className:"fk:text-xs fk:text-destructive",children:["Failed to load proposal ",t.operationsSummary,": ",g]}),jsx(c$1,{size:"sm",variant:"outline",onClick:()=>{f();},children:"Retry"})]});}else k=jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-xs fk:text-muted-foreground",children:[jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}),jsxs("span",{children:["Loading proposal ",t.operationsSummary,"..."]})]});return jsxs(B,{children:[jsxs(X,{children:[s?jsx(ShieldIcon,{className:"fk:size-3.5"}):jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),s?"Approval request":"Mutation approval",p?jsx(LoaderCircle,{className:"fk:ml-1 fk:size-3.5 fk:animate-spin"}):null]}),jsx("div",{className:"fk:mt-2",children:k}),t.status==="error"&&t.error?jsx("p",{className:"fk:mt-2 fk:text-xs fk:text-destructive",children:t.error.message}):null]})}function er({data:e}){let t=useContext(Mn),n=e.questions.length>1;return jsxs(B,{children:[jsxs(X,{children:[jsx(MessageCircleQuestionIcon,{className:"fk:size-3.5"}),e.status==="pending"?n?"The agent has questions":"The agent has a question":n?"Questions":"Question"]}),jsx("div",{className:"fk:mt-3",children:jsx(bn,{answer:t?.answerQuestion,data:e},e.status)})]})}function tr({message:e}){let t=e.operationsSummary.replace(/^Call /,"");return jsx(_e,{error:e.status==="error"?e.error?.message??"The call failed.":void 0,icon:jsx(ShieldCheckIcon,{className:"fk:size-3.5"}),loading:false,message:e.status==="error"?`${t}: ${e.error?.message??"The call failed."}`:`${t} \xB7 Auto-approved by Jev`,title:"Plugin call"})}function nr({message:e}){let t=[typeof e.processedItems=="number"?`${e.processedItems.toString()} processed`:"",typeof e.changedItems=="number"?`${e.changedItems.toString()} changed`:"",typeof e.failedItems=="number"?`${e.failedItems.toString()} failed`:"",typeof e.totalItems=="number"?`${e.totalItems.toString()} total`:""].filter(Boolean);return jsx(_e,{error:e.error?.message,icon:jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),loading:e.status==="loading"||e.status==="running",message:e.status==="error"?e.error?.message??`Failed bulk ${e.operationName}`:`${e.status==="done"?"Completed":"Running"} ${e.operationName}${t.length>0?` (${t.join(", ")})`:""}`,title:"Bulk GraphQL action"})}function ar({part:e}){return jsxs(B,{className:"fk:bg-muted/30",children:[jsxs(X,{children:[jsx(CheckCircle2Icon,{className:"fk:size-3.5"}),e.type.replace(/^data-/,"").replaceAll("-"," ")]}),jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"This run emitted a structured event that is not yet rendered by Studio."})]})}function sr(e){if(typeof e!="number")return "";if(e<1024)return `${e.toString()} B`;let t=e/1024;return t<1024?`${t.toFixed(1)} KB`:`${(t/1024).toFixed(1)} MB`}function rr(e){return e.kind==="pdf"?"PDF artifact":e.kind==="html"?"HTML artifact":e.kind==="csv"?"CSV file":e.kind==="json"?"JSON file":"Artifact"}export{Ms as A,si as B,le as C,ri as D,oi as E,ii as F,Bs as G,li as H,Zs as I,St as a,Wn as b,Ot as c,Sr as d,Ie as e,ba as f,Xe as g,Ut as h,xa as i,Qe as j,wa as k,Yt as l,Yr as m,Vr as n,Wr as o,Gr as p,sn as q,lo as r,ln as s,uo as t,Wa as u,So as v,No as w,Es as x,In as y,Mn as z};//# sourceMappingURL=chunk-DFBG7PUJ.js.map
|
|
10
|
+
//# sourceMappingURL=chunk-DFBG7PUJ.js.map
|