config.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. export * as Config from "./config"
  2. import path from "path"
  3. import { type ParseError, parse } from "jsonc-parser"
  4. import { Context, Effect, Layer, Option, Schema } from "effect"
  5. import { Permission } from "@opencode-ai/schema/permission"
  6. import { FSUtil } from "./fs-util"
  7. import { Global } from "./global"
  8. import { Location } from "./location"
  9. import { Policy } from "./policy"
  10. import { AbsolutePath } from "./schema"
  11. import { ConfigAgent } from "./config/agent"
  12. import { ConfigAttachments } from "./config/attachments"
  13. import { ConfigCompaction } from "./config/compaction"
  14. import { ConfigCommand } from "./config/command"
  15. import { ConfigExperimental } from "./config/experimental"
  16. import { ConfigFormatter } from "./config/formatter"
  17. import { ConfigLSP } from "./config/lsp"
  18. import { ConfigMCP } from "./config/mcp"
  19. import { ConfigPlugin } from "./config/plugin"
  20. import { ConfigProvider } from "./config/provider"
  21. import { ConfigReference } from "./config/reference"
  22. import { ConfigToolOutput } from "./config/tool-output"
  23. import { ConfigWatcher } from "./config/watcher"
  24. import { ConfigV1 } from "./v1/config/config"
  25. import { ConfigMigrateV1 } from "./v1/config/migrate"
  26. export class Info extends Schema.Class<Info>("Config.Info")({
  27. $schema: Schema.optional(Schema.String).annotate({
  28. description: "JSON schema reference for configuration validation",
  29. }),
  30. shell: Schema.String.pipe(Schema.optional).annotate({
  31. description: "Default shell to use for terminal and shell tool execution",
  32. }),
  33. model: Schema.String.pipe(Schema.optional).annotate({
  34. description: "Default model to use when no session or agent model is selected",
  35. }),
  36. default_agent: Schema.String.pipe(Schema.optional).annotate({
  37. description: "Default primary agent to use when no session agent is selected",
  38. }),
  39. autoupdate: Schema.Union([Schema.Boolean, Schema.Literal("notify")])
  40. .pipe(Schema.optional)
  41. .annotate({
  42. description: "Automatically update or notify when a new version is available",
  43. }),
  44. share: Schema.Literals(["manual", "auto", "disabled"]).pipe(Schema.optional).annotate({
  45. description: "Control whether sessions may be shared manually, automatically, or not at all",
  46. }),
  47. enterprise: Schema.Struct({
  48. url: Schema.String.pipe(Schema.optional),
  49. })
  50. .pipe(Schema.optional)
  51. .annotate({
  52. description: "Enterprise sharing service configuration",
  53. }),
  54. username: Schema.String.pipe(Schema.optional).annotate({
  55. description: "Username displayed in conversations and used for telemetry identity",
  56. }),
  57. permissions: Permission.Ruleset.pipe(Schema.optional).annotate({
  58. description: "Ordered tool permission rules applied to agent tool use",
  59. }),
  60. agents: Schema.Record(Schema.String, ConfigAgent.Info).pipe(Schema.optional).annotate({
  61. description: "Named built-in agent overrides and custom agent definitions",
  62. }),
  63. snapshots: Schema.Boolean.pipe(Schema.optional).annotate({
  64. description: "Enable snapshots used for undo and revert behavior",
  65. }),
  66. watcher: ConfigWatcher.Info.pipe(Schema.optional).annotate({
  67. description: "Filesystem watcher configuration",
  68. }),
  69. formatter: ConfigFormatter.Info.pipe(Schema.optional).annotate({
  70. description: "Enable built-in formatters or configure formatter overrides",
  71. }),
  72. lsp: ConfigLSP.Info.pipe(Schema.optional).annotate({
  73. description: "Enable built-in language servers or configure server overrides",
  74. }),
  75. attachments: ConfigAttachments.Info.pipe(Schema.optional).annotate({
  76. description: "Attachment processing configuration",
  77. }),
  78. tool_output: ConfigToolOutput.Info.pipe(Schema.optional).annotate({
  79. description: "Tool output truncation thresholds",
  80. }),
  81. mcp: ConfigMCP.Info.pipe(Schema.optional).annotate({
  82. description: "MCP server configuration",
  83. }),
  84. compaction: ConfigCompaction.Info.pipe(Schema.optional).annotate({
  85. description: "Conversation compaction behavior",
  86. }),
  87. skills: Schema.String.pipe(Schema.Array, Schema.optional).annotate({
  88. description: "Additional paths or URLs to discover skills from",
  89. }),
  90. commands: Schema.Record(Schema.String, ConfigCommand.Info).pipe(Schema.optional).annotate({
  91. description: "Named slash command definitions",
  92. }),
  93. instructions: Schema.String.pipe(Schema.Array, Schema.optional).annotate({
  94. description: "Additional paths or URLs supplying ambient instructions",
  95. }),
  96. references: ConfigReference.Info.pipe(Schema.optional).annotate({
  97. description: "Named local directories or Git repositories available as external context",
  98. }),
  99. plugins: ConfigPlugin.Plugins.pipe(Schema.optional).annotate({
  100. description: "Ordered external plugin packages to load",
  101. }),
  102. experimental: ConfigExperimental.Experimental.pipe(Schema.optional),
  103. providers: Schema.Record(Schema.String, ConfigProvider.Info).pipe(Schema.optional),
  104. }) {}
  105. export class Document extends Schema.Class<Document>("Config.Document")({
  106. type: Schema.Literal("document"),
  107. path: Schema.String.pipe(Schema.optional),
  108. info: Info,
  109. }) {}
  110. export class Directory extends Schema.Class<Directory>("Config.Directory")({
  111. type: Schema.Literal("directory"),
  112. path: AbsolutePath,
  113. }) {}
  114. export type Entry = Document | Directory
  115. export function latest<K extends keyof Info>(entries: readonly Entry[], key: K): Info[K] | undefined {
  116. return entries
  117. .filter((entry): entry is Document => entry.type === "document")
  118. .findLast((entry) => entry.info[key] !== undefined)?.info[key]
  119. }
  120. export interface Interface {
  121. /** Returns location config documents and supplemental directories from lowest to highest priority. */
  122. readonly entries: () => Effect.Effect<Entry[]>
  123. }
  124. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Config") {}
  125. export const layer = Layer.effect(
  126. Service,
  127. Effect.gen(function* () {
  128. const fs = yield* FSUtil.Service
  129. const global = yield* Global.Service
  130. const location = yield* Location.Service
  131. const policy = yield* Policy.Service
  132. const names = ["config.json", "opencode.json", "opencode.jsonc"]
  133. const decodeOptions = { errors: "all", onExcessProperty: "ignore", propertyOrder: "original" } as const
  134. const decodeInfo = Schema.decodeUnknownOption(Info, decodeOptions)
  135. const decodeV1Info = Schema.decodeUnknownOption(ConfigV1.Info, decodeOptions)
  136. const loadFile = Effect.fnUntraced(function* (filepath: string) {
  137. const text = yield* fs.readFileStringSafe(filepath)
  138. if (!text) return
  139. const errors: ParseError[] = []
  140. const input: unknown = parse(text, errors, { allowTrailingComma: true })
  141. if (errors.length) return
  142. const info = Option.getOrUndefined(
  143. ConfigMigrateV1.isV1(input)
  144. ? decodeV1Info(input).pipe(Option.map(ConfigMigrateV1.migrate), Option.flatMap(decodeInfo))
  145. : decodeInfo(input),
  146. )
  147. if (!info) return
  148. return new Document({ type: "document", path: filepath, info })
  149. })
  150. const loadDirectory = Effect.fnUntraced(function* (directory: AbsolutePath) {
  151. return [
  152. ...(yield* Effect.forEach(names, (file) => loadFile(path.join(directory, file))).pipe(
  153. Effect.map((configs) => configs.filter((config): config is Document => config !== undefined)),
  154. )),
  155. new Directory({ type: "directory", path: directory }),
  156. ]
  157. })
  158. const globalDirectory = AbsolutePath.make(global.config)
  159. const locationIsGlobal = path.resolve(location.directory) === path.resolve(global.config)
  160. // Read configuration once when this location opens. Later calls reuse these
  161. // values until the location is reopened.
  162. const discovered = locationIsGlobal
  163. ? []
  164. : yield* fs
  165. .up({
  166. targets: [".opencode", ...names.toReversed()],
  167. start: location.directory,
  168. stop: location.project.directory,
  169. })
  170. .pipe(Effect.orDie)
  171. const directories = [
  172. globalDirectory,
  173. ...discovered
  174. .filter((item) => path.basename(item) === ".opencode")
  175. .toReversed()
  176. .map((directory) => AbsolutePath.make(directory)),
  177. ]
  178. // A config closer to the opened directory should win over one higher up.
  179. // Search starts nearby, so reverse the results before applying them.
  180. const directPaths = discovered.filter((item) => path.basename(item) !== ".opencode").toReversed()
  181. const direct = yield* Effect.forEach(directPaths, loadFile).pipe(
  182. Effect.orDie,
  183. Effect.map((configs) => configs.filter((config): config is Document => config !== undefined)),
  184. )
  185. const supplementary = yield* Effect.forEach(directories, loadDirectory).pipe(Effect.orDie)
  186. // Apply general settings first and more specific settings last:
  187. // global config, project files, then `.opencode` files.
  188. const configs = [...(supplementary[0] ?? []), ...direct, ...supplementary.slice(1).flat()]
  189. // Rules use the opposite order so a user-global rule can override a
  190. // repository rule. Statement order inside each file stays unchanged.
  191. yield* policy.load(
  192. configs
  193. .filter((config): config is Document => config.type === "document")
  194. .toReversed()
  195. .flatMap((config) => config.info.experimental?.policies ?? []),
  196. )
  197. return Service.of({
  198. entries: Effect.fn("Config.entries")(function* () {
  199. return configs
  200. }),
  201. })
  202. }),
  203. )
  204. export const locationLayer = layer.pipe(Layer.provideMerge(Policy.locationLayer))