# Delegation API

Multi-agent task delegation with witness-based verification. Delegate tasks to teammates and verify completion with automated checks.

## Quick Start

```typescript
handler: async (input, ctx) => {
  // List available teammates
  const { teammates } = await ctx.majk.delegation.list_teammates();

  // Delegate a task
  const result = await ctx.majk.delegation.delegate_task({
    teammate: 'code-reviewer',
    task: 'Review the auth module for security issues',
    witness: { bash: 'npm test' }
  });

  // Wait for completion
  const status = await ctx.majk.delegation.await_task({
    taskId: result.taskId
  });

  return { success: status.status === 'completed' };
}
```

## API Reference

### list_teammates()

List all available teammates that can be delegated tasks to.

```typescript
const { teammates, count } = await ctx.majk.delegation.list_teammates();
// teammates: Array<{ id, name, skills?, description? }>
```

### delegate_task(input)

Delegate a task to a teammate asynchronously. Returns immediately with a task ID.

```typescript
const result = await ctx.majk.delegation.delegate_task({
  teammate: string,       // Teammate name or ID
  task: string,           // Task description
  witness: Witness,       // Verification criteria
  context?: Witness,      // Additional context
  workingDirectory?: string,
  background?: boolean,   // Run hidden from UI (default: false)
  rawPrompt?: boolean     // Use task as-is without enhancement (default: false)
});
// Returns: { taskId, teammateId, teammateName, conversationId, status: 'running' }
```

#### Background Mode

Use `background: true` to run tasks hidden from the UI. Useful for batch operations:

```typescript
// Run multiple tasks in background without cluttering the UI
const tasks = await Promise.all(
  items.map(item => ctx.majk.delegation.delegate_task({
    teammate: 'processor',
    task: `Process ${item}`,
    witness: { file: { path: `output/${item}.json`, exists: true } },
    background: true  // Hidden from NavPane
  }))
);
```

#### Raw Prompt Mode

Use `rawPrompt: true` to bypass task enhancement. By default, tasks are enhanced with context, witness criteria, and reporting instructions. When using raw prompts, you must include reporting instructions yourself:

```typescript
// Get the standard reporting instructions
const { instructions } = await ctx.majk.delegation.get_reporting_instructions();

// Use raw prompt with your own structure
const result = await ctx.majk.delegation.delegate_task({
  teammate: 'code-reviewer',
  task: `
## Custom Task Format

Your specific instructions here...

${instructions}
  `,
  witness: { bash: 'npm test' },
  rawPrompt: true  // Task used as-is, no enhancement
});
```

### get_reporting_instructions(input?)

Get the standard reporting instructions template. Use this when delegating with `rawPrompt: true`.

```typescript
const { instructions, toolNames } = await ctx.majk.delegation.get_reporting_instructions({
  taskId?: string  // Optional task ID to include in instructions
});
// Returns: {
//   instructions: string,  // Markdown template for reporting
//   toolNames: { reportDone, reportBlocker, checkWitness },
//   _hint: string
// }
```

### await_task(input)

Wait for a task to complete. Blocks until finished or timeout.

```typescript
const status = await ctx.majk.delegation.await_task({
  taskId: string,
  timeoutMs?: number    // Default: no timeout
});
// Returns: DelegationTaskStatusOutput
```

### await_tasks(input)

Wait for multiple tasks (fan-out/fan-in pattern).

```typescript
const results = await ctx.majk.delegation.await_tasks({
  taskIds: string[],
  timeoutMs?: number
});
// Returns: { results, summary: { total, completed, failed, blocked, stillRunning }, allCompleted, allSucceeded }
```

### check_task_status(input)

Check current status of a delegated task.

```typescript
const status = await ctx.majk.delegation.check_task_status({
  taskId: string,
  messageCount?: number  // Include recent messages
});
```

### check_witness(input)

Run a witness verification immediately.

```typescript
const result = await ctx.majk.delegation.check_witness({
  witness: Witness,
  workingDirectory?: string
});
// Returns: { passed, evidence, strength, executionTimeMs }
```

### get_blockers(input?)

List all currently blocked tasks.

```typescript
const { blockers, count } = await ctx.majk.delegation.get_blockers({
  teammateId?: string,
  assignedTo?: string
});
```

### resolve_blocker(input)

Resolve a blocker on a task.

```typescript
const result = await ctx.majk.delegation.resolve_blocker({
  taskId: string,
  action: 'update_task' | 'update_witness' | 'send_instruction' | 'unblock',
  newTask?: string,
  newWitness?: Witness,
  instruction?: string,
  resolution?: string
});
```

## Witness Types

Witnesses verify task completion:

```typescript
// Command execution
{ bash: 'npm test' }
{ bash: { command: 'npm test', exit_code: 0, stdout_contains: 'passed' } }

// File checks
{ file: { path: 'output.json', exists: true, contains: 'success' } }

// HTTP checks
{ http: { url: 'http://localhost:3000/health', status: 200 } }

// AI verification
{ llm: { prompt: 'Does this code handle errors properly?', file: 'src/handler.ts' } }

// Visual verification
{ vision: { image: 'screenshot.png', checklist: ['Has submit button', 'Shows form'] } }

// JavaScript
{ js: { code: 'return fs.existsSync("output.txt")' } }

// Combine witnesses
{ all: [{ bash: 'npm test' }, { file: { path: 'coverage.json', exists: true } }] }
{ any: [{ bash: 'npm test' }, { bash: 'yarn test' }] }
```

## Fan-Out/Fan-In Pattern

```typescript
// Delegate to multiple teammates in parallel
const tasks = await Promise.all([
  ctx.majk.delegation.delegate_task({
    teammate: 'backend-dev',
    task: 'Implement the API endpoint',
    witness: { bash: 'npm test -- --grep "api"' }
  }),
  ctx.majk.delegation.delegate_task({
    teammate: 'frontend-dev',
    task: 'Build the UI component',
    witness: { bash: 'npm test -- --grep "ui"' }
  })
]);

// Wait for all to complete
const results = await ctx.majk.delegation.await_tasks({
  taskIds: tasks.map(t => t.taskId),
  timeoutMs: 300000
});

if (results.allSucceeded) {
  ctx.logger.info('All tasks completed successfully');
}
```

## Best Practices

1. **Clear task descriptions** - Be specific about what needs to be done
2. **Appropriate witnesses** - Choose verification that proves completion
3. **Handle blockers** - Monitor and resolve blocked tasks
4. **Set timeouts** - Prevent indefinite waits
5. **Use fan-out for parallelism** - Delegate independent tasks simultaneously

## Next Steps

Run `npx @majkapp/plugin-kit --batch` - Batch processing API
Run `npx @majkapp/plugin-kit --tasks` - Task management API
Run `npx @majkapp/plugin-kit --teammates` - Teammate configuration
