index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /**
  2. * Workspace instruction loader for AGENTS.md-compatible files.
  3. *
  4. * Baseline instructions enter durable context before the first request; successful fs
  5. * tool touches project nested, changed, and removed instructions into the inbox.
  6. * Plugin lifecycle reads use the optional `ctx.fs` provider, so providerless products
  7. * mount it as a no-op.
  8. *
  9. * @module @deepseek-ai/dsh-workspace-context
  10. */
  11. import type { Context } from '@deepseek-ai/cordis'
  12. import { isDeepStrictEqual } from 'node:util'
  13. import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
  14. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  15. import type { Session, UserMessage } from '@deepseek-ai/dsh-session'
  16. import type { ToolExecution, ToolExecutionResult, ToolExecutionToken } from '@deepseek-ai/dsh-tools'
  17. import { Config, resolveConfig, workspaceBaselineIdentity, type ResolvedConfig } from './config.ts'
  18. import { findProjectRoot, loadBaselineInstructionSet } from './files.ts'
  19. import {
  20. applyInstructionVersionUpdates,
  21. baselineInstructionState,
  22. name,
  23. reconcileInstructionContext,
  24. workspaceContextMessage,
  25. type InstructionVersionCache,
  26. type WorkspaceInstructionSource,
  27. } from './state.ts'
  28. import type { WorkspaceInstructionChange } from './render.ts'
  29. export { Config, name }
  30. export {
  31. discoverBaselineInstructionFiles,
  32. loadBaselineInstructions,
  33. } from './files.ts'
  34. export type {
  35. InstructionFile,
  36. LoadedInstructionFile,
  37. } from './files.ts'
  38. export { renderWorkspaceContext } from './render.ts'
  39. export type { RenderedWorkspaceContext, TruncatedInstruction } from './render.ts'
  40. function visibleBaselineSource(
  41. agent: Agent,
  42. authorityMessages: readonly UserMessage[],
  43. ): WorkspaceInstructionSource | undefined {
  44. for (const message of authorityMessages.toReversed()) {
  45. if (message.source.kind === 'workspace-instructions' && message.source.baseline === true) {
  46. return message.source
  47. }
  48. }
  49. for (const seq of agent.session.surface.nodes.toReversed()) {
  50. const event = agent.session.events[seq]
  51. if (event?.type === 'user/message'
  52. && event.data.source.kind === 'workspace-instructions'
  53. && event.data.source.baseline === true) return event.data.source
  54. }
  55. return undefined
  56. }
  57. function isWorkspaceContext(message: UserMessage): boolean {
  58. return message.source.kind === 'workspace-instructions'
  59. }
  60. function sameContextPayload(left: UserMessage, right: UserMessage): boolean {
  61. return isDeepStrictEqual(left.content, right.content)
  62. && isDeepStrictEqual(left.source, right.source)
  63. }
  64. const FILE_TOUCH_TOOL_NAMES = new Set(['read', 'write', 'edit'])
  65. function filePathFromExecution(exec: ToolExecution): string | undefined {
  66. if (!FILE_TOUCH_TOOL_NAMES.has(exec.name)) return undefined
  67. if (typeof exec.arguments !== 'object' || exec.arguments === null) return undefined
  68. if (!('file_path' in exec.arguments) || typeof exec.arguments.file_path !== 'string') return undefined
  69. const filePath = exec.arguments.file_path.trim()
  70. return filePath.length > 0 ? filePath : undefined
  71. }
  72. export function apply(ctx: Context, config: Config): void {
  73. const resolved: ResolvedConfig = resolveConfig(config)
  74. const instructionVersions: InstructionVersionCache = new WeakMap()
  75. const baselinePreparations = new WeakMap<Session, {
  76. identity: string
  77. excludedScopes: ReadonlySet<string>
  78. }>()
  79. const projectionLifecycle = new AbortController()
  80. type ProjectionTouch = { agent: Agent; path: string }
  81. const executionTouches = new Map<ToolExecutionToken, ProjectionTouch[]>()
  82. ctx.effect(
  83. () => () => {
  84. projectionLifecycle.abort(new Error('workspace-context disposed'))
  85. executionTouches.clear()
  86. },
  87. 'workspace-context.projectionLifecycle',
  88. )
  89. // Emit listeners are not awaited, so each projection must compose against the
  90. // inbox produced by earlier file results for the same agent.
  91. const projectionTails = new WeakMap<Agent, Promise<void>>()
  92. // Execution ancestry and the enclosing durable step are the two commit
  93. // boundaries before an asynchronous projection may mutate the agent inbox.
  94. const openSteps = new WeakMap<Session, boolean>()
  95. const stepTouches = new WeakMap<Session, ProjectionTouch[]>()
  96. const compose = async (
  97. agent: Agent,
  98. signal: AbortSignal,
  99. claimed: readonly UserMessage[],
  100. pending: readonly UserMessage[],
  101. touchedPaths: readonly string[] = [],
  102. ): Promise<UserMessage | undefined> => {
  103. signal.throwIfAborted()
  104. if (resolved.maxBytes <= 0 || !Number.isFinite(resolved.maxBytes)) {
  105. return undefined
  106. }
  107. const fileSystem = ctx.get('fs')
  108. if (fileSystem === undefined) return undefined
  109. if (touchedPaths.length === 0 && pending.length > 0) return pending[0]
  110. const content: UserMessage['content'][number][] = []
  111. const changes: WorkspaceInstructionChange[] = []
  112. let desiredBaseline = false
  113. const authorityMessages = [...claimed]
  114. /* v8 ignore next -- normal agents carry an absolute session cwd. */
  115. const cwd = agent.session.header.cwd ?? process.cwd()
  116. const projectRoot = await findProjectRoot(cwd, resolved.projectRootMarkers, fileSystem, signal)
  117. const identity = workspaceBaselineIdentity(resolved, cwd, projectRoot)
  118. const visibleBaseline = visibleBaselineSource(agent, authorityMessages)
  119. const baselinePresent = visibleBaseline !== undefined
  120. const keepVisibleBaseline = visibleBaseline?.baselineIdentity === identity
  121. const prepared = baselinePreparations.get(agent.session)
  122. let excludedBaselineScopes = keepVisibleBaseline && prepared?.identity === identity
  123. ? prepared.excludedScopes
  124. : undefined
  125. let nextPreparation: { identity: string; excludedScopes: ReadonlySet<string> } | undefined
  126. if (!baselinePresent || !keepVisibleBaseline || excludedBaselineScopes === undefined) {
  127. const replacePreviousBaseline = baselinePresent && !keepVisibleBaseline
  128. const instructions = await loadBaselineInstructionSet({
  129. cwd,
  130. dshHome: resolved.dshHome,
  131. projectRootMarkers: resolved.projectRootMarkers,
  132. maxBytes: resolved.maxBytes,
  133. maxSourceBytes: resolved.maxSourceBytes,
  134. instructionFileCandidates: resolved.instructionFileCandidates,
  135. localInstructionFileCandidates: resolved.localInstructionFileCandidates,
  136. projectRoot,
  137. replacePreviousBaseline,
  138. signal,
  139. }, fileSystem)
  140. const baseline = baselineInstructionState(instructions?.included ?? [])
  141. const observedBaseline = baselineInstructionState(instructions?.observed ?? [])
  142. const excludedScopes = new Set(observedBaseline.changes.keys())
  143. for (const scope of baseline.changes.keys()) excludedScopes.delete(scope)
  144. excludedBaselineScopes = excludedScopes
  145. nextPreparation = { identity, excludedScopes }
  146. let versionStates = instructionVersions.get(agent.session)
  147. if (versionStates === undefined && baseline.versions.size > 0) {
  148. versionStates = new Map()
  149. instructionVersions.set(agent.session, versionStates)
  150. }
  151. for (const [scope, state] of baseline.versions) versionStates?.set(scope, state)
  152. if (!keepVisibleBaseline && instructions !== undefined && instructions.rendered.text.length > 0) {
  153. const baselineContent = workspaceContextMessage(instructions.rendered.text).content
  154. content.push(...baselineContent)
  155. const replacementScopes = new Set(baseline.changes.keys())
  156. const replacementRemovals = replacePreviousBaseline
  157. ? visibleBaseline.changes.flatMap(change => (
  158. change.action === 'remove' || replacementScopes.has(change.scope)
  159. ? []
  160. : [{ action: 'remove' as const, scope: change.scope, path: change.path }]
  161. ))
  162. : []
  163. const baselineChanges = [...replacementRemovals, ...baseline.changes.values()]
  164. changes.push(...baselineChanges)
  165. authorityMessages.push(createUserMessage({
  166. content: baselineContent,
  167. source: {
  168. kind: 'workspace-instructions',
  169. form: 'instructions',
  170. baseline: true,
  171. baselineIdentity: identity,
  172. changes: baselineChanges,
  173. },
  174. }))
  175. desiredBaseline = true
  176. }
  177. }
  178. const update = await reconcileInstructionContext(
  179. agent,
  180. resolved,
  181. instructionVersions,
  182. fileSystem,
  183. {
  184. authorityMessages,
  185. scopeMessages: pending,
  186. includeBaselineScopes: keepVisibleBaseline,
  187. ...keepVisibleBaseline ? { excludedBaselineScopes } : {},
  188. touchedPaths,
  189. projectRoot,
  190. signal,
  191. },
  192. )
  193. if (update !== undefined) {
  194. content.push(...update.context.content)
  195. /* v8 ignore next -- reconciliation constructs only workspace-instructions contexts. */
  196. if (update.context.source.kind === 'workspace-instructions') {
  197. changes.push(...update.context.source.changes)
  198. }
  199. applyInstructionVersionUpdates(agent.session, update.versionUpdates, instructionVersions)
  200. }
  201. if (nextPreparation !== undefined) baselinePreparations.set(agent.session, nextPreparation)
  202. if (content.length === 0) return undefined
  203. return createUserMessage({
  204. content,
  205. source: {
  206. kind: 'workspace-instructions',
  207. form: 'instructions',
  208. ...desiredBaseline ? { baseline: true } : {},
  209. ...desiredBaseline ? { baselineIdentity: identity } : {},
  210. changes,
  211. },
  212. })
  213. }
  214. const syncInbox = (agent: Agent, claimed: readonly UserMessage[], desired: UserMessage | undefined): void => {
  215. const pending = agent.inbox.nextStep.filter(isWorkspaceContext)
  216. const alreadySupplied = desired !== undefined && (
  217. claimed.some(message => sameContextPayload(message, desired))
  218. || agent.session.surface.nodes.some((seq) => {
  219. const event = agent.session.events[seq]
  220. return event?.type === 'user/message' && sameContextPayload(event.data, desired)
  221. })
  222. )
  223. if (desired === undefined || alreadySupplied) {
  224. for (const message of pending) agent.inbox.remove(message.id)
  225. return
  226. }
  227. const reusable = pending.find(message => sameContextPayload(message, desired))
  228. if (reusable !== undefined) {
  229. for (const message of pending) {
  230. if (message !== reusable) agent.inbox.remove(message.id)
  231. }
  232. return
  233. }
  234. const replaced = pending[0]
  235. if (replaced === undefined) agent.inbox.prepend('next-step', desired)
  236. else agent.inbox.replace(replaced.id, desired)
  237. for (const message of pending.slice(1)) agent.inbox.remove(message.id)
  238. }
  239. const composeAndSync = async (
  240. agent: Agent,
  241. signal: AbortSignal,
  242. claimed: readonly UserMessage[],
  243. touchedPaths: readonly string[] = [],
  244. ): Promise<void> => {
  245. const pending = agent.inbox.nextStep.filter(isWorkspaceContext)
  246. const desired = await compose(agent, signal, claimed, pending, touchedPaths)
  247. signal.throwIfAborted()
  248. syncInbox(agent, claimed, desired)
  249. }
  250. const queueProjection = (
  251. agent: Agent,
  252. touchedPath: string,
  253. ): void => {
  254. const previous = projectionTails.get(agent) ?? Promise.resolve()
  255. const current = previous.then(() => composeAndSync(agent, projectionLifecycle.signal, [], [touchedPath]))
  256. .catch((error: unknown) => {
  257. if (!projectionLifecycle.signal.aborted) ctx.logger.warn('workspace instruction refresh failed: %o', error)
  258. })
  259. projectionTails.set(agent, current)
  260. void current.then(() => {
  261. if (projectionTails.get(agent) === current) projectionTails.delete(agent)
  262. })
  263. }
  264. const waitForProjections = async (agent: Agent): Promise<void> => {
  265. let projection: Promise<void> | undefined
  266. while ((projection = projectionTails.get(agent)) !== undefined) await projection
  267. }
  268. const stepIsOpen = (session: Session): boolean => {
  269. const known = openSteps.get(session)
  270. if (known !== undefined) return known
  271. let open = false
  272. for (const event of session.events) {
  273. if (event.type === 'step/start') open = true
  274. else if (event.type === 'step/end' || event.type === 'turn/end') open = false
  275. }
  276. openSteps.set(session, open)
  277. return open
  278. }
  279. const projectTouch = (touch: ProjectionTouch): void => {
  280. const session = touch.agent.session
  281. if (!stepIsOpen(session)) {
  282. queueProjection(touch.agent, touch.path)
  283. return
  284. }
  285. const pending = stepTouches.get(session)
  286. if (pending === undefined) stepTouches.set(session, [touch])
  287. else pending.push(touch)
  288. }
  289. ctx.on('session/event', (session, event) => {
  290. if (event.type === 'step/start') {
  291. openSteps.set(session, true)
  292. return
  293. }
  294. if (event.type === 'turn/end') {
  295. openSteps.set(session, false)
  296. return
  297. }
  298. if (event.type !== 'step/end') return
  299. openSteps.set(session, false)
  300. const pending = stepTouches.get(session)
  301. if (pending === undefined) return
  302. stepTouches.delete(session)
  303. for (const touch of pending) queueProjection(touch.agent, touch.path)
  304. })
  305. ctx.on('agent/pre-step', async (
  306. { agent, messages, step, signal },
  307. next,
  308. ): Promise<PreStepDecision> => {
  309. const decision = await next()
  310. await waitForProjections(agent)
  311. const pending = agent.inbox.nextStep.filter(isWorkspaceContext)
  312. const desired = await compose(agent, signal, messages, pending)
  313. signal.throwIfAborted()
  314. // An empty first entry owns a no-step turn; keep context pending instead
  315. // of turning it into a standalone request. Later entries may be tool continuations.
  316. if (decision.kind === 'reject' || (step === 1 && decision.messages.length === 0)) {
  317. syncInbox(agent, messages, desired)
  318. return decision
  319. }
  320. // A proceeding step settles the pending context: it either enters below as
  321. // `desired`, or its payload is already covered by the batch, so nothing stays pending.
  322. for (const message of pending) agent.inbox.remove(message.id)
  323. if (desired === undefined || decision.messages.some(message => sameContextPayload(message, desired))) {
  324. return decision
  325. }
  326. // Fold the context right after the claimed batch, so the direct prompt
  327. // precedes it and the driver-appended runtime context follows it.
  328. const lastClaimedIndex = decision.messages.findLastIndex(message => messages.includes(message))
  329. const entered = decision.messages.toSpliced(lastClaimedIndex + 1, 0, desired)
  330. return { kind: 'enter', messages: entered }
  331. })
  332. ctx.on('tools/result', (exec: ToolExecution, result: ToolExecutionResult) => {
  333. const touches = executionTouches.get(exec.token) ?? []
  334. executionTouches.delete(exec.token)
  335. if (!result.isError && exec.agent !== undefined && !exec.signal.aborted) {
  336. const ownPath = filePathFromExecution(exec)
  337. if (ownPath !== undefined) touches.push({ agent: exec.agent, path: ownPath })
  338. }
  339. if (exec.parent !== undefined) {
  340. if (touches.length > 0) {
  341. const parentTouches = executionTouches.get(exec.parent)
  342. if (parentTouches === undefined) executionTouches.set(exec.parent, touches)
  343. else parentTouches.push(...touches)
  344. }
  345. return
  346. }
  347. for (const touch of touches) projectTouch(touch)
  348. })
  349. }