Skip to content

Commit 9c17876

Browse files
authored
feat(plugin): add vcs provider api (anomalyco#44979)
1 parent 7601ab9 commit 9c17876

22 files changed

Lines changed: 605 additions & 39 deletions

File tree

‎packages/client/src/promise/api.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export type ReferenceApi = Client["reference"]
1313
export type WebSearchApi = Client["websearch"]
1414
export type SessionApi = Client["session"]
1515
export type SkillApi = Client["skill"]
16+
export type VcsApi = Client["vcs"]
1617

1718
export interface CatalogApi {
1819
readonly provider: ProviderApi

‎packages/core/src/plugin.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { Reference } from "./reference.js"
2222
import { Skill } from "./skill.js"
2323
import { State } from "./state.js"
2424
import { Tool } from "./tool.js"
25+
import { Vcs } from "./vcs.js"
2526
import { PluginHooks } from "./plugin/hooks.js"
2627

2728
export interface Interface {
@@ -199,6 +200,7 @@ export const node = makeLocationNode({
199200
Reference.node,
200201
Skill.node,
201202
Tool.node,
203+
Vcs.node,
202204
PluginHooks.node,
203205
PluginRuntime.node,
204206
WebSearch.node,

‎packages/core/src/plugin/host.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { AbsolutePath, type DeepMutable } from "../schema.js"
2424
import { Skill } from "../skill.js"
2525
import { Tool } from "../tool.js"
2626
import { Workspace } from "../workspace.js"
27+
import { Vcs } from "../vcs.js"
2728
import { WebSearch } from "../websearch.js"
2829
import { PluginHooks } from "./hooks.js"
2930
import type { Interface } from "../plugin.js"
@@ -43,6 +44,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Interface, p
4344
const reference = yield* Reference.Service
4445
const skill = yield* Skill.Service
4546
const tools = yield* Tool.Service
47+
const vcs = yield* Vcs.Service
4648
const websearch = yield* WebSearch.Service
4749
const hooks = yield* PluginHooks.Service
4850
const runtime = yield* PluginRuntime.Service
@@ -354,6 +356,14 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Interface, p
354356
.pipe(Effect.orDie, Effect.as({ dispose: Effect.void })),
355357
hook: (name, callback) => hooks.register("tool", name, callback),
356358
},
359+
vcs: {
360+
get: () => response(vcs.info()),
361+
branches: (input) => response(vcs.branches({ search: input?.search, limit: input?.limit })),
362+
status: () => response(vcs.status()),
363+
diff: (input) => response(vcs.diff(input.mode, { context: input.context })),
364+
transform: vcs.transform,
365+
reload: vcs.reload,
366+
},
357367
websearch: {
358368
providers: () => response(websearch.providers()),
359369
query: (input) =>

‎packages/core/src/vcs.ts‎

Lines changed: 112 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
export * as Vcs from "./vcs.js"
22

33
import path from "path"
4-
import { Context, Effect, Layer, Stream } from "effect"
4+
import { Cause, Context, Effect, Layer, Schema, Stream } from "effect"
5+
import type { VcsDefinition, VcsDraft } from "@opencode-ai/plugin/effect/vcs"
56
import { FileDiff } from "@opencode-ai/schema/file-diff"
67
import { FileSystem } from "@opencode-ai/schema/filesystem"
78
import { BranchList, FileStatus, Info, Mode } from "@opencode-ai/schema/vcs"
@@ -11,8 +12,10 @@ import { FSUtil } from "@opencode-ai/util/fs-util"
1112
import { Location } from "./location.js"
1213
import { AppProcess } from "@opencode-ai/util/process"
1314
import { Bus } from "./bus.js"
15+
import { State } from "./state.js"
1416
import { VcsGit } from "./vcs/git.js"
1517
import { VcsHg } from "./vcs/hg.js"
18+
import { emptyPatch, MAX_TOTAL_PATCH_BYTES, PATCH_CONTEXT_LINES } from "./vcs/patch.js"
1619

1720
export { BranchList, FileStatus, Info, Mode }
1821

@@ -25,13 +28,20 @@ export interface BranchOptions {
2528
readonly limit?: number
2629
}
2730

28-
export interface Interface {
31+
export interface Adapter {
2932
readonly info: () => Effect.Effect<Info>
3033
readonly branches: (options?: BranchOptions) => Effect.Effect<BranchList>
3134
readonly status: () => Effect.Effect<FileStatus[]>
3235
readonly diff: (mode: Mode, options?: DiffOptions) => Effect.Effect<FileDiff.Info[]>
3336
}
3437

38+
export interface Interface extends Adapter, State.Transformable<VcsDraft> {}
39+
40+
interface Data {
41+
readonly providers: Map<string, VcsDefinition>
42+
selection?: string
43+
}
44+
3545
export class Service extends Context.Service<Service, Interface>()("@opencode/Vcs") {}
3646

3747
// Adapter seam: one working-copy implementation per VCS type, selected by the
@@ -50,11 +60,59 @@ const layer = Layer.effect(
5060
const fs = yield* FSUtil.Service
5161
const location = yield* Location.Service
5262
const bus = yield* Bus.Service
53-
const impl = adapter(proc, fs, location)
63+
const native = adapter(proc, fs, location)
5464
const vcs = location.vcs
55-
const state = { info: impl ? yield* impl.info() : ({ branch: {} } satisfies Info) }
65+
const current = { info: native ? yield* native.info() : ({ branch: {} } satisfies Info) }
66+
const scope = {
67+
directory: location.directory,
68+
worktree: location.project.directory,
69+
canonical: location.project.canonical,
70+
...(vcs ? { store: vcs.store } : {}),
71+
}
72+
const decodeInfo = Schema.decodeUnknownEffect(Info)
73+
const decodeBranches = Schema.decodeUnknownEffect(BranchList)
74+
const decodeStatus = Schema.decodeUnknownEffect(Schema.Array(FileStatus))
75+
const decodeDiff = Schema.decodeUnknownEffect(Schema.Array(FileDiff.Info))
76+
const state: State.Interface<Data, VcsDraft> = State.create<Data, VcsDraft>({
77+
name: "vcs",
78+
initial: () => ({ providers: new Map() }),
79+
draft: (draft) => ({
80+
add: (provider) => draft.providers.set(provider.id, provider),
81+
default: {
82+
get: () => draft.selection,
83+
set: (selection) => (draft.selection = selection),
84+
},
85+
}),
86+
finalize: () => refresh(),
87+
})
88+
const selected = () => {
89+
const value = state.get()
90+
const id = value.selection ?? vcs?.type
91+
return id ? value.providers.get(id) : undefined
92+
}
93+
const protect = <A>(provider: VcsDefinition, operation: string, effect: Effect.Effect<A, unknown>, fallback: A) =>
94+
effect.pipe(
95+
Effect.catchCause((cause) =>
96+
Cause.hasInterrupts(cause)
97+
? Effect.failCause(cause).pipe(Effect.orDie)
98+
: Effect.logWarning("vcs provider failed", { provider: provider.id, operation, cause }).pipe(
99+
Effect.as(fallback),
100+
),
101+
),
102+
)
103+
const refresh = Effect.fn("Vcs.refresh")(function* () {
104+
const provider = selected()
105+
const next: Info = provider
106+
? yield* protect(provider, "info", provider.info(scope).pipe(Effect.flatMap(decodeInfo)), { branch: {} })
107+
: native
108+
? yield* native.info()
109+
: { branch: {} }
110+
const changed = current.info.branch.current !== next.branch.current
111+
current.info = next
112+
if (changed) yield* bus.publish(VcsEvent.BranchUpdated, { branch: next.branch.current })
113+
})
56114

57-
if (vcs && impl) {
115+
if (vcs && native) {
58116
const store = yield* fs.realPath(vcs.store).pipe(Effect.orElseSucceed(() => vcs.store))
59117
const isBranchMetadata =
60118
vcs.type === "git"
@@ -63,33 +121,68 @@ const layer = Layer.effect(
63121
yield* bus.subscribe(FileSystem.Event.Changed).pipe(
64122
Stream.filter((event) => isBranchMetadata(event.data.file)),
65123
Stream.runForEach((event) =>
66-
Effect.gen(function* () {
67-
const next = yield* impl.info()
68-
const changed = state.info.branch.current !== next.branch.current
69-
state.info = next
70-
if (!changed) return
71-
yield* bus.publish(VcsEvent.BranchUpdated, { branch: next.branch.current })
72-
}).pipe(Effect.withSpan("Vcs.refreshBranch", { attributes: { file: event.data.file } })),
124+
refresh().pipe(Effect.withSpan("Vcs.refreshBranch", { attributes: { file: event.data.file } })),
73125
),
74126
Effect.forkScoped({ startImmediately: true }),
75127
)
76128
}
77129

78130
return Service.of({
131+
transform: state.transform,
132+
reload: state.reload,
79133
info: Effect.fn("Vcs.info")(function* () {
80-
return state.info
134+
return current.info
81135
}),
82136
branches: Effect.fn("Vcs.branches")(function* (options?: BranchOptions) {
83-
if (!impl) return []
84-
return yield* impl.branches(options)
137+
const provider = selected()
138+
if (provider)
139+
return yield* protect(
140+
provider,
141+
"branches",
142+
provider.branches({ ...scope, ...options }).pipe(Effect.flatMap(decodeBranches)),
143+
[],
144+
)
145+
if (!native) return []
146+
return yield* native.branches(options)
85147
}),
86148
status: Effect.fn("Vcs.status")(function* () {
87-
if (!impl) return []
88-
return yield* impl.status()
149+
const provider = selected()
150+
if (provider)
151+
return yield* protect(
152+
provider,
153+
"status",
154+
provider.status(scope).pipe(
155+
Effect.flatMap(decodeStatus),
156+
Effect.map((rows) => Array.from(rows)),
157+
),
158+
[],
159+
)
160+
if (!native) return []
161+
return yield* native.status()
89162
}),
90163
diff: Effect.fn("Vcs.diff")(function* (mode: Mode, options?: DiffOptions) {
91-
if (!impl) return []
92-
return yield* impl.diff(mode, options)
164+
const provider = selected()
165+
if (!provider) return native ? yield* native.diff(mode, options) : []
166+
const rows = yield* protect(
167+
provider,
168+
"diff",
169+
provider
170+
.diff({
171+
...scope,
172+
mode,
173+
context: options?.context ?? PATCH_CONTEXT_LINES,
174+
maxOutputBytes: MAX_TOTAL_PATCH_BYTES,
175+
})
176+
.pipe(Effect.flatMap(decodeDiff)),
177+
[],
178+
)
179+
let total = 0
180+
return rows.map((row) => {
181+
const bytes = Buffer.byteLength(row.patch)
182+
if (total + bytes > MAX_TOTAL_PATCH_BYTES) return { ...row, patch: emptyPatch(row.file) }
183+
total += bytes
184+
return row
185+
})
93186
}),
94187
})
95188
}),

‎packages/core/src/vcs/git.ts‎

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { ChildProcess } from "effect/unstable/process"
55
import { FileDiff } from "@opencode-ai/schema/file-diff"
66
import { BranchList, FileStatus, Info, Mode } from "@opencode-ai/schema/vcs"
77
import { AppProcess } from "@opencode-ai/util/process"
8-
import type { BranchOptions, DiffOptions, Interface } from "../vcs.js"
8+
import type { Adapter, BranchOptions, DiffOptions } from "../vcs.js"
99
import { chunksByFile, emptyPatch, MAX_PATCH_BYTES, MAX_TOTAL_PATCH_BYTES, PATCH_CONTEXT_LINES } from "./patch.js"
1010
import type { Patch } from "./patch.js"
1111

@@ -14,7 +14,7 @@ import type { Patch } from "./patch.js"
1414
* batched through one `git diff` invocation where possible and capped by
1515
* per-file and total byte budgets, falling back to empty patches when capped.
1616
*/
17-
export function make(proc: AppProcess.Interface, input: { directory: string; worktree: string }): Interface {
17+
export function make(proc: AppProcess.Interface, input: { directory: string; worktree: string }): Adapter {
1818
// Listing commands scope pathspecs to the requested directory; per-file
1919
// commands run from the worktree root because git lists root-relative paths.
2020
const ctx: Ctx = { git: makeGit(proc), directory: input.directory, worktree: input.worktree }
@@ -181,20 +181,18 @@ function makeGit(proc: AppProcess.Interface) {
181181

182182
const branches = Effect.fn("VcsGit.branches")(function* (cwd: string, options?: BranchOptions) {
183183
const search = options?.search?.trim().replace(/[*?[\]\\]/g, "\\$&")
184-
return (
185-
yield* lines(
186-
[
187-
"for-each-ref",
188-
"--ignore-case",
189-
"--sort=refname",
190-
"--sort=-committerdate",
191-
"--format=%(refname:short)",
192-
...(options?.limit ? [`--count=${options.limit}`] : []),
193-
...(search ? [`refs/heads/*${search}*`, `refs/remotes/*${search}*`] : ["refs/heads", "refs/remotes"]),
194-
],
195-
{ cwd },
196-
)
197-
).filter((item) => !item.endsWith("/HEAD")) satisfies BranchList
184+
return (yield* lines(
185+
[
186+
"for-each-ref",
187+
"--ignore-case",
188+
"--sort=refname",
189+
"--sort=-committerdate",
190+
"--format=%(refname:short)",
191+
...(options?.limit ? [`--count=${options.limit}`] : []),
192+
...(search ? [`refs/heads/*${search}*`, `refs/remotes/*${search}*`] : ["refs/heads", "refs/remotes"]),
193+
],
194+
{ cwd },
195+
)).filter((item) => !item.endsWith("/HEAD")) satisfies BranchList
198196
})
199197

200198
const defaultBranch = Effect.fn("VcsGit.defaultBranch")(function* (cwd: string) {

‎packages/core/src/vcs/hg.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { FileDiff } from "@opencode-ai/schema/file-diff"
77
import { FileStatus, Info, Mode } from "@opencode-ai/schema/vcs"
88
import { FSUtil } from "@opencode-ai/util/fs-util"
99
import { AppProcess } from "@opencode-ai/util/process"
10-
import type { DiffOptions, Interface } from "../vcs.js"
10+
import type { Adapter, DiffOptions } from "../vcs.js"
1111
import {
1212
addPatch,
1313
chunksByFile,
@@ -28,7 +28,7 @@ export function make(
2828
proc: AppProcess.Interface,
2929
fs: FSUtil.Interface,
3030
input: { directory: string; worktree: string },
31-
): Interface {
31+
): Adapter {
3232
const hg = makeHg(proc, input.worktree)
3333
// All commands run from the worktree root (hg prints root-relative paths);
3434
// this pathspec scopes them to the requested directory.

‎packages/core/test/plugin.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { AbsolutePath } from "@opencode-ai/core/schema"
1414
import { Session } from "@opencode-ai/core/session"
1515
import { SessionMessage } from "@opencode-ai/core/session/message"
1616
import { Tool } from "@opencode-ai/core/tool"
17+
import { Vcs } from "@opencode-ai/core/vcs"
1718
import { testEffect } from "./lib/effect"
1819
import { PluginTestLayer } from "./plugin/fixture"
1920

@@ -93,6 +94,37 @@ describe("Plugin", () => {
9394
}),
9495
)
9596

97+
it.effect("registers and removes scoped VCS providers", () =>
98+
Effect.gen(function* () {
99+
const plugins = yield* Plugin.Service
100+
const vcs = yield* Vcs.Service
101+
const provider = EffectPlugin.define({
102+
id: "custom-vcs",
103+
effect: (ctx) =>
104+
ctx.vcs
105+
.transform((draft) => {
106+
draft.add({
107+
id: "custom",
108+
name: "Custom VCS",
109+
info: () => Effect.succeed({ branch: { current: "feature" } }),
110+
branches: () => Effect.succeed(["feature"]),
111+
status: () => Effect.succeed([]),
112+
diff: () => Effect.succeed([]),
113+
})
114+
draft.default.set("custom")
115+
})
116+
.pipe(Effect.asVoid),
117+
})
118+
119+
yield* plugins.activate([versioned(provider)])
120+
expect(yield* vcs.info()).toEqual({ branch: { current: "feature" } })
121+
expect(yield* vcs.branches()).toEqual(["feature"])
122+
123+
yield* plugins.activate([])
124+
expect(yield* vcs.info()).toEqual({ branch: {} })
125+
}),
126+
)
127+
96128
it.effect("replaces plugins by ID and version", () =>
97129
Effect.gen(function* () {
98130
const plugins = yield* Plugin.Service

‎packages/core/test/plugin/fixture.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { Skill } from "@opencode-ai/core/skill"
2323
import { SkillDiscovery } from "@opencode-ai/core/skill/discovery"
2424
import { Watcher } from "@opencode-ai/core/filesystem/watcher"
2525
import { Tool } from "@opencode-ai/core/tool"
26+
import { Vcs } from "@opencode-ai/core/vcs"
2627
import { WebSearch } from "@opencode-ai/core/websearch"
2728
import { Effect, Layer } from "effect"
2829
import { tempLocationLayer } from "../fixture/location"
@@ -62,6 +63,7 @@ export const PluginTestLayer = LayerNode.compile(
6263
SkillDiscovery.node,
6364
PluginHooks.node,
6465
Tool.node,
66+
Vcs.node,
6567
Watcher.node,
6668
WebSearch.node,
6769
]),

‎packages/core/test/plugin/host.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,14 @@ export function host(overrides: Overrides = {}): Plugin.Context {
107107
transform: () => Effect.die("unused tool.transform"),
108108
hook: () => Effect.die("unused tool.hook"),
109109
},
110+
vcs: overrides.vcs ?? {
111+
get: () => Effect.die("unused vcs.get"),
112+
branches: () => Effect.die("unused vcs.branches"),
113+
status: () => Effect.die("unused vcs.status"),
114+
diff: () => Effect.die("unused vcs.diff"),
115+
transform: () => Effect.die("unused vcs.transform"),
116+
reload: () => Effect.die("unused vcs.reload"),
117+
},
110118
websearch: overrides.websearch ?? {
111119
providers: () => Effect.die("unused websearch.providers"),
112120
query: () => Effect.die("unused websearch.query"),

0 commit comments

Comments
 (0)