{"record":{"id":"b5ece32a4b43ceae","repo":"JuliusBrussee/caveman","slug":"cave-delegate-depth-exceeded","errorCode":"cave_delegate_depth_exceeded","errorMessage":"cave_delegate_depth_exceeded","messagePattern":"cave_delegate_depth_exceeded","errorType":"error_code","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"agents/delegate/caveman-delegate-mcp.mjs","lineNumber":141,"sourceCode":"    },\n    required: [\"task\"],\n  },\n};\n\nasync function handle(msg) {\n  const { id, method, params } = msg;\n  if (method === \"initialize\") {\n    return {\n      protocolVersion: params?.protocolVersion || PROTOCOL_FALLBACK,\n      capabilities: { tools: { listChanged: false } },\n      serverInfo: { name: \"caveman-delegate\", version: \"0.1.0\" },\n    };\n  }\n  if (method === \"tools/list\") return { tools: [TOOL] };\n  if (method === \"ping\") return {};\n  if (method === \"tools/call\") {\n    if (params?.name !== TOOL.name) throw new Error(`unknown tool: ${params?.name}`);\n    if (process.env.CAVEMAN_DELEGATE_CHILD === \"1\") throw new Error(\"cave_delegate_depth_exceeded\");\n    const task = params?.arguments?.task;\n    if (!task || typeof task !== \"string\") throw new Error(\"cave_delegate_missing_task\");\n    const r = await runWorker(task, params?.arguments?.cwd);\n    const lines = [r.out || \"(worker produced no output)\"];\n    if (r.usage) {\n      const u = r.usage;\n      let usageLine = `delegate usage (measured, provider-reported): input ${u.input + u.cacheRead + u.cacheWrite} (cacheRead ${u.cacheRead}, cacheWrite ${u.cacheWrite}), output ${u.output}`;\n      if (u.cost > 0) usageLine += `, cost $${u.cost.toFixed(4)}`;\n      lines.push(\"---\", usageLine);\n    }\n    if (r.code !== 0) {\n      lines.push(\"---\", `worker exit ${r.code}: ${r.err.slice(-500)}`);\n      return { content: [{ type: \"text\", text: lines.join(\"\\n\") }], isError: true };\n    }\n    return { content: [{ type: \"text\", text: lines.join(\"\\n\") }] };\n  }\n  if (method?.startsWith(\"notifications/\")) return undefined;\n  throw Object.assign(new Error(`method not found: ${method}`), { code: -32601 });","sourceCodeStart":123,"sourceCodeEnd":159,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/agents/delegate/caveman-delegate-mcp.mjs#L123-L159","documentation":"The delegate MCP server refuses to start a nested delegate worker when the environment variable CAVEMAN_DELEGATE_CHILD=1 is set, throwing 'cave_delegate_depth_exceeded'. Each worker sets this variable, so if the worker itself receives a cave_delegate tool call, it means delegation is recursing; the server caps it at one level to prevent infinite delegate loops.","triggerScenarios":"Invoking the cave_delegate tool from within a session that is already a cave_delegate child worker (CAVEMAN_DELEGATE_CHILD=1 in its environment), e.g. an agent task that itself calls cave_delegate.","commonSituations":"An agent prompt that tells the sub-agent it may delegate, recursive task definitions, or reusing a worker environment where the flag was incorrectly persisted/exported.","solutions":["Remove any cave_delegate calls from the delegated task text so the worker does not attempt to delegate again","Clear CAVEMAN_DELEGATE_CHILD only if you genuinely intend a new top-level session (not inside a worker)","Restructure the workflow so nested work is done directly by the worker instead of via delegation","If the flag is set unexpectedly, inspect the parent process env for an exported CAVEMAN_DELEGATE_CHILD"],"exampleFix":"// before: task instructs recursion\nrunWorker(\"use cave_delegate to investigate ...\")\n// after: worker does the work directly\nrunWorker(\"investigate the failing test and report findings\")","handlingStrategy":"try-catch","validationCode":"function canDelegate() {\n  return process.env.CAVEMAN_DELEGATE_CHILD !== '1';\n}\nif (!canDelegate()) throw new Error('already inside a delegated worker; do not call cave_delegate again');","typeGuard":null,"tryCatchPattern":"try { await callTool('cave_delegate', { task }); } catch (e) {\n  if (e.message === 'cave_delegate_depth_exceeded') {\n    // we are a child worker: perform the work directly instead of delegating\n    return doWorkLocally(task);\n  } throw e;\n}","preventionTips":["Strip cave_delegate instructions from task text passed to workers","Check CAVEMAN_DELEGATE_CHILD before offering the tool in client UIs","Do not export CAVEMAN_DELEGATE_CHILD in shells where you run top-level sessions","Design tasks so the worker completes work itself rather than re-delegating"],"tags":["recursion","mcp","guard","delegation"],"backgroundTag":"invalid-state-transition","analyzedSha":"3ee70a102609e550bd2e68004bf5990a9341c851","analyzedAt":"2026-09-20T15:53:39.229Z","contentChangedAt":"2026-09-20T15:53:39.229Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}