Skip to content

Agents v1 (14/17): CLI — propr automation command group with the run trigger primitive #2813

Closed

Description

@propr-dev

Context

The third surface for the trigger primitive is the CLI, which is also the simplest integration for the user's own cron or a GitHub Actions step (npx propr-cli automation run <id> --idempotency-key "$GITHUB_RUN_ID"). The CLI talks to the REST API from issue 5.

Naming: propr agent already manages coding-agent configurations (Claude, Codex, …). Reusing it would mix two different concepts, so the Agents feature uses a new group propr automation (alias propr automations), and help text explains "Agents (saved automations)". The UI label stays "Agents".

Requirements

  1. packages/cli/src/api/automations.ts: typed client functions listAutomations, getAutomation, triggerAutomationRun(id, { idempotencyKey, source }), listAutomationRuns, getAutomationRun, approveAutomationRun, rejectAutomationRun, cancelAutomationRun, built on ApiClient like api/goals.ts. The trigger sends Idempotency-Key and { trigger: 'cli', source }, and retries transient failures with the same key (reuse the mutate pattern from goals.ts).
  2. packages/cli/src/commands/automationCommands.ts (createAutomationCommand()):
    • list [--json]
    • show <id> [--json]
    • run <id> [--idempotency-key <key>] [--source <label>] [--wait] [--timeout <s>] [--json] — prints run id and state; with --wait, polls GET /api/agent-runs/:id every 5 s until a terminal state or awaiting_approval, then prints the report. Exit codes: 0 completed, 2 timed out, 3 skipped/deferred, 4 awaiting approval, 1 failed/error.
    • runs <id> [--limit] [--json]
    • report <runId> [--json] — prints the report Markdown to stdout (pipe-friendly; metadata to stderr).
    • approve <runId> [--note <text>], reject <runId>, cancel <runId>.
  3. Register in packages/cli/src/commands/index.ts and packages/cli/src/index.ts; add to the "Command Groups" help.
  4. Generated idempotency key when omitted: cli-<uuid>, printed so a failed command can be retried safely (same UX as propr goal create).
  5. --json outputs { version: 1, kind: 'automation-run', ... } documents.
  6. Tests: packages/cli/src/api/automations.test.ts (headers, key reuse on retry) and packages/cli/src/commands/automationCommands.test.ts (exit codes, report to stdout).

Implementation Specification

  • Use presentApiError / classifyApiError for errors; 404 prints "Agent not found".
  • The run command documents a GitHub Actions example in its help text.

