@codeworksh/cli 0.9.0-canary.167.1.g6ddcc8db → 0.9.0-canary.168.1.ge6d0f923
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/{acp-CmtcmhuX.mjs → acp-C2GCSrJd.mjs} +6 -5
- package/acp-C2GCSrJd.mjs.map +1 -0
- package/{add-Bmholf85.mjs → add-Be7-HfBj.mjs} +2 -2
- package/{add-Bmholf85.mjs.map → add-Be7-HfBj.mjs.map} +1 -1
- package/{add-Ct20ZUEC.mjs → add-D2ly9-x3.mjs} +3 -3
- package/{add-Ct20ZUEC.mjs.map → add-D2ly9-x3.mjs.map} +1 -1
- package/{catalog-BJScfJLW.mjs → catalog-Dzi9__Rq.mjs} +2 -2
- package/{catalog-BJScfJLW.mjs.map → catalog-Dzi9__Rq.mjs.map} +1 -1
- package/categories-DYD_3Pt8.mjs +19 -0
- package/categories-DYD_3Pt8.mjs.map +1 -0
- package/{check-ki1450h-.mjs → check-DzxfN43i.mjs} +2 -2
- package/{check-ki1450h-.mjs.map → check-DzxfN43i.mjs.map} +1 -1
- package/{connect-KX-A0EzQ.mjs → connect-D4w0dmRc.mjs} +5 -5
- package/{connect-KX-A0EzQ.mjs.map → connect-D4w0dmRc.mjs.map} +1 -1
- package/{control-Cotypk4e.mjs → control-CFQeKIKx.mjs} +4 -4
- package/{control-Cotypk4e.mjs.map → control-CFQeKIKx.mjs.map} +1 -1
- package/create-Bt56MHKu.mjs +35 -0
- package/create-Bt56MHKu.mjs.map +1 -0
- package/{devices-BcuQ11QF.mjs → devices-DNzXKhNy.mjs} +3 -3
- package/{devices-BcuQ11QF.mjs.map → devices-DNzXKhNy.mjs.map} +1 -1
- package/disconnect-CHEHx_ic.mjs +2 -0
- package/{disconnect-CCI1DLJ0.mjs → disconnect-CXha4LTk.mjs} +4 -4
- package/{disconnect-CCI1DLJ0.mjs.map → disconnect-CXha4LTk.mjs.map} +1 -1
- package/disconnect-Cx0sydNl.mjs +19 -0
- package/disconnect-Cx0sydNl.mjs.map +1 -0
- package/discover-wWs8qDQd.mjs +35 -0
- package/discover-wWs8qDQd.mjs.map +1 -0
- package/{discovery-D2ftXE5a.mjs → discovery-C-ploGdg.mjs} +2 -2
- package/{discovery-D2ftXE5a.mjs.map → discovery-C-ploGdg.mjs.map} +1 -1
- package/{fork-DkYRL_nQ.mjs → fork-TUz05qSe.mjs} +3 -3
- package/{fork-DkYRL_nQ.mjs.map → fork-TUz05qSe.mjs.map} +1 -1
- package/{identity-Llk4K_8w.mjs → identity-Cjr43dhQ.mjs} +2 -2
- package/{identity-Llk4K_8w.mjs.map → identity-Cjr43dhQ.mjs.map} +1 -1
- package/index.mjs +49 -39
- package/index.mjs.map +1 -1
- package/{install-hs3tvWLA.mjs → install-BtoWHZoI.mjs} +2 -2
- package/{install-hs3tvWLA.mjs.map → install-BtoWHZoI.mjs.map} +1 -1
- package/{link-BzFGtDKJ.mjs → link-Cd6T22_n.mjs} +3 -3
- package/{link-BzFGtDKJ.mjs.map → link-Cd6T22_n.mjs.map} +1 -1
- package/{list-sLzs2Y7w.mjs → list-Bn5CvS1y.mjs} +3 -3
- package/{list-sLzs2Y7w.mjs.map → list-Bn5CvS1y.mjs.map} +1 -1
- package/{list-D1c5uzCc.mjs → list-CdS1_gFF.mjs} +2 -2
- package/{list-D1c5uzCc.mjs.map → list-CdS1_gFF.mjs.map} +1 -1
- package/list-D6ABpoQC.mjs +27 -0
- package/list-D6ABpoQC.mjs.map +1 -0
- package/{list-DhL_z5v2.mjs → list-DAA92mUG.mjs} +3 -3
- package/{list-DhL_z5v2.mjs.map → list-DAA92mUG.mjs.map} +1 -1
- package/{list-Dt0_ol5P.mjs → list-MiZ6rD_w.mjs} +3 -3
- package/{list-Dt0_ol5P.mjs.map → list-MiZ6rD_w.mjs.map} +1 -1
- package/{login-BxiN8frI.mjs → login-C_tBeHg6.mjs} +3 -3
- package/{login-BxiN8frI.mjs.map → login-C_tBeHg6.mjs.map} +1 -1
- package/login-DnOTWBy8.mjs +26 -0
- package/login-DnOTWBy8.mjs.map +1 -0
- package/{login-S-2L5YYB.mjs → login-Q_ezdpon.mjs} +3 -3
- package/{login-S-2L5YYB.mjs.map → login-Q_ezdpon.mjs.map} +1 -1
- package/{logout-BeMvfZkG.mjs → logout-BjL1W-0I.mjs} +3 -3
- package/{logout-BeMvfZkG.mjs.map → logout-BjL1W-0I.mjs.map} +1 -1
- package/{logout-CKcRACIf.mjs → logout-E_dRjl1L.mjs} +3 -3
- package/{logout-CKcRACIf.mjs.map → logout-E_dRjl1L.mjs.map} +1 -1
- package/package-BsCtRg3n.mjs +6 -0
- package/package-BsCtRg3n.mjs.map +1 -0
- package/package.json +4 -4
- package/{pair-BhGzBBV8.mjs → pair-BBneOJZJ.mjs} +3 -3
- package/{pair-BhGzBBV8.mjs.map → pair-BBneOJZJ.mjs.map} +1 -1
- package/{providers-DdBYxi9t.mjs → providers-BYnMGDs7.mjs} +3 -3
- package/{providers-DdBYxi9t.mjs.map → providers-BYnMGDs7.mjs.map} +1 -1
- package/reconnect-BKpud0ma.mjs +2 -0
- package/{refresh-BgQfD2zv.mjs → refresh-CvE_f1Fa.mjs} +3 -3
- package/{refresh-BgQfD2zv.mjs.map → refresh-CvE_f1Fa.mjs.map} +1 -1
- package/{refresh-Cy6abMk_.mjs → refresh-Dy9kI2El.mjs} +3 -3
- package/{refresh-Cy6abMk_.mjs.map → refresh-Dy9kI2El.mjs.map} +1 -1
- package/{relay-BmHXs1yg.mjs → relay-CO46Wh73.mjs} +3 -3
- package/{relay-BmHXs1yg.mjs.map → relay-CO46Wh73.mjs.map} +1 -1
- package/{relink-Dxg1kstB.mjs → relink-DxftNq9n.mjs} +3 -3
- package/{relink-Dxg1kstB.mjs.map → relink-DxftNq9n.mjs.map} +1 -1
- package/{reload-CUyG343t.mjs → reload-DRp3UlHQ.mjs} +3 -3
- package/{reload-CUyG343t.mjs.map → reload-DRp3UlHQ.mjs.map} +1 -1
- package/remove-Bad0ln8h.mjs +22 -0
- package/remove-Bad0ln8h.mjs.map +1 -0
- package/{remove-BXmNNX2f.mjs → remove-C0e5sHqb.mjs} +3 -3
- package/{remove-BXmNNX2f.mjs.map → remove-C0e5sHqb.mjs.map} +1 -1
- package/{remove-CJ__oofS.mjs → remove-CdcoheOp.mjs} +2 -2
- package/{remove-CJ__oofS.mjs.map → remove-CdcoheOp.mjs.map} +1 -1
- package/{restart-CMDZZJ4N.mjs → restart-CvkGtFq2.mjs} +4 -4
- package/{restart-CMDZZJ4N.mjs.map → restart-CvkGtFq2.mjs.map} +1 -1
- package/{revoke-DigrkMoL.mjs → revoke-DoMHa1vL.mjs} +3 -3
- package/{revoke-DigrkMoL.mjs.map → revoke-DoMHa1vL.mjs.map} +1 -1
- package/{run-BN0xfxh_.mjs → run-n_t47yPB.mjs} +8 -5
- package/run-n_t47yPB.mjs.map +1 -0
- package/{runtime-Q4G4z83G.mjs → runtime-CyXV7HH_.mjs} +152 -9
- package/runtime-CyXV7HH_.mjs.map +1 -0
- package/{serve-CfjS09-r.mjs → serve-BaNbYK1f.mjs} +27 -11
- package/serve-BaNbYK1f.mjs.map +1 -0
- package/service-CA6VAOdR.mjs +1652 -0
- package/service-CA6VAOdR.mjs.map +1 -0
- package/{service-B0O4PjbL.mjs → service-YVNwFMNf.mjs} +2 -2
- package/{service-B0O4PjbL.mjs.map → service-YVNwFMNf.mjs.map} +1 -1
- package/shared-CA47qIai.mjs +212 -0
- package/shared-CA47qIai.mjs.map +1 -0
- package/{shared-C2sMimyK.mjs → shared-CDJQxUb9.mjs} +4 -4
- package/{shared-C2sMimyK.mjs.map → shared-CDJQxUb9.mjs.map} +1 -1
- package/{shared-C4j4rGe4.mjs → shared-D_MVXtOf.mjs} +3 -3
- package/{shared-C4j4rGe4.mjs.map → shared-D_MVXtOf.mjs.map} +1 -1
- package/{start-DbCTFswo.mjs → start-D3lqmljh.mjs} +4 -4
- package/{start-DbCTFswo.mjs.map → start-D3lqmljh.mjs.map} +1 -1
- package/{status-CR_E6RiI.mjs → status-BoTZqXwd.mjs} +3 -3
- package/{status-CR_E6RiI.mjs.map → status-BoTZqXwd.mjs.map} +1 -1
- package/{status-Dcbdl6Sv.mjs → status-P0hOBrM6.mjs} +4 -4
- package/{status-Dcbdl6Sv.mjs.map → status-P0hOBrM6.mjs.map} +1 -1
- package/status-tYcs05sk.mjs +23 -0
- package/status-tYcs05sk.mjs.map +1 -0
- package/{stop-ML5Yeo_s.mjs → stop-BuDB-rqB.mjs} +4 -4
- package/{stop-ML5Yeo_s.mjs.map → stop-BuDB-rqB.mjs.map} +1 -1
- package/{update-BK_LdUUv.mjs → update-mWc5cR7q.mjs} +2 -2
- package/{update-BK_LdUUv.mjs.map → update-mWc5cR7q.mjs.map} +1 -1
- package/acp-CmtcmhuX.mjs.map +0 -1
- package/disconnect-DKi3PmC2.mjs +0 -2
- package/package-D_TWKUKk.mjs +0 -6
- package/package-D_TWKUKk.mjs.map +0 -1
- package/reconnect-DgUK2fwU.mjs +0 -2
- package/run-BN0xfxh_.mjs.map +0 -1
- package/runtime-Q4G4z83G.mjs.map +0 -1
- package/serve-CfjS09-r.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-CA6VAOdR.mjs","names":[],"sources":["../../src/connector/catalog.ts","../../src/connector/db.ts","../../src/connector/oauth.ts","../../src/connector/service.ts"],"sourcesContent":["/* @effect-diagnostics nodeBuiltinImport:off -- catalog cache lives on the local host filesystem. */\n/* @effect-diagnostics asyncFunction:off -- catalog fetch wraps Promise-based globalThis.fetch. */\n/* @effect-diagnostics preferSchemaOverJson:off -- catalog reads JSON from disk/HTTP and validates with Schema. */\n/* @effect-diagnostics schemaSync:off -- local fallback reads cache synchronously at service startup. */\n/* @effect-diagnostics processEnv:off -- catalog URL override reads CODEWORK_CONNECTORS_CATALOG_URL. */\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport {\n\tConnectorCatalog,\n\ttype ConnectorKind,\n\ttype ConnectorSpec,\n\tDEFAULT_CONNECTOR_CATALOG,\n\tDEFAULT_CONNECTORS_CATALOG_URL,\n} from \"@codeworksh/schema/connector\";\nimport { Effect, Schema } from \"effect\";\n\nconst decodeCatalog = Schema.decodeUnknownSync(ConnectorCatalog);\n\nexport interface CatalogOptions {\n\treadonly home: string;\n\treadonly url?: string | undefined;\n\treadonly fetch?: typeof globalThis.fetch | undefined;\n}\n\nconst catalogUrl = (override?: string): string =>\n\toverride ?? process.env[\"CODEWORK_CONNECTORS_CATALOG_URL\"] ?? DEFAULT_CONNECTORS_CATALOG_URL;\n\nconst cachePath = (home: string): string => join(home, \"cache\", \"connectors.json\");\nconst etagPath = (home: string): string => join(home, \"cache\", \"connectors.etag\");\n\nconst readCachedCatalog = (home: string): ConnectorCatalog | undefined => {\n\tconst file = cachePath(home);\n\tif (!existsSync(file)) return undefined;\n\ttry {\n\t\treturn decodeCatalog(JSON.parse(readFileSync(file, \"utf-8\")));\n\t} catch {\n\t\treturn undefined;\n\t}\n};\n\nconst readCachedEtag = (home: string): string | undefined => {\n\tconst file = etagPath(home);\n\tif (!existsSync(file)) return undefined;\n\ttry {\n\t\tconst tag = readFileSync(file, \"utf-8\").trim();\n\t\treturn tag.length > 0 ? tag : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n};\n\nconst writeCachedCatalog = (home: string, raw: string, etag: string | undefined): void => {\n\tconst file = cachePath(home);\n\tmkdirSync(dirname(file), { recursive: true, mode: 0o700 });\n\twriteFileSync(file, raw, { encoding: \"utf-8\", mode: 0o600 });\n\tconst tag = etag ?? `\"${createHash(\"md5\").update(raw).digest(\"hex\")}\"`;\n\twriteFileSync(etagPath(home), tag, { encoding: \"utf-8\", mode: 0o600 });\n};\n\n/**\n * Load the connector catalog from cache or bundled fallback without hitting the network.\n */\nexport const loadLocalCatalog = (home: string): ConnectorCatalog =>\n\treadCachedCatalog(home) ?? DEFAULT_CONNECTOR_CATALOG;\n\n/**\n * Refresh the connector catalog from `catalog.codework.sh/v1/connectors.json` (using `If-None-Match`\n * so unchanged catalogs answer `304`), falling back cleanly to the disk cache or bundled snapshot.\n */\nexport const fetchCatalog = (options: CatalogOptions) =>\n\tEffect.tryPromise({\n\t\ttry: async (): Promise<ConnectorCatalog> => {\n\t\t\tconst cached = readCachedCatalog(options.home);\n\t\t\tconst url = catalogUrl(options.url);\n\t\t\tconst fetcher = options.fetch ?? globalThis.fetch;\n\t\t\tconst headers: Record<string, string> = { Accept: \"application/json\" };\n\t\t\tconst etag = readCachedEtag(options.home);\n\t\t\tif (cached && etag) headers[\"If-None-Match\"] = etag;\n\n\t\t\ttry {\n\t\t\t\tconst response = await fetcher(url, {\n\t\t\t\t\theaders,\n\t\t\t\t\tsignal: AbortSignal.timeout(5_000),\n\t\t\t\t});\n\t\t\t\tif (response.status === 304 && cached) return cached;\n\t\t\t\tif (!response.ok) return cached ?? DEFAULT_CONNECTOR_CATALOG;\n\t\t\t\tconst text = await response.text();\n\t\t\t\tconst parsed = decodeCatalog(JSON.parse(text));\n\t\t\t\twriteCachedCatalog(options.home, text, response.headers.get(\"etag\") ?? undefined);\n\t\t\t\treturn parsed;\n\t\t\t} catch {\n\t\t\t\treturn cached ?? DEFAULT_CONNECTOR_CATALOG;\n\t\t\t}\n\t\t},\n\t\tcatch: () => undefined,\n\t}).pipe(Effect.orElseSucceed(() => loadLocalCatalog(options.home)));\n\n/** Look up a connector by exact reverse-DNS `id` or short `alias` (case-insensitive). */\nexport const findConnector = (catalog: ConnectorCatalog, idOrAlias: string): ConnectorSpec | undefined => {\n\tconst needle = idOrAlias.trim().toLowerCase();\n\tif (needle.length === 0) return undefined;\n\tconst exact = catalog.connectors[needle];\n\tif (exact !== undefined) return exact;\n\tfor (const spec of Object.values(catalog.connectors)) {\n\t\tif (spec.id.toLowerCase() === needle || spec.alias?.toLowerCase() === needle) return spec;\n\t}\n\treturn undefined;\n};\n\n/** Find the catalog connector powering a given `aikit` providerId (e.g. `\"anthropic\"`, `\"openai-codex\"`). */\nexport const findConnectorByProviderId = (catalog: ConnectorCatalog, providerId: string): ConnectorSpec | undefined => {\n\tfor (const spec of Object.values(catalog.connectors)) {\n\t\tif (spec.capabilities.provider?.providerId === providerId) return spec;\n\t}\n\treturn undefined;\n};\n\nexport interface CatalogFilter {\n\treadonly kind?: ConnectorKind | undefined;\n\treadonly category?: string | undefined;\n\treadonly query?: string | undefined;\n}\n\nexport const filterConnectors = (\n\tcatalog: ConnectorCatalog,\n\tfilter: CatalogFilter = {},\n): ReadonlyArray<ConnectorSpec> => {\n\tconst q = filter.query?.trim().toLowerCase();\n\tconst cat = filter.category?.trim().toLowerCase();\n\treturn Object.values(catalog.connectors)\n\t\t.filter((spec) => {\n\t\t\tif (filter.kind !== undefined && !spec.kinds.includes(filter.kind)) return false;\n\t\t\tif (cat !== undefined && cat.length > 0 && !spec.categories.some((c) => c.toLowerCase() === cat)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (q !== undefined && q.length > 0) {\n\t\t\t\tconst haystack = [spec.id, spec.alias ?? \"\", spec.name, spec.description, ...spec.categories]\n\t\t\t\t\t.join(\" \")\n\t\t\t\t\t.toLowerCase();\n\t\t\t\tif (!haystack.includes(q)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t})\n\t\t.sort((a, b) => {\n\t\t\tif (Boolean(a.featured) !== Boolean(b.featured)) return a.featured ? -1 : 1;\n\t\t\treturn a.name.localeCompare(b.name);\n\t\t});\n};\n","/* @effect-diagnostics nodeBuiltinImport:off -- machine-local connections store uses node:sqlite and 0600 file permissions. */\n/* @effect-diagnostics preferSchemaOverJson:off -- SQLite columns store JSON payloads validated at boundary. */\n/* @effect-diagnostics schemaSync:off -- synchronous node:sqlite rows decode immediately inside transactions. */\nimport { chmodSync, existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport {\n\tConnectionConfig,\n\tConnectionID,\n\ttype ConnectorKind,\n\ttype ConnectorSource,\n\tConnectorSpec,\n\ttype CredentialStatus,\n\tDEFAULT_CONNECTOR_CATALOG,\n\ttype Ownership,\n\ttype StoredAuthType,\n\tformatUid,\n} from \"@codeworksh/schema/connector\";\nimport { Schema } from \"effect\";\n\nconst decodeConfig = Schema.decodeUnknownSync(ConnectionConfig);\nconst decodeSpec = Schema.decodeUnknownSync(ConnectorSpec);\n\nexport type SubjectType = \"app\" | \"user\";\n\nexport interface StoredApiKeySecret {\n\treadonly type: \"apikey\";\n\treadonly apiKey: string;\n}\n\nexport interface StoredOAuthClient {\n\treadonly clientId: string;\n\treadonly clientSecret?: string | undefined;\n\treadonly tokenEndpoint?: string | undefined;\n\treadonly authorizeEndpoint?: string | undefined;\n\treadonly resource?: string | undefined;\n}\n\nexport interface StoredOAuthSecret {\n\treadonly type: \"oauth\";\n\treadonly accessToken: string;\n\treadonly refreshToken?: string | undefined;\n\treadonly expiresAt?: number | undefined;\n\treadonly tokenType?: string | undefined;\n\treadonly scopes?: ReadonlyArray<string> | undefined;\n\treadonly accountId?: string | undefined;\n\treadonly accountLabel?: string | undefined;\n\treadonly apiEndpoint?: string | undefined;\n\treadonly enterpriseUrl?: string | undefined;\n\treadonly availableModelIds?: ReadonlyArray<string> | undefined;\n\treadonly client?: StoredOAuthClient | undefined;\n}\n\nexport type StoredSecret = StoredApiKeySecret | StoredOAuthSecret;\n\nexport interface ConnectionRow {\n\treadonly id: ConnectionID;\n\treadonly workspaceId: string;\n\treadonly uid: string;\n\treadonly label: string | undefined;\n\treadonly source: ConnectorSource;\n\treadonly connectorId: string;\n\treadonly kinds: ReadonlyArray<ConnectorKind>;\n\treadonly authType: StoredAuthType;\n\treadonly ownership: Ownership;\n\treadonly enabled: boolean;\n\treadonly isDefault: boolean;\n\treadonly allowedHosts: ReadonlyArray<string>;\n\treadonly config: ConnectionConfig;\n\treadonly spec: ConnectorSpec | undefined;\n\treadonly createdAt: number;\n\treadonly updatedAt: number;\n}\n\nexport interface CredentialRow {\n\treadonly connectionId: ConnectionID;\n\treadonly subjectType: SubjectType;\n\treadonly subjectId: string;\n\treadonly secret: StoredSecret;\n\treadonly status: CredentialStatus;\n\treadonly lastError: string | undefined;\n\treadonly expiresAt: number | undefined;\n\treadonly updatedAt: number;\n}\n\ninterface RawConnectionRow {\n\tid: string;\n\tworkspace_id: string;\n\tuid: string;\n\tlabel: string | null;\n\tsource: string;\n\tconnector_id: string;\n\tkinds: string;\n\tauth_type: string;\n\townership: string;\n\tenabled: number;\n\tis_default: number;\n\tallowed_hosts: string;\n\tconfig: string;\n\tspec: string | null;\n\tcreated_at: number;\n\tupdated_at: number;\n}\n\ninterface RawCredentialRow {\n\tconnection_id: string;\n\tsubject_type: string;\n\tsubject_id: string;\n\tsecret: string;\n\tstatus: string;\n\tlast_error: string | null;\n\texpires_at: number | null;\n\tupdated_at: number;\n}\n\nconst parseJsonArray = (raw: string): ReadonlyArray<string> => {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(raw);\n\t\treturn Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === \"string\") : [];\n\t} catch {\n\t\treturn [];\n\t}\n};\n\nconst parseKinds = (raw: string): ReadonlyArray<ConnectorKind> =>\n\tparseJsonArray(raw).filter(\n\t\t(item): item is ConnectorKind => item === \"provider\" || item === \"mcp\" || item === \"integration\",\n\t);\n\nconst parseConfig = (raw: string): ConnectionConfig => {\n\ttry {\n\t\treturn decodeConfig(JSON.parse(raw));\n\t} catch {\n\t\treturn {};\n\t}\n};\n\nconst parseSpec = (raw: string | null): ConnectorSpec | undefined => {\n\tif (raw === null) return undefined;\n\ttry {\n\t\treturn decodeSpec(JSON.parse(raw));\n\t} catch {\n\t\treturn undefined;\n\t}\n};\n\nconst toConnectionRow = (raw: RawConnectionRow): ConnectionRow => ({\n\tid: ConnectionID.from(raw.id),\n\tworkspaceId: raw.workspace_id,\n\tuid: raw.uid,\n\tlabel: raw.label ?? undefined,\n\tsource: raw.source === \"custom\" ? \"custom\" : \"catalog\",\n\tconnectorId: raw.connector_id,\n\tkinds: parseKinds(raw.kinds),\n\tauthType: raw.auth_type === \"oauth\" ? \"oauth\" : \"apikey\",\n\townership: raw.ownership === \"personal\" ? \"personal\" : \"shared\",\n\tenabled: raw.enabled !== 0,\n\tisDefault: raw.is_default !== 0,\n\tallowedHosts: parseJsonArray(raw.allowed_hosts),\n\tconfig: parseConfig(raw.config),\n\tspec: parseSpec(raw.spec),\n\tcreatedAt: raw.created_at,\n\tupdatedAt: raw.updated_at,\n});\n\nconst toCredentialRow = (raw: RawCredentialRow): CredentialRow => ({\n\tconnectionId: ConnectionID.from(raw.connection_id),\n\tsubjectType: raw.subject_type === \"user\" ? \"user\" : \"app\",\n\tsubjectId: raw.subject_id,\n\tsecret: JSON.parse(raw.secret) as StoredSecret,\n\tstatus:\n\t\traw.status === \"active\" ||\n\t\traw.status === \"not_connected\" ||\n\t\traw.status === \"expired\" ||\n\t\traw.status === \"revoked\" ||\n\t\traw.status === \"error\"\n\t\t\t? raw.status\n\t\t\t: \"active\",\n\tlastError: raw.last_error ?? undefined,\n\texpiresAt: raw.expires_at ?? undefined,\n\tupdatedAt: raw.updated_at,\n});\n\nexport const connectionsDbPath = (home: string): string => join(home, \"connections.db\");\n\nconst MIGRATION_V1 = `\nCREATE TABLE IF NOT EXISTS meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS connection (\n id TEXT PRIMARY KEY,\n workspace_id TEXT NOT NULL,\n uid TEXT NOT NULL,\n label TEXT,\n source TEXT NOT NULL DEFAULT 'catalog',\n connector_id TEXT NOT NULL,\n kinds TEXT NOT NULL,\n auth_type TEXT NOT NULL,\n ownership TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 1,\n is_default INTEGER NOT NULL DEFAULT 0,\n allowed_hosts TEXT NOT NULL,\n config TEXT NOT NULL DEFAULT '{}',\n spec TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n UNIQUE (workspace_id, uid)\n);\n\nCREATE INDEX IF NOT EXISTS idx_connection_workspace ON connection(workspace_id);\nCREATE INDEX IF NOT EXISTS idx_connection_connector ON connection(workspace_id, connector_id);\n\nCREATE TABLE IF NOT EXISTS credential (\n connection_id TEXT NOT NULL REFERENCES connection(id) ON DELETE CASCADE,\n subject_type TEXT NOT NULL,\n subject_id TEXT NOT NULL,\n secret TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'active',\n last_error TEXT,\n expires_at INTEGER,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (connection_id, subject_type, subject_id)\n);\n`;\n\nexport interface InsertConnectionInput {\n\treadonly id: ConnectionID;\n\treadonly workspaceId: string;\n\treadonly uid: string;\n\treadonly label?: string | undefined;\n\treadonly source: ConnectorSource;\n\treadonly connectorId: string;\n\treadonly kinds: ReadonlyArray<ConnectorKind>;\n\treadonly authType: StoredAuthType;\n\treadonly ownership: Ownership;\n\treadonly enabled: boolean;\n\treadonly isDefault: boolean;\n\treadonly allowedHosts: ReadonlyArray<string>;\n\treadonly config: ConnectionConfig;\n\treadonly spec?: ConnectorSpec | undefined;\n\treadonly now: number;\n}\n\nexport interface UpdateConnectionInput {\n\treadonly uid?: string | undefined;\n\treadonly label?: string | null | undefined;\n\treadonly ownership?: Ownership | undefined;\n\treadonly enabled?: boolean | undefined;\n\treadonly isDefault?: boolean | undefined;\n\treadonly config?: ConnectionConfig | undefined;\n\treadonly now: number;\n}\n\n/**\n * Machine-local SQLite store for workspace connections and secrets (`<home>/connections.db`).\n */\nexport class ConnectionsDb {\n\treadonly path: string;\n\tprivate readonly db: DatabaseSync;\n\n\tconstructor(filePath: string) {\n\t\tthis.path = filePath;\n\t\tif (filePath !== \":memory:\") {\n\t\t\tmkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });\n\t\t}\n\t\tthis.db = new DatabaseSync(filePath);\n\t\tif (filePath !== \":memory:\") {\n\t\t\ttry {\n\t\t\t\tchmodSync(filePath, 0o600);\n\t\t\t} catch {\n\t\t\t\t// Best-effort on filesystems that ignore POSIX mode bits.\n\t\t\t}\n\t\t}\n\t\tthis.db.exec(\"PRAGMA journal_mode = WAL;\");\n\t\tthis.db.exec(\"PRAGMA busy_timeout = 5000;\");\n\t\tthis.db.exec(\"PRAGMA foreign_keys = ON;\");\n\t\tthis.db.exec(MIGRATION_V1);\n\t\tthis.setMetaIfMissing(\"schema_version\", \"1\");\n\t}\n\n\tclose(): void {\n\t\tthis.db.close();\n\t}\n\n\tgetMeta(key: string): string | undefined {\n\t\tconst row = this.db.prepare(\"SELECT value FROM meta WHERE key = ?\").get(key) as { value: string } | undefined;\n\t\treturn row?.value;\n\t}\n\n\tsetMeta(key: string, value: string): void {\n\t\tthis.db\n\t\t\t.prepare(\"INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value\")\n\t\t\t.run(key, value);\n\t}\n\n\tprivate setMetaIfMissing(key: string, value: string): void {\n\t\tthis.db.prepare(\"INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)\").run(key, value);\n\t}\n\n\twithImmediateTx<A>(fn: () => A): A {\n\t\tthis.db.exec(\"BEGIN IMMEDIATE\");\n\t\ttry {\n\t\t\tconst result = fn();\n\t\t\tthis.db.exec(\"COMMIT\");\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tthis.db.exec(\"ROLLBACK\");\n\t\t\t} catch {\n\t\t\t\t// Ignore rollback failure after a failed transaction.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tlistConnections(\n\t\tworkspaceId: string,\n\t\tfilter: {\n\t\t\treadonly kind?: ConnectorKind | undefined;\n\t\t\treadonly connectorId?: string | undefined;\n\t\t\treadonly enabled?: boolean | undefined;\n\t\t} = {},\n\t): ReadonlyArray<ConnectionRow> {\n\t\tconst clauses = [\"workspace_id = ?\"];\n\t\tconst params: Array<string | number> = [workspaceId];\n\t\tif (filter.connectorId !== undefined) {\n\t\t\tclauses.push(\"connector_id = ?\");\n\t\t\tparams.push(filter.connectorId);\n\t\t}\n\t\tif (filter.enabled !== undefined) {\n\t\t\tclauses.push(\"enabled = ?\");\n\t\t\tparams.push(filter.enabled ? 1 : 0);\n\t\t}\n\t\tconst sql = `SELECT * FROM connection WHERE ${clauses.join(\" AND \")} ORDER BY is_default DESC, created_at ASC`;\n\t\tconst rows = (this.db.prepare(sql).all(...params) as unknown as Array<RawConnectionRow>).map(toConnectionRow);\n\t\tif (filter.kind === undefined) return rows;\n\t\treturn rows.filter((row) => row.kinds.includes(filter.kind!));\n\t}\n\n\tfindConnection(workspaceId: string, ref: string): ConnectionRow | undefined {\n\t\tconst row = this.db\n\t\t\t.prepare(\"SELECT * FROM connection WHERE workspace_id = ? AND (id = ? OR uid = ?) LIMIT 1\")\n\t\t\t.get(workspaceId, ref, ref) as unknown as RawConnectionRow | undefined;\n\t\treturn row === undefined ? undefined : toConnectionRow(row);\n\t}\n\n\tfindConnectionById(id: string): ConnectionRow | undefined {\n\t\tconst row = this.db.prepare(\"SELECT * FROM connection WHERE id = ? LIMIT 1\").get(id) as unknown as\n\t\t\t| RawConnectionRow\n\t\t\t| undefined;\n\t\treturn row === undefined ? undefined : toConnectionRow(row);\n\t}\n\n\tinsertConnection(input: InsertConnectionInput): ConnectionRow {\n\t\tthis.withImmediateTx(() => {\n\t\t\tif (input.isDefault) {\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"UPDATE connection SET is_default = 0 WHERE workspace_id = ? AND connector_id = ?\")\n\t\t\t\t\t.run(input.workspaceId, input.connectorId);\n\t\t\t}\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`INSERT INTO connection (\n\t\t\t\t\t\tid, workspace_id, uid, label, source, connector_id, kinds,\n\t\t\t\t\t\tauth_type, ownership, enabled, is_default, allowed_hosts,\n\t\t\t\t\t\tconfig, spec, created_at, updated_at\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\t)\n\t\t\t\t.run(\n\t\t\t\t\tinput.id,\n\t\t\t\t\tinput.workspaceId,\n\t\t\t\t\tinput.uid,\n\t\t\t\t\tinput.label ?? null,\n\t\t\t\t\tinput.source,\n\t\t\t\t\tinput.connectorId,\n\t\t\t\t\tJSON.stringify(input.kinds),\n\t\t\t\t\tinput.authType,\n\t\t\t\t\tinput.ownership,\n\t\t\t\t\tinput.enabled ? 1 : 0,\n\t\t\t\t\tinput.isDefault ? 1 : 0,\n\t\t\t\t\tJSON.stringify(input.allowedHosts),\n\t\t\t\t\tJSON.stringify(input.config),\n\t\t\t\t\tinput.spec === undefined ? null : JSON.stringify(input.spec),\n\t\t\t\t\tinput.now,\n\t\t\t\t\tinput.now,\n\t\t\t\t);\n\t\t});\n\t\treturn this.findConnectionById(input.id)!;\n\t}\n\n\tupdateConnection(id: string, input: UpdateConnectionInput): ConnectionRow | undefined {\n\t\treturn this.withImmediateTx(() => {\n\t\t\tconst existing = this.findConnectionById(id);\n\t\t\tif (existing === undefined) return undefined;\n\t\t\tif (input.isDefault === true) {\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"UPDATE connection SET is_default = 0 WHERE workspace_id = ? AND connector_id = ? AND id != ?\")\n\t\t\t\t\t.run(existing.workspaceId, existing.connectorId, id);\n\t\t\t}\n\t\t\tconst nextUid = input.uid ?? existing.uid;\n\t\t\tconst nextLabel = input.label === undefined ? (existing.label ?? null) : input.label;\n\t\t\tconst nextOwnership = input.ownership ?? existing.ownership;\n\t\t\tconst nextEnabled = input.enabled === undefined ? existing.enabled : input.enabled;\n\t\t\tconst nextDefault = input.isDefault === undefined ? existing.isDefault : input.isDefault;\n\t\t\tconst nextConfig = input.config === undefined ? existing.config : input.config;\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`UPDATE connection\n\t\t\t\t\t SET uid = ?, label = ?, ownership = ?, enabled = ?, is_default = ?, config = ?, updated_at = ?\n\t\t\t\t\t WHERE id = ?`,\n\t\t\t\t)\n\t\t\t\t.run(\n\t\t\t\t\tnextUid,\n\t\t\t\t\tnextLabel,\n\t\t\t\t\tnextOwnership,\n\t\t\t\t\tnextEnabled ? 1 : 0,\n\t\t\t\t\tnextDefault ? 1 : 0,\n\t\t\t\t\tJSON.stringify(nextConfig),\n\t\t\t\t\tinput.now,\n\t\t\t\t\tid,\n\t\t\t\t);\n\t\t\treturn this.findConnectionById(id);\n\t\t});\n\t}\n\n\tdeleteConnection(id: string): boolean {\n\t\tconst info = this.db.prepare(\"DELETE FROM connection WHERE id = ?\").run(id);\n\t\treturn info.changes > 0;\n\t}\n\n\tgetCredential(connectionId: string, subjectType: SubjectType, subjectId: string): CredentialRow | undefined {\n\t\tconst row = this.db\n\t\t\t.prepare(\"SELECT * FROM credential WHERE connection_id = ? AND subject_type = ? AND subject_id = ? LIMIT 1\")\n\t\t\t.get(connectionId, subjectType, subjectId) as unknown as RawCredentialRow | undefined;\n\t\treturn row === undefined ? undefined : toCredentialRow(row);\n\t}\n\n\tupsertCredential(input: {\n\t\treadonly connectionId: string;\n\t\treadonly subjectType: SubjectType;\n\t\treadonly subjectId: string;\n\t\treadonly secret: StoredSecret;\n\t\treadonly status?: CredentialStatus | undefined;\n\t\treadonly lastError?: string | undefined;\n\t\treadonly expiresAt?: number | undefined;\n\t\treadonly now: number;\n\t}): CredentialRow {\n\t\tthis.db\n\t\t\t.prepare(\n\t\t\t\t`INSERT INTO credential (connection_id, subject_type, subject_id, secret, status, last_error, expires_at, updated_at)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n\t\t\t\t ON CONFLICT(connection_id, subject_type, subject_id) DO UPDATE SET\n\t\t\t\t secret = excluded.secret,\n\t\t\t\t status = excluded.status,\n\t\t\t\t last_error = excluded.last_error,\n\t\t\t\t expires_at = excluded.expires_at,\n\t\t\t\t updated_at = excluded.updated_at`,\n\t\t\t)\n\t\t\t.run(\n\t\t\t\tinput.connectionId,\n\t\t\t\tinput.subjectType,\n\t\t\t\tinput.subjectId,\n\t\t\t\tJSON.stringify(input.secret),\n\t\t\t\tinput.status ?? \"active\",\n\t\t\t\tinput.lastError ?? null,\n\t\t\t\tinput.expiresAt ?? null,\n\t\t\t\tinput.now,\n\t\t\t);\n\t\treturn this.getCredential(input.connectionId, input.subjectType, input.subjectId)!;\n\t}\n\n\tmarkCredentialStatus(\n\t\tconnectionId: string,\n\t\tsubjectType: SubjectType,\n\t\tsubjectId: string,\n\t\tstatus: CredentialStatus,\n\t\tlastError: string | undefined,\n\t\tnow: number,\n\t): void {\n\t\tthis.db\n\t\t\t.prepare(\n\t\t\t\t`UPDATE credential SET status = ?, last_error = ?, updated_at = ?\n\t\t\t\t WHERE connection_id = ? AND subject_type = ? AND subject_id = ?`,\n\t\t\t)\n\t\t\t.run(status, lastError ?? null, now, connectionId, subjectType, subjectId);\n\t}\n\n\tdeleteCredential(connectionId: string, subjectType: SubjectType, subjectId: string): boolean {\n\t\tconst info = this.db\n\t\t\t.prepare(\"DELETE FROM credential WHERE connection_id = ? AND subject_type = ? AND subject_id = ?\")\n\t\t\t.run(connectionId, subjectType, subjectId);\n\t\treturn info.changes > 0;\n\t}\n\n\t/**\n\t * Non-destructive one-time import of existing `<home>/aikit/auth.json` Codex / Copilot OAuth logins\n\t * into the `local` workspace so existing users stay signed in when upgrading to connections.db.\n\t */\n\timportLegacyAikitAuth(authFile: string | undefined, now: number): void {\n\t\tif (authFile === undefined || !existsSync(authFile)) return;\n\t\tif (this.getMeta(\"legacy_aikit_imported\") === \"1\") return;\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(readFileSync(authFile, \"utf-8\"));\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return;\n\t\tconst entries = parsed as Record<string, unknown>;\n\n\t\tconst importOne = (\n\t\t\tlegacyKey: \"openai-codex\" | \"github-copilot\",\n\t\t\tconnectorId: \"com.openai.codex\" | \"com.github.copilot\",\n\t\t) => {\n\t\t\tconst raw = entries[legacyKey];\n\t\t\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) return;\n\t\t\tconst record = raw as Record<string, unknown>;\n\t\t\tif (typeof record[\"access\"] !== \"string\" || record[\"access\"].length === 0) return;\n\t\t\tconst spec = DEFAULT_CONNECTOR_CATALOG.connectors[connectorId];\n\t\t\tif (spec === undefined) return;\n\t\t\tconst uid = formatUid(connectorId, \"default\");\n\t\t\tif (this.findConnection(\"local\", uid) !== undefined) return;\n\t\t\tconst id = ConnectionID.create();\n\t\t\tconst existingSame = this.listConnections(\"local\", { connectorId });\n\t\t\tconst enterpriseUrl = typeof record[\"enterpriseUrl\"] === \"string\" ? record[\"enterpriseUrl\"] : undefined;\n\t\t\tthis.insertConnection({\n\t\t\t\tid,\n\t\t\t\tworkspaceId: \"local\",\n\t\t\t\tuid,\n\t\t\t\tlabel: spec.name,\n\t\t\t\tsource: \"catalog\",\n\t\t\t\tconnectorId,\n\t\t\t\tkinds: spec.kinds,\n\t\t\t\tauthType: \"oauth\",\n\t\t\t\townership: \"personal\",\n\t\t\t\tenabled: true,\n\t\t\t\tisDefault: existingSame.length === 0,\n\t\t\t\tallowedHosts: spec.allowedHosts,\n\t\t\t\tconfig: enterpriseUrl ? { fields: { enterpriseUrl } } : {},\n\t\t\t\tnow,\n\t\t\t});\n\t\t\tconst expires = typeof record[\"expires\"] === \"number\" && record[\"expires\"] > 0 ? record[\"expires\"] : undefined;\n\t\t\tconst availableModelIds = Array.isArray(record[\"availableModelIds\"])\n\t\t\t\t? record[\"availableModelIds\"].filter((m): m is string => typeof m === \"string\")\n\t\t\t\t: undefined;\n\t\t\tconst secret: StoredOAuthSecret = {\n\t\t\t\ttype: \"oauth\",\n\t\t\t\taccessToken: record[\"access\"],\n\t\t\t\t...(typeof record[\"refresh\"] === \"string\" && record[\"refresh\"].length > 0\n\t\t\t\t\t? { refreshToken: record[\"refresh\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(expires !== undefined ? { expiresAt: expires } : {}),\n\t\t\t\t...(typeof record[\"accountId\"] === \"string\" ? { accountId: record[\"accountId\"] } : {}),\n\t\t\t\t...(typeof record[\"apiEndpoint\"] === \"string\" ? { apiEndpoint: record[\"apiEndpoint\"] } : {}),\n\t\t\t\t...(enterpriseUrl !== undefined ? { enterpriseUrl } : {}),\n\t\t\t\t...(availableModelIds !== undefined ? { availableModelIds } : {}),\n\t\t\t};\n\t\t\tthis.upsertCredential({\n\t\t\t\tconnectionId: id,\n\t\t\t\tsubjectType: \"user\",\n\t\t\t\tsubjectId: \"local\",\n\t\t\t\tsecret,\n\t\t\t\tstatus: \"active\",\n\t\t\t\t...(expires !== undefined ? { expiresAt: expires } : {}),\n\t\t\t\tnow,\n\t\t\t});\n\t\t};\n\n\t\timportOne(\"openai-codex\", \"com.openai.codex\");\n\t\timportOne(\"github-copilot\", \"com.github.copilot\");\n\t\tthis.setMeta(\"legacy_aikit_imported\", \"1\");\n\t}\n}\n","/* @effect-diagnostics nodeBuiltinImport:off -- PKCE and state generation use node:crypto. */\n/* @effect-diagnostics asyncFunction:off -- OAuth HTTP exchanges wrap Promise-based fetch and aikit OAuth helpers. */\n/* @effect-diagnostics globalDate:off -- OAuth token expiry and state TTL compare wall-clock epoch millis. */\n/* @effect-diagnostics globalDateInEffect:off -- OAuth token expiry and state TTL compare wall-clock epoch millis. */\n/* @effect-diagnostics preferSchemaOverJson:off -- OAuth HTTP requests/responses speak RFC 6749/7591 JSON directly. */\nimport { createHash, randomBytes } from \"node:crypto\";\nimport {\n\tcreateGitHubCopilotDeviceFlow,\n\tfetchGitHubCopilotModels,\n\tfetchGitHubCopilotUser,\n\tgitHubCopilotBaseUrl,\n\tgitHubCopilotEntitlementError,\n\tgitHubCopilotHeaders,\n\tnormalizeGitHubDomain,\n\ttype GitHubCopilotOAuthCredentials,\n} from \"@codeworksh/aikit/oauth/github/copilot\";\nimport {\n\tcreateOpenAICodexAuthorizationFlow,\n\tcreateOpenAICodexDeviceAuth,\n\texchangeOpenAICodexAuthorizationCode,\n\tgetOpenAICodexAccountId,\n\topenAICodexHeaders,\n\tparseOpenAICodexAuthorizationInput,\n\trefreshOpenAICodexToken,\n\ttype OpenAICodexOAuthCredentials,\n} from \"@codeworksh/aikit/oauth/openai/codex\";\nimport { ConnectorAuthError, type ConnectorSpec, type HeaderInjection } from \"@codeworksh/schema/connector\";\nimport { Effect } from \"effect\";\nimport type { ConnectionRow, StoredOAuthClient, StoredOAuthSecret } from \"./db.ts\";\n\nconst PENDING_TTL_MS = 10 * 60 * 1000;\nconst HTTP_TIMEOUT_MS = 15_000;\nconst CODEX_DEVICE_TOKEN_URL = \"https://auth.openai.com/api/accounts/deviceauth/token\";\nconst CODEX_DEVICE_REDIRECT_URI = \"https://auth.openai.com/deviceauth/callback\";\nconst GITHUB_COPILOT_CLIENT_ID = \"Iv1.b507a08c87ecfe98\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst randomState = () => randomBytes(24).toString(\"base64url\");\n\nconst generatePkce = () => {\n\tconst verifier = randomBytes(32).toString(\"base64url\");\n\tconst challenge = createHash(\"sha256\").update(verifier).digest(\"base64url\");\n\treturn { verifier, challenge };\n};\n\ninterface DiscoveredOAuth {\n\treadonly authorizeEndpoint: string;\n\treadonly tokenEndpoint: string;\n\treadonly registrationEndpoint?: string | undefined;\n\treadonly resource?: string | undefined;\n\treadonly scopesSupported?: ReadonlyArray<string> | undefined;\n}\n\nconst fetchJson = async (\n\tfetcher: typeof globalThis.fetch,\n\turl: string,\n): Promise<Record<string, unknown> | undefined> => {\n\ttry {\n\t\tconst res = await fetcher(url, {\n\t\t\theaders: { Accept: \"application/json\" },\n\t\t\tsignal: AbortSignal.timeout(HTTP_TIMEOUT_MS),\n\t\t});\n\t\tif (!res.ok) return undefined;\n\t\tconst parsed: unknown = await res.json();\n\t\treturn isRecord(parsed) ? parsed : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n};\n\n/**\n * RFC 9728 (Protected Resource Metadata) -> RFC 8414 (Authorization Server Metadata) / OIDC discovery.\n */\nconst discoverOAuthMetadata = async (\n\tresourceUrl: string,\n\tfetcher: typeof globalThis.fetch = globalThis.fetch,\n): Promise<DiscoveredOAuth> => {\n\tconst parsed = new URL(resourceUrl);\n\tconst origin = parsed.origin;\n\tconst pathname = parsed.pathname.replace(/\\/+$/, \"\");\n\n\t// 1. Try RFC 9728 protected resource metadata (path-scoped then root)\n\tconst prmCandidates = [\n\t\t...(pathname.length > 0 ? [`${origin}/.well-known/oauth-protected-resource${pathname}`] : []),\n\t\t`${origin}/.well-known/oauth-protected-resource`,\n\t];\n\n\tlet authServerOrigin = origin;\n\tlet resource: string | undefined = resourceUrl;\n\tlet scopesSupported: ReadonlyArray<string> | undefined;\n\n\tfor (const candidate of prmCandidates) {\n\t\tconst prm = await fetchJson(fetcher, candidate);\n\t\tif (!prm) continue;\n\t\tif (typeof prm[\"resource\"] === \"string\") resource = prm[\"resource\"];\n\t\tif (Array.isArray(prm[\"scopes_supported\"])) {\n\t\t\tscopesSupported = prm[\"scopes_supported\"].filter((s): s is string => typeof s === \"string\");\n\t\t}\n\t\tif (Array.isArray(prm[\"authorization_servers\"]) && typeof prm[\"authorization_servers\"][0] === \"string\") {\n\t\t\tauthServerOrigin = prm[\"authorization_servers\"][0].replace(/\\/+$/, \"\");\n\t\t}\n\t\tbreak;\n\t}\n\n\t// 2. Try RFC 8414 / OIDC authorization server metadata\n\tconst asUrl = new URL(authServerOrigin);\n\tconst asPath = asUrl.pathname.replace(/\\/+$/, \"\");\n\tconst asmCandidates =\n\t\tasPath.length > 0\n\t\t\t? [\n\t\t\t\t\t`${asUrl.origin}/.well-known/oauth-authorization-server${asPath}`,\n\t\t\t\t\t`${asUrl.origin}/.well-known/openid-configuration${asPath}`,\n\t\t\t\t\t`${authServerOrigin}/.well-known/openid-configuration`,\n\t\t\t\t]\n\t\t\t: [\n\t\t\t\t\t`${asUrl.origin}/.well-known/oauth-authorization-server`,\n\t\t\t\t\t`${asUrl.origin}/.well-known/openid-configuration`,\n\t\t\t\t];\n\n\tfor (const candidate of asmCandidates) {\n\t\tconst meta = await fetchJson(fetcher, candidate);\n\t\tif (!meta) continue;\n\t\tconst authorizeEndpoint = meta[\"authorization_endpoint\"];\n\t\tconst tokenEndpoint = meta[\"token_endpoint\"];\n\t\tif (typeof authorizeEndpoint === \"string\" && typeof tokenEndpoint === \"string\") {\n\t\t\treturn {\n\t\t\t\tauthorizeEndpoint,\n\t\t\t\ttokenEndpoint,\n\t\t\t\tregistrationEndpoint:\n\t\t\t\t\ttypeof meta[\"registration_endpoint\"] === \"string\" ? meta[\"registration_endpoint\"] : undefined,\n\t\t\t\tresource,\n\t\t\t\tscopesSupported:\n\t\t\t\t\tscopesSupported ??\n\t\t\t\t\t(Array.isArray(meta[\"scopes_supported\"])\n\t\t\t\t\t\t? meta[\"scopes_supported\"].filter((s): s is string => typeof s === \"string\")\n\t\t\t\t\t\t: undefined),\n\t\t\t};\n\t\t}\n\t}\n\n\tthrow new Error(`Could not discover OAuth metadata for ${resourceUrl}`);\n};\n\nconst registerDynamicClient = async (\n\tregistrationEndpoint: string,\n\tredirectUrl: string,\n\tfetcher: typeof globalThis.fetch,\n): Promise<{ readonly clientId: string; readonly clientSecret?: string | undefined }> => {\n\tconst response = await fetcher(registrationEndpoint, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/json\", Accept: \"application/json\" },\n\t\tbody: JSON.stringify({\n\t\t\tclient_name: \"CodeWork\",\n\t\t\tredirect_uris: [redirectUrl],\n\t\t\tgrant_types: [\"authorization_code\", \"refresh_token\"],\n\t\t\tresponse_types: [\"code\"],\n\t\t\ttoken_endpoint_auth_method: \"none\",\n\t\t}),\n\t\tsignal: AbortSignal.timeout(HTTP_TIMEOUT_MS),\n\t});\n\tif (!response.ok) {\n\t\tconst body = await response.text().catch(() => \"\");\n\t\tthrow new Error(`Dynamic client registration failed (${response.status}): ${body || response.statusText}`);\n\t}\n\tconst data: unknown = await response.json();\n\tif (!isRecord(data) || typeof data[\"client_id\"] !== \"string\" || data[\"client_id\"].length === 0) {\n\t\tthrow new Error(\"Dynamic client registration returned no client_id\");\n\t}\n\treturn {\n\t\tclientId: data[\"client_id\"],\n\t\tclientSecret: typeof data[\"client_secret\"] === \"string\" ? data[\"client_secret\"] : undefined,\n\t};\n};\n\ninterface PendingAuthCode {\n\treadonly kind: \"auth_code\";\n\treadonly workspaceId: string;\n\treadonly actorId: string;\n\treadonly connectionId: string;\n\treadonly connector: ConnectorSpec;\n\treadonly handler?: string | undefined;\n\treadonly redirectUrl: string;\n\treadonly codeVerifier: string;\n\treadonly client: StoredOAuthClient;\n\treadonly scopes?: ReadonlyArray<string> | undefined;\n\treadonly expiresAt: number;\n}\n\ninterface PendingDeviceCode {\n\treadonly kind: \"device_code\";\n\treadonly workspaceId: string;\n\treadonly actorId: string;\n\treadonly connectionId: string;\n\treadonly connector: ConnectorSpec;\n\treadonly handler: \"openai-codex\" | \"github-copilot\";\n\treadonly deviceCode: string;\n\treadonly userCode: string;\n\treadonly verificationUri: string;\n\treadonly intervalSeconds: number;\n\treadonly enterpriseUrl?: string | undefined;\n\treadonly expiresAt: number;\n}\n\nexport type PendingOAuth = PendingAuthCode | PendingDeviceCode;\n\nexport class PendingOAuthStore {\n\tprivate readonly entries = new Map<string, PendingOAuth>();\n\n\tprivate prune(now: number): void {\n\t\tfor (const [key, value] of this.entries) {\n\t\t\tif (value.expiresAt <= now) this.entries.delete(key);\n\t\t}\n\t}\n\n\tput(state: string, entry: PendingOAuth): void {\n\t\tthis.prune(Date.now());\n\t\tthis.entries.set(state, entry);\n\t}\n\n\tpeek(state: string, workspaceId: string, actorId: string): PendingOAuth | undefined {\n\t\tthis.prune(Date.now());\n\t\tconst entry = this.entries.get(state);\n\t\tif (entry === undefined) return undefined;\n\t\tif (entry.workspaceId !== workspaceId || entry.actorId !== actorId) return undefined;\n\t\treturn entry;\n\t}\n\n\tconsume(state: string, workspaceId: string, actorId: string): PendingOAuth | undefined {\n\t\tconst entry = this.peek(state, workspaceId, actorId);\n\t\tif (entry !== undefined) this.entries.delete(state);\n\t\treturn entry;\n\t}\n\n\tdelete(state: string): void {\n\t\tthis.entries.delete(state);\n\t}\n}\n\nconst errorMessage = (cause: unknown): string =>\n\tcause instanceof Error && cause.message.trim().length > 0 ? cause.message : String(cause);\n\nconst parseTokenResponse = (\n\tdata: unknown,\n\tclient: StoredOAuthClient,\n\tfallbackRefresh?: string,\n\tfallbackScopes?: ReadonlyArray<string>,\n): StoredOAuthSecret => {\n\tif (!isRecord(data) || typeof data[\"access_token\"] !== \"string\" || data[\"access_token\"].length === 0) {\n\t\tthrow new Error(\"OAuth token endpoint returned no access_token\");\n\t}\n\tconst expiresIn =\n\t\ttypeof data[\"expires_in\"] === \"number\" && Number.isFinite(data[\"expires_in\"]) ? data[\"expires_in\"] : undefined;\n\tconst refreshToken =\n\t\ttypeof data[\"refresh_token\"] === \"string\" && data[\"refresh_token\"].length > 0\n\t\t\t? data[\"refresh_token\"]\n\t\t\t: fallbackRefresh;\n\tconst scopeStr = typeof data[\"scope\"] === \"string\" ? data[\"scope\"] : undefined;\n\tconst scopes = scopeStr\n\t\t? scopeStr\n\t\t\t\t.split(/\\s+/)\n\t\t\t\t.map((s) => s.trim())\n\t\t\t\t.filter((s) => s.length > 0)\n\t\t: fallbackScopes;\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccessToken: data[\"access_token\"],\n\t\t...(refreshToken !== undefined ? { refreshToken } : {}),\n\t\t...(expiresIn !== undefined ? { expiresAt: Date.now() + expiresIn * 1000 } : {}),\n\t\t...(typeof data[\"token_type\"] === \"string\" ? { tokenType: data[\"token_type\"] } : {}),\n\t\t...(scopes !== undefined && scopes.length > 0 ? { scopes } : {}),\n\t\tclient,\n\t};\n};\n\nexport const startAuthCodeFlow = (input: {\n\treadonly store: PendingOAuthStore;\n\treadonly connector: ConnectorSpec;\n\treadonly connection: ConnectionRow;\n\treadonly redirectUrl: string;\n\treadonly scopes?: ReadonlyArray<string> | undefined;\n\treadonly workspaceId: string;\n\treadonly actorId: string;\n\treadonly fetch?: typeof globalThis.fetch | undefined;\n}) =>\n\tEffect.tryPromise({\n\t\ttry: async () => {\n\t\t\tconst spec = input.connector.auth.oauth;\n\t\t\tif (spec === undefined) {\n\t\t\t\tthrow new Error(`Connector \"${input.connector.id}\" does not support OAuth`);\n\t\t\t}\n\t\t\tconst now = Date.now();\n\t\t\tconst expiresAt = now + PENDING_TTL_MS;\n\n\t\t\t// Built-in OpenAI Codex browser PKCE flow\n\t\t\tif (spec.handler === \"openai-codex\") {\n\t\t\t\tconst flow = await createOpenAICodexAuthorizationFlow({\n\t\t\t\t\tredirectUri: input.redirectUrl,\n\t\t\t\t\t...(input.scopes && input.scopes.length > 0 ? { scope: input.scopes.join(\" \") } : {}),\n\t\t\t\t});\n\t\t\t\tinput.store.put(flow.state, {\n\t\t\t\t\tkind: \"auth_code\",\n\t\t\t\t\tworkspaceId: input.workspaceId,\n\t\t\t\t\tactorId: input.actorId,\n\t\t\t\t\tconnectionId: input.connection.id,\n\t\t\t\t\tconnector: input.connector,\n\t\t\t\t\thandler: \"openai-codex\",\n\t\t\t\t\tredirectUrl: flow.redirectUri,\n\t\t\t\t\tcodeVerifier: flow.verifier,\n\t\t\t\t\tclient: { clientId: \"openai-codex\" },\n\t\t\t\t\tscopes: input.scopes,\n\t\t\t\t\texpiresAt,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tstate: flow.state,\n\t\t\t\t\tauthorizeUrl: flow.url,\n\t\t\t\t\tredirectUrl: flow.redirectUri,\n\t\t\t\t\texpiresAt,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (spec.handler === \"github-copilot\") {\n\t\t\t\tthrow new Error(\"GitHub Copilot uses device-code OAuth; start a device flow instead\");\n\t\t\t}\n\n\t\t\t// Standard OAuth 2.1 + PKCE (+ optional discovery & DCR)\n\t\t\tconst fetcher = input.fetch ?? globalThis.fetch;\n\t\t\tlet authorizeEndpoint = spec.authorizeUrl;\n\t\t\tlet tokenEndpoint = spec.tokenUrl;\n\t\t\tlet registrationEndpoint: string | undefined;\n\t\t\tlet resource: string | undefined = input.connector.capabilities.mcp?.url;\n\n\t\t\tif (spec.discovery === \"auto\" || !authorizeEndpoint || !tokenEndpoint) {\n\t\t\t\tconst discoveryTarget =\n\t\t\t\t\tinput.connector.capabilities.mcp?.url ??\n\t\t\t\t\tinput.connector.capabilities.integration?.baseUrl ??\n\t\t\t\t\tinput.connector.capabilities.provider?.baseUrl;\n\t\t\t\tif (!discoveryTarget) {\n\t\t\t\t\tthrow new Error(`Connector \"${input.connector.id}\" has no OAuth endpoints or discovery URL`);\n\t\t\t\t}\n\t\t\t\tconst discovered = await discoverOAuthMetadata(discoveryTarget, fetcher);\n\t\t\t\tauthorizeEndpoint = authorizeEndpoint ?? discovered.authorizeEndpoint;\n\t\t\t\ttokenEndpoint = tokenEndpoint ?? discovered.tokenEndpoint;\n\t\t\t\tregistrationEndpoint = discovered.registrationEndpoint;\n\t\t\t\tresource = discovered.resource ?? resource;\n\t\t\t}\n\n\t\t\tlet clientId = spec.clientId;\n\t\t\tlet clientSecret: string | undefined;\n\t\t\tif (!clientId) {\n\t\t\t\tif (!registrationEndpoint) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`OAuth server for \"${input.connector.id}\" does not advertise dynamic client registration`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst registered = await registerDynamicClient(registrationEndpoint, input.redirectUrl, fetcher);\n\t\t\t\tclientId = registered.clientId;\n\t\t\t\tclientSecret = registered.clientSecret;\n\t\t\t}\n\n\t\t\tconst { verifier, challenge } = generatePkce();\n\t\t\tconst state = randomState();\n\t\t\tconst scopes = input.scopes ?? input.connection.config.scopes ?? spec.scopes;\n\n\t\t\tconst url = new URL(authorizeEndpoint);\n\t\t\turl.searchParams.set(\"response_type\", \"code\");\n\t\t\turl.searchParams.set(\"client_id\", clientId);\n\t\t\turl.searchParams.set(\"redirect_uri\", input.redirectUrl);\n\t\t\turl.searchParams.set(\"state\", state);\n\t\t\tif (spec.pkce !== false) {\n\t\t\t\turl.searchParams.set(\"code_challenge\", challenge);\n\t\t\t\turl.searchParams.set(\"code_challenge_method\", \"S256\");\n\t\t\t}\n\t\t\tif (scopes && scopes.length > 0) {\n\t\t\t\turl.searchParams.set(\"scope\", scopes.join(\" \"));\n\t\t\t}\n\t\t\tif (resource) {\n\t\t\t\turl.searchParams.set(\"resource\", resource);\n\t\t\t}\n\n\t\t\tconst client: StoredOAuthClient = {\n\t\t\t\tclientId,\n\t\t\t\t...(clientSecret !== undefined ? { clientSecret } : {}),\n\t\t\t\tauthorizeEndpoint,\n\t\t\t\ttokenEndpoint,\n\t\t\t\t...(resource !== undefined ? { resource } : {}),\n\t\t\t};\n\n\t\t\tinput.store.put(state, {\n\t\t\t\tkind: \"auth_code\",\n\t\t\t\tworkspaceId: input.workspaceId,\n\t\t\t\tactorId: input.actorId,\n\t\t\t\tconnectionId: input.connection.id,\n\t\t\t\tconnector: input.connector,\n\t\t\t\tredirectUrl: input.redirectUrl,\n\t\t\t\tcodeVerifier: verifier,\n\t\t\t\tclient,\n\t\t\t\tscopes,\n\t\t\t\texpiresAt,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\tstate,\n\t\t\t\tauthorizeUrl: url.toString(),\n\t\t\t\tredirectUrl: input.redirectUrl,\n\t\t\t\texpiresAt,\n\t\t\t};\n\t\t},\n\t\tcatch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) }),\n\t});\n\nexport const finishAuthCodeFlow = (input: {\n\treadonly store: PendingOAuthStore;\n\treadonly state: string;\n\treadonly codeOrUrl: string;\n\treadonly workspaceId: string;\n\treadonly actorId: string;\n\treadonly fetch?: typeof globalThis.fetch | undefined;\n}) =>\n\tEffect.tryPromise({\n\t\ttry: async (): Promise<{ readonly connectionId: string; readonly secret: StoredOAuthSecret }> => {\n\t\t\tconst pending = input.store.consume(input.state, input.workspaceId, input.actorId);\n\t\t\tif (pending === undefined || pending.kind !== \"auth_code\") {\n\t\t\t\tthrow new Error(\"Invalid, expired, or unauthorized OAuth state\");\n\t\t\t}\n\n\t\t\t// Allow pasting either a bare authorization code or a full redirect URL.\n\t\t\tconst parsedInput = parseOpenAICodexAuthorizationInput(input.codeOrUrl);\n\t\t\tconst code = parsedInput.code ?? input.codeOrUrl.trim();\n\t\t\tif (parsedInput.state !== undefined && parsedInput.state !== input.state) {\n\t\t\t\tthrow new Error(\"OAuth state mismatch\");\n\t\t\t}\n\t\t\tif (code.length === 0) {\n\t\t\t\tthrow new Error(\"Missing authorization code\");\n\t\t\t}\n\n\t\t\tif (pending.handler === \"openai-codex\") {\n\t\t\t\tconst result = await exchangeOpenAICodexAuthorizationCode(code, pending.codeVerifier, pending.redirectUrl);\n\t\t\t\tif (result.type !== \"success\") {\n\t\t\t\t\tthrow new Error(result.message);\n\t\t\t\t}\n\t\t\t\tconst accountId = getOpenAICodexAccountId(result.access) ?? undefined;\n\t\t\t\treturn {\n\t\t\t\t\tconnectionId: pending.connectionId,\n\t\t\t\t\tsecret: {\n\t\t\t\t\t\ttype: \"oauth\",\n\t\t\t\t\t\taccessToken: result.access,\n\t\t\t\t\t\trefreshToken: result.refresh,\n\t\t\t\t\t\texpiresAt: result.expires,\n\t\t\t\t\t\t...(accountId !== undefined ? { accountId, accountLabel: accountId } : {}),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst tokenEndpoint = pending.client.tokenEndpoint;\n\t\t\tif (!tokenEndpoint) {\n\t\t\t\tthrow new Error(\"Missing OAuth token endpoint\");\n\t\t\t}\n\n\t\t\tconst body = new URLSearchParams({\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tclient_id: pending.client.clientId,\n\t\t\t\tcode,\n\t\t\t\tredirect_uri: pending.redirectUrl,\n\t\t\t\tcode_verifier: pending.codeVerifier,\n\t\t\t});\n\t\t\tif (pending.client.clientSecret) {\n\t\t\t\tbody.set(\"client_secret\", pending.client.clientSecret);\n\t\t\t}\n\t\t\tif (pending.client.resource) {\n\t\t\t\tbody.set(\"resource\", pending.client.resource);\n\t\t\t}\n\n\t\t\tconst fetcher = input.fetch ?? globalThis.fetch;\n\t\t\tconst response = await fetcher(tokenEndpoint, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\", Accept: \"application/json\" },\n\t\t\t\tbody,\n\t\t\t\tsignal: AbortSignal.timeout(HTTP_TIMEOUT_MS),\n\t\t\t});\n\t\t\tif (!response.ok) {\n\t\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\t\tthrow new Error(`OAuth token exchange failed (${response.status}): ${text || response.statusText}`);\n\t\t\t}\n\t\t\tconst data: unknown = await response.json();\n\t\t\treturn {\n\t\t\t\tconnectionId: pending.connectionId,\n\t\t\t\tsecret: parseTokenResponse(data, pending.client, undefined, pending.scopes),\n\t\t\t};\n\t\t},\n\t\tcatch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) }),\n\t});\n\nexport const startDeviceCodeFlow = (input: {\n\treadonly store: PendingOAuthStore;\n\treadonly connector: ConnectorSpec;\n\treadonly connection: ConnectionRow;\n\treadonly enterpriseUrl?: string | undefined;\n\treadonly workspaceId: string;\n\treadonly actorId: string;\n\treadonly fetch?: typeof globalThis.fetch | undefined;\n}) =>\n\tEffect.tryPromise({\n\t\ttry: async () => {\n\t\t\tconst spec = input.connector.auth.oauth;\n\t\t\tif (spec === undefined || !spec.grants.includes(\"device_code\")) {\n\t\t\t\tthrow new Error(`Connector \"${input.connector.id}\" does not support device-code OAuth`);\n\t\t\t}\n\t\t\tconst state = randomState();\n\t\t\tconst now = Date.now();\n\n\t\t\tif (spec.handler === \"github-copilot\") {\n\t\t\t\tconst enterpriseUrl = input.enterpriseUrl ?? input.connection.config.fields?.[\"enterpriseUrl\"];\n\t\t\t\tconst domain = normalizeGitHubDomain(enterpriseUrl);\n\t\t\t\tconst flow = await createGitHubCopilotDeviceFlow({\n\t\t\t\t\t...(domain !== undefined ? { domain } : {}),\n\t\t\t\t\t...(input.fetch !== undefined ? { fetch: input.fetch } : {}),\n\t\t\t\t});\n\t\t\t\tconst expiresAt = now + (flow.expiresInSeconds ?? 900) * 1000;\n\t\t\t\tinput.store.put(state, {\n\t\t\t\t\tkind: \"device_code\",\n\t\t\t\t\tworkspaceId: input.workspaceId,\n\t\t\t\t\tactorId: input.actorId,\n\t\t\t\t\tconnectionId: input.connection.id,\n\t\t\t\t\tconnector: input.connector,\n\t\t\t\t\thandler: \"github-copilot\",\n\t\t\t\t\tdeviceCode: flow.deviceCode,\n\t\t\t\t\tuserCode: flow.userCode,\n\t\t\t\t\tverificationUri: flow.verificationUri,\n\t\t\t\t\tintervalSeconds: flow.intervalSeconds,\n\t\t\t\t\t...(enterpriseUrl !== undefined ? { enterpriseUrl } : {}),\n\t\t\t\t\texpiresAt,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tstate,\n\t\t\t\t\tverificationUri: flow.verificationUri,\n\t\t\t\t\tuserCode: flow.userCode,\n\t\t\t\t\tintervalSeconds: flow.intervalSeconds,\n\t\t\t\t\texpiresAt,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (spec.handler === \"openai-codex\") {\n\t\t\t\tconst device = await createOpenAICodexDeviceAuth();\n\t\t\t\tconst expiresAt = now + 15 * 60 * 1000;\n\t\t\t\tinput.store.put(state, {\n\t\t\t\t\tkind: \"device_code\",\n\t\t\t\t\tworkspaceId: input.workspaceId,\n\t\t\t\t\tactorId: input.actorId,\n\t\t\t\t\tconnectionId: input.connection.id,\n\t\t\t\t\tconnector: input.connector,\n\t\t\t\t\thandler: \"openai-codex\",\n\t\t\t\t\tdeviceCode: device.deviceAuthId,\n\t\t\t\t\tuserCode: device.userCode,\n\t\t\t\t\tverificationUri: device.verificationUri,\n\t\t\t\t\tintervalSeconds: device.intervalSeconds,\n\t\t\t\t\texpiresAt,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tstate,\n\t\t\t\t\tverificationUri: device.verificationUri,\n\t\t\t\t\tuserCode: device.userCode,\n\t\t\t\t\tintervalSeconds: device.intervalSeconds,\n\t\t\t\t\texpiresAt,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tthrow new Error(`Unsupported device-code handler for \"${input.connector.id}\"`);\n\t\t},\n\t\tcatch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) }),\n\t});\n\n/**\n * Performs one non-blocking poll step for an active device-code login so RPC/UI callers never hang.\n */\nexport const pollDeviceCodeStep = (input: {\n\treadonly store: PendingOAuthStore;\n\treadonly state: string;\n\treadonly workspaceId: string;\n\treadonly actorId: string;\n\treadonly fetch?: typeof globalThis.fetch | undefined;\n}) =>\n\tEffect.tryPromise({\n\t\ttry: async (): Promise<\n\t\t\t| { readonly status: \"pending\"; readonly intervalSeconds?: number | undefined }\n\t\t\t| { readonly status: \"complete\"; readonly connectionId: string; readonly secret: StoredOAuthSecret }\n\t\t> => {\n\t\t\tconst pending = input.store.peek(input.state, input.workspaceId, input.actorId);\n\t\t\tif (pending === undefined || pending.kind !== \"device_code\") {\n\t\t\t\tthrow new Error(\"Invalid, expired, or unauthorized device-code state\");\n\t\t\t}\n\t\t\tconst fetcher = input.fetch ?? globalThis.fetch;\n\n\t\t\tif (pending.handler === \"github-copilot\") {\n\t\t\t\tconst domain = normalizeGitHubDomain(pending.enterpriseUrl) ?? \"github.com\";\n\t\t\t\tconst response = await fetcher(`https://${domain}/login/oauth/access_token`, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: { Accept: \"application/json\", \"Content-Type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tclient_id: GITHUB_COPILOT_CLIENT_ID,\n\t\t\t\t\t\tdevice_code: pending.deviceCode,\n\t\t\t\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\t\t\t}),\n\t\t\t\t\tsignal: AbortSignal.timeout(HTTP_TIMEOUT_MS),\n\t\t\t\t});\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new Error(`GitHub device token poll failed (${response.status})`);\n\t\t\t\t}\n\t\t\t\tconst data: unknown = await response.json();\n\t\t\t\tif (!isRecord(data)) throw new Error(\"Invalid GitHub device token response\");\n\t\t\t\tif (typeof data[\"access_token\"] === \"string\" && data[\"access_token\"].length > 0) {\n\t\t\t\t\tinput.store.delete(input.state);\n\t\t\t\t\tconst accessToken = data[\"access_token\"];\n\t\t\t\t\tconst user = await fetchGitHubCopilotUser(accessToken, {\n\t\t\t\t\t\tdomain,\n\t\t\t\t\t\tfetch: fetcher,\n\t\t\t\t\t});\n\t\t\t\t\tconst entitlementIssue = user\n\t\t\t\t\t\t? gitHubCopilotEntitlementError({\n\t\t\t\t\t\t\t\tchat_enabled: user.chatEnabled,\n\t\t\t\t\t\t\t\tcan_signup_for_limited: user.canSignupForLimited,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (entitlementIssue) throw new Error(entitlementIssue);\n\t\t\t\t\tconst baseURL =\n\t\t\t\t\t\tuser?.apiEndpoint ??\n\t\t\t\t\t\t(pending.enterpriseUrl ? gitHubCopilotBaseUrl({ enterpriseUrl: pending.enterpriseUrl }) : undefined);\n\t\t\t\t\tconst remoteModels = await fetchGitHubCopilotModels(accessToken, {\n\t\t\t\t\t\tdomain,\n\t\t\t\t\t\t...(baseURL !== undefined ? { baseURL } : {}),\n\t\t\t\t\t\tfetch: fetcher,\n\t\t\t\t\t}).catch(() => undefined);\n\t\t\t\t\tconst availableModelIds = remoteModels?.map((m) => m.id);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"complete\",\n\t\t\t\t\t\tconnectionId: pending.connectionId,\n\t\t\t\t\t\tsecret: {\n\t\t\t\t\t\t\ttype: \"oauth\",\n\t\t\t\t\t\t\taccessToken,\n\t\t\t\t\t\t\trefreshToken: accessToken,\n\t\t\t\t\t\t\t...(user?.apiEndpoint !== undefined ? { apiEndpoint: user.apiEndpoint } : {}),\n\t\t\t\t\t\t\t...(pending.enterpriseUrl !== undefined ? { enterpriseUrl: pending.enterpriseUrl } : {}),\n\t\t\t\t\t\t\t...(availableModelIds !== undefined && availableModelIds.length > 0 ? { availableModelIds } : {}),\n\t\t\t\t\t\t\taccountLabel: pending.enterpriseUrl ?? \"github.com\",\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst err = typeof data[\"error\"] === \"string\" ? data[\"error\"] : undefined;\n\t\t\t\tif (err === \"authorization_pending\") {\n\t\t\t\t\treturn { status: \"pending\", intervalSeconds: pending.intervalSeconds };\n\t\t\t\t}\n\t\t\t\tif (err === \"slow_down\") {\n\t\t\t\t\tconst nextInterval =\n\t\t\t\t\t\ttypeof data[\"interval\"] === \"number\" && data[\"interval\"] > 0\n\t\t\t\t\t\t\t? data[\"interval\"]\n\t\t\t\t\t\t\t: pending.intervalSeconds + 5;\n\t\t\t\t\treturn { status: \"pending\", intervalSeconds: nextInterval };\n\t\t\t\t}\n\t\t\t\tinput.store.delete(input.state);\n\t\t\t\tconst desc = typeof data[\"error_description\"] === \"string\" ? `: ${data[\"error_description\"]}` : \"\";\n\t\t\t\tthrow new Error(`GitHub device authorization failed: ${err ?? \"unknown\"}${desc}`);\n\t\t\t}\n\n\t\t\t// OpenAI Codex device poll\n\t\t\tconst response = await fetcher(CODEX_DEVICE_TOKEN_URL, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ device_auth_id: pending.deviceCode, user_code: pending.userCode }),\n\t\t\t\tsignal: AbortSignal.timeout(HTTP_TIMEOUT_MS),\n\t\t\t});\n\t\t\tif (response.status === 403 || response.status === 404) {\n\t\t\t\treturn { status: \"pending\", intervalSeconds: pending.intervalSeconds };\n\t\t\t}\n\t\t\tif (response.ok) {\n\t\t\t\tconst data: unknown = await response.json();\n\t\t\t\tif (\n\t\t\t\t\t!isRecord(data) ||\n\t\t\t\t\ttypeof data[\"authorization_code\"] !== \"string\" ||\n\t\t\t\t\ttypeof data[\"code_verifier\"] !== \"string\"\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"Invalid OpenAI Codex device token response\");\n\t\t\t\t}\n\t\t\t\tinput.store.delete(input.state);\n\t\t\t\tconst exchanged = await exchangeOpenAICodexAuthorizationCode(\n\t\t\t\t\tdata[\"authorization_code\"],\n\t\t\t\t\tdata[\"code_verifier\"],\n\t\t\t\t\tCODEX_DEVICE_REDIRECT_URI,\n\t\t\t\t);\n\t\t\t\tif (exchanged.type !== \"success\") throw new Error(exchanged.message);\n\t\t\t\tconst accountId = getOpenAICodexAccountId(exchanged.access) ?? undefined;\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"complete\",\n\t\t\t\t\tconnectionId: pending.connectionId,\n\t\t\t\t\tsecret: {\n\t\t\t\t\t\ttype: \"oauth\",\n\t\t\t\t\t\taccessToken: exchanged.access,\n\t\t\t\t\t\trefreshToken: exchanged.refresh,\n\t\t\t\t\t\texpiresAt: exchanged.expires,\n\t\t\t\t\t\t...(accountId !== undefined ? { accountId, accountLabel: accountId } : {}),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\tlet errorCode: unknown;\n\t\t\ttry {\n\t\t\t\tconst parsed: unknown = JSON.parse(text);\n\t\t\t\tconst err = isRecord(parsed) ? parsed[\"error\"] : undefined;\n\t\t\t\terrorCode = isRecord(err) ? err[\"code\"] : err;\n\t\t\t} catch {\n\t\t\t\t// Not JSON.\n\t\t\t}\n\t\t\tif (errorCode === \"deviceauth_authorization_pending\") {\n\t\t\t\treturn { status: \"pending\", intervalSeconds: pending.intervalSeconds };\n\t\t\t}\n\t\t\tif (errorCode === \"slow_down\") {\n\t\t\t\treturn { status: \"pending\", intervalSeconds: pending.intervalSeconds + 5 };\n\t\t\t}\n\t\t\tinput.store.delete(input.state);\n\t\t\tthrow new Error(`OpenAI Codex device authorization failed (${response.status})`);\n\t\t},\n\t\tcatch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) }),\n\t});\n\n/**\n * Network refresh step (called under the broker's double-checked lock).\n */\nexport const refreshOAuthSecret = async (\n\tconnector: ConnectorSpec,\n\tcurrent: StoredOAuthSecret,\n\tfetcher: typeof globalThis.fetch = globalThis.fetch,\n): Promise<StoredOAuthSecret> => {\n\tconst handler = connector.auth.oauth?.handler;\n\n\tif (handler === \"github-copilot\") {\n\t\t// GitHub OAuth tokens do not expire.\n\t\treturn current;\n\t}\n\n\tif (!current.refreshToken) {\n\t\tthrow new Error(`OAuth token for \"${connector.id}\" expired and has no refresh token`);\n\t}\n\n\tif (handler === \"openai-codex\") {\n\t\tconst refreshed = await refreshOpenAICodexToken(current.refreshToken);\n\t\tconst accountId = getOpenAICodexAccountId(refreshed.access) ?? current.accountId;\n\t\treturn {\n\t\t\t...current,\n\t\t\taccessToken: refreshed.access,\n\t\t\trefreshToken: refreshed.refresh,\n\t\t\texpiresAt: refreshed.expires,\n\t\t\t...(accountId !== undefined ? { accountId, accountLabel: accountId } : {}),\n\t\t};\n\t}\n\n\tconst tokenEndpoint = current.client?.tokenEndpoint ?? connector.auth.oauth?.tokenUrl;\n\tconst clientId = current.client?.clientId ?? connector.auth.oauth?.clientId;\n\tif (!tokenEndpoint || !clientId) {\n\t\tthrow new Error(`Missing OAuth token endpoint or client_id for \"${connector.id}\" refresh`);\n\t}\n\n\tconst body = new URLSearchParams({\n\t\tgrant_type: \"refresh_token\",\n\t\tclient_id: clientId,\n\t\trefresh_token: current.refreshToken,\n\t});\n\tif (current.client?.clientSecret) {\n\t\tbody.set(\"client_secret\", current.client.clientSecret);\n\t}\n\tif (current.client?.resource) {\n\t\tbody.set(\"resource\", current.client.resource);\n\t}\n\n\tconst response = await fetcher(tokenEndpoint, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\", Accept: \"application/json\" },\n\t\tbody,\n\t\tsignal: AbortSignal.timeout(HTTP_TIMEOUT_MS),\n\t});\n\tif (!response.ok) {\n\t\tconst text = await response.text().catch(() => \"\");\n\t\tthrow new Error(`OAuth refresh failed (${response.status}): ${text || response.statusText}`);\n\t}\n\tconst data: unknown = await response.json();\n\tconst refreshed = parseTokenResponse(\n\t\tdata,\n\t\tcurrent.client ?? { clientId, tokenEndpoint },\n\t\tcurrent.refreshToken,\n\t\tcurrent.scopes,\n\t);\n\treturn {\n\t\t...current,\n\t\t...refreshed,\n\t};\n};\n\n/**\n * Pure request-auth derivation (`toAuth` in Pi's model): maps a valid stored OAuth secret to\n * `{ token, headers?, baseUrl? }` without performing any network calls.\n */\nexport const deriveOAuthRequestAuth = (\n\tconnector: ConnectorSpec,\n\tsecret: StoredOAuthSecret,\n): {\n\treadonly token: string;\n\treadonly headers?: Readonly<Record<string, string>> | undefined;\n\treadonly baseUrl?: string | undefined;\n} => {\n\tconst handler = connector.auth.oauth?.handler;\n\tif (handler === \"github-copilot\") {\n\t\tconst creds: GitHubCopilotOAuthCredentials = {\n\t\t\taccess: secret.accessToken,\n\t\t\trefresh: secret.refreshToken ?? secret.accessToken,\n\t\t\texpires: 0,\n\t\t\t...(secret.enterpriseUrl !== undefined ? { enterpriseUrl: secret.enterpriseUrl } : {}),\n\t\t\t...(secret.apiEndpoint !== undefined ? { apiEndpoint: secret.apiEndpoint } : {}),\n\t\t\t...(secret.availableModelIds !== undefined ? { availableModelIds: [...secret.availableModelIds] } : {}),\n\t\t};\n\t\treturn {\n\t\t\ttoken: secret.accessToken,\n\t\t\theaders: gitHubCopilotHeaders(creds),\n\t\t\tbaseUrl:\n\t\t\t\tsecret.apiEndpoint ??\n\t\t\t\t(secret.enterpriseUrl ? gitHubCopilotBaseUrl({ enterpriseUrl: secret.enterpriseUrl }) : undefined),\n\t\t};\n\t}\n\n\tif (handler === \"openai-codex\") {\n\t\tconst creds: OpenAICodexOAuthCredentials = {\n\t\t\taccess: secret.accessToken,\n\t\t\trefresh: secret.refreshToken ?? \"\",\n\t\t\texpires: secret.expiresAt ?? 0,\n\t\t\taccountId: secret.accountId ?? getOpenAICodexAccountId(secret.accessToken) ?? \"\",\n\t\t};\n\t\treturn {\n\t\t\ttoken: secret.accessToken,\n\t\t\theaders: creds.accountId ? openAICodexHeaders(creds) : undefined,\n\t\t};\n\t}\n\n\treturn {\n\t\ttoken: secret.accessToken,\n\t\theaders: { Authorization: `Bearer ${secret.accessToken}` },\n\t};\n};\n\nexport const applyHeaderInjection = (\n\tinject: HeaderInjection | undefined,\n\ttoken: string,\n): Readonly<Record<string, string>> | undefined => {\n\tif (inject === undefined) return undefined;\n\treturn { [inject.name]: `${inject.prefix ?? \"\"}${token}` };\n};\n","/* @effect-diagnostics processEnv:off -- machine-global env connector projection reads host process.env. */\nimport { Actor } from \"@codeworksh/schema/actor\";\nimport {\n\tAuthRequiredError,\n\tCONNECTION_SLUG_PATTERN,\n\tCONNECTION_UID_PATTERN,\n\tConnectionConflictError,\n\ttype ConnectionConfig,\n\tConnectionID,\n\tConnectionNotFoundError,\n\ttype ConnectionSummary,\n\ttype ConnectorCatalog,\n\ttype ConnectorError,\n\ttype ConnectorKind,\n\tConnectorNotFoundError,\n\ttype ConnectorSpec,\n\tConnectorValidationError,\n\ttype DevicePollResult,\n\ttype DeviceStartResult,\n\tHostNotAllowedError,\n\ttype OAuthStartResult,\n\ttype Ownership,\n\ttype StoredAuthType,\n\tformatUid,\n\thostMatches,\n} from \"@codeworksh/schema/connector\";\nimport { Connector, Global } from \"@codeworksh/harness/effect\";\nimport { Clock, Context, Effect, Layer, Redacted, Semaphore } from \"effect\";\nimport {\n\ttype CatalogFilter,\n\tfetchCatalog,\n\tfilterConnectors,\n\tfindConnector,\n\tfindConnectorByProviderId,\n\tloadLocalCatalog,\n} from \"./catalog.ts\";\nimport {\n\ttype ConnectionRow,\n\tConnectionsDb,\n\ttype CredentialRow,\n\ttype StoredOAuthSecret,\n\ttype SubjectType,\n\tconnectionsDbPath,\n} from \"./db.ts\";\nimport {\n\tPendingOAuthStore,\n\tapplyHeaderInjection,\n\tderiveOAuthRequestAuth,\n\tfinishAuthCodeFlow,\n\tpollDeviceCodeStep,\n\trefreshOAuthSecret,\n\tstartAuthCodeFlow,\n\tstartDeviceCodeFlow,\n} from \"./oauth.ts\";\n\nconst DEFAULT_OAUTH_MIN_VALIDITY_MS = 5 * 60 * 1000;\n\nexport interface CreateConnectionInput {\n\treadonly connector: string;\n\treadonly slug?: string | undefined;\n\treadonly label?: string | undefined;\n\treadonly authType?: StoredAuthType | undefined;\n\treadonly ownership?: Ownership | undefined;\n\treadonly enabled?: boolean | undefined;\n\treadonly isDefault?: boolean | undefined;\n\treadonly config?: ConnectionConfig | undefined;\n}\n\nexport interface UpdateConnectionPatch {\n\treadonly ref: string;\n\treadonly uid?: string | undefined;\n\treadonly label?: string | null | undefined;\n\treadonly ownership?: Ownership | undefined;\n\treadonly enabled?: boolean | undefined;\n\treadonly isDefault?: boolean | undefined;\n\treadonly config?: ConnectionConfig | undefined;\n}\n\nexport interface ServiceInterface extends Connector.BrokerInterface {\n\treadonly catalog: (options?: {\n\t\treadonly kind?: ConnectorKind | undefined;\n\t\treadonly category?: string | undefined;\n\t\treadonly query?: string | undefined;\n\t\treadonly refresh?: boolean | undefined;\n\t}) => Effect.Effect<{\n\t\treadonly schemaVersion: 1;\n\t\treadonly generatedAt: string;\n\t\treadonly categories: ConnectorCatalog[\"categories\"];\n\t\treadonly connectors: ReadonlyArray<ConnectorSpec>;\n\t}>;\n\treadonly list: (filter?: {\n\t\treadonly kind?: ConnectorKind | undefined;\n\t\treadonly connectorId?: string | undefined;\n\t\treadonly enabled?: boolean | undefined;\n\t\treadonly includeEnv?: boolean | undefined;\n\t}) => Effect.Effect<ReadonlyArray<ConnectionSummary>, ConnectorError>;\n\treadonly get: (ref: string) => Effect.Effect<ConnectionSummary, ConnectorError>;\n\treadonly create: (input: CreateConnectionInput) => Effect.Effect<ConnectionSummary, ConnectorError>;\n\treadonly update: (input: UpdateConnectionPatch) => Effect.Effect<ConnectionSummary, ConnectorError>;\n\treadonly remove: (ref: string) => Effect.Effect<boolean, ConnectorError>;\n\treadonly setApiKey: (ref: string, apiKey: string) => Effect.Effect<ConnectionSummary, ConnectorError>;\n\treadonly disconnect: (ref: string) => Effect.Effect<ConnectionSummary, ConnectorError>;\n\treadonly oauthStart: (input: {\n\t\treadonly ref: string;\n\t\treadonly redirectUrl: string;\n\t\treadonly scopes?: ReadonlyArray<string> | undefined;\n\t}) => Effect.Effect<OAuthStartResult, ConnectorError>;\n\treadonly oauthFinish: (input: {\n\t\treadonly state: string;\n\t\treadonly code: string;\n\t}) => Effect.Effect<ConnectionSummary, ConnectorError>;\n\treadonly deviceStart: (input: {\n\t\treadonly ref: string;\n\t\treadonly enterpriseUrl?: string | undefined;\n\t}) => Effect.Effect<DeviceStartResult, ConnectorError>;\n\treadonly devicePoll: (state: string) => Effect.Effect<DevicePollResult, ConnectorError>;\n}\n\nexport class Service extends Context.Service<Service, ServiceInterface>()(\"@codeworksh/cli/connector/service\") {}\n\nexport interface LayerOptions {\n\treadonly home?: string | undefined;\n\treadonly dbPath?: string | undefined;\n\treadonly catalogUrl?: string | undefined;\n\treadonly fetch?: typeof globalThis.fetch | undefined;\n\treadonly env?: Readonly<Record<string, string | undefined>> | undefined;\n}\n\nconst subjectFor = (row: ConnectionRow, actor: Actor.ActorRef): { readonly type: SubjectType; readonly id: string } =>\n\trow.ownership === \"personal\" ? { type: \"user\", id: actor.id } : { type: \"app\", id: actor.scope };\n\nconst readEnvVar = (\n\tenv: Readonly<Record<string, string | undefined>>,\n\tvars: ReadonlyArray<string>,\n): { readonly name: string; readonly value: string } | undefined => {\n\tfor (const name of vars) {\n\t\tconst raw = env[name]?.trim();\n\t\tif (raw !== undefined && raw.length > 0) return { name, value: raw };\n\t}\n\treturn undefined;\n};\n\nconst summarizeStored = (row: ConnectionRow, cred: CredentialRow | undefined, now: number): ConnectionSummary => {\n\tlet status = cred?.status ?? \"not_connected\";\n\tif (\n\t\tstatus === \"active\" &&\n\t\trow.authType === \"oauth\" &&\n\t\tcred?.expiresAt !== undefined &&\n\t\tcred.expiresAt <= now &&\n\t\tcred.secret.type === \"oauth\" &&\n\t\t!cred.secret.refreshToken\n\t) {\n\t\tstatus = \"expired\";\n\t}\n\tconst sourceLabel = row.authType === \"oauth\" ? `OAuth (${row.ownership})` : `API key (${row.ownership})`;\n\tconst accountLabel = cred?.secret.type === \"oauth\" ? cred.secret.accountLabel : undefined;\n\n\treturn {\n\t\tid: row.id,\n\t\tuid: row.uid,\n\t\tconnectorId: row.connectorId,\n\t\tworkspaceId: row.workspaceId,\n\t\t...(row.label !== undefined ? { label: row.label } : {}),\n\t\tsource: row.source,\n\t\tkinds: row.kinds,\n\t\tauthType: row.authType,\n\t\townership: row.ownership,\n\t\tenabled: row.enabled,\n\t\tisDefault: row.isDefault,\n\t\tstatus,\n\t\tsourceLabel,\n\t\t...(accountLabel !== undefined ? { accountLabel } : {}),\n\t\t...(cred?.lastError !== undefined ? { lastError: cred.lastError } : {}),\n\t\t...(cred?.expiresAt !== undefined ? { expiresAt: cred.expiresAt } : {}),\n\t\tallowedHosts: row.allowedHosts,\n\t\tconfig: row.config,\n\t\treadOnly: false,\n\t\tcreatedAt: row.createdAt,\n\t\tupdatedAt: row.updatedAt,\n\t};\n};\n\nconst summarizeEnv = (spec: ConnectorSpec, workspaceId: string, envVar: string): ConnectionSummary => ({\n\tid: `env:${spec.id}`,\n\tuid: formatUid(spec.id, \"env\"),\n\tconnectorId: spec.id,\n\tworkspaceId,\n\tlabel: `${spec.name} (host env)`,\n\tsource: \"catalog\",\n\tkinds: spec.kinds,\n\tauthType: \"env\",\n\townership: \"shared\",\n\tenabled: true,\n\tisDefault: false,\n\tstatus: \"active\",\n\tsourceLabel: `$${envVar}`,\n\tenvVar,\n\tallowedHosts: spec.allowedHosts,\n\tconfig: {},\n\treadOnly: true,\n\tcreatedAt: 0,\n\tupdatedAt: 0,\n});\n\nconst resolveFields = (\n\tspec: ConnectorSpec,\n\trow: ConnectionRow,\n\tenv: Readonly<Record<string, string | undefined>>,\n): Readonly<Record<string, string>> | undefined => {\n\tconst fieldSpecs = row.authType === \"oauth\" ? spec.auth.oauth?.fields : spec.auth.apikey?.fields;\n\tconst merged: Record<string, string> = { ...row.config.fields };\n\tif (fieldSpecs) {\n\t\tfor (const field of fieldSpecs) {\n\t\t\tif (merged[field.key] === undefined && field.envFallback) {\n\t\t\t\tconst val = env[field.envFallback]?.trim();\n\t\t\t\tif (val) merged[field.key] = val;\n\t\t\t}\n\t\t}\n\t}\n\treturn Object.keys(merged).length > 0 ? merged : undefined;\n};\n\nconst validateHost = (\n\tconnectionId: string,\n\tuid: string,\n\tallowedHosts: ReadonlyArray<string>,\n\ttargetHost: string | undefined,\n): Effect.Effect<void, HostNotAllowedError> => {\n\tif (targetHost === undefined || allowedHosts.length === 0) return Effect.void;\n\tif (hostMatches(targetHost, allowedHosts)) return Effect.void;\n\treturn Effect.fail(\n\t\tnew HostNotAllowedError({\n\t\t\tconnectionId,\n\t\t\tuid,\n\t\t\thost: targetHost,\n\t\t\tallowedHosts: [...allowedHosts],\n\t\t\tmessage: `Host \"${targetHost}\" is not allowed for connection \"${uid}\"`,\n\t\t}),\n\t);\n};\n\nconst make = (options: LayerOptions = {}) =>\n\tEffect.acquireRelease(\n\t\tEffect.gen(function* () {\n\t\t\tconst paths = yield* Global.resolve(options.home === undefined ? {} : { home: options.home });\n\t\t\tconst home = paths.home;\n\t\t\tconst dbFile = options.dbPath ?? connectionsDbPath(home);\n\t\t\tconst db = new ConnectionsDb(dbFile);\n\t\t\tconst legacyAuthFile = Global.authFile(options.home === undefined ? undefined : home) ?? Global.authFile(home);\n\t\t\tdb.importLegacyAikitAuth(legacyAuthFile, yield* Clock.currentTimeMillis);\n\n\t\t\tlet cachedCatalog = loadLocalCatalog(home);\n\t\t\tconst pendingOAuth = new PendingOAuthStore();\n\t\t\tconst refreshLocks = new Map<string, Semaphore.Semaphore>();\n\t\t\tconst getEnv = () => options.env ?? process.env;\n\n\t\t\tconst semaphoreFor = (key: string): Semaphore.Semaphore => {\n\t\t\t\tlet lock = refreshLocks.get(key);\n\t\t\t\tif (lock === undefined) {\n\t\t\t\t\tlock = Semaphore.makeUnsafe(1);\n\t\t\t\t\trefreshLocks.set(key, lock);\n\t\t\t\t}\n\t\t\t\treturn lock;\n\t\t\t};\n\n\t\t\tconst specForRow = (row: ConnectionRow): ConnectorSpec | undefined =>\n\t\t\t\trow.source === \"custom\" ? row.spec : cachedCatalog.connectors[row.connectorId];\n\n\t\t\tconst currentCatalog = (refresh?: boolean) =>\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tif (refresh) {\n\t\t\t\t\t\tcachedCatalog = yield* fetchCatalog({\n\t\t\t\t\t\t\thome,\n\t\t\t\t\t\t\turl: options.catalogUrl,\n\t\t\t\t\t\t\tfetch: options.fetch,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\treturn cachedCatalog;\n\t\t\t\t});\n\n\t\t\tconst resolveRowSecret = Effect.fn(\"Connector.resolveRowSecret\")(function* (\n\t\t\t\trow: ConnectionRow,\n\t\t\t\tactor: Actor.ActorRef,\n\t\t\t\tinput: { readonly targetHost?: string | undefined; readonly minValidityMs?: number | undefined },\n\t\t\t): Effect.fn.Return<Connector.ResolvedCredential, ConnectorError> {\n\t\t\t\tconst spec = specForRow(row);\n\t\t\t\tif (spec === undefined) {\n\t\t\t\t\treturn yield* new ConnectorNotFoundError({\n\t\t\t\t\t\tconnectorId: row.connectorId,\n\t\t\t\t\t\tmessage: `Connector \"${row.connectorId}\" is not in the catalog`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tyield* validateHost(row.id, row.uid, row.allowedHosts, input.targetHost);\n\t\t\t\tif (!row.enabled) {\n\t\t\t\t\treturn yield* new AuthRequiredError({\n\t\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\t\tuid: row.uid,\n\t\t\t\t\t\tconnectorId: row.connectorId,\n\t\t\t\t\t\treason: \"not_connected\",\n\t\t\t\t\t\tmessage: `Connection \"${row.uid}\" is disabled`,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst subject = subjectFor(row, actor);\n\t\t\t\tconst cred = db.getCredential(row.id, subject.type, subject.id);\n\t\t\t\tif (cred === undefined) {\n\t\t\t\t\treturn yield* new AuthRequiredError({\n\t\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\t\tuid: row.uid,\n\t\t\t\t\t\tconnectorId: row.connectorId,\n\t\t\t\t\t\treason: \"not_connected\",\n\t\t\t\t\t\tmessage: `Connection \"${row.uid}\" has not been authenticated yet`,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst fields = resolveFields(spec, row, getEnv());\n\n\t\t\t\tif (row.authType === \"apikey\") {\n\t\t\t\t\tif (cred.secret.type !== \"apikey\" || cred.secret.apiKey.length === 0) {\n\t\t\t\t\t\treturn yield* new AuthRequiredError({\n\t\t\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\t\t\tuid: row.uid,\n\t\t\t\t\t\t\tconnectorId: row.connectorId,\n\t\t\t\t\t\t\treason: \"not_connected\",\n\t\t\t\t\t\t\tmessage: `Connection \"${row.uid}\" has no API key stored`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst headers = applyHeaderInjection(spec.auth.apikey?.inject, cred.secret.apiKey);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\t\tuid: row.uid,\n\t\t\t\t\t\ttoken: Redacted.make(cred.secret.apiKey),\n\t\t\t\t\t\t...(headers !== undefined ? { headers } : {}),\n\t\t\t\t\t\t...(spec.capabilities.provider?.baseUrl !== undefined\n\t\t\t\t\t\t\t? { baseUrl: spec.capabilities.provider.baseUrl }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(fields !== undefined ? { fields } : {}),\n\t\t\t\t\t\tsourceLabel: `API key (${row.ownership})`,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// OAuth resolution with double-checked locking & uncancellable refresh write.\n\t\t\t\tif (cred.secret.type !== \"oauth\") {\n\t\t\t\t\treturn yield* new AuthRequiredError({\n\t\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\t\tuid: row.uid,\n\t\t\t\t\t\tconnectorId: row.connectorId,\n\t\t\t\t\t\treason: \"not_connected\",\n\t\t\t\t\t\tmessage: `Connection \"${row.uid}\" is missing OAuth credentials`,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst minValidity = Math.max(DEFAULT_OAUTH_MIN_VALIDITY_MS, input.minValidityMs ?? 0);\n\t\t\t\tconst needsRefresh = (secret: StoredOAuthSecret, now: number) =>\n\t\t\t\t\tsecret.expiresAt !== undefined && secret.expiresAt > 0 && now + minValidity >= secret.expiresAt;\n\n\t\t\t\tlet activeSecret = cred.secret;\n\t\t\t\tif (needsRefresh(activeSecret, yield* Clock.currentTimeMillis)) {\n\t\t\t\t\tconst lockKey = `${row.id}:${subject.type}:${subject.id}`;\n\t\t\t\t\tconst lock = semaphoreFor(lockKey);\n\t\t\t\t\tactiveSecret = yield* lock.withPermits(1)(\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\t// Re-check authoritative DB state inside the lock (another fiber/process may have refreshed).\n\t\t\t\t\t\t\tconst latest = db.getCredential(row.id, subject.type, subject.id);\n\t\t\t\t\t\t\tif (latest === undefined || latest.secret.type !== \"oauth\") {\n\t\t\t\t\t\t\t\treturn yield* new AuthRequiredError({\n\t\t\t\t\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\t\t\t\t\tuid: row.uid,\n\t\t\t\t\t\t\t\t\tconnectorId: row.connectorId,\n\t\t\t\t\t\t\t\t\treason: \"not_connected\",\n\t\t\t\t\t\t\t\t\tmessage: `Connection \"${row.uid}\" was disconnected`,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!needsRefresh(latest.secret, yield* Clock.currentTimeMillis)) {\n\t\t\t\t\t\t\t\treturn latest.secret;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Once the refresh request starts, do not drop a rotated refresh token on fiber cancel.\n\t\t\t\t\t\t\treturn yield* Effect.uninterruptible(\n\t\t\t\t\t\t\t\tEffect.tryPromise({\n\t\t\t\t\t\t\t\t\ttry: () => refreshOAuthSecret(spec, latest.secret as StoredOAuthSecret, options.fetch),\n\t\t\t\t\t\t\t\t\tcatch: (cause) => (cause instanceof Error ? cause.message : String(cause)),\n\t\t\t\t\t\t\t\t}).pipe(\n\t\t\t\t\t\t\t\t\tEffect.tap((refreshed) =>\n\t\t\t\t\t\t\t\t\t\tClock.currentTimeMillis.pipe(\n\t\t\t\t\t\t\t\t\t\t\tEffect.map((now) => {\n\t\t\t\t\t\t\t\t\t\t\t\tdb.withImmediateTx(() => {\n\t\t\t\t\t\t\t\t\t\t\t\t\tdb.upsertCredential({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsubjectType: subject.type,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsubjectId: subject.id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsecret: refreshed,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstatus: \"active\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t...(refreshed.expiresAt !== undefined\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? { expiresAt: refreshed.expiresAt }\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tEffect.catch((message) =>\n\t\t\t\t\t\t\t\t\t\tClock.currentTimeMillis.pipe(\n\t\t\t\t\t\t\t\t\t\t\tEffect.flatMap((now) =>\n\t\t\t\t\t\t\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\t\t\t\t\t\t\tdb.markCredentialStatus(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\trow.id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsubject.type,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsubject.id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"expired\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmessage,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\tEffect.flatMap(() =>\n\t\t\t\t\t\t\t\t\t\t\t\tEffect.fail(\n\t\t\t\t\t\t\t\t\t\t\t\t\tnew AuthRequiredError({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tuid: row.uid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconnectorId: row.connectorId,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treason: \"expired\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmessage: `OAuth refresh failed for \"${row.uid}\": ${message}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst derived = deriveOAuthRequestAuth(spec, activeSecret);\n\t\t\t\treturn {\n\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\tuid: row.uid,\n\t\t\t\t\ttoken: Redacted.make(derived.token),\n\t\t\t\t\t...(derived.headers !== undefined ? { headers: derived.headers } : {}),\n\t\t\t\t\t...(derived.baseUrl !== undefined ? { baseUrl: derived.baseUrl } : {}),\n\t\t\t\t\t...(fields !== undefined ? { fields } : {}),\n\t\t\t\t\tsourceLabel: `OAuth (${row.ownership})`,\n\t\t\t\t\t...(activeSecret.expiresAt !== undefined ? { expiresAt: activeSecret.expiresAt } : {}),\n\t\t\t\t};\n\t\t\t});\n\n\t\t\tconst resolveEnvFallback = (\n\t\t\t\tspec: ConnectorSpec,\n\t\t\t\ttargetHost: string | undefined,\n\t\t\t): Effect.Effect<Connector.ResolvedCredential | undefined, ConnectorError> =>\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst envSpec = spec.auth.env;\n\t\t\t\t\tif (envSpec === undefined) return undefined;\n\t\t\t\t\tconst found = readEnvVar(getEnv(), envSpec.vars);\n\t\t\t\t\tif (found === undefined) return undefined;\n\t\t\t\t\tconst id = `env:${spec.id}`;\n\t\t\t\t\tconst uid = formatUid(spec.id, \"env\");\n\t\t\t\t\tyield* validateHost(id, uid, spec.allowedHosts, targetHost);\n\t\t\t\t\tconst headers = applyHeaderInjection(envSpec.inject, found.value);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tconnectionId: id,\n\t\t\t\t\t\tuid,\n\t\t\t\t\t\ttoken: Redacted.make(found.value),\n\t\t\t\t\t\t...(headers !== undefined ? { headers } : {}),\n\t\t\t\t\t\t...(spec.capabilities.provider?.baseUrl !== undefined\n\t\t\t\t\t\t\t? { baseUrl: spec.capabilities.provider.baseUrl }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tsourceLabel: `$${found.name}`,\n\t\t\t\t\t};\n\t\t\t\t});\n\n\t\t\tconst service: ServiceInterface = {\n\t\t\t\tcatalog: (filter = {}) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst cat = yield* currentCatalog(filter.refresh);\n\t\t\t\t\t\tconst catalogFilter: CatalogFilter = {\n\t\t\t\t\t\t\tkind: filter.kind,\n\t\t\t\t\t\t\tcategory: filter.category,\n\t\t\t\t\t\t\tquery: filter.query,\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tschemaVersion: cat.schemaVersion,\n\t\t\t\t\t\t\tgeneratedAt: cat.generatedAt,\n\t\t\t\t\t\t\tcategories: cat.categories,\n\t\t\t\t\t\t\tconnectors: filterConnectors(cat, catalogFilter),\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\n\t\t\t\tlist: (filter = {}) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst now = yield* Clock.currentTimeMillis;\n\t\t\t\t\t\tconst rows = db.listConnections(actor.scope, {\n\t\t\t\t\t\t\tkind: filter.kind,\n\t\t\t\t\t\t\tconnectorId: filter.connectorId,\n\t\t\t\t\t\t\tenabled: filter.enabled,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst summaries: Array<ConnectionSummary> = rows.map((row) => {\n\t\t\t\t\t\t\tconst subject = subjectFor(row, actor);\n\t\t\t\t\t\t\treturn summarizeStored(row, db.getCredential(row.id, subject.type, subject.id), now);\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (filter.includeEnv !== false && filter.enabled !== false) {\n\t\t\t\t\t\t\tconst env = getEnv();\n\t\t\t\t\t\t\tfor (const spec of Object.values(cachedCatalog.connectors)) {\n\t\t\t\t\t\t\t\tif (filter.kind !== undefined && !spec.kinds.includes(filter.kind)) continue;\n\t\t\t\t\t\t\t\tif (filter.connectorId !== undefined && spec.id !== filter.connectorId) continue;\n\t\t\t\t\t\t\t\tif (spec.auth.env === undefined) continue;\n\t\t\t\t\t\t\t\tconst found = readEnvVar(env, spec.auth.env.vars);\n\t\t\t\t\t\t\t\tif (found !== undefined) {\n\t\t\t\t\t\t\t\t\tsummaries.push(summarizeEnv(spec, actor.scope, found.name));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn summaries;\n\t\t\t\t\t}),\n\n\t\t\t\tget: (ref) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst now = yield* Clock.currentTimeMillis;\n\t\t\t\t\t\tconst row = db.findConnection(actor.scope, ref);\n\t\t\t\t\t\tif (row !== undefined) {\n\t\t\t\t\t\t\tconst subject = subjectFor(row, actor);\n\t\t\t\t\t\t\treturn summarizeStored(row, db.getCredential(row.id, subject.type, subject.id), now);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Check ambient env projection (`env:<id>` or `<id>/env`)\n\t\t\t\t\t\tfor (const spec of Object.values(cachedCatalog.connectors)) {\n\t\t\t\t\t\t\tif (spec.auth.env === undefined) continue;\n\t\t\t\t\t\t\tif (ref === `env:${spec.id}` || ref === formatUid(spec.id, \"env\")) {\n\t\t\t\t\t\t\t\tconst found = readEnvVar(getEnv(), spec.auth.env.vars);\n\t\t\t\t\t\t\t\tif (found !== undefined) return summarizeEnv(spec, actor.scope, found.name);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn yield* new ConnectionNotFoundError({\n\t\t\t\t\t\t\tref,\n\t\t\t\t\t\t\tmessage: `Connection \"${ref}\" not found`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}),\n\n\t\t\t\tcreate: (input) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst spec = findConnector(cachedCatalog, input.connector);\n\t\t\t\t\t\tif (spec === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectorNotFoundError({\n\t\t\t\t\t\t\t\tconnectorId: input.connector,\n\t\t\t\t\t\t\t\tmessage: `Unknown connector \"${input.connector}\"`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst slug = (input.slug ?? \"default\").trim().toLowerCase();\n\t\t\t\t\t\tif (!CONNECTION_SLUG_PATTERN.test(slug)) {\n\t\t\t\t\t\t\treturn yield* new ConnectorValidationError({\n\t\t\t\t\t\t\t\tmessage: `Invalid connection name \"${slug}\". Use lowercase letters, numbers, and hyphens.`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst uid = formatUid(spec.id, slug);\n\t\t\t\t\t\tif (db.findConnection(actor.scope, uid) !== undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectionConflictError({\n\t\t\t\t\t\t\t\tuid,\n\t\t\t\t\t\t\t\tmessage: `Connection \"${uid}\" already exists in this workspace`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst chosenAuth: StoredAuthType | undefined =\n\t\t\t\t\t\t\tinput.authType ??\n\t\t\t\t\t\t\t(spec.auth.oauth !== undefined ? \"oauth\" : spec.auth.apikey !== undefined ? \"apikey\" : undefined);\n\t\t\t\t\t\tif (chosenAuth === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectorValidationError({\n\t\t\t\t\t\t\t\tmessage: `Connector \"${spec.id}\" has no storable auth method`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (chosenAuth === \"oauth\" && spec.auth.oauth === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectorValidationError({\n\t\t\t\t\t\t\t\tmessage: `Connector \"${spec.id}\" does not support OAuth`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (chosenAuth === \"apikey\" && spec.auth.apikey === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectorValidationError({\n\t\t\t\t\t\t\t\tmessage: `Connector \"${spec.id}\" does not support API key authentication`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst ownership: Ownership =\n\t\t\t\t\t\t\tinput.ownership ??\n\t\t\t\t\t\t\t(chosenAuth === \"oauth\"\n\t\t\t\t\t\t\t\t? (spec.auth.oauth?.defaultOwnership ?? \"personal\")\n\t\t\t\t\t\t\t\t: (spec.auth.apikey?.defaultOwnership ?? \"shared\"));\n\n\t\t\t\t\t\tconst existingSame = db.listConnections(actor.scope, { connectorId: spec.id });\n\t\t\t\t\t\tconst isDefault = input.isDefault ?? existingSame.length === 0;\n\n\t\t\t\t\t\tconst now = yield* Clock.currentTimeMillis;\n\t\t\t\t\t\tconst row = db.insertConnection({\n\t\t\t\t\t\t\tid: ConnectionID.create(),\n\t\t\t\t\t\t\tworkspaceId: actor.scope,\n\t\t\t\t\t\t\tuid,\n\t\t\t\t\t\t\tlabel: input.label ?? spec.name,\n\t\t\t\t\t\t\tsource: \"catalog\",\n\t\t\t\t\t\t\tconnectorId: spec.id,\n\t\t\t\t\t\t\tkinds: spec.kinds,\n\t\t\t\t\t\t\tauthType: chosenAuth,\n\t\t\t\t\t\t\townership,\n\t\t\t\t\t\t\tenabled: input.enabled ?? true,\n\t\t\t\t\t\t\tisDefault,\n\t\t\t\t\t\t\tallowedHosts: spec.allowedHosts,\n\t\t\t\t\t\t\tconfig: input.config ?? {},\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn summarizeStored(row, undefined, now);\n\t\t\t\t\t}),\n\n\t\t\t\tupdate: (input) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst row = db.findConnection(actor.scope, input.ref);\n\t\t\t\t\t\tif (row === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectionNotFoundError({\n\t\t\t\t\t\t\t\tref: input.ref,\n\t\t\t\t\t\t\t\tmessage: `Connection \"${input.ref}\" not found`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (input.uid !== undefined && input.uid !== row.uid) {\n\t\t\t\t\t\t\tif (!CONNECTION_UID_PATTERN.test(input.uid)) {\n\t\t\t\t\t\t\t\treturn yield* new ConnectorValidationError({\n\t\t\t\t\t\t\t\t\tmessage: `Invalid connection uid \"${input.uid}\"`,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (db.findConnection(actor.scope, input.uid) !== undefined) {\n\t\t\t\t\t\t\t\treturn yield* new ConnectionConflictError({\n\t\t\t\t\t\t\t\t\tuid: input.uid,\n\t\t\t\t\t\t\t\t\tmessage: `Connection \"${input.uid}\" already exists in this workspace`,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst now = yield* Clock.currentTimeMillis;\n\t\t\t\t\t\tconst updated = db.updateConnection(row.id, {\n\t\t\t\t\t\t\tuid: input.uid,\n\t\t\t\t\t\t\tlabel: input.label,\n\t\t\t\t\t\t\townership: input.ownership,\n\t\t\t\t\t\t\tenabled: input.enabled,\n\t\t\t\t\t\t\tisDefault: input.isDefault,\n\t\t\t\t\t\t\tconfig: input.config,\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (updated === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectionNotFoundError({\n\t\t\t\t\t\t\t\tref: input.ref,\n\t\t\t\t\t\t\t\tmessage: `Connection \"${input.ref}\" not found`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst subject = subjectFor(updated, actor);\n\t\t\t\t\t\treturn summarizeStored(updated, db.getCredential(updated.id, subject.type, subject.id), now);\n\t\t\t\t\t}),\n\n\t\t\t\tremove: (ref) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst row = db.findConnection(actor.scope, ref);\n\t\t\t\t\t\tif (row === undefined) return false;\n\t\t\t\t\t\treturn db.deleteConnection(row.id);\n\t\t\t\t\t}),\n\n\t\t\t\tsetApiKey: (ref, apiKey) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst trimmed = apiKey.trim();\n\t\t\t\t\t\tif (trimmed.length === 0) {\n\t\t\t\t\t\t\treturn yield* new ConnectorValidationError({ message: \"API key cannot be empty\" });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst row = db.findConnection(actor.scope, ref);\n\t\t\t\t\t\tif (row === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectionNotFoundError({\n\t\t\t\t\t\t\t\tref,\n\t\t\t\t\t\t\t\tmessage: `Connection \"${ref}\" not found`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (row.authType !== \"apikey\") {\n\t\t\t\t\t\t\treturn yield* new ConnectorValidationError({\n\t\t\t\t\t\t\t\tmessage: `Connection \"${row.uid}\" uses ${row.authType}, not apikey`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst now = yield* Clock.currentTimeMillis;\n\t\t\t\t\t\tconst subject = subjectFor(row, actor);\n\t\t\t\t\t\tconst cred = db.upsertCredential({\n\t\t\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\t\t\tsubjectType: subject.type,\n\t\t\t\t\t\t\tsubjectId: subject.id,\n\t\t\t\t\t\t\tsecret: { type: \"apikey\", apiKey: trimmed },\n\t\t\t\t\t\t\tstatus: \"active\",\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn summarizeStored(row, cred, now);\n\t\t\t\t\t}),\n\n\t\t\t\tdisconnect: (ref) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst now = yield* Clock.currentTimeMillis;\n\t\t\t\t\t\tconst row = db.findConnection(actor.scope, ref);\n\t\t\t\t\t\tif (row === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectionNotFoundError({\n\t\t\t\t\t\t\t\tref,\n\t\t\t\t\t\t\t\tmessage: `Connection \"${ref}\" not found`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst subject = subjectFor(row, actor);\n\t\t\t\t\t\tdb.deleteCredential(row.id, subject.type, subject.id);\n\t\t\t\t\t\treturn summarizeStored(row, undefined, now);\n\t\t\t\t\t}),\n\n\t\t\t\toauthStart: (input) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst row = db.findConnection(actor.scope, input.ref);\n\t\t\t\t\t\tif (row === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectionNotFoundError({\n\t\t\t\t\t\t\t\tref: input.ref,\n\t\t\t\t\t\t\t\tmessage: `Connection \"${input.ref}\" not found`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (row.authType !== \"oauth\") {\n\t\t\t\t\t\t\treturn yield* new ConnectorValidationError({\n\t\t\t\t\t\t\t\tmessage: `Connection \"${row.uid}\" uses ${row.authType}, not oauth`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst spec = specForRow(row);\n\t\t\t\t\t\tif (spec === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectorNotFoundError({\n\t\t\t\t\t\t\t\tconnectorId: row.connectorId,\n\t\t\t\t\t\t\t\tmessage: `Connector \"${row.connectorId}\" is not in the catalog`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn yield* startAuthCodeFlow({\n\t\t\t\t\t\t\tstore: pendingOAuth,\n\t\t\t\t\t\t\tconnector: spec,\n\t\t\t\t\t\t\tconnection: row,\n\t\t\t\t\t\t\tredirectUrl: input.redirectUrl,\n\t\t\t\t\t\t\tscopes: input.scopes,\n\t\t\t\t\t\t\tworkspaceId: actor.scope,\n\t\t\t\t\t\t\tactorId: actor.id,\n\t\t\t\t\t\t\tfetch: options.fetch,\n\t\t\t\t\t\t});\n\t\t\t\t\t}),\n\n\t\t\t\toauthFinish: (input) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst { connectionId, secret } = yield* finishAuthCodeFlow({\n\t\t\t\t\t\t\tstore: pendingOAuth,\n\t\t\t\t\t\t\tstate: input.state,\n\t\t\t\t\t\t\tcodeOrUrl: input.code,\n\t\t\t\t\t\t\tworkspaceId: actor.scope,\n\t\t\t\t\t\t\tactorId: actor.id,\n\t\t\t\t\t\t\tfetch: options.fetch,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst row = db.findConnectionById(connectionId);\n\t\t\t\t\t\tif (row === undefined || row.workspaceId !== actor.scope) {\n\t\t\t\t\t\t\treturn yield* new ConnectionNotFoundError({\n\t\t\t\t\t\t\t\tref: connectionId,\n\t\t\t\t\t\t\t\tmessage: `Connection \"${connectionId}\" no longer exists`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst now = yield* Clock.currentTimeMillis;\n\t\t\t\t\t\tconst subject = subjectFor(row, actor);\n\t\t\t\t\t\tconst cred = db.upsertCredential({\n\t\t\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\t\t\tsubjectType: subject.type,\n\t\t\t\t\t\t\tsubjectId: subject.id,\n\t\t\t\t\t\t\tsecret,\n\t\t\t\t\t\t\tstatus: \"active\",\n\t\t\t\t\t\t\t...(secret.expiresAt !== undefined ? { expiresAt: secret.expiresAt } : {}),\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn summarizeStored(row, cred, now);\n\t\t\t\t\t}),\n\n\t\t\t\tdeviceStart: (input) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst row = db.findConnection(actor.scope, input.ref);\n\t\t\t\t\t\tif (row === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectionNotFoundError({\n\t\t\t\t\t\t\t\tref: input.ref,\n\t\t\t\t\t\t\t\tmessage: `Connection \"${input.ref}\" not found`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (row.authType !== \"oauth\") {\n\t\t\t\t\t\t\treturn yield* new ConnectorValidationError({\n\t\t\t\t\t\t\t\tmessage: `Connection \"${row.uid}\" uses ${row.authType}, not oauth`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst spec = specForRow(row);\n\t\t\t\t\t\tif (spec === undefined) {\n\t\t\t\t\t\t\treturn yield* new ConnectorNotFoundError({\n\t\t\t\t\t\t\t\tconnectorId: row.connectorId,\n\t\t\t\t\t\t\t\tmessage: `Connector \"${row.connectorId}\" is not in the catalog`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (input.enterpriseUrl !== undefined) {\n\t\t\t\t\t\t\tconst now = yield* Clock.currentTimeMillis;\n\t\t\t\t\t\t\tdb.updateConnection(row.id, {\n\t\t\t\t\t\t\t\tconfig: {\n\t\t\t\t\t\t\t\t\t...row.config,\n\t\t\t\t\t\t\t\t\tfields: { ...row.config.fields, enterpriseUrl: input.enterpriseUrl },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn yield* startDeviceCodeFlow({\n\t\t\t\t\t\t\tstore: pendingOAuth,\n\t\t\t\t\t\t\tconnector: spec,\n\t\t\t\t\t\t\tconnection: row,\n\t\t\t\t\t\t\tenterpriseUrl: input.enterpriseUrl,\n\t\t\t\t\t\t\tworkspaceId: actor.scope,\n\t\t\t\t\t\t\tactorId: actor.id,\n\t\t\t\t\t\t\tfetch: options.fetch,\n\t\t\t\t\t\t});\n\t\t\t\t\t}),\n\n\t\t\t\tdevicePoll: (state) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst step = yield* pollDeviceCodeStep({\n\t\t\t\t\t\t\tstore: pendingOAuth,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\tworkspaceId: actor.scope,\n\t\t\t\t\t\t\tactorId: actor.id,\n\t\t\t\t\t\t\tfetch: options.fetch,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (step.status === \"pending\") {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tstatus: \"pending\" as const,\n\t\t\t\t\t\t\t\t...(step.intervalSeconds !== undefined ? { intervalSeconds: step.intervalSeconds } : {}),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst row = db.findConnectionById(step.connectionId);\n\t\t\t\t\t\tif (row === undefined || row.workspaceId !== actor.scope) {\n\t\t\t\t\t\t\treturn yield* new ConnectionNotFoundError({\n\t\t\t\t\t\t\t\tref: step.connectionId,\n\t\t\t\t\t\t\t\tmessage: `Connection \"${step.connectionId}\" no longer exists`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst now = yield* Clock.currentTimeMillis;\n\t\t\t\t\t\tconst subject = subjectFor(row, actor);\n\t\t\t\t\t\tconst cred = db.upsertCredential({\n\t\t\t\t\t\t\tconnectionId: row.id,\n\t\t\t\t\t\t\tsubjectType: subject.type,\n\t\t\t\t\t\t\tsubjectId: subject.id,\n\t\t\t\t\t\t\tsecret: step.secret,\n\t\t\t\t\t\t\tstatus: \"active\",\n\t\t\t\t\t\t\t...(step.secret.expiresAt !== undefined ? { expiresAt: step.secret.expiresAt } : {}),\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tstatus: \"complete\" as const,\n\t\t\t\t\t\t\tconnection: summarizeStored(row, cred, now),\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\n\t\t\t\tresolve: (input) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst row = db.findConnection(actor.scope, input.ref);\n\t\t\t\t\t\tif (row !== undefined) {\n\t\t\t\t\t\t\treturn yield* resolveRowSecret(row, actor, {\n\t\t\t\t\t\t\t\ttargetHost: input.targetHost,\n\t\t\t\t\t\t\t\tminValidityMs: input.minValidityMs,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Support resolving an ambient env projection (`env:<id>` or `<id>/env`).\n\t\t\t\t\t\tfor (const spec of Object.values(cachedCatalog.connectors)) {\n\t\t\t\t\t\t\tif (input.ref === `env:${spec.id}` || input.ref === formatUid(spec.id, \"env\")) {\n\t\t\t\t\t\t\t\tconst resolved = yield* resolveEnvFallback(spec, input.targetHost);\n\t\t\t\t\t\t\t\tif (resolved !== undefined) return resolved;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn yield* new ConnectionNotFoundError({\n\t\t\t\t\t\t\tref: input.ref,\n\t\t\t\t\t\t\tmessage: `Connection \"${input.ref}\" not found`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}),\n\n\t\t\t\tresolveProvider: (providerId) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst spec = findConnectorByProviderId(cachedCatalog, providerId);\n\t\t\t\t\t\tif (spec === undefined) return undefined;\n\n\t\t\t\t\t\t// Stored-first precedence: an explicit stored Connection owns the provider;\n\t\t\t\t\t\t// ambient env is consulted only when no explicit enabled Connection exists.\n\t\t\t\t\t\tconst rows = db.listConnections(actor.scope, { connectorId: spec.id, enabled: true });\n\t\t\t\t\t\tconst chosen = rows.find((r) => r.isDefault) ?? rows[0];\n\t\t\t\t\t\tif (chosen !== undefined) {\n\t\t\t\t\t\t\treturn yield* resolveRowSecret(chosen, actor, {});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn yield* resolveEnvFallback(spec, undefined);\n\t\t\t\t\t}),\n\n\t\t\t\tlistMcpConnections: () =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst rows = db.listConnections(actor.scope, { kind: \"mcp\", enabled: true });\n\t\t\t\t\t\tconst active: Array<Connector.ActiveMcpConnection> = [];\n\t\t\t\t\t\tconst seenConnectors = new Set<string>();\n\n\t\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\t\tconst spec = specForRow(row);\n\t\t\t\t\t\t\tconst mcp = spec?.capabilities.mcp;\n\t\t\t\t\t\t\tif (spec === undefined || mcp === undefined) continue;\n\t\t\t\t\t\t\tseenConnectors.add(row.connectorId);\n\t\t\t\t\t\t\tactive.push({\n\t\t\t\t\t\t\t\tid: row.id,\n\t\t\t\t\t\t\t\tuid: row.uid,\n\t\t\t\t\t\t\t\tconnectorId: row.connectorId,\n\t\t\t\t\t\t\t\tname: row.label ?? spec.name,\n\t\t\t\t\t\t\t\turl: mcp.url,\n\t\t\t\t\t\t\t\ttransport: mcp.transport ?? \"http\",\n\t\t\t\t\t\t\t\texposure: row.config.mcp?.exposure ?? mcp.defaultExposure ?? \"eager\",\n\t\t\t\t\t\t\t\tauthType: row.authType,\n\t\t\t\t\t\t\t\t...(row.authType === \"apikey\" && spec.auth.apikey?.inject !== undefined\n\t\t\t\t\t\t\t\t\t? { inject: spec.auth.apikey.inject }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\tallowedHosts: row.allowedHosts,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Also surface ambient env MCP connections if no explicit connection exists for that connector.\n\t\t\t\t\t\tconst env = getEnv();\n\t\t\t\t\t\tfor (const spec of Object.values(cachedCatalog.connectors)) {\n\t\t\t\t\t\t\tif (seenConnectors.has(spec.id)) continue;\n\t\t\t\t\t\t\tconst mcp = spec.capabilities.mcp;\n\t\t\t\t\t\t\tif (mcp === undefined || spec.auth.env === undefined) continue;\n\t\t\t\t\t\t\tconst found = readEnvVar(env, spec.auth.env.vars);\n\t\t\t\t\t\t\tif (found === undefined) continue;\n\t\t\t\t\t\t\tactive.push({\n\t\t\t\t\t\t\t\tid: `env:${spec.id}`,\n\t\t\t\t\t\t\t\tuid: formatUid(spec.id, \"env\"),\n\t\t\t\t\t\t\t\tconnectorId: spec.id,\n\t\t\t\t\t\t\t\tname: spec.name,\n\t\t\t\t\t\t\t\turl: mcp.url,\n\t\t\t\t\t\t\t\ttransport: mcp.transport ?? \"http\",\n\t\t\t\t\t\t\t\texposure: mcp.defaultExposure ?? \"eager\",\n\t\t\t\t\t\t\t\tauthType: \"env\",\n\t\t\t\t\t\t\t\t...(spec.auth.env.inject !== undefined ? { inject: spec.auth.env.inject } : {}),\n\t\t\t\t\t\t\t\tallowedHosts: spec.allowedHosts,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn active;\n\t\t\t\t\t}),\n\n\t\t\t\tlistProviderStates: () =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst actor = yield* Actor.Current;\n\t\t\t\t\t\tconst now = yield* Clock.currentTimeMillis;\n\t\t\t\t\t\tconst states: Array<Connector.ProviderConnectionState> = [];\n\t\t\t\t\t\tconst env = getEnv();\n\t\t\t\t\t\tfor (const spec of Object.values(cachedCatalog.connectors)) {\n\t\t\t\t\t\t\tconst providerId = spec.capabilities.provider?.providerId;\n\t\t\t\t\t\t\tif (providerId === undefined) continue;\n\t\t\t\t\t\t\tconst rows = db.listConnections(actor.scope, { connectorId: spec.id, enabled: true });\n\t\t\t\t\t\t\tconst chosen = rows.find((r) => r.isDefault) ?? rows[0];\n\t\t\t\t\t\t\tif (chosen !== undefined) {\n\t\t\t\t\t\t\t\tconst subject = subjectFor(chosen, actor);\n\t\t\t\t\t\t\t\tconst cred = db.getCredential(chosen.id, subject.type, subject.id);\n\t\t\t\t\t\t\t\tconst summary = summarizeStored(chosen, cred, now);\n\t\t\t\t\t\t\t\tconst oauthSecret = cred?.secret.type === \"oauth\" ? cred.secret : undefined;\n\t\t\t\t\t\t\t\tstates.push({\n\t\t\t\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\t\t\t\tconnectorId: spec.id,\n\t\t\t\t\t\t\t\t\tuid: chosen.uid,\n\t\t\t\t\t\t\t\t\tauthType: chosen.authType,\n\t\t\t\t\t\t\t\t\tstatus: summary.status,\n\t\t\t\t\t\t\t\t\tsourceLabel: summary.sourceLabel,\n\t\t\t\t\t\t\t\t\t...(oauthSecret?.apiEndpoint !== undefined ? { apiEndpoint: oauthSecret.apiEndpoint } : {}),\n\t\t\t\t\t\t\t\t\t...(oauthSecret?.availableModelIds !== undefined\n\t\t\t\t\t\t\t\t\t\t? { availableModelIds: oauthSecret.availableModelIds }\n\t\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (spec.auth.env !== undefined) {\n\t\t\t\t\t\t\t\tconst found = readEnvVar(env, spec.auth.env.vars);\n\t\t\t\t\t\t\t\tif (found !== undefined) {\n\t\t\t\t\t\t\t\t\tstates.push({\n\t\t\t\t\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\t\t\t\t\tconnectorId: spec.id,\n\t\t\t\t\t\t\t\t\t\tuid: formatUid(spec.id, \"env\"),\n\t\t\t\t\t\t\t\t\t\tauthType: \"env\",\n\t\t\t\t\t\t\t\t\t\tstatus: \"active\",\n\t\t\t\t\t\t\t\t\t\tsourceLabel: `$${found.name}`,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn states;\n\t\t\t\t\t}),\n\t\t\t};\n\n\t\t\treturn { db, service };\n\t\t}),\n\t\t({ db }) => Effect.sync(() => db.close()),\n\t).pipe(Effect.map(({ service }) => service));\n\n/**\n * Provides both the full host `Connector.Service` and the narrowed `@codeworksh/plugin/connector` `Broker`\n * backed by the exact same `<home>/connections.db` instance.\n */\nexport const layer = (options: LayerOptions = {}) =>\n\tLayer.effectContext(\n\t\tmake(options).pipe(\n\t\t\tEffect.map((service) =>\n\t\t\t\tContext.empty().pipe(Context.add(Service, service), Context.add(Connector.Broker, service)),\n\t\t\t),\n\t\t),\n\t);\n"],"mappings":";;;;;;;;;;;AAiBA,MAAM,gBAAgB,OAAO,kBAAkB,gBAAgB;AAQ/D,MAAM,cAAc,aACnB,YAAY,QAAQ,IAAI,sCAAsC;AAE/D,MAAM,aAAa,SAAyB,KAAK,MAAM,SAAS,iBAAiB;AACjF,MAAM,YAAY,SAAyB,KAAK,MAAM,SAAS,iBAAiB;AAEhF,MAAM,qBAAqB,SAA+C;CACzE,MAAM,OAAO,UAAU,IAAI;CAC3B,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO,KAAA;CAC9B,IAAI;EACH,OAAO,cAAc,KAAK,MAAM,aAAa,MAAM,OAAO,CAAC,CAAC;CAC7D,QAAQ;EACP;CACD;AACD;AAEA,MAAM,kBAAkB,SAAqC;CAC5D,MAAM,OAAO,SAAS,IAAI;CAC1B,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO,KAAA;CAC9B,IAAI;EACH,MAAM,MAAM,aAAa,MAAM,OAAO,CAAC,CAAC,KAAK;EAC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,CAAC;OACzF,GAAI,aAAa,sBAAsB,KAAA,IACpC,EAAE,mBAAmB,YAAY,kBAAkB,IACnD,CAAC;MACL,CAAC;MACD;KACD;KACA,IAAI,KAAK,KAAK,QAAQ,KAAA,GAAW;MAChC,MAAM,QAAQ,WAAW,KAAK,KAAK,KAAK,IAAI,IAAI;MAChD,IAAI,UAAU,KAAA,GACb,OAAO,KAAK;OACX;OACA,aAAa,KAAK;OAClB,KAAK,UAAU,KAAK,IAAI,KAAK;OAC7B,UAAU;OACV,QAAQ;OACR,aAAa,IAAI,MAAM;MACxB,CAAC;KAEH;IACD;IACA,OAAO;GACR,CAAC;EAGgB;CAAE;AACtB,CAAC,IACA,EAAE,SAAS,OAAO,WAAW,GAAG,MAAM,CAAC,CACzC,CAAC,CAAC,KAAK,OAAO,KAAK,EAAE,cAAc,OAAO,CAAC;;;;;AAM5C,MAAa,SAAS,UAAwB,CAAC,MAC9C,MAAM,cACL,KAAK,OAAO,CAAC,CAAC,KACb,OAAO,KAAK,YACX,QAAQ,MAAM,CAAC,CAAC,KAAK,QAAQ,IAAI,SAAS,OAAO,GAAG,QAAQ,IAAI,UAAU,QAAQ,OAAO,CAAC,CAC3F,CACD,CACD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { h as layer } from "./error-BsI8iNna.mjs";
|
|
2
|
-
import { i as Cmd } from "./runtime-
|
|
2
|
+
import { i as Cmd } from "./runtime-CyXV7HH_.mjs";
|
|
3
3
|
import { i as read, n as file } from "./registration-C6yiv31r.mjs";
|
|
4
4
|
import { Effect, Option, Schema } from "effect";
|
|
5
5
|
import { FetchHttpClient, HttpClient } from "effect/http";
|
|
@@ -77,4 +77,4 @@ const connect = (url) => (program) => Effect.gen(function* () {
|
|
|
77
77
|
//#endregion
|
|
78
78
|
export { home as n, options as r, connect as t };
|
|
79
79
|
|
|
80
|
-
//# sourceMappingURL=service-
|
|
80
|
+
//# sourceMappingURL=service-YVNwFMNf.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-
|
|
1
|
+
{"version":3,"file":"service-YVNwFMNf.mjs","names":["Registration.read","Registration.file","Client.layer"],"sources":["../../src/cli/service.ts"],"sourcesContent":["import { Global } from \"@codeworksh/harness/effect\";\nimport { Door } from \"@codeworksh/schema/door\";\nimport { Effect, Option, Schema } from \"effect\";\nimport { FetchHttpClient, HttpClient } from \"effect/http\";\nimport { RpcClientError } from \"effect/rpc\";\nimport * as Client from \"../server/client.ts\";\nimport type * as Discovery from \"../server/discovery.ts\";\nimport * as Registration from \"../server/registration.ts\";\nimport { Cmd } from \"./cmd/cmd.ts\";\n\ninterface Shared {\n\treadonly userConfigDir: Option.Option<string>;\n\treadonly home: Option.Option<string>;\n\treadonly database: Option.Option<string>;\n}\n\n/** The CodeWork home the shared flags name, resolved the way the harness resolves it. */\nexport const home = (shared: Shared) => Global.resolve(Option.isSome(shared.home) ? { home: shared.home.value } : {});\n\n/**\n * How `service` finds or starts the background server: the home whose\n * `service.json` names it, and the server-owned flags it is started with, in the\n * order `serve` parses them.\n */\nexport const options = (shared: Shared, server: { readonly host: string; readonly port: number }) =>\n\thome(shared).pipe(\n\t\tEffect.map((paths): Discovery.Options => ({\n\t\t\thome: paths.home,\n\t\t\tlog: paths.log,\n\t\t\t...server,\n\t\t\targs: [\n\t\t\t\t...(Option.isSome(shared.home) ? [\"--home\", shared.home.value] : []),\n\t\t\t\t...(Option.isSome(shared.database) ? [\"--database\", shared.database.value] : []),\n\t\t\t\t...(Option.isSome(shared.userConfigDir) ? [\"--user-config-dir\", shared.userConfigDir.value] : []),\n\t\t\t],\n\t\t})),\n\t);\n\nclass ConnectError extends Schema.TaggedError<ConnectError>()(\"CLI.ConnectError\", {\n\tmessage: Schema.String,\n}) {}\n\nconst isClientError = Schema.is(RpcClientError.RpcClientError);\n\n/** Names for this computer; a server bound to every address answers to all of them. */\nconst loopback = new Set([\"127.0.0.1\", \"localhost\", \"[::1]\", \"0.0.0.0\", \"[::]\"]);\n\n/** Two URLs of one server: equal, or the same port and path under two of this computer's names. */\nconst same = (a: string, b: string) => {\n\tif (a === b) return true;\n\tconst [x, y] = [URL.parse(a), URL.parse(b)];\n\treturn (\n\t\tx !== null &&\n\t\ty !== null &&\n\t\tloopback.has(x.hostname) &&\n\t\tloopback.has(y.hostname) &&\n\t\tx.port === y.port &&\n\t\tx.pathname === y.pathname\n\t);\n};\n\n/**\n * The server the home's `service.json` names, and that only: the token goes nowhere else, as any\n * other server, however local it looks, may belong to someone else. A `url` must name it; a loopback\n * alias of that URL is the server as filed.\n */\nconst target = Effect.fn(\"CLI.target\")(function* (url: string | undefined) {\n\tconst paths = yield* home(yield* Cmd.spec);\n\tconst registered = yield* Registration.read(Registration.file(paths.home));\n\tif (registered === undefined)\n\t\treturn yield* new ConnectError({\n\t\t\tmessage: [\"no CodeWork server is running for this home\", \"hint: start one with `codework service start`\"].join(\n\t\t\t\t\"\\n\",\n\t\t\t),\n\t\t});\n\tif (url !== undefined && !same(registered.url, url))\n\t\treturn yield* new ConnectError({\n\t\t\tmessage: [\n\t\t\t\t`${url} is not this home's server`,\n\t\t\t\t`hint: this home's server is ${registered.url}; pass --home for another home's server`,\n\t\t\t].join(\"\\n\"),\n\t\t});\n\treturn { url: registered.url, token: registered.token };\n});\n\n/**\n * Why a socket to `server` did not open. The WebSocket hides the HTTP status, so the same request\n * is made again as a plain GET, with the token offered the same way, and the door's status read.\n */\nconst refused = Effect.fn(\"CLI.refused\")(function* (url: string, server: Client.Target) {\n\tconst status = yield* HttpClient.get(server.url.replace(/^ws/, \"http\"), {\n\t\theaders: { \"sec-websocket-protocol\": Door.protocols(server.token).join(\", \") },\n\t}).pipe(\n\t\tEffect.map((response) => response.status),\n\t\tEffect.timeout(\"2 seconds\"),\n\t\tEffect.provide(FetchHttpClient.layer),\n\t\tEffect.orElseSucceed(() => undefined),\n\t);\n\tswitch (status) {\n\t\tcase 401:\n\t\t\treturn yield* new ConnectError({\n\t\t\t\tmessage: [\n\t\t\t\t\t`the CodeWork server at ${url} refused this home's token`,\n\t\t\t\t\t\"hint: restart it with `codework service restart`, or check --home names its home\",\n\t\t\t\t].join(\"\\n\"),\n\t\t\t});\n\t\tcase 403:\n\t\t\treturn yield* new ConnectError({\n\t\t\t\tmessage: `the CodeWork server at ${url} refused the request's origin`,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn yield* new ConnectError({\n\t\t\t\tmessage: [\n\t\t\t\t\t`could not connect to the CodeWork server at ${url}`,\n\t\t\t\t\t\"hint: check it is running with `codework service status`\",\n\t\t\t\t].join(\"\\n\"),\n\t\t\t});\n\t}\n});\n\n/**\n * Runs `program` against the server at `url`, or the home's when none is named, naming why when its\n * socket does not open.\n */\nexport const connect =\n\t(url?: string) =>\n\t<A, E, R>(program: Effect.Effect<A, E, R>) =>\n\t\tEffect.gen(function* () {\n\t\t\tconst server = yield* target(url);\n\t\t\treturn yield* program.pipe(\n\t\t\t\t// Scoped inside the client, so the program's own finalizers still reach the server.\n\t\t\t\tEffect.scoped,\n\t\t\t\tEffect.provide(Client.layer(server)),\n\t\t\t\tEffect.catchIf(\n\t\t\t\t\t(error) => isClientError(error) && error.reason._tag === \"SocketOpenError\",\n\t\t\t\t\t() => refused(url ?? server.url, server),\n\t\t\t\t),\n\t\t\t);\n\t\t});\n"],"mappings":";;;;;;;;;;AAiBA,MAAa,QAAQ,WAAmB,OAAO,QAAQ,OAAO,OAAO,OAAO,IAAI,IAAI,EAAE,MAAM,OAAO,KAAK,MAAM,IAAI,CAAC,CAAC;;;;;;AAOpH,MAAa,WAAW,QAAgB,WACvC,KAAK,MAAM,CAAC,CAAC,KACZ,OAAO,KAAK,WAA8B;CACzC,MAAM,MAAM;CACZ,KAAK,MAAM;CACX,GAAG;CACH,MAAM;EACL,GAAI,OAAO,OAAO,OAAO,IAAI,IAAI,CAAC,UAAU,OAAO,KAAK,KAAK,IAAI,CAAC;EAClE,GAAI,OAAO,OAAO,OAAO,QAAQ,IAAI,CAAC,cAAc,OAAO,S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OAAO,GAAG,aAAa,CAAC,CAAC,WAAW,KAAa,QAAuB;CASvF,QAAQ,OARc,WAAW,IAAI,OAAO,IAAI,QAAQ,OAAO,MAAM,GAAG,EACvE,SAAS,EAAE,0BAA0B,KAAK,UAAU,OAAO,KAAK,CAAC,CAAC,KAAK,IAAI,EAAE,EAC9E,CAAC,CAAC,CAAC,KACF,OAAO,KAAK,aAAa,SAAS,MAAM,GACxC,OAAO,QAAQ,WAAW,GAC1B,OAAO,QAAQ,gBAAgB,KAAK,GACpC,OAAO,oBAAoB,KAAA,CAAS,CACrC,GACA;EACC,KAAK,KACJ,OAAO,OAAO,IAAI,aAAa,EAC9B,SAAS,CACR,0BAA0B,IAAI,6BAC9B,kFACD,CAAC,CAAC,KAAK,IAAI,EACZ,CAAC;EACF,KAAK,KACJ,OAAO,OAAO,IAAI,aAAa,EAC9B,SAAS,0BAA0B,IAAI,+BACxC,CAAC;EACF,SACC,OAAO,OAAO,IAAI,aAAa,EAC9B,SAAS,CACR,+CAA+C,OAC/C,0DACD,CAAC,CAAC,KAAK,IAAI,EACZ,CAAC;CACH;AACD,CAAC;;;;;AAMD,MAAa,WACX,SACS,YACT,OAAO,IAAI,aAAa;CACvB,MAAM,SAAS,OAAO,OAAO,GAAG;CAChC,OAAO,OAAO,QAAQ,KAErB,OAAO,QACP,OAAO,QAAQC,MAAa,MAAM,CAAC,GACnC,OAAO,SACL,UAAU,cAAc,KAAK,KAAK,MAAM,OAAO,SAAS,yBACnD,QAAQ,OAAO,OAAO,KAAK,MAAM,CACxC,CACD;AACD,CAAC"}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { g as make, m as writeOut } from "./error-BsI8iNna.mjs";
|
|
2
|
+
import { i as Cmd } from "./runtime-CyXV7HH_.mjs";
|
|
3
|
+
import { n as layer, t as Service } from "./service-CA6VAOdR.mjs";
|
|
4
|
+
import { t as connect } from "./service-YVNwFMNf.mjs";
|
|
5
|
+
import { Duration, Effect, Option, Schema } from "effect";
|
|
6
|
+
import { oauthErrorHtml, oauthSuccessHtml, openBrowser, promptLine } from "@codeworksh/aikit/oauth/interactive";
|
|
7
|
+
import { createServer } from "node:http";
|
|
8
|
+
//#region src/cli/cmd/handlers/connect/shared.ts
|
|
9
|
+
var ConnectCliError = class extends Schema.TaggedError()("CLI.ConnectError", { message: Schema.String }) {};
|
|
10
|
+
const toCliError = (cause) => new ConnectCliError({ message: typeof cause === "object" && cause !== null && "message" in cause && typeof cause.message === "string" ? cause.message : String(cause) });
|
|
11
|
+
const mapErr = (effect) => effect.pipe(Effect.mapError(toCliError));
|
|
12
|
+
/**
|
|
13
|
+
* Runs an operation against either a running RPC server (`--server`) or the local `<home>/connections.db`.
|
|
14
|
+
*/
|
|
15
|
+
const withConnectApi = (server, fn) => Effect.gen(function* () {
|
|
16
|
+
if (Option.isSome(server)) return yield* Effect.gen(function* () {
|
|
17
|
+
const rpc = yield* make;
|
|
18
|
+
return yield* fn({
|
|
19
|
+
catalog: (input) => mapErr(rpc["connectors.catalog"](input)),
|
|
20
|
+
list: (input) => mapErr(rpc["connections.list"](input)),
|
|
21
|
+
get: (ref) => mapErr(rpc["connections.get"]({ ref })),
|
|
22
|
+
create: (input) => mapErr(rpc["connections.create"](input)),
|
|
23
|
+
remove: (ref) => mapErr(rpc["connections.remove"]({ ref }).pipe(Effect.map((r) => r.removed))),
|
|
24
|
+
setApiKey: (ref, apiKey) => mapErr(rpc["connections.setApiKey"]({
|
|
25
|
+
ref,
|
|
26
|
+
apiKey
|
|
27
|
+
})),
|
|
28
|
+
disconnect: (ref) => mapErr(rpc["connections.disconnect"]({ ref })),
|
|
29
|
+
oauthStart: (input) => mapErr(rpc["connections.oauth.start"](input)),
|
|
30
|
+
oauthFinish: (input) => mapErr(rpc["connections.oauth.finish"](input)),
|
|
31
|
+
deviceStart: (input) => mapErr(rpc["connections.oauth.deviceStart"](input)),
|
|
32
|
+
devicePoll: (state) => mapErr(rpc["connections.oauth.devicePoll"]({ state }))
|
|
33
|
+
});
|
|
34
|
+
}).pipe(Effect.scoped, connect(server.value));
|
|
35
|
+
const shared = yield* Cmd.spec;
|
|
36
|
+
const layer$1 = layer(Option.isNone(shared.home) ? {} : { home: shared.home.value });
|
|
37
|
+
return yield* Effect.gen(function* () {
|
|
38
|
+
const svc = yield* Service;
|
|
39
|
+
return yield* fn({
|
|
40
|
+
catalog: (input) => mapErr(svc.catalog(input)),
|
|
41
|
+
list: (input) => mapErr(svc.list(input)),
|
|
42
|
+
get: (ref) => mapErr(svc.get(ref)),
|
|
43
|
+
create: (input) => mapErr(svc.create(input)),
|
|
44
|
+
remove: (ref) => mapErr(svc.remove(ref)),
|
|
45
|
+
setApiKey: (ref, apiKey) => mapErr(svc.setApiKey(ref, apiKey)),
|
|
46
|
+
disconnect: (ref) => mapErr(svc.disconnect(ref)),
|
|
47
|
+
oauthStart: (input) => mapErr(svc.oauthStart(input)),
|
|
48
|
+
oauthFinish: (input) => mapErr(svc.oauthFinish(input)),
|
|
49
|
+
deviceStart: (input) => mapErr(svc.deviceStart(input)),
|
|
50
|
+
devicePoll: (state) => mapErr(svc.devicePoll(state))
|
|
51
|
+
});
|
|
52
|
+
}).pipe(Effect.provide(layer$1));
|
|
53
|
+
});
|
|
54
|
+
const replyHtml = (res, status, html) => res.writeHead(status, {
|
|
55
|
+
"content-type": "text/html; charset=utf-8",
|
|
56
|
+
"cache-control": "no-store"
|
|
57
|
+
}).end(html);
|
|
58
|
+
const startLoopback = (opts) => new Promise((resolve, reject) => {
|
|
59
|
+
const server = createServer();
|
|
60
|
+
let pending;
|
|
61
|
+
server.on("request", (req, res) => {
|
|
62
|
+
const addr = server.address();
|
|
63
|
+
const port = addr !== null && typeof addr === "object" ? addr.port : opts.port;
|
|
64
|
+
const base = `http://${opts.redirectHost}:${port}`;
|
|
65
|
+
const url = new URL(req.url ?? "/", base);
|
|
66
|
+
if (url.pathname !== opts.path) return replyHtml(res, 404, oauthErrorHtml("Not found."));
|
|
67
|
+
const state = url.searchParams.get("state");
|
|
68
|
+
if (!pending || state !== pending.state) return replyHtml(res, 400, oauthErrorHtml("Invalid or expired OAuth state."));
|
|
69
|
+
const current = pending;
|
|
70
|
+
pending = void 0;
|
|
71
|
+
const error = url.searchParams.get("error");
|
|
72
|
+
const code = url.searchParams.get("code");
|
|
73
|
+
if (error !== null) {
|
|
74
|
+
const desc = url.searchParams.get("error_description") ?? error;
|
|
75
|
+
current.fail(new Error(desc));
|
|
76
|
+
return replyHtml(res, 200, oauthErrorHtml("Sign-in failed. You may close this window.", desc));
|
|
77
|
+
}
|
|
78
|
+
if (code === null || code.length === 0) {
|
|
79
|
+
current.fail(/* @__PURE__ */ new Error("Missing authorization code"));
|
|
80
|
+
return replyHtml(res, 400, oauthErrorHtml("Missing authorization code."));
|
|
81
|
+
}
|
|
82
|
+
current.done(code);
|
|
83
|
+
return replyHtml(res, 200, oauthSuccessHtml("Connected to CodeWork. You may close this window."));
|
|
84
|
+
});
|
|
85
|
+
server.once("error", (err) => reject(err));
|
|
86
|
+
server.listen(opts.port, opts.host, () => {
|
|
87
|
+
const addr = server.address();
|
|
88
|
+
if (addr === null || typeof addr !== "object") {
|
|
89
|
+
server.close();
|
|
90
|
+
reject(/* @__PURE__ */ new Error("Failed to bind loopback callback server"));
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
resolve({
|
|
94
|
+
redirectUrl: `http://${opts.redirectHost}:${addr.port}${opts.path}`,
|
|
95
|
+
wait: (expectedState, signal) => new Promise((done, fail) => {
|
|
96
|
+
if (signal.aborted) {
|
|
97
|
+
fail(/* @__PURE__ */ new Error("Cancelled"));
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const onAbort = () => {
|
|
101
|
+
if (pending?.state === expectedState) pending = void 0;
|
|
102
|
+
fail(/* @__PURE__ */ new Error("Cancelled"));
|
|
103
|
+
};
|
|
104
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
105
|
+
pending = {
|
|
106
|
+
state: expectedState,
|
|
107
|
+
done: (code) => {
|
|
108
|
+
signal.removeEventListener("abort", onAbort);
|
|
109
|
+
done(code);
|
|
110
|
+
},
|
|
111
|
+
fail: (err) => {
|
|
112
|
+
signal.removeEventListener("abort", onAbort);
|
|
113
|
+
fail(err);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}),
|
|
117
|
+
close: () => {
|
|
118
|
+
server.close();
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
/**
|
|
124
|
+
* Runs the interactive authentication flow (API key, OAuth PKCE loopback raced with paste, or device code)
|
|
125
|
+
* for an existing Connection via `api`.
|
|
126
|
+
*/
|
|
127
|
+
const authenticateConnection = (api, connection, spec, options) => Effect.gen(function* () {
|
|
128
|
+
if (connection.authType === "apikey") {
|
|
129
|
+
const key = options.apiKey ?? (yield* Effect.tryPromise({
|
|
130
|
+
try: () => promptLine(`Enter API key for ${connection.uid}${spec?.auth.apikey?.keyUrl ? ` (${spec.auth.apikey.keyUrl})` : ""}: `),
|
|
131
|
+
catch: toCliError
|
|
132
|
+
}));
|
|
133
|
+
return yield* api.setApiKey(connection.uid, key);
|
|
134
|
+
}
|
|
135
|
+
if (connection.authType !== "oauth") return connection;
|
|
136
|
+
const oauthSpec = spec?.auth.oauth;
|
|
137
|
+
if (options.device === true || oauthSpec !== void 0 && !oauthSpec.grants.includes("authorization_code") && oauthSpec.grants.includes("device_code")) {
|
|
138
|
+
const started = yield* api.deviceStart({
|
|
139
|
+
ref: connection.uid,
|
|
140
|
+
enterpriseUrl: options.enterpriseUrl
|
|
141
|
+
});
|
|
142
|
+
process.stderr.write(`Open ${started.verificationUri} and enter code: ${started.userCode}\n`);
|
|
143
|
+
if (options.browser !== false) openBrowser(started.verificationUri, (err) => {
|
|
144
|
+
process.stderr.write(`Failed to open browser: ${err.message}\n`);
|
|
145
|
+
});
|
|
146
|
+
let intervalSeconds = Math.max(1, started.intervalSeconds);
|
|
147
|
+
while (true) {
|
|
148
|
+
yield* Effect.sleep(Duration.seconds(intervalSeconds));
|
|
149
|
+
const polled = yield* api.devicePoll(started.state);
|
|
150
|
+
if (polled.status === "complete") return polled.connection;
|
|
151
|
+
if (polled.intervalSeconds !== void 0 && polled.intervalSeconds > 0) intervalSeconds = polled.intervalSeconds;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const isCodex = oauthSpec?.handler === "openai-codex";
|
|
155
|
+
const listener = yield* Effect.tryPromise({
|
|
156
|
+
try: () => startLoopback(isCodex ? {
|
|
157
|
+
host: "127.0.0.1",
|
|
158
|
+
redirectHost: "localhost",
|
|
159
|
+
port: 1455,
|
|
160
|
+
path: "/auth/callback"
|
|
161
|
+
} : {
|
|
162
|
+
host: "127.0.0.1",
|
|
163
|
+
redirectHost: "127.0.0.1",
|
|
164
|
+
port: 0,
|
|
165
|
+
path: "/oauth/callback"
|
|
166
|
+
}),
|
|
167
|
+
catch: toCliError
|
|
168
|
+
});
|
|
169
|
+
try {
|
|
170
|
+
const started = yield* api.oauthStart({
|
|
171
|
+
ref: connection.uid,
|
|
172
|
+
redirectUrl: listener.redirectUrl
|
|
173
|
+
});
|
|
174
|
+
process.stderr.write(`Authorize ${connection.uid} in your browser:\n${started.authorizeUrl}\n`);
|
|
175
|
+
if (options.browser !== false) openBrowser(started.authorizeUrl, (err) => {
|
|
176
|
+
process.stderr.write(`Failed to open browser: ${err.message}\n`);
|
|
177
|
+
});
|
|
178
|
+
const controller = new AbortController();
|
|
179
|
+
const code = yield* Effect.tryPromise({
|
|
180
|
+
try: async () => {
|
|
181
|
+
const callbackPromise = listener.wait(started.state, controller.signal);
|
|
182
|
+
if (!process.stdin.isTTY) return await callbackPromise;
|
|
183
|
+
const manualPromise = promptLine("Waiting for browser callback (or paste redirected URL / code here): ");
|
|
184
|
+
try {
|
|
185
|
+
return await Promise.race([callbackPromise, manualPromise]);
|
|
186
|
+
} finally {
|
|
187
|
+
controller.abort();
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
catch: toCliError
|
|
191
|
+
});
|
|
192
|
+
return yield* api.oauthFinish({
|
|
193
|
+
state: started.state,
|
|
194
|
+
code
|
|
195
|
+
});
|
|
196
|
+
} finally {
|
|
197
|
+
listener.close();
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
const printJson = (value) => writeOut(`${JSON.stringify(value, null, 2)}\n`);
|
|
201
|
+
const formatConnectionLine = (c) => {
|
|
202
|
+
const flags = [c.status, c.sourceLabel];
|
|
203
|
+
if (c.isDefault) flags.push("default");
|
|
204
|
+
if (!c.enabled) flags.push("disabled");
|
|
205
|
+
if (c.readOnly) flags.push("read-only");
|
|
206
|
+
const account = c.accountLabel ? ` [${c.accountLabel}]` : "";
|
|
207
|
+
return `${c.uid}${account} (${flags.join(", ")})`;
|
|
208
|
+
};
|
|
209
|
+
//#endregion
|
|
210
|
+
export { withConnectApi as i, formatConnectionLine as n, printJson as r, authenticateConnection as t };
|
|
211
|
+
|
|
212
|
+
//# sourceMappingURL=shared-CA47qIai.mjs.map
|