location-layer.test.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import fs from "fs/promises"
  2. import path from "path"
  3. import { describe, expect } from "bun:test"
  4. import { DateTime, Effect, Equal, Hash, Layer, Schema } from "effect"
  5. import { Tool } from "@opencode-ai/core/tool/tool"
  6. import { define } from "@opencode-ai/plugin/v2/effect"
  7. import { AgentV2 } from "@opencode-ai/core/agent"
  8. import { Catalog } from "@opencode-ai/core/catalog"
  9. import { LocationServiceMap, locationServiceMapLayer } from "@opencode-ai/core/location-services"
  10. import { Location } from "@opencode-ai/core/location"
  11. import { PluginV2 } from "@opencode-ai/core/plugin"
  12. import { ModelV2 } from "@opencode-ai/core/model"
  13. import { ProjectV2 } from "@opencode-ai/core/project"
  14. import { ProviderV2 } from "@opencode-ai/core/provider"
  15. import { AbsolutePath } from "@opencode-ai/core/schema"
  16. import { SessionV2 } from "@opencode-ai/core/session"
  17. import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
  18. import { tmpdir } from "./fixture/tmpdir"
  19. import { testEffect } from "./lib/effect"
  20. import { toolDefinitions } from "./lib/tool"
  21. import { FSUtil } from "../src/fs-util"
  22. import { Credential } from "../src/credential"
  23. import { Database } from "../src/database/database"
  24. import { EventV2 } from "../src/event"
  25. import { Global } from "../src/global"
  26. import { ModelsDev } from "../src/models-dev"
  27. import { Npm } from "../src/npm"
  28. import { Project } from "../src/project"
  29. import { Reference } from "../src/reference"
  30. import { ToolRegistry } from "../src/tool/registry"
  31. import { ApplicationTools } from "../src/tool/application-tools"
  32. const applicationTools = ApplicationTools.layer
  33. const it = testEffect(
  34. Layer.merge(
  35. Layer.mergeAll(applicationTools, Database.defaultLayer, EventV2.defaultLayer),
  36. locationServiceMapLayer.pipe(
  37. Layer.provide(applicationTools),
  38. Layer.provide(
  39. Layer.mergeAll(
  40. Project.defaultLayer,
  41. EventV2.defaultLayer,
  42. Credential.defaultLayer.pipe(Layer.fresh),
  43. Npm.defaultLayer,
  44. ModelsDev.defaultLayer,
  45. FSUtil.defaultLayer,
  46. Global.defaultLayer,
  47. ),
  48. ),
  49. ),
  50. ),
  51. )
  52. describe("LocationServiceMap", () => {
  53. it.live("reuses cached services for constructed and decoded location refs", () =>
  54. Effect.acquireRelease(
  55. Effect.promise(() => tmpdir()),
  56. (dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
  57. ).pipe(
  58. Effect.flatMap((dir) =>
  59. Effect.scoped(
  60. Effect.gen(function* () {
  61. const locations = yield* LocationServiceMap.Service
  62. const directory = AbsolutePath.make(dir.path)
  63. const constructed = Location.Ref.make({ directory })
  64. const decoded = Schema.decodeUnknownSync(Location.Ref)({ directory })
  65. expect(constructed).toEqual({ directory, workspaceID: undefined })
  66. expect(decoded).toEqual(constructed)
  67. expect(Equal.equals(constructed, decoded)).toBe(true)
  68. expect(Hash.hash(constructed)).toBe(Hash.hash(decoded))
  69. expect(yield* locations.contextEffect(constructed)).toBe(yield* locations.contextEffect(decoded))
  70. }),
  71. ),
  72. ),
  73. ),
  74. )
  75. it.live("isolates location state while sharing location policy with catalog", () =>
  76. Effect.acquireRelease(
  77. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  78. (dirs) => Effect.promise(() => Promise.all(dirs.map((dir) => dir[Symbol.asyncDispose]())).then(() => undefined)),
  79. ).pipe(
  80. Effect.flatMap(([blocked, allowed]) =>
  81. Effect.gen(function* () {
  82. yield* (yield* ApplicationTools.Service).register({
  83. application_context: Tool.make({
  84. description: "Read application context",
  85. input: Schema.Struct({}),
  86. output: Schema.Struct({ ok: Schema.Boolean }),
  87. execute: () => Effect.succeed({ ok: true }),
  88. }),
  89. })
  90. yield* Effect.promise(() =>
  91. fs.writeFile(
  92. path.join(blocked.path, "opencode.json"),
  93. JSON.stringify({
  94. experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "test" }] },
  95. }),
  96. ),
  97. )
  98. const update = (directory: string) =>
  99. Effect.gen(function* () {
  100. yield* Reference.Service
  101. const catalog = yield* Catalog.Service
  102. yield* catalog.transform((editor) => editor.provider.update(ProviderV2.ID.make("test"), () => {}))
  103. return {
  104. providers: yield* catalog.provider.all(),
  105. tools: yield* toolDefinitions(yield* ToolRegistry.Service),
  106. }
  107. }).pipe(
  108. Effect.scoped,
  109. Effect.provide(
  110. LocationServiceMap.Service.get(Location.Ref.make({ directory: AbsolutePath.make(directory) })),
  111. ),
  112. )
  113. const blockedState = yield* update(blocked.path)
  114. expect(blockedState.providers.some((provider) => provider.id === ProviderV2.ID.make("test"))).toBe(false)
  115. expect(blockedState.tools.map((tool) => tool.name).sort()).toEqual([
  116. "application_context",
  117. "apply_patch",
  118. "bash",
  119. "edit",
  120. "glob",
  121. "grep",
  122. "question",
  123. "read",
  124. "skill",
  125. "todowrite",
  126. "webfetch",
  127. "websearch",
  128. "write",
  129. ])
  130. const allowedState = yield* update(allowed.path)
  131. expect(allowedState.providers.some((provider) => provider.id === ProviderV2.ID.make("test"))).toBe(true)
  132. expect(allowedState.tools.map((tool) => tool.name).sort()).toEqual([
  133. "application_context",
  134. "apply_patch",
  135. "bash",
  136. "edit",
  137. "glob",
  138. "grep",
  139. "question",
  140. "read",
  141. "skill",
  142. "todowrite",
  143. "webfetch",
  144. "websearch",
  145. "write",
  146. ])
  147. }),
  148. ),
  149. ),
  150. )
  151. it.live("rejects an unavailable selected model during location model resolution", () =>
  152. Effect.acquireRelease(
  153. Effect.promise(() => tmpdir()),
  154. (dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
  155. ).pipe(
  156. Effect.flatMap((dir) =>
  157. Effect.gen(function* () {
  158. const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) })
  159. yield* Effect.promise(() =>
  160. fs.writeFile(
  161. path.join(dir.path, "opencode.json"),
  162. JSON.stringify({
  163. providers: {
  164. unavailable: {
  165. name: "Unavailable",
  166. api: { type: "native", settings: {} },
  167. models: { chat: { disabled: true } },
  168. },
  169. },
  170. }),
  171. ),
  172. )
  173. const failure = yield* SessionRunnerModel.Service.use((models) =>
  174. models.resolve(
  175. SessionV2.Info.make({
  176. id: SessionV2.ID.make("ses_unavailable_model"),
  177. projectID: ProjectV2.ID.global,
  178. title: "test",
  179. model: {
  180. id: ModelV2.ID.make("chat"),
  181. providerID: ProviderV2.ID.make("unavailable"),
  182. },
  183. cost: 0,
  184. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  185. time: { created: DateTime.makeUnsafe(0), updated: DateTime.makeUnsafe(0) },
  186. location,
  187. }),
  188. ),
  189. ).pipe(Effect.provide(LocationServiceMap.Service.get(location)), Effect.flip)
  190. expect(failure).toMatchObject({
  191. _tag: "SessionRunnerModel.ModelUnavailableError",
  192. providerID: "unavailable",
  193. modelID: "chat",
  194. })
  195. }),
  196. ),
  197. ),
  198. )
  199. it.live("installs public plugins into a location", () =>
  200. Effect.acquireRelease(
  201. Effect.promise(() => tmpdir()),
  202. (dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
  203. ).pipe(
  204. Effect.flatMap((dir) =>
  205. Effect.gen(function* () {
  206. const plugins = yield* PluginV2.Service
  207. const reviewer = define({
  208. id: "reviewer",
  209. effect: (ctx) =>
  210. ctx.agent
  211. .transform((agent) => {
  212. agent.update("reviewer", (item) => {
  213. item.description = "Reviews code"
  214. item.mode = "subagent"
  215. })
  216. })
  217. .pipe(Effect.asVoid),
  218. })
  219. yield* plugins.add(PluginV2.ID.make(reviewer.id), reviewer.effect)
  220. expect(yield* (yield* AgentV2.Service).get(AgentV2.ID.make("reviewer"))).toMatchObject({
  221. description: "Reviews code",
  222. mode: "subagent",
  223. })
  224. }).pipe(
  225. Effect.scoped,
  226. Effect.provide(LocationServiceMap.Service.get(Location.Ref.make({ directory: AbsolutePath.make(dir.path) }))),
  227. ),
  228. ),
  229. ),
  230. )
  231. })