index.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. export * as SystemContext from "./index"
  2. import { Effect, Option, Schema } from "effect"
  3. /**
  4. * Models privileged system context as independently refreshable typed sources.
  5. *
  6. * `Source<A>` describes how to observe, compare, and render one value. `make`
  7. * closes over `A`, producing an opaque `SystemContext` that composes uniformly
  8. * with contexts built from other value types. Interpreters observe the composed
  9. * context once, then produce a durable structured
  10. * `Snapshot` alongside the exact model-visible baseline or update text.
  11. *
  12. * Returning `unavailable` means observation failed temporarily. It differs from
  13. * removing a source from the context: refresh preserves the admitted snapshot,
  14. * and replacement waits rather than silently constructing an incomplete baseline.
  15. *
  16. * @module
  17. */
  18. /** Stable namespaced identity for one independently refreshable context source. */
  19. export const Key = Schema.String.check(Schema.isPattern(/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._/-]*$/)).pipe(
  20. Schema.brand("SystemContext.Key"),
  21. )
  22. export type Key = typeof Key.Type
  23. /** Indicates that a source could not be observed without treating it as removed. */
  24. export const unavailable = Symbol.for("@opencode/SystemContext.Unavailable")
  25. export type Unavailable = typeof unavailable
  26. /** Defines one typed source before its value type is hidden by `make`. */
  27. export interface Source<A> {
  28. readonly key: Key
  29. readonly codec: Schema.Codec<A, Schema.Json, never, never>
  30. readonly load: Effect.Effect<A | Unavailable>
  31. readonly baseline: (current: A) => string
  32. readonly update: (previous: A, current: A) => string
  33. readonly removed?: (previous: A) => string
  34. }
  35. const ContextTypeId: unique symbol = Symbol.for("@opencode/SystemContext")
  36. /** Opaque carrier for composable system context sources. */
  37. export interface SystemContext {
  38. readonly [ContextTypeId]: ReadonlyArray<PackedSource>
  39. }
  40. /** Durable comparison state for one admitted source. */
  41. export const SourceSnapshot = Schema.Struct({
  42. value: Schema.Json,
  43. removed: Schema.optional(Schema.NonEmptyString),
  44. })
  45. export type SourceSnapshot = typeof SourceSnapshot.Type
  46. /** Durable structured comparison state for one active context generation. */
  47. export const Snapshot = Schema.Record(Key, SourceSnapshot)
  48. export type Snapshot = Readonly<Record<string, SourceSnapshot>>
  49. export interface Generation {
  50. readonly baseline: string
  51. readonly snapshot: Snapshot
  52. }
  53. export interface Updated {
  54. readonly _tag: "Updated"
  55. readonly text: string
  56. readonly snapshot: Snapshot
  57. }
  58. export interface ReplacementReady {
  59. readonly _tag: "ReplacementReady"
  60. readonly generation: Generation
  61. }
  62. export interface ReplacementBlocked {
  63. readonly _tag: "ReplacementBlocked"
  64. }
  65. export type ReplacementResult = ReplacementReady | ReplacementBlocked
  66. export type ReconcileResult = { readonly _tag: "Unchanged" } | Updated | ReplacementResult
  67. export class InitializationBlocked extends Schema.TaggedErrorClass<InitializationBlocked>()(
  68. "SystemContext.InitializationBlocked",
  69. { keys: Schema.Array(Key) },
  70. ) {}
  71. export class DuplicateKeyError extends Schema.TaggedErrorClass<DuplicateKeyError>()("SystemContext.DuplicateKeyError", {
  72. key: Key,
  73. }) {
  74. override get message() {
  75. return `Duplicate system context key: ${this.key}`
  76. }
  77. }
  78. interface PackedSource {
  79. readonly key: Key
  80. readonly load: Effect.Effect<Loaded | Unavailable>
  81. }
  82. interface Loaded {
  83. readonly baseline: () => Rendered
  84. readonly compare: (previous: Schema.Json) => Compared
  85. }
  86. interface Rendered {
  87. readonly text: string
  88. readonly snapshot: SourceSnapshot
  89. }
  90. type Compared =
  91. | { readonly _tag: "Incompatible" }
  92. | { readonly _tag: "Unchanged" }
  93. | { readonly _tag: "Updated"; readonly render: () => Rendered }
  94. interface AvailableEntry extends Loaded {
  95. readonly _tag: "Available"
  96. readonly key: Key
  97. }
  98. interface UnavailableEntry {
  99. readonly _tag: "Unavailable"
  100. readonly key: Key
  101. }
  102. type Entry = AvailableEntry | UnavailableEntry
  103. /** The identity context. */
  104. export const empty = context([])
  105. /** Closes a typed source into a context that composes with differently typed sources. */
  106. export function make<A>(source: Source<A>): SystemContext {
  107. const decode = Schema.decodeUnknownOption(source.codec)
  108. const encode = Schema.encodeSync(source.codec)
  109. const equivalent = Schema.toEquivalence(source.codec)
  110. return context([
  111. {
  112. key: source.key,
  113. load: source.load.pipe(
  114. Effect.map((value) => {
  115. if (isUnavailable(value)) return value
  116. const snapshot = (): SourceSnapshot => ({
  117. value: encode(value),
  118. ...(source.removed ? { removed: requireText(source.key, "removal", source.removed(value)) } : {}),
  119. })
  120. return {
  121. baseline: (): Rendered => ({
  122. text: requireText(source.key, "baseline", source.baseline(value)),
  123. snapshot: snapshot(),
  124. }),
  125. compare: (previous): Compared =>
  126. Option.match(decode(previous), {
  127. onNone: (): Compared => ({ _tag: "Incompatible" }),
  128. onSome: (decoded): Compared =>
  129. equivalent(decoded, value)
  130. ? { _tag: "Unchanged" }
  131. : {
  132. _tag: "Updated",
  133. render: () => ({
  134. text: requireText(source.key, "update", source.update(decoded, value)),
  135. snapshot: snapshot(),
  136. }),
  137. },
  138. }),
  139. }
  140. }),
  141. ),
  142. },
  143. ])
  144. }
  145. /** Combines contexts in order and rejects duplicate source keys immediately. */
  146. export function combine(values: ReadonlyArray<SystemContext>): SystemContext {
  147. const sources = values.flatMap((value) => value[ContextTypeId])
  148. assertUniqueKeys(sources)
  149. return context(sources)
  150. }
  151. const observe = (value: SystemContext) =>
  152. Effect.forEach(
  153. value[ContextTypeId],
  154. (source) =>
  155. source.load.pipe(
  156. Effect.map(
  157. (result): Entry =>
  158. result === unavailable
  159. ? { _tag: "Unavailable", key: source.key }
  160. : { _tag: "Available", key: source.key, ...result },
  161. ),
  162. ),
  163. { concurrency: "unbounded" },
  164. )
  165. /** Creates the immutable baseline and durable snapshot for a new generation. */
  166. export function initialize(value: SystemContext): Effect.Effect<Generation, InitializationBlocked> {
  167. return observe(value).pipe(
  168. Effect.flatMap((entries) => {
  169. const unavailable = entries.flatMap((entry) => (entry._tag === "Unavailable" ? [entry.key] : []))
  170. if (unavailable.length > 0) return new InitializationBlocked({ keys: unavailable })
  171. return Effect.succeed(initializeObservation(entries))
  172. }),
  173. )
  174. }
  175. function initializeObservation(entries: ReadonlyArray<Entry>): Generation {
  176. const available = entries.filter((entry): entry is AvailableEntry => entry._tag === "Available")
  177. const rendered = available.map((entry) => [entry.key, entry.baseline()] as const)
  178. return {
  179. baseline: render(rendered.map(([, result]) => result.text)),
  180. snapshot: Object.fromEntries(rendered.map(([key, result]) => [key, result.snapshot])),
  181. }
  182. }
  183. /** Reconciles current source values with one active generation. */
  184. export function reconcile(value: SystemContext, previous: Snapshot): Effect.Effect<ReconcileResult> {
  185. return observe(value).pipe(
  186. Effect.map((entries): ReconcileResult => {
  187. const result = reconcileObservation(entries, previous)
  188. if (result._tag === "Unchanged" || result._tag === "Updated") return result
  189. return replaceObservation(entries, previous)
  190. }),
  191. )
  192. }
  193. function reconcileObservation(
  194. entries: ReadonlyArray<Entry>,
  195. previous: Snapshot,
  196. ): { readonly _tag: "Unchanged" } | Updated | { readonly _tag: "Replace" } {
  197. const keys = new Set(entries.map((entry) => entry.key))
  198. const comparisons = new Map<Key, Compared>()
  199. for (const entry of entries) {
  200. if (entry._tag === "Unavailable") continue
  201. const stored = getSnapshot(previous, entry.key)
  202. if (!stored) continue
  203. const compared = entry.compare(stored.value)
  204. if (compared._tag === "Incompatible") return { _tag: "Replace" }
  205. comparisons.set(entry.key, compared)
  206. }
  207. for (const key of Object.keys(previous).sort()) {
  208. if (keys.has(Key.make(key))) continue
  209. if (previous[key].removed === undefined) return { _tag: "Replace" }
  210. }
  211. const snapshot: Record<string, SourceSnapshot> = {}
  212. const updates: string[] = []
  213. for (const entry of entries) {
  214. const stored = getSnapshot(previous, entry.key)
  215. if (entry._tag === "Unavailable") {
  216. if (stored) snapshot[entry.key] = stored
  217. continue
  218. }
  219. if (!stored) {
  220. const rendered = entry.baseline()
  221. updates.push(rendered.text)
  222. snapshot[entry.key] = rendered.snapshot
  223. continue
  224. }
  225. const compared = comparisons.get(entry.key)
  226. if (!compared || compared._tag === "Incompatible")
  227. throw new Error(`Missing comparison for system context source ${entry.key}`)
  228. if (compared._tag === "Unchanged") {
  229. snapshot[entry.key] = stored
  230. continue
  231. }
  232. const rendered = compared.render()
  233. updates.push(rendered.text)
  234. snapshot[entry.key] = rendered.snapshot
  235. }
  236. for (const key of Object.keys(previous).sort()) {
  237. if (keys.has(Key.make(key))) continue
  238. const removed = previous[key].removed
  239. if (removed === undefined) throw new Error(`Missing removal rendering for system context source ${key}`)
  240. updates.push(removed)
  241. }
  242. if (updates.length === 0) return { _tag: "Unchanged" }
  243. return { _tag: "Updated", text: render(updates), snapshot }
  244. }
  245. /** Creates a complete replacement generation or blocks while admitted context is unavailable. */
  246. export function replace(value: SystemContext, previous: Snapshot): Effect.Effect<ReplacementResult> {
  247. return observe(value).pipe(Effect.map((entries) => replaceObservation(entries, previous)))
  248. }
  249. function replaceObservation(entries: ReadonlyArray<Entry>, previous: Snapshot): ReplacementResult {
  250. if (entries.some((entry) => entry._tag === "Unavailable" && getSnapshot(previous, entry.key) !== undefined))
  251. return { _tag: "ReplacementBlocked" }
  252. return { _tag: "ReplacementReady", generation: initializeObservation(entries) }
  253. }
  254. function context(sources: ReadonlyArray<PackedSource>): SystemContext {
  255. return { [ContextTypeId]: sources }
  256. }
  257. function render(parts: ReadonlyArray<string>) {
  258. return parts.join("\n\n")
  259. }
  260. function getSnapshot(snapshot: Snapshot, key: Key) {
  261. return Object.hasOwn(snapshot, key) ? snapshot[key] : undefined
  262. }
  263. function isUnavailable(value: unknown): value is Unavailable {
  264. return value === unavailable
  265. }
  266. function requireText(key: Key, kind: string, text: string) {
  267. if (text.length === 0) throw new Error(`System context source ${key} rendered an empty ${kind}`)
  268. return text
  269. }
  270. function assertUniqueKeys(sources: ReadonlyArray<PackedSource>) {
  271. const keys = new Set<Key>()
  272. for (const source of sources) {
  273. if (keys.has(source.key)) throw new DuplicateKeyError({ key: source.key })
  274. keys.add(source.key)
  275. }
  276. }