Acceptance Criteria

  • propr automation run <id> --idempotency-key abc12345 twice creates one run (server dedupes; CLI prints created: false the second time).
  • --wait exits 0 with the report on stdout for a dry-run agent.
  • A cost-gated scheduled-style trigger that is deferred exits 3 with the reason on stderr.
  • propr --help lists the new group; propr agent is unchanged.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The CLI is a client of the REST trigger endpoint — no logic of its own beyond retries and waiting. We copy the proven goals.ts mutation pattern (one idempotency key per logical request, transient retries reuse it, uncertain outcomes print the key) because "trigger from my own cron" is exactly the environment where network blips and retries happen.

    A new command group avoids overloading propr agent (coding-agent configuration). Distinct exit codes make the CLI usable as a CI step: a deferred/skipped run (cost gate) is distinguishable from a failure.

    File: packages/cli/src/api/automations.ts (new file)

    Why this file: Typed REST client for Agents, shared by all automation subcommands.

    import { randomUUID } from 'node:crypto';
    import type { AgentDefinition, AgentRun } from '@propr/shared';
    import { ApiClient, createApiClient } from './client.js';
    import { ApiError, NetworkError, TimeoutError } from './errors.js';
    
    const ATTEMPTS = 3;
    
    export function newAutomationIdempotencyKey(): string {
      return `cli-${randomUUID()}`;
    }
    
    async function client(given?: ApiClient) { return given ?? createApiClient(); }
    
    export async function listAutomations(api?: ApiClient): Promise<{ definitions: AgentDefinition[]; nextOffset: number | null }> {
      return (await (await client(api)).get<{ definitions: AgentDefinition[]; nextOffset: number | null }>('/api/agent-definitions')).data;
    }
    
    export async function getAutomation(id: string, api?: ApiClient): Promise<AgentDefinition> {
      return (await (await client(api)).get<{ definition: AgentDefinition }>(`/api/agent-definitions/${encodeURIComponent(id)}`)).data.definition;
    }
    
    /**
     * The trigger primitive from the CLI. Transient failures retry with the SAME key,
     * so a flaky network from a CI runner can never start two runs.
     */
    export async function triggerAutomationRun(id: string, options: { idempotencyKey: string; source?: string }, api?: ApiClient): Promise<{ run: AgentRun; created: boolean }> {
      const apiClient = await client(api);
      let lastError: unknown;
      for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
        try {
          const response = await apiClient.post<{ run: AgentRun; created: boolean }>(`/api/agent-definitions/${encodeURIComponent(id)}/runs`, {
            body: { trigger: 'cli', ...(options.source ? { source: options.source } : {}) },
            headers: { 'Idempotency-Key': options.idempotencyKey },
          });
          return response.data;
        } catch (error) {
          const transient = error instanceof NetworkError || error instanceof TimeoutError || (error instanceof ApiError && [502, 503, 504].includes(error.status));
          if (!transient) throw error;
          lastError = error;
          await new Promise(resolve => setTimeout(resolve, 500 * attempt));
        }
      }
      throw Object.assign(new Error(`Could not confirm the trigger (${(lastError as Error).message}). Re-run with --idempotency-key ${options.idempotencyKey}; it will not start a second run.`), { idempotencyKey: options.idempotencyKey });
    }
    
    export async function listAutomationRuns(id: string, limit = 20, api?: ApiClient) {
      return (await (await client(api)).get<{ runs: AgentRun[]; nextOffset: number | null }>(`/api/agent-definitions/${encodeURIComponent(id)}/runs`, { params: { limit: String(limit) } })).data;
    }
    
    export async function getAutomationRun(runId: string, api?: ApiClient): Promise<AgentRun> {
      return (await (await client(api)).get<{ run: AgentRun }>(`/api/agent-runs/${encodeURIComponent(runId)}`)).data.run;
    }
    
    async function runAction(runId: string, action: 'approve' | 'reject' | 'cancel', body: object = {}, api?: ApiClient): Promise<AgentRun> {
      return (await (await client(api)).post<{ run: AgentRun }>(`/api/agent-runs/${encodeURIComponent(runId)}/${action}`, { body })).data.run;
    }
    export const approveAutomationRun = (runId: string, note?: string, api?: ApiClient) => runAction(runId, 'approve', note ? { note } : {}, api);
    export const rejectAutomationRun = (runId: string, api?: ApiClient) => runAction(runId, 'reject', {}, api);
    export const cancelAutomationRun = (runId: string, api?: ApiClient) => runAction(runId, 'cancel', {}, api);

    File: packages/cli/src/commands/automationCommands.ts (new file)

    Why this file: The propr automation command group, including run --wait designed for CI usage.

    import { Command } from 'commander';
    import { TERMINAL_AGENT_RUN_STATES, type AgentRun } from '@propr/shared';
    import {
      approveAutomationRun, cancelAutomationRun, getAutomation, getAutomationRun, listAutomationRuns, listAutomations,
      newAutomationIdempotencyKey, rejectAutomationRun, triggerAutomationRun,
    } from '../api/automations.js';
    import { printOutput } from '../utils/index.js';
    import { presentApiError } from '../utils/apiErrorPresentation.js';
    
    export const AUTOMATION_EXIT_CODES = { completed: 0, error: 1, timed_out: 2, not_run: 3, awaiting_approval: 4 } as const;
    
    function exitCodeFor(run: AgentRun): number {
      if (run.state === 'completed') return AUTOMATION_EXIT_CODES.completed;
      if (run.state === 'awaiting_approval') return AUTOMATION_EXIT_CODES.awaiting_approval;
      // Cost-gated outcomes are not failures; CI can treat them differently.
      if (run.state === 'skipped' || run.state === 'deferred') return AUTOMATION_EXIT_CODES.not_run;
      return AUTOMATION_EXIT_CODES.error;
    }
    
    function fail(error: unknown): never {
      presentApiError(error, { fallbackMessage: message => `Error: ${message}` });
      process.exit(AUTOMATION_EXIT_CODES.error);
    }
    
    export function createAutomationCommand(): Command {
      const automation = new Command('automation').alias('automations')
        .description('Agents (saved automations): run on demand or on a schedule and produce a report')
        .addHelpText('after', `
    Agents are configured in the web UI (Agents page). From the CLI you can list
    them, trigger runs, wait for reports and approve preview-mode runs.
    
    GitHub Actions example:
      - run: npx propr-cli automation run "$AGENT_ID" --idempotency-key "gh-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" --source "github-actions:$GITHUB_REPOSITORY"
    `);
    
      automation.command('list').option('-j, --json').action(async (options: { json?: boolean }) => {
        try {
          const { definitions } = await listAutomations();
          if (printOutput({ version: 1, kind: 'automation-list', definitions }, options.json ?? false)) return;
          if (!definitions.length) { console.log('No agents yet. Create one on the Agents page.'); return; }
          for (const def of definitions) console.log(`${def.id}  ${def.name}  ${def.autonomyMode}  ${def.scheduleEnabled && def.schedule ? `${def.schedule} (next ${def.nextRunAt})` : 'manual'}`);
        } catch (error) { fail(error); }
      });
    
      automation.command('show <id>').option('-j, --json').action(async (id: string, options: { json?: boolean }) => {
        try {
          const definition = await getAutomation(id);
          if (printOutput({ version: 1, kind: 'automation', definition }, options.json ?? false)) return;
          console.log(`${definition.name}\nRepositories: ${definition.repositories.join(', ')}\nModel: ${definition.agentAlias}:${definition.model}\nCapabilities: ${definition.capabilities.join(', ') || 'none'}\nAutonomy: ${definition.autonomyMode}\nSchedule: ${definition.schedule ?? 'none'}`);
        } catch (error) { fail(error); }
      });
    
      automation.command('run <id>')
        .description('Trigger a run (the same primitive as the API and MCP)')
        .option('--idempotency-key <key>', 'Reuse to retry this exact trigger without starting a second run')
        .option('--source <label>', 'Free-form label recorded on the run, e.g. github-actions:owner/repo')
        .option('--wait', 'Wait for the report (or approval/terminal state) and print it')
        .option('--timeout <seconds>', 'Maximum wait with --wait', '1800')
        .option('-j, --json')
        .action(async (id: string, options: { idempotencyKey?: string; source?: string; wait?: boolean; timeout: string; json?: boolean }) => {
          const key = options.idempotencyKey ?? newAutomationIdempotencyKey();
          try {
            let { run, created } = await triggerAutomationRun(id, { idempotencyKey: key, source: options.source });
            if (!options.json) console.error(`Run ${run.id} ${created ? 'created' : 'already existed for this key'}: ${run.state}${run.skipReason ? ` — ${run.skipReason}` : ''} (idempotency key ${key})`);
            if (options.wait) {
              const deadline = Date.now() + Number(options.timeout) * 1000;
              while (!(TERMINAL_AGENT_RUN_STATES as readonly string[]).includes(run.state) && !['awaiting_approval', 'deferred'].includes(run.state)) {
                if (Date.now() > deadline) {
                  if (!options.json) console.error('Timed out waiting; the run continues on the server.');
                  process.exit(AUTOMATION_EXIT_CODES.timed_out);
                }
                await new Promise(resolve => setTimeout(resolve, 5_000));
                run = await getAutomationRun(run.id);
              }
            }
            if (options.json) printOutput({ version: 1, kind: 'automation-run', created, idempotencyKey: key, run }, true);
            else if (run.report) process.stdout.write(`${run.report}\n`);
            process.exit(options.wait ? exitCodeFor(run) : AUTOMATION_EXIT_CODES.completed);
          } catch (error) { fail(error); }
        });
    
      automation.command('runs <id>').option('-l, --limit <n>', 'Number of runs', '20').option('-j, --json').action(async (id: string, options: { limit: string; json?: boolean }) => {
        try {
          const { runs } = await listAutomationRuns(id, Number(options.limit));
          if (printOutput({ version: 1, kind: 'automation-runs', runs }, options.json ?? false)) return;
          for (const run of runs) console.log(`${run.id}  ${run.createdAt}  ${run.trigger}  ${run.state}${run.skipReason ? `  (${run.skipReason})` : ''}`);
        } catch (error) { fail(error); }
      });
    
      automation.command('report <runId>').description('Print a run report (Markdown) to stdout').option('-j, --json').action(async (runId: string, options: { json?: boolean }) => {
        try {
          const run = await getAutomationRun(runId);
          if (printOutput({ version: 1, kind: 'automation-run', run }, options.json ?? false)) return;
          console.error(`${run.state} · ${run.reportedAt ?? 'no report yet'}`);
          if (run.report) process.stdout.write(`${run.report}\n`);
        } catch (error) { fail(error); }
      });
    
      automation.command('approve <runId>').option('--note <text>', 'Guidance for the acting agent').action(async (runId: string, options: { note?: string }) => {
        try { console.log(`Run ${runId}: ${(await approveAutomationRun(runId, options.note)).state}`); } catch (error) { fail(error); }
      });
      automation.command('reject <runId>').action(async (runId: string) => {
        try { console.log(`Run ${runId}: ${(await rejectAutomationRun(runId)).state}`); } catch (error) { fail(error); }
      });
      automation.command('cancel <runId>').action(async (runId: string) => {
        try { console.log(`Run ${runId}: ${(await cancelAutomationRun(runId)).state}`); } catch (error) { fail(error); }
      });
      return automation;
    }

    File: packages/cli/src/commands/index.ts and packages/cli/src/index.ts

    Why these files: Register the group and advertise it in the root help.

    --- a/packages/cli/src/commands/index.ts
    +++ b/packages/cli/src/commands/index.ts
    @@
     export { createGoalCommand } from "./goalCommands.js";
    +export { createAutomationCommand } from "./automationCommands.js";
    --- a/packages/cli/src/index.ts
    +++ b/packages/cli/src/index.ts
    @@
       createGoalCommand,
    +  createAutomationCommand,
    @@
       Goals:          goal [capabilities|create|list|inspect|input|inputs|pause|resume|cancel|model]
    +  Agents:         automation [list|show|run|runs|report|approve|reject|cancel]
    @@
     program.addCommand(createGoalCommand());
    +program.addCommand(createAutomationCommand());

    File: packages/cli/src/api/automations.test.ts (new file)

    Why this file: The idempotency contract of the CLI trigger.

    import assert from 'node:assert/strict';
    import { test } from 'node:test';
    import { NetworkError } from './errors.js';
    import { triggerAutomationRun } from './automations.js';
    
    test('retries transient failures with the same idempotency key', async () => {
      const seen: Array<{ key?: string; body: unknown }> = [];
      let calls = 0;
      const api = { post: async (_path: string, options: { headers: Record<string, string>; body: unknown }) => {
        seen.push({ key: options.headers['Idempotency-Key'], body: options.body });
        if (++calls === 1) throw new NetworkError('reset');
        return { data: { run: { id: 'r1', state: 'queued' }, created: true } };
      } } as never;
      const result = await triggerAutomationRun('def-1', { idempotencyKey: 'ci-key-123', source: 'cron' }, api);
      assert.equal(result.run.id, 'r1');
      assert.deepEqual(seen.map(entry => entry.key), ['ci-key-123', 'ci-key-123']);
      assert.deepEqual(seen[0].body, { trigger: 'cli', source: 'cron' });
    });

    automationCommands.test.ts follows the harness in goalCommands.test.ts (fake fetch, captured stdout/stderr, intercepted process.exit) and asserts: run --wait on a completed run prints the report to stdout and exits 0; a deferred response exits 3 with the reason on stderr; awaiting_approval exits 4.

  2. propr-dev commented on Oct 7, 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: 2813/claude-opus-5-5-agents-v1-14-17-cli-propr-20261007-0921-etz
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2813-20261007-0921-claude-opus-5-5-etz

    🔍 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