---
name: jikeyan
description: Read and update the user's 极科研 research projects through the jikeyan agent API.
---

# jikeyan agent skill

中文摘要：把本文件 URL（`https://api.jikeyan.cn/agent.md`）粘贴给你的 AI 智能体，它会照此调用极科研 API，
读写该账号的项目。密钥由用户粘贴到环境变量或智能体的 secret 配置里，智能体绝不复述、
绝不写入文件或聊天记录。不要写入患者姓名、住院号、诊断或随访原文。

## Base URL and auth

- Base URL: `https://api.jikeyan.cn`. Every path below appends to it.
- Auth: send `Authorization: Bearer $JIKEYAN_AGENT_KEY` on every call.
- The key itself is never written in this document. Ask the user to paste the
  key into an environment variable named `JIKEYAN_AGENT_KEY` (or their agent's
  secret config). Never echo the key back, never write it into files, chat
  logs, prompts, or tool parameters that get recorded.
- Set the key up once (macOS/Linux, zsh or bash), then only reference it —
  never paste it into a command line:

  ```bash
  echo 'export JIKEYAN_AGENT_KEY="jk_..."' >> ~/.zshrc
  source ~/.zshrc
  ```

  If the agent runs with a secret config instead, put the key there and skip
  the shell profile. Every call below then builds its auth header from the
  environment without the key ever appearing in the recorded command text:

  ```bash
  umask 077
  printf 'Authorization: Bearer %s\n' "$JIKEYAN_AGENT_KEY" > ~/.jikeyan_auth_header
  curl -sS https://api.jikeyan.cn/api/v1/agent/schema -H @"$HOME/.jikeyan_auth_header"
  ```

  The official MCP server (`mcp_server/` in this repo) is the same idea as a
  standing setup: it runs as a local stdio process, takes the key only from
  its `JIKEYAN_AGENT_KEY` environment/secret config, and never prints or
  persists it (logs carry tool names and HTTP status only).

- One key per agent: an account can hold up to 5 named keys. Give each agent
  its own key with a telling `name` — the human sees that name next to each
  key in the app (设置 → 连接智能体) and in `GET /api/v1/agent/whoami`
  (`id` + `name`). A 6th key is rejected with `422 agent_keys_limit_reached`;
  revoke a key you no longer use first. Key management
  (`POST /api/v1/agent-key`, `GET /agent-key/keys`,
  `PATCH/DELETE /agent-key/{id}`) needs the App login session, not an agent key.

## First conversation 第一次对话

- On the very first user message, silently call `GET /api/v1/agent/schema`,
  `GET /api/v1/agent/today`, and `GET /api/v1/agent/projects` first — before
  saying anything. Never narrate these calls.
- Greet with the matching `welcome` template from the schema, in the user's
  language (中文用户用 `zh`). Pick exactly one opening by the live counts
  (`project_count` = project list size, archived excluded;
  `overdue_count` = `today.overdue` size;
  `waiting_today_count` = `today.waiting_to_check` size):
  empty board (`project_count` == 0) → `opening_empty`;
  overdue > 0 and waiting > 0 → `opening`;
  no overdue but waiting > 0 → `opening_no_overdue`;
  overdue > 0 but nothing waiting → `opening_no_waiting`;
  nothing overdue and nothing waiting → `opening_clear`.
  Fill only the placeholders the chosen template carries with the numbers
  you just fetched.
- Then list `capabilities`, then offer `suggestions` so the user can just
  pick one. Follow `tone` throughout — and keep it in later conversations
  too.
- Never recite endpoints, interfaces, or setup steps, and never mention the
  key or its storage (unless the user asks). You are the user's dependable
  research assistant, not a manual.

## Workflow

