@codeworksh/cli 0.9.0-canary.167.1.g6ddcc8db → 0.9.0-canary.169.1.g71f19429

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/{acp-CmtcmhuX.mjs → acp-Cw5Ljayx.mjs} +6 -5
  2. package/acp-Cw5Ljayx.mjs.map +1 -0
  3. package/{add-Bmholf85.mjs → add-Be7-HfBj.mjs} +2 -2
  4. package/{add-Bmholf85.mjs.map → add-Be7-HfBj.mjs.map} +1 -1
  5. package/{add-Ct20ZUEC.mjs → add-D2ly9-x3.mjs} +3 -3
  6. package/{add-Ct20ZUEC.mjs.map → add-D2ly9-x3.mjs.map} +1 -1
  7. package/{catalog-BJScfJLW.mjs → catalog-Dzi9__Rq.mjs} +2 -2
  8. package/{catalog-BJScfJLW.mjs.map → catalog-Dzi9__Rq.mjs.map} +1 -1
  9. package/categories-DD30aGHU.mjs +19 -0
  10. package/categories-DD30aGHU.mjs.map +1 -0
  11. package/{check-ki1450h-.mjs → check-DzxfN43i.mjs} +2 -2
  12. package/{check-ki1450h-.mjs.map → check-DzxfN43i.mjs.map} +1 -1
  13. package/{connect-KX-A0EzQ.mjs → connect-AqacTFrV.mjs} +5 -5
  14. package/{connect-KX-A0EzQ.mjs.map → connect-AqacTFrV.mjs.map} +1 -1
  15. package/{control-Cotypk4e.mjs → control-CFQeKIKx.mjs} +4 -4
  16. package/{control-Cotypk4e.mjs.map → control-CFQeKIKx.mjs.map} +1 -1
  17. package/create-dxNGBbiQ.mjs +35 -0
  18. package/create-dxNGBbiQ.mjs.map +1 -0
  19. package/{devices-BcuQ11QF.mjs → devices-DNzXKhNy.mjs} +3 -3
  20. package/{devices-BcuQ11QF.mjs.map → devices-DNzXKhNy.mjs.map} +1 -1
  21. package/disconnect-BcwEk1sG.mjs +19 -0
  22. package/disconnect-BcwEk1sG.mjs.map +1 -0
  23. package/disconnect-CHEHx_ic.mjs +2 -0
  24. package/{disconnect-CCI1DLJ0.mjs → disconnect-V4MnDMkF.mjs} +4 -4
  25. package/{disconnect-CCI1DLJ0.mjs.map → disconnect-V4MnDMkF.mjs.map} +1 -1
  26. package/discover-DAP4t5Kb.mjs +35 -0
  27. package/discover-DAP4t5Kb.mjs.map +1 -0
  28. package/{discovery-D2ftXE5a.mjs → discovery-C6H7dCHz.mjs} +2 -2
  29. package/{discovery-D2ftXE5a.mjs.map → discovery-C6H7dCHz.mjs.map} +1 -1
  30. package/{fork-DkYRL_nQ.mjs → fork-TUz05qSe.mjs} +3 -3
  31. package/{fork-DkYRL_nQ.mjs.map → fork-TUz05qSe.mjs.map} +1 -1
  32. package/{identity-Llk4K_8w.mjs → identity-fLl347sJ.mjs} +2 -2
  33. package/{identity-Llk4K_8w.mjs.map → identity-fLl347sJ.mjs.map} +1 -1
  34. package/index.mjs +49 -39
  35. package/index.mjs.map +1 -1
  36. package/{install-hs3tvWLA.mjs → install-BtoWHZoI.mjs} +2 -2
  37. package/{install-hs3tvWLA.mjs.map → install-BtoWHZoI.mjs.map} +1 -1
  38. package/{link-BzFGtDKJ.mjs → link-Cd6T22_n.mjs} +3 -3
  39. package/{link-BzFGtDKJ.mjs.map → link-Cd6T22_n.mjs.map} +1 -1
  40. package/{list-sLzs2Y7w.mjs → list-Bn5CvS1y.mjs} +3 -3
  41. package/{list-sLzs2Y7w.mjs.map → list-Bn5CvS1y.mjs.map} +1 -1
  42. package/list-C29G-xrA.mjs +27 -0
  43. package/list-C29G-xrA.mjs.map +1 -0
  44. package/{list-D1c5uzCc.mjs → list-CdS1_gFF.mjs} +2 -2
  45. package/{list-D1c5uzCc.mjs.map → list-CdS1_gFF.mjs.map} +1 -1
  46. package/{list-DhL_z5v2.mjs → list-DAA92mUG.mjs} +3 -3
  47. package/{list-DhL_z5v2.mjs.map → list-DAA92mUG.mjs.map} +1 -1
  48. package/{list-Dt0_ol5P.mjs → list-MiZ6rD_w.mjs} +3 -3
  49. package/{list-Dt0_ol5P.mjs.map → list-MiZ6rD_w.mjs.map} +1 -1
  50. package/{login-BxiN8frI.mjs → login-C_tBeHg6.mjs} +3 -3
  51. package/{login-BxiN8frI.mjs.map → login-C_tBeHg6.mjs.map} +1 -1
  52. package/login-D0EMtnh2.mjs +26 -0
  53. package/login-D0EMtnh2.mjs.map +1 -0
  54. package/{login-S-2L5YYB.mjs → login-Q_ezdpon.mjs} +3 -3
  55. package/{login-S-2L5YYB.mjs.map → login-Q_ezdpon.mjs.map} +1 -1
  56. package/{logout-BeMvfZkG.mjs → logout-BjL1W-0I.mjs} +3 -3
  57. package/{logout-BeMvfZkG.mjs.map → logout-BjL1W-0I.mjs.map} +1 -1
  58. package/{logout-CKcRACIf.mjs → logout-E_dRjl1L.mjs} +3 -3
  59. package/{logout-CKcRACIf.mjs.map → logout-E_dRjl1L.mjs.map} +1 -1
  60. package/package-Y0eg0qm4.mjs +6 -0
  61. package/package-Y0eg0qm4.mjs.map +1 -0
  62. package/package.json +4 -4
  63. package/{pair-BhGzBBV8.mjs → pair-BBneOJZJ.mjs} +3 -3
  64. package/{pair-BhGzBBV8.mjs.map → pair-BBneOJZJ.mjs.map} +1 -1
  65. package/{providers-DdBYxi9t.mjs → providers-BYnMGDs7.mjs} +3 -3
  66. package/{providers-DdBYxi9t.mjs.map → providers-BYnMGDs7.mjs.map} +1 -1
  67. package/reconnect-BKpud0ma.mjs +2 -0
  68. package/{refresh-BgQfD2zv.mjs → refresh-CvE_f1Fa.mjs} +3 -3
  69. package/{refresh-BgQfD2zv.mjs.map → refresh-CvE_f1Fa.mjs.map} +1 -1
  70. package/{refresh-Cy6abMk_.mjs → refresh-Dy9kI2El.mjs} +3 -3
  71. package/{refresh-Cy6abMk_.mjs.map → refresh-Dy9kI2El.mjs.map} +1 -1
  72. package/{relay-BmHXs1yg.mjs → relay-DbZQ4i7J.mjs} +3 -3
  73. package/{relay-BmHXs1yg.mjs.map → relay-DbZQ4i7J.mjs.map} +1 -1
  74. package/{relink-Dxg1kstB.mjs → relink-DxftNq9n.mjs} +3 -3
  75. package/{relink-Dxg1kstB.mjs.map → relink-DxftNq9n.mjs.map} +1 -1
  76. package/{reload-CUyG343t.mjs → reload-DRp3UlHQ.mjs} +3 -3
  77. package/{reload-CUyG343t.mjs.map → reload-DRp3UlHQ.mjs.map} +1 -1
  78. package/{remove-BXmNNX2f.mjs → remove-C0e5sHqb.mjs} +3 -3
  79. package/{remove-BXmNNX2f.mjs.map → remove-C0e5sHqb.mjs.map} +1 -1
  80. package/{remove-CJ__oofS.mjs → remove-CdcoheOp.mjs} +2 -2
  81. package/{remove-CJ__oofS.mjs.map → remove-CdcoheOp.mjs.map} +1 -1
  82. package/remove-y_AI5IuH.mjs +22 -0
  83. package/remove-y_AI5IuH.mjs.map +1 -0
  84. package/{restart-CMDZZJ4N.mjs → restart-BcpKCYwQ.mjs} +4 -4
  85. package/{restart-CMDZZJ4N.mjs.map → restart-BcpKCYwQ.mjs.map} +1 -1
  86. package/{revoke-DigrkMoL.mjs → revoke-DoMHa1vL.mjs} +3 -3
  87. package/{revoke-DigrkMoL.mjs.map → revoke-DoMHa1vL.mjs.map} +1 -1
  88. package/{run-BN0xfxh_.mjs → run-DNbme1W_.mjs} +8 -5
  89. package/run-DNbme1W_.mjs.map +1 -0
  90. package/{runtime-Q4G4z83G.mjs → runtime-CyXV7HH_.mjs} +152 -9
  91. package/runtime-CyXV7HH_.mjs.map +1 -0
  92. package/{serve-CfjS09-r.mjs → serve-CGPp3kyd.mjs} +27 -11
  93. package/serve-CGPp3kyd.mjs.map +1 -0
  94. package/service-C1UBpOCn.mjs +1718 -0
  95. package/service-C1UBpOCn.mjs.map +1 -0
  96. package/{service-B0O4PjbL.mjs → service-YVNwFMNf.mjs} +2 -2
  97. package/{service-B0O4PjbL.mjs.map → service-YVNwFMNf.mjs.map} +1 -1
  98. package/{shared-C2sMimyK.mjs → shared-CDJQxUb9.mjs} +4 -4
  99. package/{shared-C2sMimyK.mjs.map → shared-CDJQxUb9.mjs.map} +1 -1
  100. package/shared-CXbDdgs4.mjs +223 -0
  101. package/shared-CXbDdgs4.mjs.map +1 -0
  102. package/{shared-C4j4rGe4.mjs → shared-D_MVXtOf.mjs} +3 -3
  103. package/{shared-C4j4rGe4.mjs.map → shared-D_MVXtOf.mjs.map} +1 -1
  104. package/{start-DbCTFswo.mjs → start-Dky5Iihf.mjs} +4 -4
  105. package/{start-DbCTFswo.mjs.map → start-Dky5Iihf.mjs.map} +1 -1
  106. package/status-B29jKo_s.mjs +23 -0
  107. package/status-B29jKo_s.mjs.map +1 -0
  108. package/{status-CR_E6RiI.mjs → status-BoTZqXwd.mjs} +3 -3
  109. package/{status-CR_E6RiI.mjs.map → status-BoTZqXwd.mjs.map} +1 -1
  110. package/{status-Dcbdl6Sv.mjs → status-CdAZIIEi.mjs} +4 -4
  111. package/{status-Dcbdl6Sv.mjs.map → status-CdAZIIEi.mjs.map} +1 -1
  112. package/{stop-ML5Yeo_s.mjs → stop-BCAMcHem.mjs} +4 -4
  113. package/{stop-ML5Yeo_s.mjs.map → stop-BCAMcHem.mjs.map} +1 -1
  114. package/{update-BK_LdUUv.mjs → update-mWc5cR7q.mjs} +2 -2
  115. package/{update-BK_LdUUv.mjs.map → update-mWc5cR7q.mjs.map} +1 -1
  116. package/acp-CmtcmhuX.mjs.map +0 -1
  117. package/disconnect-DKi3PmC2.mjs +0 -2
  118. package/package-D_TWKUKk.mjs +0 -6
  119. package/package-D_TWKUKk.mjs.map +0 -1
  120. package/reconnect-DgUK2fwU.mjs +0 -2
  121. package/run-BN0xfxh_.mjs.map +0 -1
  122. package/runtime-Q4G4z83G.mjs.map +0 -1
  123. package/serve-CfjS09-r.mjs.map +0 -1
