# Throughline: setup for coding agents

Facts version 2026-11-13.1, checked against hosted service source (`d8d2f2c`), installed on 2026-11-12. Public routes, authentication boundaries and an existing account's noncharged usage passed. Real browser approval and paid checkout flows require their own tests. Examples are illustrative.

You are helping a person connect their project to Throughline, a read-only feed of which news articles are relevant to which Polymarket contracts. Full reference: https://throughline.markets/api.md

## Rules for you

- Never ask the person to paste the API key into this conversation, and never print, echo or log it. If a key appears in chat, tell them to revoke it in the account page and make a new one.
- You request access; one signed-in person approves it in their browser. Use the pairing setup below. You never sign in for them, never open the approval link yourself and never approve on their behalf.
- Ask for `news:read` only, unless the person tells you to manage keys or read the account. They can grant less than you ask for.
- Payment and the trial are the person's own actions in the account page. An API key cannot manage the account, and no credential you can hold can pay, start checkout or change a plan.
- Store exactly one thing in `.env`: `THROUGHLINE_API_KEY`. Never create, overwrite, truncate, move or display `.env` by hand. It may already hold other secrets. Only the `throughline` command or the person edits it.
- Never load `.env` with `source`, `.`, `eval` or `export $(...)`. That runs whatever the file contains.
- Never put the key on a command line, including in a `curl` argument. Other processes can read command lines.
- Do not invent endpoints, parameters or fields. Everything that exists is in https://throughline.markets/openapi.json
- The private files keep the key out of chat, logs and source control. They do not hide it from you: you can read local files. Do not.

## Setup

1. Before any key exists, make sure the private files will be ignored. In the project root:

   ```sh
   if [ -L .env ]; then
     echo "STOP: .env is a symbolic link"
   elif git ls-files --error-unmatch .env >/dev/null 2>&1; then
     echo "STOP: .env is tracked by git"
   else
     for path in .env .throughline/; do
       if git check-ignore -q "$path" 2>/dev/null; then
         echo "OK: $path is already ignored"
       else
         printf '\n%s\n' "$path" >> .gitignore && echo "OK: added $path to .gitignore"
       fi
     done
   fi
   ```

   On `STOP`, do not continue. Tell the person what you found and let them decide where the key should live. This step only ever appends lines to `.gitignore`. It does not create or change `.env`.

2. Install the `throughline` command from the public repository, pinned to one commit, into the project's Python environment (Python 3.10 or later, a POSIX system, `git` available). It has no dependencies.

   ```
   python3 -m pip install "git+https://github.com/mokn/throughline@df5cd8a0bc6aa063bd9da9ca37c33115f54096f2"
   ```

   There is no package-registry release; install from the repository. If this cannot be done here, use "Without the command" below.

3. Ask for access:

   ```
   throughline login --name "<a short name the person will recognise>"
   ```

   It prints one JSON object and exits with code 2, which means waiting. Give the person `verification_uri_complete` and `user_code` from that output. Neither is a secret. Ask them to open the link, sign in with Google or GitHub, check that the code on the page is the same code, choose what to allow, and approve. Start polling immediately after relaying that link and code; do not wait for a second human reply. Do not ask them to send any key back.

   The command made the key itself and sent only its SHA-256 hash. The key does nothing until the person approves. It waits in `.throughline/pending.json`; do not open that file.

4. Start collecting immediately after you relay the code and link. Do not wait for the person to say Done:

   ```
   throughline login --wait
   ```

   - Exit 0, `"status": "delivered"`: the key is now in `.env` as `THROUGHLINE_API_KEY`. Go to step 5.
   - Exit 3, `"status": "denied"`: the person said no. Nothing is active. Stop.
   - Exit 2: still waiting. Run it again later, not in a tight loop.
   - Exit 4, `"status": "delivery_unknown"`: the request expired before the result was collected. This is not proof that nobody approved it; the key may be active. Do not delete anything and do not claim that nothing was activated. Tell the person to open the account page, look under "Your connections" for the connection named in the output, and revoke it if they do not want it. Then run `throughline cancel`, and start again only if they ask.
   - Exit 4 with an `error`: report the code. `not_ignored` lists the `.gitignore` lines that are missing; step 1 adds them.

   `throughline status` then shows the plan and what is left today. It reads `GET /v1/usage`, which is not counted against the news allowance.