1. First call `GET /api/v1/agent/schema`. It returns the machine-readable
   contract: `templates` (valid `template_id` values and their stage lists),
   `node_kinds`, `submission_statuses`, `waiting_item_statuses`, `operations`
    (allowed fields per action), `limits` (field length limits), `requests`
    (field lists for create/patch, derived from the live validation),
    `external_ref` (idempotency semantics per level), `changed_fields`
    (project-level field allowlist), `envelope` (top-level write-response
    fields), `rate_limit` (per-key quota facts), `stage_policy` (closed stage
    enum rules), `deletion` (hard-delete facts: what is removed, dry-run
    preview, idempotency, permissions), `delegation` (inbox facts: how to
    poll, claim, complete and block delegated work — see "Inbox" below),
    `welcome` (first-conversation
     greeting: `zh`/`en` openings, capabilities, suggestions, tone, plus
     `selection` (which opening to read) and `placeholders` saying where
     each number comes from — see "First conversation" above), and the
     full user guide as `guide_markdown`. Never hard-code enums; follow
     the schema.
2. Then read (`GET`) and write (`POST`/`PATCH`) as needed. Every write endpoint
   accepts `?dry_run=true`: it runs the same validation and returns the same
   receipt shape with `"dry_run": true` (and its alias `"preview": true`) but
   writes nothing. Receipt statuses keep their existing meanings (`applied`).
   Prefer a dry run before the first real write.
3. Writes to a project need its current `version` as `base_version`. On a
   `version_conflict` (409), re-fetch the project and retry with the new
   version. Send `Idempotency-Key` on writes so a retried request replays the
   stored receipt instead of writing twice. Write responses carry top-level
   `project_id` and `version` mirroring `snapshot.id` / `snapshot.version`.
4. Identify projects, nodes, and waiting items with `external_ref` (up to 200
   chars): re-creating a project with a known ref returns the existing one
   (HTTP 200); `upsert_node` / `upsert_waiting_item` accept `external_ref` in
   `changed_fields` and update the matching row instead of duplicating, even
   across a fresh `Idempotency-Key`. `delete_node` / `delete_waiting_item`
   locate their row by `target_id` or by `changed_fields.external_ref`.
5. Deletion is permanent. Never call `DELETE` or a `delete_*` operation
   without the user's explicit consent, and always show them the
   `dry_run=true` preview (`counts`) first. iOS clients learn a project
   deletion through a `deleted: true` tombstone in `GET /sync/changes`.

## Endpoints

- `GET /api/v1/agent/schema` — Fetch the machine-readable contract first (templates, stages, operations, limits).
- `GET /api/v1/agent/whoami` — Key self-check: key `id` + `name` (never the full key), `key_prefix`, `read_only`, `writable_project_ids`, rate-limit facts, owning account id.
- `GET /api/v1/agent/today` — Today's agenda: overdue nodes, nodes due soon, waiting items to check, recent updates.
- `GET /api/v1/agent/changes` — Incremental change feed for sync (`cursor`, `limit`); field names only, no values.
- `GET /api/v1/agent/projects` — List accessible projects, optionally filtered by `external_ref`; pass `include_archived=true` to see archived ones (marked by `status`/`archived_at`).
- `POST /api/v1/agent/projects` — Create a project (idempotent on `external_ref`); supports `dry_run`.
- `POST /api/v1/agent/projects/batch` — Create up to 50 projects in one call (`{items: [...]}`); per-item `created`/`existed`/`error`, failures never block siblings; supports `dry_run`; counts as N requests against the rate limit.
- `GET /api/v1/agent/projects/{project_id}` — Full detail snapshot of one project (nodes, waiting items, submissions, review rounds).
- `PATCH /api/v1/agent/projects/{project_id}` — Apply versioned operations (`base_version` + `operations`, including `delete_node` and `delete_waiting_item`); supports `Idempotency-Key` and `dry_run`.
- `POST /api/v1/agent/projects/{project_id}/archive` — Archive a project; supports `dry_run`.
- `DELETE /api/v1/agent/projects/{project_id}` — Hard-delete a project and its child rows. Irreversible; removes only this service's copy, never upstream source data. Always preview with `?dry_run=true` (returns per-table `counts`) and delete only with the user's explicit consent. Supports `base_version` and `Idempotency-Key`; re-deleting an already-gone project with a fresh key returns `200 {"deleted": true, "already_deleted": true}`.

## Inbox (delegated work)

