mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 13:05:14 +03:00
refactor(core): remove small dead code and duplicate helpers (#61181)
This commit is contained in:
committed by
GitHub
Unverified
parent
c930ef1f08
commit
dbcd5ce948
@@ -26,10 +26,9 @@ export function rewrite<ID extends string>(
|
||||
input: Context & { readonly specifier: string | undefined },
|
||||
) {
|
||||
if (input.specifier === undefined) return
|
||||
const plain = resolve(input.specifier, input)
|
||||
if (!plain) return
|
||||
const settings = decode(target.settings ?? {})
|
||||
const replacement = resolve(input.specifier, { ...input, settings }) ?? plain
|
||||
const replacement = resolve(input.specifier, { ...input, settings })
|
||||
if (!replacement) return
|
||||
const translated = options(replacement, input.modelID, settings)
|
||||
if (target.package !== undefined || replacement !== input.specifier) target.package = replacement
|
||||
// Without `provider`, the native compatible package reports every AI SDK-mapped host as `openai-compatible`.
|
||||
|
||||
+18
-23
@@ -509,7 +509,7 @@ function prompt(request: LLMRequest): LanguageModelV3Prompt {
|
||||
.join("\n\n")
|
||||
const pending: UserContent = []
|
||||
const messages = request.messages.flatMap((input, index) => {
|
||||
if (input.role !== "tool") return message(input)
|
||||
if (input.role !== "tool") return message(input.role, input.content)
|
||||
const lowered = toolMessage(input)
|
||||
pending.push(...lowered.media)
|
||||
if (request.messages[index + 1]?.role === "tool" || pending.length === 0) return lowered.messages
|
||||
@@ -527,8 +527,11 @@ function prompt(request: LLMRequest): LanguageModelV3Prompt {
|
||||
return [{ role: "system", content: system }, ...messages]
|
||||
}
|
||||
|
||||
function message(input: LLMRequest["messages"][number]): LanguageModelV3Message[] {
|
||||
switch (input.role) {
|
||||
function message(
|
||||
role: Exclude<LLMRequest["messages"][number]["role"], "tool">,
|
||||
content: LLMRequest["messages"][number]["content"],
|
||||
): LanguageModelV3Message[] {
|
||||
switch (role) {
|
||||
case "system":
|
||||
// The initial privileged prompt lives in `request.system` and is prepended above. A system message here is a
|
||||
// chronological instruction update, but opaque AI SDK providers do not uniformly allow the system role after
|
||||
@@ -539,17 +542,15 @@ function message(input: LLMRequest["messages"][number]): LanguageModelV3Message[
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: ProviderShared.wrapSystemUpdate(input.content.filter((part) => part.type === "text")),
|
||||
text: ProviderShared.wrapSystemUpdate(content.filter((part) => part.type === "text")),
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
case "user":
|
||||
return [{ role: "user", content: input.content.flatMap(userPart) }]
|
||||
return [{ role: "user", content: content.flatMap(userPart) }]
|
||||
case "assistant":
|
||||
return [{ role: "assistant", content: input.content.flatMap(assistantPart) }]
|
||||
case "tool":
|
||||
return toolMessage(input).messages
|
||||
return [{ role: "assistant", content: content.flatMap(assistantPart) }]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -838,20 +839,14 @@ function streamPartEvents(
|
||||
providerMetadata: providerMetadata(event.providerMetadata),
|
||||
}),
|
||||
])
|
||||
case "finish":
|
||||
return Effect.succeed([
|
||||
LLMEvent.stepFinish({
|
||||
index: state.step++,
|
||||
reason: { normalized: finishReason(event.finishReason), raw: event.finishReason.raw },
|
||||
usage: usage(event.usage),
|
||||
providerMetadata: providerMetadata(event.providerMetadata),
|
||||
}),
|
||||
LLMEvent.finish({
|
||||
reason: { normalized: finishReason(event.finishReason), raw: event.finishReason.raw },
|
||||
usage: usage(event.usage),
|
||||
providerMetadata: providerMetadata(event.providerMetadata),
|
||||
}),
|
||||
])
|
||||
case "finish": {
|
||||
const finish = {
|
||||
reason: { normalized: finishReason(event.finishReason), raw: event.finishReason.raw },
|
||||
usage: usage(event.usage),
|
||||
providerMetadata: providerMetadata(event.providerMetadata),
|
||||
}
|
||||
return Effect.succeed([LLMEvent.stepFinish({ index: state.step++, ...finish }), LLMEvent.finish(finish)])
|
||||
}
|
||||
case "error":
|
||||
return Effect.fail(llmError(event.error, "read"))
|
||||
}
|
||||
@@ -941,7 +936,7 @@ function llmError(error: unknown, operation: "request" | "read") {
|
||||
|
||||
// AI SDK stream errors can arrive as plain objects. A gateway's type validation error keeps the provider's error
|
||||
// response in `value`, which carries the message and codes.
|
||||
const errorValue = (error: unknown) => (ProviderShared.isRecord(error) ? error.value : undefined)
|
||||
const errorValue = (error: unknown) => (isRecord(error) ? error.value : undefined)
|
||||
|
||||
// Runtime-generated network failure shapes. The codes mirror the AI SDK's own
|
||||
// Bun network error list in handleFetchError; the messages are undici's fetch
|
||||
|
||||
@@ -212,6 +212,12 @@ const layer = Layer.effect(
|
||||
|
||||
const rootDir = path.join(global.data, "artifacts")
|
||||
const itemDir = (id: ID) => path.join(rootDir, id)
|
||||
const requireRecord = (id: ID) =>
|
||||
loadProjectRecord(kv, id, location.project.id).pipe(
|
||||
Effect.flatMap((existing) =>
|
||||
existing ? Effect.succeed(existing) : Effect.fail(new NotFoundError({ artifactID: id })),
|
||||
),
|
||||
)
|
||||
|
||||
const localProvider: ProviderImplementation = {
|
||||
id: LocalProviderID,
|
||||
@@ -220,14 +226,9 @@ const layer = Layer.effect(
|
||||
prompt:
|
||||
"Artifacts are served as HTML by this OpenCode server. Only people who can reach this server can open them.",
|
||||
create: (input) =>
|
||||
replaceDirectoryFiles(itemDir(input.id), input.files).pipe(
|
||||
Effect.as({ url: `/api/experimental/artifacts/${encodeURIComponent(input.id)}/view/` }),
|
||||
),
|
||||
replaceDirectoryFiles(itemDir(input.id), input.files).pipe(Effect.as({ url: viewURL(input.id) })),
|
||||
read: (id) => readDirectoryFiles(itemDir(id)),
|
||||
update: (id, input) =>
|
||||
replaceDirectoryFiles(itemDir(id), input.files).pipe(
|
||||
Effect.as({ url: `/api/experimental/artifacts/${encodeURIComponent(id)}/view/` }),
|
||||
),
|
||||
update: (id, input) => replaceDirectoryFiles(itemDir(id), input.files).pipe(Effect.as({ url: viewURL(id) })),
|
||||
delete: (id) => Effect.promise(() => fs.rm(itemDir(id), { recursive: true, force: true })),
|
||||
}
|
||||
|
||||
@@ -349,7 +350,7 @@ const layer = Layer.effect(
|
||||
...(input.sessionID === undefined ? {} : { sessionID: input.sessionID }),
|
||||
title,
|
||||
entry,
|
||||
url: created.url ?? `/api/experimental/artifacts/${encodeURIComponent(id)}/view/`,
|
||||
url: created.url ?? viewURL(id),
|
||||
time: { created: now, updated: now },
|
||||
})
|
||||
yield* kv.set(
|
||||
@@ -364,14 +365,12 @@ const layer = Layer.effect(
|
||||
}),
|
||||
info: Effect.fn("Artifact.info")(function* (id) {
|
||||
yield* requireEnabled()
|
||||
const existing = yield* loadProjectRecord(kv, id, location.project.id)
|
||||
if (!existing) return yield* new NotFoundError({ artifactID: id })
|
||||
const existing = yield* requireRecord(id)
|
||||
return existing.info
|
||||
}),
|
||||
get: Effect.fn("Artifact.get")(function* (id) {
|
||||
yield* requireEnabled()
|
||||
const existing = yield* loadProjectRecord(kv, id, location.project.id)
|
||||
if (!existing) return yield* new NotFoundError({ artifactID: id })
|
||||
const existing = yield* requireRecord(id)
|
||||
const provider = yield* resolveProvider(existing.info.provider)
|
||||
const raw = yield* provider
|
||||
.read(id)
|
||||
@@ -384,8 +383,7 @@ const layer = Layer.effect(
|
||||
update: Effect.fn("Artifact.update")(function* (id, input) {
|
||||
yield* requireEnabled()
|
||||
yield* checkSession(input.sessionID)
|
||||
const existing = yield* loadProjectRecord(kv, id, location.project.id)
|
||||
if (!existing) return yield* new NotFoundError({ artifactID: id })
|
||||
const existing = yield* requireRecord(id)
|
||||
const title = input.title === undefined ? existing.info.title : input.title.trim()
|
||||
if (!title) return yield* new InvalidError({ reason: "Artifact title must not be empty", field: "title" })
|
||||
const files = yield* normalizeFiles(encodeStringFiles(input.files))
|
||||
@@ -420,8 +418,7 @@ const layer = Layer.effect(
|
||||
}),
|
||||
remove: Effect.fn("Artifact.remove")(function* (id) {
|
||||
yield* requireEnabled()
|
||||
const existing = yield* loadProjectRecord(kv, id, location.project.id)
|
||||
if (!existing) return yield* new NotFoundError({ artifactID: id })
|
||||
const existing = yield* requireRecord(id)
|
||||
const provider = state.get().providers.get(existing.info.provider)
|
||||
if (provider) {
|
||||
yield* provider
|
||||
@@ -432,8 +429,7 @@ const layer = Layer.effect(
|
||||
}),
|
||||
readLocalFile: Effect.fn("Artifact.readLocalFile")(function* (id, subpath) {
|
||||
yield* requireEnabled()
|
||||
const existing = yield* loadProjectRecord(kv, id, location.project.id)
|
||||
if (!existing) return yield* new NotFoundError({ artifactID: id })
|
||||
const existing = yield* requireRecord(id)
|
||||
if (existing.info.provider !== LocalProviderID) {
|
||||
return yield* new InvalidError({
|
||||
reason: `Artifact ${id} is hosted by provider "${existing.info.provider}", not the local server`,
|
||||
@@ -482,9 +478,14 @@ function detectFileMime(filePath: string, bytes: Uint8Array) {
|
||||
}
|
||||
|
||||
function normalizePath(raw: string): Effect.Effect<string, InvalidError> {
|
||||
const trimmed = raw.replaceAll("\\", "/").replace(/^(?:\.\/)+/u, "").replace(/^\/+/u, "")
|
||||
const trimmed = raw
|
||||
.replaceAll("\\", "/")
|
||||
.replace(/^(?:\.\/)+/u, "")
|
||||
.replace(/^\/+/u, "")
|
||||
if (!trimmed || trimmed.includes("\0")) {
|
||||
return Effect.fail(new InvalidError({ reason: `Invalid artifact file path: ${JSON.stringify(raw)}`, field: "files" }))
|
||||
return Effect.fail(
|
||||
new InvalidError({ reason: `Invalid artifact file path: ${JSON.stringify(raw)}`, field: "files" }),
|
||||
)
|
||||
}
|
||||
const segments = trimmed.split("/")
|
||||
if (segments.some((part) => !part || part === "." || part === "..")) {
|
||||
@@ -532,6 +533,10 @@ function resolveEntry(files: Readonly<Record<string, Uint8Array>>, requested?: s
|
||||
)
|
||||
}
|
||||
|
||||
function viewURL(id: ID) {
|
||||
return `/api/experimental/artifacts/${encodeURIComponent(id)}/view/`
|
||||
}
|
||||
|
||||
function loadProjectRecord(kv: KV.Interface, id: ID, projectID: string) {
|
||||
return kv.get(ItemPrefix + id).pipe(
|
||||
Effect.map((stored) => {
|
||||
|
||||
+25
-46
@@ -71,6 +71,12 @@ const envelope = (aggregateID: string, seq: number, version: number) => ({
|
||||
version: Event.Version.make(version),
|
||||
})
|
||||
|
||||
const requireAggregateID = (type: string, aggregate: string, data: unknown) => {
|
||||
const aggregateID = (data as Record<string, unknown>)[aggregate]
|
||||
if (typeof aggregateID === "string") return Effect.succeed(aggregateID)
|
||||
return Effect.die(new InvalidDurableEventError({ type, message: `Expected string aggregate field ${aggregate}` }))
|
||||
}
|
||||
|
||||
// Every stored event decodes through here, so payloads written in older shapes are upgraded in one place.
|
||||
const decodeStoredData = (definition: Event.DurableDefinition, data: unknown) =>
|
||||
Schema.decodeUnknownSync(definition.data)(SessionLegacy.event(definition.type, data))
|
||||
@@ -295,14 +301,7 @@ export function configured(options?: Options) {
|
||||
return Effect.gen(function* () {
|
||||
const durable = definition.durable
|
||||
if (!durable) return yield* Effect.void
|
||||
const aggregateID = (event.data as Record<string, unknown>)[durable.aggregate]
|
||||
if (typeof aggregateID !== "string")
|
||||
return yield* Effect.die(
|
||||
new InvalidDurableEventError({
|
||||
type: event.type,
|
||||
message: `Expected string aggregate field ${durable.aggregate}`,
|
||||
}),
|
||||
)
|
||||
const aggregateID = yield* requireAggregateID(event.type, durable.aggregate, event.data)
|
||||
if (input && input.aggregateID !== aggregateID) {
|
||||
yield* Effect.die(
|
||||
new InvalidDurableEventError({
|
||||
@@ -508,8 +507,8 @@ export function configured(options?: Options) {
|
||||
})
|
||||
}
|
||||
|
||||
function publish<D extends Event.Definition>(definition: D, data: Event.Data<D>, options?: PublishOptions) {
|
||||
return Effect.gen(function* () {
|
||||
const makePayload = (definition: Event.Definition, data: unknown, options: PublishOptions | undefined) =>
|
||||
Effect.gen(function* () {
|
||||
const serviceLocation = Option.getOrUndefined(yield* Effect.serviceOption(Location.Service))
|
||||
const location = options?.global
|
||||
? undefined
|
||||
@@ -517,53 +516,33 @@ export function configured(options?: Options) {
|
||||
(serviceLocation
|
||||
? { directory: serviceLocation.directory, workspaceID: serviceLocation.workspaceID }
|
||||
: undefined))
|
||||
return yield* publishEvent(
|
||||
definition,
|
||||
{
|
||||
id: options?.id ?? Event.ID.create(),
|
||||
created: yield* Clock.currentTimeMillis,
|
||||
...(options?.metadata ? { metadata: options.metadata } : {}),
|
||||
type: definition.type,
|
||||
...(location ? { location } : {}),
|
||||
data,
|
||||
} as Event.Payload<D>,
|
||||
options?.commit,
|
||||
)
|
||||
return {
|
||||
id: options?.id ?? Event.ID.create(),
|
||||
created: yield* Clock.currentTimeMillis,
|
||||
...(options?.metadata ? { metadata: options.metadata } : {}),
|
||||
type: definition.type,
|
||||
...(location ? { location } : {}),
|
||||
data,
|
||||
} as Event.Payload
|
||||
})
|
||||
|
||||
function publish<D extends Event.Definition>(definition: D, data: Event.Data<D>, options?: PublishOptions) {
|
||||
return Effect.gen(function* () {
|
||||
const event = (yield* makePayload(definition, data, options)) as Event.Payload<D>
|
||||
return yield* publishEvent(definition, event, options?.commit)
|
||||
})
|
||||
}
|
||||
|
||||
function publishAll<const I extends readonly [PublishInput, ...PublishInput[]]>(events: I) {
|
||||
return Effect.gen(function* () {
|
||||
const serviceLocation = Option.getOrUndefined(yield* Effect.serviceOption(Location.Service))
|
||||
const payloads = yield* Effect.forEach(events, ([definition, data, options]) =>
|
||||
Effect.gen(function* () {
|
||||
const aggregateID = (data as Record<string, unknown>)[definition.durable.aggregate]
|
||||
if (typeof aggregateID !== "string") {
|
||||
return yield* Effect.die(
|
||||
new InvalidDurableEventError({
|
||||
type: definition.type,
|
||||
message: `Expected string aggregate field ${definition.durable.aggregate}`,
|
||||
}),
|
||||
)
|
||||
}
|
||||
const location = options?.global
|
||||
? undefined
|
||||
: (options?.location ??
|
||||
(serviceLocation
|
||||
? { directory: serviceLocation.directory, workspaceID: serviceLocation.workspaceID }
|
||||
: undefined))
|
||||
const aggregateID = yield* requireAggregateID(definition.type, definition.durable.aggregate, data)
|
||||
return {
|
||||
definition,
|
||||
aggregateID,
|
||||
commit: options?.commit,
|
||||
event: {
|
||||
id: options?.id ?? Event.ID.create(),
|
||||
created: yield* Clock.currentTimeMillis,
|
||||
...(options?.metadata ? { metadata: options.metadata } : {}),
|
||||
type: definition.type,
|
||||
...(location ? { location } : {}),
|
||||
data,
|
||||
} as Event.Payload,
|
||||
event: yield* makePayload(definition, data, options),
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
+49
-106
@@ -1,6 +1,6 @@
|
||||
export * as Credential from "./credential.js"
|
||||
|
||||
import { asc, desc, eq } from "drizzle-orm"
|
||||
import { asc, desc, eq, type SQL } from "drizzle-orm"
|
||||
import { Cause, Context, Effect, Fiber, Layer, Schema } from "effect"
|
||||
import { Credential } from "@opencode/schema/credential"
|
||||
import { CredentialLegacy } from "@opencode/schema/credential-legacy"
|
||||
@@ -93,6 +93,38 @@ const layer = Layer.effect(
|
||||
const credential = stored(row)
|
||||
return credential ? [credential] : []
|
||||
})
|
||||
const rows = (where?: SQL) =>
|
||||
db
|
||||
.select()
|
||||
.from(CredentialTable)
|
||||
.where(where)
|
||||
.orderBy(asc(CredentialTable.active), asc(CredentialTable.time_created), asc(CredentialTable.id))
|
||||
.all()
|
||||
.pipe(Effect.orDie, Effect.map(storedRows))
|
||||
type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0]
|
||||
const currentActive = (tx: Transaction, integrationID: Integration.ID) =>
|
||||
tx
|
||||
.select({ id: CredentialTable.id, active: CredentialTable.active })
|
||||
.from(CredentialTable)
|
||||
.where(eq(CredentialTable.integration_id, integrationID))
|
||||
.orderBy(desc(CredentialTable.active), desc(CredentialTable.time_created), desc(CredentialTable.id))
|
||||
.get()
|
||||
const deactivateAll = (tx: Transaction, integrationID: Integration.ID) =>
|
||||
tx.update(CredentialTable).set({ active: false }).where(eq(CredentialTable.integration_id, integrationID)).run()
|
||||
const switchActive = (tx: Transaction, integrationID: Integration.ID, id: ID) =>
|
||||
Effect.gen(function* () {
|
||||
yield* deactivateAll(tx, integrationID)
|
||||
yield* tx.update(CredentialTable).set({ active: true }).where(eq(CredentialTable.id, id)).run()
|
||||
})
|
||||
const logFailure =
|
||||
(message: string, fields: Record<string, unknown>) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
effect.pipe(
|
||||
Effect.onError((cause) =>
|
||||
Effect.logError(message, { ...fields, errors: ErrorSummary.from(Cause.squash(cause)) }),
|
||||
),
|
||||
Effect.orDie,
|
||||
)
|
||||
|
||||
return Service.of({
|
||||
lock: Effect.fn("Credential.lock")((id, operation) =>
|
||||
@@ -112,22 +144,8 @@ const layer = Layer.effect(
|
||||
}),
|
||||
),
|
||||
),
|
||||
all: () =>
|
||||
db
|
||||
.select()
|
||||
.from(CredentialTable)
|
||||
.orderBy(asc(CredentialTable.active), asc(CredentialTable.time_created), asc(CredentialTable.id))
|
||||
.all()
|
||||
.pipe(Effect.orDie, Effect.map(storedRows)),
|
||||
list: Effect.fn("Credential.list")((integrationID) =>
|
||||
db
|
||||
.select()
|
||||
.from(CredentialTable)
|
||||
.where(eq(CredentialTable.integration_id, integrationID))
|
||||
.orderBy(asc(CredentialTable.active), asc(CredentialTable.time_created), asc(CredentialTable.id))
|
||||
.all()
|
||||
.pipe(Effect.orDie, Effect.map(storedRows)),
|
||||
),
|
||||
all: () => rows(),
|
||||
list: Effect.fn("Credential.list")((integrationID) => rows(eq(CredentialTable.integration_id, integrationID))),
|
||||
get: Effect.fn("Credential.get")(function* (id) {
|
||||
const row = yield* db.select().from(CredentialTable).where(eq(CredentialTable.id, id)).get().pipe(Effect.orDie)
|
||||
return row ? stored(row) : undefined
|
||||
@@ -142,19 +160,9 @@ const layer = Layer.effect(
|
||||
const activated = yield* db
|
||||
.transaction((tx) =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* tx
|
||||
.select({ id: CredentialTable.id, active: CredentialTable.active })
|
||||
.from(CredentialTable)
|
||||
.where(eq(CredentialTable.integration_id, credential.integrationID))
|
||||
.orderBy(desc(CredentialTable.active), desc(CredentialTable.time_created), desc(CredentialTable.id))
|
||||
.get()
|
||||
const current = yield* currentActive(tx, credential.integrationID)
|
||||
const activate = input.activate !== false || !current
|
||||
if (activate)
|
||||
yield* tx
|
||||
.update(CredentialTable)
|
||||
.set({ active: false })
|
||||
.where(eq(CredentialTable.integration_id, credential.integrationID))
|
||||
.run()
|
||||
if (activate) yield* deactivateAll(tx, credential.integrationID)
|
||||
// Legacy rows have no active flag and the newest one is selected, so pin it before inserting a newer row.
|
||||
if (!activate && current && !current.active)
|
||||
yield* tx.update(CredentialTable).set({ active: true }).where(eq(CredentialTable.id, current.id)).run()
|
||||
@@ -172,14 +180,10 @@ const layer = Layer.effect(
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.onError((cause) =>
|
||||
Effect.logError("credential create failed", {
|
||||
credentialID: credential.id,
|
||||
integrationID: credential.integrationID,
|
||||
errors: ErrorSummary.from(Cause.squash(cause)),
|
||||
}),
|
||||
),
|
||||
Effect.orDie,
|
||||
logFailure("credential create failed", {
|
||||
credentialID: credential.id,
|
||||
integrationID: credential.integrationID,
|
||||
}),
|
||||
)
|
||||
yield* Effect.logInfo("credential created", {
|
||||
credentialID: credential.id,
|
||||
@@ -202,31 +206,13 @@ const layer = Layer.effect(
|
||||
Effect.gen(function* () {
|
||||
const credential = yield* tx.select().from(CredentialTable).where(eq(CredentialTable.id, id)).get()
|
||||
if (!credential?.integration_id) return
|
||||
const active = yield* tx
|
||||
.select({ id: CredentialTable.id })
|
||||
.from(CredentialTable)
|
||||
.where(eq(CredentialTable.integration_id, credential.integration_id))
|
||||
.orderBy(desc(CredentialTable.active), desc(CredentialTable.time_created), desc(CredentialTable.id))
|
||||
.get()
|
||||
const active = yield* currentActive(tx, credential.integration_id)
|
||||
if (active?.id === id) return
|
||||
yield* tx
|
||||
.update(CredentialTable)
|
||||
.set({ active: false })
|
||||
.where(eq(CredentialTable.integration_id, credential.integration_id))
|
||||
.run()
|
||||
yield* tx.update(CredentialTable).set({ active: true }).where(eq(CredentialTable.id, id)).run()
|
||||
yield* switchActive(tx, credential.integration_id, id)
|
||||
return credential.integration_id
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.onError((cause) =>
|
||||
Effect.logError("credential activate failed", {
|
||||
credentialID: id,
|
||||
errors: ErrorSummary.from(Cause.squash(cause)),
|
||||
}),
|
||||
),
|
||||
Effect.orDie,
|
||||
)
|
||||
.pipe(logFailure("credential activate failed", { credentialID: id }))
|
||||
if (integrationID) {
|
||||
yield* Effect.logInfo("credential activated", { integrationID, credentialID: id })
|
||||
yield* bus.publish(Event.Switched, { integrationID, credentialID: id }, { global: true })
|
||||
@@ -239,15 +225,7 @@ const layer = Layer.effect(
|
||||
.from(CredentialTable)
|
||||
.where(eq(CredentialTable.id, id))
|
||||
.get()
|
||||
.pipe(
|
||||
Effect.onError((cause) =>
|
||||
Effect.logError("credential update lookup failed", {
|
||||
credentialID: id,
|
||||
errors: ErrorSummary.from(Cause.squash(cause)),
|
||||
}),
|
||||
),
|
||||
Effect.orDie,
|
||||
)
|
||||
.pipe(logFailure("credential update lookup failed", { credentialID: id }))
|
||||
if (!credential?.integrationID) {
|
||||
yield* Effect.logWarning("credential update skipped", { credentialID: id, reason: "credential_missing" })
|
||||
return
|
||||
@@ -259,16 +237,7 @@ const layer = Layer.effect(
|
||||
.where(eq(CredentialTable.id, id))
|
||||
.returning({ id: CredentialTable.id })
|
||||
.get()
|
||||
.pipe(
|
||||
Effect.onError((cause) =>
|
||||
Effect.logError("credential update failed", {
|
||||
credentialID: id,
|
||||
integrationID: credential.integrationID,
|
||||
errors: ErrorSummary.from(Cause.squash(cause)),
|
||||
}),
|
||||
),
|
||||
Effect.orDie,
|
||||
)
|
||||
.pipe(logFailure("credential update failed", { credentialID: id, integrationID: credential.integrationID }))
|
||||
if (!updated) {
|
||||
yield* Effect.logWarning("credential update skipped", { credentialID: id, reason: "credential_removed" })
|
||||
return
|
||||
@@ -288,14 +257,7 @@ const layer = Layer.effect(
|
||||
Effect.gen(function* () {
|
||||
const credential = yield* tx.select().from(CredentialTable).where(eq(CredentialTable.id, id)).get()
|
||||
if (!credential) return
|
||||
const active = credential.integration_id
|
||||
? yield* tx
|
||||
.select({ id: CredentialTable.id })
|
||||
.from(CredentialTable)
|
||||
.where(eq(CredentialTable.integration_id, credential.integration_id))
|
||||
.orderBy(desc(CredentialTable.active), desc(CredentialTable.time_created), desc(CredentialTable.id))
|
||||
.get()
|
||||
: undefined
|
||||
const active = credential.integration_id ? yield* currentActive(tx, credential.integration_id) : undefined
|
||||
yield* tx.delete(CredentialTable).where(eq(CredentialTable.id, id)).run()
|
||||
if (!credential.integration_id || active?.id !== id)
|
||||
return { switched: false as const, integrationID: credential.integration_id }
|
||||
@@ -305,18 +267,7 @@ const layer = Layer.effect(
|
||||
.where(eq(CredentialTable.integration_id, credential.integration_id))
|
||||
.orderBy(desc(CredentialTable.time_created), desc(CredentialTable.id))
|
||||
.get()
|
||||
if (replacement) {
|
||||
yield* tx
|
||||
.update(CredentialTable)
|
||||
.set({ active: false })
|
||||
.where(eq(CredentialTable.integration_id, credential.integration_id))
|
||||
.run()
|
||||
yield* tx
|
||||
.update(CredentialTable)
|
||||
.set({ active: true })
|
||||
.where(eq(CredentialTable.id, replacement.id))
|
||||
.run()
|
||||
}
|
||||
if (replacement) yield* switchActive(tx, credential.integration_id, replacement.id)
|
||||
return {
|
||||
switched: true as const,
|
||||
integrationID: credential.integration_id,
|
||||
@@ -324,15 +275,7 @@ const layer = Layer.effect(
|
||||
}
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.onError((cause) =>
|
||||
Effect.logError("credential remove failed", {
|
||||
credentialID: id,
|
||||
errors: ErrorSummary.from(Cause.squash(cause)),
|
||||
}),
|
||||
),
|
||||
Effect.orDie,
|
||||
)
|
||||
.pipe(logFailure("credential remove failed", { credentialID: id }))
|
||||
if (!removed) return
|
||||
yield* Effect.logInfo("credential removed", {
|
||||
credentialID: id,
|
||||
|
||||
@@ -3,7 +3,7 @@ import { makeLocationNode } from "@opencode/util/effect/app-node"
|
||||
import { Context, Effect, Layer } from "effect"
|
||||
import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner"
|
||||
import type { Files } from "./files.js"
|
||||
import { makeFiles } from "./index.js"
|
||||
import { makeFiles } from "./exec-defaults.js"
|
||||
import { makeLocalDriver } from "./local.js"
|
||||
import { Location } from "../location.js"
|
||||
import { Workspace } from "../workspace.js"
|
||||
|
||||
@@ -2,7 +2,8 @@ import { Effect, Stream } from "effect"
|
||||
import { ChildProcess } from "effect/process"
|
||||
import type { ChildProcessSpawner } from "effect/process/ChildProcessSpawner"
|
||||
import { collectStream } from "@opencode/util/process"
|
||||
import { Failed, NotFound, WrongKind, type FileInfo, type FileType, type FilesImpl } from "./files.js"
|
||||
import type { Driver } from "./driver.js"
|
||||
import { Failed, NotFound, WrongKind, type FileInfo, type Files, type FileType, type FilesImpl } from "./files.js"
|
||||
|
||||
/**
|
||||
* Files derived from spawning processes: one process per intent, "$1" is
|
||||
@@ -189,4 +190,9 @@ const parseList = (bytes: Uint8Array) => {
|
||||
}))
|
||||
}
|
||||
|
||||
export const makeFiles = (driver: Driver): Files => ({
|
||||
...execDefaults(driver.spawner),
|
||||
...driver.overrides,
|
||||
})
|
||||
|
||||
export * as EnvironmentExecDefaults from "./exec-defaults.js"
|
||||
|
||||
@@ -13,16 +13,7 @@ export {
|
||||
typeFollowing,
|
||||
WrongKind,
|
||||
} from "./files.js"
|
||||
export { execDefaults } from "./exec-defaults.js"
|
||||
export { execDefaults, makeFiles } from "./exec-defaults.js"
|
||||
export { makeLocalDriver } from "./local.js"
|
||||
export { makeMemoryDriver, type MemoryDriver } from "./memory.js"
|
||||
export { type Interface, node, Service } from "./environment.js"
|
||||
|
||||
import type { Driver } from "./driver.js"
|
||||
import { execDefaults } from "./exec-defaults.js"
|
||||
import type { Files } from "./files.js"
|
||||
|
||||
export const makeFiles = (driver: Driver): Files => ({
|
||||
...execDefaults(driver.spawner),
|
||||
...driver.overrides,
|
||||
})
|
||||
|
||||
@@ -19,20 +19,6 @@ const DARWIN_HOME = [
|
||||
"Library",
|
||||
]
|
||||
|
||||
const DARWIN_LIBRARY = [
|
||||
"Application Support/AddressBook",
|
||||
"Calendars",
|
||||
"Mail",
|
||||
"Messages",
|
||||
"Safari",
|
||||
"Cookies",
|
||||
"Application Support/com.apple.TCC",
|
||||
"PersonalizationPortrait",
|
||||
"Metadata/CoreSpotlight",
|
||||
"Suggestions",
|
||||
]
|
||||
|
||||
const DARWIN_ROOT = ["/.DocumentRevisions-V100", "/.Spotlight-V100", "/.Trashes", "/.fseventsd"]
|
||||
const WIN32_HOME = ["AppData", "Downloads", "Desktop", "Documents", "Pictures", "Music", "Videos", "OneDrive"]
|
||||
|
||||
/** Directory basenames to skip when scanning the home directory. */
|
||||
@@ -42,16 +28,4 @@ export function names(): ReadonlySet<string> {
|
||||
return new Set()
|
||||
}
|
||||
|
||||
/** Absolute paths that should never be watched, stated, or scanned. */
|
||||
export function paths(): string[] {
|
||||
if (process.platform === "darwin")
|
||||
return [
|
||||
...DARWIN_HOME.map((name) => path.join(home, name)),
|
||||
...DARWIN_LIBRARY.map((name) => path.join(home, "Library", name)),
|
||||
...DARWIN_ROOT,
|
||||
]
|
||||
if (process.platform === "win32") return WIN32_HOME.map((name) => path.join(home, name))
|
||||
return []
|
||||
}
|
||||
|
||||
export * as Protected from "./protected.js"
|
||||
|
||||
@@ -537,43 +537,48 @@ function hasConfiguredAuth(model: RuntimeInfo) {
|
||||
)
|
||||
}
|
||||
|
||||
const API_KEY_AUTH_PACKAGES: ReadonlySet<string> = new Set([
|
||||
"@ai-sdk/openai",
|
||||
"@ai-sdk/anthropic",
|
||||
"@ai-sdk/cerebras",
|
||||
"@ai-sdk/deepinfra",
|
||||
"@ai-sdk/openai-compatible",
|
||||
"@ai-sdk/google",
|
||||
"@ai-sdk/groq",
|
||||
"@ai-sdk/mistral",
|
||||
"@ai-sdk/togetherai",
|
||||
"@ai-sdk/xai",
|
||||
"@openrouter/ai-sdk-provider",
|
||||
"@ai-sdk/azure",
|
||||
"@opencode/ai/providers/openai",
|
||||
"@opencode/ai/providers/anthropic",
|
||||
"@opencode/ai/providers/anthropic-compatible",
|
||||
"@opencode/ai/providers/baseten",
|
||||
"@opencode/ai/providers/cerebras",
|
||||
"@opencode/ai/providers/cloudflare-ai-gateway",
|
||||
"@opencode/ai/providers/cloudflare-workers-ai",
|
||||
"@opencode/ai/providers/deepinfra",
|
||||
"@opencode/ai/providers/deepseek",
|
||||
"@opencode/ai/providers/fireworks",
|
||||
"@opencode/ai/providers/openai-compatible",
|
||||
"@opencode/ai/providers/google",
|
||||
"@opencode/ai/providers/google/interactions",
|
||||
"@opencode/ai/providers/groq",
|
||||
"@opencode/ai/providers/mistral",
|
||||
"@opencode/ai/providers/togetherai",
|
||||
"@opencode/ai/providers/vercel-ai-gateway",
|
||||
"@opencode/ai/providers/xai",
|
||||
"@opencode/ai/providers/openrouter",
|
||||
"@opencode/ai/providers/azure",
|
||||
])
|
||||
|
||||
function usesAPIKeyAuth(packageName: string | undefined) {
|
||||
const name = Provider.packageName(packageName)
|
||||
if (name === undefined) return false
|
||||
return (
|
||||
name === "@ai-sdk/openai" ||
|
||||
name === "@ai-sdk/anthropic" ||
|
||||
name === "@ai-sdk/cerebras" ||
|
||||
name === "@ai-sdk/deepinfra" ||
|
||||
name === "@ai-sdk/openai-compatible" ||
|
||||
name === "@ai-sdk/google" ||
|
||||
name === "@ai-sdk/groq" ||
|
||||
name === "@ai-sdk/mistral" ||
|
||||
name === "@ai-sdk/togetherai" ||
|
||||
name === "@ai-sdk/xai" ||
|
||||
name === "@openrouter/ai-sdk-provider" ||
|
||||
name === "@ai-sdk/azure" ||
|
||||
name === "@opencode/ai/providers/openai" ||
|
||||
name?.startsWith("@opencode/ai/providers/openai/") === true ||
|
||||
name === "@opencode/ai/providers/anthropic" ||
|
||||
name === "@opencode/ai/providers/anthropic-compatible" ||
|
||||
name === "@opencode/ai/providers/baseten" ||
|
||||
name === "@opencode/ai/providers/cerebras" ||
|
||||
name === "@opencode/ai/providers/cloudflare-ai-gateway" ||
|
||||
name === "@opencode/ai/providers/cloudflare-workers-ai" ||
|
||||
name === "@opencode/ai/providers/deepinfra" ||
|
||||
name === "@opencode/ai/providers/deepseek" ||
|
||||
name === "@opencode/ai/providers/fireworks" ||
|
||||
name === "@opencode/ai/providers/openai-compatible" ||
|
||||
name === "@opencode/ai/providers/google" ||
|
||||
name === "@opencode/ai/providers/google/interactions" ||
|
||||
name === "@opencode/ai/providers/groq" ||
|
||||
name === "@opencode/ai/providers/mistral" ||
|
||||
name === "@opencode/ai/providers/togetherai" ||
|
||||
name === "@opencode/ai/providers/vercel-ai-gateway" ||
|
||||
name === "@opencode/ai/providers/xai" ||
|
||||
name === "@opencode/ai/providers/openrouter" ||
|
||||
name === "@opencode/ai/providers/azure" ||
|
||||
name?.startsWith("@opencode/ai/providers/azure/") === true
|
||||
API_KEY_AUTH_PACKAGES.has(name) ||
|
||||
name.startsWith("@opencode/ai/providers/openai/") ||
|
||||
name.startsWith("@opencode/ai/providers/azure/")
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -93,17 +93,17 @@ export interface Interface {
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/RepositoryCache") {}
|
||||
|
||||
export function isError(error: unknown): error is Error {
|
||||
return (
|
||||
error instanceof InvalidBranchError ||
|
||||
error instanceof CloneFailedError ||
|
||||
error instanceof FetchFailedError ||
|
||||
error instanceof CheckoutFailedError ||
|
||||
error instanceof ResetFailedError ||
|
||||
error instanceof LockFailedError ||
|
||||
error instanceof CacheOperationError
|
||||
)
|
||||
}
|
||||
export const isError: (error: unknown) => error is Error = Schema.is(
|
||||
Schema.Union([
|
||||
InvalidBranchError,
|
||||
CloneFailedError,
|
||||
FetchFailedError,
|
||||
CheckoutFailedError,
|
||||
ResetFailedError,
|
||||
LockFailedError,
|
||||
CacheOperationError,
|
||||
]),
|
||||
)
|
||||
|
||||
export const validateBranch = Effect.fn("RepositoryCache.validateBranch")(function* (branch: string) {
|
||||
return yield* Effect.try({
|
||||
|
||||
@@ -136,9 +136,10 @@ const layer = Layer.effect(
|
||||
return { origin, integrationID: Integration.ID.make(origin), manifest }
|
||||
})
|
||||
|
||||
const readOrigins = kv.get(sourcesKey).pipe(Effect.map((value) => (Schema.is(Sources)(value) ? value : [])))
|
||||
|
||||
const load = Effect.fn("WellKnown.load")(function* () {
|
||||
const value = yield* kv.get(sourcesKey)
|
||||
const origins = Schema.is(Sources)(value) ? value : []
|
||||
const origins = yield* readOrigins
|
||||
const current = yield* Ref.get(cache)
|
||||
const entries = yield* Effect.forEach(origins, (origin) => {
|
||||
const cached = current.get(origin)
|
||||
@@ -151,8 +152,7 @@ const layer = Layer.effect(
|
||||
|
||||
const refresh = Effect.fn("WellKnown.refresh")(
|
||||
function* () {
|
||||
const value = yield* kv.get(sourcesKey)
|
||||
const origins = Schema.is(Sources)(value) ? value : []
|
||||
const origins = yield* readOrigins
|
||||
if (!origins.length) return false
|
||||
const entries = yield* Effect.forEach(origins, loadEntry)
|
||||
const next = new Map(entries.map((entry) => [entry.origin, entry]))
|
||||
@@ -174,8 +174,7 @@ const layer = Layer.effect(
|
||||
const origin = value.replace(/\/+$/, "")
|
||||
const entry = yield* loadEntry(origin)
|
||||
if (!entry.manifest.auth) return yield* Effect.fail(new Error(`No authentication method found at ${origin}`))
|
||||
const sources = yield* kv.get(sourcesKey)
|
||||
const origins = Schema.is(Sources)(sources) ? sources : []
|
||||
const origins = yield* readOrigins
|
||||
yield* kv.set(sourcesKey, Array.from(new Set([...origins, origin])))
|
||||
yield* Ref.update(cache, (current) => new Map(current).set(origin, entry))
|
||||
yield* bus.publish(Event.Updated, {}, { global: true })
|
||||
@@ -186,8 +185,7 @@ const layer = Layer.effect(
|
||||
remove: Effect.fn("WellKnown.remove")(
|
||||
function* (value) {
|
||||
const origin = value.replace(/\/+$/, "")
|
||||
const sources = yield* kv.get(sourcesKey)
|
||||
const origins = Schema.is(Sources)(sources) ? sources : []
|
||||
const origins = yield* readOrigins
|
||||
yield* kv.set(
|
||||
sourcesKey,
|
||||
origins.filter((item) => item !== origin),
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Clock, Context, Deferred, Duration, Effect, Exit, FiberSet, Layer, Ref,
|
||||
import { systemError } from "effect/PlatformError"
|
||||
import { make } from "effect/process/ChildProcessSpawner"
|
||||
import type { EnvironmentDriver } from "./environment/driver.js"
|
||||
import { execDefaults } from "./environment/exec-defaults.js"
|
||||
import { makeFiles } from "./environment/exec-defaults.js"
|
||||
import { Failed, type Files, type FilesImpl } from "./environment/files.js"
|
||||
import { Database } from "./database/database.js"
|
||||
import { KeyedMutex } from "./effect/keyed-mutex.js"
|
||||
@@ -169,10 +169,7 @@ const layer = (options: Options) =>
|
||||
const connection: Connection = {
|
||||
driver,
|
||||
environment,
|
||||
files: {
|
||||
...execDefaults(environment.spawner),
|
||||
...environment.overrides,
|
||||
},
|
||||
files: makeFiles(environment),
|
||||
saveBinding: persistBinding,
|
||||
lastActivity: yield* Ref.make(now),
|
||||
active: yield* Ref.make(0),
|
||||
|
||||
Reference in New Issue
Block a user