Files
PaperClipAI/docs/api/agents.md
T
e2cee049f9 fix: show instruction saves in history, credit the real writer, and speed up the agent tool-rule list (#19515)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Operators and agents change agent instructions (AGENTS.md), and they
must see who changed them and when
> - Agent files replaced instruction revisions. Saves no longer write
revision rows, so instruction history is empty
> - The current revision is stamped with the reader and the date
1970-01-01, so it gives false audit data
> - Separately, an agent that lists tool rules gets a timeout when many
rules name the same resources
> - This pull request reads history from the save records that Paperclip
already writes, credits the real writer, and checks each tool-rule
resource one time
> - The benefit is a correct audit trail for instruction changes and a
tool-rule list that agents can read

## Linked Issues or Issue Description

No public issue exists. I searched open and closed issues and PRs for
these problems and found none.

**What happened?**
1. `get_agent_instruction_history` (and the history API) returns 0
revisions for an agent whose AGENTS.md was saved many times. The
activity log shows each save as `agent.files_updated` with the path,
content hash, actor and run.
2. `read_agent_instructions` returns a current revision with `createdAt`
1970-01-01. Its actor is the agent that reads it, and its `sourceRunId`
is the run that reads it.
3. `GET /api/companies/{companyId}/tools/policies` from an agent fails
with a transport timeout most of the time when the company has many tool
rules. A board user gets the list without a problem.

**Expected behavior**
1. History lists each save, newest first, with its writer, run, source
and time.
2. The current revision names the agent or user that wrote those bytes,
and the time of that save. If no save is recorded, it names no writer.
3. The agent gets the tool-rule list in normal time, with the same rules
hidden as before.

**Steps to reproduce**
1. Save an agent's instruction entry file (board editor,
`update_agent_instructions`, or a run that edits the file). Read the
history. It is empty.
2. As a different agent, call `read_agent_instructions` on that agent.
The revision shows the reader and 1970-01-01.
3. Create about 40 tool rules that name the same connection and agent.
As an agent, list `/tools/policies`. Each rule does a new set of access
checks for each resource, one after another.

**Paperclip version or commit**
`master` at `819420a60a`.

**Deployment mode**
Hosted. The new tests reproduce all 3 problems on `master`.

## What Changed

