command.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. export * as CommandV2 from "./command"
  2. import { Context, Effect, Layer, Schema } from "effect"
  3. import { castDraft, type Draft } from "immer"
  4. import { ModelV2 } from "./model"
  5. import { State } from "./state"
  6. export class Info extends Schema.Class<Info>("CommandV2.Info")({
  7. name: Schema.String,
  8. template: Schema.String,
  9. description: Schema.String.pipe(Schema.optional),
  10. agent: Schema.String.pipe(Schema.optional),
  11. model: ModelV2.Ref.pipe(Schema.optional),
  12. subtask: Schema.Boolean.pipe(Schema.optional),
  13. }) {}
  14. export type Data = {
  15. commands: Map<string, Info>
  16. }
  17. export type Editor = {
  18. list: () => readonly Info[]
  19. get: (name: string) => Info | undefined
  20. update: (name: string, update: (command: Draft<Info>) => void) => void
  21. remove: (name: string) => void
  22. }
  23. export interface Interface {
  24. readonly transform: State.Interface<Data, Editor>["transform"]
  25. readonly get: (name: string) => Effect.Effect<Info | undefined>
  26. readonly list: () => Effect.Effect<Info[]>
  27. }
  28. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Command") {}
  29. export const layer = Layer.effect(
  30. Service,
  31. Effect.sync(() => {
  32. const state = State.create<Data, Editor>({
  33. initial: () => ({ commands: new Map() }),
  34. editor: (draft) => ({
  35. list: () => Array.from(draft.commands.values()) as Info[],
  36. get: (name) => draft.commands.get(name),
  37. update: (name, update) => {
  38. const current = draft.commands.get(name) ?? castDraft(new Info({ name, template: "" }))
  39. if (!draft.commands.has(name)) draft.commands.set(name, current)
  40. update(current)
  41. current.name = name
  42. },
  43. remove: (name) => {
  44. draft.commands.delete(name)
  45. },
  46. }),
  47. })
  48. return Service.of({
  49. transform: state.transform,
  50. get: Effect.fn("CommandV2.get")(function* (name) {
  51. return state.get().commands.get(name)
  52. }),
  53. list: Effect.fn("CommandV2.list")(function* () {
  54. return Array.from(state.get().commands.values())
  55. }),
  56. })
  57. }),
  58. )
  59. export const locationLayer = layer