Spaces:
Runtime error
Runtime error
Nyk commited on
Commit ·
0d54fcf
1
Parent(s): 7f2d33e
feat(tasks): add agent queue polling endpoint
Browse files- README.md +1 -0
- openapi.json +84 -0
- src/app/api/tasks/queue/route.ts +147 -0
- tests/task-queue.spec.ts +69 -0
README.md
CHANGED
|
@@ -217,6 +217,7 @@ All endpoints require authentication unless noted. Full reference below.
|
|
| 217 |
| `POST` | `/api/agents/message` | operator | Send message to agent |
|
| 218 |
| `GET` | `/api/tasks` | viewer | List tasks (filter: `?status=`, `?assigned_to=`, `?priority=`) |
|
| 219 |
| `POST` | `/api/tasks` | operator | Create task |
|
|
|
|
| 220 |
| `GET` | `/api/tasks/[id]` | viewer | Task details |
|
| 221 |
| `PUT` | `/api/tasks/[id]` | operator | Update task |
|
| 222 |
| `DELETE` | `/api/tasks/[id]` | admin | Delete task |
|
|
|
|
| 217 |
| `POST` | `/api/agents/message` | operator | Send message to agent |
|
| 218 |
| `GET` | `/api/tasks` | viewer | List tasks (filter: `?status=`, `?assigned_to=`, `?priority=`) |
|
| 219 |
| `POST` | `/api/tasks` | operator | Create task |
|
| 220 |
+
| `GET` | `/api/tasks/queue` | operator | Poll next task for an agent (`?agent=`, optional `?max_capacity=`) |
|
| 221 |
| `GET` | `/api/tasks/[id]` | viewer | Task details |
|
| 222 |
| `PUT` | `/api/tasks/[id]` | operator | Update task |
|
| 223 |
| `DELETE` | `/api/tasks/[id]` | admin | Delete task |
|
openapi.json
CHANGED
|
@@ -5814,6 +5814,90 @@
|
|
| 5814 |
}
|
| 5815 |
}
|
| 5816 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5817 |
"/api/tasks/{id}": {
|
| 5818 |
"get": {
|
| 5819 |
"tags": [
|
|
|
|
| 5814 |
}
|
| 5815 |
}
|
| 5816 |
},
|
| 5817 |
+
"/api/tasks/queue": {
|
| 5818 |
+
"get": {
|
| 5819 |
+
"tags": [
|
| 5820 |
+
"Tasks"
|
| 5821 |
+
],
|
| 5822 |
+
"summary": "Poll next task for an agent",
|
| 5823 |
+
"operationId": "pollTaskQueue",
|
| 5824 |
+
"parameters": [
|
| 5825 |
+
{
|
| 5826 |
+
"name": "agent",
|
| 5827 |
+
"in": "query",
|
| 5828 |
+
"required": false,
|
| 5829 |
+
"schema": {
|
| 5830 |
+
"type": "string"
|
| 5831 |
+
},
|
| 5832 |
+
"description": "Agent name. Optional when x-agent-name header is provided."
|
| 5833 |
+
},
|
| 5834 |
+
{
|
| 5835 |
+
"name": "max_capacity",
|
| 5836 |
+
"in": "query",
|
| 5837 |
+
"required": false,
|
| 5838 |
+
"schema": {
|
| 5839 |
+
"type": "integer",
|
| 5840 |
+
"minimum": 1,
|
| 5841 |
+
"maximum": 20,
|
| 5842 |
+
"default": 1
|
| 5843 |
+
}
|
| 5844 |
+
},
|
| 5845 |
+
{
|
| 5846 |
+
"name": "x-agent-name",
|
| 5847 |
+
"in": "header",
|
| 5848 |
+
"required": false,
|
| 5849 |
+
"schema": {
|
| 5850 |
+
"type": "string"
|
| 5851 |
+
},
|
| 5852 |
+
"description": "Agent attribution header used when `agent` query param is omitted."
|
| 5853 |
+
}
|
| 5854 |
+
],
|
| 5855 |
+
"responses": {
|
| 5856 |
+
"200": {
|
| 5857 |
+
"description": "Queue poll result",
|
| 5858 |
+
"content": {
|
| 5859 |
+
"application/json": {
|
| 5860 |
+
"schema": {
|
| 5861 |
+
"type": "object",
|
| 5862 |
+
"properties": {
|
| 5863 |
+
"task": {
|
| 5864 |
+
"oneOf": [
|
| 5865 |
+
{ "$ref": "#/components/schemas/Task" },
|
| 5866 |
+
{ "type": "null" }
|
| 5867 |
+
]
|
| 5868 |
+
},
|
| 5869 |
+
"reason": {
|
| 5870 |
+
"type": "string",
|
| 5871 |
+
"enum": [
|
| 5872 |
+
"continue_current",
|
| 5873 |
+
"assigned",
|
| 5874 |
+
"at_capacity",
|
| 5875 |
+
"no_tasks_available"
|
| 5876 |
+
]
|
| 5877 |
+
},
|
| 5878 |
+
"agent": {
|
| 5879 |
+
"type": "string"
|
| 5880 |
+
},
|
| 5881 |
+
"timestamp": {
|
| 5882 |
+
"type": "integer"
|
| 5883 |
+
}
|
| 5884 |
+
}
|
| 5885 |
+
}
|
| 5886 |
+
}
|
| 5887 |
+
}
|
| 5888 |
+
},
|
| 5889 |
+
"400": {
|
| 5890 |
+
"$ref": "#/components/responses/BadRequest"
|
| 5891 |
+
},
|
| 5892 |
+
"401": {
|
| 5893 |
+
"$ref": "#/components/responses/Unauthorized"
|
| 5894 |
+
},
|
| 5895 |
+
"403": {
|
| 5896 |
+
"$ref": "#/components/responses/Forbidden"
|
| 5897 |
+
}
|
| 5898 |
+
}
|
| 5899 |
+
}
|
| 5900 |
+
},
|
| 5901 |
"/api/tasks/{id}": {
|
| 5902 |
"get": {
|
| 5903 |
"tags": [
|
src/app/api/tasks/queue/route.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { NextRequest, NextResponse } from 'next/server'
|
| 2 |
+
import { getDatabase } from '@/lib/db'
|
| 3 |
+
import { requireRole } from '@/lib/auth'
|
| 4 |
+
import { logger } from '@/lib/logger'
|
| 5 |
+
|
| 6 |
+
type QueueReason = 'continue_current' | 'assigned' | 'at_capacity' | 'no_tasks_available'
|
| 7 |
+
|
| 8 |
+
function safeParseJson<T>(raw: string | null | undefined, fallback: T): T {
|
| 9 |
+
if (!raw) return fallback
|
| 10 |
+
try {
|
| 11 |
+
return JSON.parse(raw) as T
|
| 12 |
+
} catch {
|
| 13 |
+
return fallback
|
| 14 |
+
}
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
function mapTaskRow(task: any) {
|
| 18 |
+
return {
|
| 19 |
+
...task,
|
| 20 |
+
tags: safeParseJson(task.tags, [] as string[]),
|
| 21 |
+
metadata: safeParseJson(task.metadata, {} as Record<string, unknown>),
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
function priorityRankSql() {
|
| 26 |
+
return `
|
| 27 |
+
CASE priority
|
| 28 |
+
WHEN 'critical' THEN 0
|
| 29 |
+
WHEN 'high' THEN 1
|
| 30 |
+
WHEN 'medium' THEN 2
|
| 31 |
+
WHEN 'low' THEN 3
|
| 32 |
+
ELSE 4
|
| 33 |
+
END
|
| 34 |
+
`
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
/**
|
| 38 |
+
* GET /api/tasks/queue - Poll next task for an agent.
|
| 39 |
+
*
|
| 40 |
+
* Query params:
|
| 41 |
+
* - agent: required agent name (or use x-agent-name header)
|
| 42 |
+
* - max_capacity: optional integer 1..20 (default 1)
|
| 43 |
+
*/
|
| 44 |
+
export async function GET(request: NextRequest) {
|
| 45 |
+
const auth = requireRole(request, 'operator')
|
| 46 |
+
if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
|
| 47 |
+
|
| 48 |
+
try {
|
| 49 |
+
const db = getDatabase()
|
| 50 |
+
const workspaceId = auth.user.workspace_id
|
| 51 |
+
const { searchParams } = new URL(request.url)
|
| 52 |
+
|
| 53 |
+
const agent =
|
| 54 |
+
(searchParams.get('agent') || '').trim() ||
|
| 55 |
+
(request.headers.get('x-agent-name') || '').trim()
|
| 56 |
+
|
| 57 |
+
if (!agent) {
|
| 58 |
+
return NextResponse.json({ error: 'Missing agent. Provide ?agent=... or x-agent-name header.' }, { status: 400 })
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
const maxCapacityRaw = searchParams.get('max_capacity') || '1'
|
| 62 |
+
if (!/^\d+$/.test(maxCapacityRaw)) {
|
| 63 |
+
return NextResponse.json({ error: 'Invalid max_capacity. Expected integer 1..20.' }, { status: 400 })
|
| 64 |
+
}
|
| 65 |
+
const maxCapacity = Number(maxCapacityRaw)
|
| 66 |
+
if (!Number.isInteger(maxCapacity) || maxCapacity < 1 || maxCapacity > 20) {
|
| 67 |
+
return NextResponse.json({ error: 'Invalid max_capacity. Expected integer 1..20.' }, { status: 400 })
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
const now = Math.floor(Date.now() / 1000)
|
| 71 |
+
|
| 72 |
+
const currentTask = db.prepare(`
|
| 73 |
+
SELECT *
|
| 74 |
+
FROM tasks
|
| 75 |
+
WHERE workspace_id = ? AND assigned_to = ? AND status = 'in_progress'
|
| 76 |
+
ORDER BY updated_at DESC
|
| 77 |
+
LIMIT 1
|
| 78 |
+
`).get(workspaceId, agent) as any | undefined
|
| 79 |
+
|
| 80 |
+
if (currentTask) {
|
| 81 |
+
return NextResponse.json({
|
| 82 |
+
task: mapTaskRow(currentTask),
|
| 83 |
+
reason: 'continue_current' as QueueReason,
|
| 84 |
+
agent,
|
| 85 |
+
timestamp: now,
|
| 86 |
+
})
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
const inProgressCount = (db.prepare(`
|
| 90 |
+
SELECT COUNT(*) as c
|
| 91 |
+
FROM tasks
|
| 92 |
+
WHERE workspace_id = ? AND assigned_to = ? AND status = 'in_progress'
|
| 93 |
+
`).get(workspaceId, agent) as { c: number }).c
|
| 94 |
+
|
| 95 |
+
if (inProgressCount >= maxCapacity) {
|
| 96 |
+
return NextResponse.json({
|
| 97 |
+
task: null,
|
| 98 |
+
reason: 'at_capacity' as QueueReason,
|
| 99 |
+
agent,
|
| 100 |
+
timestamp: now,
|
| 101 |
+
})
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
// Best-effort atomic pickup loop for race safety.
|
| 105 |
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
| 106 |
+
const candidate = db.prepare(`
|
| 107 |
+
SELECT *
|
| 108 |
+
FROM tasks
|
| 109 |
+
WHERE workspace_id = ?
|
| 110 |
+
AND status IN ('assigned', 'inbox')
|
| 111 |
+
AND (assigned_to IS NULL OR assigned_to = ?)
|
| 112 |
+
ORDER BY ${priorityRankSql()} ASC, due_date ASC NULLS LAST, created_at ASC
|
| 113 |
+
LIMIT 1
|
| 114 |
+
`).get(workspaceId, agent) as any | undefined
|
| 115 |
+
|
| 116 |
+
if (!candidate) break
|
| 117 |
+
|
| 118 |
+
const claimed = db.prepare(`
|
| 119 |
+
UPDATE tasks
|
| 120 |
+
SET status = 'in_progress', assigned_to = ?, updated_at = ?
|
| 121 |
+
WHERE id = ? AND workspace_id = ?
|
| 122 |
+
AND status IN ('assigned', 'inbox')
|
| 123 |
+
AND (assigned_to IS NULL OR assigned_to = ?)
|
| 124 |
+
`).run(agent, now, candidate.id, workspaceId, agent)
|
| 125 |
+
|
| 126 |
+
if (claimed.changes > 0) {
|
| 127 |
+
const task = db.prepare('SELECT * FROM tasks WHERE id = ? AND workspace_id = ?').get(candidate.id, workspaceId) as any
|
| 128 |
+
return NextResponse.json({
|
| 129 |
+
task: mapTaskRow(task),
|
| 130 |
+
reason: 'assigned' as QueueReason,
|
| 131 |
+
agent,
|
| 132 |
+
timestamp: now,
|
| 133 |
+
})
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
return NextResponse.json({
|
| 138 |
+
task: null,
|
| 139 |
+
reason: 'no_tasks_available' as QueueReason,
|
| 140 |
+
agent,
|
| 141 |
+
timestamp: now,
|
| 142 |
+
})
|
| 143 |
+
} catch (error) {
|
| 144 |
+
logger.error({ err: error }, 'GET /api/tasks/queue error')
|
| 145 |
+
return NextResponse.json({ error: 'Failed to poll task queue' }, { status: 500 })
|
| 146 |
+
}
|
| 147 |
+
}
|
tests/task-queue.spec.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { expect, test } from '@playwright/test'
|
| 2 |
+
import { API_KEY_HEADER, createTestTask, deleteTestTask } from './helpers'
|
| 3 |
+
|
| 4 |
+
test.describe('Task Queue API', () => {
|
| 5 |
+
const cleanup: number[] = []
|
| 6 |
+
|
| 7 |
+
test.afterEach(async ({ request }) => {
|
| 8 |
+
for (const id of cleanup) {
|
| 9 |
+
await deleteTestTask(request, id).catch(() => {})
|
| 10 |
+
}
|
| 11 |
+
cleanup.length = 0
|
| 12 |
+
})
|
| 13 |
+
|
| 14 |
+
test('picks the next task and marks it in_progress for agent', async ({ request }) => {
|
| 15 |
+
const low = await createTestTask(request, { priority: 'low', status: 'inbox' })
|
| 16 |
+
const critical = await createTestTask(request, { priority: 'critical', status: 'inbox' })
|
| 17 |
+
cleanup.push(low.id, critical.id)
|
| 18 |
+
|
| 19 |
+
const res = await request.get('/api/tasks/queue?agent=queue-agent', { headers: API_KEY_HEADER })
|
| 20 |
+
expect(res.status()).toBe(200)
|
| 21 |
+
const body = await res.json()
|
| 22 |
+
|
| 23 |
+
expect(body.reason).toBe('assigned')
|
| 24 |
+
expect(body.task).toBeTruthy()
|
| 25 |
+
expect(body.task.id).toBe(critical.id)
|
| 26 |
+
expect(body.task.status).toBe('in_progress')
|
| 27 |
+
expect(body.task.assigned_to).toBe('queue-agent')
|
| 28 |
+
})
|
| 29 |
+
|
| 30 |
+
test('returns current in_progress task as continue_current', async ({ request }) => {
|
| 31 |
+
const task = await createTestTask(request, {
|
| 32 |
+
status: 'in_progress',
|
| 33 |
+
assigned_to: 'queue-agent-2',
|
| 34 |
+
priority: 'high',
|
| 35 |
+
})
|
| 36 |
+
cleanup.push(task.id)
|
| 37 |
+
|
| 38 |
+
const res = await request.get('/api/tasks/queue?agent=queue-agent-2', { headers: API_KEY_HEADER })
|
| 39 |
+
expect(res.status()).toBe(200)
|
| 40 |
+
const body = await res.json()
|
| 41 |
+
expect(body.reason).toBe('continue_current')
|
| 42 |
+
expect(body.task?.id).toBe(task.id)
|
| 43 |
+
})
|
| 44 |
+
|
| 45 |
+
test('validates max_capacity input', async ({ request }) => {
|
| 46 |
+
const res = await request.get('/api/tasks/queue?agent=queue-agent-empty&max_capacity=999', {
|
| 47 |
+
headers: API_KEY_HEADER,
|
| 48 |
+
})
|
| 49 |
+
expect(res.status()).toBe(400)
|
| 50 |
+
})
|
| 51 |
+
|
| 52 |
+
test('uses x-agent-name header when query param is omitted', async ({ request }) => {
|
| 53 |
+
const task = await createTestTask(request, {
|
| 54 |
+
status: 'assigned',
|
| 55 |
+
assigned_to: 'header-agent',
|
| 56 |
+
priority: 'high',
|
| 57 |
+
})
|
| 58 |
+
cleanup.push(task.id)
|
| 59 |
+
|
| 60 |
+
const res = await request.get('/api/tasks/queue', {
|
| 61 |
+
headers: { ...API_KEY_HEADER, 'x-agent-name': 'header-agent' },
|
| 62 |
+
})
|
| 63 |
+
expect(res.status()).toBe(200)
|
| 64 |
+
const body = await res.json()
|
| 65 |
+
expect(body.reason).toBe('assigned')
|
| 66 |
+
expect(body.agent).toBe('header-agent')
|
| 67 |
+
expect(body.task?.id).toBe(task.id)
|
| 68 |
+
})
|
| 69 |
+
})
|