hook.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import type { PluginInput } from '@opencode-ai/plugin';
  2. import {
  3. DELEGATE_TASK_ERROR_PATTERNS,
  4. type DetectedError,
  5. detectDelegateTaskError,
  6. } from './patterns';
  7. function extractAvailableList(output: string): string | null {
  8. const match = output.match(/Allowed agents:\s*(.+)$/m);
  9. if (match) return match[1].trim();
  10. const available = output.match(/Available[^:]*:\s*(.+)$/m);
  11. if (available) return available[1].trim();
  12. return null;
  13. }
  14. function buildRetryGuidance(errorInfo: DetectedError): string {
  15. const pattern = DELEGATE_TASK_ERROR_PATTERNS.find(
  16. (p) => p.errorType === errorInfo.errorType,
  17. );
  18. if (!pattern) {
  19. return '\n[delegate-task retry] Fix parameters and retry with corrected arguments.';
  20. }
  21. const available = extractAvailableList(errorInfo.originalOutput);
  22. const lines = [
  23. '',
  24. '[delegate-task retry suggestion]',
  25. `Error type: ${errorInfo.errorType}`,
  26. `Fix: ${pattern.fixHint}`,
  27. ];
  28. if (available) {
  29. lines.push(`Available: ${available}`);
  30. }
  31. lines.push(
  32. 'Retry now with corrected parameters. Example:',
  33. 'task(description="...", prompt="...", category="unspecified-low", run_in_background=false, load_skills=[])',
  34. );
  35. return lines.join('\n');
  36. }
  37. export function createDelegateTaskRetryHook(_ctx: PluginInput) {
  38. return {
  39. 'tool.execute.after': async (
  40. input: { tool: string },
  41. output: { output: unknown },
  42. ): Promise<void> => {
  43. const toolName = input.tool.toLowerCase();
  44. const isDelegateTool = toolName === 'task';
  45. if (!isDelegateTool) return;
  46. if (typeof output.output !== 'string') return;
  47. const detected = detectDelegateTaskError(output.output);
  48. if (!detected) return;
  49. output.output += `\n${buildRetryGuidance(detected)}`;
  50. },
  51. };
  52. }