@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.
Files changed (123) hide show
  1. package/{acp-CmtcmhuX.mjs → acp-C2GCSrJd.mjs} +6 -5
  2. package/acp-C2GCSrJd.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-DYD_3Pt8.mjs +19 -0
  10. package/categories-DYD_3Pt8.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-D4w0dmRc.mjs} +5 -5
  14. package/{connect-KX-A0EzQ.mjs.map → connect-D4w0dmRc.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-Bt56MHKu.mjs +35 -0
  18. package/create-Bt56MHKu.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-CHEHx_ic.mjs +2 -0
  22. package/{disconnect-CCI1DLJ0.mjs → disconnect-CXha4LTk.mjs} +4 -4
  23. package/{disconnect-CCI1DLJ0.mjs.map → disconnect-CXha4LTk.mjs.map} +1 -1
  24. package/disconnect-Cx0sydNl.mjs +19 -0
  25. package/disconnect-Cx0sydNl.mjs.map +1 -0
  26. package/discover-wWs8qDQd.mjs +35 -0
  27. package/discover-wWs8qDQd.mjs.map +1 -0
  28. package/{discovery-D2ftXE5a.mjs → discovery-C-ploGdg.mjs} +2 -2
  29. package/{discovery-D2ftXE5a.mjs.map → discovery-C-ploGdg.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-Cjr43dhQ.mjs} +2 -2
  33. package/{identity-Llk4K_8w.mjs.map → identity-Cjr43dhQ.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-D1c5uzCc.mjs → list-CdS1_gFF.mjs} +2 -2
  43. package/{list-D1c5uzCc.mjs.map → list-CdS1_gFF.mjs.map} +1 -1
  44. package/list-D6ABpoQC.mjs +27 -0
  45. package/list-D6ABpoQC.mjs.map +1 -0
  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-DnOTWBy8.mjs +26 -0
  53. package/login-DnOTWBy8.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-BsCtRg3n.mjs +6 -0
  61. package/package-BsCtRg3n.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-CO46Wh73.mjs} +3 -3
  73. package/{relay-BmHXs1yg.mjs.map → relay-CO46Wh73.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-Bad0ln8h.mjs +22 -0
  79. package/remove-Bad0ln8h.mjs.map +1 -0
  80. package/{remove-BXmNNX2f.mjs → remove-C0e5sHqb.mjs} +3 -3
  81. package/{remove-BXmNNX2f.mjs.map → remove-C0e5sHqb.mjs.map} +1 -1
  82. package/{remove-CJ__oofS.mjs → remove-CdcoheOp.mjs} +2 -2
  83. package/{remove-CJ__oofS.mjs.map → remove-CdcoheOp.mjs.map} +1 -1
  84. package/{restart-CMDZZJ4N.mjs → restart-CvkGtFq2.mjs} +4 -4
  85. package/{restart-CMDZZJ4N.mjs.map → restart-CvkGtFq2.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-n_t47yPB.mjs} +8 -5
  89. package/run-n_t47yPB.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-BaNbYK1f.mjs} +27 -11
  93. package/serve-BaNbYK1f.mjs.map +1 -0
  94. package/service-CA6VAOdR.mjs +1652 -0
  95. package/service-CA6VAOdR.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-CA47qIai.mjs +212 -0
  99. package/shared-CA47qIai.mjs.map +1 -0
  100. package/{shared-C2sMimyK.mjs → shared-CDJQxUb9.mjs} +4 -4
  101. package/{shared-C2sMimyK.mjs.map → shared-CDJQxUb9.mjs.map} +1 -1
  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-D3lqmljh.mjs} +4 -4
  105. package/{start-DbCTFswo.mjs.map → start-D3lqmljh.mjs.map} +1 -1
  106. package/{status-CR_E6RiI.mjs → status-BoTZqXwd.mjs} +3 -3
  107. package/{status-CR_E6RiI.mjs.map → status-BoTZqXwd.mjs.map} +1 -1
  108. package/{status-Dcbdl6Sv.mjs → status-P0hOBrM6.mjs} +4 -4
  109. package/{status-Dcbdl6Sv.mjs.map → status-P0hOBrM6.mjs.map} +1 -1
  110. package/status-tYcs05sk.mjs +23 -0
  111. package/status-tYcs05sk.mjs.map +1 -0
  112. package/{stop-ML5Yeo_s.mjs → stop-BuDB-rqB.mjs} +4 -4
  113. package/{stop-ML5Yeo_s.mjs.map → stop-BuDB-rqB.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,1652 @@
1
+ import { Clock, Context, Effect, Layer, Redacted, Schema, Semaphore } from "effect";
2
+ import { Connector, Global } 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
+ authorizeEndpoint,
471
+ tokenEndpoint,
472
+ registrationEndpoint: typeof meta["registration_endpoint"] === "string" ? meta["registration_endpoint"] : void 0,
473
+ resource,
474
+ scopesSupported: scopesSupported ?? (Array.isArray(meta["scopes_supported"]) ? meta["scopes_supported"].filter((s) => typeof s === "string") : void 0)
475
+ };
476
+ }
477
+ throw new Error(`Could not discover OAuth metadata for ${resourceUrl}`);
478
+ };
479
+ const registerDynamicClient = async (registrationEndpoint, redirectUrl, fetcher) => {
480
+ const response = await fetcher(registrationEndpoint, {
481
+ method: "POST",
482
+ headers: {
483
+ "Content-Type": "application/json",
484
+ Accept: "application/json"
485
+ },
486
+ body: JSON.stringify({
487
+ client_name: "CodeWork",
488
+ redirect_uris: [redirectUrl],
489
+ grant_types: ["authorization_code", "refresh_token"],
490
+ response_types: ["code"],
491
+ token_endpoint_auth_method: "none"
492
+ }),
493
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
494
+ });
495
+ if (!response.ok) {
496
+ const body = await response.text().catch(() => "");
497
+ throw new Error(`Dynamic client registration failed (${response.status}): ${body || response.statusText}`);
498
+ }
499
+ const data = await response.json();
500
+ if (!isRecord(data) || typeof data["client_id"] !== "string" || data["client_id"].length === 0) throw new Error("Dynamic client registration returned no client_id");
501
+ return {
502
+ clientId: data["client_id"],
503
+ clientSecret: typeof data["client_secret"] === "string" ? data["client_secret"] : void 0
504
+ };
505
+ };
506
+ var PendingOAuthStore = class {
507
+ entries = /* @__PURE__ */ new Map();
508
+ prune(now) {
509
+ for (const [key, value] of this.entries) if (value.expiresAt <= now) this.entries.delete(key);
510
+ }
511
+ put(state, entry) {
512
+ this.prune(Date.now());
513
+ this.entries.set(state, entry);
514
+ }
515
+ peek(state, workspaceId, actorId) {
516
+ this.prune(Date.now());
517
+ const entry = this.entries.get(state);
518
+ if (entry === void 0) return void 0;
519
+ if (entry.workspaceId !== workspaceId || entry.actorId !== actorId) return void 0;
520
+ return entry;
521
+ }
522
+ consume(state, workspaceId, actorId) {
523
+ const entry = this.peek(state, workspaceId, actorId);
524
+ if (entry !== void 0) this.entries.delete(state);
525
+ return entry;
526
+ }
527
+ delete(state) {
528
+ this.entries.delete(state);
529
+ }
530
+ };
531
+ const errorMessage = (cause) => cause instanceof Error && cause.message.trim().length > 0 ? cause.message : String(cause);
532
+ const parseTokenResponse = (data, client, fallbackRefresh, fallbackScopes) => {
533
+ if (!isRecord(data) || typeof data["access_token"] !== "string" || data["access_token"].length === 0) throw new Error("OAuth token endpoint returned no access_token");
534
+ const expiresIn = typeof data["expires_in"] === "number" && Number.isFinite(data["expires_in"]) ? data["expires_in"] : void 0;
535
+ const refreshToken = typeof data["refresh_token"] === "string" && data["refresh_token"].length > 0 ? data["refresh_token"] : fallbackRefresh;
536
+ const scopeStr = typeof data["scope"] === "string" ? data["scope"] : void 0;
537
+ const scopes = scopeStr ? scopeStr.split(/\s+/).map((s) => s.trim()).filter((s) => s.length > 0) : fallbackScopes;
538
+ return {
539
+ type: "oauth",
540
+ accessToken: data["access_token"],
541
+ ...refreshToken !== void 0 ? { refreshToken } : {},
542
+ ...expiresIn !== void 0 ? { expiresAt: Date.now() + expiresIn * 1e3 } : {},
543
+ ...typeof data["token_type"] === "string" ? { tokenType: data["token_type"] } : {},
544
+ ...scopes !== void 0 && scopes.length > 0 ? { scopes } : {},
545
+ client
546
+ };
547
+ };
548
+ const startAuthCodeFlow = (input) => Effect.tryPromise({
549
+ try: async () => {
550
+ const spec = input.connector.auth.oauth;
551
+ if (spec === void 0) throw new Error(`Connector "${input.connector.id}" does not support OAuth`);
552
+ const expiresAt = Date.now() + PENDING_TTL_MS;
553
+ if (spec.handler === "openai-codex") {
554
+ const flow = await createOpenAICodexAuthorizationFlow({
555
+ redirectUri: input.redirectUrl,
556
+ ...input.scopes && input.scopes.length > 0 ? { scope: input.scopes.join(" ") } : {}
557
+ });
558
+ input.store.put(flow.state, {
559
+ kind: "auth_code",
560
+ workspaceId: input.workspaceId,
561
+ actorId: input.actorId,
562
+ connectionId: input.connection.id,
563
+ connector: input.connector,
564
+ handler: "openai-codex",
565
+ redirectUrl: flow.redirectUri,
566
+ codeVerifier: flow.verifier,
567
+ client: { clientId: "openai-codex" },
568
+ scopes: input.scopes,
569
+ expiresAt
570
+ });
571
+ return {
572
+ state: flow.state,
573
+ authorizeUrl: flow.url,
574
+ redirectUrl: flow.redirectUri,
575
+ expiresAt
576
+ };
577
+ }
578
+ if (spec.handler === "github-copilot") throw new Error("GitHub Copilot uses device-code OAuth; start a device flow instead");
579
+ const fetcher = input.fetch ?? globalThis.fetch;
580
+ let authorizeEndpoint = spec.authorizeUrl;
581
+ let tokenEndpoint = spec.tokenUrl;
582
+ let registrationEndpoint;
583
+ let resource = input.connector.capabilities.mcp?.url;
584
+ if (spec.discovery === "auto" || !authorizeEndpoint || !tokenEndpoint) {
585
+ const discoveryTarget = input.connector.capabilities.mcp?.url ?? input.connector.capabilities.integration?.baseUrl ?? input.connector.capabilities.provider?.baseUrl;
586
+ if (!discoveryTarget) throw new Error(`Connector "${input.connector.id}" has no OAuth endpoints or discovery URL`);
587
+ const discovered = await discoverOAuthMetadata(discoveryTarget, fetcher);
588
+ authorizeEndpoint = authorizeEndpoint ?? discovered.authorizeEndpoint;
589
+ tokenEndpoint = tokenEndpoint ?? discovered.tokenEndpoint;
590
+ registrationEndpoint = discovered.registrationEndpoint;
591
+ resource = discovered.resource ?? resource;
592
+ }
593
+ let clientId = spec.clientId;
594
+ let clientSecret;
595
+ if (!clientId) {
596
+ if (!registrationEndpoint) throw new Error(`OAuth server for "${input.connector.id}" does not advertise dynamic client registration`);
597
+ const registered = await registerDynamicClient(registrationEndpoint, input.redirectUrl, fetcher);
598
+ clientId = registered.clientId;
599
+ clientSecret = registered.clientSecret;
600
+ }
601
+ const { verifier, challenge } = generatePkce();
602
+ const state = randomState();
603
+ const scopes = input.scopes ?? input.connection.config.scopes ?? spec.scopes;
604
+ const url = new URL(authorizeEndpoint);
605
+ url.searchParams.set("response_type", "code");
606
+ url.searchParams.set("client_id", clientId);
607
+ url.searchParams.set("redirect_uri", input.redirectUrl);
608
+ url.searchParams.set("state", state);
609
+ if (spec.pkce !== false) {
610
+ url.searchParams.set("code_challenge", challenge);
611
+ url.searchParams.set("code_challenge_method", "S256");
612
+ }
613
+ if (scopes && scopes.length > 0) url.searchParams.set("scope", scopes.join(" "));
614
+ if (resource) url.searchParams.set("resource", resource);
615
+ const client = {
616
+ clientId,
617
+ ...clientSecret !== void 0 ? { clientSecret } : {},
618
+ authorizeEndpoint,
619
+ tokenEndpoint,
620
+ ...resource !== void 0 ? { resource } : {}
621
+ };
622
+ input.store.put(state, {
623
+ kind: "auth_code",
624
+ workspaceId: input.workspaceId,
625
+ actorId: input.actorId,
626
+ connectionId: input.connection.id,
627
+ connector: input.connector,
628
+ redirectUrl: input.redirectUrl,
629
+ codeVerifier: verifier,
630
+ client,
631
+ scopes,
632
+ expiresAt
633
+ });
634
+ return {
635
+ state,
636
+ authorizeUrl: url.toString(),
637
+ redirectUrl: input.redirectUrl,
638
+ expiresAt
639
+ };
640
+ },
641
+ catch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) })
642
+ });
643
+ const finishAuthCodeFlow = (input) => Effect.tryPromise({
644
+ try: async () => {
645
+ const pending = input.store.consume(input.state, input.workspaceId, input.actorId);
646
+ if (pending === void 0 || pending.kind !== "auth_code") throw new Error("Invalid, expired, or unauthorized OAuth state");
647
+ const parsedInput = parseOpenAICodexAuthorizationInput(input.codeOrUrl);
648
+ const code = parsedInput.code ?? input.codeOrUrl.trim();
649
+ if (parsedInput.state !== void 0 && parsedInput.state !== input.state) throw new Error("OAuth state mismatch");
650
+ if (code.length === 0) throw new Error("Missing authorization code");
651
+ if (pending.handler === "openai-codex") {
652
+ const result = await exchangeOpenAICodexAuthorizationCode(code, pending.codeVerifier, pending.redirectUrl);
653
+ if (result.type !== "success") throw new Error(result.message);
654
+ const accountId = getOpenAICodexAccountId(result.access) ?? void 0;
655
+ return {
656
+ connectionId: pending.connectionId,
657
+ secret: {
658
+ type: "oauth",
659
+ accessToken: result.access,
660
+ refreshToken: result.refresh,
661
+ expiresAt: result.expires,
662
+ ...accountId !== void 0 ? {
663
+ accountId,
664
+ accountLabel: accountId
665
+ } : {}
666
+ }
667
+ };
668
+ }
669
+ const tokenEndpoint = pending.client.tokenEndpoint;
670
+ if (!tokenEndpoint) throw new Error("Missing OAuth token endpoint");
671
+ const body = new URLSearchParams({
672
+ grant_type: "authorization_code",
673
+ client_id: pending.client.clientId,
674
+ code,
675
+ redirect_uri: pending.redirectUrl,
676
+ code_verifier: pending.codeVerifier
677
+ });
678
+ if (pending.client.clientSecret) body.set("client_secret", pending.client.clientSecret);
679
+ if (pending.client.resource) body.set("resource", pending.client.resource);
680
+ const response = await (input.fetch ?? globalThis.fetch)(tokenEndpoint, {
681
+ method: "POST",
682
+ headers: {
683
+ "Content-Type": "application/x-www-form-urlencoded",
684
+ Accept: "application/json"
685
+ },
686
+ body,
687
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
688
+ });
689
+ if (!response.ok) {
690
+ const text = await response.text().catch(() => "");
691
+ throw new Error(`OAuth token exchange failed (${response.status}): ${text || response.statusText}`);
692
+ }
693
+ const data = await response.json();
694
+ return {
695
+ connectionId: pending.connectionId,
696
+ secret: parseTokenResponse(data, pending.client, void 0, pending.scopes)
697
+ };
698
+ },
699
+ catch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) })
700
+ });
701
+ const startDeviceCodeFlow = (input) => Effect.tryPromise({
702
+ try: async () => {
703
+ const spec = input.connector.auth.oauth;
704
+ if (spec === void 0 || !spec.grants.includes("device_code")) throw new Error(`Connector "${input.connector.id}" does not support device-code OAuth`);
705
+ const state = randomState();
706
+ const now = Date.now();
707
+ if (spec.handler === "github-copilot") {
708
+ const enterpriseUrl = input.enterpriseUrl ?? input.connection.config.fields?.["enterpriseUrl"];
709
+ const domain = normalizeGitHubDomain(enterpriseUrl);
710
+ const flow = await createGitHubCopilotDeviceFlow({
711
+ ...domain !== void 0 ? { domain } : {},
712
+ ...input.fetch !== void 0 ? { fetch: input.fetch } : {}
713
+ });
714
+ const expiresAt = now + (flow.expiresInSeconds ?? 900) * 1e3;
715
+ input.store.put(state, {
716
+ kind: "device_code",
717
+ workspaceId: input.workspaceId,
718
+ actorId: input.actorId,
719
+ connectionId: input.connection.id,
720
+ connector: input.connector,
721
+ handler: "github-copilot",
722
+ deviceCode: flow.deviceCode,
723
+ userCode: flow.userCode,
724
+ verificationUri: flow.verificationUri,
725
+ intervalSeconds: flow.intervalSeconds,
726
+ ...enterpriseUrl !== void 0 ? { enterpriseUrl } : {},
727
+ expiresAt
728
+ });
729
+ return {
730
+ state,
731
+ verificationUri: flow.verificationUri,
732
+ userCode: flow.userCode,
733
+ intervalSeconds: flow.intervalSeconds,
734
+ expiresAt
735
+ };
736
+ }
737
+ if (spec.handler === "openai-codex") {
738
+ const device = await createOpenAICodexDeviceAuth();
739
+ const expiresAt = now + 9e5;
740
+ input.store.put(state, {
741
+ kind: "device_code",
742
+ workspaceId: input.workspaceId,
743
+ actorId: input.actorId,
744
+ connectionId: input.connection.id,
745
+ connector: input.connector,
746
+ handler: "openai-codex",
747
+ deviceCode: device.deviceAuthId,
748
+ userCode: device.userCode,
749
+ verificationUri: device.verificationUri,
750
+ intervalSeconds: device.intervalSeconds,
751
+ expiresAt
752
+ });
753
+ return {
754
+ state,
755
+ verificationUri: device.verificationUri,
756
+ userCode: device.userCode,
757
+ intervalSeconds: device.intervalSeconds,
758
+ expiresAt
759
+ };
760
+ }
761
+ throw new Error(`Unsupported device-code handler for "${input.connector.id}"`);
762
+ },
763
+ catch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) })
764
+ });
765
+ /**
766
+ * Performs one non-blocking poll step for an active device-code login so RPC/UI callers never hang.
767
+ */
768
+ const pollDeviceCodeStep = (input) => Effect.tryPromise({
769
+ try: async () => {
770
+ const pending = input.store.peek(input.state, input.workspaceId, input.actorId);
771
+ if (pending === void 0 || pending.kind !== "device_code") throw new Error("Invalid, expired, or unauthorized device-code state");
772
+ const fetcher = input.fetch ?? globalThis.fetch;
773
+ if (pending.handler === "github-copilot") {
774
+ const domain = normalizeGitHubDomain(pending.enterpriseUrl) ?? "github.com";
775
+ const response = await fetcher(`https://${domain}/login/oauth/access_token`, {
776
+ method: "POST",
777
+ headers: {
778
+ Accept: "application/json",
779
+ "Content-Type": "application/json"
780
+ },
781
+ body: JSON.stringify({
782
+ client_id: GITHUB_COPILOT_CLIENT_ID,
783
+ device_code: pending.deviceCode,
784
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
785
+ }),
786
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
787
+ });
788
+ if (!response.ok) throw new Error(`GitHub device token poll failed (${response.status})`);
789
+ const data = await response.json();
790
+ if (!isRecord(data)) throw new Error("Invalid GitHub device token response");
791
+ if (typeof data["access_token"] === "string" && data["access_token"].length > 0) {
792
+ input.store.delete(input.state);
793
+ const accessToken = data["access_token"];
794
+ const user = await fetchGitHubCopilotUser(accessToken, {
795
+ domain,
796
+ fetch: fetcher
797
+ });
798
+ const entitlementIssue = user ? gitHubCopilotEntitlementError({
799
+ chat_enabled: user.chatEnabled,
800
+ can_signup_for_limited: user.canSignupForLimited
801
+ }) : void 0;
802
+ if (entitlementIssue) throw new Error(entitlementIssue);
803
+ const baseURL = user?.apiEndpoint ?? (pending.enterpriseUrl ? gitHubCopilotBaseUrl({ enterpriseUrl: pending.enterpriseUrl }) : void 0);
804
+ const availableModelIds = (await fetchGitHubCopilotModels(accessToken, {
805
+ domain,
806
+ ...baseURL !== void 0 ? { baseURL } : {},
807
+ fetch: fetcher
808
+ }).catch(() => void 0))?.map((m) => m.id);
809
+ return {
810
+ status: "complete",
811
+ connectionId: pending.connectionId,
812
+ secret: {
813
+ type: "oauth",
814
+ accessToken,
815
+ refreshToken: accessToken,
816
+ ...user?.apiEndpoint !== void 0 ? { apiEndpoint: user.apiEndpoint } : {},
817
+ ...pending.enterpriseUrl !== void 0 ? { enterpriseUrl: pending.enterpriseUrl } : {},
818
+ ...availableModelIds !== void 0 && availableModelIds.length > 0 ? { availableModelIds } : {},
819
+ accountLabel: pending.enterpriseUrl ?? "github.com"
820
+ }
821
+ };
822
+ }
823
+ const err = typeof data["error"] === "string" ? data["error"] : void 0;
824
+ if (err === "authorization_pending") return {
825
+ status: "pending",
826
+ intervalSeconds: pending.intervalSeconds
827
+ };
828
+ if (err === "slow_down") return {
829
+ status: "pending",
830
+ intervalSeconds: typeof data["interval"] === "number" && data["interval"] > 0 ? data["interval"] : pending.intervalSeconds + 5
831
+ };
832
+ input.store.delete(input.state);
833
+ const desc = typeof data["error_description"] === "string" ? `: ${data["error_description"]}` : "";
834
+ throw new Error(`GitHub device authorization failed: ${err ?? "unknown"}${desc}`);
835
+ }
836
+ const response = await fetcher(CODEX_DEVICE_TOKEN_URL, {
837
+ method: "POST",
838
+ headers: { "Content-Type": "application/json" },
839
+ body: JSON.stringify({
840
+ device_auth_id: pending.deviceCode,
841
+ user_code: pending.userCode
842
+ }),
843
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
844
+ });
845
+ if (response.status === 403 || response.status === 404) return {
846
+ status: "pending",
847
+ intervalSeconds: pending.intervalSeconds
848
+ };
849
+ if (response.ok) {
850
+ const data = await response.json();
851
+ if (!isRecord(data) || typeof data["authorization_code"] !== "string" || typeof data["code_verifier"] !== "string") throw new Error("Invalid OpenAI Codex device token response");
852
+ input.store.delete(input.state);
853
+ const exchanged = await exchangeOpenAICodexAuthorizationCode(data["authorization_code"], data["code_verifier"], CODEX_DEVICE_REDIRECT_URI);
854
+ if (exchanged.type !== "success") throw new Error(exchanged.message);
855
+ const accountId = getOpenAICodexAccountId(exchanged.access) ?? void 0;
856
+ return {
857
+ status: "complete",
858
+ connectionId: pending.connectionId,
859
+ secret: {
860
+ type: "oauth",
861
+ accessToken: exchanged.access,
862
+ refreshToken: exchanged.refresh,
863
+ expiresAt: exchanged.expires,
864
+ ...accountId !== void 0 ? {
865
+ accountId,
866
+ accountLabel: accountId
867
+ } : {}
868
+ }
869
+ };
870
+ }
871
+ const text = await response.text().catch(() => "");
872
+ let errorCode;
873
+ try {
874
+ const parsed = JSON.parse(text);
875
+ const err = isRecord(parsed) ? parsed["error"] : void 0;
876
+ errorCode = isRecord(err) ? err["code"] : err;
877
+ } catch {}
878
+ if (errorCode === "deviceauth_authorization_pending") return {
879
+ status: "pending",
880
+ intervalSeconds: pending.intervalSeconds
881
+ };
882
+ if (errorCode === "slow_down") return {
883
+ status: "pending",
884
+ intervalSeconds: pending.intervalSeconds + 5
885
+ };
886
+ input.store.delete(input.state);
887
+ throw new Error(`OpenAI Codex device authorization failed (${response.status})`);
888
+ },
889
+ catch: (cause) => new ConnectorAuthError({ message: errorMessage(cause) })
890
+ });
891
+ /**
892
+ * Network refresh step (called under the broker's double-checked lock).
893
+ */
894
+ const refreshOAuthSecret = async (connector, current, fetcher = globalThis.fetch) => {
895
+ const handler = connector.auth.oauth?.handler;
896
+ if (handler === "github-copilot") return current;
897
+ if (!current.refreshToken) throw new Error(`OAuth token for "${connector.id}" expired and has no refresh token`);
898
+ if (handler === "openai-codex") {
899
+ const refreshed = await refreshOpenAICodexToken(current.refreshToken);
900
+ const accountId = getOpenAICodexAccountId(refreshed.access) ?? current.accountId;
901
+ return {
902
+ ...current,
903
+ accessToken: refreshed.access,
904
+ refreshToken: refreshed.refresh,
905
+ expiresAt: refreshed.expires,
906
+ ...accountId !== void 0 ? {
907
+ accountId,
908
+ accountLabel: accountId
909
+ } : {}
910
+ };
911
+ }
912
+ const tokenEndpoint = current.client?.tokenEndpoint ?? connector.auth.oauth?.tokenUrl;
913
+ const clientId = current.client?.clientId ?? connector.auth.oauth?.clientId;
914
+ if (!tokenEndpoint || !clientId) throw new Error(`Missing OAuth token endpoint or client_id for "${connector.id}" refresh`);
915
+ const body = new URLSearchParams({
916
+ grant_type: "refresh_token",
917
+ client_id: clientId,
918
+ refresh_token: current.refreshToken
919
+ });
920
+ if (current.client?.clientSecret) body.set("client_secret", current.client.clientSecret);
921
+ if (current.client?.resource) body.set("resource", current.client.resource);
922
+ const response = await fetcher(tokenEndpoint, {
923
+ method: "POST",
924
+ headers: {
925
+ "Content-Type": "application/x-www-form-urlencoded",
926
+ Accept: "application/json"
927
+ },
928
+ body,
929
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
930
+ });
931
+ if (!response.ok) {
932
+ const text = await response.text().catch(() => "");
933
+ throw new Error(`OAuth refresh failed (${response.status}): ${text || response.statusText}`);
934
+ }
935
+ const data = await response.json();
936
+ const refreshed = parseTokenResponse(data, current.client ?? {
937
+ clientId,
938
+ tokenEndpoint
939
+ }, current.refreshToken, current.scopes);
940
+ return {
941
+ ...current,
942
+ ...refreshed
943
+ };
944
+ };
945
+ /**
946
+ * Pure request-auth derivation (`toAuth` in Pi's model): maps a valid stored OAuth secret to
947
+ * `{ token, headers?, baseUrl? }` without performing any network calls.
948
+ */
949
+ const deriveOAuthRequestAuth = (connector, secret) => {
950
+ const handler = connector.auth.oauth?.handler;
951
+ if (handler === "github-copilot") {
952
+ const creds = {
953
+ access: secret.accessToken,
954
+ refresh: secret.refreshToken ?? secret.accessToken,
955
+ expires: 0,
956
+ ...secret.enterpriseUrl !== void 0 ? { enterpriseUrl: secret.enterpriseUrl } : {},
957
+ ...secret.apiEndpoint !== void 0 ? { apiEndpoint: secret.apiEndpoint } : {},
958
+ ...secret.availableModelIds !== void 0 ? { availableModelIds: [...secret.availableModelIds] } : {}
959
+ };
960
+ return {
961
+ token: secret.accessToken,
962
+ headers: gitHubCopilotHeaders(creds),
963
+ baseUrl: secret.apiEndpoint ?? (secret.enterpriseUrl ? gitHubCopilotBaseUrl({ enterpriseUrl: secret.enterpriseUrl }) : void 0)
964
+ };
965
+ }
966
+ if (handler === "openai-codex") {
967
+ const creds = {
968
+ access: secret.accessToken,
969
+ refresh: secret.refreshToken ?? "",
970
+ expires: secret.expiresAt ?? 0,
971
+ accountId: secret.accountId ?? getOpenAICodexAccountId(secret.accessToken) ?? ""
972
+ };
973
+ return {
974
+ token: secret.accessToken,
975
+ headers: creds.accountId ? openAICodexHeaders(creds) : void 0
976
+ };
977
+ }
978
+ return {
979
+ token: secret.accessToken,
980
+ headers: { Authorization: `Bearer ${secret.accessToken}` }
981
+ };
982
+ };
983
+ const applyHeaderInjection = (inject, token) => {
984
+ if (inject === void 0) return void 0;
985
+ return { [inject.name]: `${inject.prefix ?? ""}${token}` };
986
+ };
987
+ //#endregion
988
+ //#region src/connector/service.ts
989
+ const DEFAULT_OAUTH_MIN_VALIDITY_MS = 3e5;
990
+ var Service = class extends Context.Service()("@codeworksh/cli/connector/service") {};
991
+ const subjectFor = (row, actor) => row.ownership === "personal" ? {
992
+ type: "user",
993
+ id: actor.id
994
+ } : {
995
+ type: "app",
996
+ id: actor.scope
997
+ };
998
+ const readEnvVar = (env, vars) => {
999
+ for (const name of vars) {
1000
+ const raw = env[name]?.trim();
1001
+ if (raw !== void 0 && raw.length > 0) return {
1002
+ name,
1003
+ value: raw
1004
+ };
1005
+ }
1006
+ };
1007
+ const summarizeStored = (row, cred, now) => {
1008
+ let status = cred?.status ?? "not_connected";
1009
+ if (status === "active" && row.authType === "oauth" && cred?.expiresAt !== void 0 && cred.expiresAt <= now && cred.secret.type === "oauth" && !cred.secret.refreshToken) status = "expired";
1010
+ const sourceLabel = row.authType === "oauth" ? `OAuth (${row.ownership})` : `API key (${row.ownership})`;
1011
+ const accountLabel = cred?.secret.type === "oauth" ? cred.secret.accountLabel : void 0;
1012
+ return {
1013
+ id: row.id,
1014
+ uid: row.uid,
1015
+ connectorId: row.connectorId,
1016
+ workspaceId: row.workspaceId,
1017
+ ...row.label !== void 0 ? { label: row.label } : {},
1018
+ source: row.source,
1019
+ kinds: row.kinds,
1020
+ authType: row.authType,
1021
+ ownership: row.ownership,
1022
+ enabled: row.enabled,
1023
+ isDefault: row.isDefault,
1024
+ status,
1025
+ sourceLabel,
1026
+ ...accountLabel !== void 0 ? { accountLabel } : {},
1027
+ ...cred?.lastError !== void 0 ? { lastError: cred.lastError } : {},
1028
+ ...cred?.expiresAt !== void 0 ? { expiresAt: cred.expiresAt } : {},
1029
+ allowedHosts: row.allowedHosts,
1030
+ config: row.config,
1031
+ readOnly: false,
1032
+ createdAt: row.createdAt,
1033
+ updatedAt: row.updatedAt
1034
+ };
1035
+ };
1036
+ const summarizeEnv = (spec, workspaceId, envVar) => ({
1037
+ id: `env:${spec.id}`,
1038
+ uid: formatUid(spec.id, "env"),
1039
+ connectorId: spec.id,
1040
+ workspaceId,
1041
+ label: `${spec.name} (host env)`,
1042
+ source: "catalog",
1043
+ kinds: spec.kinds,
1044
+ authType: "env",
1045
+ ownership: "shared",
1046
+ enabled: true,
1047
+ isDefault: false,
1048
+ status: "active",
1049
+ sourceLabel: `$${envVar}`,
1050
+ envVar,
1051
+ allowedHosts: spec.allowedHosts,
1052
+ config: {},
1053
+ readOnly: true,
1054
+ createdAt: 0,
1055
+ updatedAt: 0
1056
+ });
1057
+ const resolveFields = (spec, row, env) => {
1058
+ const fieldSpecs = row.authType === "oauth" ? spec.auth.oauth?.fields : spec.auth.apikey?.fields;
1059
+ const merged = { ...row.config.fields };
1060
+ if (fieldSpecs) {
1061
+ for (const field of fieldSpecs) if (merged[field.key] === void 0 && field.envFallback) {
1062
+ const val = env[field.envFallback]?.trim();
1063
+ if (val) merged[field.key] = val;
1064
+ }
1065
+ }
1066
+ return Object.keys(merged).length > 0 ? merged : void 0;
1067
+ };
1068
+ const validateHost = (connectionId, uid, allowedHosts, targetHost) => {
1069
+ if (targetHost === void 0 || allowedHosts.length === 0) return Effect.void;
1070
+ if (hostMatches(targetHost, allowedHosts)) return Effect.void;
1071
+ return Effect.fail(new HostNotAllowedError({
1072
+ connectionId,
1073
+ uid,
1074
+ host: targetHost,
1075
+ allowedHosts: [...allowedHosts],
1076
+ message: `Host "${targetHost}" is not allowed for connection "${uid}"`
1077
+ }));
1078
+ };
1079
+ const make = (options = {}) => Effect.acquireRelease(Effect.gen(function* () {
1080
+ const home = (yield* Global.resolve(options.home === void 0 ? {} : { home: options.home })).home;
1081
+ const db = new ConnectionsDb(options.dbPath ?? connectionsDbPath(home));
1082
+ const legacyAuthFile = Global.authFile(options.home === void 0 ? void 0 : home) ?? Global.authFile(home);
1083
+ db.importLegacyAikitAuth(legacyAuthFile, yield* Clock.currentTimeMillis);
1084
+ let cachedCatalog = loadLocalCatalog(home);
1085
+ const pendingOAuth = new PendingOAuthStore();
1086
+ const refreshLocks = /* @__PURE__ */ new Map();
1087
+ const getEnv = () => options.env ?? process.env;
1088
+ const semaphoreFor = (key) => {
1089
+ let lock = refreshLocks.get(key);
1090
+ if (lock === void 0) {
1091
+ lock = Semaphore.makeUnsafe(1);
1092
+ refreshLocks.set(key, lock);
1093
+ }
1094
+ return lock;
1095
+ };
1096
+ const specForRow = (row) => row.source === "custom" ? row.spec : cachedCatalog.connectors[row.connectorId];
1097
+ const currentCatalog = (refresh) => Effect.gen(function* () {
1098
+ if (refresh) cachedCatalog = yield* fetchCatalog({
1099
+ home,
1100
+ url: options.catalogUrl,
1101
+ fetch: options.fetch
1102
+ });
1103
+ return cachedCatalog;
1104
+ });
1105
+ const resolveRowSecret = Effect.fn("Connector.resolveRowSecret")(function* (row, actor, input) {
1106
+ const spec = specForRow(row);
1107
+ if (spec === void 0) return yield* new ConnectorNotFoundError({
1108
+ connectorId: row.connectorId,
1109
+ message: `Connector "${row.connectorId}" is not in the catalog`
1110
+ });
1111
+ yield* validateHost(row.id, row.uid, row.allowedHosts, input.targetHost);
1112
+ if (!row.enabled) return yield* new AuthRequiredError({
1113
+ connectionId: row.id,
1114
+ uid: row.uid,
1115
+ connectorId: row.connectorId,
1116
+ reason: "not_connected",
1117
+ message: `Connection "${row.uid}" is disabled`
1118
+ });
1119
+ const subject = subjectFor(row, actor);
1120
+ const cred = db.getCredential(row.id, subject.type, subject.id);
1121
+ if (cred === void 0) return yield* new AuthRequiredError({
1122
+ connectionId: row.id,
1123
+ uid: row.uid,
1124
+ connectorId: row.connectorId,
1125
+ reason: "not_connected",
1126
+ message: `Connection "${row.uid}" has not been authenticated yet`
1127
+ });
1128
+ const fields = resolveFields(spec, row, getEnv());
1129
+ if (row.authType === "apikey") {
1130
+ if (cred.secret.type !== "apikey" || cred.secret.apiKey.length === 0) return yield* new AuthRequiredError({
1131
+ connectionId: row.id,
1132
+ uid: row.uid,
1133
+ connectorId: row.connectorId,
1134
+ reason: "not_connected",
1135
+ message: `Connection "${row.uid}" has no API key stored`
1136
+ });
1137
+ const headers = applyHeaderInjection(spec.auth.apikey?.inject, cred.secret.apiKey);
1138
+ return {
1139
+ connectionId: row.id,
1140
+ uid: row.uid,
1141
+ token: Redacted.make(cred.secret.apiKey),
1142
+ ...headers !== void 0 ? { headers } : {},
1143
+ ...spec.capabilities.provider?.baseUrl !== void 0 ? { baseUrl: spec.capabilities.provider.baseUrl } : {},
1144
+ ...fields !== void 0 ? { fields } : {},
1145
+ sourceLabel: `API key (${row.ownership})`
1146
+ };
1147
+ }
1148
+ if (cred.secret.type !== "oauth") return yield* new AuthRequiredError({
1149
+ connectionId: row.id,
1150
+ uid: row.uid,
1151
+ connectorId: row.connectorId,
1152
+ reason: "not_connected",
1153
+ message: `Connection "${row.uid}" is missing OAuth credentials`
1154
+ });
1155
+ const minValidity = Math.max(DEFAULT_OAUTH_MIN_VALIDITY_MS, input.minValidityMs ?? 0);
1156
+ const needsRefresh = (secret, now) => secret.expiresAt !== void 0 && secret.expiresAt > 0 && now + minValidity >= secret.expiresAt;
1157
+ let activeSecret = cred.secret;
1158
+ if (needsRefresh(activeSecret, yield* Clock.currentTimeMillis)) {
1159
+ const lockKey = `${row.id}:${subject.type}:${subject.id}`;
1160
+ activeSecret = yield* semaphoreFor(lockKey).withPermits(1)(Effect.gen(function* () {
1161
+ const latest = db.getCredential(row.id, subject.type, subject.id);
1162
+ if (latest === void 0 || latest.secret.type !== "oauth") return yield* new AuthRequiredError({
1163
+ connectionId: row.id,
1164
+ uid: row.uid,
1165
+ connectorId: row.connectorId,
1166
+ reason: "not_connected",
1167
+ message: `Connection "${row.uid}" was disconnected`
1168
+ });
1169
+ if (!needsRefresh(latest.secret, yield* Clock.currentTimeMillis)) return latest.secret;
1170
+ return yield* Effect.uninterruptible(Effect.tryPromise({
1171
+ try: () => refreshOAuthSecret(spec, latest.secret, options.fetch),
1172
+ catch: (cause) => cause instanceof Error ? cause.message : String(cause)
1173
+ }).pipe(Effect.tap((refreshed) => Clock.currentTimeMillis.pipe(Effect.map((now) => {
1174
+ db.withImmediateTx(() => {
1175
+ db.upsertCredential({
1176
+ connectionId: row.id,
1177
+ subjectType: subject.type,
1178
+ subjectId: subject.id,
1179
+ secret: refreshed,
1180
+ status: "active",
1181
+ ...refreshed.expiresAt !== void 0 ? { expiresAt: refreshed.expiresAt } : {},
1182
+ now
1183
+ });
1184
+ });
1185
+ }))), Effect.catch((message) => Clock.currentTimeMillis.pipe(Effect.flatMap((now) => Effect.sync(() => {
1186
+ db.markCredentialStatus(row.id, subject.type, subject.id, "expired", message, now);
1187
+ })), Effect.flatMap(() => Effect.fail(new AuthRequiredError({
1188
+ connectionId: row.id,
1189
+ uid: row.uid,
1190
+ connectorId: row.connectorId,
1191
+ reason: "expired",
1192
+ message: `OAuth refresh failed for "${row.uid}": ${message}`
1193
+ })))))));
1194
+ }));
1195
+ }
1196
+ const derived = deriveOAuthRequestAuth(spec, activeSecret);
1197
+ return {
1198
+ connectionId: row.id,
1199
+ uid: row.uid,
1200
+ token: Redacted.make(derived.token),
1201
+ ...derived.headers !== void 0 ? { headers: derived.headers } : {},
1202
+ ...derived.baseUrl !== void 0 ? { baseUrl: derived.baseUrl } : {},
1203
+ ...fields !== void 0 ? { fields } : {},
1204
+ sourceLabel: `OAuth (${row.ownership})`,
1205
+ ...activeSecret.expiresAt !== void 0 ? { expiresAt: activeSecret.expiresAt } : {}
1206
+ };
1207
+ });
1208
+ const resolveEnvFallback = (spec, targetHost) => Effect.gen(function* () {
1209
+ const envSpec = spec.auth.env;
1210
+ if (envSpec === void 0) return void 0;
1211
+ const found = readEnvVar(getEnv(), envSpec.vars);
1212
+ if (found === void 0) return void 0;
1213
+ const id = `env:${spec.id}`;
1214
+ const uid = formatUid(spec.id, "env");
1215
+ yield* validateHost(id, uid, spec.allowedHosts, targetHost);
1216
+ const headers = applyHeaderInjection(envSpec.inject, found.value);
1217
+ return {
1218
+ connectionId: id,
1219
+ uid,
1220
+ token: Redacted.make(found.value),
1221
+ ...headers !== void 0 ? { headers } : {},
1222
+ ...spec.capabilities.provider?.baseUrl !== void 0 ? { baseUrl: spec.capabilities.provider.baseUrl } : {},
1223
+ sourceLabel: `$${found.name}`
1224
+ };
1225
+ });
1226
+ return {
1227
+ db,
1228
+ service: {
1229
+ catalog: (filter = {}) => Effect.gen(function* () {
1230
+ const cat = yield* currentCatalog(filter.refresh);
1231
+ const catalogFilter = {
1232
+ kind: filter.kind,
1233
+ category: filter.category,
1234
+ query: filter.query
1235
+ };
1236
+ return {
1237
+ schemaVersion: cat.schemaVersion,
1238
+ generatedAt: cat.generatedAt,
1239
+ categories: cat.categories,
1240
+ connectors: filterConnectors(cat, catalogFilter)
1241
+ };
1242
+ }),
1243
+ list: (filter = {}) => Effect.gen(function* () {
1244
+ const actor = yield* Actor.Current;
1245
+ const now = yield* Clock.currentTimeMillis;
1246
+ const summaries = db.listConnections(actor.scope, {
1247
+ kind: filter.kind,
1248
+ connectorId: filter.connectorId,
1249
+ enabled: filter.enabled
1250
+ }).map((row) => {
1251
+ const subject = subjectFor(row, actor);
1252
+ return summarizeStored(row, db.getCredential(row.id, subject.type, subject.id), now);
1253
+ });
1254
+ if (filter.includeEnv !== false && filter.enabled !== false) {
1255
+ const env = getEnv();
1256
+ for (const spec of Object.values(cachedCatalog.connectors)) {
1257
+ if (filter.kind !== void 0 && !spec.kinds.includes(filter.kind)) continue;
1258
+ if (filter.connectorId !== void 0 && spec.id !== filter.connectorId) continue;
1259
+ if (spec.auth.env === void 0) continue;
1260
+ const found = readEnvVar(env, spec.auth.env.vars);
1261
+ if (found !== void 0) summaries.push(summarizeEnv(spec, actor.scope, found.name));
1262
+ }
1263
+ }
1264
+ return summaries;
1265
+ }),
1266
+ get: (ref) => Effect.gen(function* () {
1267
+ const actor = yield* Actor.Current;
1268
+ const now = yield* Clock.currentTimeMillis;
1269
+ const row = db.findConnection(actor.scope, ref);
1270
+ if (row !== void 0) {
1271
+ const subject = subjectFor(row, actor);
1272
+ return summarizeStored(row, db.getCredential(row.id, subject.type, subject.id), now);
1273
+ }
1274
+ for (const spec of Object.values(cachedCatalog.connectors)) {
1275
+ if (spec.auth.env === void 0) continue;
1276
+ if (ref === `env:${spec.id}` || ref === formatUid(spec.id, "env")) {
1277
+ const found = readEnvVar(getEnv(), spec.auth.env.vars);
1278
+ if (found !== void 0) return summarizeEnv(spec, actor.scope, found.name);
1279
+ }
1280
+ }
1281
+ return yield* new ConnectionNotFoundError({
1282
+ ref,
1283
+ message: `Connection "${ref}" not found`
1284
+ });
1285
+ }),
1286
+ create: (input) => Effect.gen(function* () {
1287
+ const actor = yield* Actor.Current;
1288
+ const spec = findConnector(cachedCatalog, input.connector);
1289
+ if (spec === void 0) return yield* new ConnectorNotFoundError({
1290
+ connectorId: input.connector,
1291
+ message: `Unknown connector "${input.connector}"`
1292
+ });
1293
+ const slug = (input.slug ?? "default").trim().toLowerCase();
1294
+ if (!CONNECTION_SLUG_PATTERN.test(slug)) return yield* new ConnectorValidationError({ message: `Invalid connection name "${slug}". Use lowercase letters, numbers, and hyphens.` });
1295
+ const uid = formatUid(spec.id, slug);
1296
+ if (db.findConnection(actor.scope, uid) !== void 0) return yield* new ConnectionConflictError({
1297
+ uid,
1298
+ message: `Connection "${uid}" already exists in this workspace`
1299
+ });
1300
+ const chosenAuth = input.authType ?? (spec.auth.oauth !== void 0 ? "oauth" : spec.auth.apikey !== void 0 ? "apikey" : void 0);
1301
+ if (chosenAuth === void 0) return yield* new ConnectorValidationError({ message: `Connector "${spec.id}" has no storable auth method` });
1302
+ if (chosenAuth === "oauth" && spec.auth.oauth === void 0) return yield* new ConnectorValidationError({ message: `Connector "${spec.id}" does not support OAuth` });
1303
+ if (chosenAuth === "apikey" && spec.auth.apikey === void 0) return yield* new ConnectorValidationError({ message: `Connector "${spec.id}" does not support API key authentication` });
1304
+ const ownership = input.ownership ?? (chosenAuth === "oauth" ? spec.auth.oauth?.defaultOwnership ?? "personal" : spec.auth.apikey?.defaultOwnership ?? "shared");
1305
+ const existingSame = db.listConnections(actor.scope, { connectorId: spec.id });
1306
+ const isDefault = input.isDefault ?? existingSame.length === 0;
1307
+ const now = yield* Clock.currentTimeMillis;
1308
+ const row = db.insertConnection({
1309
+ id: ConnectionID.create(),
1310
+ workspaceId: actor.scope,
1311
+ uid,
1312
+ label: input.label ?? spec.name,
1313
+ source: "catalog",
1314
+ connectorId: spec.id,
1315
+ kinds: spec.kinds,
1316
+ authType: chosenAuth,
1317
+ ownership,
1318
+ enabled: input.enabled ?? true,
1319
+ isDefault,
1320
+ allowedHosts: spec.allowedHosts,
1321
+ config: input.config ?? {},
1322
+ now
1323
+ });
1324
+ return summarizeStored(row, void 0, now);
1325
+ }),
1326
+ update: (input) => Effect.gen(function* () {
1327
+ const actor = yield* Actor.Current;
1328
+ const row = db.findConnection(actor.scope, input.ref);
1329
+ if (row === void 0) return yield* new ConnectionNotFoundError({
1330
+ ref: input.ref,
1331
+ message: `Connection "${input.ref}" not found`
1332
+ });
1333
+ if (input.uid !== void 0 && input.uid !== row.uid) {
1334
+ if (!CONNECTION_UID_PATTERN.test(input.uid)) return yield* new ConnectorValidationError({ message: `Invalid connection uid "${input.uid}"` });
1335
+ if (db.findConnection(actor.scope, input.uid) !== void 0) return yield* new ConnectionConflictError({
1336
+ uid: input.uid,
1337
+ message: `Connection "${input.uid}" already exists in this workspace`
1338
+ });
1339
+ }
1340
+ const now = yield* Clock.currentTimeMillis;
1341
+ const updated = db.updateConnection(row.id, {
1342
+ uid: input.uid,
1343
+ label: input.label,
1344
+ ownership: input.ownership,
1345
+ enabled: input.enabled,
1346
+ isDefault: input.isDefault,
1347
+ config: input.config,
1348
+ now
1349
+ });
1350
+ if (updated === void 0) return yield* new ConnectionNotFoundError({
1351
+ ref: input.ref,
1352
+ message: `Connection "${input.ref}" not found`
1353
+ });
1354
+ const subject = subjectFor(updated, actor);
1355
+ return summarizeStored(updated, db.getCredential(updated.id, subject.type, subject.id), now);
1356
+ }),
1357
+ remove: (ref) => Effect.gen(function* () {
1358
+ const actor = yield* Actor.Current;
1359
+ const row = db.findConnection(actor.scope, ref);
1360
+ if (row === void 0) return false;
1361
+ return db.deleteConnection(row.id);
1362
+ }),
1363
+ setApiKey: (ref, apiKey) => Effect.gen(function* () {
1364
+ const actor = yield* Actor.Current;
1365
+ const trimmed = apiKey.trim();
1366
+ if (trimmed.length === 0) return yield* new ConnectorValidationError({ message: "API key cannot be empty" });
1367
+ const row = db.findConnection(actor.scope, ref);
1368
+ if (row === void 0) return yield* new ConnectionNotFoundError({
1369
+ ref,
1370
+ message: `Connection "${ref}" not found`
1371
+ });
1372
+ if (row.authType !== "apikey") return yield* new ConnectorValidationError({ message: `Connection "${row.uid}" uses ${row.authType}, not apikey` });
1373
+ const now = yield* Clock.currentTimeMillis;
1374
+ const subject = subjectFor(row, actor);
1375
+ const cred = db.upsertCredential({
1376
+ connectionId: row.id,
1377
+ subjectType: subject.type,
1378
+ subjectId: subject.id,
1379
+ secret: {
1380
+ type: "apikey",
1381
+ apiKey: trimmed
1382
+ },
1383
+ status: "active",
1384
+ now
1385
+ });
1386
+ return summarizeStored(row, cred, now);
1387
+ }),
1388
+ disconnect: (ref) => Effect.gen(function* () {
1389
+ const actor = yield* Actor.Current;
1390
+ const now = yield* Clock.currentTimeMillis;
1391
+ const row = db.findConnection(actor.scope, ref);
1392
+ if (row === void 0) return yield* new ConnectionNotFoundError({
1393
+ ref,
1394
+ message: `Connection "${ref}" not found`
1395
+ });
1396
+ const subject = subjectFor(row, actor);
1397
+ db.deleteCredential(row.id, subject.type, subject.id);
1398
+ return summarizeStored(row, void 0, now);
1399
+ }),
1400
+ oauthStart: (input) => Effect.gen(function* () {
1401
+ const actor = yield* Actor.Current;
1402
+ const row = db.findConnection(actor.scope, input.ref);
1403
+ if (row === void 0) return yield* new ConnectionNotFoundError({
1404
+ ref: input.ref,
1405
+ message: `Connection "${input.ref}" not found`
1406
+ });
1407
+ if (row.authType !== "oauth") return yield* new ConnectorValidationError({ message: `Connection "${row.uid}" uses ${row.authType}, not oauth` });
1408
+ const spec = specForRow(row);
1409
+ if (spec === void 0) return yield* new ConnectorNotFoundError({
1410
+ connectorId: row.connectorId,
1411
+ message: `Connector "${row.connectorId}" is not in the catalog`
1412
+ });
1413
+ return yield* startAuthCodeFlow({
1414
+ store: pendingOAuth,
1415
+ connector: spec,
1416
+ connection: row,
1417
+ redirectUrl: input.redirectUrl,
1418
+ scopes: input.scopes,
1419
+ workspaceId: actor.scope,
1420
+ actorId: actor.id,
1421
+ fetch: options.fetch
1422
+ });
1423
+ }),
1424
+ oauthFinish: (input) => Effect.gen(function* () {
1425
+ const actor = yield* Actor.Current;
1426
+ const { connectionId, secret } = yield* finishAuthCodeFlow({
1427
+ store: pendingOAuth,
1428
+ state: input.state,
1429
+ codeOrUrl: input.code,
1430
+ workspaceId: actor.scope,
1431
+ actorId: actor.id,
1432
+ fetch: options.fetch
1433
+ });
1434
+ const row = db.findConnectionById(connectionId);
1435
+ if (row === void 0 || row.workspaceId !== actor.scope) return yield* new ConnectionNotFoundError({
1436
+ ref: connectionId,
1437
+ message: `Connection "${connectionId}" no longer exists`
1438
+ });
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
+ status: "active",
1447
+ ...secret.expiresAt !== void 0 ? { expiresAt: secret.expiresAt } : {},
1448
+ now
1449
+ });
1450
+ return summarizeStored(row, cred, now);
1451
+ }),
1452
+ deviceStart: (input) => Effect.gen(function* () {
1453
+ const actor = yield* Actor.Current;
1454
+ const row = db.findConnection(actor.scope, input.ref);
1455
+ if (row === void 0) return yield* new ConnectionNotFoundError({
1456
+ ref: input.ref,
1457
+ message: `Connection "${input.ref}" not found`
1458
+ });
1459
+ if (row.authType !== "oauth") return yield* new ConnectorValidationError({ message: `Connection "${row.uid}" uses ${row.authType}, not oauth` });
1460
+ const spec = specForRow(row);
1461
+ if (spec === void 0) return yield* new ConnectorNotFoundError({
1462
+ connectorId: row.connectorId,
1463
+ message: `Connector "${row.connectorId}" is not in the catalog`
1464
+ });
1465
+ if (input.enterpriseUrl !== void 0) {
1466
+ const now = yield* Clock.currentTimeMillis;
1467
+ db.updateConnection(row.id, {
1468
+ config: {
1469
+ ...row.config,
1470
+ fields: {
1471
+ ...row.config.fields,
1472
+ enterpriseUrl: input.enterpriseUrl
1473
+ }
1474
+ },
1475
+ now
1476
+ });
1477
+ }
1478
+ return yield* startDeviceCodeFlow({
1479
+ store: pendingOAuth,
1480
+ connector: spec,
1481
+ connection: row,
1482
+ enterpriseUrl: input.enterpriseUrl,
1483
+ workspaceId: actor.scope,
1484
+ actorId: actor.id,
1485
+ fetch: options.fetch
1486
+ });
1487
+ }),
1488
+ devicePoll: (state) => Effect.gen(function* () {
1489
+ const actor = yield* Actor.Current;
1490
+ const step = yield* pollDeviceCodeStep({
1491
+ store: pendingOAuth,
1492
+ state,
1493
+ workspaceId: actor.scope,
1494
+ actorId: actor.id,
1495
+ fetch: options.fetch
1496
+ });
1497
+ if (step.status === "pending") return {
1498
+ status: "pending",
1499
+ ...step.intervalSeconds !== void 0 ? { intervalSeconds: step.intervalSeconds } : {}
1500
+ };
1501
+ const row = db.findConnectionById(step.connectionId);
1502
+ if (row === void 0 || row.workspaceId !== actor.scope) return yield* new ConnectionNotFoundError({
1503
+ ref: step.connectionId,
1504
+ message: `Connection "${step.connectionId}" no longer exists`
1505
+ });
1506
+ const now = yield* Clock.currentTimeMillis;
1507
+ const subject = subjectFor(row, actor);
1508
+ const cred = db.upsertCredential({
1509
+ connectionId: row.id,
1510
+ subjectType: subject.type,
1511
+ subjectId: subject.id,
1512
+ secret: step.secret,
1513
+ status: "active",
1514
+ ...step.secret.expiresAt !== void 0 ? { expiresAt: step.secret.expiresAt } : {},
1515
+ now
1516
+ });
1517
+ return {
1518
+ status: "complete",
1519
+ connection: summarizeStored(row, cred, now)
1520
+ };
1521
+ }),
1522
+ resolve: (input) => Effect.gen(function* () {
1523
+ const actor = yield* Actor.Current;
1524
+ const row = db.findConnection(actor.scope, input.ref);
1525
+ if (row !== void 0) return yield* resolveRowSecret(row, actor, {
1526
+ targetHost: input.targetHost,
1527
+ minValidityMs: input.minValidityMs
1528
+ });
1529
+ for (const spec of Object.values(cachedCatalog.connectors)) if (input.ref === `env:${spec.id}` || input.ref === formatUid(spec.id, "env")) {
1530
+ const resolved = yield* resolveEnvFallback(spec, input.targetHost);
1531
+ if (resolved !== void 0) return resolved;
1532
+ }
1533
+ return yield* new ConnectionNotFoundError({
1534
+ ref: input.ref,
1535
+ message: `Connection "${input.ref}" not found`
1536
+ });
1537
+ }),
1538
+ resolveProvider: (providerId) => Effect.gen(function* () {
1539
+ const actor = yield* Actor.Current;
1540
+ const spec = findConnectorByProviderId(cachedCatalog, providerId);
1541
+ if (spec === void 0) return void 0;
1542
+ const rows = db.listConnections(actor.scope, {
1543
+ connectorId: spec.id,
1544
+ enabled: true
1545
+ });
1546
+ const chosen = rows.find((r) => r.isDefault) ?? rows[0];
1547
+ if (chosen !== void 0) return yield* resolveRowSecret(chosen, actor, {});
1548
+ return yield* resolveEnvFallback(spec, void 0);
1549
+ }),
1550
+ listMcpConnections: () => Effect.gen(function* () {
1551
+ const actor = yield* Actor.Current;
1552
+ const rows = db.listConnections(actor.scope, {
1553
+ kind: "mcp",
1554
+ enabled: true
1555
+ });
1556
+ const active = [];
1557
+ const seenConnectors = /* @__PURE__ */ new Set();
1558
+ for (const row of rows) {
1559
+ const spec = specForRow(row);
1560
+ const mcp = spec?.capabilities.mcp;
1561
+ if (spec === void 0 || mcp === void 0) continue;
1562
+ seenConnectors.add(row.connectorId);
1563
+ active.push({
1564
+ id: row.id,
1565
+ uid: row.uid,
1566
+ connectorId: row.connectorId,
1567
+ name: row.label ?? spec.name,
1568
+ url: mcp.url,
1569
+ transport: mcp.transport ?? "http",
1570
+ exposure: row.config.mcp?.exposure ?? mcp.defaultExposure ?? "eager",
1571
+ authType: row.authType,
1572
+ ...row.authType === "apikey" && spec.auth.apikey?.inject !== void 0 ? { inject: spec.auth.apikey.inject } : {},
1573
+ allowedHosts: row.allowedHosts
1574
+ });
1575
+ }
1576
+ const env = getEnv();
1577
+ for (const spec of Object.values(cachedCatalog.connectors)) {
1578
+ if (seenConnectors.has(spec.id)) continue;
1579
+ const mcp = spec.capabilities.mcp;
1580
+ if (mcp === void 0 || spec.auth.env === void 0) continue;
1581
+ if (readEnvVar(env, spec.auth.env.vars) === void 0) continue;
1582
+ active.push({
1583
+ id: `env:${spec.id}`,
1584
+ uid: formatUid(spec.id, "env"),
1585
+ connectorId: spec.id,
1586
+ name: spec.name,
1587
+ url: mcp.url,
1588
+ transport: mcp.transport ?? "http",
1589
+ exposure: mcp.defaultExposure ?? "eager",
1590
+ authType: "env",
1591
+ ...spec.auth.env.inject !== void 0 ? { inject: spec.auth.env.inject } : {},
1592
+ allowedHosts: spec.allowedHosts
1593
+ });
1594
+ }
1595
+ return active;
1596
+ }),
1597
+ listProviderStates: () => Effect.gen(function* () {
1598
+ const actor = yield* Actor.Current;
1599
+ const now = yield* Clock.currentTimeMillis;
1600
+ const states = [];
1601
+ const env = getEnv();
1602
+ for (const spec of Object.values(cachedCatalog.connectors)) {
1603
+ const providerId = spec.capabilities.provider?.providerId;
1604
+ if (providerId === void 0) continue;
1605
+ const rows = db.listConnections(actor.scope, {
1606
+ connectorId: spec.id,
1607
+ enabled: true
1608
+ });
1609
+ const chosen = rows.find((r) => r.isDefault) ?? rows[0];
1610
+ if (chosen !== void 0) {
1611
+ const subject = subjectFor(chosen, actor);
1612
+ const cred = db.getCredential(chosen.id, subject.type, subject.id);
1613
+ const summary = summarizeStored(chosen, cred, now);
1614
+ const oauthSecret = cred?.secret.type === "oauth" ? cred.secret : void 0;
1615
+ states.push({
1616
+ providerId,
1617
+ connectorId: spec.id,
1618
+ uid: chosen.uid,
1619
+ authType: chosen.authType,
1620
+ status: summary.status,
1621
+ sourceLabel: summary.sourceLabel,
1622
+ ...oauthSecret?.apiEndpoint !== void 0 ? { apiEndpoint: oauthSecret.apiEndpoint } : {},
1623
+ ...oauthSecret?.availableModelIds !== void 0 ? { availableModelIds: oauthSecret.availableModelIds } : {}
1624
+ });
1625
+ continue;
1626
+ }
1627
+ if (spec.auth.env !== void 0) {
1628
+ const found = readEnvVar(env, spec.auth.env.vars);
1629
+ if (found !== void 0) states.push({
1630
+ providerId,
1631
+ connectorId: spec.id,
1632
+ uid: formatUid(spec.id, "env"),
1633
+ authType: "env",
1634
+ status: "active",
1635
+ sourceLabel: `$${found.name}`
1636
+ });
1637
+ }
1638
+ }
1639
+ return states;
1640
+ })
1641
+ }
1642
+ };
1643
+ }), ({ db }) => Effect.sync(() => db.close())).pipe(Effect.map(({ service }) => service));
1644
+ /**
1645
+ * Provides both the full host `Connector.Service` and the narrowed `@codeworksh/plugin/connector` `Broker`
1646
+ * backed by the exact same `<home>/connections.db` instance.
1647
+ */
1648
+ const layer = (options = {}) => Layer.effectContext(make(options).pipe(Effect.map((service) => Context.empty().pipe(Context.add(Service, service), Context.add(Connector.Broker, service)))));
1649
+ //#endregion
1650
+ export { layer as n, Service as t };
1651
+
1652
+ //# sourceMappingURL=service-CA6VAOdR.mjs.map