@@ -0,0 +1,1718 @@
1
+ import { Clock, Context, Effect, Layer, Redacted, Schema, Semaphore } from "effect";
2
+ import { Connector, Global, OAuthCimd } from "@codeworksh/harness/effect";
3
+ import { Actor } from "@codeworksh/schema/actor";
4
+ import { AuthRequiredError, CONNECTION_SLUG_PATTERN, CONNECTION_UID_PATTERN, ConnectionConfig, ConnectionConflictError, ConnectionID, ConnectionNotFoundError, ConnectorAuthError, ConnectorCatalog, ConnectorNotFoundError, ConnectorSpec, ConnectorValidationError, DEFAULT_CONNECTORS_CATALOG_URL, DEFAULT_CONNECTOR_CATALOG, HostNotAllowedError, formatUid, hostMatches } from "@codeworksh/schema/connector";
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ import { DatabaseSync } from "node:sqlite";
9
+ import { createGitHubCopilotDeviceFlow, fetchGitHubCopilotModels, fetchGitHubCopilotUser, gitHubCopilotBaseUrl, gitHubCopilotEntitlementError, gitHubCopilotHeaders, normalizeGitHubDomain } from "@codeworksh/aikit/oauth/github/copilot";
10
+ import { createOpenAICodexAuthorizationFlow, createOpenAICodexDeviceAuth, exchangeOpenAICodexAuthorizationCode, getOpenAICodexAccountId, openAICodexHeaders, parseOpenAICodexAuthorizationInput, refreshOpenAICodexToken } from "@codeworksh/aikit/oauth/openai/codex";
11
+ //#region src/connector/catalog.ts
12
+ const decodeCatalog = Schema.decodeUnknownSync(ConnectorCatalog);
13
+ const catalogUrl = (override) => override ?? process.env["CODEWORK_CONNECTORS_CATALOG_URL"] ?? DEFAULT_CONNECTORS_CATALOG_URL;
14
+ const cachePath = (home) => join(home, "cache", "connectors.json");
15
+ const etagPath = (home) => join(home, "cache", "connectors.etag");
16
+ const readCachedCatalog = (home) => {
17
+ const file = cachePath(home);
18
+ if (!existsSync(file)) return void 0;
19
+ try {
20
+ return decodeCatalog(JSON.parse(readFileSync(file, "utf-8")));
21
+ } catch {
22
+ return;
23
+ }
24
+ };
25
+ const readCachedEtag = (home) => {
26
+ const file = etagPath(home);
27
+ if (!existsSync(file)) return void 0;
28
+ try {
29
+ const tag = readFileSync(file, "utf-8").trim();
30
+ return tag.length > 0 ? tag : void 0;
31
+ } catch {
32
+ return;
33
+ }
34
+ };
35
+ const writeCachedCatalog = (home, raw, etag) => {
36
+ const file = cachePath(home);
37
+ mkdirSync(dirname(file), {
38
+ recursive: true,
39
+ mode: 448
40
+ });
41
+ writeFileSync(file, raw, {
42
+ encoding: "utf-8",
43
+ mode: 384
44
+ });
45
+ const tag = etag ?? `"${createHash("md5").update(raw).digest("hex")}"`;
46
+ writeFileSync(etagPath(home), tag, {
47
+ encoding: "utf-8",
48
+ mode: 384
49
+ });
50
+ };
51
+ /**
52
+ * Load the connector catalog from cache or bundled fallback without hitting the network.
53
+ */
54
+ const loadLocalCatalog = (home) => readCachedCatalog(home) ?? DEFAULT_CONNECTOR_CATALOG;
55
+ /**
56
+ * Refresh the connector catalog from `catalog.codework.sh/v1/connectors.json` (using `If-None-Match`
57
+ * so unchanged catalogs answer `304`), falling back cleanly to the disk cache or bundled snapshot.
58
+ */
59
+ const fetchCatalog = (options) => Effect.tryPromise({
60
+ try: async () => {
61
+ const cached = readCachedCatalog(options.home);
62
+ const url = catalogUrl(options.url);
63
+ const fetcher = options.fetch ?? globalThis.fetch;
64
+ const headers = { Accept: "application/json" };
65
+ const etag = readCachedEtag(options.home);
66
+ if (cached && etag) headers["If-None-Match"] = etag;
67
+ try {
68
+ const response = await fetcher(url, {
69
+ headers,
70
+ signal: AbortSignal.timeout(5e3)
71
+ });
72
+ if (response.status === 304 && cached) return cached;
73
+ if (!response.ok) return cached ?? DEFAULT_CONNECTOR_CATALOG;
74
+ const text = await response.text();
75
+ const parsed = decodeCatalog(JSON.parse(text));
76
+ writeCachedCatalog(options.home, text, response.headers.get("etag") ?? void 0);
77
+ return parsed;
78
+ } catch {
79
+ return cached ?? DEFAULT_CONNECTOR_CATALOG;
80
+ }
81
+ },
82
+ catch: () => void 0
83
+ }).pipe(Effect.orElseSucceed(() => loadLocalCatalog(options.home)));
84
+ /** Look up a connector by exact reverse-DNS `id` or short `alias` (case-insensitive). */
85
+ const findConnector = (catalog, idOrAlias) => {
86
+ const needle = idOrAlias.trim().toLowerCase();
87
+ if (needle.length === 0) return void 0;
88
+ const exact = catalog.connectors[needle];
89
+ if (exact !== void 0) return exact;
90
+ for (const spec of Object.values(catalog.connectors)) if (spec.id.toLowerCase() === needle || spec.alias?.toLowerCase() === needle) return spec;
91
+ };
92
+ /** Find the catalog connector powering a given `aikit` providerId (e.g. `"anthropic"`, `"openai-codex"`). */
93
+ const findConnectorByProviderId = (catalog, providerId) => {
94
+ for (const spec of Object.values(catalog.connectors)) if (spec.capabilities.provider?.providerId === providerId) return spec;
95
+ };
96
+ const filterConnectors = (catalog, filter = {}) => {
97
+ const q = filter.query?.trim().toLowerCase();
98
+ const cat = filter.category?.trim().toLowerCase();
99
+ return Object.values(catalog.connectors).filter((spec) => {
100
+ if (filter.kind !== void 0 && !spec.kinds.includes(filter.kind)) return false;
101
+ if (cat !== void 0 && cat.length > 0 && !spec.categories.some((c) => c.toLowerCase() === cat)) return false;
102
+ if (q !== void 0 && q.length > 0) {
103
+ if (![
104
+ spec.id,
105
+ spec.alias ?? "",
106
+ spec.name,
107
+ spec.description,
108
+ ...spec.categories
109
+ ].join(" ").toLowerCase().includes(q)) return false;
110
+ }
111
+ return true;
112
+ }).sort((a, b) => {
113
+ if (Boolean(a.featured) !== Boolean(b.featured)) return a.featured ? -1 : 1;
114
+ return a.name.localeCompare(b.name);
115
+ });
116
+ };
117
+ //#endregion
118
+ //#region src/connector/db.ts
119
+ const decodeConfig = Schema.decodeUnknownSync(ConnectionConfig);
120
+ const decodeSpec = Schema.decodeUnknownSync(ConnectorSpec);
121
+ const parseJsonArray = (raw) => {
122
+ try {
123
+ const parsed = JSON.parse(raw);
124
+ return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
125
+ } catch {
126
+ return [];
127
+ }
128
+ };
129
+ const parseKinds = (raw) => parseJsonArray(raw).filter((item) => item === "provider" || item === "mcp" || item === "integration");
130
+ const parseConfig = (raw) => {
131
+ try {
132
+ return decodeConfig(JSON.parse(raw));
133
+ } catch {
134
+ return {};
135
+ }
136
+ };
137
+ const parseSpec = (raw) => {
138
+ if (raw === null) return void 0;
139
+ try {
140
+ return decodeSpec(JSON.parse(raw));
141
+ } catch {
142
+ return;
143
+ }
144
+ };
145
+ const toConnectionRow = (raw) => ({
146
+ id: ConnectionID.from(raw.id),
147
+ workspaceId: raw.workspace_id,
148
+ uid: raw.uid,
149
+ label: raw.label ?? void 0,
150
+ source: raw.source === "custom" ? "custom" : "catalog",
151
+ connectorId: raw.connector_id,
152
+ kinds: parseKinds(raw.kinds),
153
+ authType: raw.auth_type === "oauth" ? "oauth" : "apikey",
154
+ ownership: raw.ownership === "personal" ? "personal" : "shared",
155
+ enabled: raw.enabled !== 0,
156
+ isDefault: raw.is_default !== 0,
157
+ allowedHosts: parseJsonArray(raw.allowed_hosts),
158
+ config: parseConfig(raw.config),
159
+ spec: parseSpec(raw.spec),
160
+ createdAt: raw.created_at,
161
+ updatedAt: raw.updated_at
162
+ });
163
+ const toCredentialRow = (raw) => ({
164
+ connectionId: ConnectionID.from(raw.connection_id),
165
+ subjectType: raw.subject_type === "user" ? "user" : "app",
166
+ subjectId: raw.subject_id,
167
+ secret: JSON.parse(raw.secret),
168
+ status: raw.status === "active" || raw.status === "not_connected" || raw.status === "expired" || raw.status === "revoked" || raw.status === "error" ? raw.status : "active",
169
+ lastError: raw.last_error ?? void 0,
170
+ expiresAt: raw.expires_at ?? void 0,
171
+ updatedAt: raw.updated_at
172
+ });
173
+ const connectionsDbPath = (home) => join(home, "connections.db");
174
+ const MIGRATION_V1 = `
175
+ CREATE TABLE IF NOT EXISTS meta (
176
+ key TEXT PRIMARY KEY,
177
+ value TEXT NOT NULL
178
+ );
179
+
180
+ CREATE TABLE IF NOT EXISTS connection (
181
+ id TEXT PRIMARY KEY,
182
+ workspace_id TEXT NOT NULL,
183
+ uid TEXT NOT NULL,
184
+ label TEXT,
185
+ source TEXT NOT NULL DEFAULT 'catalog',
186
+ connector_id TEXT NOT NULL,
187
+ kinds TEXT NOT NULL,
188
+ auth_type TEXT NOT NULL,
189
+ ownership TEXT NOT NULL,
190
+ enabled INTEGER NOT NULL DEFAULT 1,
191
+ is_default INTEGER NOT NULL DEFAULT 0,
192
+ allowed_hosts TEXT NOT NULL,
193
+ config TEXT NOT NULL DEFAULT '{}',
194
+ spec TEXT,
195
+ created_at INTEGER NOT NULL,
196
+ updated_at INTEGER NOT NULL,
197
+ UNIQUE (workspace_id, uid)
198
+ );
199
+
200
+ CREATE INDEX IF NOT EXISTS idx_connection_workspace ON connection(workspace_id);
201
+ CREATE INDEX IF NOT EXISTS idx_connection_connector ON connection(workspace_id, connector_id);
202
+
203
+ CREATE TABLE IF NOT EXISTS credential (
204
+ connection_id TEXT NOT NULL REFERENCES connection(id) ON DELETE CASCADE,
205
+ subject_type TEXT NOT NULL,
206
+ subject_id TEXT NOT NULL,
207
+ secret TEXT NOT NULL,
208
+ status TEXT NOT NULL DEFAULT 'active',
209
+ last_error TEXT,
210
+ expires_at INTEGER,
211
+ updated_at INTEGER NOT NULL,
212
+ PRIMARY KEY (connection_id, subject_type, subject_id)
213
+ );
214
+ `;
215
+ /**
216
+ * Machine-local SQLite store for workspace connections and secrets (`<home>/connections.db`).
217
+ */
218
+ var ConnectionsDb = class {
219
+ path;
220
+ db;
221
+ constructor(filePath) {
222
+ this.path = filePath;
223
+ if (filePath !== ":memory:") mkdirSync(dirname(filePath), {
224
+ recursive: true,
225
+ mode: 448
226
+ });
227
+ this.db = new DatabaseSync(filePath);
228
+ if (filePath !== ":memory:") try {
229
+ chmodSync(filePath, 384);
230
+ } catch {}
231
+ this.db.exec("PRAGMA journal_mode = WAL;");
232
+ this.db.exec("PRAGMA busy_timeout = 5000;");
233
+ this.db.exec("PRAGMA foreign_keys = ON;");
234
+ this.db.exec(MIGRATION_V1);
235
+ this.setMetaIfMissing("schema_version", "1");
236
+ }
237
+ close() {
238
+ this.db.close();
239
+ }
240
+ getMeta(key) {
241
+ return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(key)?.value;
242
+ }
243
+ setMeta(key, value) {
244
+ this.db.prepare("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);
245
+ }
246
+ setMetaIfMissing(key, value) {
247
+ this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)").run(key, value);
248
+ }
249
+ withImmediateTx(fn) {
250
+ this.db.exec("BEGIN IMMEDIATE");
251
+ try {
252
+ const result = fn();
253
+ this.db.exec("COMMIT");
254
+ return result;
255
+ } catch (error) {
256
+ try {
257
+ this.db.exec("ROLLBACK");
258
+ } catch {}
259
+ throw error;
260
+ }
261
+ }
262
+ listConnections(workspaceId, filter = {}) {
263
+ const clauses = ["workspace_id = ?"];
264
+ const params = [workspaceId];
265
+ if (filter.connectorId !== void 0) {
266
+ clauses.push("connector_id = ?");
267
+ params.push(filter.connectorId);
268
+ }
269
+ if (filter.enabled !== void 0) {
270
+ clauses.push("enabled = ?");
271
+ params.push(filter.enabled ? 1 : 0);
272
+ }
273
+ const sql = `SELECT * FROM connection WHERE ${clauses.join(" AND ")} ORDER BY is_default DESC, created_at ASC`;
274
+ const rows = this.db.prepare(sql).all(...params).map(toConnectionRow);
275
+ if (filter.kind === void 0) return rows;
276
+ return rows.filter((row) => row.kinds.includes(filter.kind));
277
+ }
278
+ findConnection(workspaceId, ref) {
279
+ const row = this.db.prepare("SELECT * FROM connection WHERE workspace_id = ? AND (id = ? OR uid = ?) LIMIT 1").get(workspaceId, ref, ref);
280
+ return row === void 0 ? void 0 : toConnectionRow(row);
281
+ }
282
+ findConnectionById(id) {
283
+ const row = this.db.prepare("SELECT * FROM connection WHERE id = ? LIMIT 1").get(id);
284
+ return row === void 0 ? void 0 : toConnectionRow(row);
285
+ }
286
+ insertConnection(input) {
287
+ this.withImmediateTx(() => {
288
+ if (input.isDefault) this.db.prepare("UPDATE connection SET is_default = 0 WHERE workspace_id = ? AND connector_id = ?").run(input.workspaceId, input.connectorId);
289
+ this.db.prepare(`INSERT INTO connection (
290
+ id, workspace_id, uid, label, source, connector_id, kinds,
291
+ auth_type, ownership, enabled, is_default, allowed_hosts,
292
+ config, spec, created_at, updated_at
293
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(input.id, input.workspaceId, input.uid, input.label ?? null, input.source, input.connectorId, JSON.stringify(input.kinds), input.authType, input.ownership, input.enabled ? 1 : 0, input.isDefault ? 1 : 0, JSON.stringify(input.allowedHosts), JSON.stringify(input.config), input.spec === void 0 ? null : JSON.stringify(input.spec), input.now, input.now);
294
+ });
295
+ return this.findConnectionById(input.id);
296
+ }
297
+ updateConnection(id, input) {
298
+ return this.withImmediateTx(() => {
299
+ const existing = this.findConnectionById(id);
300
+ if (existing === void 0) return void 0;
301
+ if (input.isDefault === true) this.db.prepare("UPDATE connection SET is_default = 0 WHERE workspace_id = ? AND connector_id = ? AND id != ?").run(existing.workspaceId, existing.connectorId, id);
302
+ const nextUid = input.uid ?? existing.uid;
303
+ const nextLabel = input.label === void 0 ? existing.label ?? null : input.label;
304
+ const nextOwnership = input.ownership ?? existing.ownership;
305
+ const nextEnabled = input.enabled === void 0 ? existing.enabled : input.enabled;
306
+ const nextDefault = input.isDefault === void 0 ? existing.isDefault : input.isDefault;
307
+ const nextConfig = input.config === void 0 ? existing.config : input.config;
308
+ this.db.prepare(`UPDATE connection
309
+ SET uid = ?, label = ?, ownership = ?, enabled = ?, is_default = ?, config = ?, updated_at = ?
310
+ WHERE id = ?`).run(nextUid, nextLabel, nextOwnership, nextEnabled ? 1 : 0, nextDefault ? 1 : 0, JSON.stringify(nextConfig), input.now, id);
311
+ return this.findConnectionById(id);
312
+ });
313
+ }
314
+ deleteConnection(id) {
315
+ return this.db.prepare("DELETE FROM connection WHERE id = ?").run(id).changes > 0;
316
+ }
317
+ getCredential(connectionId, subjectType, subjectId) {
318
+ const row = this.db.prepare("SELECT * FROM credential WHERE connection_id = ? AND subject_type = ? AND subject_id = ? LIMIT 1").get(connectionId, subjectType, subjectId);
319
+ return row === void 0 ? void 0 : toCredentialRow(row);
320
+ }
321
+ upsertCredential(input) {
322
+ this.db.prepare(`INSERT INTO credential (connection_id, subject_type, subject_id, secret, status, last_error, expires_at, updated_at)
323
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
324
+ ON CONFLICT(connection_id, subject_type, subject_id) DO UPDATE SET
325
+ secret = excluded.secret,
326
+ status = excluded.status,
327
+ last_error = excluded.last_error,
328
+ expires_at = excluded.expires_at,
329
+ updated_at = excluded.updated_at`).run(input.connectionId, input.subjectType, input.subjectId, JSON.stringify(input.secret), input.status ?? "active", input.lastError ?? null, input.expiresAt ?? null, input.now);
330
+ return this.getCredential(input.connectionId, input.subjectType, input.subjectId);
331
+ }
332
+ markCredentialStatus(connectionId, subjectType, subjectId, status, lastError, now) {
333
+ this.db.prepare(`UPDATE credential SET status = ?, last_error = ?, updated_at = ?
334
+ WHERE connection_id = ? AND subject_type = ? AND subject_id = ?`).run(status, lastError ?? null, now, connectionId, subjectType, subjectId);
335
+ }
336
+ deleteCredential(connectionId, subjectType, subjectId) {
337
+ return this.db.prepare("DELETE FROM credential WHERE connection_id = ? AND subject_type = ? AND subject_id = ?").run(connectionId, subjectType, subjectId).changes > 0;
338
+ }
339
+ /**
340
+ * Non-destructive one-time import of existing `<home>/aikit/auth.json` Codex / Copilot OAuth logins
341
+ * into the `local` workspace so existing users stay signed in when upgrading to connections.db.
342
+ */
343
+ importLegacyAikitAuth(authFile, now) {
344
+ if (authFile === void 0 || !existsSync(authFile)) return;
345
+ if (this.getMeta("legacy_aikit_imported") === "1") return;
346
+ let parsed;
347
+ try {
348
+ parsed = JSON.parse(readFileSync(authFile, "utf-8"));
349
+ } catch {
350
+ return;
351
+ }
352
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return;
353
+ const entries = parsed;
354
+ const importOne = (legacyKey, connectorId) => {
355
+ const raw = entries[legacyKey];
356
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return;
357
+ const record = raw;
358
+ if (typeof record["access"] !== "string" || record["access"].length === 0) return;
359
+ const spec = DEFAULT_CONNECTOR_CATALOG.connectors[connectorId];
360
+ if (spec === void 0) return;
361
+ const uid = formatUid(connectorId, "default");
362
+ if (this.findConnection("local", uid) !== void 0) return;
363
+ const id = ConnectionID.create();
364
+ const existingSame = this.listConnections("local", { connectorId });
365
+ const enterpriseUrl = typeof record["enterpriseUrl"] === "string" ? record["enterpriseUrl"] : void 0;
366
+ this.insertConnection({
367
+ id,
368
+ workspaceId: "local",
369
+ uid,
370
+ label: spec.name,
371
+ source: "catalog",
372
+ connectorId,
373
+ kinds: spec.kinds,
374
+ authType: "oauth",
375
+ ownership: "personal",
376
+ enabled: true,
377
+ isDefault: existingSame.length === 0,
378
+ allowedHosts: spec.allowedHosts,
379
+ config: enterpriseUrl ? { fields: { enterpriseUrl } } : {},
380
+ now
381
+ });
382
+ const expires = typeof record["expires"] === "number" && record["expires"] > 0 ? record["expires"] : void 0;
383
+ const availableModelIds = Array.isArray(record["availableModelIds"]) ? record["availableModelIds"].filter((m) => typeof m === "string") : void 0;
384
+ const secret = {
385
+ type: "oauth",
386
+ accessToken: record["access"],
387
+ ...typeof record["refresh"] === "string" && record["refresh"].length > 0 ? { refreshToken: record["refresh"] } : {},
388
+ ...expires !== void 0 ? { expiresAt: expires } : {},
389
+ ...typeof record["accountId"] === "string" ? { accountId: record["accountId"] } : {},
390
+ ...typeof record["apiEndpoint"] === "string" ? { apiEndpoint: record["apiEndpoint"] } : {},
391
+ ...enterpriseUrl !== void 0 ? { enterpriseUrl } : {},
392
+ ...availableModelIds !== void 0 ? { availableModelIds } : {}
393
+ };
394
+ this.upsertCredential({
395
+ connectionId: id,
396
+ subjectType: "user",
397
+ subjectId: "local",
398
+ secret,
399
+ status: "active",
400
+ ...expires !== void 0 ? { expiresAt: expires } : {},
401
+ now
402
+ });
403
+ };
404
+ importOne("openai-codex", "com.openai.codex");
405
+ importOne("github-copilot", "com.github.copilot");
406
+ this.setMeta("legacy_aikit_imported", "1");
407
+ }
408
+ };
409
+ //#endregion
410
+ //#region src/connector/oauth.ts
411
+ const PENDING_TTL_MS = 6e5;
412
+ const HTTP_TIMEOUT_MS = 15e3;
413
+ const CODEX_DEVICE_TOKEN_URL = "https://auth.openai.com/api/accounts/deviceauth/token";
414
+ const CODEX_DEVICE_REDIRECT_URI = "https://auth.openai.com/deviceauth/callback";
415
+ const GITHUB_COPILOT_CLIENT_ID = "Iv1.b507a08c87ecfe98";
416
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
417
+ const randomState = () => randomBytes(24).toString("base64url");
418
+ const generatePkce = () => {
419
+ const verifier = randomBytes(32).toString("base64url");
420
+ return {
421
+ verifier,
422
+ challenge: createHash("sha256").update(verifier).digest("base64url")
423
+ };
424
+ };
425
+ const fetchJson = async (fetcher, url) => {
426
+ try {
427
+ const res = await fetcher(url, {
428
+ headers: { Accept: "application/json" },
429
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
430
+ });
431
+ if (!res.ok) return void 0;
432
+ const parsed = await res.json();
433
+ return isRecord(parsed) ? parsed : void 0;
434
+ } catch {
435
+ return;
436
+ }
437
+ };
438
+ /**
439
+ * RFC 9728 (Protected Resource Metadata) -> RFC 8414 (Authorization Server Metadata) / OIDC discovery.
440
+ */
441
+ const discoverOAuthMetadata = async (resourceUrl, fetcher = globalThis.fetch) => {
442
+ const parsed = new URL(resourceUrl);
443
+ const origin = parsed.origin;
444
+ const pathname = parsed.pathname.replace(/\/+$/, "");
445
+ const prmCandidates = [...pathname.length > 0 ? [`${origin}/.well-known/oauth-protected-resource${pathname}`] : [], `${origin}/.well-known/oauth-protected-resource`];
446
+ let authServerOrigin = origin;
447
+ let resource = resourceUrl;
448
+ let scopesSupported;
449
+ for (const candidate of prmCandidates) {
450
+ const prm = await fetchJson(fetcher, candidate);
451
+ if (!prm) continue;
452
+ if (typeof prm["resource"] === "string") resource = prm["resource"];
453
+ if (Array.isArray(prm["scopes_supported"])) scopesSupported = prm["scopes_supported"].filter((s) => typeof s === "string");
454
+ if (Array.isArray(prm["authorization_servers"]) && typeof prm["authorization_servers"][0] === "string") authServerOrigin = prm["authorization_servers"][0].replace(/\/+$/, "");
455
+ break;
456
+ }
457
+ const asUrl = new URL(authServerOrigin);
458
+ const asPath = asUrl.pathname.replace(/\/+$/, "");
459
+ const asmCandidates = asPath.length > 0 ? [
460
+ `${asUrl.origin}/.well-known/oauth-authorization-server${asPath}`,
461
+ `${asUrl.origin}/.well-known/openid-configuration${asPath}`,
462
+ `${authServerOrigin}/.well-known/openid-configuration`
463
+ ] : [`${asUrl.origin}/.well-known/oauth-authorization-server`, `${asUrl.origin}/.well-known/openid-configuration`];
464
+ for (const candidate of asmCandidates) {
465
+ const meta = await fetchJson(fetcher, candidate);
466
+ if (!meta) continue;
467
+ const authorizeEndpoint = meta["authorization_endpoint"];
468
+ const tokenEndpoint = meta["token_endpoint"];
469
+ if (typeof authorizeEndpoint === "string" && typeof tokenEndpoint === "string") return {
470
+ issuer: typeof meta["issuer"] === "string" ? meta["issuer"] : void 0,
471
+ authorizeEndpoint,
472
+ tokenEndpoint,
473
+ registrationEndpoint: typeof meta["registration_endpoint"] === "string" ? meta["registration_endpoint"] : void 0,
474
+ resource,
475
+ scopesSupported: scopesSupported ?? (Array.isArray(meta["scopes_supported"]) ? meta["scopes_supported"].filter((s) => typeof s === "string") : void 0),
476
+ clientIdMetadataDocumentSupported: meta["client_id_metadata_document_supported"] === true,
477
+ tokenEndpointAuthMethodsSupported: Array.isArray(meta["token_endpoint_auth_methods_supported"]) ? meta["token_endpoint_auth_methods_supported"].filter((s) => typeof s === "string") : void 0,
478
+ authorizationResponseIssParameterSupported: meta["authorization_response_iss_parameter_supported"] === true
479
+ };
480
+ }
481
+ throw new Error(`Could not discover OAuth metadata for ${resourceUrl}`);
482
+ };
483
+ const registerDynamicClient = async (registrationEndpoint, redirectUrl, fetcher) => {
484
+ const parsedRedirect = new URL(redirectUrl);
485
+ const redirectUris = parsedRedirect.hostname === "127.0.0.1" ? [redirectUrl, (() => {
486
+ const alt = new URL(parsedRedirect);
487
+ alt.hostname = "localhost";
488
+ return alt.href;
489
+ })()] : [redirectUrl];
490
+ const response = await fetcher(registrationEndpoint, {
491
+ method: "POST",
492
+ headers: {
493
+ "Content-Type": "application/json",
494
+ Accept: "application/json"
495
+ },
496
+ body: JSON.stringify({
497
+ client_name: OAuthCimd.CLIENT_NAME,
498
+ client_uri: OAuthCimd.CLIENT_URI,
499
+ logo_uri: OAuthCimd.LOGO_URI,
500
+ redirect_uris: redirectUris,
501
+ grant_types: ["authorization_code", "refresh_token"],
502
+ response_types: ["code"],
503
+ token_endpoint_auth_method: "none"
504
+ }),
505
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
506
+ });
507
+ if (!response.ok) {
508
+ const body = await response.text().catch(() => "");
509
+ throw new Error(`Dynamic client registration failed (${response.status}): ${body || response.statusText}`);
510
+ }
511
+ const data = await response.json();
512
+ if (!isRecord(data) || typeof data["client_id"] !== "string" || data["client_id"].length === 0) throw new Error("Dynamic client registration returned no client_id");
513
+ return {
514
+ clientId: data["client_id"],
515
+ clientSecret: typeof data["client_secret"] === "string" ? data["client_secret"] : void 0
516
+ };
517
+ };
518
+ var PendingOAuthStore = class {
519
+ entries = /* @__PURE__ */ new Map();
520
+ prune(now) {
521
+ for (const [key, value] of this.entries) if (value.expiresAt <= now) this.entries.delete(key);
522
+ }
523
+ put(state, entry) {
524
+ this.prune(Date.now());
525
+ this.entries.set(state, entry);
526
+ }
527
+ peek(state, workspaceId, actorId) {
528
+ this.prune(Date.now());
529
+ const entry = this.entries.get(state);
530
+ if (entry === void 0) return void 0;
531
+ if (entry.workspaceId !== workspaceId || entry.actorId !== actorId) return void 0;
532
+ return entry;
533
+ }
534
+ consume(state, workspaceId, actorId) {
535
+ const entry = this.peek(state, workspaceId, actorId);
536
+ if (entry !== void 0) this.entries.delete(state);
537
+ return entry;
538
+ }
539
+ delete(state) {
540
+ this.entries.delete(state);
541
+ }
542
+ };
543
+ const errorMessage = (cause) => cause instanceof Error && cause.message.trim().length > 0 ? cause.message : String(cause);
544
+ const parseTokenResponse = (data, client, fallbackRefresh, fallbackScopes) => {
545
+ if (!isRecord(data) || typeof data["access_token"] !== "string" || data["access_token"].length === 0) throw new Error("OAuth token endpoint returned no access_token");
546
+ const expiresIn = typeof data["expires_in"] === "number" && Number.isFinite(data["expires_in"]) ? data["expires_in"] : void 0;
547
+ const refreshToken = typeof data["refresh_token"] === "string" && data["refresh_token"].length > 0 ? data["refresh_token"] : fallbackRefresh;
548
+ const scopeStr = typeof data["scope"] === "string" ? data["scope"] : void 0;
549
+ const scopes = scopeStr ? scopeStr.split(/\s+/).map((s) => s.trim()).filter((s) => s.length > 0) : fallbackScopes;
550
+ return {
551
+ type: "oauth",
552
+ accessToken: data["access_token"],
553
+ ...refreshToken !== void 0 ? { refreshToken } : {},
554
+ ...expiresIn !== void 0 ? { expiresAt: Date.now() + expiresIn * 1e3 } : {},
555
+ ...typeof data["token_type"] === "string" ? { tokenType: data["token_type"] } : {},
556
+ ...scopes !== void 0 && scopes.length > 0 ? { scopes } : {},
557
+ client
558
+ };
559
+ };
560
+ const startAuthCodeFlow = (input) => Effect.tryPromise({
561
+ try: async () => {
562
+ const spec = input.connector.auth.oauth;
563
+ if (spec === void 0) throw new Error(`Connector "${input.connector.id}" does not support OAuth`);
564
+ const expiresAt = Date.now() + PENDING_TTL_MS;
565
+ if (spec.handler === "openai-codex") {
566
+ const flow = await createOpenAICodexAuthorizationFlow({
567
+ redirectUri: input.redirectUrl,
568
+ ...input.scopes && input.scopes.length > 0 ? { scope: input.scopes.join(" ") } : {}
569
+ });
570
+ input.store.put(flow.state, {
571
+ kind: "auth_code",
572
+ workspaceId: input.workspaceId,
573
+ actorId: input.actorId,
574
+ connectionId: input.connection.id,
575
+ connector: input.connector,
576
+ handler: "openai-codex",
577
+ redirectUrl: flow.redirectUri,
578
+ codeVerifier: flow.verifier,
579
+ client: { clientId: "openai-codex" },
580
+ scopes: input.scopes,
581
+ expiresAt
582
+ });
583
+ return {
584
+ state: flow.state,
585
+ authorizeUrl: flow.url,
586
+ redirectUrl: flow.redirectUri,
587
+ expiresAt
588
+ };
589
+ }
590
+ if (spec.handler === "github-copilot") throw new Error("GitHub Copilot uses device-code OAuth; start a device flow instead");
591
+ const fetcher = input.fetch ?? globalThis.fetch;
592
+ let authorizeEndpoint = spec.authorizeUrl;
593
+ let tokenEndpoint = spec.tokenUrl;
594
+ let registrationEndpoint;
595
+ let resource = input.connector.capabilities.mcp?.url;
596
+ let discovered;
597
+ const discoveryTarget = input.connector.capabilities.mcp?.url ?? input.connector.capabilities.integration?.baseUrl ?? input.connector.capabilities.provider?.baseUrl;
598
+ if (spec.discovery === "auto" || !authorizeEndpoint || !tokenEndpoint) {
599
+ if (!discoveryTarget) throw new Error(`Connector "${input.connector.id}" has no OAuth endpoints or discovery URL`);
600
+ discovered = await discoverOAuthMetadata(discoveryTarget, fetcher);
601
+ authorizeEndpoint = authorizeEndpoint ?? discovered.authorizeEndpoint;
602
+ tokenEndpoint = tokenEndpoint ?? discovered.tokenEndpoint;
603
+ registrationEndpoint = discovered.registrationEndpoint;
604
+ resource = discovered.resource ?? resource;
605
+ }
606
+ let clientId = spec.clientId;
607
+ let clientSecret;
608
+ let effectiveRedirectUrl = input.redirectUrl;
609
+ if (!clientId) {
610
+ const cimdResource = discoveryTarget ?? resource;
611
+ const cimd = cimdResource !== void 0 && OAuthCimd.offersClientMetadataDocument({
612
+ clientId: spec.clientId,
613
+ redirectUrl: input.redirectUrl
614
+ }) ? OAuthCimd.selectClientMetadataDocument({
615
+ resourceUrl: cimdResource,
616
+ redirectUrl: input.redirectUrl,
617
+ metadata: {
618
+ client_id_metadata_document_supported: discovered?.clientIdMetadataDocumentSupported,
619
+ token_endpoint_auth_methods_supported: discovered?.tokenEndpointAuthMethodsSupported,
620
+ authorization_response_iss_parameter_supported: discovered?.authorizationResponseIssParameterSupported
621
+ }
622
+ }) : void 0;
623
+ if (cimd !== void 0) {
624
+ clientId = cimd.clientId;
625
+ effectiveRedirectUrl = cimd.redirectUrl;
626
+ } else {
627
+ if (!registrationEndpoint) throw new Error(`OAuth server for "${input.connector.id}" does not advertise dynamic client registration`);
628
+ const registered = await registerDynamicClient(registrationEndpoint, effectiveRedirectUrl, fetcher);
629
+ clientId = registered.clientId;
630
+ clientSecret = registered.clientSecret;
631
+ }
632
+ }
633
+ const { verifier, challenge } = generatePkce();
634
+ const state = randomState();
635
+ const scopes = input.scopes ?? input.connection.config.scopes ?? spec.scopes;
636
+ const url = new URL(authorizeEndpoint);
637
+ url.searchParams.set("response_type", "code");
638
+ url.searchParams.set("client_id", clientId);
639
+ url.searchParams.set("redirect_uri", effectiveRedirectUrl);
640
+ url.searchParams.set("state", state);
641
+ if (spec.pkce !== false) {
642
+ url.searchParams.set("code_challenge", challenge);
643
+ url.searchParams.set("code_challenge_method", "S256");
644
+ }
645
+ if (scopes && scopes.length > 0) url.searchParams.set("scope", scopes.join(" "));
646
+ if (resource) url.searchParams.set("resource", resource);
647
+ const client = {
648
+ clientId,
649
+ ...clientSecret !== void 0 ? { clientSecret } : {},
650
+ authorizeEndpoint,
651
+ tokenEndpoint,
652
+ ...resource !== void 0 ? { resource } : {}
653
+ };
654
+ input.store.put(state, {
655
+ kind: "auth_code",
656
+ workspaceId: input.workspaceId,
657
+ actorId: input.actorId,
658
+ connectionId: input.connection.id,
659
+ connector: input.connector,
660
+ redirectUrl: effectiveRedirectUrl,
661
+ codeVerifier: verifier,
662
+ client,
663
+ ...discovered?.issuer !== void 0 ? { issuer: discovered.issuer } : {},
664
+ ...discovered?.authorizationResponseIssParameterSupported !== void 0 ? { issParameterSupported: discovered.authorizationResponseIssParameterSupported } : {},
665
+ scopes,
666
+ expiresAt
667
+ });
668
+ return {
669
+ state,
670
+ authorizeUrl: url.toString(),
671
+ redirectUrl: effectiveRedirectUrl,
672
+ expiresAt
673
+ };
674
+ },
675
+ catch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) })
676
+ });
677
+ const finishAuthCodeFlow = (input) => Effect.tryPromise({
678
+ try: async () => {
679
+ const pending = input.store.peek(input.state, input.workspaceId, input.actorId);
680
+ if (pending === void 0 || pending.kind !== "auth_code") throw new Error("Invalid, expired, or unauthorized OAuth state");
681
+ if (pending.handler === "openai-codex") {
682
+ const parsedInput = parseOpenAICodexAuthorizationInput(input.codeOrUrl);
683
+ const code = parsedInput.code ?? input.codeOrUrl.trim();
684
+ if (parsedInput.state !== void 0 && parsedInput.state !== input.state) throw new Error("OAuth state mismatch");
685
+ if (code.length === 0) throw new Error("Missing authorization code");
686
+ input.store.consume(input.state, input.workspaceId, input.actorId);
687
+ const result = await exchangeOpenAICodexAuthorizationCode(code, pending.codeVerifier, pending.redirectUrl);
688
+ if (result.type !== "success") throw new Error(result.message);
689
+ const accountId = getOpenAICodexAccountId(result.access) ?? void 0;
690
+ return {
691
+ connectionId: pending.connectionId,
692
+ secret: {
693
+ type: "oauth",
694
+ accessToken: result.access,
695
+ refreshToken: result.refresh,
696
+ expiresAt: result.expires,
697
+ ...accountId !== void 0 ? {
698
+ accountId,
699
+ accountLabel: accountId
700
+ } : {}
701
+ }
702
+ };
703
+ }
704
+ const trimmed = input.codeOrUrl.trim();
705
+ let code;
706
+ let exchangeRedirectUrl = pending.redirectUrl;
707
+ if (URL.canParse(trimmed)) {
708
+ const callbackUrl = new URL(trimmed);
709
+ const matchedRedirect = OAuthCimd.matchCallbackRedirect(callbackUrl, new URL(pending.redirectUrl));
710
+ if (matchedRedirect === void 0) throw new Error("The redirect URL does not match this sign-in's redirect URI");
711
+ const callbackError = callbackUrl.searchParams.get("error");
712
+ if (callbackError !== null) throw new Error(callbackUrl.searchParams.get("error_description") ?? callbackError);
713
+ if (callbackUrl.searchParams.get("state") !== input.state) throw new Error("OAuth state mismatch");
714
+ const iss = callbackUrl.searchParams.get("iss") ?? void 0;
715
+ if (pending.issParameterSupported === true) {
716
+ if (iss === void 0) throw new Error("OAuth authorization response is missing required issuer (iss) parameter");
717
+ if (pending.issuer === void 0 || iss !== pending.issuer) throw new Error(`OAuth issuer mismatch: expected ${pending.issuer ?? "(unknown)"}, got ${iss}`);
718
+ } else if (iss !== void 0) {
719
+ if (pending.issuer === void 0) throw new Error(`The authorization response names issuer ${iss}, but no authorization server metadata was discovered to check it against`);
720
+ if (iss !== pending.issuer) throw new Error(`OAuth issuer mismatch: expected ${pending.issuer}, got ${iss}`);
721
+ }
722
+ const parsedCode = callbackUrl.searchParams.get("code");
723
+ if (parsedCode === null || parsedCode.length === 0) throw new Error("Missing authorization code");
724
+ code = parsedCode;
725
+ exchangeRedirectUrl = matchedRedirect;
726
+ } else {
727
+ if (pending.issParameterSupported === true) throw new Error("Expected the full redirect URL from the browser's address bar");
728
+ const parsedInput = parseOpenAICodexAuthorizationInput(trimmed);
729
+ code = parsedInput.code ?? trimmed;
730
+ if (parsedInput.state !== void 0 && parsedInput.state !== input.state) throw new Error("OAuth state mismatch");
731
+ if (code.length === 0) throw new Error("Missing authorization code");
732
+ }
733
+ const tokenEndpoint = pending.client.tokenEndpoint;
734
+ if (!tokenEndpoint) throw new Error("Missing OAuth token endpoint");
735
+ const consumed = input.store.consume(input.state, input.workspaceId, input.actorId);
736
+ if (consumed === void 0 || consumed.kind !== "auth_code") throw new Error("Invalid, expired, or unauthorized OAuth state");
737
+ const body = new URLSearchParams({
738
+ grant_type: "authorization_code",
739
+ client_id: pending.client.clientId,
740
+ code,
741
+ redirect_uri: exchangeRedirectUrl,
742
+ code_verifier: pending.codeVerifier
743
+ });
744
+ if (pending.client.clientSecret) body.set("client_secret", pending.client.clientSecret);
745
+ if (pending.client.resource) body.set("resource", pending.client.resource);
746
+ const response = await (input.fetch ?? globalThis.fetch)(tokenEndpoint, {
747
+ method: "POST",
748
+ headers: {
749
+ "Content-Type": "application/x-www-form-urlencoded",
750
+ Accept: "application/json"
751
+ },
752
+ body,
753
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
754
+ });
755
+ if (!response.ok) {
756
+ const text = await response.text().catch(() => "");
757
+ throw new Error(`OAuth token exchange failed (${response.status}): ${text || response.statusText}`);
758
+ }
759
+ const data = await response.json();
760
+ return {
761
+ connectionId: pending.connectionId,
762
+ secret: parseTokenResponse(data, pending.client, void 0, pending.scopes)
763
+ };
764
+ },
765
+ catch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) })
766
+ });
767
+ const startDeviceCodeFlow = (input) => Effect.tryPromise({
768
+ try: async () => {
769
+ const spec = input.connector.auth.oauth;
770
+ if (spec === void 0 || !spec.grants.includes("device_code")) throw new Error(`Connector "${input.connector.id}" does not support device-code OAuth`);
771
+ const state = randomState();
772
+ const now = Date.now();
773
+ if (spec.handler === "github-copilot") {
774
+ const enterpriseUrl = input.enterpriseUrl ?? input.connection.config.fields?.["enterpriseUrl"];
775
+ const domain = normalizeGitHubDomain(enterpriseUrl);
776
+ const flow = await createGitHubCopilotDeviceFlow({
777
+ ...domain !== void 0 ? { domain } : {},
778
+ ...input.fetch !== void 0 ? { fetch: input.fetch } : {}
779
+ });
780
+ const expiresAt = now + (flow.expiresInSeconds ?? 900) * 1e3;
781
+ input.store.put(state, {
782
+ kind: "device_code",
783
+ workspaceId: input.workspaceId,
784
+ actorId: input.actorId,
785
+ connectionId: input.connection.id,
786
+ connector: input.connector,
787
+ handler: "github-copilot",
788
+ deviceCode: flow.deviceCode,
789
+ userCode: flow.userCode,
790
+ verificationUri: flow.verificationUri,
791
+ intervalSeconds: flow.intervalSeconds,
792
+ ...enterpriseUrl !== void 0 ? { enterpriseUrl } : {},
793
+ expiresAt
794
+ });
795
+ return {
796
+ state,
797
+ verificationUri: flow.verificationUri,
798
+ userCode: flow.userCode,
799
+ intervalSeconds: flow.intervalSeconds,
800
+ expiresAt
801
+ };
802
+ }
803
+ if (spec.handler === "openai-codex") {
804
+ const device = await createOpenAICodexDeviceAuth();
805
+ const expiresAt = now + 9e5;
806
+ input.store.put(state, {
807
+ kind: "device_code",
808
+ workspaceId: input.workspaceId,
809
+ actorId: input.actorId,
810
+ connectionId: input.connection.id,
811
+ connector: input.connector,
812
+ handler: "openai-codex",
813
+ deviceCode: device.deviceAuthId,
814
+ userCode: device.userCode,
815
+ verificationUri: device.verificationUri,
816
+ intervalSeconds: device.intervalSeconds,
817
+ expiresAt
818
+ });
819
+ return {
820
+ state,
821
+ verificationUri: device.verificationUri,
822
+ userCode: device.userCode,
823
+ intervalSeconds: device.intervalSeconds,
824
+ expiresAt
825
+ };
826
+ }
827
+ throw new Error(`Unsupported device-code handler for "${input.connector.id}"`);
828
+ },
829
+ catch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) })
830
+ });
831
+ /**
832
+ * Performs one non-blocking poll step for an active device-code login so RPC/UI callers never hang.
833
+ */
834
+ const pollDeviceCodeStep = (input) => Effect.tryPromise({
835
+ try: async () => {
836
+ const pending = input.store.peek(input.state, input.workspaceId, input.actorId);
837
+ if (pending === void 0 || pending.kind !== "device_code") throw new Error("Invalid, expired, or unauthorized device-code state");
838
+ const fetcher = input.fetch ?? globalThis.fetch;
839
+ if (pending.handler === "github-copilot") {
840
+ const domain = normalizeGitHubDomain(pending.enterpriseUrl) ?? "github.com";
841
+ const response = await fetcher(`https://${domain}/login/oauth/access_token`, {
842
+ method: "POST",
843
+ headers: {
844
+ Accept: "application/json",
845
+ "Content-Type": "application/json"
846
+ },
847
+ body: JSON.stringify({
848
+ client_id: GITHUB_COPILOT_CLIENT_ID,
849
+ device_code: pending.deviceCode,
850
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
851
+ }),
852
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
853
+ });
854
+ if (!response.ok) throw new Error(`GitHub device token poll failed (${response.status})`);
855
+ const data = await response.json();
856
+ if (!isRecord(data)) throw new Error("Invalid GitHub device token response");
857
+ if (typeof data["access_token"] === "string" && data["access_token"].length > 0) {
858
+ input.store.delete(input.state);
859
+ const accessToken = data["access_token"];
860
+ const user = await fetchGitHubCopilotUser(accessToken, {
861
+ domain,
862
+ fetch: fetcher
863
+ });
864
+ const entitlementIssue = user ? gitHubCopilotEntitlementError({
865
+ chat_enabled: user.chatEnabled,
866
+ can_signup_for_limited: user.canSignupForLimited
867
+ }) : void 0;
868
+ if (entitlementIssue) throw new Error(entitlementIssue);
869
+ const baseURL = user?.apiEndpoint ?? (pending.enterpriseUrl ? gitHubCopilotBaseUrl({ enterpriseUrl: pending.enterpriseUrl }) : void 0);
870
+ const availableModelIds = (await fetchGitHubCopilotModels(accessToken, {
871
+ domain,
872
+ ...baseURL !== void 0 ? { baseURL } : {},
873
+ fetch: fetcher
874
+ }).catch(() => void 0))?.map((m) => m.id);
875
+ return {
876
+ status: "complete",
877
+ connectionId: pending.connectionId,
878
+ secret: {
879
+ type: "oauth",
880
+ accessToken,
881
+ refreshToken: accessToken,
882
+ ...user?.apiEndpoint !== void 0 ? { apiEndpoint: user.apiEndpoint } : {},
883
+ ...pending.enterpriseUrl !== void 0 ? { enterpriseUrl: pending.enterpriseUrl } : {},
884
+ ...availableModelIds !== void 0 && availableModelIds.length > 0 ? { availableModelIds } : {},
885
+ accountLabel: pending.enterpriseUrl ?? "github.com"
886
+ }
887
+ };
888
+ }
889
+ const err = typeof data["error"] === "string" ? data["error"] : void 0;
890
+ if (err === "authorization_pending") return {
891
+ status: "pending",
892
+ intervalSeconds: pending.intervalSeconds
893
+ };
894
+ if (err === "slow_down") return {
895
+ status: "pending",
896
+ intervalSeconds: typeof data["interval"] === "number" && data["interval"] > 0 ? data["interval"] : pending.intervalSeconds + 5
897
+ };
898
+ input.store.delete(input.state);
899
+ const desc = typeof data["error_description"] === "string" ? `: ${data["error_description"]}` : "";
900
+ throw new Error(`GitHub device authorization failed: ${err ?? "unknown"}${desc}`);
901
+ }
902
+ const response = await fetcher(CODEX_DEVICE_TOKEN_URL, {
903
+ method: "POST",
904
+ headers: { "Content-Type": "application/json" },
905
+ body: JSON.stringify({
906
+ device_auth_id: pending.deviceCode,
907
+ user_code: pending.userCode
908
+ }),
909
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
910
+ });
911
+ if (response.status === 403 || response.status === 404) return {
912
+ status: "pending",
913
+ intervalSeconds: pending.intervalSeconds
914
+ };
915
+ if (response.ok) {
916
+ const data = await response.json();
917
+ if (!isRecord(data) || typeof data["authorization_code"] !== "string" || typeof data["code_verifier"] !== "string") throw new Error("Invalid OpenAI Codex device token response");
918
+ input.store.delete(input.state);
919
+ const exchanged = await exchangeOpenAICodexAuthorizationCode(data["authorization_code"], data["code_verifier"], CODEX_DEVICE_REDIRECT_URI);
920
+ if (exchanged.type !== "success") throw new Error(exchanged.message);
921
+ const accountId = getOpenAICodexAccountId(exchanged.access) ?? void 0;
922
+ return {
923
+ status: "complete",
924
+ connectionId: pending.connectionId,
925
+ secret: {
926
+ type: "oauth",
927
+ accessToken: exchanged.access,
928
+ refreshToken: exchanged.refresh,
929
+ expiresAt: exchanged.expires,
930
+ ...accountId !== void 0 ? {
931
+ accountId,
932
+ accountLabel: accountId
933
+ } : {}
934
+ }
935
+ };
936
+ }
937
+ const text = await response.text().catch(() => "");
938
+ let errorCode;
939
+ try {
940
+ const parsed = JSON.parse(text);
941
+ const err = isRecord(parsed) ? parsed["error"] : void 0;
942
+ errorCode = isRecord(err) ? err["code"] : err;
943
+ } catch {}
944
+ if (errorCode === "deviceauth_authorization_pending") return {
945
+ status: "pending",
946
+ intervalSeconds: pending.intervalSeconds
947
+ };
948
+ if (errorCode === "slow_down") return {
949
+ status: "pending",
950
+ intervalSeconds: pending.intervalSeconds + 5
951
+ };
952
+ input.store.delete(input.state);
953
+ throw new Error(`OpenAI Codex device authorization failed (${response.status})`);
954
+ },
955
+ catch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) })
956
+ });
957
+ /**
958
+ * Network refresh step (called under the broker's double-checked lock).
959
+ */
960
+ const refreshOAuthSecret = async (connector, current, fetcher = globalThis.fetch) => {
961
+ const handler = connector.auth.oauth?.handler;
962
+ if (handler === "github-copilot") return current;
963
+ if (!current.refreshToken) throw new Error(`OAuth token for "${connector.id}" expired and has no refresh token`);
964
+ if (handler === "openai-codex") {
965
+ const refreshed = await refreshOpenAICodexToken(current.refreshToken);
966
+ const accountId = getOpenAICodexAccountId(refreshed.access) ?? current.accountId;
967
+ return {
968
+ ...current,
969
+ accessToken: refreshed.access,
970
+ refreshToken: refreshed.refresh,
971
+ expiresAt: refreshed.expires,
972
+ ...accountId !== void 0 ? {
973
+ accountId,
974
+ accountLabel: accountId
975
+ } : {}
976
+ };
977
+ }
978
+ const tokenEndpoint = current.client?.tokenEndpoint ?? connector.auth.oauth?.tokenUrl;
979
+ const clientId = current.client?.clientId ?? connector.auth.oauth?.clientId;
980
+ if (!tokenEndpoint || !clientId) throw new Error(`Missing OAuth token endpoint or client_id for "${connector.id}" refresh`);
981
+ const body = new URLSearchParams({
982
+ grant_type: "refresh_token",
983
+ client_id: clientId,
984
+ refresh_token: current.refreshToken
985
+ });
986
+ if (current.client?.clientSecret) body.set("client_secret", current.client.clientSecret);
987
+ if (current.client?.resource) body.set("resource", current.client.resource);
988
+ const response = await fetcher(tokenEndpoint, {
989
+ method: "POST",
990
+ headers: {
991
+ "Content-Type": "application/x-www-form-urlencoded",
992
+ Accept: "application/json"
993
+ },
994
+ body,
995
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
996
+ });
997
+ if (!response.ok) {
998
+ const text = await response.text().catch(() => "");
999
+ throw new Error(`OAuth refresh failed (${response.status}): ${text || response.statusText}`);
1000
+ }
1001
+ const data = await response.json();
1002
+ const refreshed = parseTokenResponse(data, current.client ?? {
1003
+ clientId,
1004
+ tokenEndpoint
1005
+ }, current.refreshToken, current.scopes);
1006
+ return {
1007
+ ...current,
1008
+ ...refreshed
1009
+ };
1010
+ };
1011
+ /**
1012
+ * Pure request-auth derivation (`toAuth` in Pi's model): maps a valid stored OAuth secret to
1013
+ * `{ token, headers?, baseUrl? }` without performing any network calls.
1014
+ */
1015
+ const deriveOAuthRequestAuth = (connector, secret) => {
1016
+ const handler = connector.auth.oauth?.handler;
1017
+ if (handler === "github-copilot") {
1018
+ const creds = {
1019
+ access: secret.accessToken,
1020
+ refresh: secret.refreshToken ?? secret.accessToken,
1021
+ expires: 0,
1022
+ ...secret.enterpriseUrl !== void 0 ? { enterpriseUrl: secret.enterpriseUrl } : {},
1023
+ ...secret.apiEndpoint !== void 0 ? { apiEndpoint: secret.apiEndpoint } : {},
1024
+ ...secret.availableModelIds !== void 0 ? { availableModelIds: [...secret.availableModelIds] } : {}
1025
+ };
1026
+ return {
1027
+ token: secret.accessToken,
1028
+ headers: gitHubCopilotHeaders(creds),
1029
+ baseUrl: secret.apiEndpoint ?? (secret.enterpriseUrl ? gitHubCopilotBaseUrl({ enterpriseUrl: secret.enterpriseUrl }) : void 0)
1030
+ };
1031
+ }
1032
+ if (handler === "openai-codex") {
1033
+ const creds = {
1034
+ access: secret.accessToken,
1035
+ refresh: secret.refreshToken ?? "",
1036
+ expires: secret.expiresAt ?? 0,
1037
+ accountId: secret.accountId ?? getOpenAICodexAccountId(secret.accessToken) ?? ""
1038
+ };
1039
+ return {
1040
+ token: secret.accessToken,
1041
+ headers: creds.accountId ? openAICodexHeaders(creds) : void 0
1042
+ };
1043
+ }
1044
+ return {
1045
+ token: secret.accessToken,
1046
+ headers: { Authorization: `Bearer ${secret.accessToken}` }
1047
+ };
1048
+ };
1049
+ const applyHeaderInjection = (inject, token) => {
1050
+ if (inject === void 0) return void 0;
1051
+ return { [inject.name]: `${inject.prefix ?? ""}${token}` };
1052
+ };
1053
+ //#endregion
1054
+ //#region src/connector/service.ts
1055
+ const DEFAULT_OAUTH_MIN_VALIDITY_MS = 3e5;
1056
+ var Service = class extends Context.Service()("@codeworksh/cli/connector/service") {};
1057
+ const subjectFor = (row, actor) => row.ownership === "personal" ? {
1058
+ type: "user",
1059
+ id: actor.id
1060
+ } : {
1061
+ type: "app",
1062
+ id: actor.scope
1063
+ };
1064
+ const readEnvVar = (env, vars) => {
1065
+ for (const name of vars) {
1066
+ const raw = env[name]?.trim();
1067
+ if (raw !== void 0 && raw.length > 0) return {
1068
+ name,
1069
+ value: raw
1070
+ };
1071
+ }
1072
+ };
1073
+ const summarizeStored = (row, cred, now) => {
1074
+ let status = cred?.status ?? "not_connected";
1075
+ if (status === "active" && row.authType === "oauth" && cred?.expiresAt !== void 0 && cred.expiresAt <= now && cred.secret.type === "oauth" && !cred.secret.refreshToken) status = "expired";
1076
+ const sourceLabel = row.authType === "oauth" ? `OAuth (${row.ownership})` : `API key (${row.ownership})`;
1077
+ const accountLabel = cred?.secret.type === "oauth" ? cred.secret.accountLabel : void 0;
1078
+ return {
1079
+ id: row.id,
1080
+ uid: row.uid,
1081
+ connectorId: row.connectorId,
1082
+ workspaceId: row.workspaceId,
1083
+ ...row.label !== void 0 ? { label: row.label } : {},
1084
+ source: row.source,
1085
+ kinds: row.kinds,
1086
+ authType: row.authType,
1087
+ ownership: row.ownership,
1088
+ enabled: row.enabled,
1089
+ isDefault: row.isDefault,
1090
+ status,
1091
+ sourceLabel,
1092
+ ...accountLabel !== void 0 ? { accountLabel } : {},
1093
+ ...cred?.lastError !== void 0 ? { lastError: cred.lastError } : {},
1094
+ ...cred?.expiresAt !== void 0 ? { expiresAt: cred.expiresAt } : {},
1095
+ allowedHosts: row.allowedHosts,
1096
+ config: row.config,
1097
+ readOnly: false,
1098
+ createdAt: row.createdAt,
1099
+ updatedAt: row.updatedAt
1100
+ };
1101
+ };
1102
+ const summarizeEnv = (spec, workspaceId, envVar) => ({
1103
+ id: `env:${spec.id}`,
1104
+ uid: formatUid(spec.id, "env"),
1105
+ connectorId: spec.id,
1106
+ workspaceId,
1107
+ label: `${spec.name} (host env)`,
1108
+ source: "catalog",
1109
+ kinds: spec.kinds,
1110
+ authType: "env",
1111
+ ownership: "shared",
1112
+ enabled: true,
1113
+ isDefault: false,
1114
+ status: "active",
1115
+ sourceLabel: `$${envVar}`,
1116
+ envVar,
1117
+ allowedHosts: spec.allowedHosts,
1118
+ config: {},
1119
+ readOnly: true,
1120
+ createdAt: 0,
1121
+ updatedAt: 0
1122
+ });
1123
+ const resolveFields = (spec, row, env) => {
1124
+ const fieldSpecs = row.authType === "oauth" ? spec.auth.oauth?.fields : spec.auth.apikey?.fields;
1125
+ const merged = { ...row.config.fields };
1126
+ if (fieldSpecs) {
1127
+ for (const field of fieldSpecs) if (merged[field.key] === void 0 && field.envFallback) {
1128
+ const val = env[field.envFallback]?.trim();
1129
+ if (val) merged[field.key] = val;
1130
+ }
1131
+ }
1132
+ return Object.keys(merged).length > 0 ? merged : void 0;
1133
+ };
1134
+ const validateHost = (connectionId, uid, allowedHosts, targetHost) => {
1135
+ if (targetHost === void 0 || allowedHosts.length === 0) return Effect.void;
1136
+ if (hostMatches(targetHost, allowedHosts)) return Effect.void;
1137
+ return Effect.fail(new HostNotAllowedError({
1138
+ connectionId,
1139
+ uid,
1140
+ host: targetHost,
1141
+ allowedHosts: [...allowedHosts],
1142
+ message: `Host "${targetHost}" is not allowed for connection "${uid}"`
1143
+ }));
1144
+ };
1145
+ const make = (options = {}) => Effect.acquireRelease(Effect.gen(function* () {
1146
+ const home = (yield* Global.resolve(options.home === void 0 ? {} : { home: options.home })).home;
1147
+ const db = new ConnectionsDb(options.dbPath ?? connectionsDbPath(home));
1148
+ const legacyAuthFile = Global.authFile(options.home === void 0 ? void 0 : home) ?? Global.authFile(home);
1149
+ db.importLegacyAikitAuth(legacyAuthFile, yield* Clock.currentTimeMillis);
1150
+ let cachedCatalog = loadLocalCatalog(home);
1151
+ const pendingOAuth = new PendingOAuthStore();
1152
+ const refreshLocks = /* @__PURE__ */ new Map();
1153
+ const getEnv = () => options.env ?? process.env;
1154
+ const semaphoreFor = (key) => {
1155
+ let lock = refreshLocks.get(key);
1156
+ if (lock === void 0) {
1157
+ lock = Semaphore.makeUnsafe(1);
1158
+ refreshLocks.set(key, lock);
1159
+ }
1160
+ return lock;
1161
+ };
1162
+ const specForRow = (row) => row.source === "custom" ? row.spec : cachedCatalog.connectors[row.connectorId];
1163
+ const currentCatalog = (refresh) => Effect.gen(function* () {
1164
+ if (refresh) cachedCatalog = yield* fetchCatalog({
1165
+ home,
1166
+ url: options.catalogUrl,
1167
+ fetch: options.fetch
1168
+ });
1169
+ return cachedCatalog;
1170
+ });
1171
+ const resolveRowSecret = Effect.fn("Connector.resolveRowSecret")(function* (row, actor, input) {
1172
+ const spec = specForRow(row);
1173
+ if (spec === void 0) return yield* new ConnectorNotFoundError({
1174
+ connectorId: row.connectorId,
1175
+ message: `Connector "${row.connectorId}" is not in the catalog`
1176
+ });
1177
+ yield* validateHost(row.id, row.uid, row.allowedHosts, input.targetHost);
1178
+ if (!row.enabled) return yield* new AuthRequiredError({
1179
+ connectionId: row.id,
1180
+ uid: row.uid,
1181
+ connectorId: row.connectorId,
1182
+ reason: "not_connected",
1183
+ message: `Connection "${row.uid}" is disabled`
1184
+ });
1185
+ const subject = subjectFor(row, actor);
1186
+ const cred = db.getCredential(row.id, subject.type, subject.id);
1187
+ if (cred === void 0) return yield* new AuthRequiredError({
1188
+ connectionId: row.id,
1189
+ uid: row.uid,
1190
+ connectorId: row.connectorId,
1191
+ reason: "not_connected",
1192
+ message: `Connection "${row.uid}" has not been authenticated yet`
1193
+ });
1194
+ const fields = resolveFields(spec, row, getEnv());
1195
+ if (row.authType === "apikey") {
1196
+ if (cred.secret.type !== "apikey" || cred.secret.apiKey.length === 0) return yield* new AuthRequiredError({
1197
+ connectionId: row.id,
1198
+ uid: row.uid,
1199
+ connectorId: row.connectorId,
1200
+ reason: "not_connected",
1201
+ message: `Connection "${row.uid}" has no API key stored`
1202
+ });
1203
+ const headers = applyHeaderInjection(spec.auth.apikey?.inject, cred.secret.apiKey);
1204
+ return {
1205
+ connectionId: row.id,
1206
+ uid: row.uid,
1207
+ token: Redacted.make(cred.secret.apiKey),
1208
+ ...headers !== void 0 ? { headers } : {},
1209
+ ...spec.capabilities.provider?.baseUrl !== void 0 ? { baseUrl: spec.capabilities.provider.baseUrl } : {},
1210
+ ...fields !== void 0 ? { fields } : {},
1211
+ sourceLabel: `API key (${row.ownership})`
1212
+ };
1213
+ }
1214
+ if (cred.secret.type !== "oauth") return yield* new AuthRequiredError({
1215
+ connectionId: row.id,
1216
+ uid: row.uid,
1217
+ connectorId: row.connectorId,
1218
+ reason: "not_connected",
1219
+ message: `Connection "${row.uid}" is missing OAuth credentials`
1220
+ });
1221
+ const minValidity = Math.max(DEFAULT_OAUTH_MIN_VALIDITY_MS, input.minValidityMs ?? 0);
1222
+ const needsRefresh = (secret, now) => secret.expiresAt !== void 0 && secret.expiresAt > 0 && now + minValidity >= secret.expiresAt;
1223
+ let activeSecret = cred.secret;
1224
+ if (needsRefresh(activeSecret, yield* Clock.currentTimeMillis)) {
1225
+ const lockKey = `${row.id}:${subject.type}:${subject.id}`;
1226
+ activeSecret = yield* semaphoreFor(lockKey).withPermits(1)(Effect.gen(function* () {
1227
+ const latest = db.getCredential(row.id, subject.type, subject.id);
1228
+ if (latest === void 0 || latest.secret.type !== "oauth") return yield* new AuthRequiredError({
1229
+ connectionId: row.id,
1230
+ uid: row.uid,
1231
+ connectorId: row.connectorId,
1232
+ reason: "not_connected",
1233
+ message: `Connection "${row.uid}" was disconnected`
1234
+ });
1235
+ if (!needsRefresh(latest.secret, yield* Clock.currentTimeMillis)) return latest.secret;
1236
+ return yield* Effect.uninterruptible(Effect.tryPromise({
1237
+ try: () => refreshOAuthSecret(spec, latest.secret, options.fetch),
1238
+ catch: (cause) => cause instanceof Error ? cause.message : String(cause)
1239
+ }).pipe(Effect.tap((refreshed) => Clock.currentTimeMillis.pipe(Effect.map((now) => {
1240
+ db.withImmediateTx(() => {
1241
+ db.upsertCredential({
1242
+ connectionId: row.id,
1243
+ subjectType: subject.type,
1244
+ subjectId: subject.id,
1245
+ secret: refreshed,
1246
+ status: "active",
1247
+ ...refreshed.expiresAt !== void 0 ? { expiresAt: refreshed.expiresAt } : {},
1248
+ now
1249
+ });
1250
+ });
1251
+ }))), Effect.catch((message) => Clock.currentTimeMillis.pipe(Effect.flatMap((now) => Effect.sync(() => {
1252
+ db.markCredentialStatus(row.id, subject.type, subject.id, "expired", message, now);
1253
+ })), Effect.flatMap(() => Effect.fail(new AuthRequiredError({
1254
+ connectionId: row.id,
1255
+ uid: row.uid,
1256
+ connectorId: row.connectorId,
1257
+ reason: "expired",
1258
+ message: `OAuth refresh failed for "${row.uid}": ${message}`
1259
+ })))))));
1260
+ }));
1261
+ }
1262
+ const derived = deriveOAuthRequestAuth(spec, activeSecret);
1263
+ return {
1264
+ connectionId: row.id,
1265
+ uid: row.uid,
1266
+ token: Redacted.make(derived.token),
1267
+ ...derived.headers !== void 0 ? { headers: derived.headers } : {},
1268
+ ...derived.baseUrl !== void 0 ? { baseUrl: derived.baseUrl } : {},
1269
+ ...fields !== void 0 ? { fields } : {},
1270
+ sourceLabel: `OAuth (${row.ownership})`,
1271
+ ...activeSecret.expiresAt !== void 0 ? { expiresAt: activeSecret.expiresAt } : {}
1272
+ };
1273
+ });
1274
+ const resolveEnvFallback = (spec, targetHost) => Effect.gen(function* () {
1275
+ const envSpec = spec.auth.env;
1276
+ if (envSpec === void 0) return void 0;
1277
+ const found = readEnvVar(getEnv(), envSpec.vars);
1278
+ if (found === void 0) return void 0;
1279
+ const id = `env:${spec.id}`;
1280
+ const uid = formatUid(spec.id, "env");
1281
+ yield* validateHost(id, uid, spec.allowedHosts, targetHost);
1282
+ const headers = applyHeaderInjection(envSpec.inject, found.value);
1283
+ return {
1284
+ connectionId: id,
1285
+ uid,
1286
+ token: Redacted.make(found.value),
1287
+ ...headers !== void 0 ? { headers } : {},
1288
+ ...spec.capabilities.provider?.baseUrl !== void 0 ? { baseUrl: spec.capabilities.provider.baseUrl } : {},
1289
+ sourceLabel: `$${found.name}`
1290
+ };
1291
+ });
1292
+ return {
1293
+ db,
1294
+ service: {
1295
+ catalog: (filter = {}) => Effect.gen(function* () {
1296
+ const cat = yield* currentCatalog(filter.refresh);
1297
+ const catalogFilter = {
1298
+ kind: filter.kind,
1299
+ category: filter.category,
1300
+ query: filter.query
1301
+ };
1302
+ return {
1303
+ schemaVersion: cat.schemaVersion,
1304
+ generatedAt: cat.generatedAt,
1305
+ categories: cat.categories,
1306
+ connectors: filterConnectors(cat, catalogFilter)
1307
+ };
1308
+ }),
1309
+ list: (filter = {}) => Effect.gen(function* () {
1310
+ const actor = yield* Actor.Current;
1311
+ const now = yield* Clock.currentTimeMillis;
1312
+ const summaries = db.listConnections(actor.scope, {
1313
+ kind: filter.kind,
1314
+ connectorId: filter.connectorId,
1315
+ enabled: filter.enabled
1316
+ }).map((row) => {
1317
+ const subject = subjectFor(row, actor);
1318
+ return summarizeStored(row, db.getCredential(row.id, subject.type, subject.id), now);
1319
+ });
1320
+ if (filter.includeEnv !== false && filter.enabled !== false) {
1321
+ const env = getEnv();
1322
+ for (const spec of Object.values(cachedCatalog.connectors)) {
1323
+ if (filter.kind !== void 0 && !spec.kinds.includes(filter.kind)) continue;
1324
+ if (filter.connectorId !== void 0 && spec.id !== filter.connectorId) continue;
1325
+ if (spec.auth.env === void 0) continue;
1326
+ const found = readEnvVar(env, spec.auth.env.vars);
1327
+ if (found !== void 0) summaries.push(summarizeEnv(spec, actor.scope, found.name));
1328
+ }
1329
+ }
1330
+ return summaries;
1331
+ }),
1332
+ get: (ref) => Effect.gen(function* () {
1333
+ const actor = yield* Actor.Current;
1334
+ const now = yield* Clock.currentTimeMillis;
1335
+ const row = db.findConnection(actor.scope, ref);
1336
+ if (row !== void 0) {
1337
+ const subject = subjectFor(row, actor);
1338
+ return summarizeStored(row, db.getCredential(row.id, subject.type, subject.id), now);
1339
+ }
1340
+ for (const spec of Object.values(cachedCatalog.connectors)) {
1341
+ if (spec.auth.env === void 0) continue;
1342
+ if (ref === `env:${spec.id}` || ref === formatUid(spec.id, "env")) {
1343
+ const found = readEnvVar(getEnv(), spec.auth.env.vars);
1344
+ if (found !== void 0) return summarizeEnv(spec, actor.scope, found.name);
1345
+ }
1346
+ }
1347
+ return yield* new ConnectionNotFoundError({
1348
+ ref,
1349
+ message: `Connection "${ref}" not found`
1350
+ });
1351
+ }),
1352
+ create: (input) => Effect.gen(function* () {
1353
+ const actor = yield* Actor.Current;
1354
+ const spec = findConnector(cachedCatalog, input.connector);
1355
+ if (spec === void 0) return yield* new ConnectorNotFoundError({
1356
+ connectorId: input.connector,
1357
+ message: `Unknown connector "${input.connector}"`
1358
+ });
1359
+ const slug = (input.slug ?? "default").trim().toLowerCase();
1360
+ if (!CONNECTION_SLUG_PATTERN.test(slug)) return yield* new ConnectorValidationError({ message: `Invalid connection name "${slug}". Use lowercase letters, numbers, and hyphens.` });
1361
+ const uid = formatUid(spec.id, slug);
1362
+ if (db.findConnection(actor.scope, uid) !== void 0) return yield* new ConnectionConflictError({
1363
+ uid,
1364
+ message: `Connection "${uid}" already exists in this workspace`
1365
+ });
1366
+ const chosenAuth = input.authType ?? (spec.auth.oauth !== void 0 ? "oauth" : spec.auth.apikey !== void 0 ? "apikey" : void 0);
1367
+ if (chosenAuth === void 0) return yield* new ConnectorValidationError({ message: `Connector "${spec.id}" has no storable auth method` });
1368
+ if (chosenAuth === "oauth" && spec.auth.oauth === void 0) return yield* new ConnectorValidationError({ message: `Connector "${spec.id}" does not support OAuth` });
1369
+ if (chosenAuth === "apikey" && spec.auth.apikey === void 0) return yield* new ConnectorValidationError({ message: `Connector "${spec.id}" does not support API key authentication` });
1370
+ const ownership = input.ownership ?? (chosenAuth === "oauth" ? spec.auth.oauth?.defaultOwnership ?? "personal" : spec.auth.apikey?.defaultOwnership ?? "shared");
1371
+ const existingSame = db.listConnections(actor.scope, { connectorId: spec.id });
1372
+ const isDefault = input.isDefault ?? existingSame.length === 0;
1373
+ const now = yield* Clock.currentTimeMillis;
1374
+ const row = db.insertConnection({
1375
+ id: ConnectionID.create(),
1376
+ workspaceId: actor.scope,
1377
+ uid,
1378
+ label: input.label ?? spec.name,
1379
+ source: "catalog",
1380
+ connectorId: spec.id,
1381
+ kinds: spec.kinds,
1382
+ authType: chosenAuth,
1383
+ ownership,
1384
+ enabled: input.enabled ?? true,
1385
+ isDefault,
1386
+ allowedHosts: spec.allowedHosts,
1387
+ config: input.config ?? {},
1388
+ now
1389
+ });
1390
+ return summarizeStored(row, void 0, now);
1391
+ }),
1392
+ update: (input) => Effect.gen(function* () {
1393
+ const actor = yield* Actor.Current;
1394
+ const row = db.findConnection(actor.scope, input.ref);
1395
+ if (row === void 0) return yield* new ConnectionNotFoundError({
1396
+ ref: input.ref,
1397
+ message: `Connection "${input.ref}" not found`
1398
+ });
1399
+ if (input.uid !== void 0 && input.uid !== row.uid) {
1400
+ if (!CONNECTION_UID_PATTERN.test(input.uid)) return yield* new ConnectorValidationError({ message: `Invalid connection uid "${input.uid}"` });
1401
+ if (db.findConnection(actor.scope, input.uid) !== void 0) return yield* new ConnectionConflictError({
1402
+ uid: input.uid,
1403
+ message: `Connection "${input.uid}" already exists in this workspace`
1404
+ });
1405
+ }
1406
+ const now = yield* Clock.currentTimeMillis;
1407
+ const updated = db.updateConnection(row.id, {
1408
+ uid: input.uid,
1409
+ label: input.label,
1410
+ ownership: input.ownership,
1411
+ enabled: input.enabled,
1412
+ isDefault: input.isDefault,
1413
+ config: input.config,
1414
+ now
1415
+ });
1416
+ if (updated === void 0) return yield* new ConnectionNotFoundError({
1417
+ ref: input.ref,
1418
+ message: `Connection "${input.ref}" not found`
1419
+ });
1420
+ const subject = subjectFor(updated, actor);
1421
+ return summarizeStored(updated, db.getCredential(updated.id, subject.type, subject.id), now);
1422
+ }),
1423
+ remove: (ref) => Effect.gen(function* () {
1424
+ const actor = yield* Actor.Current;
1425
+ const row = db.findConnection(actor.scope, ref);
1426
+ if (row === void 0) return false;
1427
+ return db.deleteConnection(row.id);
1428
+ }),
1429
+ setApiKey: (ref, apiKey) => Effect.gen(function* () {
1430
+ const actor = yield* Actor.Current;
1431
+ const trimmed = apiKey.trim();
1432
+ if (trimmed.length === 0) return yield* new ConnectorValidationError({ message: "API key cannot be empty" });
1433
+ const row = db.findConnection(actor.scope, ref);
1434
+ if (row === void 0) return yield* new ConnectionNotFoundError({
1435
+ ref,
1436
+ message: `Connection "${ref}" not found`
1437
+ });
1438
+ if (row.authType !== "apikey") return yield* new ConnectorValidationError({ message: `Connection "${row.uid}" uses ${row.authType}, not apikey` });
1439
+ const now = yield* Clock.currentTimeMillis;
1440
+ const subject = subjectFor(row, actor);
1441
+ const cred = db.upsertCredential({
1442
+ connectionId: row.id,
1443
+ subjectType: subject.type,
1444
+ subjectId: subject.id,
1445
+ secret: {
1446
+ type: "apikey",
1447
+ apiKey: trimmed
1448
+ },
1449
+ status: "active",
1450
+ now
1451
+ });
1452
+ return summarizeStored(row, cred, now);
1453
+ }),
1454
+ disconnect: (ref) => Effect.gen(function* () {
1455
+ const actor = yield* Actor.Current;
1456
+ const now = yield* Clock.currentTimeMillis;
1457
+ const row = db.findConnection(actor.scope, ref);
1458
+ if (row === void 0) return yield* new ConnectionNotFoundError({
1459
+ ref,
1460
+ message: `Connection "${ref}" not found`
1461
+ });
1462
+ const subject = subjectFor(row, actor);
1463
+ db.deleteCredential(row.id, subject.type, subject.id);
1464
+ return summarizeStored(row, void 0, now);
1465
+ }),
1466
+ oauthStart: (input) => Effect.gen(function* () {
1467
+ const actor = yield* Actor.Current;
1468
+ const row = db.findConnection(actor.scope, input.ref);
1469
+ if (row === void 0) return yield* new ConnectionNotFoundError({
1470
+ ref: input.ref,
1471
+ message: `Connection "${input.ref}" not found`
1472
+ });
1473
+ if (row.authType !== "oauth") return yield* new ConnectorValidationError({ message: `Connection "${row.uid}" uses ${row.authType}, not oauth` });
1474
+ const spec = specForRow(row);
1475
+ if (spec === void 0) return yield* new ConnectorNotFoundError({
1476
+ connectorId: row.connectorId,
1477
+ message: `Connector "${row.connectorId}" is not in the catalog`
1478
+ });
1479
+ return yield* startAuthCodeFlow({
1480
+ store: pendingOAuth,
1481
+ connector: spec,
1482
+ connection: row,
1483
+ redirectUrl: input.redirectUrl,
1484
+ scopes: input.scopes,
1485
+ workspaceId: actor.scope,
1486
+ actorId: actor.id,
1487
+ fetch: options.fetch
1488
+ });
1489
+ }),
1490
+ oauthFinish: (input) => Effect.gen(function* () {
1491
+ const actor = yield* Actor.Current;
1492
+ const { connectionId, secret } = yield* finishAuthCodeFlow({
1493
+ store: pendingOAuth,
1494
+ state: input.state,
1495
+ codeOrUrl: input.code,
1496
+ workspaceId: actor.scope,
1497
+ actorId: actor.id,
1498
+ fetch: options.fetch
1499
+ });
1500
+ const row = db.findConnectionById(connectionId);
1501
+ if (row === void 0 || row.workspaceId !== actor.scope) return yield* new ConnectionNotFoundError({
1502
+ ref: connectionId,
1503
+ message: `Connection "${connectionId}" no longer exists`
1504
+ });
1505
+ const now = yield* Clock.currentTimeMillis;
1506
+ const subject = subjectFor(row, actor);
1507
+ const cred = db.upsertCredential({
1508
+ connectionId: row.id,
1509
+ subjectType: subject.type,
1510
+ subjectId: subject.id,
1511
+ secret,
1512
+ status: "active",
1513
+ ...secret.expiresAt !== void 0 ? { expiresAt: secret.expiresAt } : {},
1514
+ now
1515
+ });
1516
+ return summarizeStored(row, cred, now);
1517
+ }),
1518
+ deviceStart: (input) => Effect.gen(function* () {
1519
+ const actor = yield* Actor.Current;
1520
+ const row = db.findConnection(actor.scope, input.ref);
1521
+ if (row === void 0) return yield* new ConnectionNotFoundError({
1522
+ ref: input.ref,
1523
+ message: `Connection "${input.ref}" not found`
1524
+ });
1525
+ if (row.authType !== "oauth") return yield* new ConnectorValidationError({ message: `Connection "${row.uid}" uses ${row.authType}, not oauth` });
1526
+ const spec = specForRow(row);
1527
+ if (spec === void 0) return yield* new ConnectorNotFoundError({
1528
+ connectorId: row.connectorId,
1529
+ message: `Connector "${row.connectorId}" is not in the catalog`
1530
+ });
1531
+ if (input.enterpriseUrl !== void 0) {
1532
+ const now = yield* Clock.currentTimeMillis;
1533
+ db.updateConnection(row.id, {
1534
+ config: {
1535
+ ...row.config,
1536
+ fields: {
1537
+ ...row.config.fields,
1538
+ enterpriseUrl: input.enterpriseUrl
1539
+ }
1540
+ },
1541
+ now
1542
+ });
1543
+ }
1544
+ return yield* startDeviceCodeFlow({
1545
+ store: pendingOAuth,
1546
+ connector: spec,
1547
+ connection: row,
1548
+ enterpriseUrl: input.enterpriseUrl,
1549
+ workspaceId: actor.scope,
1550
+ actorId: actor.id,
1551
+ fetch: options.fetch
1552
+ });
1553
+ }),
1554
+ devicePoll: (state) => Effect.gen(function* () {
1555
+ const actor = yield* Actor.Current;
1556
+ const step = yield* pollDeviceCodeStep({
1557
+ store: pendingOAuth,
1558
+ state,
1559
+ workspaceId: actor.scope,
1560
+ actorId: actor.id,
1561
+ fetch: options.fetch
1562
+ });
1563
+ if (step.status === "pending") return {
1564
+ status: "pending",
1565
+ ...step.intervalSeconds !== void 0 ? { intervalSeconds: step.intervalSeconds } : {}
1566
+ };
1567
+ const row = db.findConnectionById(step.connectionId);
1568
+ if (row === void 0 || row.workspaceId !== actor.scope) return yield* new ConnectionNotFoundError({
1569
+ ref: step.connectionId,
1570
+ message: `Connection "${step.connectionId}" no longer exists`
1571
+ });
1572
+ const now = yield* Clock.currentTimeMillis;
1573
+ const subject = subjectFor(row, actor);
1574
+ const cred = db.upsertCredential({
1575
+ connectionId: row.id,
1576
+ subjectType: subject.type,
1577
+ subjectId: subject.id,
1578
+ secret: step.secret,
1579
+ status: "active",
1580
+ ...step.secret.expiresAt !== void 0 ? { expiresAt: step.secret.expiresAt } : {},
1581
+ now
1582
+ });
1583
+ return {
1584
+ status: "complete",
1585
+ connection: summarizeStored(row, cred, now)
1586
+ };
1587
+ }),
1588
+ resolve: (input) => Effect.gen(function* () {
1589
+ const actor = yield* Actor.Current;
1590
+ const row = db.findConnection(actor.scope, input.ref);
1591
+ if (row !== void 0) return yield* resolveRowSecret(row, actor, {
1592
+ targetHost: input.targetHost,
1593
+ minValidityMs: input.minValidityMs
1594
+ });
1595
+ for (const spec of Object.values(cachedCatalog.connectors)) if (input.ref === `env:${spec.id}` || input.ref === formatUid(spec.id, "env")) {
1596
+ const resolved = yield* resolveEnvFallback(spec, input.targetHost);
1597
+ if (resolved !== void 0) return resolved;
1598
+ }
1599
+ return yield* new ConnectionNotFoundError({
1600
+ ref: input.ref,
1601
+ message: `Connection "${input.ref}" not found`
1602
+ });
1603
+ }),
1604
+ resolveProvider: (providerId) => Effect.gen(function* () {
1605
+ const actor = yield* Actor.Current;
1606
+ const spec = findConnectorByProviderId(cachedCatalog, providerId);
1607
+ if (spec === void 0) return void 0;
1608
+ const rows = db.listConnections(actor.scope, {
1609
+ connectorId: spec.id,
1610
+ enabled: true
1611
+ });
1612
+ const chosen = rows.find((r) => r.isDefault) ?? rows[0];
1613
+ if (chosen !== void 0) return yield* resolveRowSecret(chosen, actor, {});
1614
+ return yield* resolveEnvFallback(spec, void 0);
1615
+ }),
1616
+ listMcpConnections: () => Effect.gen(function* () {
1617
+ const actor = yield* Actor.Current;
1618
+ const rows = db.listConnections(actor.scope, {
1619
+ kind: "mcp",
1620
+ enabled: true
1621
+ });
1622
+ const active = [];
1623
+ const seenConnectors = /* @__PURE__ */ new Set();
1624
+ for (const row of rows) {
1625
+ const spec = specForRow(row);
1626
+ const mcp = spec?.capabilities.mcp;
1627
+ if (spec === void 0 || mcp === void 0) continue;
1628
+ seenConnectors.add(row.connectorId);
1629
+ active.push({
1630
+ id: row.id,
1631
+ uid: row.uid,
1632
+ connectorId: row.connectorId,
1633
+ name: row.label ?? spec.name,
1634
+ url: mcp.url,
1635
+ transport: mcp.transport ?? "http",
1636
+ exposure: row.config.mcp?.exposure ?? mcp.defaultExposure ?? "eager",
1637
+ authType: row.authType,
1638
+ ...row.authType === "apikey" && spec.auth.apikey?.inject !== void 0 ? { inject: spec.auth.apikey.inject } : {},
1639
+ allowedHosts: row.allowedHosts
1640
+ });
1641
+ }
1642
+ const env = getEnv();
1643
+ for (const spec of Object.values(cachedCatalog.connectors)) {
1644
+ if (seenConnectors.has(spec.id)) continue;
1645
+ const mcp = spec.capabilities.mcp;
1646
+ if (mcp === void 0 || spec.auth.env === void 0) continue;
1647
+ if (readEnvVar(env, spec.auth.env.vars) === void 0) continue;
1648
+ active.push({
1649
+ id: `env:${spec.id}`,
1650
+ uid: formatUid(spec.id, "env"),
1651
+ connectorId: spec.id,
1652
+ name: spec.name,
1653
+ url: mcp.url,
1654
+ transport: mcp.transport ?? "http",
1655
+ exposure: mcp.defaultExposure ?? "eager",
1656
+ authType: "env",
1657
+ ...spec.auth.env.inject !== void 0 ? { inject: spec.auth.env.inject } : {},
1658
+ allowedHosts: spec.allowedHosts
1659
+ });
1660
+ }
1661
+ return active;
1662
+ }),
1663
+ listProviderStates: () => Effect.gen(function* () {
1664
+ const actor = yield* Actor.Current;
1665
+ const now = yield* Clock.currentTimeMillis;
1666
+ const states = [];
1667
+ const env = getEnv();
1668
+ for (const spec of Object.values(cachedCatalog.connectors)) {
1669
+ const providerId = spec.capabilities.provider?.providerId;
1670
+ if (providerId === void 0) continue;
1671
+ const rows = db.listConnections(actor.scope, {
1672
+ connectorId: spec.id,
1673
+ enabled: true
1674
+ });
1675
+ const chosen = rows.find((r) => r.isDefault) ?? rows[0];
1676
+ if (chosen !== void 0) {
1677
+ const subject = subjectFor(chosen, actor);
1678
+ const cred = db.getCredential(chosen.id, subject.type, subject.id);
1679
+ const summary = summarizeStored(chosen, cred, now);
1680
+ const oauthSecret = cred?.secret.type === "oauth" ? cred.secret : void 0;
1681
+ states.push({
1682
+ providerId,
1683
+ connectorId: spec.id,
1684
+ uid: chosen.uid,
1685
+ authType: chosen.authType,
1686
+ status: summary.status,
1687
+ sourceLabel: summary.sourceLabel,
1688
+ ...oauthSecret?.apiEndpoint !== void 0 ? { apiEndpoint: oauthSecret.apiEndpoint } : {},
1689
+ ...oauthSecret?.availableModelIds !== void 0 ? { availableModelIds: oauthSecret.availableModelIds } : {}
1690
+ });
1691
+ continue;
1692
+ }
1693
+ if (spec.auth.env !== void 0) {
1694
+ const found = readEnvVar(env, spec.auth.env.vars);
1695
+ if (found !== void 0) states.push({
1696
+ providerId,
1697
+ connectorId: spec.id,
1698
+ uid: formatUid(spec.id, "env"),
1699
+ authType: "env",
1700
+ status: "active",
1701
+ sourceLabel: `$${found.name}`
1702
+ });
1703
+ }
1704
+ }
1705
+ return states;
1706
+ })
1707
+ }
1708
+ };
1709
+ }), ({ db }) => Effect.sync(() => db.close())).pipe(Effect.map(({ service }) => service));
1710
+ /**
1711
+ * Provides both the full host `Connector.Service` and the narrowed `@codeworksh/plugin/connector` `Broker`
1712
+ * backed by the exact same `<home>/connections.db` instance.
1713
+ */
1714
+ const layer = (options = {}) => Layer.effectContext(make(options).pipe(Effect.map((service) => Context.empty().pipe(Context.add(Service, service), Context.add(Connector.Broker, service)))));
1715
+ //#endregion
1716
+ export { layer as n, Service as t };
1717
+
1718
+ //# sourceMappingURL=service-C1UBpOCn.mjs.map