application-tools.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. export * as ApplicationTools from "./application-tools"
  2. import { Context, Effect, Layer, Scope } from "effect"
  3. import { State } from "../state"
  4. import { Tool } from "./tool"
  5. type Data = {
  6. readonly entries: Map<string, Entry>
  7. }
  8. type Draft = {
  9. readonly set: (name: string, entry: Entry) => void
  10. }
  11. export interface Entry {
  12. readonly identity: object
  13. readonly tool: Tool.AnyTool
  14. }
  15. export interface Interface {
  16. readonly register: (
  17. tools: Readonly<Record<string, Tool.AnyTool>>,
  18. ) => Effect.Effect<void, Tool.RegistrationError, Scope.Scope>
  19. readonly entries: () => ReadonlyMap<string, Entry>
  20. }
  21. export class Service extends Context.Service<Service, Interface>()("@opencode/ApplicationTools") {}
  22. export const layer = Layer.effect(
  23. Service,
  24. Effect.gen(function* () {
  25. const state = State.create<Data, Draft>({
  26. initial: () => ({ entries: new Map() }),
  27. draft: (draft) => ({
  28. set: (name, tool) => {
  29. draft.entries.set(name, tool)
  30. },
  31. }),
  32. })
  33. return Service.of({
  34. register: Effect.fn("ApplicationTools.register")(function* (tools) {
  35. const entries = Object.entries(tools)
  36. if (entries.length === 0) return
  37. yield* Effect.forEach(entries, ([name]) => Tool.validateName(name), { discard: true })
  38. const registrations = entries.map(([name, tool]) => [name, { identity: {}, tool }] as const)
  39. yield* state.transform((draft) => {
  40. for (const [name, entry] of registrations) draft.set(name, entry)
  41. })
  42. }),
  43. entries: () => state.get().entries,
  44. })
  45. }),
  46. )