tool-ralph.spec.ts 20 KB

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