config.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 { PermissionSchema } from "./permission/schema"
  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. autoupdate: Schema.Union([Schema.Boolean, Schema.Literal("notify")])
  37. .pipe(Schema.optional)
  38. .annotate({
  39. description: "Automatically update or notify when a new version is available",
  40. }),
  41. share: Schema.Literals(["manual", "auto", "disabled"]).pipe(Schema.optional).annotate({
  42. description: "Control whether sessions may be shared manually, automatically, or not at all",
  43. }),
  44. enterprise: Schema.Struct({
  45. url: Schema.String.pipe(Schema.optional),
  46. })
  47. .pipe(Schema.optional)
  48. .annotate({
  49. description: "Enterprise sharing service configuration",
  50. }),
  51. username: Schema.String.pipe(Schema.optional).annotate({
  52. description: "Username displayed in conversations and used for telemetry identity",
  53. }),
  54. permissions: PermissionSchema.Ruleset.pipe(Schema.optional).annotate({
  55. description: "Ordered tool permission rules applied to agent tool use",
  56. }),
  57. agents: Schema.Record(Schema.String, ConfigAgent.Info).pipe(Schema.optional).annotate({
  58. description: "Named built-in agent overrides and custom agent definitions",
  59. }),
  60. snapshots: Schema.Boolean.pipe(Schema.optional).annotate({
  61. description: "Enable snapshots used for undo and revert behavior",
  62. }),
  63. watcher: ConfigWatcher.Info.pipe(Schema.optional).annotate({
  64. description: "Filesystem watcher configuration",
  65. }),
  66. formatter: ConfigFormatter.Info.pipe(Schema.optional).annotate({
  67. description: "Enable built-in formatters or configure formatter overrides",
  68. }),
  69. lsp: ConfigLSP.Info.pipe(Schema.optional).annotate({
  70. description: "Enable built-in language servers or configure server overrides",
  71. }),
  72. attachments: ConfigAttachments.Info.pipe(Schema.optional).annotate({
  73. description: "Attachment processing configuration",
  74. }),
  75. tool_output: ConfigToolOutput.Info.pipe(Schema.optional).annotate({
  76. description: "Tool output truncation thresholds",
  77. }),
  78. mcp: ConfigMCP.Info.pipe(Schema.optional).annotate({
  79. description: "MCP server configuration",
  80. }),
  81. compaction: ConfigCompaction.Info.pipe(Schema.optional).annotate({
  82. description: "Conversation compaction behavior",
  83. }),
  84. skills: Schema.String.pipe(Schema.Array, Schema.optional).annotate({
  85. description: "Additional paths or URLs to discover skills from",
  86. }),
  87. commands: Schema.Record(Schema.String, ConfigCommand.Info).pipe(Schema.optional).annotate({
  88. description: "Named slash command definitions",
  89. }),
  90. instructions: Schema.String.pipe(Schema.Array, Schema.optional).annotate({
  91. description: "Additional paths or URLs supplying ambient instructions",
  92. }),
  93. references: ConfigReference.Info.pipe(Schema.optional).annotate({
  94. description: "Named local directories or Git repositories available as external context",
  95. }),
  96. plugins: ConfigPlugin.Plugins.pipe(Schema.optional).annotate({
  97. description: "Ordered external plugin packages to load",
  98. }),
  99. experimental: ConfigExperimental.Experimental.pipe(Schema.optional),
  100. providers: Schema.Record(Schema.String, ConfigProvider.Info).pipe(Schema.optional),
  101. }) {}
  102. export class Document extends Schema.Class<Document>("Config.Document")({
  103. type: Schema.Literal("document"),
  104. path: Schema.String.pipe(Schema.optional),
  105. info: Info,
  106. }) {}
  107. export class Directory extends Schema.Class<Directory>("Config.Directory")({
  108. type: Schema.Literal("directory"),
  109. path: AbsolutePath,
  110. }) {}
  111. export type Entry = Document | Directory
  112. export interface Interface {
  113. /** Returns location config documents and supplemental directories from lowest to highest priority. */
  114. readonly entries: () => Effect.Effect<Entry[]>
  115. }
  116. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Config") {}
  117. export const layer = Layer.effect(
  118. Service,
  119. Effect.gen(function* () {
  120. const fs = yield* FSUtil.Service
  121. const global = yield* Global.Service
  122. const location = yield* Location.Service
  123. const policy = yield* Policy.Service
  124. const names = ["config.json", "opencode.json", "opencode.jsonc"]
  125. const loadFile = Effect.fnUntraced(function* (filepath: string) {
  126. const text = yield* fs.readFileStringSafe(filepath)
  127. if (!text) return
  128. const errors: ParseError[] = []
  129. const input: unknown = parse(text, errors, { allowTrailingComma: true })
  130. if (errors.length) return
  131. const decoded = ConfigMigrateV1.isV1(input)
  132. ? Option.map(
  133. Schema.decodeUnknownOption(ConfigV1.Info)(input, {
  134. errors: "all",
  135. onExcessProperty: "ignore",
  136. propertyOrder: "original",
  137. }),
  138. ConfigMigrateV1.migrate,
  139. )
  140. : Option.some(input)
  141. const info = Option.getOrUndefined(
  142. Option.flatMap(
  143. decoded,
  144. Schema.decodeUnknownOption(Info, { errors: "all", onExcessProperty: "ignore", propertyOrder: "original" }),
  145. ),
  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))