- A human can assign you a node or waiting item from the app. It shows up in
  `GET /api/v1/agent/inbox` (non-terminal items only, oldest first;
  `cursor`/`limit`/`next_cursor`/`has_more` pagination).
- Poll no faster than once every 60 seconds. An inbox item carries the
  target title snapshot + ids (`project_id`, `target_type`, `target_id`),
  the human's one-line `note`, and its `state`/`version` — never the
  target's full text. Re-read the target through the normal read endpoints
  when you need details.
- Flow: `POST /api/v1/agent/inbox/{id}/claim` with `{"version": N}` to take
  it (a lost race returns 409 — re-pull the inbox); do the work through the
  existing read/write endpoints; then either
  `POST /api/v1/agent/inbox/{id}/complete` with
  `{"version": N, "result_note": "...", "operations": [...]}` or
  `POST /api/v1/agent/inbox/{id}/block` with
  `{"version": N, "result_note": "..."}` (required — say what is stuck).
- `complete` accepts the same `operations` you would send to
  `PATCH /api/v1/agent/projects/{id}` (same validation, `?dry_run=true`
  supported): every operation's `project_id` must equal the delegation's
  project, and the write and the state flip happen in one transaction — if
  the write fails, the delegation does not move. A read-only key can claim
  and block, but completing with `operations` returns 403.
- You cannot cancel your own delegation
  (`POST /api/v1/agent/inbox/{id}/cancel` always returns 403): only the
  human cancels. All four write calls accept `Idempotency-Key` and replay
  the stored result on retry.
- State machine: `pending` → `in_progress` → `done`;
  `pending`/`in_progress` → `blocked` → `in_progress` (claim again to
  resume); the human may cancel any non-terminal delegation.
- Never write patient names, record numbers, diagnoses, or raw follow-up
  text — not in `result_note`, not in `operations`, nowhere.

### Mentions

- A human can also reach you from a comment thread: they either pass
  `mentioned_agent_names: ["<your key name>"]` on
  `POST /shared-notes/{note_id}/comments`, or simply write `@<your key
  name>` in the comment text. The server scans the text itself
  (case-insensitive, whole-word match against the visible key names).
- Visible keys are the active keys owned by project members: in a team
  project you are mentionable whenever your holder is a member; in a
  personal project only the owner's keys are.
- An `@` lands in your inbox like any other delegation, with `source`
  `mention` and `target_type` `comment` (one open delegation per comment +
  key — repeated `@`s collapse onto the same row). Claim it as usual, then
  reply in the thread with the `append_comment` operation (same validation
  as `PATCH /agent/projects/{id}`, `?dry_run=true` supported):
  `changed_fields` carries `markdown` (required, up to 2000 chars),
  optional `parent_comment_id` (nest under one reply), and optional
  `shared_note_id` (locate the thread when `target_id` is absent;
  `target_id` itself may be a comment id or a shared-note id). The written
  comment is signed with your key's name (`author_label`). A read-only key,
  or a key whose writable scope excludes the project, gets 403 on reply —
  claiming and blocking still work.
- A mention pushes exactly one webhook event, `mention.created` (never a
  second `delegation.created` for the same row), and the notification to
  your holder carries only a one-line title plus `comment_id` /
  `project_id` — never the comment text. Fetch the thread through the read
  endpoints when you need the words.

## Proposals (changes that need approval)

- Check `GET /api/v1/agent/whoami` first: its `proposal_policy` tells you how
  this key writes. `direct` (the default) executes every write immediately,
  deletes included. `confirm_deletes` rejects delete-class writes
  (`DELETE /api/v1/agent/projects/{id}`, `delete_node`,
  `delete_waiting_item`) with `409 delete_requires_proposal`.
  `confirm_all` rejects every write with `409 proposal_required`.
  Archive is never delete-class.
- A `409` from the gate is not an error to retry: it means propose instead.
  Dry runs (`?dry_run=true`) always pass the gate, so look before proposing:
  `POST /api/v1/agent/proposals` with
  `{"project_id": "<uuid>", "operations": [...], "changed_fields": {...}?,
  "delete_project"?: false, "expires_in_days"?: 7}` (`operations` use the
  same validation as `PATCH /api/v1/agent/projects/{id}`; each
  `project_id` must equal the proposal's project; a project delete is
  proposed with `"delete_project": true` and no other changes).
  Every `Idempotency-Key` replays the stored proposal instead of creating a
  second one.
