Compare commits

..

1 Commits

Author SHA1 Message Date
Aiden Cline dd3a279458 fix(core): merge authenticated provider allowlists 2026-08-08 02:36:26 +00:00
16 changed files with 303 additions and 478 deletions
+2 -14
View File
@@ -1,4 +1,4 @@
import { Cause, Context, Effect, Layer, Option, Schema } from "effect"
import { Cause, Context, Effect, Layer } from "effect"
import {
FetchHttpClient,
Headers,
@@ -198,20 +198,8 @@ const responseBody = (body: string | void, request: HttpClientRequest.HttpClient
return { body: redacted.slice(0, BODY_LIMIT), bodyTruncated: true }
}
const decodeProviderBody = Schema.decodeUnknownOption(
Schema.fromJsonString(
Schema.Struct({
message: Schema.optionalKey(Schema.String),
error: Schema.optionalKey(Schema.Struct({ message: Schema.optionalKey(Schema.String) })),
}),
),
)
const providerMessage = (status: number, body: { readonly body?: string }) => {
if (body.body && body.body.length <= 500) {
const decoded = Option.getOrUndefined(decodeProviderBody(body.body))
return `Provider request failed with HTTP ${status}: ${decoded?.error?.message ?? decoded?.message ?? body.body}`
}
if (body.body && body.body.length <= 500) return `Provider request failed with HTTP ${status}: ${body.body}`
return `Provider request failed with HTTP ${status}`
}
+101
View File
@@ -0,0 +1,101 @@
export * as Account from "./account"
import { Schema } from "effect"
import type { HttpClientError } from "effect/unstable/http"
export const ID = Schema.String.pipe(Schema.brand("AccountID"))
export type ID = Schema.Schema.Type<typeof ID>
export const OrgID = Schema.String.pipe(Schema.brand("OrgID"))
export type OrgID = Schema.Schema.Type<typeof OrgID>
export const AccessToken = Schema.String.pipe(Schema.brand("AccessToken"))
export type AccessToken = Schema.Schema.Type<typeof AccessToken>
export const RefreshToken = Schema.String.pipe(Schema.brand("RefreshToken"))
export type RefreshToken = Schema.Schema.Type<typeof RefreshToken>
export const DeviceCode = Schema.String.pipe(Schema.brand("DeviceCode"))
export type DeviceCode = Schema.Schema.Type<typeof DeviceCode>
export const UserCode = Schema.String.pipe(Schema.brand("UserCode"))
export type UserCode = Schema.Schema.Type<typeof UserCode>
export class Info extends Schema.Class<Info>("Account")({
id: ID,
email: Schema.String,
url: Schema.String,
active_org_id: Schema.NullOr(OrgID),
}) {}
export class Org extends Schema.Class<Org>("Org")({
id: OrgID,
name: Schema.String,
}) {}
export class AccountRepoError extends Schema.TaggedErrorClass<AccountRepoError>()("AccountRepoError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {}
export class AccountServiceError extends Schema.TaggedErrorClass<AccountServiceError>()("AccountServiceError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {}
export class AccountTransportError extends Schema.TaggedErrorClass<AccountTransportError>()("AccountTransportError", {
method: Schema.String,
url: Schema.String,
description: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
}) {
static fromHttpClientError(error: HttpClientError.TransportError): AccountTransportError {
return new AccountTransportError({
method: error.request.method,
url: error.request.url,
description: error.description,
cause: error.cause,
})
}
override get message(): string {
return [
`Could not reach ${this.method} ${this.url}.`,
`This failed before the server returned an HTTP response.`,
this.description,
`Check your network, proxy, or VPN configuration and try again.`,
]
.filter(Boolean)
.join("\n")
}
}
export type AccountError = AccountRepoError | AccountServiceError | AccountTransportError
export class Login extends Schema.Class<Login>("Login")({
code: DeviceCode,
user: UserCode,
url: Schema.String,
server: Schema.String,
expiry: Schema.Duration,
interval: Schema.Duration,
}) {}
export class PollSuccess extends Schema.TaggedClass<PollSuccess>()("PollSuccess", {
email: Schema.String,
}) {}
export class PollPending extends Schema.TaggedClass<PollPending>()("PollPending", {}) {}
export class PollSlow extends Schema.TaggedClass<PollSlow>()("PollSlow", {}) {}
export class PollExpired extends Schema.TaggedClass<PollExpired>()("PollExpired", {}) {}
export class PollDenied extends Schema.TaggedClass<PollDenied>()("PollDenied", {}) {}
export class PollError extends Schema.TaggedClass<PollError>()("PollError", {
cause: Schema.Defect(),
}) {}
export const PollResult = Schema.Union([PollSuccess, PollPending, PollSlow, PollExpired, PollDenied, PollError])
export type PollResult = Schema.Schema.Type<typeof PollResult>
+10 -7
View File
@@ -1,21 +1,24 @@
import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core"
import { Account } from "../account"
import { Timestamps } from "../database/schema.sql"
export const AccountTable = sqliteTable("account", {
id: text().primaryKey(),
id: text().$type<Account.ID>().primaryKey(),
email: text().notNull(),
url: text().notNull(),
access_token: text().notNull(),
refresh_token: text().notNull(),
access_token: text().$type<Account.AccessToken>().notNull(),
refresh_token: text().$type<Account.RefreshToken>().notNull(),
token_expiry: integer(),
...Timestamps,
})
export const AccountStateTable = sqliteTable("account_state", {
id: integer().primaryKey(),
active_account_id: text().references(() => AccountTable.id, { onDelete: "set null" }),
active_org_id: text(),
active_account_id: text()
.$type<Account.ID>()
.references(() => AccountTable.id, { onDelete: "set null" }),
active_org_id: text().$type<Account.OrgID>(),
})
// LEGACY
@@ -24,8 +27,8 @@ export const ControlAccountTable = sqliteTable(
{
email: text().notNull(),
url: text().notNull(),
access_token: text().notNull(),
refresh_token: text().notNull(),
access_token: text().$type<Account.AccessToken>().notNull(),
refresh_token: text().$type<Account.RefreshToken>().notNull(),
token_expiry: integer(),
active: integer({ mode: "boolean" })
.notNull()
+29 -13
View File
@@ -141,7 +141,7 @@ export const layer = (options?: Options) => Layer.effect(
Effect.logWarning("failed to discover wellknown config", { error }).pipe(Effect.as([] as const)),
),
)
return yield* Effect.forEach(entries, (entry) =>
const resolved = yield* Effect.forEach(entries, (entry) =>
Effect.gen(function* () {
const auth = entry.manifest.auth
if (!auth) return []
@@ -151,20 +151,29 @@ export const layer = (options?: Options) => Layer.effect(
if (!credential || credential.value.type !== "key") return []
const variables = { [auth.env]: credential.value.key }
const configs = yield* wellknown.resolve(entry, variables).pipe(Effect.orDie)
return yield* Effect.forEach(configs, (config) =>
ConfigVariable.substitute({
type: "virtual",
source: entry.origin,
dir: entry.origin,
text: JSON.stringify(config),
env: variables,
}).pipe(
Effect.flatMap((text) => parseInfo(text, entry.origin)),
Effect.map((info) => (info ? new Document({ type: "document", info }) : undefined)),
),
).pipe(Effect.map((documents) => documents.filter((document) => document !== undefined)))
return configs.map((config) => ({ config, source: entry.origin, variables }))
}),
).pipe(Effect.map((documents) => documents.flat()))
// V1 merged authenticated configs before applying this allowlist. Give every
// migrated document the union so one source's wildcard deny cannot hide another.
const enabledProviders = Array.from(
new Set(resolved.flatMap((item) => legacyEnabledProviders(item.config) ?? [])),
)
return yield* Effect.forEach(resolved, (item) => {
const config = legacyEnabledProviders(item.config)
? { ...item.config, enabled_providers: enabledProviders }
: item.config
return ConfigVariable.substitute({
type: "virtual",
source: item.source,
dir: item.source,
text: JSON.stringify(config),
env: item.variables,
}).pipe(
Effect.flatMap((text) => parseInfo(text, item.source)),
Effect.map((info) => (info ? new Document({ type: "document", info }) : undefined)),
)
}).pipe(Effect.map((documents) => documents.filter((document) => document !== undefined)))
})
const loadDirectory = Effect.fnUntraced(function* (directory: AbsolutePath) {
@@ -360,6 +369,13 @@ export const layer = (options?: Options) => Layer.effect(
}),
)
function legacyEnabledProviders(config: WellKnown.Config) {
if (typeof config !== "object" || config === null) return
if (!Array.isArray(config.enabled_providers)) return
if (!config.enabled_providers.every((provider): provider is string => typeof provider === "string")) return
return config.enabled_providers
}
export function configured(options?: Options) {
return makeLocationNode({
service: Service,
+2
View File
@@ -1,5 +1,6 @@
export * as PluginHooks from "./hooks"
import type { AISDKHooks } from "@opencode-ai/plugin/effect/aisdk"
import type { SessionHooks } from "@opencode-ai/plugin/effect/session"
import type { ShellHooks } from "@opencode-ai/plugin/effect/shell"
import type { ToolHooks } from "@opencode-ai/plugin/effect/tool"
@@ -8,6 +9,7 @@ import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { State } from "../state"
export interface Domains {
readonly aisdk: AISDKHooks
readonly session: SessionHooks
readonly shell: ShellHooks
readonly tool: ToolHooks
+15 -9
View File
@@ -3,6 +3,7 @@ export * as PatchTool from "./patch"
import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin"
import { ToolFailure } from "@opencode-ai/ai"
import { FileDiff } from "@opencode-ai/schema/file-diff"
import { createTwoFilesPatch, diffLines } from "diff"
import { Effect, Result, Schema } from "effect"
import path from "path"
import { Bom } from "@opencode-ai/util/bom"
@@ -14,7 +15,6 @@ import { Location } from "../../location"
import { Patch } from "@opencode-ai/util/patch"
import { Permission } from "../../permission"
import DESCRIPTION from "../patch.txt"
import { fileDiff } from "./file-diff"
export const name = "patch"
@@ -353,16 +353,22 @@ function errorMessage(error: unknown) {
function patchFile(change: Prepared, after = change.after): typeof FileDiff.Info.Type {
const target = (change.type === "update" ? change.moveTarget : undefined)?.resource ?? change.target.resource
const diff = fileDiff(
change.target.absolute,
change.before,
after,
change.type === "add" ? "added" : change.type === "delete" ? "deleted" : "modified",
)
const patch = trimDiff(createTwoFilesPatch(change.target.absolute, change.target.absolute, change.before, after))
const counts =
change.type === "delete"
? { additions: 0, deletions: change.before.split("\n").length }
: diffLines(change.before, after).reduce(
(result, item) => ({
additions: result.additions + (item.added ? (item.count ?? 0) : 0),
deletions: result.deletions + (item.removed ? (item.count ?? 0) : 0),
}),
{ additions: 0, deletions: 0 },
)
return {
...diff,
file: target,
patch: trimDiff(diff.patch),
patch,
status: change.type === "add" ? "added" : change.type === "delete" ? "deleted" : "modified",
...counts,
}
}
+41 -9
View File
@@ -307,7 +307,7 @@ describe("Config", () => {
}),
)
it.live("loads authenticated wellknown config before user configuration", () =>
it.live("loads and merges authenticated wellknown config before user configuration", () =>
Effect.acquireUseRelease(
Effect.promise(() => tmpdir()),
(tmp) =>
@@ -322,6 +322,7 @@ describe("Config", () => {
})
const integrationID = Integration.ID.make("https://example.com")
const supplementalID = Integration.ID.make("https://models.example.com")
let key = "secret"
const credentialNode = makeGlobalNode({
service: Credential.Service,
@@ -329,13 +330,16 @@ describe("Config", () => {
Credential.Service,
Credential.Service.of({
all: () => Effect.die("unused Credential.all"),
list: () =>
list: (requested) =>
Effect.succeed([
new Credential.Info({
id: Credential.ID.create(),
integrationID,
integrationID: requested,
label: "default",
value: Credential.Key.make({ type: "key", key }),
value: Credential.Key.make({
type: "key",
key: requested === integrationID ? key : "supplemental",
}),
}),
]),
get: () => Effect.die("unused Credential.get"),
@@ -351,17 +355,28 @@ describe("Config", () => {
integrationID,
manifest: { auth: { command: ["login"], env: "TOKEN" } },
}
const supplemental: WellKnown.Entry = {
origin: "https://models.example.com",
integrationID: supplementalID,
manifest: { auth: { command: ["login"], env: "TOKEN" } },
}
const wellknownNode = makeGlobalNode({
service: WellKnown.Service,
layer: Layer.succeed(
WellKnown.Service,
WellKnown.Service.of({
entries: () => Effect.succeed([entry]),
snapshot: () => [entry],
entries: () => Effect.succeed([entry, supplemental]),
snapshot: () => [entry, supplemental],
refresh: () => Effect.succeed(false),
add: () => Effect.die("unused Wellknown.add"),
remove: () => Effect.die("unused Wellknown.remove"),
resolve: (_entry, variables) => Effect.succeed([{ shell: variables.TOKEN }]),
resolve: (resolved, variables) =>
Effect.succeed([
{
shell: variables.TOKEN,
enabled_providers: [resolved.integrationID === integrationID ? "primary" : "fable"],
},
]),
}),
),
deps: [],
@@ -376,7 +391,24 @@ describe("Config", () => {
initial.flatMap((entry) =>
entry.type === "document" && entry.info.shell ? [entry.info.shell] : [],
),
).toEqual(["secret", "global", "project"])
).toEqual(["secret", "supplemental", "global", "project"])
expect(
initial
.filter((entry): entry is Document => entry.type === "document" && entry.info.shell !== undefined)
.slice(0, 2)
.map((entry) => entry.info.experimental?.policies),
).toEqual([
[
{ action: "provider.use", resource: "*", effect: "deny" },
{ action: "provider.use", resource: "primary", effect: "allow" },
{ action: "provider.use", resource: "fable", effect: "allow" },
],
[
{ action: "provider.use", resource: "*", effect: "deny" },
{ action: "provider.use", resource: "primary", effect: "allow" },
{ action: "provider.use", resource: "fable", effect: "allow" },
],
])
const updated = yield* bus
.subscribe(Event.Updated)
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
@@ -390,7 +422,7 @@ describe("Config", () => {
refreshed.flatMap((entry) =>
entry.type === "document" && entry.info.shell ? [entry.info.shell] : [],
),
).toEqual(["next", "global", "project"])
).toEqual(["next", "supplemental", "global", "project"])
}).pipe(
Effect.provide(testLayer(project, global, project, undefined, undefined, credentialNode, wellknownNode)),
)
+2 -25
View File
@@ -215,7 +215,7 @@ describe("PatchTool", () => {
file: "remove.txt",
status: "deleted",
additions: 0,
deletions: 1,
deletions: 2,
patch: expect.stringContaining("-remove"),
},
],
@@ -248,29 +248,6 @@ describe("PatchTool", () => {
),
)
it.live("counts deleted lines with and without a trailing newline", () =>
withTempTool((directory, registry) =>
Effect.gen(function* () {
yield* Effect.promise(() =>
Promise.all([
fs.writeFile(path.join(directory, "trailing.txt"), "remove\n"),
fs.writeFile(path.join(directory, "unterminated.txt"), "remove"),
]),
)
const settled = yield* executeTool(
registry,
call("*** Begin Patch\n*** Delete File: trailing.txt\n*** Delete File: unterminated.txt\n*** End Patch"),
)
expect(settled.status).toBe("completed")
if (settled.status !== "completed") return
expect(settled.output.files).toMatchObject([
{ file: "trailing.txt", additions: 0, deletions: 1 },
{ file: "unterminated.txt", additions: 0, deletions: 1 },
])
}),
),
)
it.live("serializes concurrent patch transactions", () =>
withTempTool((directory, registry) => {
const target = path.join(directory, "concurrent.txt")
@@ -469,7 +446,7 @@ describe("PatchTool", () => {
{
file: "renamed/dir/name.txt",
status: "modified",
patch: expect.stringContaining(`Index: ${source}`),
patch: expect.stringContaining("-old content\n+new content"),
},
],
})
+14 -139
View File
@@ -198,13 +198,13 @@ describe("FlowchartDiagram", () => {
B --> A`)
expectDiagram(output).toEqualDiagram(`
╭───────────╮
│ │
│ │
▼ │
╭───╮ ╭─┴─╮
│ A ├──────▶│ B │
╰───╯ ╰───╯
╭──────────────
╭───╮ ╭─┴─╮
│ A ├─────────▶│ B │
╰───╯ ╰───╯
`)
})
@@ -599,7 +599,7 @@ flowchart LR
const output = renderFlowchartDiagram(content)
expect(diagram.edges).toEqual([{ from: "Build", to: "Ship", label: "", style: "thick" }])
expect(output).toContain("━━━━━━▶")
expect(output).toContain("━━━━━━━━━▶")
})
test("parses and renders Mermaid dashed edges", () => {
@@ -611,7 +611,7 @@ flowchart LR
const output = renderFlowchartDiagram(content)
expect(diagram.edges).toEqual([{ from: "Build", to: "Ship", label: "", style: "dashed" }])
expect(output).toContain("──────▶")
expect(output).toContain("─────────▶")
})
test("paints horizontal and vertical dashed routes with solid terminal cells", () => {
@@ -689,11 +689,11 @@ graph LR
`)
expectDiagram(output).toEqualDiagram(`
╭───────╮
╭────────╮ ╭─────╮ ├───────┤
│ Client ├──────▶│ API ├──────▶│ Cache │
╰────────╯ ╰─────╯ ├───────┤
╰───────╯
╭───────╮
╭────────╮ ╭─────╮ ├───────┤
│ Client ├─────────▶│ API ├─────────▶│ Cache │
╰────────╯ ╰─────╯ ├───────┤
╰───────╯
`)
})
@@ -1062,131 +1062,6 @@ flowchart LR
}
})
test.each(["TD", "BT", "LR", "RL"] as const)(
"keeps parallel top-level subgraphs in the same rank for %s diagrams",
(direction) => {
const layout = layoutFlowchartDiagram(`flowchart ${direction}
subgraph source [Source]
A[A]
end
subgraph left [Left]
B[B]
end
subgraph right [Right]
C[C]
end
A --> B
A --> C`)
const source = layout.subgraphBounds.get("source")!
const left = layout.subgraphBounds.get("left")!
const right = layout.subgraphBounds.get("right")!
const leftNode = layout.bounds.get("B")!
const rightNode = layout.bounds.get("C")!
const horizontal = direction === "LR" || direction === "RL"
const reversed = direction === "BT" || direction === "RL"
const start = (bound: typeof source) => {
const value = horizontal ? bound.left : bound.top
const size = horizontal ? bound.width : bound.height
return reversed ? -(value + size) : value
}
const size = (bound: typeof source) => (horizontal ? bound.width : bound.height)
expect(horizontal ? leftNode.centerX : leftNode.centerY).toBe(horizontal ? rightNode.centerX : rightNode.centerY)
expect(Math.min(start(left), start(right))).toBeGreaterThanOrEqual(start(source) + size(source))
},
)
test.each(["TD", "BT", "LR", "RL"] as const)(
"separates oversized parallel subgraph labels across %s diagrams",
(direction) => {
const horizontal = direction === "LR" || direction === "RL"
const label = horizontal ? "one<br/>two<br/>three<br/>four<br/>five" : "A very very wide downstream subgraph title"
const layout = layoutFlowchartDiagram(`flowchart ${direction}
subgraph source [Source]
A[A]
end
subgraph left [${label}]
B[B]
end
subgraph right [Right]
C[C]
end
A --> B
A --> C`)
const left = layout.subgraphBounds.get("left")!
const right = layout.subgraphBounds.get("right")!
const overlap =
left.left < right.left + right.width &&
left.left + left.width > right.left &&
left.top < right.top + right.height &&
left.top + left.height > right.top
expect(overlap).toBe(false)
},
)
test.each(["TD", "BT", "LR", "RL"] as const)(
"ranks nested order-only subgraph dependencies for %s diagrams",
(direction) => {
const layout = layoutFlowchartDiagram(`flowchart ${direction}
subgraph first [First]
subgraph firstInner [First inner]
A[A]
end
end
subgraph second [Second]
subgraph secondInner [Second inner]
B[B]
end
end
firstInner ~~~ secondInner`)
const first = layout.subgraphBounds.get("first")!
const second = layout.subgraphBounds.get("second")!
const horizontal = direction === "LR" || direction === "RL"
const reversed = direction === "BT" || direction === "RL"
const start = (bound: typeof first) => {
const value = horizontal ? bound.left : bound.top
const size = horizontal ? bound.width : bound.height
return reversed ? -(value + size) : value
}
const size = horizontal ? first.width : first.height
expect(start(second)).toBeGreaterThanOrEqual(start(first) + size)
},
)
test.each(["TD", "BT", "LR", "RL"] as const)(
"ranks cyclic top-level subgraphs as one downstream component for %s diagrams",
(direction) => {
const layout = layoutFlowchartDiagram(`flowchart ${direction}
subgraph source [Source]
A[A]
end
subgraph first [First]
B[B]
end
subgraph second [Second]
C[C]
end
A --> B
B --> C
C --> B`)
const source = layout.subgraphBounds.get("source")!
const first = layout.subgraphBounds.get("first")!
const second = layout.subgraphBounds.get("second")!
const horizontal = direction === "LR" || direction === "RL"
const reversed = direction === "BT" || direction === "RL"
const start = (bound: typeof source) => {
const value = horizontal ? bound.left : bound.top
const size = horizontal ? bound.width : bound.height
return reversed ? -(value + size) : value
}
const size = (bound: typeof source) => (horizontal ? bound.width : bound.height)
expect(Math.min(start(first), start(second))).toBeGreaterThanOrEqual(start(source) + size(source))
},
)
test("moves subgraph labels away from crossing routes", () => {
const output = renderFlowchartDiagram(`
flowchart TD
+45 -142
View File
@@ -27,7 +27,7 @@ import type {
export const DEFAULT_MIN_NODE_GAP = 5
export const DEFAULT_MIN_BRANCH_LABEL_GAP = 12
export const DEFAULT_MIN_RANK_GAP = 7
export const DEFAULT_MIN_RANK_GAP = 10
export const DEFAULT_MIN_VERTICAL_RANK_GAP = 4
export const COMPACT_MIN_RANK_GAP = 4
export const COMPACT_MIN_VERTICAL_RANK_GAP = 2
@@ -511,79 +511,19 @@ function collectSubgraphNodeIds(diagram: FlowchartDiagram, subgraphId: string):
return nodeIds
}
function rankGraphComponents(ids: readonly string[], outgoing: ReadonlyMap<string, ReadonlySet<string>>): Map<string, number> {
const reachable = new Map<string, Set<string>>()
for (const id of ids) {
const seen = new Set<string>()
const queue = [id]
for (let index = 0; index < queue.length; index++) {
const current = queue[index]!
if (seen.has(current)) continue
seen.add(current)
queue.push(...(outgoing.get(current) ?? []))
}
reachable.set(id, seen)
}
const componentById = new Map<string, number>()
const components: string[][] = []
for (const id of ids) {
if (componentById.has(id)) continue
const component = ids.filter(
(candidate) => !componentById.has(candidate) && reachable.get(id)!.has(candidate) && reachable.get(candidate)!.has(id),
)
const componentIndex = components.length
components.push(component)
for (const member of component) componentById.set(member, componentIndex)
}
const componentOutgoing = new Map(components.map((_, index) => [index, new Set<number>()]))
const incoming = new Map(components.map((_, index) => [index, 0]))
for (const [from, targets] of outgoing) {
const fromComponent = componentById.get(from)!
for (const to of targets) {
const toComponent = componentById.get(to)!
if (fromComponent === toComponent || componentOutgoing.get(fromComponent)!.has(toComponent)) continue
componentOutgoing.get(fromComponent)!.add(toComponent)
incoming.set(toComponent, incoming.get(toComponent)! + 1)
}
}
const componentRanks = new Map<number, number>()
const queue = components.map((_, index) => index).filter((index) => incoming.get(index) === 0)
for (const component of queue) componentRanks.set(component, 0)
for (let index = 0; index < queue.length; index++) {
const component = queue[index]!
for (const to of componentOutgoing.get(component)!) {
componentRanks.set(to, Math.max(componentRanks.get(to) ?? 0, componentRanks.get(component)! + 1))
incoming.set(to, incoming.get(to)! - 1)
if (incoming.get(to) === 0) queue.push(to)
}
}
return new Map(ids.map((id) => [id, componentRanks.get(componentById.get(id)!) ?? 0]))
}
function separateTopLevelItems(
diagram: FlowchartDiagram,
nodeBounds: Map<string, FlowchartNodeBounds>,
subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds>,
gap: number,
): boolean {
): void {
const hasLocalDirection = (diagram.subgraphs ?? []).some(
(subgraph) => subgraph.direction && subgraph.direction !== diagram.direction,
)
const coveredNodeIds = new Set<string>()
const items: { id: string; bounds: FlowchartBounds; nodeIds: Set<string>; rank: number }[] = []
const itemByEndpoint = new Map<string, string>()
const subgraphs = diagram.subgraphs ?? []
const subgraphById = new Map(subgraphs.map((subgraph) => [subgraph.id, subgraph]))
const topLevelSubgraphId = (id: string): string => {
let current = subgraphById.get(id)
while (current?.parentId) current = subgraphById.get(current.parentId)
return current?.id ?? id
}
for (const subgraph of subgraphs) {
for (const subgraph of diagram.subgraphs ?? []) {
if (subgraph.parentId) continue
const bounds = subgraphBounds.get(subgraph.id)
const nodeIds = collectSubgraphNodeIds(diagram, subgraph.id)
@@ -595,7 +535,6 @@ function separateTopLevelItems(
itemByEndpoint.set(nodeId, subgraph.id)
}
}
for (const subgraph of subgraphs) itemByEndpoint.set(subgraph.id, topLevelSubgraphId(subgraph.id))
for (const node of diagram.nodes) {
if (coveredNodeIds.has(node.id)) continue
@@ -604,19 +543,12 @@ function separateTopLevelItems(
items.push({ id: node.id, bounds, nodeIds: new Set([node.id]), rank: 0 })
itemByEndpoint.set(node.id, node.id)
}
if (items.length < 2) return false
if (items.length < 2) return
const horizontal = isHorizontalDirection(diagram.direction)
const moveItem = (item: (typeof items)[number], dx: number, dy: number): void => {
for (const nodeId of item.nodeIds) {
const bounds = nodeBounds.get(nodeId)
if (bounds) translateBounds(bounds, dx, dy)
}
}
if (hasLocalDirection) {
items.sort((a, b) => (horizontal ? a.bounds.left - b.bounds.left : a.bounds.top - b.bounds.top))
let cursor: number | undefined
let moved = false
for (const item of items) {
const start = horizontal ? item.bounds.left : item.bounds.top
const size = horizontal ? item.bounds.width : item.bounds.height
@@ -625,31 +557,42 @@ function separateTopLevelItems(
continue
}
const shift = cursor - start
moved ||= shift !== 0
moveItem(item, horizontal ? shift : 0, horizontal ? 0 : shift)
for (const nodeId of item.nodeIds) {
const bounds = nodeBounds.get(nodeId)
if (bounds) translateBounds(bounds, horizontal ? shift : 0, horizontal ? 0 : shift)
}
cursor = start + shift + size + gap
}
return moved
return
}
const topLevelIds = new Set(subgraphs.filter((subgraph) => !subgraph.parentId).map((subgraph) => subgraph.id))
const topLevelIds = new Set(
(diagram.subgraphs ?? []).filter((subgraph) => !subgraph.parentId).map((subgraph) => subgraph.id),
)
const rankedItems = items.filter((item) => topLevelIds.has(item.id))
if (rankedItems.length < 2) return false
if (rankedItems.length < 2) return
const itemById = new Map(rankedItems.map((item) => [item.id, item]))
const outgoing = new Map(rankedItems.map((item) => [item.id, new Set<string>()]))
const incoming = new Map(rankedItems.map((item) => [item.id, 0]))
for (const edge of diagram.edges) {
const from = itemByEndpoint.get(edge.from)
const to = itemByEndpoint.get(edge.to)
if (!from || !to || from === to || !itemById.has(from) || !itemById.has(to) || outgoing.get(from)!.has(to)) continue
outgoing.get(from)!.add(to)
incoming.set(to, incoming.get(to)! + 1)
}
const ranks = rankGraphComponents(
rankedItems.map((item) => item.id),
outgoing,
)
for (const item of rankedItems) item.rank = ranks.get(item.id)!
const queue = rankedItems.filter((item) => incoming.get(item.id) === 0)
for (let index = 0; index < queue.length; index++) {
const item = queue[index]!
for (const to of outgoing.get(item.id)!) {
const downstream = itemById.get(to)!
downstream.rank = Math.max(downstream.rank, item.rank + 1)
incoming.set(to, incoming.get(to)! - 1)
if (incoming.get(to) === 0) queue.push(downstream)
}
}
const reversed = diagram.direction === "RL" || diagram.direction === "BT"
const primaryStart = (item: (typeof items)[number]): number => {
@@ -657,54 +600,28 @@ function separateTopLevelItems(
const size = horizontal ? item.bounds.width : item.bounds.height
return reversed ? -(start + size) : start
}
const itemsByRank = Map.groupBy(rankedItems, (item) => item.rank)
const rankKeys = [...itemsByRank.keys()].sort((a, b) => a - b)
rankedItems.sort((a, b) => a.rank - b.rank || primaryStart(a) - primaryStart(b))
let cursor: number | undefined
let moved = false
for (const rank of rankKeys) {
const rankItems = itemsByRank.get(rank)!
const start = Math.min(...rankItems.map(primaryStart))
const end = Math.max(
...rankItems.map((item) => primaryStart(item) + (horizontal ? item.bounds.width : item.bounds.height)),
)
for (const item of rankedItems) {
const start = primaryStart(item)
const size = horizontal ? item.bounds.width : item.bounds.height
if (cursor === undefined) {
cursor = end + gap
cursor = start + size + gap
continue
}
const shift = Math.max(0, cursor - start)
if (shift > 0) {
moved = true
for (const item of rankItems) {
const offset = reversed ? -shift : shift
moveItem(item, horizontal ? offset : 0, horizontal ? 0 : offset)
for (const nodeId of item.nodeIds) {
const bounds = nodeBounds.get(nodeId)
if (bounds) {
const offset = reversed ? -shift : shift
translateBounds(bounds, horizontal ? offset : 0, horizontal ? 0 : offset)
}
}
}
cursor = end + shift + gap
cursor = start + shift + size + gap
}
for (const rank of rankKeys) {
const rankItems = itemsByRank
.get(rank)!
.toSorted((a, b) =>
horizontal ? a.bounds.top - b.bounds.top : a.bounds.left - b.bounds.left,
)
let crossCursor: number | undefined
for (const item of rankItems) {
const start = horizontal ? item.bounds.top : item.bounds.left
const size = horizontal ? item.bounds.height : item.bounds.width
if (crossCursor === undefined) {
crossCursor = start + size + gap
continue
}
const shift = Math.max(0, crossCursor - start)
if (shift > 0) {
moved = true
moveItem(item, horizontal ? 0 : shift, horizontal ? shift : 0)
}
crossCursor = start + shift + size + gap
}
}
return moved
}
function layoutSubgraphs(
@@ -759,27 +676,13 @@ function layoutFlowchartWithDirection(
const bounds = layoutRankedNodes(diagram, direction, sizes, minNodeGap, requestedMinRankGap)
layoutLocalSubgraphDirections(diagram, bounds, sizes, minNodeGap, requestedMinRankGap)
const subgraphs = diagram.subgraphs ?? []
let subgraphBounds = new Map<string, FlowchartSubgraphBounds>()
let routes: FlowchartEdgeRoute[]
if (subgraphs.length === 0) {
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
} else {
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
const moved = separateTopLevelItems(
diagram,
bounds,
subgraphBounds,
Math.max(1, Math.floor(requestedMinRankGap / 2)),
)
if (moved) {
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
}
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge), subgraphBounds)
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
}
let routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
let subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
separateTopLevelItems(diagram, bounds, subgraphBounds, Math.max(1, Math.floor(requestedMinRankGap / 2)))
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge))
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
routes = routeFlowchartEdges(diagram, bounds, (edge) => edgeDirection(diagram, edge), subgraphBounds)
subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
const allBounds = [...bounds.values(), ...subgraphBounds.values(), ...routeRenderBounds(routes)]
const dx = Math.max(0, -Math.min(0, ...allBounds.map((bound) => bound.left)))
const dy = Math.max(0, -Math.min(0, ...allBounds.map((bound) => bound.top)))
-51
View File
@@ -1,51 +0,0 @@
import { describe, expect, test } from "bun:test"
import { RGBA } from "@opentui/core"
import { createOpenCodeDiagramPalette } from "./palette.js"
type Rgb = readonly [number, number, number]
const rgb = (value: Rgb) => RGBA.fromInts(...value)
describe("OpenCode diagram palette", () => {
test.each(
[
{
name: "dark theme",
text: [230, 232, 240],
subdued: [114, 120, 138],
secondary: [172, 176, 189],
muted: [149, 154, 169],
},
{
name: "light theme",
text: [32, 35, 43],
subdued: [119, 125, 138],
secondary: [76, 80, 91],
muted: [93, 98, 110],
},
] satisfies ReadonlyArray<{
name: string
text: Rgb
subdued: Rgb
secondary: Rgb
muted: Rgb
}>,
)("derives a controlled neutral ladder for a $name", ({ text, subdued, secondary, muted }) => {
const primary = rgb(text)
const info = RGBA.fromInts(40, 120, 220)
const background = RGBA.fromInts(10, 20, 30)
const palette = createOpenCodeDiagramPalette({
text: primary,
subdued: rgb(subdued),
info,
background,
})
expect(palette.text).toBe(primary)
expect(palette.primary).toBe(primary)
expect(palette.secondary.equals(rgb(secondary))).toBe(true)
expect(palette.muted.equals(rgb(muted))).toBe(true)
expect(palette.warning).toBe(info)
expect(palette.background).toBe(background)
})
})
-20
View File
@@ -1,20 +0,0 @@
import type { RGBA } from "@opentui/core"
import { blendColor } from "./core/color/style.js"
export interface OpenCodeDiagramPaletteInput {
readonly text: RGBA
readonly subdued: RGBA
readonly info: RGBA
readonly background: RGBA
}
export function createOpenCodeDiagramPalette(input: OpenCodeDiagramPaletteInput) {
return {
text: input.text,
primary: input.text,
secondary: blendColor(input.text, input.subdued, 0.5),
muted: blendColor(input.text, input.subdued, 0.7),
warning: input.info,
background: input.background,
}
}
+7 -6
View File
@@ -1,6 +1,5 @@
import { Plugin } from "@opencode-ai/plugin/tui"
import { createMermaidCodeBlockRenderer } from "./markdown.js"
import { createOpenCodeDiagramPalette } from "./palette.js"
export default Plugin.define({
id: "opencode.merman",
@@ -8,12 +7,14 @@ export default Plugin.define({
context.markdown.registerCodeBlockRenderer(
"mermaid",
createMermaidCodeBlockRenderer(context.renderer, () => ({
colors: createOpenCodeDiagramPalette({
text: context.theme.text.default,
subdued: context.theme.text.subdued,
info: context.theme.text.feedback.info.default,
colors: {
text: context.theme.markdown.text,
primary: context.theme.text.default,
secondary: context.theme.text.subdued,
muted: context.theme.border.default,
warning: context.theme.text.feedback.info.default,
background: context.theme.background.default,
}),
},
})),
)
},
+11 -36
View File
@@ -13,30 +13,15 @@ trap 'rm -f -- "$pidfile"' EXIT
"$@"
`
// Modal's VM runtime accepts process-group signals without delivering them
// (kill(-pgid) returns 0 and nothing dies; direct-pid signals work), so the
// group is enumerated from /proc and each member is signalled directly. The
// second pass catches children forked between scan and signal.
const KILL = `
pidfile=$1
sig=$2
i=0
while [ ! -s "$pidfile" ] && [ "$i" -lt 250 ]; do sleep 0.02; i=$((i + 1)); done
[ -s "$pidfile" ] || exit 47
target=$(cat "$pidfile")
pass=0
while [ "$pass" -lt 2 ]; do
for stat in /proc/[0-9]*/stat; do
[ -e "$stat" ] || continue
pid=\${stat#/proc/}
pid=\${pid%/stat}
set -- $(sed "s/.*) //" "$stat" 2>/dev/null)
if [ "\${3:-}" = "$target" ]; then
/bin/kill "-$sig" "$pid" 2>/dev/null || true
fi
done
pass=$((pass + 1))
done
while [ ! -s "$1" ] && [ "$i" -lt 250 ]; do sleep 0.02; i=$((i + 1)); done
if [ -s "$1" ]; then
pid=$(cat "$1")
/bin/kill "-$2" "-$pid" 2>/dev/null || true
else
exit 47
fi
`
export interface ModalImageSpec {
@@ -69,15 +54,7 @@ export const createModalSandbox = async (options: ModalSandboxOptions) => {
const app = await client.apps.fromName(options.app, { createIfMissing: true })
const imageSpec = options.image ?? ubuntuImage
const image = client.images.fromRegistry(imageSpec.registry).dockerfileCommands([...imageSpec.dockerfileCommands])
// Always Modal's Full-VM runtime (beta, enabled per account): a real kernel
// with real device nodes, so workspaces can run Docker and other
// kernel-dependent workloads. Costs versus gVisor, measured Aug 2026:
// per-exec floor ~285-535ms versus ~90-165ms, and filesystem snapshots only
// (no memory snapshots — acceptable; fs-snapshot is the persistence design).
const sandbox = await client.sandboxes.create(app, image, {
...options.sandbox,
experimentalOptions: { ...options.sandbox?.experimentalOptions, vm_runtime: true },
})
const sandbox = await client.sandboxes.create(app, image, options.sandbox)
return {
driver: makeModalDriver(sandbox),
sandbox,
@@ -87,14 +64,12 @@ export const createModalSandbox = async (options: ModalSandboxOptions) => {
/**
* Adapts Modal exec to the Environment driver. Files intentionally has no native
* overrides: exec latency dominates payload work (VM runtime floor measured
* ~285-535ms per exec, Aug 2026), so the derived exec defaults are the simplest
* implementation with no measured loss.
* overrides: Modal exec and filesystem tools share the same roughly 175ms floor,
* so the derived exec defaults are the simplest implementation with no measured loss.
*
* Modal cannot signal a ContainerProcess. Each command therefore starts a new
* process group and records its leader in a unique pid file; kill runs a second
* sandbox command that enumerates that group from /proc and signals each member
* directly (see KILL). Pid files are removed best-effort.
* sandbox command that signals that group. Pid files are removed best-effort.
*/
export const makeModalDriver = (sandbox: Sandbox): Driver => {
const spawn = Effect.fnUntraced(function* (command: Command) {
+9
View File
@@ -1154,6 +1154,15 @@ function App(props: { pair?: DialogPairCredentials }) {
}
})
event.on("session.execution.failed", (evt, { workspace }) => {
if (workspace !== (location.current?.workspaceID ?? data.location.default().workspaceID)) return
toast.show({
variant: "error",
message: evt.data.error.message,
duration: 5000,
})
})
// Suppress the full-screen overlay for transient startup and event-stream retry states.
// Initial connection gets a longer grace period; retries surface more quickly.
const [showReconnecting, setShowReconnecting] = createSignal(false)
+15 -7
View File
@@ -1631,13 +1631,21 @@ function AssistantFooter(props: { message: SessionMessageAssistant }) {
const interrupted = createMemo(() => props.message.error?.message === "Step interrupted")
return (
<>
<Show when={props.message.error && !interrupted() && !props.message.retry}>
<box paddingLeft={3}>
<text fg={theme.text.feedback.error.default}>Error: {errorMessage(props.message.error)}</text>
<Show when={props.message.error && !interrupted()}>
<box
border={["left"]}
paddingTop={1}
paddingBottom={1}
paddingLeft={2}
backgroundColor={theme.background.default}
customBorderChars={SplitBorder.customBorderChars}
borderColor={theme.text.feedback.error.default}
>
<text fg={theme.text.subdued}>{errorMessage(props.message.error)}</text>
</box>
</Show>
<AssistantRetry retry={props.message.retry} />
<box paddingLeft={3} marginTop={props.message.retry || (props.message.error && !interrupted()) ? 1 : 0}>
<box paddingLeft={3} marginTop={props.message.error && !interrupted() ? 1 : 0}>
<text>
<span style={{ fg: props.message.error ? theme.text.subdued : local.agent.color(props.message.agent) }}>
{Locale.titlecase(props.message.agent)}
@@ -2037,9 +2045,9 @@ function AssistantRetry(props: { retry: SessionMessageAssistant["retry"] }) {
return (
<Show when={props.retry}>
{(retry) => (
<box paddingLeft={3}>
<text fg={theme.text.feedback.warning.default}>
Retry attempt {retry().attempt} scheduled: {retry().error.message}
<box paddingLeft={3} marginTop={1}>
<text fg={theme.text.subdued}>
Retry attempt {retry().attempt} scheduled: {retry().error.message} [{retry().error.type}]
</text>
</box>
)}