integration.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. export * as Integration from "./integration"
  2. import { makeLocationNode } from "./effect/app-node"
  3. import {
  4. Cause,
  5. Clock,
  6. Context,
  7. Duration,
  8. Effect,
  9. Exit,
  10. Layer,
  11. Schedule,
  12. Schema,
  13. Scope,
  14. SynchronizedRef,
  15. Types,
  16. } from "effect"
  17. import { Integration } from "@kirincode-ai/schema/integration"
  18. import { Credential } from "./credential"
  19. import { State } from "./state"
  20. import { EventV2 } from "./event"
  21. import { IntegrationConnection } from "./integration/connection"
  22. export const ID = Integration.ID
  23. export type ID = Integration.ID
  24. export const MethodID = Integration.MethodID
  25. export type MethodID = Integration.MethodID
  26. export const AttemptID = Integration.AttemptID
  27. export type AttemptID = typeof AttemptID.Type
  28. export const When = Integration.When
  29. export type When = Integration.When
  30. export const TextPrompt = Integration.TextPrompt
  31. export type TextPrompt = Integration.TextPrompt
  32. export const SelectPrompt = Integration.SelectPrompt
  33. export type SelectPrompt = Integration.SelectPrompt
  34. export const Prompt = Integration.Prompt
  35. export type Prompt = Integration.Prompt
  36. export const OAuthMethod = Integration.OAuthMethod
  37. export type OAuthMethod = Integration.OAuthMethod
  38. export const KeyMethod = Integration.KeyMethod
  39. export type KeyMethod = Integration.KeyMethod
  40. export const EnvMethod = Integration.EnvMethod
  41. export type EnvMethod = Integration.EnvMethod
  42. export const Method = Integration.Method
  43. export type Method = Integration.Method
  44. export const Info = Integration.Info
  45. export type Info = Integration.Info
  46. export const Inputs = Integration.Inputs
  47. export type Inputs = Integration.Inputs
  48. export type OAuthAuthorization = {
  49. readonly url: string
  50. readonly instructions: string
  51. } & (
  52. | {
  53. readonly mode: "auto"
  54. readonly callback: Effect.Effect<Credential.OAuth, unknown>
  55. }
  56. | {
  57. readonly mode: "code"
  58. readonly callback: (code: string) => Effect.Effect<Credential.OAuth, unknown>
  59. }
  60. )
  61. export interface OAuthImplementation {
  62. readonly integrationID: ID
  63. readonly method: OAuthMethod
  64. readonly authorize: (inputs: Inputs) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope>
  65. readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
  66. readonly label?: (credential: Credential.OAuth) => string | undefined
  67. }
  68. export interface KeyImplementation {
  69. readonly integrationID: ID
  70. readonly method: KeyMethod
  71. }
  72. export interface EnvImplementation {
  73. readonly integrationID: ID
  74. readonly method: EnvMethod
  75. }
  76. export type Implementation = OAuthImplementation | KeyImplementation | EnvImplementation
  77. export const Attempt = Integration.Attempt
  78. export type Attempt = Integration.Attempt
  79. export const AttemptStatus = Integration.AttemptStatus
  80. export type AttemptStatus = typeof AttemptStatus.Type
  81. export class CodeRequiredError extends Schema.TaggedErrorClass<CodeRequiredError>()("Integration.CodeRequired", {
  82. attemptID: AttemptID,
  83. }) {}
  84. export class AuthorizationError extends Schema.TaggedErrorClass<AuthorizationError>()("Integration.Authorization", {
  85. cause: Schema.Defect(),
  86. }) {}
  87. export type Error = CodeRequiredError | AuthorizationError
  88. export const Event = Integration.Event
  89. export const Ref = Integration.Ref
  90. export type Ref = Integration.Ref
  91. type Entry = {
  92. ref: Types.DeepMutable<Ref>
  93. methods: Types.DeepMutable<Method>[]
  94. implementations: Map<MethodID, Types.DeepMutable<OAuthImplementation>>
  95. }
  96. type Data = {
  97. integrations: Map<ID, Entry>
  98. }
  99. export type Draft = {
  100. list: () => readonly Ref[]
  101. get: (id: ID) => Ref | undefined
  102. update: (id: ID, update: (integration: Types.DeepMutable<Ref>) => void) => void
  103. remove: (id: ID) => void
  104. method: {
  105. list: (integrationID: ID) => readonly Method[]
  106. update: (implementation: Implementation) => void
  107. remove: (integrationID: ID, method: Method) => void
  108. }
  109. }
  110. export interface Interface extends State.Transformable<Draft> {
  111. /** Registers a scoped transform over the integration registry. */
  112. /** Returns one integration with its methods and current connections. */
  113. readonly get: (id: ID) => Effect.Effect<Info | undefined>
  114. /** Returns all integrations with their methods and current connections. */
  115. readonly list: () => Effect.Effect<Info[]>
  116. readonly connection: {
  117. /** Returns the active connection for one integration. */
  118. readonly active: (id: ID) => Effect.Effect<IntegrationConnection.Info | undefined>
  119. /** Resolves a connection into usable credential material. */
  120. readonly resolve: (
  121. connection: IntegrationConnection.Info,
  122. ) => Effect.Effect<Credential.Value | undefined, AuthorizationError>
  123. /** Runs a key method and stores the resulting credential. */
  124. readonly key: (input: {
  125. /** Integration receiving the credential. */
  126. readonly integrationID: ID
  127. /** Secret entered by the user. */
  128. readonly key: string
  129. /** User-facing label for the stored credential. */
  130. readonly label?: string
  131. }) => Effect.Effect<void, AuthorizationError>
  132. /** Starts a stateful OAuth attempt. */
  133. readonly oauth: (input: {
  134. /** Integration being authenticated. */
  135. readonly integrationID: ID
  136. /** OAuth method selected by the caller. */
  137. readonly methodID: MethodID
  138. /** Answers to the method's optional prompts. */
  139. readonly inputs: Inputs
  140. /** User-facing label for the credential created on completion. */
  141. readonly label?: string
  142. }) => Effect.Effect<Attempt, AuthorizationError>
  143. /** Updates a stored credential exposed as a connection. */
  144. readonly update: (
  145. credentialID: Credential.ID,
  146. updates: Partial<Pick<Credential.Info, "label">>,
  147. ) => Effect.Effect<void>
  148. /** Removes a stored credential connection. */
  149. readonly remove: (credentialID: Credential.ID) => Effect.Effect<void>
  150. }
  151. readonly attempt: {
  152. /** Returns the current state of an OAuth attempt. */
  153. readonly status: (attemptID: AttemptID) => Effect.Effect<AttemptStatus>
  154. /** Completes the attempt and stores its credential. */
  155. readonly complete: (input: {
  156. /** Opaque handle returned by `oauth`. */
  157. readonly attemptID: AttemptID
  158. /** Authorization code required by attempts in code mode. */
  159. readonly code?: string
  160. }) => Effect.Effect<void, CodeRequiredError | AuthorizationError>
  161. /** Cancels an attempt and releases its resources. */
  162. readonly cancel: (attemptID: AttemptID) => Effect.Effect<void>
  163. }
  164. }
  165. export class Service extends Context.Service<Service, Interface>()("@kirincode/v2/Integration") {}
  166. const attemptLifetime = Duration.toMillis(Duration.minutes(10))
  167. const terminalRetention = Duration.toMillis(Duration.minutes(1))
  168. const scrubInterval = Duration.seconds(30)
  169. type AttemptTime = { created: number; expires: number }
  170. type PendingAttempt = {
  171. status: "pending"
  172. completing: boolean
  173. authorization: OAuthAuthorization
  174. integrationID: ID
  175. methodID: MethodID
  176. label?: string
  177. scope: Scope.Closeable
  178. time: AttemptTime
  179. }
  180. type TerminalAttempt = {
  181. status: "complete" | "failed" | "expired"
  182. message?: string
  183. removeAt: number
  184. time: AttemptTime
  185. }
  186. type AttemptEntry = PendingAttempt | TerminalAttempt
  187. export const locationLayer = Layer.effect(
  188. Service,
  189. Effect.gen(function* () {
  190. const credentials = yield* Credential.Service
  191. const events = yield* EventV2.Service
  192. const scope = yield* Scope.Scope
  193. const attempts = SynchronizedRef.makeUnsafe(new Map<AttemptID, AttemptEntry>())
  194. const state = State.create<Data, Draft>({
  195. initial: () => ({ integrations: new Map<ID, Entry>() }),
  196. draft: (draft) => ({
  197. list: () => Array.from(draft.integrations.values(), (entry) => entry.ref) as Ref[],
  198. get: (id) => draft.integrations.get(id)?.ref as Ref | undefined,
  199. update: (id, update) => {
  200. const current = draft.integrations.get(id) ?? {
  201. ref: { id, name: id },
  202. methods: [],
  203. implementations: new Map(),
  204. }
  205. if (!draft.integrations.has(id)) draft.integrations.set(id, current)
  206. update(current.ref)
  207. current.ref.id = id
  208. },
  209. remove: (id) => draft.integrations.delete(id),
  210. method: {
  211. list: (integrationID) => (draft.integrations.get(integrationID)?.methods as Method[] | undefined) ?? [],
  212. update: (implementation) => {
  213. const current = draft.integrations.get(implementation.integrationID) ?? {
  214. ref: {
  215. id: implementation.integrationID,
  216. name: implementation.integrationID,
  217. },
  218. methods: [],
  219. implementations: new Map<MethodID, Types.DeepMutable<OAuthImplementation>>(),
  220. }
  221. if (!draft.integrations.has(implementation.integrationID)) {
  222. draft.integrations.set(implementation.integrationID, current)
  223. }
  224. const index = current.methods.findIndex((method) => {
  225. if (method.type !== implementation.method.type) return false
  226. if (method.type !== "oauth" || implementation.method.type !== "oauth") return true
  227. return method.id === implementation.method.id
  228. })
  229. if (index === -1) current.methods.push(implementation.method as Types.DeepMutable<Method>)
  230. else current.methods[index] = implementation.method as Types.DeepMutable<Method>
  231. if (implementation.method.type === "oauth") {
  232. current.implementations.set(
  233. implementation.method.id,
  234. implementation as Types.DeepMutable<OAuthImplementation>,
  235. )
  236. }
  237. },
  238. remove: (integrationID, method) => {
  239. const current = draft.integrations.get(integrationID)
  240. if (!current) return
  241. const index = current.methods.findIndex((candidate) => {
  242. if (candidate.type !== method.type) return false
  243. if (candidate.type !== "oauth" || method.type !== "oauth") return true
  244. return candidate.id === method.id
  245. })
  246. if (index !== -1) current.methods.splice(index, 1)
  247. if (method.type === "oauth") current.implementations.delete(method.id)
  248. },
  249. },
  250. }),
  251. finalize: () => events.publish(Event.Updated, {}).pipe(Effect.asVoid),
  252. })
  253. const resolveConnections = (entry: Entry | undefined, saved: readonly Credential.Info[]) => {
  254. const credentials = saved
  255. .map((credential) => ({
  256. type: "credential" as const,
  257. id: credential.id,
  258. label: credential.label,
  259. }))
  260. .toReversed()
  261. const env = (entry?.methods ?? [])
  262. .filter((method) => method.type === "env")
  263. .flatMap((method) => method.names.filter((name) => process.env[name]))
  264. .map((name) => ({ type: "env" as const, name }))
  265. return [...credentials, ...env]
  266. }
  267. const project = (entry: Entry, connections: IntegrationConnection.Info[]) =>
  268. new Info({
  269. id: entry.ref.id,
  270. name: entry.ref.name,
  271. methods: entry.methods,
  272. connections,
  273. })
  274. const authorize = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
  275. effect.pipe(Effect.mapError((cause) => new AuthorizationError({ cause })))
  276. const close = (attemptScope: Scope.Closeable) =>
  277. Scope.close(attemptScope, Exit.void).pipe(Effect.forkIn(scope, { startImmediately: true }), Effect.asVoid)
  278. const message = (cause: Cause.Cause<unknown>) => {
  279. const error = Cause.squash(cause)
  280. return error instanceof Error ? error.message : String(error)
  281. }
  282. const settle = Effect.fnUntraced(function* (attemptID: AttemptID, exit: Exit.Exit<Credential.OAuth, unknown>) {
  283. const now = yield* Clock.currentTimeMillis
  284. const result = yield* SynchronizedRef.modify(attempts, (current) => {
  285. const attempt = current.get(attemptID)
  286. if (!attempt || attempt.status !== "pending") return [undefined, current]
  287. const terminal: TerminalAttempt = Exit.isSuccess(exit)
  288. ? { status: "complete", time: attempt.time, removeAt: now + terminalRetention }
  289. : { status: "failed", message: message(exit.cause), time: attempt.time, removeAt: now + terminalRetention }
  290. return [attempt, new Map(current).set(attemptID, terminal)]
  291. })
  292. if (!result) return
  293. if (Exit.isSuccess(exit)) {
  294. const implementation = state.get().integrations.get(result.integrationID)?.implementations.get(result.methodID)
  295. yield* credentials.create({
  296. integrationID: result.integrationID,
  297. label: result.label ?? implementation?.label?.(exit.value),
  298. value: exit.value,
  299. })
  300. yield* events.publish(Event.ConnectionUpdated, { integrationID: result.integrationID })
  301. yield* events.publish(Event.Updated, {})
  302. }
  303. yield* close(result.scope)
  304. })
  305. const scrub = Effect.fnUntraced(function* () {
  306. const now = yield* Clock.currentTimeMillis
  307. const expired = yield* SynchronizedRef.modify(attempts, (current) => {
  308. const next = new Map(current)
  309. const scopes: Scope.Closeable[] = []
  310. for (const [id, attempt] of current) {
  311. if (attempt.status === "pending" && attempt.time.expires <= now) {
  312. scopes.push(attempt.scope)
  313. next.set(id, { status: "expired", time: attempt.time, removeAt: now + terminalRetention })
  314. continue
  315. }
  316. if (attempt.status !== "pending" && attempt.removeAt <= now) next.delete(id)
  317. }
  318. return [scopes, next]
  319. })
  320. yield* Effect.forEach(expired, close, { discard: true })
  321. })
  322. yield* scrub().pipe(Effect.repeat(Schedule.spaced(scrubInterval)), Effect.forkIn(scope))
  323. return Service.of({
  324. transform: state.transform,
  325. reload: state.reload,
  326. get: Effect.fn("Integration.get")(function* (id) {
  327. const entry = state.get().integrations.get(id)
  328. if (!entry) return undefined
  329. return project(entry, resolveConnections(entry, yield* credentials.list(id)))
  330. }),
  331. list: Effect.fn("Integration.list")(function* () {
  332. const saved = Map.groupBy(yield* credentials.all(), (credential) => credential.integrationID)
  333. return Array.from(state.get().integrations.values(), (entry) =>
  334. project(entry, resolveConnections(entry, saved.get(entry.ref.id) ?? [])),
  335. ).toSorted((a, b) => a.name.localeCompare(b.name))
  336. }),
  337. connection: {
  338. active: Effect.fn("Integration.connection.active")(function* (id) {
  339. const entry = state.get().integrations.get(id)
  340. return resolveConnections(entry, yield* credentials.list(id))[0]
  341. }),
  342. resolve: Effect.fn("Integration.connection.resolve")(function* (connection) {
  343. if (connection.type === "env") {
  344. const key = process.env[connection.name]
  345. return key ? Credential.Key.make({ type: "key", key }) : undefined
  346. }
  347. const credential = yield* credentials.get(connection.id)
  348. if (!credential) return undefined
  349. if (credential.value.type === "key") return credential.value
  350. const implementation = state
  351. .get()
  352. .integrations.get(credential.integrationID)
  353. ?.implementations.get(credential.value.methodID)
  354. if (!implementation?.refresh) return credential.value
  355. const now = yield* Clock.currentTimeMillis
  356. if (credential.value.expires > now + Duration.toMillis(Duration.minutes(5))) return credential.value
  357. const value = yield* authorize(implementation.refresh(credential.value))
  358. yield* credentials.update(credential.id, { value })
  359. return value
  360. }),
  361. key: Effect.fn("Integration.connection.key")(function* (input) {
  362. const method = state
  363. .get()
  364. .integrations.get(input.integrationID)
  365. ?.methods.some((method) => method.type === "key")
  366. if (!method) return yield* Effect.die(`Key method not found: ${input.integrationID}`)
  367. yield* credentials.create({
  368. integrationID: input.integrationID,
  369. label: input.label,
  370. value: Credential.Key.make({ type: "key", key: input.key }),
  371. })
  372. yield* events.publish(Event.ConnectionUpdated, { integrationID: input.integrationID })
  373. yield* events.publish(Event.Updated, {})
  374. }),
  375. oauth: Effect.fn("Integration.connection.oauth")(function* (input) {
  376. const method = state.get().integrations.get(input.integrationID)?.implementations.get(input.methodID)
  377. if (!method) {
  378. return yield* Effect.die(`OAuth method not found: ${input.integrationID}/${input.methodID}`)
  379. }
  380. const attemptScope = yield* Scope.fork(scope)
  381. const authorization = yield* authorize(method.authorize(input.inputs)).pipe(
  382. Scope.provide(attemptScope),
  383. Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void)),
  384. )
  385. const id = AttemptID.create()
  386. const created = yield* Clock.currentTimeMillis
  387. const time = { created, expires: created + attemptLifetime }
  388. yield* SynchronizedRef.update(attempts, (current) =>
  389. new Map(current).set(id, {
  390. status: "pending",
  391. completing: authorization.mode === "auto",
  392. authorization,
  393. integrationID: input.integrationID,
  394. methodID: input.methodID,
  395. label: input.label,
  396. scope: attemptScope,
  397. time,
  398. }),
  399. )
  400. if (authorization.mode === "auto") {
  401. yield* authorization.callback.pipe(
  402. Effect.exit,
  403. Effect.flatMap((exit) => settle(id, exit)),
  404. Effect.forkIn(attemptScope, { startImmediately: true }),
  405. )
  406. }
  407. return new Attempt({
  408. attemptID: id,
  409. url: authorization.url,
  410. instructions: authorization.instructions,
  411. mode: authorization.mode,
  412. time,
  413. })
  414. }),
  415. update: Effect.fn("Integration.connection.update")(function* (credentialID, updates) {
  416. const credential = yield* credentials.get(credentialID)
  417. yield* credentials.update(credentialID, updates)
  418. if (credential) {
  419. yield* events.publish(Event.ConnectionUpdated, { integrationID: credential.integrationID })
  420. }
  421. yield* events.publish(Event.Updated, {})
  422. }),
  423. remove: Effect.fn("Integration.connection.remove")(function* (credentialID) {
  424. const credential = yield* credentials.get(credentialID)
  425. yield* credentials.remove(credentialID)
  426. if (credential) {
  427. yield* events.publish(Event.ConnectionUpdated, { integrationID: credential.integrationID })
  428. }
  429. yield* events.publish(Event.Updated, {})
  430. }),
  431. },
  432. attempt: {
  433. status: Effect.fn("Integration.attempt.status")(function* (attemptID) {
  434. const attempt = (yield* SynchronizedRef.get(attempts)).get(attemptID)
  435. if (!attempt) return yield* Effect.die(`OAuth attempt not found: ${attemptID}`)
  436. if (attempt.status === "failed") {
  437. return { status: attempt.status, message: attempt.message ?? "Authorization failed", time: attempt.time }
  438. }
  439. return { status: attempt.status, time: attempt.time }
  440. }),
  441. complete: Effect.fn("Integration.attempt.complete")(function* (input) {
  442. const attempt = yield* SynchronizedRef.modify(attempts, (current) => {
  443. const match = current.get(input.attemptID)
  444. if (!match || match.status !== "pending" || match.completing) return [match, current]
  445. if (match.authorization.mode === "code" && input.code === undefined) return [match, current]
  446. return [match, new Map(current).set(input.attemptID, { ...match, completing: true })]
  447. })
  448. if (!attempt) return yield* Effect.die(`OAuth attempt not found: ${input.attemptID}`)
  449. if (attempt.status !== "pending") return
  450. if (attempt.authorization.mode === "code" && input.code === undefined) {
  451. return yield* new CodeRequiredError({ attemptID: input.attemptID })
  452. }
  453. if (attempt.completing) return yield* Effect.die(`OAuth attempt already completing: ${input.attemptID}`)
  454. const callback =
  455. attempt.authorization.mode === "auto"
  456. ? attempt.authorization.callback
  457. : attempt.authorization.callback(input.code as string)
  458. const exit = yield* authorize(callback).pipe(Effect.exit)
  459. yield* settle(input.attemptID, exit)
  460. if (Exit.isFailure(exit)) return yield* exit
  461. }),
  462. cancel: Effect.fn("Integration.attempt.cancel")(function* (attemptID) {
  463. const attempt = yield* SynchronizedRef.modify(attempts, (current) => {
  464. const match = current.get(attemptID)
  465. if (!match || match.status !== "pending") return [undefined, current]
  466. const next = new Map(current)
  467. next.delete(attemptID)
  468. return [match, next]
  469. })
  470. if (attempt) yield* Scope.close(attempt.scope, Exit.void)
  471. }),
  472. },
  473. })
  474. }),
  475. )
  476. export const node = makeLocationNode({ service: Service, layer: locationLayer, deps: [Credential.node, EventV2.node] })