tool-ralph.spec.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import Loader from '@deepseek-ai/cordis-plugin-loader'
  4. import type { Agent } from '@deepseek-ai/dsh-agent'
  5. import { ToolCallId } from '@deepseek-ai/dsh-llm'
  6. import { SessionId } from '@deepseek-ai/dsh-session'
  7. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  8. import SubagentRuntime from '@deepseek-ai/dsh-subagent'
  9. import type { SubagentCapabilities, SubagentProvider, SubagentRun, SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
  10. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  11. import ToolRuntime, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools'
  12. import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  13. import { WorkflowRunId, WorkflowEngine } from '@deepseek-ai/dsh-workflow'
  14. import type { WorkflowResult, WorkflowRun, WorkflowStartRequest } from '@deepseek-ai/dsh-workflow'
  15. import * as toolRalph from '../src/index.ts'
  16. const testToolSignal = new AbortController().signal
  17. class StubEngine extends WorkflowEngine {
  18. requests: WorkflowStartRequest[] = []
  19. cancels: string[] = []
  20. disposed = 0
  21. settle!: (result: WorkflowResult) => void
  22. startError: Error | undefined
  23. onStart: (() => void) | undefined
  24. start(request: WorkflowStartRequest): WorkflowRun {
  25. if (this.startError !== undefined) throw this.startError
  26. this.requests.push(request)
  27. const result = new Promise<WorkflowResult>((resolve) => { this.settle = resolve })
  28. this.onStart?.()
  29. return {
  30. id: WorkflowRunId(`ralph-${this.requests.length}`),
  31. meta: request.meta,
  32. result,
  33. cancel: (reason?: string) => {
  34. this.cancels.push(reason ?? 'cancelled')
  35. this.settle({
  36. value: null,
  37. stopReason: 'cancelled',
  38. ...reason === undefined ? {} : { error: reason },
  39. agentsStarted: 0,
  40. })
  41. },
  42. dispose: () => {
  43. this.disposed += 1
  44. return Promise.resolve()
  45. },
  46. }
  47. }
  48. }
  49. class StubProvider implements SubagentProvider {
  50. readonly name = 'fresh'
  51. readonly capabilities: SubagentCapabilities
  52. readonly inheritsParentContext: boolean
  53. constructor(options?: { outputSchema?: boolean; inheritsParentContext?: boolean }) {
  54. this.capabilities = {
  55. agentOptions: true,
  56. outputSchema: options?.outputSchema ?? true,
  57. depthLimit: true,
  58. toolFilter: true,
  59. persona: true,
  60. }
  61. this.inheritsParentContext = options?.inheritsParentContext ?? false
  62. }
  63. start(_request: SubagentStartRequest): Promise<SubagentRun> {
  64. return Promise.reject(new Error('StubProvider.start must not be reached behind StubEngine'))
  65. }
  66. }
  67. interface SetupOptions {
  68. config?: toolRalph.Config
  69. provider?: StubProvider | false
  70. }
  71. async function setup(options?: SetupOptions) {
  72. const ctx = new Context()
  73. await ctx.plugin(SystemPrompt)
  74. await ctx.plugin(ToolRuntime)
  75. await ctx.plugin(SessionProjectionRegistry)
  76. await ctx.plugin(SubagentRuntime)
  77. const provider = options?.provider === false ? undefined : options?.provider ?? new StubProvider()
  78. if (provider !== undefined) ctx.subagents.registerProvider(provider)
  79. await ctx.plugin(StubEngine)
  80. const config: toolRalph.Config = { subagentProvider: 'fresh' }
  81. if (options?.config?.subagentProvider !== undefined) config.subagentProvider = options.config.subagentProvider
  82. if (options?.config?.maxRounds !== undefined) config.maxRounds = options.config.maxRounds
  83. if (options?.config?.maxHandoffChars !== undefined) config.maxHandoffChars = options.config.maxHandoffChars
  84. if (options?.config?.maxResultChars !== undefined) config.maxResultChars = options.config.maxResultChars
  85. const fiber = await ctx.plugin(toolRalph, config)
  86. const parent = { id: SessionId('caller'), options: {} } as unknown as Agent
  87. return { ctx, engine: ctx.workflowEngine as StubEngine, parent, fiber }
  88. }
  89. function execute(
  90. ctx: Context,
  91. args: unknown,
  92. extra?: { agent?: Agent; signal?: AbortSignal },
  93. ): Promise<ToolExecutionResult> {
  94. return ctx.tools.execute({
  95. signal: extra?.signal ?? testToolSignal,
  96. callId: ToolCallId('ralph-call'),
  97. name: 'ralph',
  98. arguments: args,
  99. ...extra?.agent === undefined ? {} : { agent: extra.agent },
  100. })
  101. }
  102. const CONTINUE = {
  103. status: 'continue',
  104. summary: 'Implemented the first slice.',
  105. evidence: ['Focused tests pass.'],
  106. nextSteps: ['Implement the second slice.'],
  107. blocker: '',
  108. }
  109. const COMPLETE = {
  110. status: 'complete',
  111. summary: 'The objective is complete.',
  112. evidence: ['All required gates pass.'],
  113. nextSteps: [],
  114. blocker: '',
  115. }
  116. const BLOCKED = {
  117. status: 'blocked',
  118. summary: 'No local work can progress.',
  119. evidence: ['The required remote service is unavailable.'],
  120. nextSteps: ['Retry after service recovery.'],
  121. blocker: 'The required remote service is unavailable.',
  122. }
  123. async function settleCompleted(
  124. engine: StubEngine,
  125. pending: Promise<ToolExecutionResult>,
  126. value: unknown,
  127. agentsStarted = 1,
  128. ): Promise<ToolExecutionResult> {
  129. await vi.waitFor(() => { expect(engine.requests.length).toBeGreaterThan(0) })
  130. engine.settle({ value, stopReason: 'completed', agentsStarted })
  131. return pending
  132. }
  133. describe('dsh-tool-ralph', () => {
  134. it('starts the fixed workflow through the configured fresh provider and renders completion', async () => {
  135. const { ctx, engine, parent } = await setup({ config: { maxRounds: 9, maxHandoffChars: 9000 } })
  136. const pending = execute(ctx, { objective: ' Finish the migration. ', maxRounds: 4 }, { agent: parent })
  137. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  138. expect(engine.requests[0]).toMatchObject({
  139. meta: { name: 'ralph-loop' },
  140. args: { objective: 'Finish the migration.', maxRounds: 4, maxHandoffChars: 9000 },
  141. subagentProvider: 'fresh',
  142. maxTotalAgents: 4,
  143. parent,
  144. })
  145. expect(engine.requests[0]!.script).toContain("status: 'budget-limited'")
  146. const result = await settleCompleted(engine, pending, {
  147. status: 'complete',
  148. roundsStarted: 1,
  149. report: COMPLETE,
  150. })
  151. expect(result.isError).toBe(false)
  152. if (result.isError) throw new Error('expected Ralph success')
  153. expect(result.value).toEqual({
  154. runId: 'ralph-1',
  155. agentsStarted: 1,
  156. result: { status: 'complete', roundsStarted: 1, report: COMPLETE },
  157. })
  158. expect((result.content[0] as { text: string }).text)
  159. .toContain('Ralph worker reported completion after 1 round.')
  160. expect((result.content[0] as { text: string }).text).toContain('All required gates pass.')
  161. expect(engine.disposed).toBe(1)
  162. })
  163. it('renders blocked and budget-limited terminal outcomes as bounded successful results', async () => {
  164. const { ctx, engine, parent } = await setup({ config: { maxRounds: 2 } })
  165. const blocked = execute(ctx, { objective: 'Ship it.' }, { agent: parent })
  166. const blockedResult = await settleCompleted(engine, blocked, {
  167. status: 'blocked',
  168. roundsStarted: 2,
  169. report: BLOCKED,
  170. }, 2)
  171. expect((blockedResult.content[0] as { text: string }).text)
  172. .toContain('Ralph worker reported a blocker after 2 rounds.')
  173. const limited = execute(ctx, { objective: 'Ship it.' }, { agent: parent })
  174. await vi.waitFor(() => { expect(engine.requests).toHaveLength(2) })
  175. const limitedResult = await settleCompleted(engine, limited, {
  176. status: 'budget-limited',
  177. roundsStarted: 2,
  178. report: CONTINUE,
  179. }, 2)
  180. expect((limitedResult.content[0] as { text: string }).text)
  181. .toContain('Ralph reached its 2 rounds limit; the worker reported work remaining.')
  182. })
  183. it('bounds the complete parent result and labels worker-reported completion', async () => {
  184. const { ctx, engine, parent } = await setup({ config: { maxResultChars: 160 } })
  185. const pending = execute(ctx, { objective: 'Ship it.' }, { agent: parent })
  186. const result = await settleCompleted(engine, pending, {
  187. status: 'complete',
  188. roundsStarted: 1,
  189. report: { ...COMPLETE, evidence: ['x'.repeat(500)] },
  190. })
  191. const text = (result.content[0] as { text: string }).text
  192. expect(text).toHaveLength(160)
  193. expect(text).toContain('Ralph worker reported completion after 1 round.')
  194. expect(text).toMatch(/… \[truncated\]$/)
  195. })
  196. it('honors a result limit shorter than the truncation marker', async () => {
  197. const { ctx, engine, parent } = await setup({ config: { maxResultChars: 5 } })
  198. const result = await settleCompleted(engine, execute(ctx, { objective: 'Ship it.' }, { agent: parent }), {
  199. status: 'complete',
  200. roundsStarted: 1,
  201. report: COMPLETE,
  202. })
  203. expect((result.content[0] as { text: string }).text).toBe('\n… [t')
  204. })
  205. it('reports an ordinary child failure with the failed round and last durable handoff', async () => {
  206. const { ctx, engine, parent } = await setup({ config: { maxRounds: 2 } })
  207. const first = execute(ctx, { objective: 'Ship it.', maxRounds: 2 }, { agent: parent })
  208. const firstResult = await settleCompleted(engine, first, {
  209. status: 'round-failed',
  210. roundsStarted: 1,
  211. lastReport: null,
  212. })
  213. expect(firstResult.isError).toBe(true)
  214. expect((firstResult.content[0] as { text: string }).text).toContain('Ralph round 1 child failed')
  215. expect((firstResult.content[0] as { text: string }).text).toContain('No previous handoff was available.')
  216. const later = execute(ctx, { objective: 'Ship it.', maxRounds: 2 }, { agent: parent })
  217. const laterResult = await settleCompleted(engine, later, {
  218. status: 'round-failed',
  219. roundsStarted: 2,
  220. lastReport: CONTINUE,
  221. })
  222. expect(laterResult.isError).toBe(true)
  223. expect((laterResult.content[0] as { text: string }).text).toContain('Ralph round 2 child failed')
  224. expect((laterResult.content[0] as { text: string }).text).toContain('Implemented the first slice.')
  225. })
  226. it('maps workflow error and cancellation reasons to tool errors and always disposes', async () => {
  227. const { ctx, engine, parent } = await setup()
  228. const failed = execute(ctx, { objective: 'Work.' }, { agent: parent })
  229. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  230. engine.settle({ value: null, stopReason: 'error', error: 'child report malformed', agentsStarted: 1 })
  231. expect(((await failed).content[0] as { text: string }).text)
  232. .toContain('Ralph workflow failed: child report malformed')
  233. const unknown = execute(ctx, { objective: 'Work.' }, { agent: parent })
  234. await vi.waitFor(() => { expect(engine.requests).toHaveLength(2) })
  235. engine.settle({ value: null, stopReason: 'error', agentsStarted: 0 })
  236. expect(((await unknown).content[0] as { text: string }).text).toContain('unknown error')
  237. const cancelled = execute(ctx, { objective: 'Work.' }, { agent: parent })
  238. await vi.waitFor(() => { expect(engine.requests).toHaveLength(3) })
  239. engine.settle({ value: null, stopReason: 'cancelled', error: 'user stopped', agentsStarted: 0 })
  240. expect(((await cancelled).content[0] as { text: string }).text).toContain('cancelled (user stopped)')
  241. const bare = execute(ctx, { objective: 'Work.' }, { agent: parent })
  242. await vi.waitFor(() => { expect(engine.requests).toHaveLength(4) })
  243. engine.settle({ value: null, stopReason: 'cancelled', agentsStarted: 0 })
  244. expect(((await bare).content[0] as { text: string }).text).toMatch(/cancelled$/)
  245. expect(engine.disposed).toBe(4)
  246. })
  247. it('bridges mid-flight cancellation and skips dispatch for an already-aborted parent signal', async () => {
  248. const { ctx, engine, parent } = await setup()
  249. const controller = new AbortController()
  250. const pending = execute(ctx, { objective: 'Work.' }, { agent: parent, signal: controller.signal })
  251. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  252. controller.abort()
  253. expect((await pending).isError).toBe(true)
  254. const already = new AbortController()
  255. already.abort()
  256. const skipped = await execute(ctx, { objective: 'Work.' }, { agent: parent, signal: already.signal })
  257. expect(skipped.error?.info?.code).toBe(TOOL_ABORTED_BEFORE_DISPATCH)
  258. expect(engine.requests).toHaveLength(1)
  259. expect(engine.cancels).toEqual(['parent step aborted'])
  260. expect(engine.disposed).toBe(1)
  261. })
  262. it('bridges cancellation that arrives while the workflow is starting', async () => {
  263. const { ctx, engine, parent } = await setup()
  264. const controller = new AbortController()
  265. engine.onStart = () => { controller.abort() }
  266. const result = await execute(ctx, { objective: 'Work.' }, { agent: parent, signal: controller.signal })
  267. expect(result.isError).toBe(true)
  268. expect(engine.requests[0]?.signal).toBe(controller.signal)
  269. expect(engine.cancels).toEqual(['parent step aborted'])
  270. expect(engine.disposed).toBe(1)
  271. })
  272. it('rejects absent authority, empty objectives, bad round caps, and schema-invalid calls before start', async () => {
  273. const { ctx, engine, parent } = await setup({ config: { maxRounds: 3 } })
  274. expect((await execute(ctx, { objective: 'Work.' })).isError).toBe(true)
  275. expect((await execute(ctx, { objective: ' ' }, { agent: parent })).isError).toBe(true)
  276. for (const maxRounds of [0, 1.5, Number.NaN, 4]) {
  277. expect((await execute(ctx, { objective: 'Work.', maxRounds }, { agent: parent })).isError).toBe(true)
  278. }
  279. const missing = await execute(ctx, {}, { agent: parent })
  280. expect(missing.error?.info?.code).toBe('INVALID_ARGS')
  281. expect(engine.requests).toHaveLength(0)
  282. })
  283. it('rejects missing, unstructured, and parent-context-inheriting provider routes', async () => {
  284. const missing = await setup({ provider: false })
  285. expect(((await execute(missing.ctx, { objective: 'Work.' }, { agent: missing.parent })).content[0] as { text: string }).text)
  286. .toContain('is not registered')
  287. expect(missing.engine.requests).toHaveLength(0)
  288. const unstructured = await setup({ provider: new StubProvider({ outputSchema: false }) })
  289. expect(((await execute(unstructured.ctx, { objective: 'Work.' }, { agent: unstructured.parent })).content[0] as { text: string }).text)
  290. .toContain('does not support structured output')
  291. const inherited = await setup({ provider: new StubProvider({ inheritsParentContext: true }) })
  292. expect(((await execute(inherited.ctx, { objective: 'Work.' }, { agent: inherited.parent })).content[0] as { text: string }).text)
  293. .toContain('inherits parent context')
  294. })
  295. it('rejects invalid direct-apply config before touching injected services', () => {
  296. expect(() => { toolRalph.apply(new Context(), { subagentProvider: ' ' }) }).toThrow('non-empty normalized')
  297. expect(() => { toolRalph.apply(new Context(), { maxRounds: 0 }) }).toThrow('positive safe integer')
  298. expect(() => { toolRalph.apply(new Context(), { maxHandoffChars: 1.5 }) }).toThrow('positive safe integer')
  299. expect(() => { toolRalph.apply(new Context(), { maxResultChars: 0 }) }).toThrow('positive safe integer')
  300. })
  301. it('turns malformed fixed-workflow terminal values and reports into errors', async () => {
  302. const cases: { value: unknown; message: string; config?: toolRalph.Config }[] = [
  303. { value: null, message: 'malformed terminal result' },
  304. { value: { status: 'complete', roundsStarted: 0, report: COMPLETE }, message: 'malformed terminal result' },
  305. { value: { status: 'complete', roundsStarted: 3, report: COMPLETE }, message: 'malformed terminal result', config: { maxRounds: 2 } },
  306. { value: { status: 'mystery', roundsStarted: 1, report: COMPLETE }, message: 'unknown terminal status' },
  307. { value: { status: 'budget-limited', roundsStarted: 1, report: CONTINUE }, message: 'before the round limit', config: { maxRounds: 2 } },
  308. { value: { status: 'complete', roundsStarted: 1, report: null }, message: 'malformed round report' },
  309. { value: { status: 'complete', roundsStarted: 1, report: COMPLETE, extra: true }, message: 'malformed terminal result' },
  310. { value: { status: 'blocked', roundsStarted: 1, report: BLOCKED, extra: true }, message: 'malformed terminal result' },
  311. { value: { status: 'budget-limited', roundsStarted: 1, report: CONTINUE, extra: true }, message: 'malformed terminal result', config: { maxRounds: 1 } },
  312. { value: { status: 'complete', roundsStarted: 1, report: { ...COMPLETE, status: 'continue' } }, message: 'malformed round report' },
  313. { value: { status: 'budget-limited', roundsStarted: 1, report: { ...CONTINUE, nextSteps: [] } }, message: 'invalid continuing report', config: { maxRounds: 1 } },
  314. { value: { status: 'complete', roundsStarted: 1, report: { ...COMPLETE, evidence: [] } }, message: 'invalid completion report' },
  315. { value: { status: 'blocked', roundsStarted: 1, report: { ...BLOCKED, blocker: '' } }, message: 'invalid blocked report' },
  316. { value: { status: 'complete', roundsStarted: 1, report: { ...COMPLETE, summary: 'x'.repeat(500) } }, message: 'oversized handoff', config: { maxHandoffChars: 100 } },
  317. { value: { status: 'round-failed', roundsStarted: 1 }, message: 'malformed terminal result' },
  318. { value: { status: 'round-failed', roundsStarted: 1, lastReport: CONTINUE }, message: 'invalid first-round failure' },
  319. { value: { status: 'round-failed', roundsStarted: 2, lastReport: null }, message: 'without its last handoff', config: { maxRounds: 2 } },
  320. { value: { status: 'round-failed', roundsStarted: 2, lastReport: { ...CONTINUE, nextSteps: [] } }, message: 'invalid continuing report', config: { maxRounds: 2 } },
  321. ]
  322. for (const testCase of cases) {
  323. const { ctx, engine, parent } = await setup(
  324. testCase.config === undefined ? undefined : { config: testCase.config },
  325. )
  326. const result = await settleCompleted(
  327. engine,
  328. execute(ctx, { objective: 'Work.', ...testCase.config?.maxRounds === undefined ? {} : { maxRounds: testCase.config.maxRounds } }, { agent: parent }),
  329. testCase.value,
  330. )
  331. expect(result.isError).toBe(true)
  332. expect((result.content[0] as { text: string }).text).toContain(testCase.message)
  333. }
  334. })
  335. it('surfaces a synchronous engine start failure without inventing a run', async () => {
  336. const { ctx, engine, parent } = await setup()
  337. engine.startError = new Error('engine refused fixed script')
  338. const result = await execute(ctx, { objective: 'Work.' }, { agent: parent })
  339. expect(result.isError).toBe(true)
  340. expect((result.content[0] as { text: string }).text).toContain('engine refused fixed script')
  341. expect(engine.disposed).toBe(0)
  342. })
  343. it('registers scoped guidance and pure replay-safe generic presentation', async () => {
  344. const { ctx, fiber } = await setup()
  345. const section = (await ctx.systemPrompt.assemble()).sections.find(candidate => candidate.name === 'tool:ralph')
  346. expect(section?.text).toContain('ONLY when the direct human explicitly asks')
  347. expect(section?.text).toContain('worker reports, not independent evaluation')
  348. const tool = ctx.tools.get('ralph')!
  349. expect(tool.description).toContain('worker reports completion')
  350. expect(tool.presentCall!({ objective: 'Finish it.' })).toEqual({
  351. card: 'generic',
  352. title: 'ralph',
  353. rawInput: 'Finish it.',
  354. })
  355. expect(tool.presentResult!({ objective: 'Finish it.' }, { content: [], isError: false })).toEqual({ card: 'generic' })
  356. expect(tool.presentCall!({ nope: true })).toBeUndefined()
  357. await fiber.dispose()
  358. expect(ctx.tools.get('ralph')).toBeUndefined()
  359. expect((await ctx.systemPrompt.assemble()).sections.some(candidate => candidate.name === 'tool:ralph')).toBe(false)
  360. })
  361. it('has the namespace-plugin export shape', () => {
  362. expect('default' in toolRalph).toBe(false)
  363. expect(toolRalph.name).toBe('tool-ralph')
  364. expect(toolRalph.inject).toEqual(['tools', 'workflowEngine', 'subagents', 'systemPrompt'])
  365. const loader = Object.create(Loader.prototype) as Loader
  366. const unwrapped = loader.unwrapExports(toolRalph) as Record<string, unknown>
  367. expect(unwrapped).toBe(toolRalph)
  368. expect(typeof unwrapped.apply).toBe('function')
  369. })
  370. })