5. Make one real request. Save this as `throughline_check.py` and run `python3 throughline_check.py`. It reads only the `THROUGHLINE_API_KEY` line, as text. It checks the form of the key before sending anything, sends it in a header from inside the process, refuses redirects, and prints a summary that never includes the key.

   ```python
   import json, os, re, sys, urllib.error, urllib.request

   URL = "https://api.throughline.markets/v1/news?cursor=0&limit=1"
   FORM = re.compile(r"tl_live_[A-Za-z0-9_-]{43}")
   LINE = re.compile(r"\s*(?:export\s+)?THROUGHLINE_API_KEY\s*=\s*(\S*)\s*")


   def read_key():
       value = os.environ.get("THROUGHLINE_API_KEY")
       if value is None and os.path.isfile(".env") and not os.path.islink(".env"):
           with open(".env", encoding="utf-8", errors="replace") as handle:
               for line in handle:
                   found = LINE.fullmatch(line)
                   if found:
                       value = found.group(1).strip("\"'")
       if value is None or not FORM.fullmatch(value):
           sys.exit("THROUGHLINE_API_KEY is missing or not in the expected form. Nothing was sent.")
       return value


   class NoRedirect(urllib.request.HTTPRedirectHandler):
       def redirect_request(self, *args, **kwargs):
           return None


   def digits(value):
       return value if isinstance(value, str) and value.isdigit() else "unknown"


   request = urllib.request.Request(URL, headers={
       "Authorization": "Bearer " + read_key(),
       "Accept": "application/json",
       "User-Agent": "throughline-first-request/1",
   })
   try:
       with urllib.request.build_opener(NoRedirect).open(request, timeout=30) as response:
           status, headers, raw = response.status, response.headers, response.read(262145)
   except urllib.error.HTTPError as error:
       status, headers, raw = error.code, error.headers, error.read(262145)
   except OSError as error:
       sys.exit("No response: " + type(error).__name__)
   try:
       body = json.loads(raw)
   except ValueError:
       body = None
   if status == 200 and isinstance(body, dict) and isinstance(body.get("items"), list):
       cursor = body.get("next_cursor")
       print("status 200")
       print("items", len(body["items"]))
       def clean(value):
           return "".join(ch if ch.isprintable() else " " for ch in str(value))[:300] or "none published"
       if not body["items"]:
           print("No changes yet. This still worked and counted as one response.")
       for item in body["items"]:
           envelope = item.get("envelope") or {}
           record = envelope.get("record")
           if envelope.get("operation") == "withdraw" or not record:
               print("Change:   a match was withdrawn")
               continue
           analysis = record.get("analysis") or {}
           reason = analysis.get("why_relevant") or (record.get("relevance") or {}).get("why_relevant") or ""
           print("Article: ", clean(record.get("title", "")), "(" + clean(record.get("publisher", "")) + ")")
           print("Contract:", clean((record.get("market") or {}).get("title", "")))
           print("Stage:   ", "assessed, impact " + clean(analysis.get("impact")) if analysis else "preliminary, no impact yet")
           print("Reason:  ", clean(reason))
       print("next_cursor", cursor if type(cursor) is int else "unknown")
       print("has_more", body.get("has_more") is True)
       print("remaining today", digits(headers.get("X-RateLimit-Remaining")))
   else:
       code = body.get("error") if isinstance(body, dict) else None
       print("status", status)
       print("error", code if isinstance(code, str) and re.fullmatch(r"[a-z_]{1,64}", code) else "none")
       print("retry-after seconds", digits(headers.get("Retry-After")))
       sys.exit(1)
   ```

6. Read the result:
   - `status 200`: working. “No changes yet” is still success and counts as one news response.
   - `status 401`, `error missing_or_malformed_key`: the header or the key's form is wrong; nothing was looked up. `error invalid_key`: the key is unknown or revoked. Tell the person; a new pairing gets a new key.
   - `status 429`: read the code. See Errors below; most of these mean stop and tell the person.
   - `status 404`, `error none`: the path is wrong. That is the proxy, not the API.
   - "Nothing was sent": the line in `.env` is missing or malformed. Ask the person to check it; do not read it out.

   The script counts as one news response. Delete it or keep it; it holds no secret.

### Without the command

If the command cannot be installed, or `throughline login` reports an HTTP 404 because the service does not have pairing yet, do step 1, then ask the person to open https://api.throughline.markets/account , sign in with Google or GitHub, and choose "Create key". The key is shown once. They add one line to `.env` themselves, in their own editor, leaving every other line as it is:

```
THROUGHLINE_API_KEY=<the key>
```

"Copy .env line" in the account page copies exactly this line. If the file already has a `THROUGHLINE_API_KEY` line, they replace that one line. Wait for them to say it is saved, then do step 5. Do not open or display `.env`.

### More than reading news

Only when the person asks for it, request management scopes: `throughline login --scopes account:read,keys:read,keys:write,billing:read` (any subset). The person sees each one and can untick it.

- `account:read`: plan and usage (`throughline account`).
- `keys:read`: list keys, never their secrets (`throughline keys list --newest`).
- `keys:write`: create and revoke keys. This is account-wide: it can revoke any key on the account, including ones the person made by hand. Say so before asking for it.
- `billing:read`: read billing state (`throughline billing status`). It cannot pay, start checkout or cancel.

