index.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /**
  2. * Host Remote owner for the configuration surfaces over the settings-domain
  3. * seams. Two namespaces: `settings`, the redacted reads and writes of
  4. * `ctx.settings`, owned by the class below; and `credentials`, mounted from
  5. * here as its own plugin.
  6. *
  7. * @module @deepseek-ai/dsh-api-settings-controller
  8. */
  9. import { dirname } from 'node:path'
  10. import { Context } from '@deepseek-ai/cordis'
  11. import Schema from '@deepseek-ai/schemastery'
  12. // Type-only: resolves the `agentPresets` Context augmentation this controller reads.
  13. import type {} from '@deepseek-ai/dsh-agent-presets'
  14. import {
  15. canOpenNativePath,
  16. openNativePath,
  17. openNativeTextFile,
  18. } from '@deepseek-ai/dsh-native-command'
  19. import type { SettingsDescriptor, SettingsPathOp, SettingsProvider } from '@deepseek-ai/dsh-settings'
  20. import type {
  21. SettingsDescribeValue, SettingsNamespaceView, SettingsPathOpView,
  22. } from '@deepseek-ai/dsh-settings/types'
  23. import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
  24. import type { JsonValue } from '@deepseek-ai/dsh-util-values'
  25. import { z } from 'zod'
  26. import { CredentialsController } from './credentials.ts'
  27. import type { AgentPresetDirectoryOpenValue, SettingsDocumentOpenValue } from './types.ts'
  28. export { CredentialsController } from './credentials.ts'
  29. export type * from './types.ts'
  30. const settingsNamespaceRequestSchema = z.object({ ns: z.string().min(1) })
  31. /** Native document-opening policy. */
  32. export interface Config {
  33. /** Override platform desktop-opener detection. */
  34. readonly nativeOpen?: boolean
  35. }
  36. /** Read abort state afresh after an awaited provider or opener call. */
  37. function isAborted(signal: AbortSignal): boolean {
  38. return signal.aborted
  39. }
  40. /** Host integrations replaceable by direct unit tests. */
  41. export interface SettingsControllerInternals {
  42. readonly openPath?: (path: string, signal: AbortSignal) => Promise<void>
  43. readonly openTextFile?: (path: string, signal: AbortSignal) => Promise<void>
  44. readonly canOpenPath?: () => boolean
  45. }
  46. /**
  47. * Project one redacted descriptor onto its wire view, field by field. The
  48. * Gateway returns a business result without decoding it, so a provider whose
  49. * descriptor carried extra enumerable properties would otherwise serialize them
  50. * to the caller.
  51. * @param descriptor - one descriptor read under `redactSecrets`.
  52. * @returns the same facts with nothing else attached.
  53. */
  54. function namespaceView(descriptor: SettingsDescriptor): SettingsNamespaceView {
  55. return {
  56. ns: String(descriptor.ns),
  57. schema: descriptor.schema as JsonValue,
  58. value: descriptor.value as JsonValue,
  59. ...descriptor.base === undefined ? {} : { base: descriptor.base as JsonValue },
  60. ...descriptor.user === undefined ? {} : { user: descriptor.user as JsonValue },
  61. applies: descriptor.applies,
  62. secrets: (descriptor.secrets ?? []).map(secret => ({ path: [...secret.path], set: secret.set })),
  63. revision: descriptor.revision,
  64. }
  65. }
  66. declare module '@deepseek-ai/cordis' {
  67. interface Context {
  68. /** Host owner of the `settings` Remote namespace. */
  69. settingsController: SettingsController
  70. }
  71. }
  72. /**
  73. * Host service backing the generated `ctx.remote.settings` namespace. Every
  74. * remote read uses `redactSecrets: true`, so a `role('secret')` field cannot
  75. * ride a response. Writes expose the settings service's merge, replacement,
  76. * and path-addressed operations, and classify every provider refusal as
  77. * `settings/conflict` or `settings/rejected` with the service's message.
  78. */
  79. export class SettingsController extends TypertRemoteService {
  80. static Config: Schema<Config> = Schema.object({ nativeOpen: Schema.boolean() })
  81. private readonly openPath: (path: string, signal: AbortSignal) => Promise<void>
  82. private readonly openTextFile: (path: string, signal: AbortSignal) => Promise<void>
  83. private readonly canOpenPath: () => boolean
  84. /**
  85. * Register the settings namespace and mount the credentials namespace beside
  86. * it. Both namespaces stay registered when a provider is absent so calls can
  87. * return the configuration API's actionable missing-provider diagnostic.
  88. * @param ctx - Host context where settings and credential providers may be mounted.
  89. */
  90. constructor(ctx: Context, config: Config = {}, internals: SettingsControllerInternals = {}) {
  91. super(ctx, 'settingsController', { namespace: 'settings' })
  92. this.openPath = internals.openPath ?? openNativePath
  93. this.openTextFile = internals.openTextFile ?? openNativeTextFile
  94. this.canOpenPath = internals.canOpenPath
  95. ?? (() => config.nativeOpen ?? (internals.openPath !== undefined || canOpenNativePath()))
  96. ctx.plugin(CredentialsController)
  97. }
  98. /**
  99. * Describe every registered namespace for a configuration page: redacted
  100. * layered values plus the serialized schema the page renders its form from.
  101. * @returns provider writability, local-document presence, and one view per namespace.
  102. * @throws RemoteError when no settings provider is mounted.
  103. */
  104. @Remote
  105. describe(): SettingsDescribeValue {
  106. const settings = this.provider()
  107. return {
  108. writable: settings.writable,
  109. hasDocument: settings.documentPath !== undefined,
  110. namespaces: settings.describe({ redactSecrets: true }).map(namespaceView),
  111. }
  112. }
  113. /**
  114. * Report whether this deployment can open an authored Agent preset directory natively.
  115. * @returns true when the matching open operation is available.
  116. */
  117. @Remote
  118. canOpenAgentPresetDirectory(): boolean {
  119. return this.canOpenPath()
  120. }
  121. /**
  122. * Merge a patch into one namespace's stored user section.
  123. * @param ns - namespace key to write.
  124. * @param patch - fields to merge into the user section.
  125. * @param expectedRevision - revision the caller read; `undefined` writes unconditionally.
  126. * @returns the namespace's redacted view after the write.
  127. * @throws RemoteError when the request is invalid, no provider is mounted, or the provider refuses the write.
  128. */
  129. @Remote
  130. update(
  131. ns: string,
  132. patch: Record<string, JsonValue>,
  133. expectedRevision: number | undefined,
  134. ): Promise<SettingsNamespaceView> {
  135. return this.write(ns, 'update', patch, expectedRevision)
  136. }
  137. /**
  138. * Replace one namespace's stored user section wholesale.
  139. * @param ns - namespace key to write.
  140. * @param section - complete replacement user section.
  141. * @param expectedRevision - revision the caller read; `undefined` writes unconditionally.
  142. * @returns the namespace's redacted view after the write.
  143. * @throws RemoteError when the request is invalid, no provider is mounted, or the provider refuses the write.
  144. */
  145. @Remote
  146. replace(
  147. ns: string,
  148. section: Record<string, JsonValue>,
  149. expectedRevision: number | undefined,
  150. ): Promise<SettingsNamespaceView> {
  151. return this.write(ns, 'replace', section, expectedRevision)
  152. }
  153. /**
  154. * Apply path-addressed edits to one namespace's user section, resolved against
  155. * the section as stored rather than against whatever the caller last read,
  156. * then answer with that namespace's new redacted view.
  157. * @param ns - namespace key to write.
  158. * @param ops - the edits to apply, in order.
  159. * @param expectedRevision - revision the caller read; `undefined` writes unconditionally.
  160. * @returns the namespace's redacted view after the write.
  161. * @throws RemoteError when the request is invalid, no provider is mounted, or the provider refuses the write.
  162. */
  163. @Remote
  164. async mutate(
  165. ns: string,
  166. ops: SettingsPathOpView[],
  167. expectedRevision: number | undefined,
  168. ): Promise<SettingsNamespaceView> {
  169. return this.write(ns, 'mutate', ops, expectedRevision)
  170. }
  171. /**
  172. * Materialize the provider-owned settings document and open it in a native text editor.
  173. * @param signal - caller lifetime; abort terminates preparation or the native command.
  174. * @returns confirmation after the native opener accepts the document.
  175. * @throws RemoteError when no document exists, preparation fails, or opening fails.
  176. */
  177. @Remote
  178. async openSettingsDocument(signal: AbortSignal): Promise<SettingsDocumentOpenValue> {
  179. const settings = this.provider()
  180. if (isAborted(signal)) throw new RemoteError('gateway/cancelled', 'settings document open was aborted', {})
  181. let path: string | undefined
  182. try {
  183. path = await settings.prepareDocument()
  184. } catch (error: unknown) {
  185. if (isAborted(signal)) throw new RemoteError('gateway/cancelled', 'settings document preparation was aborted', {})
  186. throw new RemoteError('gateway/internal', `settings document preparation failed: ${messageOf(error)}`, {}, { cause: error })
  187. }
  188. if (path === undefined) {
  189. throw new RemoteError('gateway/internal', 'settings provider has no local document to open', {})
  190. }
  191. if (isAborted(signal)) throw new RemoteError('gateway/cancelled', 'settings document open was aborted', {})
  192. try {
  193. await this.openTextFile(path, signal)
  194. return { opened: true }
  195. } catch (error: unknown) {
  196. if (isAborted(signal)) throw new RemoteError('gateway/cancelled', 'settings document open was aborted', {})
  197. throw new RemoteError('gateway/internal', `path open failed: ${messageOf(error)}`, {}, { cause: error })
  198. }
  199. }
  200. /**
  201. * Open one user-authored Agent preset directory or return its path when no native opener exists.
  202. * @param agentPreset - preset id resolved against Host-owned roots.
  203. * @param signal - caller lifetime; abort terminates the native command.
  204. * @returns an opened confirmation or the resolved directory for text display.
  205. * @throws RemoteError when the preset is missing, read-only, invalid, or cannot be opened.
  206. */
  207. @Remote
  208. async openAgentPresetDirectory(
  209. agentPreset: string,
  210. signal: AbortSignal,
  211. ): Promise<AgentPresetDirectoryOpenValue> {
  212. if (agentPreset.length === 0) {
  213. throw new RemoteError('gateway/bad-request', 'agent preset id must not be empty', {})
  214. }
  215. const presets = this.ctx.get('agentPresets')
  216. if (presets === undefined) {
  217. throw new RemoteError(
  218. 'agent-preset/not-found',
  219. 'this deployment composes no agent presets',
  220. { agentPreset, available: [] },
  221. )
  222. }
  223. const preset = await presets.resolve(agentPreset)
  224. if (preset.trust !== 'user') {
  225. throw new RemoteError(
  226. 'agent-preset/read-only',
  227. `agent-presets: preset "${preset.id}" cannot be written: it ships with the deployment`,
  228. { agentPreset: preset.id, reason: 'it ships with the deployment' },
  229. )
  230. }
  231. const directory = dirname(preset.path)
  232. if (!this.canOpenPath()) return { opened: false, path: directory }
  233. try {
  234. await this.openPath(directory, signal)
  235. return { opened: true }
  236. } catch (error: unknown) {
  237. if (signal.aborted) throw new RemoteError('gateway/cancelled', 'path open was aborted', {})
  238. throw new RemoteError('gateway/internal', `path open failed: ${messageOf(error)}`, {}, { cause: error })
  239. }
  240. }
  241. private async write(
  242. ns: string,
  243. mode: 'update' | 'replace' | 'mutate',
  244. input: Record<string, JsonValue> | SettingsPathOpView[],
  245. expectedRevision: number | undefined,
  246. ): Promise<SettingsNamespaceView> {
  247. const parsed = settingsNamespaceRequestSchema.safeParse({ ns })
  248. if (!parsed.success) {
  249. throw new RemoteError('gateway/bad-request', `invalid payload for settings.${mode}`, { issues: parsed.error.issues })
  250. }
  251. const settings = this.provider()
  252. const namespace = parsed.data.ns
  253. try {
  254. if (mode === 'update') await settings.update(namespace, input, expectedRevision)
  255. else if (mode === 'replace') await settings.replace(namespace, input, expectedRevision)
  256. else await settings.mutate(namespace, input as SettingsPathOp[], expectedRevision)
  257. } catch (error: unknown) {
  258. throw rejected(ns, error)
  259. }
  260. const descriptor = settings.describe({ redactSecrets: true }).find(candidate => candidate.ns === namespace)
  261. if (descriptor === undefined) {
  262. // The write committed but the namespace vanished before this read: only a
  263. // concurrent registrant disposal can produce it.
  264. throw new RemoteError('gateway/internal', `settings namespace "${ns}" was disposed after the ${mode}`, {})
  265. }
  266. return namespaceView(descriptor)
  267. }
  268. /** Resolve the optional provider or report how to supply it. */
  269. private provider(): SettingsProvider {
  270. const settings = this.ctx.get('settings')
  271. if (settings === undefined) {
  272. throw new RemoteError(
  273. 'gateway/internal',
  274. 'settings service is absent: this deployment does not mount a settings provider (e.g. @deepseek-ai/dsh-settings-file) in its composition',
  275. {},
  276. )
  277. }
  278. return settings
  279. }
  280. }
  281. function messageOf(error: unknown): string {
  282. return error instanceof Error ? error.message : String(error)
  283. }
  284. interface SettingsConflict {
  285. readonly code: 'SETTINGS_CONFLICT'
  286. readonly message: string
  287. readonly expected: number
  288. readonly actual: number
  289. }
  290. function settingsConflictOf(error: unknown): SettingsConflict | undefined {
  291. if (typeof error !== 'object' || error === null) return undefined
  292. if (Reflect.get(error, 'code') !== 'SETTINGS_CONFLICT'
  293. || typeof Reflect.get(error, 'message') !== 'string'
  294. || typeof Reflect.get(error, 'expected') !== 'number'
  295. || typeof Reflect.get(error, 'actual') !== 'number') return undefined
  296. return error as SettingsConflict
  297. }
  298. /**
  299. * Classify one seam refusal. A stale writer is its own outcome, not a malformed
  300. * request: the client must re-read and re-apply rather than treat the write as
  301. * invalid.
  302. * @param ns - the namespace the write addressed.
  303. * @param error - whatever the seam threw.
  304. * @returns the failure to raise for that refusal.
  305. */
  306. function rejected(ns: string, error: unknown): RemoteError {
  307. const conflict = settingsConflictOf(error)
  308. if (conflict !== undefined) {
  309. return new RemoteError(
  310. 'settings/conflict',
  311. conflict.message,
  312. { ns, expected: conflict.expected, actual: conflict.actual },
  313. { cause: error },
  314. )
  315. }
  316. return new RemoteError('settings/rejected', messageOf(error), { ns }, { cause: error })
  317. }
  318. export default SettingsController