config.ts 9.0 KB

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