tool-registry.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. export * as ToolRegistry from "./tool-registry"
  2. import {
  3. Tool,
  4. ToolFailure,
  5. ToolOutput,
  6. ToolResultValue as ToolResult,
  7. type Tool as TypedTool,
  8. type ToolCall,
  9. type ToolResultValue,
  10. type ToolSchema,
  11. type ToolSettlement,
  12. } from "@opencode-ai/llm"
  13. import { Context, Effect, Layer, Schema, Scope } from "effect"
  14. import { castDraft, enableMapSet } from "immer"
  15. import { PermissionV2 } from "./permission"
  16. import { State } from "./state"
  17. import { SessionSchema } from "./session/schema"
  18. import type { SessionV2 } from "./session"
  19. export type ExecuteInput = {
  20. readonly sessionID: SessionSchema.ID
  21. readonly call: ToolCall
  22. }
  23. /**
  24. * Narrow cross-cutting context for one registry invocation. Leaf tools retain
  25. * ownership of sequence-sensitive policy decisions; the registry only binds
  26. * identity and shared helper behavior consistently.
  27. *
  28. * TODO: Add `source` when the runner can pass the durable owning assistant
  29. * message ID alongside the call ID. Do not infer it from the tool call alone.
  30. * TODO: Add cancellation and progress only when the runner exposes a real
  31. * signal and durable/live progress sink.
  32. */
  33. export type Invocation = ExecuteInput & {
  34. readonly source?: PermissionV2.Source
  35. readonly assertPermission: (
  36. input: Omit<PermissionV2.AssertInput, "sessionID" | "source">,
  37. ) => Effect.Effect<void, PermissionV2.Error | SessionV2.NotFoundError>
  38. }
  39. /** Kept as the leaf entry input name for backwards-compatible execute usage. */
  40. export type AuthorizeInput<Parameters = unknown> = Invocation & {
  41. readonly parameters: Parameters
  42. }
  43. export type Entry<
  44. Parameters extends ToolSchema<any> = ToolSchema<any>,
  45. Success extends ToolSchema<any> = ToolSchema<any>,
  46. > = {
  47. readonly tool: TypedTool<Parameters, Success>
  48. readonly authorize?: (input: AuthorizeInput<Schema.Schema.Type<Parameters>>) => Effect.Effect<void, ToolFailure>
  49. readonly execute?: (
  50. input: AuthorizeInput<Schema.Schema.Type<Parameters>>,
  51. ) => Effect.Effect<Schema.Schema.Type<Success>, ToolFailure>
  52. }
  53. type Data = {
  54. readonly entries: Map<string, Entry>
  55. }
  56. export type Editor = {
  57. readonly list: () => ReadonlyArray<readonly [string, Entry]>
  58. readonly get: (name: string) => Entry | undefined
  59. readonly set: <Parameters extends ToolSchema<any>, Success extends ToolSchema<any>>(
  60. name: string,
  61. entry: Entry<Parameters, Success>,
  62. ) => void
  63. readonly remove: (name: string) => void
  64. }
  65. export interface Interface {
  66. readonly transform: State.Interface<Data, Editor>["transform"]
  67. readonly contribute: (update: State.Transform<Editor>) => Effect.Effect<void, never, Scope.Scope>
  68. readonly definitions: () => Effect.Effect<ReadonlyArray<ReturnType<typeof Tool.toDefinitions>[number]>>
  69. readonly execute: (input: ExecuteInput) => Effect.Effect<ToolResultValue>
  70. readonly settle: (input: ExecuteInput) => Effect.Effect<ToolSettlement>
  71. }
  72. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/ToolRegistry") {}
  73. enableMapSet()
  74. export const layer = Layer.effect(
  75. Service,
  76. Effect.gen(function* () {
  77. const permission = yield* PermissionV2.Service
  78. const state = State.create<Data, Editor>({
  79. initial: () => ({ entries: new Map() }),
  80. editor: (draft) => ({
  81. list: () => Array.from(draft.entries.entries()) as Array<[string, Entry]>,
  82. get: (name) => draft.entries.get(name) as Entry | undefined,
  83. set: (name, entry) => {
  84. draft.entries.set(
  85. name,
  86. castDraft(entry) as typeof draft.entries extends Map<string, infer Value> ? Value : never,
  87. )
  88. },
  89. remove: (name) => {
  90. draft.entries.delete(name)
  91. },
  92. }),
  93. })
  94. const definitions = Effect.fn("ToolRegistry.definitions")(function* () {
  95. return Tool.toDefinitions(
  96. Object.fromEntries(Array.from(state.get().entries, ([name, entry]) => [name, entry.tool])),
  97. )
  98. })
  99. const invocation = (input: ExecuteInput): Invocation => ({
  100. ...input,
  101. // Source needs the durable owning assistant message ID, which the registry does not receive yet.
  102. assertPermission: (request) => permission.assert({ ...request, sessionID: input.sessionID }),
  103. })
  104. const settle = Effect.fn("ToolRegistry.settle")(function* (input: ExecuteInput) {
  105. const entry = state.get().entries.get(input.call.name)
  106. if (!entry) return { result: { type: "error" as const, value: `Unknown tool: ${input.call.name}` } }
  107. if (!entry.execute && !entry.tool.execute)
  108. return { result: { type: "error" as const, value: `Tool has no execute handler: ${input.call.name}` } }
  109. return yield* entry.tool._decode(input.call.input).pipe(
  110. Effect.mapError((error) => new ToolFailure({ message: `Invalid tool input: ${error.message}` })),
  111. Effect.flatMap((parameters) => {
  112. const context = { ...invocation(input), parameters }
  113. const execute =
  114. entry.execute?.(context) ?? entry.tool.execute!(parameters, { id: input.call.id, name: input.call.name })
  115. return (
  116. entry.authorize === undefined ? execute : entry.authorize(context).pipe(Effect.andThen(execute))
  117. ).pipe(
  118. Effect.flatMap((value) =>
  119. entry.tool._encode(value).pipe(
  120. Effect.mapError(
  121. (error) =>
  122. new ToolFailure({
  123. message: `Tool returned an invalid value for its success schema: ${error.message}`,
  124. }),
  125. ),
  126. ),
  127. ),
  128. Effect.map((value): ToolSettlement => {
  129. if (entry.tool._legacyResult && ToolResult.is(value))
  130. return { result: value, output: ToolOutput.fromResultValue(value) }
  131. const output = entry.tool._project(parameters, input.call.id, value)
  132. const result = ToolOutput.toResultValue(output)
  133. return result.type === "error" ? { result } : { result, output }
  134. }),
  135. )
  136. }),
  137. Effect.catchTag("LLM.ToolFailure", (failure) =>
  138. Effect.succeed({ result: { type: "error" as const, value: failure.message } }),
  139. ),
  140. )
  141. })
  142. const execute = Effect.fn("ToolRegistry.execute")(function* (input: ExecuteInput) {
  143. return (yield* settle(input)).result
  144. })
  145. return Service.of({
  146. transform: state.transform,
  147. contribute: Effect.fn("ToolRegistry.contribute")(function* (update) {
  148. const transform = yield* state.transform()
  149. yield* transform(update)
  150. }),
  151. definitions,
  152. execute,
  153. settle,
  154. })
  155. }),
  156. )