index.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /**
  2. * Model-facing foreground Ralph loop over the workflow and subagent seams. A
  3. * fixed script starts one fresh structured-output child per round, carrying
  4. * only the immutable objective and the previous bounded handoff between them.
  5. * @module @deepseek-ai/dsh-tool-ralph
  6. */
  7. import type { Context } from '@deepseek-ai/cordis'
  8. import z from '@deepseek-ai/schemastery'
  9. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  10. import type { JsonValue } from '@deepseek-ai/dsh-util-values'
  11. import type { SubagentProvider } from '@deepseek-ai/dsh-subagent'
  12. import { defineTool } from '@deepseek-ai/dsh-tools'
  13. import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools'
  14. import type { WorkflowResult, WorkflowRun } from '@deepseek-ai/dsh-workflow'
  15. export const name = 'tool-ralph'
  16. export const inject = ['tools', 'workflowEngine', 'subagents', 'systemPrompt']
  17. /** Deployment policy for the fixed Ralph workflow. */
  18. export interface Config {
  19. /** Fresh structured-output provider used for every round (default `spawn`). */
  20. subagentProvider?: string
  21. /** Default and deployment ceiling for one call's round count (default 256). */
  22. maxRounds?: number
  23. /** Maximum serialized characters in one structured handoff (default 16384). */
  24. maxHandoffChars?: number
  25. /** Maximum characters in a successful parent-facing terminal text (default 16384). */
  26. maxResultChars?: number
  27. }
  28. /** Schemastery configuration for the Ralph tool. */
  29. export const Config: z<Config> = z.object({
  30. subagentProvider: z.string().default('spawn'),
  31. maxRounds: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(256),
  32. maxHandoffChars: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(16_384),
  33. maxResultChars: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(16_384),
  34. })
  35. interface ResolvedConfig {
  36. readonly subagentProvider: string
  37. readonly maxRounds: number
  38. readonly maxHandoffChars: number
  39. readonly maxResultChars: number
  40. }
  41. type RalphRoundStatus = 'continue' | 'complete' | 'blocked'
  42. interface RalphRoundReport {
  43. readonly status: RalphRoundStatus
  44. readonly summary: string
  45. readonly evidence: string[]
  46. readonly nextSteps: string[]
  47. readonly blocker: string
  48. }
  49. type RalphRunStatus = 'complete' | 'blocked' | 'budget-limited'
  50. interface RalphRunResult {
  51. readonly status: RalphRunStatus
  52. readonly roundsStarted: number
  53. readonly report: RalphRoundReport
  54. }
  55. interface RalphRoundFailure {
  56. readonly status: 'round-failed'
  57. readonly roundsStarted: number
  58. readonly lastReport?: RalphRoundReport
  59. }
  60. type RalphTerminalResult = RalphRunResult | RalphRoundFailure
  61. interface RalphCallArgs {
  62. objective: string
  63. maxRounds?: number
  64. }
  65. const RALPH_META = {
  66. name: 'ralph-loop',
  67. description: 'Iterate toward one objective with a fresh child and bounded structured handoff per round.',
  68. phases: [{ title: 'Fresh-agent rounds', detail: 'One clean child context per Ralph round.' }],
  69. }
  70. /**
  71. * Fixed, deployment-owned orchestration. The model supplies data only; it
  72. * cannot alter the loop, provider route, schema, or handoff validation.
  73. */
  74. const RALPH_SCRIPT = String.raw`
  75. const reportSchema = {
  76. type: 'object',
  77. properties: {
  78. status: { type: 'string', enum: ['continue', 'complete', 'blocked'] },
  79. summary: { type: 'string' },
  80. evidence: { type: 'array', items: { type: 'string' } },
  81. nextSteps: { type: 'array', items: { type: 'string' } },
  82. blocker: { type: 'string' },
  83. },
  84. required: ['status', 'summary', 'evidence', 'nextSteps', 'blocker'],
  85. additionalProperties: false,
  86. }
  87. function normalizedText(value) {
  88. return typeof value === 'string' && value.length > 0 && value === value.trim()
  89. }
  90. function normalizedList(value) {
  91. return Array.isArray(value) && value.every(normalizedText)
  92. }
  93. function validateReport(report) {
  94. if (report === null || typeof report !== 'object' || Array.isArray(report)) {
  95. throw new Error('Ralph child returned no structured round report')
  96. }
  97. if (!normalizedText(report.summary)) {
  98. throw new Error('Ralph round report summary must be non-empty and normalized')
  99. }
  100. if (!normalizedList(report.evidence) || !normalizedList(report.nextSteps)) {
  101. throw new Error('Ralph round report evidence and nextSteps must contain only non-empty normalized strings')
  102. }
  103. if (typeof report.blocker !== 'string' || report.blocker !== report.blocker.trim()) {
  104. throw new Error('Ralph round report blocker must be a normalized string')
  105. }
  106. switch (report.status) {
  107. case 'continue':
  108. if (report.nextSteps.length === 0 || report.blocker !== '') {
  109. throw new Error('a continuing Ralph report needs nextSteps and an empty blocker')
  110. }
  111. break
  112. case 'complete':
  113. if (report.evidence.length === 0 || report.nextSteps.length !== 0 || report.blocker !== '') {
  114. throw new Error('a complete Ralph report needs evidence, no nextSteps, and an empty blocker')
  115. }
  116. break
  117. case 'blocked':
  118. if (!normalizedText(report.blocker)) {
  119. throw new Error('a blocked Ralph report needs a concrete blocker')
  120. }
  121. break
  122. default:
  123. throw new Error('Ralph round report status is invalid')
  124. }
  125. const serialized = JSON.stringify(report)
  126. if (serialized.length > args.maxHandoffChars) {
  127. throw new Error('Ralph round report exceeds maxHandoffChars (' + serialized.length + ' > ' + args.maxHandoffChars + ')')
  128. }
  129. return report
  130. }
  131. let previous
  132. phase('Fresh-agent rounds')
  133. for (let round = 1; round <= args.maxRounds; round += 1) {
  134. const prior = previous === undefined ? '(none — this is the first round)' : JSON.stringify(previous)
  135. const prompt = [
  136. 'You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.',
  137. 'Immutable objective:\n' + args.objective,
  138. 'Ralph round: ' + round + ' of ' + args.maxRounds + '.',
  139. 'The shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.',
  140. 'Previous structured handoff:\n' + prior,
  141. 'Return one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked.',
  142. ].join('\n\n')
  143. const rawReport = await agent(prompt, {
  144. label: 'Ralph round ' + round,
  145. phase: 'Fresh-agent rounds',
  146. schema: reportSchema,
  147. })
  148. if (rawReport === null) {
  149. return { status: 'round-failed', roundsStarted: round, lastReport: previous ?? null }
  150. }
  151. const report = validateReport(rawReport)
  152. if (report.status === 'complete') return { status: 'complete', roundsStarted: round, report }
  153. if (report.status === 'blocked') return { status: 'blocked', roundsStarted: round, report }
  154. previous = report
  155. }
  156. return { status: 'budget-limited', roundsStarted: args.maxRounds, report: previous }
  157. `
  158. const DESCRIPTION = 'Run a foreground fresh-agent Ralph loop toward one immutable objective. '
  159. + 'Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round '
  160. + 'opens a new child with no parent conversation or prior child session; the shared workspace is '
  161. + 'long-term memory, and only a bounded structured report crosses rounds. The call returns when '
  162. + 'a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work '
  163. + 'belongs to goal tools.'
  164. /** Validate defaults even when a caller invokes apply() without Loader normalization. */
  165. function resolveConfig(config: Config): ResolvedConfig {
  166. const subagentProvider = config.subagentProvider ?? 'spawn'
  167. const maxRounds = config.maxRounds ?? 256
  168. const maxHandoffChars = config.maxHandoffChars ?? 16_384
  169. const maxResultChars = config.maxResultChars ?? 16_384
  170. if (subagentProvider.length === 0 || subagentProvider !== subagentProvider.trim()) {
  171. throw new TypeError('subagentProvider must be a non-empty normalized string')
  172. }
  173. if (!Number.isSafeInteger(maxRounds) || maxRounds < 1) {
  174. throw new TypeError('maxRounds must be a positive safe integer')
  175. }
  176. if (!Number.isSafeInteger(maxHandoffChars) || maxHandoffChars < 1) {
  177. throw new TypeError('maxHandoffChars must be a positive safe integer')
  178. }
  179. if (!Number.isSafeInteger(maxResultChars) || maxResultChars < 1) {
  180. throw new TypeError('maxResultChars must be a positive safe integer')
  181. }
  182. return { subagentProvider, maxRounds, maxHandoffChars, maxResultChars }
  183. }
  184. /** Resolve one model-selected cap against the deployment ceiling. */
  185. function resolveMaxRounds(requested: number | undefined, ceiling: number): number {
  186. const value = requested ?? ceiling
  187. if (!Number.isSafeInteger(value) || value < 1) {
  188. throw new TypeError('Ralph maxRounds must be a positive safe integer')
  189. }
  190. if (value > ceiling) {
  191. throw new TypeError(`Ralph maxRounds ${value} exceeds the deployment ceiling ${ceiling}`)
  192. }
  193. return value
  194. }
  195. /** Require the configured route to mean a genuinely fresh structured child. */
  196. function requireFreshProvider(ctx: Context, name: string): SubagentProvider {
  197. const provider = ctx.subagents.getProvider(name)
  198. if (provider === undefined) {
  199. throw new Error(`Ralph subagent provider "${name}" is not registered`)
  200. }
  201. if (!provider.capabilities.outputSchema) {
  202. throw new Error(`Ralph subagent provider "${name}" does not support structured output`)
  203. }
  204. if (provider.inheritsParentContext) {
  205. throw new Error(`Ralph subagent provider "${name}" inherits parent context; Ralph requires a fresh provider`)
  206. }
  207. return provider
  208. }
  209. function isRecord(value: unknown): value is Record<string, unknown> {
  210. return typeof value === 'object' && value !== null && !Array.isArray(value)
  211. }
  212. function normalizedText(value: unknown): value is string {
  213. return typeof value === 'string' && value.length > 0 && value === value.trim()
  214. }
  215. function normalizedList(value: unknown): value is string[] {
  216. return Array.isArray(value) && value.every(normalizedText)
  217. }
  218. /** Defensively decode the fixed script's report across a provider boundary. */
  219. function readReport(value: unknown, expectedStatus: RalphRoundStatus, maxChars: number): RalphRoundReport {
  220. if (!isRecord(value)
  221. || Object.keys(value).sort().join(',') !== 'blocker,evidence,nextSteps,status,summary'
  222. || value['status'] !== expectedStatus
  223. || !normalizedText(value['summary'])
  224. || !normalizedList(value['evidence'])
  225. || !normalizedList(value['nextSteps'])
  226. || typeof value['blocker'] !== 'string'
  227. || value['blocker'] !== value['blocker'].trim()) {
  228. throw new Error('Ralph workflow returned a malformed round report')
  229. }
  230. const report: RalphRoundReport = {
  231. status: expectedStatus,
  232. summary: value['summary'],
  233. evidence: value['evidence'],
  234. nextSteps: value['nextSteps'],
  235. blocker: value['blocker'],
  236. }
  237. if (expectedStatus === 'continue' && (report.nextSteps.length === 0 || report.blocker !== '')) {
  238. throw new Error('Ralph workflow returned an invalid continuing report')
  239. }
  240. if (expectedStatus === 'complete'
  241. && (report.evidence.length === 0 || report.nextSteps.length !== 0 || report.blocker !== '')) {
  242. throw new Error('Ralph workflow returned an invalid completion report')
  243. }
  244. if (expectedStatus === 'blocked' && !normalizedText(report.blocker)) {
  245. throw new Error('Ralph workflow returned an invalid blocked report')
  246. }
  247. const chars = JSON.stringify(report).length
  248. if (chars > maxChars) {
  249. throw new Error(`Ralph workflow returned an oversized handoff (${chars} > ${maxChars})`)
  250. }
  251. return report
  252. }
  253. /** Defensively decode the fixed script's terminal value. */
  254. function readRunResult(value: unknown, maxRounds: number, maxHandoffChars: number): RalphTerminalResult {
  255. if (!isRecord(value)
  256. || typeof value['roundsStarted'] !== 'number'
  257. || !Number.isSafeInteger(value['roundsStarted'])
  258. || value['roundsStarted'] < 1
  259. || value['roundsStarted'] > maxRounds) {
  260. throw new Error('Ralph workflow returned a malformed terminal result')
  261. }
  262. const roundsStarted = value['roundsStarted']
  263. switch (value['status']) {
  264. case 'complete':
  265. if (Object.keys(value).sort().join(',') !== 'report,roundsStarted,status') {
  266. throw new Error('Ralph workflow returned a malformed terminal result')
  267. }
  268. return { status: 'complete', roundsStarted, report: readReport(value['report'], 'complete', maxHandoffChars) }
  269. case 'blocked':
  270. if (Object.keys(value).sort().join(',') !== 'report,roundsStarted,status') {
  271. throw new Error('Ralph workflow returned a malformed terminal result')
  272. }
  273. return { status: 'blocked', roundsStarted, report: readReport(value['report'], 'blocked', maxHandoffChars) }
  274. case 'budget-limited':
  275. if (Object.keys(value).sort().join(',') !== 'report,roundsStarted,status') {
  276. throw new Error('Ralph workflow returned a malformed terminal result')
  277. }
  278. if (roundsStarted !== maxRounds) {
  279. throw new Error('Ralph workflow returned budget-limited before the round limit')
  280. }
  281. return { status: 'budget-limited', roundsStarted, report: readReport(value['report'], 'continue', maxHandoffChars) }
  282. case 'round-failed': {
  283. if (Object.keys(value).sort().join(',') !== 'lastReport,roundsStarted,status') {
  284. throw new Error('Ralph workflow returned a malformed terminal result')
  285. }
  286. if (roundsStarted === 1) {
  287. if (value['lastReport'] !== null) {
  288. throw new Error('Ralph workflow returned an invalid first-round failure')
  289. }
  290. return { status: 'round-failed', roundsStarted }
  291. }
  292. if (value['lastReport'] === null) {
  293. throw new Error('Ralph workflow returned a round failure without its last handoff')
  294. }
  295. return {
  296. status: 'round-failed',
  297. roundsStarted,
  298. lastReport: readReport(value['lastReport'], 'continue', maxHandoffChars),
  299. }
  300. }
  301. default:
  302. throw new Error('Ralph workflow returned an unknown terminal status')
  303. }
  304. }
  305. /** A non-clean workflow finish is an error, never a partial Ralph success. */
  306. function stopReasonError(result: WorkflowResult): string | undefined {
  307. switch (result.stopReason) {
  308. case 'completed':
  309. return undefined
  310. case 'cancelled':
  311. return `Ralph workflow was cancelled${result.error === undefined ? '' : ` (${result.error})`}`
  312. case 'error':
  313. return `Ralph workflow failed: ${result.error ?? 'unknown error'}`
  314. /* v8 ignore start -- WorkflowStopReason is closed; a future variant must fail loud here. */
  315. default:
  316. return `Ralph workflow ended abnormally (${String(result.stopReason satisfies never)})`
  317. /* v8 ignore stop */
  318. }
  319. }
  320. const TRUNCATION_NOTICE = '\n… [truncated]'
  321. /** Bound complete parent-facing text, including its envelope and truncation marker. */
  322. function boundResult(text: string, maxChars: number): string {
  323. if (text.length <= maxChars) return text
  324. if (maxChars <= TRUNCATION_NOTICE.length) return TRUNCATION_NOTICE.slice(0, maxChars)
  325. return `${text.slice(0, maxChars - TRUNCATION_NOTICE.length)}${TRUNCATION_NOTICE}`
  326. }
  327. /** Render the fixed terminal envelope without presenting self-report as certification. */
  328. function renderResult(result: RalphRunResult, maxChars: number): string {
  329. const rounds = `${result.roundsStarted} round${result.roundsStarted === 1 ? '' : 's'}`
  330. let text: string
  331. switch (result.status) {
  332. case 'complete':
  333. text = `Ralph worker reported completion after ${rounds}.\nFinal report:\n${JSON.stringify(result.report, null, 2)}`
  334. break
  335. case 'blocked':
  336. text = `Ralph worker reported a blocker after ${rounds}.\nFinal report:\n${JSON.stringify(result.report, null, 2)}`
  337. break
  338. case 'budget-limited':
  339. text = `Ralph reached its ${rounds} limit; the worker reported work remaining.\nFinal report:\n${JSON.stringify(result.report, null, 2)}`
  340. break
  341. }
  342. return boundResult(text, maxChars)
  343. }
  344. /** Canonical Ralph result fields shared by schema inference and rendering. */
  345. const RALPH_OUTPUT_PROPERTIES = {
  346. runId: { type: 'string', required: true },
  347. agentsStarted: { type: 'integer', required: true },
  348. result: { type: 'json', required: true },
  349. } as const
  350. /** Render an ordinary child failure with the most recent durable handoff. */
  351. function renderRoundFailure(result: RalphRoundFailure, maxChars: number): string {
  352. const header = `Ralph round ${result.roundsStarted} child failed before producing a structured report.`
  353. const text = result.lastReport === undefined
  354. ? `${header}\nNo previous handoff was available.`
  355. : `${header}\nLast successful handoff:\n${JSON.stringify(result.lastReport, null, 2)}`
  356. return boundResult(text, maxChars)
  357. }
  358. function presentCall(args: RalphCallArgs): ToolCallView {
  359. return { card: 'generic', title: 'ralph', rawInput: args.objective }
  360. }
  361. function presentResult(args: RalphCallArgs, result: { content: ContentBlock[]; isError: boolean }): ToolResultView {
  362. void args
  363. void result
  364. return { card: 'generic' }
  365. }
  366. /** Register the fixed Ralph tool and its explicit-ask usage policy. */
  367. export function apply(ctx: Context, config: Config): void {
  368. const resolved = resolveConfig(config)
  369. ctx.systemPrompt.section({
  370. name: 'tool:ralph',
  371. order: ctx.systemPrompt.getSectionOrder('TOOL_RALPH'),
  372. text: 'Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.',
  373. })
  374. ctx.tools.register(defineTool({
  375. name: 'ralph',
  376. description: DESCRIPTION,
  377. parameters: {
  378. objective: {
  379. type: 'string',
  380. required: true,
  381. description: 'The immutable completion objective for every fresh Ralph round.',
  382. },
  383. maxRounds: {
  384. type: 'number',
  385. description: 'Optional positive safe-integer round cap, bounded by the deployment ceiling.',
  386. },
  387. },
  388. output: {
  389. schema: {
  390. type: 'object',
  391. additionalProperties: false,
  392. properties: RALPH_OUTPUT_PROPERTIES,
  393. },
  394. render: (_args, value) => [{
  395. type: 'text',
  396. text: renderResult(value.result as unknown as RalphRunResult, resolved.maxResultChars),
  397. }],
  398. },
  399. async execute(args, exec) {
  400. const parent = exec.agent
  401. if (parent === undefined) {
  402. throw new Error('Ralph tool requires a calling agent (exec.agent was undefined)')
  403. }
  404. const objective = args.objective.trim()
  405. if (objective.length === 0) throw new Error('Ralph objective must be a non-empty string')
  406. const maxRounds = resolveMaxRounds(args.maxRounds, resolved.maxRounds)
  407. void requireFreshProvider(ctx, resolved.subagentProvider)
  408. const run: WorkflowRun = ctx.workflowEngine.start({
  409. script: RALPH_SCRIPT,
  410. meta: RALPH_META,
  411. args: { objective, maxRounds, maxHandoffChars: resolved.maxHandoffChars },
  412. subagentProvider: resolved.subagentProvider,
  413. maxTotalAgents: maxRounds,
  414. parent,
  415. signal: exec.signal,
  416. })
  417. const onAbort = (): void => { run.cancel('parent step aborted') }
  418. exec.signal.addEventListener('abort', onAbort, { once: true })
  419. if (exec.signal.aborted) run.cancel('parent step aborted')
  420. try {
  421. const settled = await run.result
  422. const error = stopReasonError(settled)
  423. if (error !== undefined) throw new Error(error)
  424. const value = readRunResult(settled.value, maxRounds, resolved.maxHandoffChars)
  425. if (value.status === 'round-failed') throw new Error(renderRoundFailure(value, resolved.maxResultChars))
  426. return {
  427. runId: run.id,
  428. agentsStarted: settled.agentsStarted,
  429. result: value as unknown as JsonValue,
  430. }
  431. } finally {
  432. exec.signal.removeEventListener('abort', onAbort)
  433. await run.dispose()
  434. }
  435. },
  436. presentCall,
  437. presentResult,
  438. }))
  439. }