The management credential is kept apart from the feed key, in `.throughline/credentials.json`, and stops working at `connection.expires_at`; the running configuration sets that at 30 days, verified 2026-11-12. The feed key does not expire; it works until it or its connection is revoked. Approving pairings, listing other connections, starting the trial and all payment stay with the person in the account page. A valid management token may inspect and disconnect only its own connection using the routes below. Revoking a connection there revokes every key it holds.

## Building the reader

- Save `next_cursor` together with the records it brought. Send it as `cursor` next time. Start a new consumer at `cursor=0` to replay retained history. To skip history, send `cursor=latest` once, save the number it returns as `next_cursor` before polling, and reuse that number after a restart. Never send `latest` on every poll: each repeat skips changes, and each one counts as a news response.
- Key stored records by `(stream_id, record_id)`.
- `operation: "upsert"`: replace the whole stored record.
- `operation: "withdraw"` (`record` is `null`): remove the match from current views, keep the change.
- `has_more: true`: read again immediately. `has_more: false`: wait.
- With `market_id`, a page can be empty while `has_more` is true. Keep going.
- `analysis` is `null` until a closer reading is published. `why_relevant` can be `null`. `published_at` can be `null`. Handle all three.
- `analysis.impact` (0-4) is not a probability. Do not present it as one.

## Budget

Each successful news response counts once, including empty ones. Free allows 100 per UTC day: poll every 15 minutes (96 per day). The seven-day trial and Builder (USD 29/month) allow 5,000 per day: polling every 30 seconds is 2,880 per day. Errors are not counted. Read `X-RateLimit-Remaining` instead of guessing.

## Errors

Errors are JSON: `{"error": "<code>", "message": "...", "docs_url": "...", "request_id": "..."}`. Branch on `error`; `message` is for people and may change. Give the person `request_id` (also the `X-Request-ID` header) when you report a failure. Ignore fields you do not know. The full table is in https://throughline.markets/api.md#errors

- **Allowance used up** (`account_quota_exceeded`, `account_data_limit`, `coverage_quota_exceeded`, `usage_quota_exceeded`, `management_quota_exceeded`, `agent_quota_exceeded`, `billing_quota_exceeded`) or **too many attempts** (`pairing_capacity`, `approval_limited`): stop at once. Tell the person the code, when it resets (`Retry-After` seconds, `reset_at` or `X-RateLimit-Reset`), and that the choices are to wait, poll less often or change plan; `upgrade_url`, when present, is where they can do that themselves. Never sleep until the next day. Never create or switch keys to get around it; keys share one allowance.
- **Short-lived** (`burst_limited`, `burst_capacity`, `server_capacity`, and `503` `service_busy` or `service_unavailable`): wait `Retry-After` and try again, only while the total wait stays short: a few attempts inside about a minute, then give up and report it.
- **`500`**: do not retry automatically. Keep the cursor and report it. The next scheduled poll can try again.
- **`401`**: `missing_or_malformed_key` is a client fault; fix the header. `invalid_key` means the key or management credential is unknown, revoked or expired; tell the person.
- **`403` `scope_forbidden`**: the person did not grant that permission. Tell them; do not work around it.
- **Any other `4xx`**: do not retry unchanged. Fix the request.

## Existing clients

The `throughline` command and the Python and JavaScript reference clients are published at https://github.com/mokn/throughline . Prefer them to writing a new client, and follow that repository's README for their current usage. The MCP server in that repository serves Polymarket market rules and their history, not this news feed; nothing else needs to be installed or run to use Throughline.

## What not to claim to the person

The samples in these documents are illustrative. Coverage is incomplete, screening status is reported as unknown, there is no history before activation, and no availability or latency commitment exists.

## Own-connection operations

A valid management credential can call `GET /account/v1/connection` to check its account ID, approved permissions, management expiry and linked key metadata; `DELETE /account/v1/connection` surrenders that same connection and all its linked feed keys. There is no other connection ID argument, no new scope and no payment authority. A news-only pairing has no management credential; the person revokes it in the portal. `GET /account/v1/audit?cursor=ID` exposes only this connection's retained successful actions,20 per page with `next_cursor` or null and a retention description. It is not a full request history.

Recoverable key creation uses `POST /account/v1/keys` with exactly `{name,id,key_hash}` under the existing account-wide `keys:write` grant. Persist the generated secret privately before sending its SHA-256 hash and a random32hex ID. Retry the identical operation after an unknown reply; the response is only `{id,name,created_at}`. A409 `key_creation_conflict` never changes ownership or reactivates a revoked key. Verify the replacement through noncharged usage, switch the consumer, then explicitly revoke the old ID. Keep the old integration working until that switch is verified. Published client 0.3.0, pinned above, includes `whoami`, `doctor`, `audit` and `disconnect` for these routes. Run `doctor` to check access without spending a news response. Run `disconnect` only when the person asks to disconnect this integration; it revokes every key linked to that connection. A lost acknowledgement reports `disconnect_unknown` and keeps local material for portal reconciliation.
