tool-ralph.spec.ts 20 KB

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