refactor(core): migrate accounts and load file agents
This commit is contained in:
parent
1cae8f89c5
commit
9127a9aa00
25 changed files with 1179 additions and 1916 deletions
|
|
@ -73,6 +73,7 @@
|
|||
"drizzle-orm": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"gitlab-ai-provider": "6.8.0",
|
||||
"gray-matter": "4.0.3",
|
||||
"glob": "13.0.5",
|
||||
"google-auth-library": "10.5.0",
|
||||
"immer": "11.1.4",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,17 @@
|
|||
export * as AccountV2 from "./account"
|
||||
|
||||
import { Schema } from "effect"
|
||||
import type * as HttpClientError from "effect/unstable/http/HttpClientError"
|
||||
import { Cache, Clock, Context, Duration, Effect, Layer, Option, Schedule, Schema, SchemaGetter } from "effect"
|
||||
import { eq } from "drizzle-orm"
|
||||
import {
|
||||
FetchHttpClient,
|
||||
HttpClient,
|
||||
HttpClientError,
|
||||
HttpClientRequest,
|
||||
HttpClientResponse,
|
||||
} from "effect/unstable/http"
|
||||
import { AccountStateTable, AccountTable } from "./account/sql"
|
||||
import { Database } from "./database/database"
|
||||
import { serviceUse } from "./effect/service-use"
|
||||
|
||||
export const ID = Schema.String.pipe(Schema.brand("AccountID"))
|
||||
export type ID = Schema.Schema.Type<typeof ID>
|
||||
|
|
@ -99,3 +109,441 @@ export class PollError extends Schema.TaggedClass<PollError>()("PollError", {
|
|||
|
||||
export const PollResult = Schema.Union([PollSuccess, PollPending, PollSlow, PollExpired, PollDenied, PollError])
|
||||
export type PollResult = Schema.Schema.Type<typeof PollResult>
|
||||
|
||||
export type AccountOrgs = {
|
||||
account: Info
|
||||
orgs: readonly Org[]
|
||||
}
|
||||
|
||||
export type ActiveOrg = {
|
||||
account: Info
|
||||
org: Org
|
||||
}
|
||||
|
||||
class RemoteConfig extends Schema.Class<RemoteConfig>("RemoteConfig")({
|
||||
config: Schema.Record(Schema.String, Schema.Json),
|
||||
}) {}
|
||||
|
||||
const DurationFromSeconds = Schema.Number.pipe(
|
||||
Schema.decodeTo(Schema.Duration, {
|
||||
decode: SchemaGetter.transform((n) => Duration.seconds(n)),
|
||||
encode: SchemaGetter.transform((d) => Duration.toSeconds(d)),
|
||||
}),
|
||||
)
|
||||
|
||||
class TokenRefresh extends Schema.Class<TokenRefresh>("TokenRefresh")({
|
||||
access_token: AccessToken,
|
||||
refresh_token: RefreshToken,
|
||||
expires_in: DurationFromSeconds,
|
||||
}) {}
|
||||
|
||||
class DeviceAuth extends Schema.Class<DeviceAuth>("DeviceAuth")({
|
||||
device_code: DeviceCode,
|
||||
user_code: UserCode,
|
||||
verification_uri_complete: Schema.String,
|
||||
expires_in: DurationFromSeconds,
|
||||
interval: DurationFromSeconds,
|
||||
}) {}
|
||||
|
||||
class DeviceTokenSuccess extends Schema.Class<DeviceTokenSuccess>("DeviceTokenSuccess")({
|
||||
access_token: AccessToken,
|
||||
refresh_token: RefreshToken,
|
||||
token_type: Schema.Literal("Bearer"),
|
||||
expires_in: DurationFromSeconds,
|
||||
}) {}
|
||||
|
||||
class DeviceTokenError extends Schema.Class<DeviceTokenError>("DeviceTokenError")({
|
||||
error: Schema.String,
|
||||
error_description: Schema.String,
|
||||
}) {
|
||||
toPollResult(): PollResult {
|
||||
if (this.error === "authorization_pending") return new PollPending()
|
||||
if (this.error === "slow_down") return new PollSlow()
|
||||
if (this.error === "expired_token") return new PollExpired()
|
||||
if (this.error === "access_denied") return new PollDenied()
|
||||
return new PollError({ cause: this.error })
|
||||
}
|
||||
}
|
||||
|
||||
const DeviceToken = Schema.Union([DeviceTokenSuccess, DeviceTokenError])
|
||||
|
||||
class User extends Schema.Class<User>("User")({
|
||||
id: ID,
|
||||
email: Schema.String,
|
||||
}) {}
|
||||
|
||||
class ClientId extends Schema.Class<ClientId>("ClientId")({ client_id: Schema.String }) {}
|
||||
|
||||
class DeviceTokenRequest extends Schema.Class<DeviceTokenRequest>("DeviceTokenRequest")({
|
||||
grant_type: Schema.String,
|
||||
device_code: DeviceCode,
|
||||
client_id: Schema.String,
|
||||
}) {}
|
||||
|
||||
class TokenRefreshRequest extends Schema.Class<TokenRefreshRequest>("TokenRefreshRequest")({
|
||||
grant_type: Schema.String,
|
||||
refresh_token: RefreshToken,
|
||||
client_id: Schema.String,
|
||||
}) {}
|
||||
|
||||
type AccountRow = typeof AccountTable.$inferSelect
|
||||
const ACCOUNT_STATE_ID = 1
|
||||
const clientId = "opencode-cli"
|
||||
const eagerRefreshThresholdMs = Duration.toMillis(Duration.minutes(5))
|
||||
|
||||
function normalizeServerUrl(input: string) {
|
||||
const url = new URL(input)
|
||||
url.search = ""
|
||||
url.hash = ""
|
||||
const pathname = url.pathname.replace(/\/+$/, "")
|
||||
return pathname.length === 0 ? url.origin : `${url.origin}${pathname}`
|
||||
}
|
||||
|
||||
const isTokenFresh = (tokenExpiry: number | null, now: number) =>
|
||||
tokenExpiry != null && tokenExpiry > now + eagerRefreshThresholdMs
|
||||
|
||||
const mapAccountServiceError =
|
||||
(message = "Account service operation failed") =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, AccountError, R> =>
|
||||
effect.pipe(Effect.mapError((cause) => accountErrorFromCause(cause, message)))
|
||||
|
||||
function accountErrorFromCause(cause: unknown, message: string): AccountError {
|
||||
if (cause instanceof AccountServiceError || cause instanceof AccountTransportError) return cause
|
||||
if (HttpClientError.isHttpClientError(cause)) {
|
||||
if (cause.reason._tag === "TransportError") return AccountTransportError.fromHttpClientError(cause.reason)
|
||||
return new AccountServiceError({ message, cause })
|
||||
}
|
||||
return new AccountServiceError({ message, cause })
|
||||
}
|
||||
|
||||
export interface Interface {
|
||||
readonly active: () => Effect.Effect<Option.Option<Info>, AccountError>
|
||||
readonly activeOrg: () => Effect.Effect<Option.Option<ActiveOrg>, AccountError>
|
||||
readonly list: () => Effect.Effect<Info[], AccountError>
|
||||
readonly orgsByAccount: () => Effect.Effect<readonly AccountOrgs[], AccountError>
|
||||
readonly remove: (accountID: ID) => Effect.Effect<void, AccountError>
|
||||
readonly use: (accountID: ID, orgID: Option.Option<OrgID>) => Effect.Effect<void, AccountError>
|
||||
readonly orgs: (accountID: ID) => Effect.Effect<readonly Org[], AccountError>
|
||||
readonly config: (accountID: ID, orgID: OrgID) => Effect.Effect<Option.Option<Record<string, unknown>>, AccountError>
|
||||
readonly token: (accountID: ID) => Effect.Effect<Option.Option<AccessToken>, AccountError>
|
||||
readonly login: (url: string) => Effect.Effect<Login, AccountError>
|
||||
readonly poll: (input: Login) => Effect.Effect<PollResult, AccountError>
|
||||
}
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Account") {}
|
||||
|
||||
export const use = serviceUse(Service)
|
||||
|
||||
export const layer = Layer.effect(
|
||||
Service,
|
||||
Effect.gen(function* () {
|
||||
const { db } = yield* Database.Service
|
||||
const http = yield* HttpClient.HttpClient
|
||||
const httpRead = http.pipe(
|
||||
HttpClient.retryTransient({
|
||||
retryOn: "errors-and-responses",
|
||||
times: 2,
|
||||
schedule: Schedule.exponential(200).pipe(Schedule.jittered),
|
||||
}),
|
||||
)
|
||||
const httpOk = HttpClient.filterStatusOk(http)
|
||||
const httpReadOk = HttpClient.filterStatusOk(httpRead)
|
||||
const decode = Schema.decodeUnknownSync(Info)
|
||||
|
||||
const query = <A, E>(effect: Effect.Effect<A, E>) =>
|
||||
effect.pipe(Effect.mapError((cause) => new AccountRepoError({ message: "Database operation failed", cause })))
|
||||
|
||||
const current = Effect.fnUntraced(function* () {
|
||||
const state = yield* db.select().from(AccountStateTable).where(eq(AccountStateTable.id, ACCOUNT_STATE_ID)).get()
|
||||
if (!state?.active_account_id) return
|
||||
const account = yield* db.select().from(AccountTable).where(eq(AccountTable.id, state.active_account_id)).get()
|
||||
if (!account) return
|
||||
return { ...account, active_org_id: state.active_org_id ?? null }
|
||||
})
|
||||
|
||||
const state = (accountID: ID, orgID: Option.Option<OrgID>) =>
|
||||
db
|
||||
.insert(AccountStateTable)
|
||||
.values({ id: ACCOUNT_STATE_ID, active_account_id: accountID, active_org_id: Option.getOrNull(orgID) })
|
||||
.onConflictDoUpdate({
|
||||
target: AccountStateTable.id,
|
||||
set: { active_account_id: accountID, active_org_id: Option.getOrNull(orgID) },
|
||||
})
|
||||
.run()
|
||||
|
||||
const active = Effect.fn("AccountV2.active")(() =>
|
||||
query(current()).pipe(Effect.map((row) => (row ? Option.some(decode(row)) : Option.none()))),
|
||||
)
|
||||
const list = Effect.fn("AccountV2.list")(() =>
|
||||
query(
|
||||
db
|
||||
.select()
|
||||
.from(AccountTable)
|
||||
.all()
|
||||
.pipe(Effect.map((rows) => rows.map((row) => decode({ ...row, active_org_id: null })))),
|
||||
),
|
||||
)
|
||||
const remove = Effect.fn("AccountV2.remove")((accountID: ID) =>
|
||||
query(
|
||||
db.transaction((tx) =>
|
||||
Effect.gen(function* () {
|
||||
yield* tx
|
||||
.update(AccountStateTable)
|
||||
.set({ active_account_id: null, active_org_id: null })
|
||||
.where(eq(AccountStateTable.active_account_id, accountID))
|
||||
.run()
|
||||
yield* tx.delete(AccountTable).where(eq(AccountTable.id, accountID)).run()
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.asVoid),
|
||||
)
|
||||
const select = Effect.fn("AccountV2.use")((accountID: ID, orgID: Option.Option<OrgID>) =>
|
||||
query(state(accountID, orgID)).pipe(Effect.asVoid),
|
||||
)
|
||||
const getRow = (accountID: ID) =>
|
||||
query(db.select().from(AccountTable).where(eq(AccountTable.id, accountID)).get()).pipe(
|
||||
Effect.map(Option.fromNullishOr),
|
||||
)
|
||||
|
||||
const persistToken = Effect.fnUntraced(function* (input: {
|
||||
accountID: ID
|
||||
accessToken: AccessToken
|
||||
refreshToken: RefreshToken
|
||||
expiry: Option.Option<number>
|
||||
}) {
|
||||
yield* query(
|
||||
db
|
||||
.update(AccountTable)
|
||||
.set({
|
||||
access_token: input.accessToken,
|
||||
refresh_token: input.refreshToken,
|
||||
token_expiry: Option.getOrNull(input.expiry),
|
||||
})
|
||||
.where(eq(AccountTable.id, input.accountID))
|
||||
.run(),
|
||||
)
|
||||
})
|
||||
const persistAccount = Effect.fnUntraced(function* (input: {
|
||||
id: ID
|
||||
email: string
|
||||
url: string
|
||||
accessToken: AccessToken
|
||||
refreshToken: RefreshToken
|
||||
expiry: number
|
||||
orgID: Option.Option<OrgID>
|
||||
}) {
|
||||
const url = normalizeServerUrl(input.url)
|
||||
yield* query(
|
||||
db.transaction((tx) =>
|
||||
Effect.gen(function* () {
|
||||
yield* tx
|
||||
.insert(AccountTable)
|
||||
.values({
|
||||
id: input.id,
|
||||
email: input.email,
|
||||
url,
|
||||
access_token: input.accessToken,
|
||||
refresh_token: input.refreshToken,
|
||||
token_expiry: input.expiry,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: AccountTable.id,
|
||||
set: {
|
||||
email: input.email,
|
||||
url,
|
||||
access_token: input.accessToken,
|
||||
refresh_token: input.refreshToken,
|
||||
token_expiry: input.expiry,
|
||||
},
|
||||
})
|
||||
.run()
|
||||
yield* state(input.id, input.orgID)
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
const executeRead = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
httpRead.execute(request).pipe(mapAccountServiceError("HTTP request failed"))
|
||||
const executeReadOk = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
httpReadOk.execute(request).pipe(mapAccountServiceError("HTTP request failed"))
|
||||
const executeEffectOk = <E>(request: Effect.Effect<HttpClientRequest.HttpClientRequest, E>) =>
|
||||
request.pipe(
|
||||
Effect.flatMap((req) => httpOk.execute(req)),
|
||||
mapAccountServiceError("HTTP request failed"),
|
||||
)
|
||||
const executeEffect = <E>(request: Effect.Effect<HttpClientRequest.HttpClientRequest, E>) =>
|
||||
request.pipe(
|
||||
Effect.flatMap((req) => http.execute(req)),
|
||||
mapAccountServiceError("HTTP request failed"),
|
||||
)
|
||||
|
||||
const refreshToken = Effect.fnUntraced(function* (row: AccountRow) {
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
const response = yield* executeEffectOk(
|
||||
HttpClientRequest.post(`${row.url}/auth/device/token`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.schemaBodyJson(TokenRefreshRequest)(
|
||||
new TokenRefreshRequest({
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: row.refresh_token,
|
||||
client_id: clientId,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
const parsed = yield* HttpClientResponse.schemaBodyJson(TokenRefresh)(response).pipe(
|
||||
mapAccountServiceError("Failed to decode response"),
|
||||
)
|
||||
yield* persistToken({
|
||||
accountID: row.id,
|
||||
accessToken: parsed.access_token,
|
||||
refreshToken: parsed.refresh_token,
|
||||
expiry: Option.some(now + Duration.toMillis(parsed.expires_in)),
|
||||
})
|
||||
return parsed.access_token
|
||||
})
|
||||
const refreshTokenCache = yield* Cache.make<ID, AccessToken, AccountError>({
|
||||
capacity: Number.POSITIVE_INFINITY,
|
||||
timeToLive: Duration.zero,
|
||||
lookup: Effect.fnUntraced(function* (accountID) {
|
||||
const maybeAccount = yield* getRow(accountID)
|
||||
if (Option.isNone(maybeAccount))
|
||||
return yield* new AccountServiceError({ message: "Account not found during token refresh" })
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
if (isTokenFresh(maybeAccount.value.token_expiry, now)) return maybeAccount.value.access_token
|
||||
return yield* refreshToken(maybeAccount.value)
|
||||
}),
|
||||
})
|
||||
const resolveToken = Effect.fnUntraced(function* (row: AccountRow) {
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
if (isTokenFresh(row.token_expiry, now)) return row.access_token
|
||||
return yield* Cache.get(refreshTokenCache, row.id)
|
||||
})
|
||||
const resolveAccess = Effect.fnUntraced(function* (accountID: ID) {
|
||||
const maybeAccount = yield* getRow(accountID)
|
||||
if (Option.isNone(maybeAccount)) return Option.none()
|
||||
return Option.some({ account: maybeAccount.value, accessToken: yield* resolveToken(maybeAccount.value) })
|
||||
})
|
||||
const fetchOrgs = Effect.fnUntraced(function* (url: string, accessToken: AccessToken) {
|
||||
const response = yield* executeReadOk(
|
||||
HttpClientRequest.get(`${url}/api/orgs`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(accessToken),
|
||||
),
|
||||
)
|
||||
return yield* HttpClientResponse.schemaBodyJson(Schema.Array(Org))(response).pipe(
|
||||
mapAccountServiceError("Failed to decode response"),
|
||||
)
|
||||
})
|
||||
const fetchUser = Effect.fnUntraced(function* (url: string, accessToken: AccessToken) {
|
||||
const response = yield* executeReadOk(
|
||||
HttpClientRequest.get(`${url}/api/user`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(accessToken),
|
||||
),
|
||||
)
|
||||
return yield* HttpClientResponse.schemaBodyJson(User)(response).pipe(
|
||||
mapAccountServiceError("Failed to decode response"),
|
||||
)
|
||||
})
|
||||
const token = Effect.fn("AccountV2.token")((accountID: ID) =>
|
||||
resolveAccess(accountID).pipe(Effect.map(Option.map((item) => item.accessToken))),
|
||||
)
|
||||
const orgs = Effect.fn("AccountV2.orgs")(function* (accountID: ID) {
|
||||
const resolved = yield* resolveAccess(accountID)
|
||||
if (Option.isNone(resolved)) return []
|
||||
return yield* fetchOrgs(resolved.value.account.url, resolved.value.accessToken)
|
||||
})
|
||||
const activeOrg = Effect.fn("AccountV2.activeOrg")(function* () {
|
||||
const value = yield* active()
|
||||
if (Option.isNone(value) || !value.value.active_org_id) return Option.none<ActiveOrg>()
|
||||
const org = (yield* orgs(value.value.id)).find((item) => item.id === value.value.active_org_id)
|
||||
return org ? Option.some({ account: value.value, org }) : Option.none<ActiveOrg>()
|
||||
})
|
||||
const orgsByAccount = Effect.fn("AccountV2.orgsByAccount")(function* () {
|
||||
return yield* Effect.forEach(
|
||||
yield* list(),
|
||||
(account) =>
|
||||
orgs(account.id).pipe(
|
||||
Effect.catch(() => Effect.succeed([] as readonly Org[])),
|
||||
Effect.map((orgs) => ({ account, orgs })),
|
||||
),
|
||||
{ concurrency: 3 },
|
||||
)
|
||||
})
|
||||
const config = Effect.fn("AccountV2.config")(function* (accountID: ID, orgID: OrgID) {
|
||||
const resolved = yield* resolveAccess(accountID)
|
||||
if (Option.isNone(resolved)) return Option.none()
|
||||
const response = yield* executeRead(
|
||||
HttpClientRequest.get(`${resolved.value.account.url}/api/config`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(resolved.value.accessToken),
|
||||
HttpClientRequest.setHeaders({ "x-org-id": orgID }),
|
||||
),
|
||||
)
|
||||
if (response.status === 404) return Option.none()
|
||||
const ok = yield* HttpClientResponse.filterStatusOk(response).pipe(mapAccountServiceError())
|
||||
const parsed = yield* HttpClientResponse.schemaBodyJson(RemoteConfig)(ok).pipe(
|
||||
mapAccountServiceError("Failed to decode response"),
|
||||
)
|
||||
return Option.some(parsed.config)
|
||||
})
|
||||
const login = Effect.fn("AccountV2.login")(function* (server: string) {
|
||||
const normalizedServer = normalizeServerUrl(server)
|
||||
const response = yield* executeEffectOk(
|
||||
HttpClientRequest.post(`${normalizedServer}/auth/device/code`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.schemaBodyJson(ClientId)(new ClientId({ client_id: clientId })),
|
||||
),
|
||||
)
|
||||
const parsed = yield* HttpClientResponse.schemaBodyJson(DeviceAuth)(response).pipe(
|
||||
mapAccountServiceError("Failed to decode response"),
|
||||
)
|
||||
return new Login({
|
||||
code: parsed.device_code,
|
||||
user: parsed.user_code,
|
||||
url: `${normalizedServer}${parsed.verification_uri_complete}`,
|
||||
server: normalizedServer,
|
||||
expiry: parsed.expires_in,
|
||||
interval: parsed.interval,
|
||||
})
|
||||
})
|
||||
const poll = Effect.fn("AccountV2.poll")(function* (input: Login) {
|
||||
const response = yield* executeEffect(
|
||||
HttpClientRequest.post(`${input.server}/auth/device/token`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.schemaBodyJson(DeviceTokenRequest)(
|
||||
new DeviceTokenRequest({
|
||||
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
||||
device_code: input.code,
|
||||
client_id: clientId,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
const parsed = yield* HttpClientResponse.schemaBodyJson(DeviceToken)(response).pipe(
|
||||
mapAccountServiceError("Failed to decode response"),
|
||||
)
|
||||
if (parsed instanceof DeviceTokenError) return parsed.toPollResult()
|
||||
const [account, remoteOrgs] = yield* Effect.all(
|
||||
[fetchUser(input.server, parsed.access_token), fetchOrgs(input.server, parsed.access_token)],
|
||||
{ concurrency: 2 },
|
||||
)
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
yield* persistAccount({
|
||||
id: account.id,
|
||||
email: account.email,
|
||||
url: input.server,
|
||||
accessToken: parsed.access_token,
|
||||
refreshToken: parsed.refresh_token,
|
||||
expiry: now + Duration.toMillis(parsed.expires_in),
|
||||
orgID: remoteOrgs.length ? Option.some(remoteOrgs[0].id) : Option.none(),
|
||||
})
|
||||
return new PollSuccess({ email: account.email })
|
||||
})
|
||||
|
||||
return Service.of({ active, activeOrg, list, orgsByAccount, remove, use: select, orgs, config, token, login, poll })
|
||||
}),
|
||||
)
|
||||
|
||||
export const defaultLayer = layer.pipe(Layer.provide(Database.defaultLayer), Layer.provide(FetchHttpClient.layer))
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core"
|
||||
|
||||
import { AccountV2 } from "../account"
|
||||
import type { AccountV2 } from "../account"
|
||||
import { Timestamps } from "../database/schema.sql"
|
||||
|
||||
export const AccountTable = sqliteTable("account", {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,12 @@
|
|||
export * as ConfigAgentPlugin from "./agent"
|
||||
|
||||
import { Effect } from "effect"
|
||||
import path from "path"
|
||||
import matter from "gray-matter"
|
||||
import { Effect, Option, Schema } from "effect"
|
||||
import { AgentV2 } from "../../agent"
|
||||
import { Config } from "../../config"
|
||||
import { ConfigAgent } from "../agent"
|
||||
import { AppFileSystem } from "../../filesystem"
|
||||
import { ModelV2 } from "../../model"
|
||||
import { PermissionV2 } from "../../permission"
|
||||
import { PluginV2 } from "../../plugin"
|
||||
|
|
@ -12,49 +16,83 @@ export const Plugin = PluginV2.define({
|
|||
effect: Effect.gen(function* () {
|
||||
const agent = yield* AgentV2.Service
|
||||
const config = yield* Config.Service
|
||||
const files = yield* config.get()
|
||||
const fs = yield* AppFileSystem.Service
|
||||
const documents = yield* config.get()
|
||||
const loadFile = Effect.fnUntraced(function* (directory: string, filepath: string) {
|
||||
const text = yield* fs.readFileString(filepath).pipe(Effect.orDie)
|
||||
const document = yield* Effect.try({ try: () => matter(text), catch: () => undefined }).pipe(
|
||||
Effect.catch(() => Effect.void),
|
||||
)
|
||||
if (!document) return
|
||||
|
||||
const info = Option.getOrUndefined(
|
||||
Schema.decodeUnknownOption(ConfigAgent.Info)(
|
||||
{ ...document.data, system: document.content.trim() },
|
||||
{ errors: "all", onExcessProperty: "ignore" },
|
||||
),
|
||||
)
|
||||
if (!info) return
|
||||
|
||||
const relative = path.relative(directory, filepath).split(path.sep).slice(1).join("/")
|
||||
return {
|
||||
id: AgentV2.ID.make(relative.slice(0, -path.extname(relative).length)),
|
||||
info,
|
||||
}
|
||||
})
|
||||
const files = (yield* Effect.forEach(yield* config.directories(), (directory) =>
|
||||
fs.glob("{agent,agents}/**/*.md", { cwd: directory, absolute: true, dot: true, symlink: true }).pipe(
|
||||
Effect.orDie,
|
||||
Effect.flatMap((items) => Effect.forEach(items, (item) => loadFile(directory, item))),
|
||||
Effect.map((items) => items.filter((item): item is NonNullable<typeof item> => item !== undefined)),
|
||||
),
|
||||
)).flat()
|
||||
|
||||
yield* agent.update((editor) => {
|
||||
const permissions = new Map<AgentV2.ID, PermissionV2.Ruleset>()
|
||||
|
||||
for (const file of files) {
|
||||
function update(agentID: AgentV2.ID, item: ConfigAgent.Info, disabled: boolean, rules: PermissionV2.Ruleset) {
|
||||
if (disabled) {
|
||||
editor.remove(agentID)
|
||||
permissions.delete(agentID)
|
||||
return
|
||||
}
|
||||
|
||||
editor.update(agentID, (agent) => {
|
||||
if (item.model !== undefined) {
|
||||
const model = ModelV2.parse(item.model)
|
||||
agent.model = { id: model.modelID, providerID: model.providerID, variant: agent.model?.variant }
|
||||
}
|
||||
if (item.variant !== undefined && agent.model !== undefined) {
|
||||
agent.model.variant = ModelV2.VariantID.make(item.variant)
|
||||
}
|
||||
if (item.options !== undefined) {
|
||||
Object.assign(agent.options.headers, item.options.headers ?? {})
|
||||
Object.assign(agent.options.body, item.options.body ?? {})
|
||||
Object.assign(agent.options.aisdk.provider, item.options.aisdk?.provider ?? {})
|
||||
Object.assign(agent.options.aisdk.request, item.options.aisdk?.request ?? {})
|
||||
}
|
||||
if (item.system !== undefined) agent.system = item.system
|
||||
if (item.description !== undefined) agent.description = item.description
|
||||
if (item.mode !== undefined) agent.mode = item.mode
|
||||
if (item.hidden !== undefined) agent.hidden = item.hidden
|
||||
if (item.color !== undefined) agent.color = item.color
|
||||
if (item.steps !== undefined) agent.steps = item.steps
|
||||
})
|
||||
|
||||
if (rules.length) permissions.set(agentID, [...(permissions.get(agentID) ?? []), ...rules])
|
||||
}
|
||||
|
||||
for (const file of documents) {
|
||||
for (const [id, item] of Object.entries(file.info.agents ?? {})) {
|
||||
const agentID = AgentV2.ID.make(id)
|
||||
if (item.disabled) {
|
||||
editor.remove(agentID)
|
||||
permissions.delete(agentID)
|
||||
continue
|
||||
}
|
||||
|
||||
editor.update(agentID, (agent) => {
|
||||
if (item.model !== undefined) {
|
||||
const model = ModelV2.parse(item.model)
|
||||
agent.model = { id: model.modelID, providerID: model.providerID, variant: agent.model?.variant }
|
||||
}
|
||||
if (item.variant !== undefined && agent.model !== undefined) {
|
||||
agent.model.variant = ModelV2.VariantID.make(item.variant)
|
||||
}
|
||||
if (item.options !== undefined) {
|
||||
Object.assign(agent.options.headers, item.options.headers ?? {})
|
||||
Object.assign(agent.options.body, item.options.body ?? {})
|
||||
Object.assign(agent.options.aisdk.provider, item.options.aisdk?.provider ?? {})
|
||||
Object.assign(agent.options.aisdk.request, item.options.aisdk?.request ?? {})
|
||||
}
|
||||
if (item.system !== undefined) agent.system = item.system
|
||||
if (item.description !== undefined) agent.description = item.description
|
||||
if (item.mode !== undefined) agent.mode = item.mode
|
||||
if (item.hidden !== undefined) agent.hidden = item.hidden
|
||||
if (item.color !== undefined) agent.color = item.color
|
||||
if (item.steps !== undefined) agent.steps = item.steps
|
||||
})
|
||||
|
||||
if (item.permissions !== undefined) {
|
||||
permissions.set(agentID, [...(permissions.get(agentID) ?? []), ...item.permissions])
|
||||
}
|
||||
update(AgentV2.ID.make(id), item, item.disabled ?? false, item.permissions ?? [])
|
||||
}
|
||||
}
|
||||
|
||||
const global = files.flatMap((file) => file.info.permissions ?? [])
|
||||
for (const file of files) {
|
||||
update(file.id, file.info, file.info.disabled ?? false, file.info.permissions ?? [])
|
||||
}
|
||||
|
||||
const global = documents.flatMap((file) => file.info.permissions ?? [])
|
||||
for (const current of editor.list()) {
|
||||
editor.update(current.id, (agent) => {
|
||||
agent.permissions.push(...global, ...(permissions.get(current.id) ?? []))
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { Catalog } from "../catalog"
|
|||
import { Config } from "../config"
|
||||
import { ConfigAgentPlugin } from "../config/plugin/agent"
|
||||
import { EventV2 } from "../event"
|
||||
import { AppFileSystem } from "../filesystem"
|
||||
import { Location } from "../location"
|
||||
import { ModelsDev } from "../models-dev"
|
||||
import { Npm } from "../npm"
|
||||
|
|
@ -26,6 +27,7 @@ type Plugin = {
|
|||
| AgentV2.Service
|
||||
| Npm.Service
|
||||
| EventV2.Service
|
||||
| AppFileSystem.Service
|
||||
| Location.Service
|
||||
| PluginV2.Service
|
||||
| Config.Service
|
||||
|
|
@ -51,6 +53,7 @@ export const layer = Layer.effect(
|
|||
const modelsDev = yield* ModelsDev.Service
|
||||
const npm = yield* Npm.Service
|
||||
const events = yield* EventV2.Service
|
||||
const fs = yield* AppFileSystem.Service
|
||||
const done = yield* Deferred.make<void>()
|
||||
|
||||
const add = Effect.fn("PluginBoot.add")(function* (input: Plugin) {
|
||||
|
|
@ -65,6 +68,7 @@ export const layer = Layer.effect(
|
|||
Effect.provideService(ModelsDev.Service, modelsDev),
|
||||
Effect.provideService(Npm.Service, npm),
|
||||
Effect.provideService(EventV2.Service, events),
|
||||
Effect.provideService(AppFileSystem.Service, fs),
|
||||
Effect.provideService(PluginV2.Service, plugin),
|
||||
),
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,287 +1,489 @@
|
|||
import path from "path"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { produce } from "immer"
|
||||
import { Effect, Fiber, Layer, Option, Stream } from "effect"
|
||||
import { Auth } from "@opencode-ai/core/auth"
|
||||
import { Catalog } from "@opencode-ai/core/catalog"
|
||||
import { EventV2 } from "@opencode-ai/core/event"
|
||||
import { AppFileSystem } from "@opencode-ai/core/filesystem"
|
||||
import { Global } from "@opencode-ai/core/global"
|
||||
import { PluginV2 } from "@opencode-ai/core/plugin"
|
||||
import { AccountPlugin } from "@opencode-ai/core/plugin/account"
|
||||
import { ModelV2 } from "@opencode-ai/core/model"
|
||||
import { ProviderV2 } from "@opencode-ai/core/provider"
|
||||
import { tmpdir } from "./fixture/tmpdir"
|
||||
import { expect } from "bun:test"
|
||||
import { Duration, Effect, Layer, Option, Schema } from "effect"
|
||||
import { eq, sql } from "drizzle-orm"
|
||||
import { HttpClient, HttpClientError, HttpClientResponse } from "effect/unstable/http"
|
||||
|
||||
import { AccountV2 } from "@opencode-ai/core/account"
|
||||
import { AccountStateTable, AccountTable } from "@opencode-ai/core/account/sql"
|
||||
import { Database } from "@opencode-ai/core/database/database"
|
||||
import { testEffect } from "./lib/effect"
|
||||
|
||||
const it = testEffect(PluginV2.locationLayer.pipe(Layer.provide(EventV2.defaultLayer)))
|
||||
const database = Database.layerFromPath(":memory:")
|
||||
|
||||
function context(
|
||||
records: { provider: ProviderV2.Info; models: Map<ModelV2.ID, ModelV2.Info> }[],
|
||||
updates: Array<{ id: ProviderV2.ID; enabled: ProviderV2.Info["enabled"]; apiKey?: string }>,
|
||||
): Catalog.Editor {
|
||||
return {
|
||||
provider: {
|
||||
list: () => records,
|
||||
get: (providerID) => records.find((item) => item.provider.id === providerID),
|
||||
update: (providerID, fn) => {
|
||||
const record = records.find((item) => item.provider.id === providerID)
|
||||
const provider = produce(record?.provider ?? ProviderV2.Info.empty(providerID), fn)
|
||||
if (record) record.provider = provider
|
||||
else records.push({ provider, models: new Map<ModelV2.ID, ModelV2.Info>() })
|
||||
updates.push({
|
||||
id: providerID,
|
||||
enabled: provider.enabled,
|
||||
apiKey:
|
||||
typeof provider.options.aisdk.provider.apiKey === "string"
|
||||
? provider.options.aisdk.provider.apiKey
|
||||
: undefined,
|
||||
})
|
||||
},
|
||||
remove: (providerID) => {
|
||||
const index = records.findIndex((item) => item.provider.id === providerID)
|
||||
if (index !== -1) records.splice(index, 1)
|
||||
},
|
||||
},
|
||||
model: {
|
||||
get: () => undefined,
|
||||
update: () => {},
|
||||
remove: () => {},
|
||||
default: {
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
const truncate = Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
const { db } = yield* Database.Service
|
||||
yield* db.run(sql`DELETE FROM account_state`)
|
||||
yield* db.run(sql`DELETE FROM account`)
|
||||
}),
|
||||
).pipe(Layer.provide(database))
|
||||
|
||||
function testLayer(dir: string) {
|
||||
return Auth.layer.pipe(
|
||||
Layer.provide(AppFileSystem.defaultLayer),
|
||||
Layer.provideMerge(EventV2.defaultLayer),
|
||||
Layer.provide(
|
||||
Global.layerWith({
|
||||
data: dir,
|
||||
cache: path.join(dir, "cache"),
|
||||
config: path.join(dir, "config"),
|
||||
state: path.join(dir, "state"),
|
||||
tmp: path.join(dir, "tmp"),
|
||||
bin: path.join(dir, "bin"),
|
||||
log: path.join(dir, "log"),
|
||||
repos: path.join(dir, "repos"),
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
const it = testEffect(Layer.mergeAll(database, truncate))
|
||||
|
||||
describe("Auth", () => {
|
||||
it.live("emits account lifecycle events", () =>
|
||||
Effect.acquireRelease(
|
||||
Effect.promise(() => tmpdir()),
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
).pipe(
|
||||
Effect.flatMap((tmp) =>
|
||||
Effect.gen(function* () {
|
||||
const accounts = yield* Auth.Service
|
||||
const eventSvc = yield* EventV2.Service
|
||||
const addedFiber = yield* eventSvc
|
||||
.subscribe(Auth.Event.Added)
|
||||
.pipe(Stream.take(2), Stream.runCollect, Effect.forkScoped)
|
||||
const switchedFiber = yield* eventSvc
|
||||
.subscribe(Auth.Event.Switched)
|
||||
.pipe(Stream.take(3), Stream.runCollect, Effect.forkScoped)
|
||||
const removedFiber = yield* eventSvc
|
||||
.subscribe(Auth.Event.Removed)
|
||||
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
|
||||
const insideEagerRefreshWindow = Duration.toMillis(Duration.minutes(1))
|
||||
const outsideEagerRefreshWindow = Duration.toMillis(Duration.minutes(10))
|
||||
|
||||
yield* Effect.yieldNow
|
||||
const live = (client: HttpClient.HttpClient) =>
|
||||
AccountV2.layer.pipe(Layer.provide(database), Layer.provide(Layer.succeed(HttpClient.HttpClient, client)))
|
||||
|
||||
const first = yield* accounts.create({
|
||||
serviceID: Auth.ServiceID.make("provider"),
|
||||
credential: new Auth.ApiKeyCredential({ type: "api", key: "raw-key" }),
|
||||
})
|
||||
expect(first).toBeDefined()
|
||||
if (!first) return
|
||||
expect(first.description).toBe("default")
|
||||
expect(first.credential.type).toBe("api")
|
||||
if (first.credential.type === "api") expect(first.credential.key).toBe("raw-key")
|
||||
const persist = (input: {
|
||||
id: AccountV2.ID
|
||||
email: string
|
||||
url: string
|
||||
accessToken: AccountV2.AccessToken
|
||||
refreshToken: AccountV2.RefreshToken
|
||||
expiry: number
|
||||
orgID: Option.Option<AccountV2.OrgID>
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const { db } = yield* Database.Service
|
||||
yield* db
|
||||
.insert(AccountTable)
|
||||
.values({
|
||||
id: input.id,
|
||||
email: input.email,
|
||||
url: input.url,
|
||||
access_token: input.accessToken,
|
||||
refresh_token: input.refreshToken,
|
||||
token_expiry: input.expiry,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: AccountTable.id,
|
||||
set: { access_token: input.accessToken, refresh_token: input.refreshToken, token_expiry: input.expiry },
|
||||
})
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
yield* db
|
||||
.insert(AccountStateTable)
|
||||
.values({ id: 1, active_account_id: input.id, active_org_id: Option.getOrNull(input.orgID) })
|
||||
.onConflictDoUpdate({
|
||||
target: AccountStateTable.id,
|
||||
set: { active_account_id: input.id, active_org_id: Option.getOrNull(input.orgID) },
|
||||
})
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
})
|
||||
|
||||
yield* accounts.update(first.id, { description: "keep" })
|
||||
const updated = yield* accounts.get(first.id)
|
||||
expect(updated?.description).toBe("keep")
|
||||
expect(updated?.credential.type).toBe("api")
|
||||
if (updated?.credential.type === "api") expect(updated.credential.key).toBe("raw-key")
|
||||
const row = (id: AccountV2.ID) =>
|
||||
Effect.gen(function* () {
|
||||
const { db } = yield* Database.Service
|
||||
return yield* db.select().from(AccountTable).where(eq(AccountTable.id, id)).get().pipe(Effect.orDie)
|
||||
})
|
||||
|
||||
const second = yield* accounts.create({
|
||||
serviceID: Auth.ServiceID.make("provider"),
|
||||
credential: new Auth.ApiKeyCredential({ type: "api", key: "second-key" }),
|
||||
})
|
||||
expect(second).toBeDefined()
|
||||
if (!second) return
|
||||
|
||||
yield* accounts.remove(second.id)
|
||||
const added = Array.from(yield* Fiber.join(addedFiber))
|
||||
const switched = Array.from(yield* Fiber.join(switchedFiber))
|
||||
const removed = Array.from(yield* Fiber.join(removedFiber))
|
||||
expect(added.map((event) => event.data.account.id)).toEqual([first.id, second.id])
|
||||
expect(switched.map((event) => event.data)).toEqual([
|
||||
{ serviceID: Auth.ServiceID.make("provider"), from: undefined, to: first.id },
|
||||
{ serviceID: Auth.ServiceID.make("provider"), from: first.id, to: second.id },
|
||||
{ serviceID: Auth.ServiceID.make("provider"), from: second.id, to: first.id },
|
||||
])
|
||||
expect(removed[0]?.data.account.id).toBe(second.id)
|
||||
}).pipe(Effect.provide(testLayer(tmp.path))),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("always switches to newly created accounts", () =>
|
||||
Effect.acquireRelease(
|
||||
Effect.promise(() => tmpdir()),
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
).pipe(
|
||||
Effect.flatMap((tmp) =>
|
||||
Effect.gen(function* () {
|
||||
const accounts = yield* Auth.Service
|
||||
const eventSvc = yield* EventV2.Service
|
||||
const switchedFiber = yield* eventSvc
|
||||
.subscribe(Auth.Event.Switched)
|
||||
.pipe(Stream.take(3), Stream.runCollect, Effect.forkScoped)
|
||||
|
||||
yield* Effect.yieldNow
|
||||
|
||||
const first = yield* accounts.create({
|
||||
serviceID: Auth.ServiceID.make("provider"),
|
||||
credential: new Auth.ApiKeyCredential({ type: "api", key: "first-key" }),
|
||||
})
|
||||
const second = yield* accounts.create({
|
||||
serviceID: Auth.ServiceID.make("provider"),
|
||||
credential: new Auth.ApiKeyCredential({ type: "api", key: "second-key" }),
|
||||
})
|
||||
const third = yield* accounts.create({
|
||||
serviceID: Auth.ServiceID.make("provider"),
|
||||
credential: new Auth.ApiKeyCredential({ type: "api", key: "third-key" }),
|
||||
})
|
||||
|
||||
expect(first).toBeDefined()
|
||||
expect(second).toBeDefined()
|
||||
expect(third).toBeDefined()
|
||||
if (!first || !second || !third) return
|
||||
|
||||
expect((yield* accounts.active(Auth.ServiceID.make("provider")))?.id).toBe(third.id)
|
||||
expect(Array.from(yield* Fiber.join(switchedFiber)).map((event) => event.data)).toEqual([
|
||||
{ serviceID: Auth.ServiceID.make("provider"), from: undefined, to: first.id },
|
||||
{ serviceID: Auth.ServiceID.make("provider"), from: first.id, to: second.id },
|
||||
{ serviceID: Auth.ServiceID.make("provider"), from: second.id, to: third.id },
|
||||
])
|
||||
}).pipe(Effect.provide(testLayer(tmp.path))),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("account plugin refreshes providers on account lifecycle events", () =>
|
||||
Effect.acquireRelease(
|
||||
Effect.promise(() => tmpdir()),
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
).pipe(
|
||||
Effect.flatMap((tmp) =>
|
||||
Effect.gen(function* () {
|
||||
const accounts = yield* Auth.Service
|
||||
const plugin = yield* PluginV2.Service
|
||||
const records = [
|
||||
{
|
||||
provider: ProviderV2.Info.empty(ProviderV2.ID.make("provider")),
|
||||
models: new Map<ModelV2.ID, ModelV2.Info>(),
|
||||
},
|
||||
]
|
||||
const updates: Array<{ id: ProviderV2.ID; enabled: ProviderV2.Info["enabled"]; apiKey?: string }> = []
|
||||
const catalog = Catalog.Service.of({
|
||||
transform: () => Effect.die("unexpected catalog.transform"),
|
||||
provider: {
|
||||
get: () => Effect.die("unexpected provider.get"),
|
||||
all: () => Effect.succeed([]),
|
||||
available: () => Effect.succeed([]),
|
||||
},
|
||||
model: {
|
||||
get: () => Effect.die("unexpected model.get"),
|
||||
all: () => Effect.succeed([]),
|
||||
available: () => Effect.succeed([]),
|
||||
default: () => Effect.succeed(Option.none<ModelV2.Info>()),
|
||||
small: () => Effect.succeed(Option.none<ModelV2.Info>()),
|
||||
},
|
||||
})
|
||||
|
||||
const eventSvc = yield* EventV2.Service
|
||||
yield* plugin.add({
|
||||
...AccountPlugin,
|
||||
effect: AccountPlugin.effect.pipe(
|
||||
Effect.provideService(Auth.Service, accounts),
|
||||
Effect.provideService(Catalog.Service, catalog),
|
||||
Effect.provideService(EventV2.Service, eventSvc),
|
||||
Effect.provideService(PluginV2.Service, plugin),
|
||||
),
|
||||
})
|
||||
yield* Effect.yieldNow
|
||||
|
||||
const first = yield* accounts.create({
|
||||
serviceID: Auth.ServiceID.make("provider"),
|
||||
credential: new Auth.ApiKeyCredential({ type: "api", key: "first-key" }),
|
||||
})
|
||||
expect(first).toBeDefined()
|
||||
if (!first) return
|
||||
yield* plugin.trigger("catalog.transform", context(records, updates), {})
|
||||
expect(updates).toEqual([
|
||||
{
|
||||
id: ProviderV2.ID.make("provider"),
|
||||
enabled: { via: "account", service: Auth.ServiceID.make("provider") },
|
||||
apiKey: "first-key",
|
||||
},
|
||||
])
|
||||
|
||||
updates.length = 0
|
||||
const second = yield* accounts.create({
|
||||
serviceID: Auth.ServiceID.make("provider"),
|
||||
credential: new Auth.ApiKeyCredential({ type: "api", key: "second-key" }),
|
||||
})
|
||||
expect(second).toBeDefined()
|
||||
if (!second) return
|
||||
yield* plugin.trigger("catalog.transform", context(records, updates), {})
|
||||
expect(updates).toEqual([
|
||||
{
|
||||
id: ProviderV2.ID.make("provider"),
|
||||
enabled: { via: "account", service: Auth.ServiceID.make("provider") },
|
||||
apiKey: "second-key",
|
||||
},
|
||||
])
|
||||
|
||||
updates.length = 0
|
||||
yield* accounts.activate(first.id)
|
||||
yield* plugin.trigger("catalog.transform", context(records, updates), {})
|
||||
expect(updates).toEqual([
|
||||
{
|
||||
id: ProviderV2.ID.make("provider"),
|
||||
enabled: { via: "account", service: Auth.ServiceID.make("provider") },
|
||||
apiKey: "first-key",
|
||||
},
|
||||
])
|
||||
|
||||
updates.length = 0
|
||||
yield* accounts.remove(first.id)
|
||||
yield* plugin.trigger("catalog.transform", context(records, updates), {})
|
||||
expect(updates).toEqual([
|
||||
{
|
||||
id: ProviderV2.ID.make("provider"),
|
||||
enabled: { via: "account", service: Auth.ServiceID.make("provider") },
|
||||
apiKey: "second-key",
|
||||
},
|
||||
])
|
||||
|
||||
updates.length = 0
|
||||
yield* accounts.remove(second.id)
|
||||
yield* plugin.trigger("catalog.transform", context(records, updates), {})
|
||||
expect(updates).toEqual([])
|
||||
}).pipe(Effect.provide(testLayer(tmp.path))),
|
||||
),
|
||||
),
|
||||
)
|
||||
const active = Effect.gen(function* () {
|
||||
const { db } = yield* Database.Service
|
||||
const state = yield* db.select().from(AccountStateTable).where(eq(AccountStateTable.id, 1)).get().pipe(Effect.orDie)
|
||||
if (!state?.active_account_id) return undefined
|
||||
const account = yield* row(state.active_account_id)
|
||||
return account ? { ...account, active_org_id: state.active_org_id } : undefined
|
||||
})
|
||||
|
||||
const json = (req: Parameters<typeof HttpClientResponse.fromWeb>[0], body: unknown, status = 200) =>
|
||||
HttpClientResponse.fromWeb(
|
||||
req,
|
||||
new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
)
|
||||
|
||||
const encodeOrg = Schema.encodeSync(AccountV2.Org)
|
||||
|
||||
const org = (id: string, name: string) => encodeOrg(new AccountV2.Org({ id: AccountV2.OrgID.make(id), name }))
|
||||
|
||||
const login = () =>
|
||||
new AccountV2.Login({
|
||||
code: AccountV2.DeviceCode.make("device-code"),
|
||||
user: AccountV2.UserCode.make("user-code"),
|
||||
url: "https://one.example.com/verify",
|
||||
server: "https://one.example.com",
|
||||
expiry: Duration.seconds(600),
|
||||
interval: Duration.seconds(5),
|
||||
})
|
||||
|
||||
const deviceTokenClient = (body: unknown, status = 400) =>
|
||||
HttpClient.make((req) =>
|
||||
Effect.succeed(
|
||||
req.url === "https://one.example.com/auth/device/token" ? json(req, body, status) : json(req, {}, 404),
|
||||
),
|
||||
)
|
||||
|
||||
const poll = (body: unknown, status = 400) =>
|
||||
AccountV2.Service.use((s) => s.poll(login())).pipe(Effect.provide(live(deviceTokenClient(body, status))))
|
||||
|
||||
it.live("login normalizes trailing slashes in the provided server URL", () =>
|
||||
Effect.gen(function* () {
|
||||
const seen: Array<string> = []
|
||||
const client = HttpClient.make((req) =>
|
||||
Effect.gen(function* () {
|
||||
seen.push(`${req.method} ${req.url}`)
|
||||
|
||||
if (req.url === "https://one.example.com/auth/device/code") {
|
||||
return json(req, {
|
||||
device_code: "device-code",
|
||||
user_code: "user-code",
|
||||
verification_uri_complete: "/device?user_code=user-code",
|
||||
expires_in: 600,
|
||||
interval: 5,
|
||||
})
|
||||
}
|
||||
|
||||
return json(req, {}, 404)
|
||||
}),
|
||||
)
|
||||
|
||||
const result = yield* AccountV2.use.login("https://one.example.com/").pipe(Effect.provide(live(client)))
|
||||
|
||||
expect(seen).toEqual(["POST https://one.example.com/auth/device/code"])
|
||||
expect(result.server).toBe("https://one.example.com")
|
||||
expect(result.url).toBe("https://one.example.com/device?user_code=user-code")
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("login maps transport failures to account transport errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const client = HttpClient.make((req) =>
|
||||
Effect.fail(
|
||||
new HttpClientError.HttpClientError({
|
||||
reason: new HttpClientError.TransportError({ request: req }),
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
const error = yield* Effect.flip(AccountV2.use.login("https://one.example.com").pipe(Effect.provide(live(client))))
|
||||
|
||||
expect(error).toBeInstanceOf(AccountV2.AccountTransportError)
|
||||
if (error instanceof AccountV2.AccountTransportError) {
|
||||
expect(error.method).toBe("POST")
|
||||
expect(error.url).toBe("https://one.example.com/auth/device/code")
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("orgsByAccount groups orgs per account", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* persist({
|
||||
id: AccountV2.ID.make("user-1"),
|
||||
email: "one@example.com",
|
||||
url: "https://one.example.com",
|
||||
accessToken: AccountV2.AccessToken.make("at_1"),
|
||||
refreshToken: AccountV2.RefreshToken.make("rt_1"),
|
||||
expiry: Date.now() + outsideEagerRefreshWindow,
|
||||
orgID: Option.none(),
|
||||
})
|
||||
|
||||
yield* persist({
|
||||
id: AccountV2.ID.make("user-2"),
|
||||
email: "two@example.com",
|
||||
url: "https://two.example.com",
|
||||
accessToken: AccountV2.AccessToken.make("at_2"),
|
||||
refreshToken: AccountV2.RefreshToken.make("rt_2"),
|
||||
expiry: Date.now() + outsideEagerRefreshWindow,
|
||||
orgID: Option.none(),
|
||||
})
|
||||
|
||||
const seen: Array<string> = []
|
||||
const client = HttpClient.make((req) =>
|
||||
Effect.gen(function* () {
|
||||
seen.push(`${req.method} ${req.url}`)
|
||||
|
||||
if (req.url === "https://one.example.com/api/orgs") {
|
||||
return json(req, [org("org-1", "One")])
|
||||
}
|
||||
|
||||
if (req.url === "https://two.example.com/api/orgs") {
|
||||
return json(req, [org("org-2", "Two A"), org("org-3", "Two B")])
|
||||
}
|
||||
|
||||
return json(req, [], 404)
|
||||
}),
|
||||
)
|
||||
|
||||
const rows = yield* AccountV2.use.orgsByAccount().pipe(Effect.provide(live(client)))
|
||||
|
||||
expect(rows.map((row) => [row.account.id, row.orgs.map((org) => org.id)]).map(([id, orgs]) => [id, orgs])).toEqual([
|
||||
[AccountV2.ID.make("user-1"), [AccountV2.OrgID.make("org-1")]],
|
||||
[AccountV2.ID.make("user-2"), [AccountV2.OrgID.make("org-2"), AccountV2.OrgID.make("org-3")]],
|
||||
])
|
||||
expect(seen).toEqual(["GET https://one.example.com/api/orgs", "GET https://two.example.com/api/orgs"])
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("token refresh persists the new token", () =>
|
||||
Effect.gen(function* () {
|
||||
const id = AccountV2.ID.make("user-1")
|
||||
|
||||
yield* persist({
|
||||
id,
|
||||
email: "user@example.com",
|
||||
url: "https://one.example.com",
|
||||
accessToken: AccountV2.AccessToken.make("at_old"),
|
||||
refreshToken: AccountV2.RefreshToken.make("rt_old"),
|
||||
expiry: Date.now() - 1_000,
|
||||
orgID: Option.none(),
|
||||
})
|
||||
|
||||
const client = HttpClient.make((req) =>
|
||||
Effect.succeed(
|
||||
req.url === "https://one.example.com/auth/device/token"
|
||||
? json(req, {
|
||||
access_token: "at_new",
|
||||
refresh_token: "rt_new",
|
||||
expires_in: 60,
|
||||
})
|
||||
: json(req, {}, 404),
|
||||
),
|
||||
)
|
||||
|
||||
const token = yield* AccountV2.use.token(id).pipe(Effect.provide(live(client)))
|
||||
|
||||
expect(Option.getOrThrow(token)).toBeDefined()
|
||||
expect(String(Option.getOrThrow(token))).toBe("at_new")
|
||||
|
||||
const value = yield* row(id)
|
||||
expect(value).toBeDefined()
|
||||
if (!value) return
|
||||
expect(value.access_token).toBe(AccountV2.AccessToken.make("at_new"))
|
||||
expect(value.refresh_token).toBe(AccountV2.RefreshToken.make("rt_new"))
|
||||
expect(value.token_expiry).toBeGreaterThan(Date.now())
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("token refreshes before expiry when inside the eager refresh window", () =>
|
||||
Effect.gen(function* () {
|
||||
const id = AccountV2.ID.make("user-1")
|
||||
|
||||
yield* persist({
|
||||
id,
|
||||
email: "user@example.com",
|
||||
url: "https://one.example.com",
|
||||
accessToken: AccountV2.AccessToken.make("at_old"),
|
||||
refreshToken: AccountV2.RefreshToken.make("rt_old"),
|
||||
expiry: Date.now() + insideEagerRefreshWindow,
|
||||
orgID: Option.none(),
|
||||
})
|
||||
|
||||
let refreshCalls = 0
|
||||
const client = HttpClient.make((req) =>
|
||||
Effect.promise(async () => {
|
||||
if (req.url === "https://one.example.com/auth/device/token") {
|
||||
refreshCalls += 1
|
||||
return json(req, {
|
||||
access_token: "at_new",
|
||||
refresh_token: "rt_new",
|
||||
expires_in: 60,
|
||||
})
|
||||
}
|
||||
|
||||
return json(req, {}, 404)
|
||||
}),
|
||||
)
|
||||
|
||||
const token = yield* AccountV2.use.token(id).pipe(Effect.provide(live(client)))
|
||||
|
||||
expect(String(Option.getOrThrow(token))).toBe("at_new")
|
||||
expect(refreshCalls).toBe(1)
|
||||
|
||||
const value = yield* row(id)
|
||||
expect(value).toBeDefined()
|
||||
if (!value) return
|
||||
expect(value.access_token).toBe(AccountV2.AccessToken.make("at_new"))
|
||||
expect(value.refresh_token).toBe(AccountV2.RefreshToken.make("rt_new"))
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("concurrent config and token requests coalesce token refresh", () =>
|
||||
Effect.gen(function* () {
|
||||
const id = AccountV2.ID.make("user-1")
|
||||
|
||||
yield* persist({
|
||||
id,
|
||||
email: "user@example.com",
|
||||
url: "https://one.example.com",
|
||||
accessToken: AccountV2.AccessToken.make("at_old"),
|
||||
refreshToken: AccountV2.RefreshToken.make("rt_old"),
|
||||
expiry: Date.now() - 1_000,
|
||||
orgID: Option.some(AccountV2.OrgID.make("org-9")),
|
||||
})
|
||||
|
||||
let refreshCalls = 0
|
||||
const client = HttpClient.make((req) =>
|
||||
Effect.promise(async () => {
|
||||
if (req.url === "https://one.example.com/auth/device/token") {
|
||||
refreshCalls += 1
|
||||
|
||||
if (refreshCalls === 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 25))
|
||||
return json(req, {
|
||||
access_token: "at_new",
|
||||
refresh_token: "rt_new",
|
||||
expires_in: 60,
|
||||
})
|
||||
}
|
||||
|
||||
return json(
|
||||
req,
|
||||
{
|
||||
error: "invalid_grant",
|
||||
error_description: "refresh token already used",
|
||||
},
|
||||
400,
|
||||
)
|
||||
}
|
||||
|
||||
if (req.url === "https://one.example.com/api/config") {
|
||||
return json(req, { config: { theme: "light", seats: 5 } })
|
||||
}
|
||||
|
||||
return json(req, {}, 404)
|
||||
}),
|
||||
)
|
||||
|
||||
const [cfg, token] = yield* AccountV2.Service.use((s) =>
|
||||
Effect.all([s.config(id, AccountV2.OrgID.make("org-9")), s.token(id)], { concurrency: 2 }),
|
||||
).pipe(Effect.provide(live(client)))
|
||||
|
||||
expect(Option.getOrThrow(cfg)).toEqual({ theme: "light", seats: 5 })
|
||||
expect(String(Option.getOrThrow(token))).toBe("at_new")
|
||||
expect(refreshCalls).toBe(1)
|
||||
|
||||
const value = yield* row(id)
|
||||
expect(value).toBeDefined()
|
||||
if (!value) return
|
||||
expect(value.access_token).toBe(AccountV2.AccessToken.make("at_new"))
|
||||
expect(value.refresh_token).toBe(AccountV2.RefreshToken.make("rt_new"))
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("config sends the selected org header", () =>
|
||||
Effect.gen(function* () {
|
||||
const id = AccountV2.ID.make("user-1")
|
||||
|
||||
yield* persist({
|
||||
id,
|
||||
email: "user@example.com",
|
||||
url: "https://one.example.com",
|
||||
accessToken: AccountV2.AccessToken.make("at_1"),
|
||||
refreshToken: AccountV2.RefreshToken.make("rt_1"),
|
||||
expiry: Date.now() + outsideEagerRefreshWindow,
|
||||
orgID: Option.none(),
|
||||
})
|
||||
|
||||
const seen: { auth?: string; org?: string } = {}
|
||||
const client = HttpClient.make((req) =>
|
||||
Effect.gen(function* () {
|
||||
seen.auth = req.headers.authorization
|
||||
seen.org = req.headers["x-org-id"]
|
||||
|
||||
if (req.url === "https://one.example.com/api/config") {
|
||||
return json(req, { config: { theme: "light", seats: 5 } })
|
||||
}
|
||||
|
||||
return json(req, {}, 404)
|
||||
}),
|
||||
)
|
||||
|
||||
const cfg = yield* AccountV2.Service.use((s) => s.config(id, AccountV2.OrgID.make("org-9"))).pipe(
|
||||
Effect.provide(live(client)),
|
||||
)
|
||||
|
||||
expect(Option.getOrThrow(cfg)).toEqual({ theme: "light", seats: 5 })
|
||||
expect(seen).toEqual({
|
||||
auth: "Bearer at_1",
|
||||
org: "org-9",
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("poll stores the account and first org on success", () =>
|
||||
Effect.gen(function* () {
|
||||
const client = HttpClient.make((req) =>
|
||||
Effect.succeed(
|
||||
req.url === "https://one.example.com/auth/device/token"
|
||||
? json(req, {
|
||||
access_token: "at_1",
|
||||
refresh_token: "rt_1",
|
||||
token_type: "Bearer",
|
||||
expires_in: 60,
|
||||
})
|
||||
: req.url === "https://one.example.com/api/user"
|
||||
? json(req, { id: "user-1", email: "user@example.com" })
|
||||
: req.url === "https://one.example.com/api/orgs"
|
||||
? json(req, [org("org-1", "One")])
|
||||
: json(req, {}, 404),
|
||||
),
|
||||
)
|
||||
|
||||
const res = yield* AccountV2.Service.use((s) => s.poll(login())).pipe(Effect.provide(live(client)))
|
||||
|
||||
expect(res._tag).toBe("PollSuccess")
|
||||
if (res._tag === "PollSuccess") {
|
||||
expect(res.email).toBe("user@example.com")
|
||||
}
|
||||
|
||||
const current = yield* active
|
||||
expect(current).toEqual(
|
||||
expect.objectContaining({
|
||||
id: "user-1",
|
||||
email: "user@example.com",
|
||||
active_org_id: "org-1",
|
||||
}),
|
||||
)
|
||||
}),
|
||||
)
|
||||
|
||||
for (const [name, body, expectedTag] of [
|
||||
[
|
||||
"pending",
|
||||
{
|
||||
error: "authorization_pending",
|
||||
error_description: "The authorization request is still pending",
|
||||
},
|
||||
"PollPending",
|
||||
],
|
||||
[
|
||||
"slow",
|
||||
{
|
||||
error: "slow_down",
|
||||
error_description: "Polling too frequently, please slow down",
|
||||
},
|
||||
"PollSlow",
|
||||
],
|
||||
[
|
||||
"denied",
|
||||
{
|
||||
error: "access_denied",
|
||||
error_description: "The authorization request was denied",
|
||||
},
|
||||
"PollDenied",
|
||||
],
|
||||
[
|
||||
"expired",
|
||||
{
|
||||
error: "expired_token",
|
||||
error_description: "The device code has expired",
|
||||
},
|
||||
"PollExpired",
|
||||
],
|
||||
] as const) {
|
||||
it.live(`poll returns ${name} for ${body.error}`, () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* poll(body)
|
||||
expect(result._tag).toBe(expectedTag)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
it.live("poll returns poll error for other OAuth errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* poll({
|
||||
error: "server_error",
|
||||
error_description: "An unexpected error occurred",
|
||||
})
|
||||
|
||||
expect(result._tag).toBe("PollError")
|
||||
if (result._tag === "PollError") {
|
||||
expect(String(result.cause)).toContain("server_error")
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,12 +1,17 @@
|
|||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Schema } from "effect"
|
||||
import { Effect, Layer, Schema } from "effect"
|
||||
import { AgentV2 } from "@opencode-ai/core/agent"
|
||||
import { Config } from "@opencode-ai/core/config"
|
||||
import { ConfigAgentPlugin } from "@opencode-ai/core/config/plugin/agent"
|
||||
import { AppFileSystem } from "@opencode-ai/core/filesystem"
|
||||
import { PermissionV2 } from "@opencode-ai/core/permission"
|
||||
import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
import { tmpdir } from "../fixture/tmpdir"
|
||||
import { testEffect } from "../lib/effect"
|
||||
|
||||
const it = testEffect(AgentV2.locationLayer)
|
||||
const it = testEffect(Layer.mergeAll(AgentV2.locationLayer, AppFileSystem.defaultLayer))
|
||||
const decode = Schema.decodeUnknownSync(Config.Info)
|
||||
|
||||
describe("ConfigAgentPlugin.Plugin", () => {
|
||||
|
|
@ -183,4 +188,73 @@ describe("ConfigAgentPlugin.Plugin", () => {
|
|||
expect(yield* agents.get(build)).toBeUndefined()
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("loads markdown agents from config directories in priority order", () =>
|
||||
Effect.acquireRelease(
|
||||
Effect.promise(() => tmpdir()),
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
).pipe(
|
||||
Effect.flatMap((tmp) => {
|
||||
const global = path.join(tmp.path, "global")
|
||||
const local = path.join(tmp.path, ".opencode")
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.promise(async () => {
|
||||
await fs.mkdir(path.join(global, "agent"), { recursive: true })
|
||||
await fs.mkdir(path.join(local, "agents", "team"), { recursive: true })
|
||||
await fs.writeFile(
|
||||
path.join(global, "agent", "reviewer.md"),
|
||||
`---
|
||||
description: Global reviewer
|
||||
mode: subagent
|
||||
permissions:
|
||||
- action: edit
|
||||
resource: "*"
|
||||
effect: deny
|
||||
---
|
||||
Review globally.`,
|
||||
)
|
||||
await fs.writeFile(
|
||||
path.join(local, "agents", "reviewer.md"),
|
||||
`---
|
||||
description: Local reviewer
|
||||
model: anthropic/claude-sonnet
|
||||
---
|
||||
Review locally.`,
|
||||
)
|
||||
await fs.writeFile(
|
||||
path.join(local, "agents", "team", "research.md"),
|
||||
`---
|
||||
mode: subagent
|
||||
---
|
||||
Research the issue.`,
|
||||
)
|
||||
await fs.writeFile(path.join(local, "agents", "build.md"), "---\ndisabled: true\n---\n")
|
||||
})
|
||||
|
||||
const agents = yield* AgentV2.Service
|
||||
yield* agents.update((editor) => editor.update(AgentV2.ID.make("build"), () => {}))
|
||||
const config = Config.Service.of({
|
||||
directories: () => Effect.succeed([AbsolutePath.make(global), AbsolutePath.make(local)]),
|
||||
get: () => Effect.succeed([]),
|
||||
})
|
||||
|
||||
yield* ConfigAgentPlugin.Plugin.effect.pipe(Effect.provideService(Config.Service, config))
|
||||
|
||||
const reviewer = yield* agents.get(AgentV2.ID.make("reviewer"))
|
||||
expect(reviewer).toMatchObject({
|
||||
system: "Review locally.",
|
||||
description: "Local reviewer",
|
||||
mode: "subagent",
|
||||
model: { providerID: "anthropic", id: "claude-sonnet" },
|
||||
})
|
||||
expect(PermissionV2.evaluate("edit", "src/index.ts", reviewer?.permissions ?? []).effect).toBe("deny")
|
||||
expect(yield* agents.get(AgentV2.ID.make("team/research"))).toMatchObject({
|
||||
system: "Research the issue.",
|
||||
mode: "subagent",
|
||||
})
|
||||
expect(yield* agents.get(AgentV2.ID.make("build"))).toBeUndefined()
|
||||
})
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue