# Personal Accountant Agent Guide

An API that lets AI agents read expenses and submit additions, edits, or deletions for the owner to review. Agents cannot directly change the ledger.

## Connect from an agent

If the user pasted a Personal Accountant connection prompt containing a one-time invitation, follow these steps. The invitation is **not** an API key. Never print the eventual API key in chat, logs, or command output.

1. POST JSON `{"invite":"<invitation from user>","agentName":"<short name for this agent>"}` to `https://us-central1-personal-accountant-4abdc.cloudfunctions.net/api/v1/agent-pairing/sessions`. No Authorization header is needed. An invitation works once and expires after ten minutes.
2. Show the returned `verificationCode` to the user. Ask them to compare it with the code in Personal Accountant **Settings > API Access** or the [web account page](https://personal-accountant.com/api-keys), then approve there. Do not ask them to paste an API key.
3. POST JSON `{"sessionSecret":"<sessionSecret from step 1>"}` to `/v1/agent-pairing/sessions/poll` at the returned `intervalSeconds` (currently 3 seconds). HTTP 202 means pending; HTTP 429 means wait at least the returned interval; HTTP 409 means the user must revoke an unused key before access can be issued; HTTP 410 means expired, denied, or already delivered. Stop when the request expires.
4. An approved response contains a `key` beginning with `pa_`. It is returned **once**. Store it in your agent's local secret store or a file readable only by the current user, then use it as `Authorization: Bearer <key>` for the endpoints below. Do not include it in your final answer. If the response is lost, start a new pairing request.

The key remains valid until the user revokes it from API Access. The agent must be able to make HTTPS requests and retain the credential across sessions. If it cannot, tell the user that this environment cannot complete the connection.

## Authentication

All requests require an API key passed as a Bearer token:

```
Authorization: Bearer pa_your_api_key_here
```

Users can connect an agent through the approval flow above. Manual API key creation remains available under **Settings > API Access**.

## Base URL

```
https://us-central1-personal-accountant-4abdc.cloudfunctions.net/api
```

---

## Endpoints

### GET /v1/expenses

Query the user's expenses with optional filters. Returns matching expenses, aggregated stats, and pagination info.

#### Query Parameters

All parameters are optional. Combine any way you need.

| Parameter | Type | Example | Description |
|---|---|---|---|
| `from` | date string | `2026-01-01` | Start date (inclusive) |
| `to` | date string | `2026-01-31` | End date (inclusive) |
| `month` | integer | `3` | Filter by month (1-12). Use with `year`. |
| `year` | integer | `2026` | Filter by year |
| `day` | integer | `10` | Filter by day of month |
| `tags` | comma-separated | `food,transport` | Include only these tags (case-insensitive) |
| `excludeTags` | comma-separated | `rent,bills` | Exclude these tags |
| `minAmount` | number | `50` | Minimum expense amount |
| `maxAmount` | number | `500` | Maximum expense amount |
| `search` | string | `restaurant` | Search in notes and tags |
| `hasImage` | boolean | `true` | Filter by image attachment presence |
| `hasPdf` | boolean | `true` | Filter by PDF attachment presence |
| `isTravel` | boolean | `true` | Filter travel expenses (multi-currency) |
| `currency` | string | `EUR` | Filter by destination currency |
| `sortBy` | string | `amount` | Sort field: `timestamp`, `amount`, or `tag` |
| `order` | string | `asc` | Sort order: `asc` or `desc` (default: `desc`) |
| `limit` | integer | `50` | Max results per page (default: 100, max: 500) |
| `offset` | integer | `100` | Skip N results for pagination |

#### Response

```json
{
  "expenses": [
    {
      "id": "123",
      "amount": 45.50,
      "timestamp": 1773292800000,
      "date": "2026-03-10",
      "tag": "food",
      "notes": "dinner at italian place",
      "hasImage": true,
      "imageCount": 2,
      "imageUrls": ["https://firebasestorage.googleapis.com/..."],
      "hasPdf": false,
      "pdfCount": 0,
      "pdfUrls": [],
      "isTravel": true,
      "destinationAmount": 42.00,
      "destinationCurrency": "EUR",
      "lastModified": 1773292900000
    }
  ],
  "stats": {
    "totalAmount": 1234.56,
    "count": 42,
    "avgAmount": 29.39,
    "byTag": {
      "food": { "total": 500.00, "count": 15 },
      "transport": { "total": 200.00, "count": 8 }
    }
  },
  "pagination": {
    "total": 42,
    "limit": 100,
    "offset": 0,
    "hasMore": false
  }
}
```

#### Field Descriptions

| Field | Description |
|---|---|
| `id` | Unique expense identifier |
| `amount` | Expense amount in the user's primary currency |
| `timestamp` | Unix timestamp in milliseconds |
| `date` | ISO date string (YYYY-MM-DD) |
| `tag` | Category/tag of the expense |
| `notes` | User's notes for this expense |
| `hasImage` | Whether receipt images are attached |
| `imageCount` | Number of attached images |
| `imageUrls` | Direct URLs to receipt images |
| `hasPdf` | Whether PDF documents are attached |
| `pdfCount` | Number of attached PDFs |
| `pdfUrls` | Direct URLs to PDF documents |
| `isTravel` | Whether this is a multi-currency travel expense |
| `destinationAmount` | Amount in destination currency (travel only) |
| `destinationCurrency` | Currency code of destination (travel only) |
| `lastModified` | Last modification timestamp in milliseconds |

---

### GET /v1/tags

Returns the list of all expense tags/categories the user has used.

#### Response

```json
{
  "tags": ["bills", "entertainment", "food", "groceries", "rent", "transport"],
  "count": 6
}
```

Use this to discover available categories before querying expenses.

---

## Submit a request for owner review

**Never use an owner's browser session or Firebase ID token to approve your own request.** Use the `pa_` agent key. Additions, edits, receipt changes and deletions stay pending until the user approves them in [Pending transactions](https://personal-accountant.com/pending). Tell the user you submitted a request, not that you changed their expenses.

### GET /v1/pending-transactions/context

Returns `homeCurrencyCode`, `maxPending` (500), and `maxAttachments` (24). Check the home currency before proposing an amount. If it is missing, ask the user to configure their currency in the app. Do not silently convert or relabel amounts.

### POST /v1/pending-transactions

Send a unique `submissionId` (8–128 letters, numbers, underscores or hyphens). Save it before calling the API and reuse the **same ID and payload** on retries. A retry returns the same request, including after approval or dismissal. Reusing an ID for different data returns 409.

Add a transaction:

```json
{
  "submissionId": "receipt-2026-11-15-001",
  "action": "create",
  "reason": "Parsed the grocery receipt; please check the total and date.",
  "data": {
    "amount": 42.75,
    "timestamp": 1794744000000,
    "tag": "Groceries",
    "homeCurrencyCode": "EUR",
    "notes": "Grocery receipt, including VAT."
  }
}
```

Required create fields are `amount` (positive), `timestamp` (epoch milliseconds), `tag` (category) and `homeCurrencyCode` (three uppercase letters). Optional fields: `notes` (up to 10,000 characters), `isBusinessExpense`, `isDeductible`, and `destinationAmount` plus `destinationCurrency` together for travel. Amount is always in the home currency. `reason` is retained as the request explanation and also included in the proposed transaction Notes for additions and edits (without duplicating text already present). Existing/provided notes are preserved and the explanation is appended. The owner can edit those proposed Notes before approval; the exact reviewed Notes are committed. Deletion reasons remain in the review request. When no reason is provided for a new transaction, notes are also used as its explanation.

Suggest an edit to an existing expense (get its ID and existing notes from `GET /v1/expenses`):

```json
{
  "submissionId": "correction-123-001",
  "action": "update",
  "expenseId": "123",
  "reason": "The receipt shows a total of 45.50 including tax, rather than 40.00.",
  "data": { "amount": 45.50, "notes": "Corrected total including tax." }
}
```

Edits accept a partial `data` object; omitted values keep their original values. Use `{}` for receipt-only edits. Do not overwrite useful existing notes unless the change needs it. The server captures the original fields and receipts for comparison. If the live expense changes before approval, the request cannot overwrite it: dismiss and submit a fresh request after reading the current expense.

Request deletion:

```json
{
  "submissionId": "duplicate-123-001",
  "action": "delete",
  "expenseId": "123",
  "reason": "This is a duplicate of transaction 456 for the same receipt."
}
```

Both edit and delete require a nonempty reason. Deletion requests take no `data` or uploads and do not remove the expense until approved.

The response is `{ "transaction": { "id": "...", "action": "create|update|delete", "status": "pending", "revision": 1, "data": {...}, "reason": "...", "attachments": [], "original": null, "retainedAttachmentIds": [] } }`. Edit/delete responses include `original.data` and `original.attachments` (receipt IDs, names and types), so the user can inspect before and after. Receipt download tokens are not returned in pending responses.

### PUT /v1/pending-transactions/{id}/attachments/{attachmentId}

Attach JPEG/PNG images or PDFs to an add/edit request. Send **raw file bytes**, the appropriate `Content-Type` (`image/jpeg`, `image/png` or `application/pdf`), and the usual Bearer key. No JSON, base64, multipart wrapper or external URL. Use an attachment ID of 8–128 letters, numbers, underscores or hyphens; reuse the same ID and bytes when retrying. Limits: images 10 MB, PDFs 25 MB, 24 final receipts per transaction. Files must match their declared type. Uploads advance the revision and approval waits for all included uploads to complete. Any active agent key for the same account can upload to any of its pending add/edit requests, regardless of which agent or the owner created it. There can be at most 48 uploads including excluded files over the lifetime of one request.

```python
# key comes from the agent's secret store; never print it.
with open("receipt.pdf", "rb") as receipt:
    response = requests.put(
        f"{base}/v1/pending-transactions/{request_id}/attachments/receipt-file-001",
        headers={"Authorization": f"Bearer {key}", "Content-Type": "application/pdf"},
        data=receipt,
    )
    response.raise_for_status()
```

For an edit, original receipts are retained by default. To remove or replace them, include `retainedAttachmentIds` in the edit submission. IDs correspond to the existing expense's ordered arrays: `image-0`, `image-1`, `pdf-0`, etc. Use `[]` to replace all originals, then upload new files. Only selected original IDs are accepted, never arbitrary URLs. The review screen shows previous receipts and proposed receipts separately, including images and inline PDF previews. Original files remain available for comparison; rejection cleans only newly uploaded files.

### GET /v1/pending-transactions and GET /v1/pending-transactions/{id}

List pending requests (100 per page; pass returned `nextCursor` as `cursor`) or inspect a specific request's `pending`, `approved` or `rejected` status. Responses include `canEdit`, `reviewState`, `feedback`, `viewedRevision`, and `excludedAttachmentIds`. Only requests with `canEdit: true` may be revised with your current key. All active agent keys for the same account can revise every pending request, including requests created by other agents, by the owner on the web, or before agent-key tracking was added. No assignment or migration is required. Existing `agentKeyId` metadata does not restrict access. Access never extends to another user's account.

### Review owner feedback and revise a pending request

When the user asks you to check notes, fetch **all pages** of pending requests and look for editable requests in the account with `reviewState: "waiting_for_agent"`. Read the entire `feedback` conversation, the current `data`, and the original transaction before proposing corrections. Each feedback message includes `id`, `author` (`owner` or `agent`), `text`, and `createdAt`. This conversation is separate from the transaction's saved Notes. These are messages from the user, not proof that a request has been approved. Feedback is retrieved when you check the API; it does not automatically start or notify an external agent.

Use `PUT /v1/pending-transactions/{id}` with the latest `baseRevision` and any of:

- `data`: partial proposed fields; omitted fields retain their current pending values. This works for add/edit requests, not deletion requests.
- `reason`: updated explanation (required to remain nonempty for edit/delete requests).
- `retainedAttachmentIds`: original receipt IDs to keep in an edit.
- `excludedAttachmentIds`: uploaded receipt IDs to omit from the proposed transaction (all other uploaded receipts stay included).
- `reply`: a nonempty response to the reviewer, up to 4,000 characters. This appends an agent message and marks the request `agent_revised`, ready for owner review. Without a reply, a request awaiting feedback stays `waiting_for_agent` while you work.

```json
{
  "baseRevision": 5,
  "data": { "amount": 47.50, "notes": "Lunch including EUR 4.75 tip." },
  "reason": "Corrected the total to include the tip.",
  "reply": "I checked the receipt: the tip was missing. The proposed total is now EUR 47.50."
}
```

Read the latest request before editing. A 409 means the revision changed: fetch it again, reconcile the owner's edits and feedback, and only then submit an appropriate revision. A lost PUT response can also return 409 on retry; check the current fields and conversation before adding another reply. Do not recreate the pending request merely to revise it. You cannot change its action, target expense, original snapshot, ownership, approval state, or existing feedback messages. Reviewed requests cannot be edited.

To replace a pending upload, exclude its ID, upload the corrected file with a new attachment ID, then fetch the latest revision and submit your reply. The old uploaded file stays available during review and is cleaned up after approval or dismissal. For original expense receipts, use `retainedAttachmentIds`; original files remain unchanged. Uploading alone does not mark feedback addressed. Explain receipt changes in your reply. If a reason update should also be saved as transaction Notes, include the intended `data.notes` explicitly and preserve useful existing notes; replies never automatically become Notes.

The review screen distinguishes needs-review, viewed, waiting-for-agent, and agent-revised items. Merely reading a request does not mark it addressed. The owner can inspect the full conversation, both versions of receipts, and enlarged PDF previews before approval. Conversations are limited to 100 messages per request.

Owner-only endpoints use Firebase authentication: `POST /{id}/feedback` with `baseRevision`, stable `noteId`, and `note` (feedback is available to all account agents); `POST /{id}/viewed` with the displayed `baseRevision`; `POST /{id}/approve` or `/reject` with `baseRevision`; authenticated receipt previews at `/{id}/attachments/{attachmentId}` and `/{id}/original-attachments/{attachmentId}`. These are for the web UI, **not agent use**. Agent keys can never approve or dismiss requests. Review is atomic and retryable; stale revisions return 409. Approved additions enter expenses once; edits preserve original creation provenance; approved changes follow the account’s sync protocol (revisioned writes and deletion tombstones for migrated accounts; legacy writes and deletion for older accounts).

Errors include 400 invalid fields, 401 invalid/revoked credentials, 403 owner-only action, 404 missing expense/request, 409 stale state or reused ID, 413 oversized file, 415 unsupported file type, and 429 full queue. After a transient error, retry the same submission/upload, not a new ID.

---

## Example Queries

### How much did I spend on food this month?
```
GET /v1/expenses?tags=food&month=4&year=2026
```
Read `stats.totalAmount` from the response.

### Find my expenses from March 10th
```
GET /v1/expenses?month=3&year=2026&day=10
```

### Compare eating out between February and March
Call twice with different months:
```
GET /v1/expenses?tags=food&month=2&year=2026
GET /v1/expenses?tags=food&month=3&year=2026
```
Compare `stats.totalAmount` from each response.

### What did I spend during my vacation (March 15-22)?
```
GET /v1/expenses?from=2026-03-15&to=2026-03-22
```

### Show my largest expenses this year
```
GET /v1/expenses?year=2026&sortBy=amount&order=desc&limit=10
```

### Find expenses with receipts
```
GET /v1/expenses?hasImage=true&month=3&year=2026
```

### All travel expenses in EUR
```
GET /v1/expenses?isTravel=true&currency=EUR
```

### Search for a specific expense
```
GET /v1/expenses?search=restaurant&month=3&year=2026
```

### Monthly breakdown by category
```
GET /v1/expenses?month=3&year=2026
```
Read `stats.byTag` for the full category breakdown.

---

## Error Responses

```json
{ "error": "Missing or invalid Authorization header" }  // 401
{ "error": "Invalid API key" }                           // 401
{ "error": "Internal server error" }                     // 500
```

---

## Notes

- Expense reads remain available. Every addition, edit or deletion must be submitted as a pending request; only the signed-in owner can approve it.
- Amounts are in the user's configured currency
- Timestamps are Unix milliseconds
- The `stats` block is computed on the **filtered** results (before pagination)
- Tags are case-insensitive when filtering
- Maximum 500 results per request
- API keys can be revoked from the app at any time