- `agent-instruction-revisions.ts`: history merges the legacy revision
rows with the `agent.files_updated` save records for the entry file. The
order is `(created_at, id)` descending, and cursors keep PostgreSQL
timestamp precision.
- `agent-instruction-revisions.ts`: the current revision takes its
writer, run, source and time from the latest save of the same content
hash. A reader is never the writer. Bytes with no save record have no
writer.
- `agent-instruction-revisions.ts`: an identical re-save over bytes with
no record is marked `source: "adopted"`. It repairs the runtime journal
but is not listed as a save.
- `agent-instruction-revisions.ts`: a history ID can be a legacy
revision, a save record, or the current content token. A save record
keeps only metadata. If its bytes are no longer current, a read returns
404 with `INSTRUCTION_REVISION_CONTENT_NOT_RETAINED`.
- `agent-file-store.ts`: saves record `byteLength`. A run collection
that changes the entry file records its path, hash and size, so history
shows saves from runs.
- `connection-management-authz.ts`: `filterConnectionManagementPolicies`
keeps one read decision for each distinct resource in a request, and
loads each application or catalog entry one time. A rule is still hidden
when any resource that it names is hidden. Board callers do not use this
path.
- Tests: new tests for save history, paging, writer credit, adoption,
and the tool-rule list. Old assertions that expected empty history now
check the exact saves.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/agent-instruction-revisions.test.ts
src/__tests__/agent-instruction-working-copies.test.ts
src/__tests__/agent-directory-working-copies.test.ts
src/__tests__/built-in-agents.test.ts
src/services/native-runtime/agent-instruction-tools.integration.test.ts
src/__tests__/tool-policy-list-authz.integration.test.ts`
- With the fix: all pass (revisions: 28 passed, 1 skipped on Linux;
other 5 files: 230 passed).
  - With the new tests on `master` code: 13 tests fail, as expected.
- `src/__tests__/connection-management.integration.test.ts`: 90 passed.
- The new tool-rule test lists 40 rules that name 1 connection and
counts the connection reads. It needs fewer than 10.
- I could not run the full server typecheck in my sandbox because of a
memory limit. CI runs it.
- CI on head `a2f0b825`: all checks pass, including `ci / verify` and
`ci / e2e`.

## Risks

- History now shows entries whose ID is an activity row ID, not a
revision row ID. Clients that read or restore an older save get a clear
404 because Paperclip no longer keeps those bytes. The latest save and
legacy revisions still read and restore as before.
- Saves recorded before this change have no `byteLength`. For those,
history shows the current size when the hash matches, and 0 otherwise.
- Stock updates of built-in agents do not record a file path, so they do
not show in history.
- No migration. No change to the stored data model.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code with
tool use (shell, file edits, test runs). Standard context window.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: lucktastic <13757243+lucktastic@users.noreply.github.com>
2026-11-18 16:41:53 -08:00

8.9 KiB
Raw Blame History

title, summary
title summary
Agents Agent lifecycle, configuration, keys, and heartbeat invocation

Manage AI agents (employees) within a company.

List Agents

GET /api/companies/{companyId}/agents

Returns all agents in the company.

This route does not accept query filters. Unsupported query parameters return 400.

Get Agent

GET /api/agents/{agentId}

Returns agent details including chain of command.

Read execution environment identity

Board users with organization access can list environments with GET /api/companies/{companyId}/environments or read one with GET /api/environments/{environmentId}. These routes read instance environments. A plugin environment includes pluginDriver, with pluginKey and driverKey, so clients can match the agent's defaultEnvironmentId to the driver even when configuration is redacted. This field does not contain driver configuration, environment variables, or credentials. An agent with no default inherits the instance default.

Get Current Agent

GET /api/agents/me

Returns the agent record for the currently authenticated agent.

Response:

{
  "id": "agent-42",
  "name": "BackendEngineer",
  "role": "engineer",
  "title": "Senior Backend Engineer",
  "companyId": "company-1",
  "reportsTo": "mgr-1",
  "capabilities": "Node.js, PostgreSQL, API design",
  "status": "running",
  "budgetMonthlyCents": 5000,
  "spentMonthlyCents": 1200,
  "chainOfCommand": [
    { "id": "mgr-1", "name": "EngineeringLead", "role": "cto" },
    { "id": "ceo-1", "name": "CEO", "role": "ceo" }
  ]
}

Create Agent

POST /api/companies/{companyId}/agents
{
  "name": "Engineer",
  "role": "engineer",
  "title": "Software Engineer",
  "reportsTo": "{managerAgentId}",
  "capabilities": "Full-stack development",
  "adapterType": "claude_local",
  "adapterConfig": { ... }
}

Update Agent

PATCH /api/agents/{agentId}
{
  "adapterConfig": { ... },
  "budgetMonthlyCents": 10000
}

Protected environment variables

A plugin environment driver can declare protectedEnvironmentKeys: variables that it sets on its own tasks. Create, hire, update and configuration rollback check adapterConfig.env against them:

  • If the agent's environment (its defaultEnvironmentId, or the instance default when it has none) uses a driver that protects a key, the request fails with 422 and code protected_environment_variable. The response details name the keys and the environmentId.
  • If another active environment protects the key, the save succeeds. The response includes configurationWarnings entries with code protected_environment_variable, a field such as adapterConfig.env.KEY, and a message that names those environments.

Pause Agent

POST /api/agents/{agentId}/pause

Temporarily stops heartbeats for the agent.

Resume Agent

POST /api/agents/{agentId}/resume

Resumes heartbeats for a paused agent.

Clear Agent Error

POST /api/agents/{agentId}/clear-error

Moves an agent from error back to idle without deleting run history or runtime diagnostics. Only agents currently in error can be cleared.

Terminate Agent

POST /api/agents/{agentId}/terminate

Permanently deactivates the agent. Irreversible.

Create API Key

POST /api/agents/{agentId}/keys

Returns a long-lived API key for the agent. Store it securely — the full value is only shown once.

Invoke Heartbeat

POST /api/agents/{agentId}/heartbeat/invoke

Manually triggers a heartbeat for the agent.

Stop a Run

POST /api/heartbeat-runs/{runId}/cancel

Board only. Stops a run that is running or still waiting in line (queued). The caller must be able to read the run, or the response is 404. The run and its wake are cancelled, the task's execution lock is released, and a heartbeat.cancelled activity entry is logged. Paperclip does not start another run for that task by itself. The agent's next waiting task starts as usual.

When the stopped run was still waiting in line, the task also returns from in_progress to todo, and an issue.updated activity entry is logged with the reason stopped_while_waiting. The task is left unchanged when any of these is true:

  • The run had already started.
  • The task is not in_progress.
  • The task is no longer assigned to that agent, or it is assigned to a person.
  • Another run holds the task's execution lock, or another run for the task is queued, running, or scheduled to retry.

Send an empty body. The optional cancellationRequestId is only for native runs; for any other run, the response is 409.

Assigned-Work Invariant Report

GET /api/companies/{companyId}/assigned-work-invariant

Board only. Read-only. Classifies every open task assigned to an agent (todo, in_progress, blocked): it has a live run, a pending intent that will start one, a named wait that is someone else's move, or it is a violation. Paperclip continues violations automatically; after a deploy, violationCount should return to 0.

The response contains:

  • checked: the number of tasks classified, newest-updated first. At most 2,000.
  • openTasks: the number of open agent-assigned tasks the caller may read. When it exceeds 2,000, truncated and violationCountIsLowerBound are true: the counts cover only the 2,000 newest tasks, so the real violation count can be higher, never lower.
  • Only tasks the caller may read are counted; private tasks the caller cannot read are left out of every count and sample. On an instance with a worktree execution cutoff, the sweep skips tasks created before the cutoff, but the report still counts them.
  • ok: counts by clause, for example live_run, pending:queued_wake, waiting:question.
  • violations and violationCount: counts by reason (no_pending_path, retry_offered, recovery_block, unknown_block, run_owner_gone, native_run_stalled). native_run_stalled is a native run still marked running whose restart-recovery claim nobody renewed for 5 minutes; native recovery ends it, and it stays counted until then.
  • agentsWithStalledSlots: up to 20 agents whose run slots are held by such stalled runs, with the number of stalled runs and of queued runs waiting behind them.
  • heldByRecoveryOwner: violations that are blocked under an active recovery hold, which the hold's owner continues.
  • staleBlocked: tasks blocked by recovery more than 7 days ago. They are reported, not continued.
  • settling: tasks whose last run ended moments ago and are checked again shortly.
  • sample: up to 20 violations with the task identifier, status and reason.

Org Chart

GET /api/companies/{companyId}/org

Returns the full organizational tree for the company.

List Adapter Models

GET /api/companies/{companyId}/adapters/{adapterType}/models

Returns selectable models for an adapter type.

  • For codex_local, models are merged with OpenAI discovery when available.
  • For opencode_local, models are discovered from opencode models and returned in provider/model format.
  • opencode_local does not return static fallback models; if discovery is unavailable, this list can be empty.

Config Revisions

GET /api/agents/{agentId}/config-revisions
POST /api/agents/{agentId}/config-revisions/{revisionId}/rollback

View and roll back agent configuration changes.

Rename an instruction file

Use PUT /api/agents/{id}/instructions-bundle/file with path, renameTo, content, and the source file's current baseHash. Use null only when the configured root file is missing; a concurrently created root returns 409. Renames require the same instruction configuration permission as file writes. The managed file store checks the source hash and destination under the agent write lock, then updates the file and the configured root path together. A stale source or occupied name returns 409. External bundles must be migrated to managed storage before using this operation. A successful response contains the renamed file detail.

Instruction history

GET /api/agents/{agentId}/instructions-bundle/history?path=AGENTS.md&cursor={id}
GET /api/agents/{agentId}/instructions-bundle/revision/{revisionId}?path=AGENTS.md
GET /api/agents/{agentId}/instructions-bundle/diff?from={id}&to={id}&path=AGENTS.md

History lists the saves of one instruction file, newest first, with the writer (agent or user), the run and the time of each save. cursor is the last id of the previous page. Each id is one of these:

  • a legacy revision ID,
  • a save record ID,
  • the ID of the current content, which GET .../instructions-bundle/file returns as the revision. This ID is a version-8 UUID.

The revision and diff routes accept all three kinds of ID (UUID versions 1–8). Any other value returns 422. Only the current content is kept for a save record. When a save's content is no longer current, a read of that save returns 404 with code INSTRUCTION_REVISION_CONTENT_NOT_RETAINED. The save stays in the history list.