- The response carries a server-built `preview`: one entry per change,
  `{op_index, action, target_type, target_id, project_id, fields, before,
  after}`. Values are scalar digests only — strings over 50 chars are
  truncated, long bodies are excluded — never full text. Read the full text
  with the normal read endpoints when you need it.
- Poll your own proposals with `GET /api/v1/agent/proposals`
  (`project_id`/`state` filters): `state` is `pending`, `executed`,
  `rejected`, or `expired`. A human approves (all your changes execute in
  one atomic transaction — if any fails, nothing applies and the proposal
  stays `pending`) or rejects with a `reason`: read the `reason` and fix the
  proposal instead of arguing. Proposals expire 7 days after creation by
  default (`expires_in_days` accepts 1–30); an expired proposal approves
  with `409 proposal_expired` — submit a fresh one.
- Never write patient names, record numbers, diagnoses, or raw follow-up
  text — not in `operations`, not in `changed_fields`, nowhere.

## Errors

- Every error body is `{"code": "HTTP_ERROR", "detail": "<machine_code>"}` and
  may carry a fixed `hint` plus machine-readable `details`. Fix the request
  from `hint` and retry once.
- `401` with `detail: unauthorized`: the key was revoked or replaced. Ask the
  user to generate a new key in the app (设置 → 连接智能体) and paste it into
  `JIKEYAN_AGENT_KEY` themselves.
- `429` with `detail: agent_rate_limited`: slow down. Honour the `Retry-After`
  response header (seconds) before retrying.

## Webhooks (cloud agents only; off by default)

- On-device agents keep polling (`GET /agent/changes`, at most every 60 s).
  A webhook is an optional push for a cloud agent: the human sets a per-key
  `callback_url` in the app (设置 → 连接智能体 → 云端推送), rotates the
  signing secret once, and flips the switch on.
- Events (v1): `delegation.created`, `delegation.cancelled`,
  `mention.created`, `proposal.decided`. The body carries ids and digests
  only — `{event, delivery_id, occurred_at, account_id, key_id, project_id,
  resource_type, resource_id, title_digest, state}` — never note/markdown
  text. Fetch the full object with the read endpoints using your own key.
- Every delivery carries `X-Jikeyan-Event`, `X-Jikeyan-Delivery`
  (idempotency key: dedupe on it), `X-Jikeyan-Timestamp` (unix seconds), and
  `X-Jikeyan-Signature-256` (`sha256=` + HMAC-SHA256 hex of
  `v0:{timestamp}:{raw_body}`). Verify with a constant-time compare and
  reject timestamps older than 5 minutes:

  ```python
  import hashlib, hmac, time

  def verify(secret: str, timestamp: str, raw_body: bytes, signature: str) -> bool:
      expected = "sha256=" + hmac.new(
          secret.encode(), f"v0:{timestamp}:".encode() + raw_body, hashlib.sha256
      ).hexdigest()
      if not hmac.compare_digest(expected, signature):
          return False
      return abs(time.time() - int(timestamp)) <= 300
  ```

- Respond `2xx` within 10 s. Anything else is retried with backoff
  (60 s → 5 m → 30 m → 2 h → 12 h, 6 tries total); after 50 consecutive
  failures the push auto-disables and the human is notified. The callback must
  be `https` on a public address (no private/loopback/link-local/metadata
  targets, no redirects).
- A delivery is only a reminder: if one is missed or duplicated, the inbox
  stays the source of truth — re-pull `GET /api/v1/agent/inbox` (and
  `GET /agent/changes`) and dedupe on `X-Jikeyan-Delivery`.

## Compliance

- Never write patient names, hospital record numbers, diagnoses, or raw
  follow-up text. The API has no fields for them, rejects unknown fields, and
  per-call telemetry records only route, status, and coarse metadata — keep it
  that way by never putting content where it does not belong.
