Skip to content

Agents v1 (5/17): REST API for agent definitions, runs, attachments, run-now and the HTTP trigger endpoint #2804

Closed

Description

@propr-dev

Context

With the store (issues 2-3) and the trigger primitive (issue 4) in place, the API exposes Agents to the web UI and to external automation. The HTTP trigger endpoint is the v1 integration point for event-driven behavior: a GitHub Action, a webhook relay or the user's own cron calls POST /api/agent-definitions/:id/runs with an Idempotency-Key header.

Route prefix choice: /api/agents/* already belongs to coding-agent operations (agentRoutes.ts: health, chat, OpenCode models). To avoid colliding with or confusing that namespace, Agents use /api/agent-definitions and /api/agent-runs.

Requirements

New packages/api/routes/agentDefinitionRoutes.ts (createAgentDefinitionRoutes({ db, services? })) registered in packages/api/server.ts operational routes:

Method Path Purpose
GET /api/agent-definitions List the caller's definitions (offset, limit)
GET /api/agent-definitions/contract AGENT_DEFINITION_CONTRACT for the UI form
POST /api/agent-definitions Create
GET /api/agent-definitions/:id Read
PATCH /api/agent-definitions/:id Update (expectedRevision in body → 409 on conflict)
DELETE /api/agent-definitions/:id Delete (refuses with 409 while a run is running/acting)
POST /api/agent-definitions/:id/attachments Upload an input file (reuse goalAttachmentUpload multer + AttachmentService.processUpload)
DELETE /api/agent-definitions/:id/attachments/:attachmentId Remove an input file
POST /api/agent-definitions/:id/runs Trigger primitive. Body { trigger?: 'manual' | 'api' | 'cli', source?: string }; header Idempotency-Key
GET /api/agent-definitions/:id/runs Run history (no report bodies)
GET /api/agent-runs/:runId Run detail with report
POST /api/agent-runs/:runId/cancel Cancel; stops the underlying task via stopTaskExecution when running

Rules:

  1. Every route requires an authenticated user and is owner-scoped (404 for another user's resources — never 403, so existence is not leaked; same convention as goals).
  2. Demo mode rejects mutations (the global demoModeReadOnlyMiddleware already covers non-GET routes; verify).
  3. Repository grant: create, update (when repositories change) and trigger call verifyGitHubRepositoryAccess(repo, token) for every repository using resolveGitHubMetadataToken(req), exactly like verifyPlannerRepositoryAccess. A user cannot create an agent over a repository they cannot read.
  4. Body validation via validateAgentDefinitionInput (issue 1) then validateAgentDefinitionRuntime (issue 4).
  5. trigger defaults to manual when the request carries a browser session and api otherwise (bearer / instance token); callers may pass cli. mcp and schedule are not accepted over REST.
  6. Errors map status/code from core errors to JSON { error, code }.
  7. Attachments stored under storage/agent-definitions/<definitionId>/ with the same allowed MIME types and 10 MB limit as goal attachments; metadata kept in agent_definitions.attachments.
  8. Route tests packages/api/test/agentDefinitionRoutes.test.ts.

Implementation Specification

  • Keep handlers thin; core does the work. Inject verifyAccess, resolveToken, trigger, stopTask services for tests.
  • The trigger endpoint returns 202 with { run, created }; a replayed key returns 200 with the original run.
  • The cost gate is attached in issue 11 by passing gate into triggerAgentRun; leave a gate service hook defaulting to undefined.

Acceptance Criteria

  • CRUD round-trip works for the owner; another user gets 404 on every route.
  • Creating an agent over a repository the user cannot access returns 404 REPOSITORY_NOT_ACCESSIBLE (via handleGitHubRepositoryAccessError).
  • POST .../runs with the same Idempotency-Key twice returns the same run id, status 202 then 200.
  • Deleting a definition with a running run returns 409.
  • Cancel on a queued run moves it to cancelled; on a running run it also calls stopTaskExecution(reportTaskId).
  • Routes registered without duplicates (assertNoDuplicateRoutes passes).

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    A thin Express route factory over the core store and trigger primitive, following taskSubmissionRoutes.ts and goalRoutes.ts conventions: authenticated, owner-scoped, injected services for tests. Repository grant enforcement happens at the API boundary because only the API has the caller's GitHub credential; core re-checks instance-level enablement at every trigger. We reuse goalAttachmentUpload (multer config, MIME/extension validation) and AttachmentService.processUpload rather than writing a third upload pipeline.

    Alternatives: putting the trigger under /api/agents/:id/run — rejected because /api/agents is the coding-agent namespace and a definition id could collide with existing sub-paths like /api/agents/chat.

    File: packages/api/routes/agentDefinitionRoutes.ts (new file)

    Why this file: The HTTP surface for the UI and for external automation. It translates requests into core calls and enforces the user's repository grant.

    import path from 'node:path';
    import fs from 'fs-extra';
    import type { Request, Response } from 'express';
    import type { Knex } from 'knex';
    import {
      AttachmentService, createAgentDefinition, deleteAgentDefinition, getAgentDefinition, getAgentRun,
      listAgentDefinitions, listAgentRuns, setAgentDefinitionAttachments, stopTaskExecution,
      transitionAgentRun, triggerAgentRun, updateAgentDefinition, validateAgentDefinitionRuntime,
      type AgentRunGateDecision, type MulterFile,
    } from '@propr/core';
    import { AGENT_DEFINITION_CONTRACT, AGENT_MAX_ATTACHMENTS, validateAgentDefinitionInput, type AgentDefinition, type AgentRunTrigger } from '@propr/shared';
    import { handleGitHubRepositoryAccessError, resolveGitHubMetadataToken, verifyGitHubRepositoryAccess } from '../githubMetadataAuth.js';
    import { removeTemporaryGoalUploads } from '../services/goalAttachmentService.js';
    import { validatePagination } from './validation.js';
    
    export interface AgentDefinitionRouteServices {
      verifyAccess?: (repository: string, token: string) => Promise<void>;
      resolveToken?: (req: Request) => Promise<string>;
      trigger?: typeof triggerAgentRun;
      stopTask?: (taskId: string) => Promise<unknown>;
      /** Cost gate (issue 11). Undefined means every trigger proceeds. */
      gate?: (definition: AgentDefinition, trigger: AgentRunTrigger) => Promise<AgentRunGateDecision>;
      validateRuntime?: typeof validateAgentDefinitionRuntime;
    }
    
    const ACTIVE_STATES = ['running', 'acting'];
    const ATTACHMENT_ROOT = path.join(process.cwd(), 'storage', 'agent-definitions');
    
    export function createAgentDefinitionRoutes({ db, services = {} }: { db: Knex; services?: AgentDefinitionRouteServices }) {
      const verifyAccess = services.verifyAccess ?? verifyGitHubRepositoryAccess;
      const resolveToken = services.resolveToken ?? ((req: Request) => resolveGitHubMetadataToken(req));
      const trigger = services.trigger ?? triggerAgentRun;
      const validateRuntime = services.validateRuntime ?? validateAgentDefinitionRuntime;
      const stopTask = services.stopTask ?? ((taskId: string) => stopTaskExecution(taskId, { ensureCancelled: true, cancellationReason: 'cancelled_by_user' } as never));
    
      const ownerId = (req: Request) => String(req.user!.id);
    
      /** Every repository in scope must be readable with the caller's own GitHub grant. */
      async function assertRepositoryGrant(req: Request, repositories: string[]): Promise<void> {
        const token = await resolveToken(req);
        for (const repository of repositories) await verifyAccess(repository, token);
      }
    
      async function send(req: Request, res: Response, work: () => Promise<void>) {
        try {
          if (!req.user) { res.status(401).json({ error: 'Authentication required' }); return; }
          await work();
        } catch (error) {
          // Maps GitHub 401/403/404 to the shared repository-access responses.
          if (await handleGitHubRepositoryAccessError(req, res, error)) return;
          const { status = 500, code } = error as { status?: number; code?: string };
          res.status(status).json({ error: status >= 500 && !code ? 'Internal server error' : (error as Error).message, ...(code ? { code } : {}) });
        }
      }
    
      async function ownedDefinition(req: Request, res: Response): Promise<AgentDefinition | undefined> {
        const definition = await getAgentDefinition(String(req.params.id), ownerId(req), db);
        // 404 (not 403) so another user cannot probe which ids exist.
        if (!definition) res.status(404).json({ error: 'Agent not found' });
        return definition;
      }
    
      return {
        contract: (_req: Request, res: Response) => { res.json(AGENT_DEFINITION_CONTRACT); },
    
        list: (req: Request, res: Response) => send(req, res, async () => {
          const page = validatePagination(req.query as Record<string, string>);
          if (!page.valid) { res.status(400).json({ error: page.error }); return; }
          res.json(await listAgentDefinitions(ownerId(req), { offset: page.offset ?? 0, limit: page.limit ?? 50 }, db));
        }),
    
        create: (req: Request, res: Response) => send(req, res, async () => {
          const error = validateAgentDefinitionInput(req.body ?? {});
          if (error) { res.status(400).json({ error, code: 'INVALID_INPUT' }); return; }
          await assertRepositoryGrant(req, req.body.repositories);
          const definition = await createAgentDefinition(ownerId(req), req.body, db);
          // Validate against the live catalog after insert-free checks; on failure, roll back the row.
          try { await validateRuntime(definition); } catch (cause) { await deleteAgentDefinition(definition.id, ownerId(req), db); throw cause; }
          res.status(201).json({ definition });
        }),
    
        get: (req: Request, res: Response) => send(req, res, async () => {
          const definition = await ownedDefinition(req, res);
          if (definition) res.json({ definition });
        }),
    
        update: (req: Request, res: Response) => send(req, res, async () => {
          const current = await ownedDefinition(req, res);
          if (!current) return;
          const { expectedRevision, ...patch } = req.body ?? {};
          const error = validateAgentDefinitionInput(patch, { partial: true });
          if (error) { res.status(400).json({ error, code: 'INVALID_INPUT' }); return; }
          // Only re-check the grant when the scope changes: cheaper, same guarantee.
          if (patch.repositories) await assertRepositoryGrant(req, patch.repositories);
          const updated = await updateAgentDefinition(current.id, ownerId(req), patch, { expectedRevision, database: db });
          if (patch.repositories || patch.agentAlias || patch.model || patch.capabilities) await validateRuntime(updated);
          res.json({ definition: updated });
        }),
    
        remove: (req: Request, res: Response) => send(req, res, async () => {
          const definition = await ownedDefinition(req, res);
          if (!definition) return;
          const active = await db('agent_runs').where({ definition_id: definition.id }).whereIn('state', ACTIVE_STATES).first('id');
          // Deleting would cascade the receipt of a live run and orphan its container.
          if (active) { res.status(409).json({ error: 'Cancel the running run before deleting this agent', code: 'AGENT_RUN_ACTIVE' }); return; }
          await deleteAgentDefinition(definition.id, ownerId(req), db);
          await fs.remove(path.join(ATTACHMENT_ROOT, definition.id));
          res.status(204).send();
        }),
    
        uploadAttachment: async (req: Request, res: Response) => {
          const files = (Array.isArray(req.files) ? req.files : []) as MulterFile[];
          try {
            await send(req, res, async () => {
              const definition = await ownedDefinition(req, res);
              if (!definition) return;
              if (definition.attachments.length + files.length > AGENT_MAX_ATTACHMENTS) { res.status(400).json({ error: `At most ${AGENT_MAX_ATTACHMENTS} files per agent` }); return; }
              const added = [];
              for (const file of files) {
                // Same processing (type checks, image resizing) as plan and goal attachments.
                const stored = await AttachmentService.processUpload(file, definition.id, { storageRoot: ATTACHMENT_ROOT, persistAttachment: async () => undefined });
                added.push({ id: stored.id, originalName: stored.originalName, mimeType: stored.mimeType, sizeBytes: file.size, storedPath: stored.storedPath });
              }
              await setAgentDefinitionAttachments(definition.id, ownerId(req), [...definition.attachments, ...added], db);
              res.status(201).json({ attachments: added.map(({ storedPath: _storedPath, ...rest }) => rest) });
            });
          } finally { await removeTemporaryGoalUploads(files); }
        },
    
        removeAttachment: (req: Request, res: Response) => send(req, res, async () => {
          const definition = await ownedDefinition(req, res);
          if (!definition) return;
          const remaining = definition.attachments.filter(file => file.id !== req.params.attachmentId);
          if (remaining.length === definition.attachments.length) { res.status(404).json({ error: 'Attachment not found' }); return; }
          await setAgentDefinitionAttachments(definition.id, ownerId(req), remaining, db);
          res.status(204).send();
        }),
    
        /** The trigger primitive over HTTP. External automation calls this with an Idempotency-Key. */
        triggerRun: (req: Request, res: Response) => send(req, res, async () => {
          const definition = await ownedDefinition(req, res);
          if (!definition) return;
          const requested = req.body?.trigger;
          const isBrowser = req.authenticationMethod === 'session';
          const triggerKind: AgentRunTrigger = requested === 'cli' ? 'cli' : requested === 'manual' && isBrowser ? 'manual' : isBrowser ? 'manual' : 'api';
          const key = req.get('Idempotency-Key');
          if (key !== undefined && !/^[\w.:-]{8,128}$/.test(key)) { res.status(400).json({ error: 'Idempotency-Key must be 8-128 characters of [A-Za-z0-9_.:-]' }); return; }
          // The grant can be revoked after the agent was saved; re-check on every run.
          await assertRepositoryGrant(req, definition.repositories);
          const source = typeof req.body?.source === 'string' ? req.body.source.slice(0, 255) : null;
          const result = await trigger({ definition, trigger: triggerKind, triggerSource: source, idempotencyKey: key ?? null, gate: services.gate });
          res.status(result.created ? 202 : 200).json(result);
        }),
    
        listRuns: (req: Request, res: Response) => send(req, res, async () => {
          const definition = await ownedDefinition(req, res);
          if (!definition) return;
          const page = validatePagination(req.query as Record<string, string>);
          if (!page.valid) { res.status(400).json({ error: page.error }); return; }
          res.json(await listAgentRuns(definition.id, ownerId(req), { offset: page.offset ?? 0, limit: page.limit ?? 20 }, db));
        }),
    
        getRun: (req: Request, res: Response) => send(req, res, async () => {
          const run = await getAgentRun(String(req.params.runId), ownerId(req), db);
          if (!run) { res.status(404).json({ error: 'Run not found' }); return; }
          res.json({ run });
        }),
    
        cancelRun: (req: Request, res: Response) => send(req, res, async () => {
          const run = await getAgentRun(String(req.params.runId), ownerId(req), db);
          if (!run) { res.status(404).json({ error: 'Run not found' }); return; }
          const liveTask = run.state === 'running' ? run.reportTaskId : run.state === 'acting' ? run.actionTaskId : null;
          const cancelled = await transitionAgentRun(run.id, ['queued', 'deferred', 'running', 'awaiting_approval', 'acting'], 'cancelled', {}, db);
          if (!cancelled) { res.status(409).json({ error: `Run is already ${run.state}`, code: 'AGENT_RUN_TERMINAL' }); return; }
          // Reuse the ordinary task stop path: the container is just a task container.
          if (liveTask) await stopTask(liveTask).catch(() => undefined);
          res.json({ run: cancelled });
        }),
      };
    }

    File: packages/api/routes/index.ts

    --- a/packages/api/routes/index.ts
    +++ b/packages/api/routes/index.ts
    @@
     export { createGoalRoutes } from './goalRoutes.js';
    +export { createAgentDefinitionRoutes } from './agentDefinitionRoutes.js';

    File: packages/api/server.ts

    Why this file: Registers the routes in the operational route table so assertNoDuplicateRoutes and route timing apply.

    --- a/packages/api/server.ts
    +++ b/packages/api/server.ts
    @@
       createGoalRoutes,
    +  createAgentDefinitionRoutes,
    @@
       const goalRoutes = createGoalRoutes({ db, taskQueue, redisClient });
    +  const agentDefinitionRoutes = createAgentDefinitionRoutes({ db });
    @@
         ['get', '/api/desktop/active-work', activeWorkRoutes.getActiveWork],
    +    // Agents. `/api/agents/*` is the coding-agent namespace, hence a separate prefix.
    +    ['get', '/api/agent-definitions', agentDefinitionRoutes.list], ['get', '/api/agent-definitions/contract', agentDefinitionRoutes.contract],
    +    ['post', '/api/agent-definitions', agentDefinitionRoutes.create], ['get', '/api/agent-definitions/:id', agentDefinitionRoutes.get],
    +    ['patch', '/api/agent-definitions/:id', agentDefinitionRoutes.update], ['delete', '/api/agent-definitions/:id', agentDefinitionRoutes.remove],
    +    ['post', '/api/agent-definitions/:id/attachments', goalAttachmentUpload, agentDefinitionRoutes.uploadAttachment],
    +    ['delete', '/api/agent-definitions/:id/attachments/:attachmentId', agentDefinitionRoutes.removeAttachment],
    +    ['post', '/api/agent-definitions/:id/runs', agentDefinitionRoutes.triggerRun], ['get', '/api/agent-definitions/:id/runs', agentDefinitionRoutes.listRuns],
    +    ['get', '/api/agent-runs/:runId', agentDefinitionRoutes.getRun], ['post', '/api/agent-runs/:runId/cancel', agentDefinitionRoutes.cancelRun],

    Register /api/agent-definitions/contract before /api/agent-definitions/:id (Express matches in order).

    File: packages/api/test/agentDefinitionRoutes.test.ts (new file)

    Why this file: Proves owner scoping, grant enforcement and idempotent triggering at the HTTP boundary with fake services.

    import assert from 'node:assert/strict';
    import { after, test } from 'node:test';
    import knex from 'knex';
    import type { Request, Response } from 'express';
    import { closeConnection } from '@propr/core';
    import { up } from '../../core/src/db/migrations/20261006000000_create_agent_definitions.js';
    import { createAgentDefinitionRoutes } from '../routes/agentDefinitionRoutes.js';
    
    after(closeConnection);
    
    function call(handler: (req: Request, res: Response) => unknown, req: Partial<Request>) {
      const state = { status: 200, body: undefined as unknown };
      const res = { status(code: number) { state.status = code; return this; }, json(body: unknown) { state.body = body; return this; }, send() { return this; } } as unknown as Response;
      return Promise.resolve(handler({ params: {}, query: {}, body: {}, get: () => undefined, authenticationMethod: 'session', ...req } as Request, res)).then(() => state);
    }
    
    async function fixture(denied: string[] = []) {
      const db = knex({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
      await up(db);
      const routes = createAgentDefinitionRoutes({ db, services: {
        resolveToken: async () => 'token',
        verifyAccess: async repo => { if (denied.includes(repo)) throw Object.assign(new Error('nope'), { status: 404 }); },
        validateRuntime: async () => undefined,
        trigger: (async ({ definition, idempotencyKey }) => ({ run: { id: `run-${idempotencyKey}`, definitionId: definition.id }, created: idempotencyKey !== 'replayed-key', enqueued: true })) as never,
      } });
      return { db, routes };
    }
    const body = { name: 'Bugs', repositories: ['acme/web'], prompt: 'Triage new bugs', agentAlias: 'claude', model: 'claude-opus-5-5', capabilities: [], autonomyMode: 'dry_run' };
    
    test('owner scoping and repository grant', async () => {
      const { db, routes } = await fixture(['acme/secret']);
      const created = await call(routes.create, { user: { id: 'alice' } as never, body });
      assert.equal(created.status, 201);
      const id = (created.body as { definition: { id: string } }).definition.id;
      assert.equal((await call(routes.get, { user: { id: 'bob' } as never, params: { id } })).status, 404);
      const denied = await call(routes.create, { user: { id: 'alice' } as never, body: { ...body, repositories: ['acme/secret'] } });
      assert.equal(denied.status, 404);
      await db.destroy();
    });
    
    test('trigger returns 202 for a new run and 200 for a replay', async () => {
      const { db, routes } = await fixture();
      const created = await call(routes.create, { user: { id: 'alice' } as never, body });
      const id = (created.body as { definition: { id: string } }).definition.id;
      const first = await call(routes.triggerRun, { user: { id: 'alice' } as never, params: { id }, get: (() => 'fresh-key-1') as never });
      const replay = await call(routes.triggerRun, { user: { id: 'alice' } as never, params: { id }, get: (() => 'replayed-key') as never });
      assert.equal(first.status, 202);
      assert.equal(replay.status, 200);
      await db.destroy();
    });
  2. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5-5 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5-5
    • Branch: 2804/claude-opus-5-5-agents-v1-5-17-rest-api-f-20261006-1459-lfp
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2804-20261006-1459-claude-opus-5-5-lfp

    🔍 Track Task Execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions