# Comment.io

> Comment.io is a shared workspace of Markdown documents for people and their
> agents: people work in the browser, agents over SSH, MCP or HTTP. This is the
> index of Comment.io's instructions for agents; each guide below is its own
> Markdown file.

The homepage serves this index to plain HTTP fetches and recognized agent
fetchers; browser navigation gets the web app. Use `/?mode=agent` or `/llms.txt`
to request it explicitly, even if your fetcher sends browser headers. The pages
about Comment.io answer the same way; add `.md` to a page's path to get its
Markdown. Every guide below is also in one file, [llms-full.txt](https://comment.io/llms-full.txt).

## When to use Comment.io

Use Comment.io when your work needs people to read it, correct it or build on
it, and the next agent should start from what was decided:

- **Drafts people review.** Write a spec, plan or report into the workspace.
  People comment on passages and suggest edits in the browser; you read the
  comments, answer them and revise, or propose edits for them to accept.
- **What the team knows.** Read the workspace's decisions, conventions and
  runbooks before you start, and follow the corrections people made there.
  When you learn something the next agent needs, write it into the file.
- **Plans you work through.** Work from a plan in a document and tick items off
  in the same file while people watch.
- **Several agents on one job.** Each agent is a named member. Watch files and
  send notes to other agents: one drafts, another reviews, and a third picks up
  later where they left off.
- **Invitations and new workspaces.** Prepare an invitation for a person, or
  propose a new workspace, for a person to approve.

Comment.io is not a place to run code: workspace commands run on Comment.io's
servers over the workspace's documents only, with no network access and no
other programs. Never write a key, token or other credential into a document.
Only a person in a workspace can let an agent in, so without access, ask your
human.

## How to connect

An agent works in a workspace in one of three ways: over MCP, over SSH, or over
the HTTP API. All three run the same commands as the same agent. MCP is
recommended when it is the simpler path, as it is for most apps. SSH is more
powerful: calls have no 45-second limit, and `scp` and `sftp` copy files.
Connect the first one that works from your machine, checking each yourself:

1. **MCP** is recommended. It works when your app can add the remote
   MCP server `https://comment.io/mcp` and sign in to it in your human's
   browser: a chat app with custom connectors, or a coding agent on your
   human's own computer, such as Claude Code, Codex or Cursor. Follow
   [Connect over MCP](https://comment.io/llms/mcp.md).
2. **SSH** is next, and more powerful. It works when `ssh`, `ssh-keygen` and
   `ssh-keyscan` are installed and `ssh-keyscan -T 10 -p 22 ssh.comment.io`
   prints a key line. That
   only shows the port is reachable: never add a scanned key to `known_hosts`
   (the guide pins the key from the enrollment response), and if your human's
   setup prompt names the key and the scan shows another, stop and tell them.
   Follow [Connect over SSH](https://comment.io/llms/ssh.md).
3. **The HTTP API** is for an agent that can do neither. It works when a POST
   of `{"command":"help"}` as `application/json`, without a token, to
   `https://comment.io/api/run` answers 401, and you can keep a token in a
   file only you can read. Your human makes the token: follow
   [Use the HTTP API](https://comment.io/llms/http-api.md).

## Guides

- [Connect over MCP](https://comment.io/llms/mcp.md): add the remote MCP
  server to a chat app or coding agent, and adding SSH later.
- [Connect over SSH](https://comment.io/llms/ssh.md): make a key, ask a
  person to approve it, configure and verify the SSH alias, and recover access.
- [Run workspace commands](https://comment.io/llms/commands.md): read,
  search, write and suggest edits; link a person to a file; disconnection;
  report a problem or send feedback to Comment.io (`report-problem`); skills;
  typed records (Things); copying files with scp and sftp.
- [Use the HTTP API](https://comment.io/llms/http-api.md): run any command
  with `POST /api/run` and an API token.
- [Invite a person](https://comment.io/llms/invite-a-person.md): prepare an
  invitation to an existing workspace for a member to approve.
- [Propose a new workspace](https://comment.io/llms/propose-a-workspace.md):
  for a person with a Comment.io account, optionally connecting yourself.
- [All guides in one file](https://comment.io/llms-full.txt).

## Remember the connection

For future Comment.io tasks, install the small [using-commentio skill](https://comment.io/skills/using-commentio/SKILL.md)
in your agent's skills directory on this machine. For agents that load skills
from `~/.agents/skills`, download it to
`~/.agents/skills/using-commentio/SKILL.md`; otherwise use your agent's supported
skill location. Review it before installing or updating it. After setup, add
one line to its Connections section naming the workspace, your handle and how
you connected: `- WORKSPACE as AGENT over MCP: run tool of MCP server SERVER_NAME`,
`- WORKSPACE as AGENT over SSH: ssh -n WORKSPACE.AGENT 'COMMAND'` or
`- WORKSPACE as AGENT over HTTP: token file ~/.config/commentio/WORKSPACE.AGENT.header`.
Keep the lines already there when updating it. New sessions use that line, and
otherwise find a Comment.io MCP server, a local SSH alias or a token file. The
skill contains no key, token or other credential; never write one into it.

## About Comment.io

- [Docs for people](https://comment.io/docs.md): how people use Comment.io
  in the browser, including teams, apps, comments, Catch up and sharing.
  When your human asks how to do something in Comment.io, answer from these
  and send them [https://comment.io/docs](https://comment.io/docs), which
  opens them in a browser.
- [What Comment.io is used for](https://comment.io/use-cases.md)
- [Frequently asked questions](https://comment.io/faq.md)
- [About us](https://comment.io/about.md)

# Connect an agent to a Comment.io workspace over SSH

SSH is the more powerful way for an agent with a shell to work in a Comment.io workspace, with no 45-second limit per call and `scp` for files; MCP is recommended when it is the simpler path for the agent's app. Over SSH, the agent makes its own key, a person in the workspace approves it in the browser, and the agent configures and verifies an SSH alias. Other ways to connect are in [the guide index](https://comment.io/llms.txt).

## Connect an agent to an existing workspace

Set up access on the machine where you, the agent, will run `ssh WORKSPACE.AGENT`.
You manage the local agent name, keypair, enrollment, SSH configuration, and verification;
the human only reviews the approval request in their browser.
Before creating a key or request, ask which machine and identity to recover if
the human says this agent previously had access but this machine has no local
alias, key, or saved request. Do not treat missing local files as revocation.
Prepare a request and give a current human workspace member its review link. Human-copied
setup instructions contain no credential and grant no access. The alias must
log in as the named agent using its matching private key.

## 1. Create the local keypair

Inspect `~/.ssh/config` and run `ssh -G WORKSPACE.AGENT` first. Reuse an existing
alias's dedicated key only after verifying the host, username, and matching
public key. A previously working alias can stop authenticating after its key
is revoked or the workspace is reset; that does not mean the local key is bad.
If an alias exists, try `ssh -n WORKSPACE.AGENT help` before requesting enrollment.
On failure, inspect the error and effective configuration, report the relevant
diagnosis to the human, and ask before proposing another identity. Never
overwrite an existing key to repair authentication.

Comment.io's SSH host is `ssh.comment.io`. An alias whose `HostName` is a workspace's
web address (such as `WORKSPACE.` followed by the main site's domain) predates
it, and that address no longer accepts SSH, so its connections fail. Move it
rather than enrolling again: once no other command for the alias is running,
run `ssh -O exit WORKSPACE.AGENT` (an error that no master is running is fine), set
`HostName ssh.comment.io` in its `Host` entry, keeping User, Port and IdentityFile,
and pin for `ssh.comment.io` (`[ssh.comment.io]:PORT` when the port is not 22) the same
server host key that `~/.ssh/known_hosts` already trusts for the old
`HostName` (`ssh-keygen -F OLD_HOSTNAME` shows it), stopping if the file
already trusts a different key for `ssh.comment.io`. Then run `ssh -n WORKSPACE.AGENT help`.

For a new pair, use `~/.ssh/Commentio.d/WORKSPACE.AGENT`. The `.d` directory avoids
colliding with an older private key named `~/.ssh/Commentio`. If the chosen
directory path is itself a file, preserve it and choose another directory.
Create directories with mode 700 and private keys with mode 600. Only submit
the public `.pub` key. This POSIX-shell example creates a new unencrypted key
for unattended use, or verifies and reuses the existing pair; an existing
encrypted key requires its passphrase or a working ssh-agent arrangement:

```sh
(
  set -eu
  umask 077
  Commentio_key_dir="$HOME/.ssh/Commentio.d"
  Commentio_key="$Commentio_key_dir/WORKSPACE.AGENT"
  if [ -L "$Commentio_key_dir" ] || { [ -e "$Commentio_key_dir" ] && [ ! -d "$Commentio_key_dir" ]; }; then
    echo "Key directory is a file; preserve it and choose another directory." >&2
    exit 1
  fi
  mkdir -p "$Commentio_key_dir"
  chmod 700 "$Commentio_key_dir"
  if [ -L "$Commentio_key" ] || [ -L "$Commentio_key.pub" ]; then
    echo "Key path is a symlink; inspect it and choose a dedicated file path." >&2
    exit 1
  fi
  if [ ! -e "$Commentio_key" ]; then
    if [ -e "$Commentio_key.pub" ]; then
      echo "Public key exists without its private key; recover the pair or choose a new path." >&2
      exit 1
    fi
    ssh-keygen -q -t ed25519 -N '' -f "$Commentio_key"
  fi
  chmod 600 "$Commentio_key"
  Commentio_public=$(ssh-keygen -y -f "$Commentio_key")
  Commentio_public=$(printf '%s\n' "$Commentio_public" | awk '{print $1 " " $2}')
  if [ -e "$Commentio_key.pub" ]; then
    Commentio_existing=$(awk '{print $1 " " $2}' "$Commentio_key.pub")
    if [ "$Commentio_existing" != "$Commentio_public" ]; then
      echo "Public/private key mismatch; preserve both and resolve before enrollment." >&2
      exit 1
    fi
  else
    printf '%s\n' "$Commentio_public" > "$Commentio_key.pub"
  fi
  echo "Keypair verified: $Commentio_key"
)
```

Check the command's actual exit status before reporting success. If you choose
a different key location, use that actual path in both enrollment and
`IdentityFile` below.

## 2. Request human approval

Run the request block. On HTTP 201, send **only its printed `approvalUrl` in a
user-visible assistant message before starting the polling tool call**. Tool
output is not the human handoff. Then run the polling block in the same turn
without waiting for a reply; the human approves in their browser. If your
interface cannot deliver an intermediate message before a blocking tool call,
end the turn with the link and resume polling when the interface allows it.
Replace `WORKSPACE` and `AGENT` as in section 1;
`AGENT` is the handle, matching `[a-z][a-z0-9-]{0,31}`. The blocks need POSIX
sh, Python 3, curl and jq, and keep their private files in a directory derived
from the key path, so they work in separate shells.

The request block generates a random recovery token and keeps it out of argv,
URLs and output. Rerunning it is an exact retry: it resends the saved
workspace, handle, key and token. Changing the workspace, handle or key needs a
fresh token and a new request; never reuse a token for another proposal. On a
transport failure or HTTP 429/503, wait `Retry-After` and rerun it; stop after
five consecutive failures. A request grants nothing and does not confirm that
the workspace exists.

```sh
(
  set -eu
  umask 077
  COMMENTIO_KEY="$HOME/.ssh/Commentio.d/WORKSPACE.AGENT"
  COMMENTIO_REQUEST_DIR="$COMMENTIO_KEY.request"
  mkdir -p "$COMMENTIO_REQUEST_DIR"
  if [ ! -e "$COMMENTIO_REQUEST_DIR/create.json" ]; then
    python3 - "$COMMENTIO_REQUEST_DIR" "$COMMENTIO_KEY.pub" <<'PY'
import json, secrets, sys
from pathlib import Path
p = Path(sys.argv[1])
token = secrets.token_hex(32)
key = ' '.join(Path(sys.argv[2]).read_text().split()[:2])
(p / 'status.json').write_text(json.dumps({'token': token}))
(p / 'create.json').write_text(json.dumps({
    'workspaceName': 'WORKSPACE', 'agentName': 'AGENT', 'publicKey': key, 'token': token}))
PY
  fi
  curl --silent --show-error --max-time 10 \
    -H 'Content-Type: application/json' --data-binary @"$COMMENTIO_REQUEST_DIR/create.json" \
    -D "$COMMENTIO_REQUEST_DIR/headers" -o "$COMMENTIO_REQUEST_DIR/created.json" \
    -w 'HTTP %{http_code}\n' https://comment.io/api/agent-requests
  # Continue only after HTTP 201; this prints only the human review link.
  jq -er '.approvalUrl' "$COMMENTIO_REQUEST_DIR/created.json"
)
```

The polling block normally waits about ten minutes, plus request time and
any server cooldowns. On `completed` it checks that the
enrolled key's fingerprint matches yours and saves `connection.json` for
section 3. On `rejected`, `expired` or `conflict` it deletes the request
directory, so the next request block starts afresh; a conflict means this
name or key could not be enrolled, so check for an existing enrollment before
requesting again. If it ends pending or unknown, rerun it later; never poll
concurrently. Approval is possible for 30 minutes, and a completed result stays
recoverable with the same token for 24 hours.

On a later session, inspect a saved request directory before creating another
request. An uncertain create retries the **same** saved payload and token; a
pending request resumes polling with its saved ID and token while recoverable.
After a completed enrollment, retry section 3 with its saved `connection.json`
instead of enrolling again. If recovery has expired, check the existing SSH
alias and ask the human before proposing a new identity; an unavailable status
does not prove rejection or revocation.

```sh
(
  set -eu
  COMMENTIO_KEY="$HOME/.ssh/Commentio.d/WORKSPACE.AGENT"
  COMMENTIO_REQUEST_DIR="$COMMENTIO_KEY.request"
  id=$(jq -er '.id | select(test("^[0-9a-f-]{36}$"))' "$COMMENTIO_REQUEST_DIR/created.json")
  failures=0
  wait_seconds=$(jq -er '.pollIntervalSeconds' "$COMMENTIO_REQUEST_DIR/created.json")
  for attempt in $(seq 1 120); do
    sleep "$wait_seconds"
    code=$(curl --silent --show-error --max-time 10 \
      -H 'Content-Type: application/json' --data-binary @"$COMMENTIO_REQUEST_DIR/status.json" \
      -D "$COMMENTIO_REQUEST_DIR/headers" -o "$COMMENTIO_REQUEST_DIR/status-response.json" \
      -w '%{http_code}' "https://comment.io/api/agent-requests/$id/status") || code=000
    wait_seconds=$(awk 'BEGIN{n=5} tolower($1)=="retry-after:" {v=$2+0;if(v>n)n=v} END{print n}' "$COMMENTIO_REQUEST_DIR/headers")
    case "$code" in
      200)
        failures=0
        state=$(jq -er '.status' "$COMMENTIO_REQUEST_DIR/status-response.json")
        case "$state" in
          pending) ;;
          completed)
            local_fingerprint=$(ssh-keygen -lf "$COMMENTIO_KEY.pub" | awk '{print $2}')
            if [ "$(jq -er '.connection.fingerprint' "$COMMENTIO_REQUEST_DIR/status-response.json")" != "$local_fingerprint" ]; then
              echo 'Enrolled key fingerprint does not match the local key; stop.' >&2; exit 1
            fi
            jq -e '.connection' "$COMMENTIO_REQUEST_DIR/status-response.json" > "$COMMENTIO_REQUEST_DIR/connection.json"
            echo 'completed; continue with the section 3 configuration block.'; exit ;;
          rejected|expired|conflict) find "$COMMENTIO_REQUEST_DIR" -depth -delete; echo "$state"; exit ;;
          *) echo 'Outcome unknown; preserve private recovery files.'; exit 1 ;;
        esac ;;
      400) echo 'Request unavailable; outcome unknown.'; exit 1 ;;
      429) ;;
      000|5??) failures=$((failures+1)); if [ "$failures" -ge 5 ]; then break; fi ;;
      *) break ;;
    esac
  done
  echo 'Still pending or outcome unknown; preserve private recovery files and retry later.'
  exit 1
)
```

Without a POSIX shell, follow the same contract. The recovery token is 32
cryptographically random bytes as 64 lowercase hex characters; keep it in
memory or a mode-600 file outside the repository, never in logs, output, URLs
or command arguments, and delete it after setup. POST this JSON object (at most
4096 bytes) to `https://comment.io/api/agent-requests`, built with a JSON encoder:

```json
{"workspaceName":"WORKSPACE","agentName":"AGENT","publicKey":"<canonical .pub key>","token":"<64 lowercase hex>"}
```

HTTP 201 returns `id`, `approvalUrl`, `expiresAt`, `recoverUntil` and
`pollIntervalSeconds`. Then POST `{"token":"<token>"}` to
`https://comment.io/api/agent-requests/REQUEST_ID/status` no faster than every
five seconds, honoring `Retry-After`, and stop at `recoverUntil`. HTTP 200
returns `status`; only `completed` includes `connection`. HTTP 400
`invalid_agent_request` is a generic error for an invalid or unavailable
request or credential, including a changed proposal under an existing token.
Never ask for a human session or approve the request yourself.

## 3. Configure SSH

Run the configuration block. It checks the server host-key fingerprint and pins
that key in `~/.ssh/known_hosts`, stopping if the file already trusts another or
a marked key for the endpoint. It adds this entry for the returned alias before
the first `Host` or `Match` block, leaving other entries alone, and checks with
`ssh -G` that no earlier option overrides it. Then it verifies bare SSH and
`help`, and deletes the request directory, including the recovery token. If it
stops, fix the configuration it names and rerun it; the enrollment is kept, so
do not request again.

```sshconfig
Host WORKSPACE.AGENT
  HostName ssh.comment.io
  User WORKSPACE.AGENT
  Port 22
  IdentityFile ~/.ssh/Commentio.d/WORKSPACE.AGENT
  IdentitiesOnly yes
  StrictHostKeyChecking yes
  UserKnownHostsFile ~/.ssh/known_hosts
  GlobalKnownHostsFile /dev/null
  VerifyHostKeyDNS no
  RequestTTY no
  ConnectTimeout 10
  ControlMaster auto
  ControlPersist 60
  ControlPath ~/.ssh/Commentio.d/control-%C
```

The server identifies the workspace and agent from the `WORKSPACE.AGENT`
username, not the hostname, and requires the enrolled key. The `Control*` lines
reuse one authenticated connection for 60 idle seconds; each `ssh` call is still
its own command with its own exit status. Other processes of the same OS user
can use that socket while it exists; `ssh -O exit WORKSPACE.AGENT` closes it. Native
Windows OpenSSH has no multiplexing, so omit those three lines there. Run one
command before starting parallel calls; a race prints a harmless `ControlSocket
... already exists, disabling multiplexing` warning.

When configuring by hand, keep strict host-key checking, never replace a
conflicting known-hosts entry, and write the pin as `ssh.comment.io SERVER_HOST_KEY`
on port 22 (`[ssh.comment.io]:22` never matches) or `[ssh.comment.io]:PORT` otherwise.

```sh
(
  set -eu
  umask 077
  COMMENTIO_KEY="$HOME/.ssh/Commentio.d/WORKSPACE.AGENT"
  COMMENTIO_REQUEST_DIR="$COMMENTIO_KEY.request"
  c="$COMMENTIO_REQUEST_DIR/connection.json"
  alias=$(jq -er '.alias | select(test("^[a-z0-9][a-z0-9.-]*$"))' "$c")
  host=$(jq -er '.host | select(test("^[A-Za-z0-9][A-Za-z0-9.-]*$"))' "$c")
  port=$(jq -er '.port | select(type == "number" and . >= 1 and . <= 65535 and floor == .)' "$c")
  user=$(jq -er '.username | select(test("^[a-z0-9][a-z0-9.-]*$"))' "$c")
  host_key=$(jq -er '.serverHostKey | split(" ") | .[0:2] | join(" ")' "$c")
  if [ "$(printf '%s\n' "$host_key" | ssh-keygen -lf - | awk '{print $2}')" != "$(jq -er '.serverHostKeyFingerprint' "$c")" ]; then
    echo 'Server host-key fingerprint mismatch; stop.' >&2; exit 1
  fi
  if [ "$port" = 22 ]; then known="$host"; else known="[$host]:$port"; fi
  kh="$HOME/.ssh/known_hosts"
  [ -e "$kh" ] || : > "$kh"
  set +e; trusted=$(ssh-keygen -F "$known" -f "$kh"); found=$?; set -e
  case "$found" in
    0) if ! printf '%s\n' "$trusted" | awk -v k="$host_key" '!/^#/ && NF { if ($1 ~ /^@/ || $2 " " $3 != k) bad = 1 } END { exit bad }'; then
         echo "known_hosts already has another or marked key for $known; stop and report the conflict." >&2; exit 1
       fi ;;
    1) printf '%s %s\n' "$known" "$host_key" >> "$kh" ;;
    *) echo "Cannot read $kh; stop and report the error." >&2; exit 1 ;;
  esac
  config="$HOME/.ssh/config"
  if [ -L "$config" ]; then echo "$config is a symlink; add the Host entry by hand." >&2; exit 1; fi
  [ -e "$config" ] || : > "$config"
  if ! awk -v a="$alias" 'tolower($1) == "host" { for (i = 2; i <= NF; i++) if ($i == a) found = 1 } END { exit !found }' "$config"; then
    entry=$(printf 'Host %s\n  HostName %s\n  User %s\n  Port %s\n  IdentityFile "%s"\n  IdentitiesOnly yes\n  StrictHostKeyChecking yes\n  UserKnownHostsFile ~/.ssh/known_hosts\n  GlobalKnownHostsFile /dev/null\n  VerifyHostKeyDNS no\n  RequestTTY no\n  ConnectTimeout 10\n  ControlMaster auto\n  ControlPersist 60\n  ControlPath ~/.ssh/Commentio.d/control-%%C\n' \
      "$alias" "$host" "$user" "$port" "$COMMENTIO_KEY")
    next="$config.Commentio-$$"
    COMMENTIO_ENTRY="$entry" awk '!done && tolower($1) ~ /^(host|match)$/ { print ENVIRON["COMMENTIO_ENTRY"]; print ""; done = 1 } { print }
      END { if (!done) { if (NR) print ""; print ENVIRON["COMMENTIO_ENTRY"] } }' "$config" > "$next"
    chmod 600 "$next"
    mv "$next" "$config"
  fi
  chmod 600 "$config"
  # Earlier global options or an existing entry can override these; OpenSSH keeps the first value.
  resolved=$(ssh -G "$alias")
  for want in "hostname $host" "user $user" "port $port" "identitiesonly yes" "requesttty false" \
      "stricthostkeychecking true" "userknownhostsfile $HOME/.ssh/known_hosts" \
      "globalknownhostsfile /dev/null" "verifyhostkeydns false"; do
    printf '%s\n' "$resolved" | grep -Fqx "$want" || { echo "ssh -G $alias lacks '$want'; fix the config that overrides it." >&2; exit 1; }
  done
  if ! printf '%s\n' "$resolved" | grep -Fqx -e "identityfile $COMMENTIO_KEY" -e "identityfile ~/${COMMENTIO_KEY#"$HOME"/}"; then
    echo "ssh -G $alias does not use $COMMENTIO_KEY; fix that Host entry." >&2; exit 1
  fi
  if printf '%s\n' "$resolved" | grep -Eq '^(hostkeyalias|knownhostscommand) '; then
    echo "ssh -G $alias redirects host-key trust; remove HostKeyAlias or KnownHostsCommand for it." >&2; exit 1
  fi
  # A master started under earlier settings would skip the host-key check; close it first.
  ssh -O exit "$alias" > /dev/null 2>&1 || :
  ssh -n "$alias" > /dev/null
  ssh -n "$alias" help > /dev/null
  find "$COMMENTIO_REQUEST_DIR" -depth -delete
  echo "Verified: ssh $alias (private key $COMMENTIO_KEY)"
)
```

## Completion

Verify SSH directly, without piping its output through `head`, `tee`, or another
command that can mask its exit status. `ConnectTimeout 10` is built into OpenSSH
and works on macOS; no GNU `timeout` is needed. A zero exit status and workspace
help must both be present. `Permission denied` is always a failed setup.

Setup is complete when enrollment succeeds, `ssh -G WORKSPACE.AGENT` resolves the intended host, username and private key, and both `ssh WORKSPACE.AGENT` and `ssh WORKSPACE.AGENT help` exit successfully with workspace help. Report the working alias and private-key path (not its contents) to the human so later sessions can identify it; you run subsequent workspace commands yourself with `ssh -n WORKSPACE.AGENT 'COMMAND'`. Bare SSH displays help and closes the connection.

# Run Comment.io workspace commands

Once connected, an agent works in a Comment.io workspace with shell commands over its documents: read, search, write and suggest edits, keep typed records, and copy files. The examples use SSH; over MCP or the HTTP API the same commands run with the same output and exit codes. Connecting is in [the guide index](https://comment.io/llms.txt).

## Run workspace commands

Comment.io runs shell scripts over workspace documents. Start with `help`: it
covers the everyday commands (search, edit, comment, suggest) and names, for
each other group of commands, the built-in skill with its details, which
`skill view NAME` prints.
Quote the remote script so your local shell does not expand it. Pipes, `;`,
`&&`, `||`, variables, globbing, and redirection are supported. Documents live
in `/workspace`, the initial working directory; `ls`, `ls .`, and
`ls /workspace` list that directory. Other paths belong to a temporary virtual
filesystem. The document mount is a restricted writable virtual workspace.
Explicit document commands handle namespace changes; `>`, `>>`, `tee`, and
`sed -i` commit each existing-document write when that operation is encountered.
The host filesystem, arbitrary programs, and network remain unavailable.

Run `doc-*` mutations directly. A request is either one standalone mutating
`doc-*` command or one shell script containing writes to existing documents.
Mixing explicit mutations with shell writes is rejected, but shell writes that
were already encountered remain committed. Successful mutations produce no
command output, so read back the document separately. There is no caller request
ID or replay token. If an SSH result is uncertain, read the latest state before
deciding what to do next; repeating a mutation is new work and may duplicate its
effect.

Every file lives in a team or My Space: a top-level folder holding
`definitions/`, `things/`, `apps/`, which holds only its apps (`.html` pages)
and folders of them, and `files/`, where all other files and
folders go, but no new HTML pages. Definitions and Things that every team
uses belong in the common team. `shared/` is now part of the common team:
a `shared/` path fails with `shared_retired`, naming where it is now. `skills/`
holds the workspace's skills. A text `style.css` may also sit at the workspace root
or directly in each team. A write anywhere else fails with `layout_refused`
and a line saying where it can go. `doc-create crm --folder` starts the
team `crm`.

An owner can limit a team to the people they add, so a team you were
working in can vanish mid-task. You have the access of the person you work
for: a team they aren't in appears nowhere and reads as a missing path; ask
an owner to add them. As a Viewer you read files without their comments; as a
Commenter you also read, add and resolve comments, suggest, and withdraw your
own suggestions; any other change fails with `project_read_only`. Your SSH
key or token reaches no further than the person who gave it to you, and only
the person you work for can give you a new one.
`teams` prints one JSON line per team you can open:
`{"team": NAME, "level": "edit"|"comment"|"view"}`, plus
`"limitedByGiver":true` where the
person who gave your key or token holds you below your own level. The one
marked `"common":true` is the common team: everyone in the workspace can
open it, it has the workspace's name, and it can't be restricted, renamed,
moved or deleted. Find it by that mark, not by its name; a workspace with none
marked has no common team yet. To keep something from some people, use another
team.
A personal space prints `{"space": NAME, "level": ...}`. `My Space` is the
personal space of the person you work for that only they and the workspace's
owners can open; `teams` names it `My Space`. Address it by that name, as in
`My Space/files/notes.md`. Owners' agents may also see other members' personal
spaces, named as those spaces in `teams`.

```sh
ssh -n WORKSPACE.AGENT 'rg -il needle -g "*.md" | sort | head -10'
printf '# Notes\n' | ssh WORKSPACE.AGENT 'doc-create crm/files/notes.md --stdin'
printf '\nNext: send the deck.\n' | ssh WORKSPACE.AGENT 'doc-append crm/files/notes.md --stdin'
ssh -n WORKSPACE.AGENT "doc-replace-text crm/files/notes.md Notes 'Meeting notes'"
ssh -n WORKSPACE.AGENT 'doc-read crm/files/notes.md crm/files/plan.md'
```

`doc-read` takes up to 20 paths and prints a JSON line for each, in order. A
file that fails prints its error on stderr, the rest still read, and the
command exits 1. Once it has printed 16 MiB, the paths left fail with
`read_limit_exceeded`; read them in another call.

To link a person to a file, give them its browser address: the workspace's
address, then `/` and the file's path, percent-encoded (a space is `%20`).
`help` shows the workspace's address in this form. A `My Space` link opens
only for the person you work for.

An uploaded file (a PDF, image, Office document, audio or video) is a text
file to agents: `doc-read`, `cat`, `head`, `sed` and the other utilities read
its extracted text, `rg` searches it under the file's own path, and
`rg --files` lists it. A transcript has a line per sentence, with its
speaker and start–end time; one made before October 2026 times each word
instead. Download the file for its original bytes; writes to it fail with
`binary_file`. Extracted text counts toward the workspace's search size limit.

```sh
ssh -n WORKSPACE.AGENT 'rg -n -i "budget" -g "*.mp4"'
ssh -n WORKSPACE.AGENT 'head -20 crm/files/meeting.mp4'
ssh -n WORKSPACE.AGENT 'doc-read crm/files/contract.pdf'
```

Until its text is ready, the file matches nothing and a read fails with one
of: `text_pending` (on its way; try again in a few minutes), `text_disabled`
(an owner must turn on file text extraction in workspace settings),
`text_unsupported` (no text is extracted from this type) or `text_failed`
with the reason, such as `media_too_long` or `no_audio_track`. Each read sees
one version of the text; text over 16 MiB cannot be read or searched. A shell
command prints at most 2,000,000 bytes, so `cat` fails on longer text; use
`doc-read`, or print part of it with `sed -n` or `rg`.

To create a document from a local Markdown file, or append one, without
quoting its contents:

```sh
ssh WORKSPACE.AGENT 'doc-create crm/files/notes.md --stdin' < local.md
ssh WORKSPACE.AGENT 'doc-append crm/files/notes.md --stdin' < more.md
ssh -n WORKSPACE.AGENT 'doc-read crm/files/notes.md'
```

`doc-create --stdin` creates the file and its text together: if the text is
refused (a Thing that fails its Definition, a limit), no file is left behind.

`--stdin` supplies the text for one create, append, anchored insert or
replacement; `doc-replace-text PATH ANCHOR --stdin` takes its replacement from
stdin, so multi-line text needs no quoting. Input preserves Unicode, quotes,
backticks, and trailing newlines. Invalid UTF-8 or a NUL character fails. Empty input fails for append and
insert; to `doc-replace-text` it deletes the anchor, and to `doc-create` it
makes an empty file (a skill, Thing or Definition starts from its template). Finite requests collect at most 2,000,000 bytes and require
EOF within 10 seconds, before any command executes. Oversized, timed-out, or
interrupted input commits nothing. Use `ssh -n` when no stdin is intended;
SSH clients using an API must end their input stream. Bare SSH, `help`, and
standalone `watch` do not wait for stdin. This is a finite shell, not an
interactive terminal. A request may contain only one stdin-consuming document
operation; this prevents buffered input from being consumed twice. Once an
operation commits, a later disconnect does not undo it. Read back the committed
document after an uncertain result; do not automatically retry a mutation.

**When a human disconnects an agent:**

Every current human member can Disconnect an agent in Settings, under Agents; agents cannot grant
or revoke access themselves. This revokes all of that agent's keys, not its
identity or document/notification history. A new SSH connection fails
authentication; a newly admitted exec using a revoked key fails with
`error: unauthorized` and exit 1. Draining connections reject new channels.
Live streams and transports stop within 30 seconds under a running process.
Database failure or pool starvation beyond the validity lease also closes
transports; `unavailable` does not mean a human revoked access.

Already-admitted database writes may finish after the transport closes, even
beyond 30 seconds. Forced closure may return an error/exit 1 or SSH transport-loss
exit 255; it does **not** prove rollback. Never automatically replay a mutation.
Ask a human or another authorized identity to inspect persisted state before
deciding what new work is needed. A replacement agent has a new principal, so
old receipt/request IDs do not deduplicate work across handles.

Reconnecting requires a new, unused agent handle and a new human-approved
enrollment request. Retrying the completed old enrollment does not restore keys.
Disconnect cannot recall output the agent already received.

**Agents do not need to know version numbers.** `doc-read` returns
`{path, entryId, content}` and, for a document, `openComments`. Neither you nor the command handles document revision tokens,
snapshots, or CRDT updates; the backend owns those details. Enrollment and access
recovery credentials ([Connect over SSH](https://comment.io/llms/ssh.md)) are separate from document editing.

```text
doc-read <path>...
doc-create <path> [--folder | --stdin]
doc-append [--suggest] <path> --stdin
doc-insert [--suggest] <path> (--before|--after) <anchor> [--occurrence N] --stdin
doc-delete-text [--suggest] <path> <anchor> [--occurrence N]
doc-replace-text [--suggest] <path> <anchor> [--occurrence N] (<replacement> | --stdin)
```

With `--suggest`, right after the command name, an edit to a Markdown file is
proposed as a suggestion for a person to accept or reject instead of changing
the text; `help` describes its limits and errors.

Each edit uses the document state captured by the backend when that edit
executes, after complete stdin has been received and validated where required.
An earlier `doc-read` does not pin a later edit; there is no hidden last-read or
session edit base. Anchors resolve exactly in the captured text. Insert, delete, and
replace require a unique anchor unless a one-based `--occurrence N` is supplied.
Append inserts at the captured text's end. `doc-insert` adds stdin directly
before or after the anchor text itself, not on a new line; include any newline
you need in stdin, for example `printf '\nReviewer: bot'` with
`--after "Meeting notes"`.
Whitespace, line endings, combining sequences, and Unicode are significant;
anchors are not regexes and are not normalized.

Edits committed before capture are already in the base. Edits arriving after
capture merge into the latest state of that same file; overlapping replacements
have no prose-level winner guarantee. A capture follows that file through
rename/move. Removal retires the captured identity and fails with
`stale_document_identity`; removal/recreation or reuse of its old path cannot
redirect an existing capture to a different file. A path missing when capture
starts fails with `file_not_found path="notes.md"`, naming the resolved path
JSON-quoted; `doc-rename` adds `destination="..."`, since either the source or
the destination's folder may be missing.
`doc-rename` preserves the document's text identity, and `doc-remove` removes
its path. Create refuses existing paths; rename refuses existing destinations.
A rename that would let more people see the file or folder, with its history
and comments (into a team more people can open, or out of My Space), fails
with `move_widens_access`, naming who; if they should see it, run
`doc-rename <path> <destination> --widen`.

`doc-rename` and `doc-remove` take `--entry ID`, the `entryId` that `doc-read`
printed, so they act only on the file you read: if another file has taken its
path since, they fail with `entry_changed` and change nothing. Read the path
again and decide afresh; do not retry without `--entry`. A folder has no
`entryId`, so a folder's rename or removal goes by path.
Renaming a Definition (`T/definitions/task.md`) to another team or file name
(`Q/definitions/task.md`) moves its type as one unit: every Thing in
`T/things/task/` and every file under `T/files/` they use, with their comments,
history and connections; missing folders are made. Moving `T/things/task/`
itself is refused with `thing_folder_move`.

`doc-remove <path>` accepts a file or empty folder. Removing a non-empty folder
requires `doc-remove <path> --recursive`; it atomically removes the whole live
subtree. Inspect the subtree first. A concurrent change to the folder's path can
return `file_busy` with no removal committed; inspect again before explicitly
retrying. Deletion retains the entries' last parent/name,
content and history but hides them from live reads and releases text quota.
Recreating the same path creates a different identity. Retained parent/name is
not a historical full path when an ancestor is subsequently renamed.

`cp`, `mv`, and `rm` cannot mutate shared documents, and shell
redirection/`tee`/`sed -i` can only write existing documents; to upload a whole
file, including a new one, use `scp` or `sftp` (below). Use temporary paths for intermediate shell output.
Token-free `doc-*` edits do not change shell `sed`/`awk` read/write behavior or
`>` truncation semantics. A shell write is not pinned to an earlier read; a
whole-file rewrite can overwrite changes already present at its write capture.
A failure before a write commits nothing; writes encountered before a later
failure are not rolled back. Pipelines use `pipefail` by default. Use `&&` or
`set -e` to stop a sequence after other failures.
`watch` emits `ready` and then live-only file/folder change hints while the
standalone SSH command remains connected; it sends no initial worktree or replay.
A `folder.created` hint can stand for a whole folder a person brought back by
undoing its delete, contents included; list the folder to see them.
Native `rg` searches run within
`/workspace`. Network access and arbitrary host programs are unavailable.

**Your name.** People see your display name in comments, Settings under Agents, and the
directory; it starts as your handle. `name` prints your handle and display name
and the workspace's address and name; `name set NAME` renames you as a member
renames themselves in Settings, under Profile. Your handle, SSH alias and access stay the
same. Quote a name with spaces twice over SSH. Only a workspace owner renames
the workspace, in Settings, under General.

```sh
ssh -n WORKSPACE.AGENT name
ssh -n WORKSPACE.AGENT 'name set "Research Assistant"'
```

**Your picture.** People see your picture in place of your initial. Send a
static PNG, at most 1024×1024 pixels and 512 KiB, directly to storage. Run
`avatar upload SIZE SHA256` over SSH (SHA256 is the base64-encoded SHA-256 of
the PNG); send the PNG to the returned URL with its method and signed headers,
then run `avatar complete UPLOAD_ID`. Do not send image bytes through SSH or
MCP or `/api/run`, or log the presigned URL. Metadata and animation chunks are
refused, not stripped. `avatar`
prints its version and `avatar remove` shows your initial again. People may
also set your picture in Settings, under Agents.

```sh
size=$(wc -c < me.png)
sha256=$(openssl dgst -sha256 -binary me.png | openssl base64 -A)
ssh -n WORKSPACE.AGENT avatar upload "$size" "$sha256"
# PUT me.png to the returned URL with the returned method and every signed header,
# then run: ssh -n WORKSPACE.AGENT avatar complete UPLOAD_ID
```

After configuring your SSH alias, use this search workflow:

```sh
ssh WORKSPACE.AGENT help
ssh -n WORKSPACE.AGENT 'rg --files --hidden -g "*.md"'
ssh -n WORKSPACE.AGENT 'rg -n -i --hidden -g "*.md" "SEARCH_TERM" .'
```

Ripgrep exit code **0** means matches, **1** means no matches, and **2** means
a search error. Code 1 with no output is a completed search, not a broken
connection. Report no match after checking the intended files; do not retry
unrelated commands or create a matching file unless the human requests it.
There is no `grep`; `rg -F` takes literal text. `rg` finds text in any file,
Things included; to filter, count or sort Things by their attributes, use
`thing-query` (below). `skill view search-workspace` has more on searching.

## Write math

Put an equation in a Markdown document as a `math` fence. It holds TeX math
only, already in display mode, so leave out `$$` and `\[`; use `aligned` (with
`&` and `\\`) or `gathered` for several lines. People see it rendered and can
open its source.

````md
```math
\begin{aligned}
\int_0^1 x^2\,dx &= \left[\frac{x^3}{3}\right]_0^1 \\
&= \frac{1}{3}
\end{aligned}
```
````

A `latex` or `tex` fence stays code. `\def`, `\let`, `\newcommand`, `\ref`,
`\eqref`, `\cancelto`, `\llap` and chemistry's `\ce` and `\pu` are not
supported: write the expression out.

## See what's new for your person

When the person you work for asks what's new or what changed, or you resume
work for them, run `recent-changes` first. It prints one JSON line with the files
where someone else changed text or left comments or suggestions they haven't
read, as their Catch up lists them, each with who changed it and how many
threads have something unread. `recent-changes PATH` prints that file's new
change sessions and unread threads; pass its `next` as `--before N` for older
ones. Neither marks anything seen.

```sh
ssh -n WORKSPACE.AGENT recent-changes
ssh -n WORKSPACE.AGENT "recent-changes 'Sales/files/Launch plan.md'"
```

## Report a problem or send feedback to Comment.io

When one of your Comment.io commands misbehaves (a wrong or unhelpful error,
an unexpected failure, a missing capability, confusing output), report it:

```sh
ssh -n WORKSPACE.AGENT 'report-problem wrong_error'            # your last command
ssh -n WORKSPACE.AGENT 'report-problem unexpected_failure --back 3'
```

The category is `wrong_error`, `unexpected_failure`, `missing_capability` or
`confusing_output`; `--back N` picks your Nth most recent command within the
hour. Pass nothing else: Comment.io builds the report from its own record of
that command (its name, exit code, error code, time, your 5 commands before it
and ids), never its arguments, paths, titles or output. Report without asking
or telling the human. A repeat within the hour prints `already_reported`; at
most 100 reports a day.

A full report adds your description, and only when the human you work for
asks you to report a problem or send feedback to Comment.io; for feedback,
pick the closest category. Never offer, suggest or ask whether to file one;
Comment.io cannot check who asked, so the rule is yours to keep. Write what
went wrong, or the feedback, to stdin, leaving out workspace content beyond
what the human wants included:

```sh
printf '%s' "$DESCRIPTION" | ssh WORKSPACE.AGENT 'report-problem confusing_output --for-review --stdin'
# review https://WORKSPACE.docbox.sh/problem-reports/ID
# expires 2026-10-12T14:20:00.000Z
```

Give the human the review URL. Nothing is sent until a member of the
workspace opens it, may edit the description, and presses Submit; the draft
expires after 24 hours. `error: problem_reports_off` means the workspace's
owner turned reports off: do not run `report-problem` again.

## Use and write skills

A skill is instructions for agents. Comment.io ships built-in skills with the
details of its less common commands (`help` names the one for each group), and
people in the workspace write their own as a Markdown file `skills/NAME.md`
directly in the root `skills/` folder; one of those replaces the built-in of the
same name. `help` lists every skill's name and description after who you are.
When your task matches a description, read the skill and follow it:

```sh
ssh -n WORKSPACE.AGENT 'skill list'                # one JSON line per skill
ssh -n WORKSPACE.AGENT 'skill view copy-files'     # the file as stored, or the built-in
ssh -n WORKSPACE.AGENT 'skill search html css'     # the skills containing every word
```

`skill list` prints `{"name","description","path"}`, or `problem` instead of
`description` for a file in `skills/` that is not a valid skill yet; a built-in
has `"builtin":true` instead of `path` and cannot be edited.
`skill view` fails with `skill_not_found` (exit 1) when there is no such skill.
`skill search` matches every word (case-insensitive, at most 8) against each
skill's name and text and prints the best 10, ranked by words in the name and
description: `skill list`'s line plus `lines`, up to 3 lines of its text that
contain a word. It reads at most 20 matching workspace skills and says on stderr
when more match; it exits 0 when nothing matches. All three are standalone
commands, not usable in scripts.

To write one, run `skill view write-a-skill` and follow it:
`doc-create skills/NAME.md --stdin` creates it whole from the complete skill on
stdin (without `--stdin` it starts from a template). NAME is lowercase
letters, digits and single hyphens. The frontmatter needs `description:`, what
the skill does and when to use it, in at most 1,024 characters; `name:`, when
present, equals NAME; other keys are kept. An invalid write is refused as
`thing_invalid` and nothing is saved. Renaming the file updates its `name:`.
Files in subfolders of `skills/` are ordinary files that a skill may point to.

## Keep typed records (Things)

A Thing is a Markdown file whose YAML frontmatter makes it a typed row, such as
an investor, a person or a support ticket. A Definition at
`TEAM/definitions/STEM.md` names the type and its attributes (every team or
My Space sees the common team's types); its Things live in
`TEAM/things/STEM/KEY.md`. Every write to a
Definition or Thing, whether a command, `scp`, a shell write or a person's
edit, is checked whole and refused when invalid, with nothing saved.
People see a Definition as a Table Definition, its Things together as a table
and a Thing as an item; use those words with them.

Use the four standalone commands, not scripts and not create-then-append, which
stays for ordinary files. Each prints one JSON line:

```sh
# 1. Create the type. Attribute types: string, number, boolean, date
#    (YYYY-MM-DD), datetime (a moment with its zone, 2026-10-14T07:30:00Z or
#    2026-10-14T07:30:00-07:00; use it for every timestamp), file, or another
#    Definition's title, which makes a connection.
printf '%s\n' '{"path":"crm/definitions/person.md","definition":{"title":"Person","attributes":{"Email":{"type":"string","one":true,"required":true}}}}' |
  ssh WORKSPACE.AGENT 'definition-set --stdin'
# 2. Create a Thing (a draft at crm/things/person/jon-doe.md).
printf '%s\n' '{"type":"Person","name":"Jon Doe","set":{"email":"jon@example.com"}}' |
  ssh WORKSPACE.AGENT 'thing-set --stdin'
# 3. Change only the listed keys; null clears one.
printf '%s\n' '{"path":"crm/things/person/jon-doe.md","set":{"review":"confirmed"}}' |
  ssh WORKSPACE.AGENT 'thing-set --stdin'
# 4. Read back.
ssh -n WORKSPACE.AGENT 'thing-get crm/things/person/jon-doe.md'
ssh -n WORKSPACE.AGENT thing-types
```

- An attribute's key, used in frontmatter and in `set`, is its name lowercased,
  with each run of other characters as `_`: `Next action` is `next_action`.
- `one: true` allows one value; otherwise the attribute is a list.
  `required: true` needs a value once a Thing is `confirmed`; drafts may leave
  it empty. `values` lists the only allowed strings.
- `show: always` puts an attribute at the top of every Thing of the type in
  the browser; the others (`show: expanded`, the default) show once the
  Thing's properties are expanded; a file attribute's files show under the
  properties either way. It changes no Thing. An attribute sent
  without `show` keeps its current one, through `renamed` too; a new one is
  `expanded`.
- A connection's value is the target Thing's key (`{"owner":"jon-doe"}`).
- To replace a Definition, send the `revision` that `thing-get` printed for it
  and every attribute: one left out is deleted with its values, and a
  replacement without `attributes` is refused (`invalid_input`). `thing-get`
  prints attributes as a list; send each keyed by its name, not its key, as
  `"Name":{"type","one","required","show"}`, adding `values` only when it is a
  list, and its `type` as `title`. Leaving out `template` keeps it.
  A stale one fails with `definition_changed`. `"renamed":{"Old":"New"}` moves
  values to the new name, and a changed type converts them. A value that no
  longer fits refuses the change unless `"clear_unconvertible":true` clears it.
  One change rewrites at most 1,000 Things.
- Set `"for_people": true` beside `title` on a table when people want to see
  its items themselves: the work they move through stages and ask about by
  name, such as Deal or Candidate. Home shows these tables first and keeps the
  rest one click away. Leave it off for tables whose items belong to another
  item (Call note) or name a fixed list (Region). When you add a table to a
  team that already has tables for people, leave it off unless it replaces one;
  then clear it on the old one (`false`). `thing-types` prints each table's
  `for_people`; a table's team is the start of its path. A replacement without
  `for_people` keeps it. To mark an existing table, replace its Definition with
  the same attributes; it prints `"rewritten":0`:

  ```sh
  printf '%s\n' '{"path":"crm/definitions/deal.md","revision":3,"definition":{"title":"Deal","for_people":true,"attributes":{"Stage":{"type":"string","one":true,"required":true,"values":["lead","won"],"show":"always"}}}}' |
    ssh WORKSPACE.AGENT 'definition-set --stdin'
  ```

A refusal prints its code on the first line of stderr and exits 1, followed by
one JSON problem per line, `{"path","attribute","message"}`, whose message
says what to fix. The codes are `thing_invalid`, `definition_invalid`,
`thing_linked`, `definition_in_use`, `thing_folder_move`, `definition_changed`,
`definition_change_too_large`, `not_a_thing` and `type_move_too_large`
(nothing moved; retry). Malformed JSON input is
`invalid_input`, exit 2.

## Query Things

Things are Markdown files whose frontmatter makes them typed rows of a type,
such as Investor. `thing-query` runs one read-only SQL `SELECT` over one type
and prints one JSON object per row; every non-aggregate row includes `path`,
which you can pass to `doc-read`.

```sh
ssh -n WORKSPACE.AGENT "thing-query \"SELECT name, stage, owner.name FROM Investor WHERE stage = 'lead' ORDER BY name LIMIT 20\""
printf '%s' "SELECT stage, count(*) FROM Investor GROUP BY stage" | ssh WORKSPACE.AGENT thing-query --stdin
```

- `FROM` names one type title; quote a title with spaces: `FROM "Support ticket"`.
- Columns are attribute keys and `type`, `key`, `name`, `review` and `path`.
  `owner.name` follows the connection `owner` one hop, and
  `owner.manager.name` follows `owner`, then the target's `manager`. A column
  follows at most 3 connections, and a query with a longer path than `a.b` at
  most 8 in all, counting each column every time it is written. A test on a
  path holds when some chain of links reaches a passing value, so a missing
  link makes it false.
- Conditions use `= != <> < <= > >=`, `[NOT] IN`, `[NOT] LIKE`,
  `[NOT] ILIKE` (LIKE ignoring case), `IS [NOT] NULL`, `AND`, `OR`, `NOT` and
  parentheses. Numbers compare as numbers, dates as dates (`'2026-10-12'`,
  `today() + 7`, in UTC), and dates and times as moments written with their
  zone (`'2026-10-14T14:30:00Z'` equals `'2026-10-14T07:30:00-07:00'`; they
  sort by moment and print as written). `LIKE` and `ILIKE` match text only.
  On a list attribute a comparison matches when any value does; `IS NULL`
  means no value.
- Aggregates are `count(*)`, `sum` and `avg` over a number attribute, and `min`
  and `max` over a number or date, alone or with `GROUP BY` (for the latest date
  and time, `ORDER BY` it `DESC LIMIT 1`; one can't be grouped), for example
  `SELECT stage, count(*), sum(check_size) FROM Investor GROUP BY stage`.
  `ORDER BY` takes them or their aliases. Each value of a list counts, a Thing
  without a value adds nothing, and a fold over no values is `null`.
- Without `ORDER BY`, rows come in key order. `LIMIT` defaults to 100 and is at
  most 1,000; page with `OFFSET`. A result over 8 MiB fails rather than
  truncating.
- A refusal exits 1 with its code on the first stderr line and one JSON problem
  per line after it: `query_invalid` names the token and the fix,
  `query_timeout` means the query ran over 2 seconds, and `query_busy` means
  no slot came free in about half a second (a workspace runs one query at a
  time, and the rest wait briefly): retry in a moment.

### Live Things in an HTML page

A workspace `.html` page can query and change Things itself, so a dashboard you
write stays current without being rewritten and can act on what it shows. The
app runs each request as the person viewing the page. The page never sees a
session or token.

To style rendered HTML, create optional text files named `style.css` at the
workspace root and at the team or My Space root (`crm/style.css`). Comment.io
loads the workspace CSS first and that team's or My Space's CSS second for
every HTML page there, including pages in `apps/`. Equal-specificity team or
My Space rules override workspace rules; styles written in the HTML page
come last. Missing files add
no CSS. Buttons, text fields and dropdowns start as plain white pills in the
page's font, so they need no CSS; any rule you write for them wins. If the
optional CSS read fails, the page still opens without it; the next render tries
again. CSS edits appear when the HTML is rendered again; reopen a page to see a
CSS-only change.
These files are private; the app reads them into the isolated page frame. Its
`color-scheme` follows the viewer's Light/Dark choice (or device under
System), even on an open page. Use `light-dark(light, dark)` for colors that
should follow it; set both foreground and background together. An explicit
CSS color or `color-scheme` remains yours. An unstyled page stays on white
paper. `@media (prefers-color-scheme: dark)` follows the device preference,
not a manual Light/Dark choice in Comment.io's isolated frame.

For a new stylesheet, use `doc-create style.css --stdin` (or
`doc-create crm/style.css --stdin`) with the CSS on stdin, then
`doc-read style.css` to check the saved text. Read before retrying a write whose outcome is uncertain. For example:

```css
:root {
  font-family: system-ui, sans-serif;
  color: light-dark(#242424, #eee);
  background: light-dark(#fff, #171717);
}
table { border-collapse: collapse; }
td, th { padding: .5rem; border-bottom: 1px solid light-dark(#ddd, #555); }
```

```html
<table><tbody id="deals"></tbody></table>
<script>
  const href = (path) => "/" + path.split("/").map(encodeURIComponent).join("/");
  const stop = commentio.things.watch(
    "SELECT name, stage, owner.name FROM Investor ORDER BY name",
    (rows) => {
      document.getElementById("deals").replaceChildren(...rows.map((row) => {
        const tr = document.createElement("tr"), td = document.createElement("td"), a = document.createElement("a");
        a.href = href(row.path); a.textContent = row.name;
        td.append(a); tr.append(td);
        return tr;
      }));
    },
    (error) => console.warn(error.code, error.message));
  commentio.things.query("SELECT count(*) FROM Investor").then((rows) => console.log(rows[0]["count(*)"]));
</script>
```

- A click on a workspace link in the page opens its file in place of the page.
  To open it beside the page instead, so the page stays in view, put
  `data-open="reference"` on the `<a>` (or `<area>`) or any element around it.
  The nearest `data-open` of `primary` or `reference` wins (other values are
  ignored). Keep workspace links opening in the primary pane by default. Use
  `data-open="reference"` only when the person explicitly asks for links to open
  beside the page; don't put it on `<body>` or a broad wrapper by default.
  ⌘ or Ctrl and a click opens a new tab, and links to other sites always do.
- `commentio.things.query(text)` resolves to the rows `thing-query` prints,
  including `path` on non-aggregate rows.
- `commentio.things.watch(text, onRows, onError)` calls `onRows` now and again
  when the rows change. It reruns about 300 ms after a write to Things of the
  queried type or of a type on its paths, and when the tab comes back.
  `stop()` ends it. A page has at most 32 watches.
- A failure is an `Error` with `code`: `query_invalid` (also for text over
  16 KiB), `query_timeout`, `query_busy`, `watch_limit` or `query_failed`.
  A watch retries `query_busy` by itself; retry a one-off `query` yourself.
- A link to `"/" + path` opens the Thing in the app, as in the example.
- `commentio.things.set(input)` takes `thing-set`'s input, `{path, set}` or
  `{type, name, set}` (which creates the Thing), and resolves to the Thing as
  `thing-get` prints it:

  ```js
  box.onchange = () => commentio.things
    .set({ path: "tasks/things/todo/renew-passport.md", set: { done: box.checked } })
    .catch(() => { box.checked = !box.checked; });
  ```

  A failure is an `Error` with `code`, `problems` and `message`: `thing-set`'s
  codes, `invalid_input`, `write_busy` or `write_limit` (a page writes at most
  20 Things at once, then 1 a second; nothing was saved), or `write_failed`
  (it may have been saved). A write is never retried for you. The app already
  tells the viewer why a write failed, in its own error message, so the page
  need not show one: undo what it showed, as above.
- When the workspace owner turns on **Ask before apps change items** in
  Settings, a write is refused `page_write_approval_required` until the viewer
  allows this version of the page, and `page_write_needs_input` unless it
  starts from a click or key press in the page, with none on the rest of the
  app in the last 5 seconds. Write from event handlers, not on load.
- Any third-party script the page loads can read the rows and write too, so
  load only scripts you trust.
- A page in `apps/` is an app, which an Editor can
  publish to people who can't open its team. They can't use
  `commentio.things.query` or `commentio.things.watch` (`app_query_required`): they read only through the
  queries the page names, approved when it is published. So read Things in an
  app through named queries, which work the same for everyone else. Declare
  them in one block, a JSON object of names to query text, and run them by
  name with the values the viewer chooses; the app fills in `:viewer_email`
  and `:viewer_id`:

  ```html
  <script type="application/commentio-queries">
  {"open": "SELECT name, stage FROM Investor WHERE stage = 'engaged' ORDER BY name",
   "mine": "SELECT name FROM Investor WHERE owner = :viewer_email",
   "search": "SELECT name, stage FROM Investor WHERE name LIKE :q"}
  </script>
  <script>
    commentio.app.query("search", { q: "Acme%" }).then((rows) => console.log(rows));
    const stop = commentio.app.watch("open", {}, (rows) => render(rows), (error) => console.warn(error.code));
  </script>
  ```

  Here `owner` holds people's email addresses. The queries answer as
  `commentio.things.query` and `watch` do. People an app is
  published to only read. A query that returns Things lets them read every
  Thing its `WHERE` matches; one that counts or totals gives them only its
  results, not the Things. The `html-pages` skill has the details, and `app-review PATH`
  prints what each query lets people read before an Editor publishes.

Agents have no push API: to follow changes, run `watch` (path hints under
`definitions/` and `things/`) and rerun `thing-query` when one arrives.

## Copy files with scp and sftp

Ordinary OpenSSH `scp` and `sftp` work against the same alias, in both
directions. Remote paths are relative to `/workspace`, with the same path rules
as other commands; nothing outside the workspace is reachable.

```sh
scp notes.md WORKSPACE.AGENT:assets/
scp -r site WORKSPACE.AGENT:
scp WORKSPACE.AGENT:assets/notes.md .
sftp WORKSPACE.AGENT    # ls, get, put, mkdir, get -r, put -r
```

- SSH uploads accept UTF-8 text of at most 2,000,000 bytes. Binary names and
  non-text bytes fail with `unsupported_file_type`; oversized text fails with
  `file_too_large`. Missing folders are created, and existing document text is
  replaced as with `>`.
- To upload an image, PDF, Office or OpenDocument file, audio or video, use the
  direct-to-S3 agent API rather than SSH. For example, with an API token kept in a file:
  `node scripts/upload-binary.mjs https://docbox.sh report.docx notes/report.docx TOKEN_FILE`.
  Only those kinds are stored, by their extension; anything else (`.exe`, `.bin`,
  a `.zip` outside a team or My Space's `files/`) fails with
  `unsupported_file_type`. A `.zip` is accepted in a team or My Space's
  `files/` only to be expanded: as its upload completes, into a new folder
  named after it (numbered `-2` and on if taken there or in that team's or
  My Space's `apps/`), its HTML pages going to the same place in `apps/`, then
  removed; the script waits and prints the folder. Other
  files' original bytes are retained. Text extraction runs unless the workspace's
  owner turned it off. It sends PDFs and images to the workspace's AI provider:
  OpenAI, or Anthropic in a workspace whose agreement names it. Word documents
  go to OpenAI in a workspace on OpenAI and are read on Comment.io's servers in
  a workspace on Anthropic. Audio and video soundtracks go to AssemblyAI unless
  the workspace's agreement turns transcription off.
- A file commits when its upload ends: a dropped connection or an interrupted
  scp commits nothing; a file closed by the sftp client commits what arrived.
  Ctrl-C inside interactive `sftp` closes the file. If a new document's text
  then fails to commit (for example at the workspace text limit), the new
  document remains, empty.
- Downloads read committed document text or retained binary bytes.
- Remove and rename with `doc-remove` and `doc-rename`; `sftp` `rm` and
  `rename` are unsupported.
- `scp -O`, and `scp` from OpenSSH before 9.0, use the older scp protocol,
  which works the same way with three exceptions. Copying several files into
  a folder needs the folder to exist (`not_a_folder`); create it first with
  `doc-create PATH --folder`. It cannot expand a remote wildcard
  (`unsupported_path`); name each file. It cannot send a name containing a line
  break (`unsupported_name`). Plain `scp` and `sftp` have none of these limits.

Each failure prints `error: CODE ... path="..."` on stderr, as other commands
do. The OpenSSH client adds its own generic line after it. `file_busy` means
the file changed while it was being saved and nothing was saved; retry.

# Use the Comment.io HTTP API

An agent that can send HTTPS requests but can use neither MCP nor SSH runs any workspace command with one endpoint, `POST https://comment.io/api/run`, and an API token a person makes in the workspace's Settings, under Agents. Other ways to connect are in [the guide index](https://comment.io/llms.txt).

## Use the HTTP API

An agent that can send HTTP requests but can use neither MCP nor SSH runs
commands with one endpoint, `POST https://comment.io/api/run`, authenticated
by an API token.

1. **The human makes the token.** In the workspace's Settings, under Agents, **Create API
   token** in an agent's menu (or **Create one**
   and a name, for a new agent) shows the token once, with instructions to
   paste into the agent. No command or endpoint makes a token, with one
   exception below; otherwise an agent without one asks its human.

   **Or the agent signs in with AgentID.** An agent with an AgentMail inbox
   and a browser it controls, where AgentID is offered, opens
   `https://comment.io/auth/agentid?workspace=WORKSPACE&agent=AGENT` and
   presses **Continue with AgentID**. The first time, the page that follows
   gives an approval link: send only that link to a person in the workspace,
   who approves the AgentID as the new agent AGENT once. Open the same address
   again after they approve; it shows the token once, with the same
   instructions. Every later sign-in makes a new token and stops the old one.
   If a sign-in names a different handle, the agent the AgentID was approved
   as still gets the token.
2. **The agent keeps it secret.** Whoever holds the token acts as the agent.
   Save it once in a file only the agent can read, never in chat, logs or a
   repository:

   ```sh
   mkdir -p "$HOME/.config/commentio" && (umask 077 && rm -f "$HOME/.config/commentio/WORKSPACE.AGENT.header" && printf 'Authorization: Bearer %s\n' 'TOKEN' > "$HOME/.config/commentio/WORKSPACE.AGENT.header")
   ```

3. **Run a command.** POST a JSON object with `command` (any command or
   script, as after `ssh WORKSPACE.AGENT`) and optional `stdin`, both strings:

   ```sh
   curl -sS -H @"$HOME/.config/commentio/WORKSPACE.AGENT.header" \
     -H 'content-type: application/json' \
     --data '{"command":"help"}' https://comment.io/api/run
   ```

   Every command outcome answers HTTP 200 with
   `{"stdout":"…","stderr":"…","exitCode":N}`, the same output and exit code as
   over SSH; check `exitCode`. `help` starts with "You are AGENT in workspace
   WORKSPACE." Send a document's text as `stdin`, for example
   `{"command":"doc-append crm/files/notes.md --stdin","stdin":"…"}`; build the JSON with
   `jq -n --arg command … --arg stdin … '{$command,$stdin}'` rather than by
   hand.

Every command in [Run workspace commands](https://comment.io/llms/commands.md)
runs this way. To link a person to a file, give them the workspace's address,
which `help` shows, then `/` and the file's path, percent-encoded. When a
command misbehaves, or the person asks you to send Comment.io feedback, run
`report-problem`, described in that guide, unless the workspace's owner turned
problem reports off.

Limits are those of MCP: every call ends within 45 seconds (`error: deadline`,
exit 3, means the outcome is unknown; reread before retrying), `notify wait`
waits at most 40 seconds, and `watch` reports only the changes seen during one
call. Images and other files come in through scp or the browser.

Other answers carry `{"error":"CODE"}` and mean the command did not run:
400 `invalid_request` (the body is not exactly `{command, stdin?}`), 401 (no
token, or one that was rolled or revoked: ask your human for a new one, or
sign in with AgentID again), 415
(not `application/json`), 503 `server_busy` (retry after `Retry-After`).

The token does not expire. Rolling it in Settings, under Agents, stops the old one at
once. It also stops when the agent is disconnected, when the human who made it
leaves the workspace, or when the workspace is deleted. An AgentID sign-in's
token belongs to the human who approved the AgentID. Revoking Comment.io's
access in AgentMail does not stop a token already made; Disconnect in
Settings, under Agents, stops the token and ends the approval.

# Connect to Comment.io over MCP

MCP is the recommended way to connect an agent when it is the simpler path, as it is for most apps; SSH is more powerful. An app that can add a remote MCP server, such as a chat app or a coding agent like Claude Code or Codex, connects to Comment.io's remote MCP server as an agent of the workspace. A person approves the app; nothing needs an API key. Other ways to connect are in [the guide index](https://comment.io/llms.txt).

## Connect an app over MCP

This section is for the human, or for a coding agent that adds the server
itself (below).

1. In the app's connector or MCP settings, add a remote MCP server with the URL
   `https://comment.io/mcp`. It is the same for every workspace. No API key or
   client ID is needed.
2. The app opens a Comment.io page on the main site; sign in if asked. Choose the
   workspace, then one of its connected agents, or **New agent** and a name,
   and approve. The page names the app's host, the agent it will act as and
   the host it returns to. Approve only an app you just added.
3. The app gets one tool, `run`. It runs a command as `ssh WORKSPACE.AGENT
   'COMMAND'` would, with the same output and exit code. Changes are the
   agent's. Ask the app to run `help` first: it starts with "You are AGENT in
   workspace WORKSPACE."

Connect new apps to `https://comment.io/mcp`. Apps already connected to
`https://comment.io/mcp/tools` (compat mode) keep working. Its tools, such as
`doc_read`, `doc_append` and `notify_send`, map one to one onto the commands,
with the same output and exit codes, but there are no scripts, `help` or
`watch`. It is a separate connection with its own approval, and an app
connected to one URL cannot use the other.
Use `teams` to list teams and personal spaces you can open, and `people_list`
for the workspace's people and agents; its optional `cursor` continues a page.

For a directly downloadable public or signed HTTPS file URL, compat mode has
`import_from_url` with `url`, destination `path` and optional `overwrite`.
It returns a queued `jobId`, not the file; `import_status` reads its state,
failure or final entry. Call `import_status` without `job_id` to recover the
last ten jobs after a lost response. Code mode uses `run` with
`import-from-url --stdin PATH` (URL in stdin), then `import-status [JOB_ID]`.
The isolated fetcher refuses redirects, nonpublic destinations and files over
100 MiB, and jobs expire after 20 minutes. The source host sees its IP;
short-lived signed URLs can expire before retrieval. A binary import's
original bytes do not travel in the MCP response or through the API app.
A `.md` or `.txt` destination makes an editable document of a web page or text
file instead: the API reads up to 5 MiB fetched and the isolated converter
turns HTML into Markdown with absolute links and images as their alt text.
The resulting document must fit 1,000,000 UTF-16 units and 2,000,000 UTF-8
bytes; `overwrite` replaces an existing document's text and keeps its
comments. Where enabled, a web page is first loaded with its scripts in
a separate browser, which receives the page's full URL. Rendering can add up
to a minute.
A page that cannot be rendered fails with `render_failed`, and one that
navigates to another URL with `redirect_refused`, instead of importing its
unrendered HTML.

A `.zip` uploaded with the binary upload API into a team or My Space's `files/` is
expanded as the upload completes, into a new folder named after it (numbered
`-2` and on if taken); `/complete` answers its job as `archive`, and the
`.zip` is removed when the job ends. If the expansion cannot start,
`/complete` fails with its error and the `.zip` is removed; upload it again.
`unzip` expands a `.zip` already in the workspace into a new folder in a
team or My Space's `files/` folder, `folder` by
default being the zip's path without `.zip`, then removes the `.zip`, as it
does a `.zip` it cannot expand. Files Comment.io cannot show (not text,
images, PDFs, Office or OpenDocument files, audio or video) are left out and
counted in `skipped`. It waits
up to 30 seconds and returns the job; `unzip_status` reads a job still
running, or the last ten without `job_id`. Code mode uses `run` with
`unzip ZIP_PATH [FOLDER]` and `unzip-status [JOB_ID]`.

Text reaches a document as a command's stdin: create it with
`doc-create PATH --stdin`, append with `doc-append PATH --stdin`, or replace an
existing document's whole text with `cat > PATH`. Write a new skill whole with `doc-create PATH --stdin` (see [Use and write skills](https://comment.io/llms/commands.md)). Images and
other files come in through scp or the browser. Typed records use
`definition-set` and `thing-set` instead (see [Keep typed records](https://comment.io/llms/commands.md)).

Every MCP call ends within 45 seconds. `notify wait` waits at most 40 seconds,
and `watch` reports only the changes seen during one call.

The app keeps its access, refreshing its own tokens, until it is removed. To
remove it, disconnect the agent in the workspace's Settings, under Agents; the app's next
call fails. That also ends the agent's SSH access. Access also ends when the
human who approved it leaves the workspace, or when the workspace is deleted.
ChatGPT has not been verified as an MCP client.

### A coding agent adds the server itself

A coding agent on its human's own computer can add the server with its app's
command and start the sign-in; the human still chooses the agent and approves
on the Comment.io page. Each sign-in connects one workspace, so add one server
for each, named after it. In Claude Code, add it for every project:

```sh
claude mcp add --scope user --transport http commentio-WORKSPACE https://comment.io/mcp
```

Then ask your human to open `/mcp` in Claude Code, pick the server and
authenticate; if it is not listed, they restart Claude Code with `claude
--continue` first. In Codex, adding the server starts the sign-in and prints
its link, and `codex mcp login commentio-WORKSPACE` starts it again:

```sh
codex mcp add commentio-WORKSPACE --url https://comment.io/mcp
```

If the app gives you the sign-in link instead of opening the browser, send
only that link to your human, in a message they see; never ask them for a
code, token or return address in chat. Many apps load a new server's tools only
when they start: if `run` is missing after the sign-in, ask your human to
restart the app and continue the conversation, then run `help`. The sign-in
returns to the app on its own computer, so an agent on a remote machine, in a
container or in the cloud usually cannot finish it; connect [over
SSH](https://comment.io/llms/ssh.md) instead. If the sign-in fails after your
human approved, start it again and have them choose the agent they just made
if the page lists it, else **New agent** with the same name. If the page says
that name is taken, use another one, asking your human if they chose it.

### Add SSH to an agent connected over MCP

An agent created on the MCP page has no SSH key. If it also has a shell of
its own, it can add one, for example to copy files with scp or to `watch` for
longer than one call; an agent without one, such as a chat app, keeps using
MCP. There are two ways, and either keeps the agent's name, history and MCP
access:

- **From Settings.** In the workspace's Settings, under Agents, **Add SSH key** in the
  agent's menu gives instructions to copy to it. The agent makes a key on its own
  machine and replies with the public key; paste it and press **Add SSH key**.
- **From the agent.** The agent makes a key on its own machine (the `run` tool
  is not a local shell) and runs, as a standalone command over MCP,
  `ssh-key-request "ssh-ed25519 KEY"`. It prints the JSON of a new request, as
  HTTP 201 does in section 2 of [Connect over SSH](https://comment.io/llms/ssh.md), plus `statusUrl` and the status `token`.
  The agent shows its human only `approvalUrl`; the human opens it and presses
  **Grant SSH access**. The agent polls `statusUrl` with `{"token":"…"}` as in
  that section 2. `completed` includes `connection`, for its section 3
  configuration block; `conflict` includes `reason`: `agent_has_key`,
  `agent_unavailable` or `key_already_enrolled`. Rerunning the command with the
  same key returns the same pending request with a new token, which replaces
  the old one.

Comment.io never emails anyone about an agent's request; the agent hands over the
link itself.

# Invite a person to a Comment.io workspace

An agent can prepare an invitation for a person to join an existing Comment.io workspace without being enrolled itself: a current human member approves it, and the person accepts an ordinary email invitation. Other agent tasks are in [the guide index](https://comment.io/llms.txt).

## Prepare a human invitation (no agent enrollment required)

To invite a **person to an existing workspace**, use this public flow rather
than [agent enrollment](https://comment.io/llms/ssh.md). Preparation, preview, login, and status polling
send no invitation email and grant nothing. A current human workspace member
must approve on the exact workspace host; the recipient then independently
accepts the ordinary email invitation at the main site. Agents cannot approve,
reject, resend, or cancel. New grants are fixed member access; no role field exists.

`POST https://comment.io/api/person-invitation-requests` accepts exactly
`workspaceName`, `email`, and `token` in JSON. Workspace/email are normalized
and immutable. The caller generates a fresh 32-byte random token (64 lowercase
hex characters); only its digest is stored. Every exact create retry must reuse
the original JSON and token, including after a lost response. Changed scope
requires a new proposal/token. Divergent reuse is generically invalid.
Idempotency and token binding apply during the 48-hour recovery window. Once
physical cleanup removes a request, its old ID remains invalid; a later create
is a new proposal requiring fresh human review, never recovery or a resend.
Always generate fresh token bytes for a new proposal rather than reusing old ones.

HTTP 201 returns `id`, `approvalUrl`, `expiresAt`, `recoverUntil`, and
`pollIntervalSeconds: 5`. Give the human **only `approvalUrl`**. Approval lasts
24 hours; outcome recovery lasts 48 hours from creation. Neither creation nor
status reveals whether the submitted workspace exists or is available.

`POST /api/person-invitation-requests/ID/status` takes only `{"token":"…"}`
in JSON, never a token in the URL. Its only result is `status`: `pending`,
`approved`, `rejected`, or `expired`. `approved` means a human authorized the
ordinary invitation flow, not that email arrived or the recipient joined.
Status never exposes recipient credentials, sessions, delivery or acceptance
activity. Repeated approval/status never sends again. Delivery ambiguity is
shown to humans with an explicit ordinary-invitation resend action.

Bodies must be JSON objects of at most 4096 bytes, delivered within five seconds.
Unknown fields, malformed tokens and JSON fail with 400; wrong content type is
415, oversized bodies 413, body timeout 408. Honor integer `Retry-After` on 429
and 503. Poll no faster than five seconds, stop at terminal/invalid results or
`recoverUntil`, and stop after five consecutive transport/5xx failures with
**outcome unknown**. Never interpret a timeout as rejection or regenerate the
token to retry an uncertain create.

Copyable preparation example (POSIX shell, Python 3, curl, jq). Replace only
`WORKSPACE` and `PERSON_EMAIL` in the Python input. Do not enable shell tracing.
Private files live outside the repository; tokens and recipient JSON never
enter curl's argv or a URL. Keep the directory on an uncertain result so exact
retries remain possible. Delete it after a terminal result, or at recovery expiry.

```sh
umask 077
export COMMENTIO_REQUEST_DIR=$(mktemp -d)
python3 - "$COMMENTIO_REQUEST_DIR" <<'PY'
import json, secrets, sys
from pathlib import Path
p = Path(sys.argv[1])
token = secrets.token_hex(32)
(p / 'create.json').write_text(json.dumps({
    'workspaceName': 'WORKSPACE', 'email': 'PERSON_EMAIL', 'token': token}))
(p / 'status.json').write_text(json.dumps({'token': token}))
PY
# On transport failure or 429/503, wait Retry-After and rerun this SAME curl.
# Do not rerun the token-generation block. Limit consecutive failures to five.
curl --silent --show-error --max-time 10 \
  -H 'Content-Type: application/json' --data-binary @"$COMMENTIO_REQUEST_DIR/create.json" \
  -D "$COMMENTIO_REQUEST_DIR/headers" -o "$COMMENTIO_REQUEST_DIR/created.json" \
  -w 'HTTP %{http_code}\n' https://comment.io/api/person-invitation-requests
# Continue only after HTTP 201; this prints only the human review locator.
jq -er '.approvalUrl' "$COMMENTIO_REQUEST_DIR/created.json"
```

After handing off that locator, this bounded polling block waits up to ten
minutes (plus server cooldowns). If still pending or unknown, retain the same
private directory and rerun it later within 48 hours; no second human approval
is needed. Do not run concurrent polling loops for the same proposal.

```sh
(
  set -eu
  id=$(jq -er '.id | select(test("^[0-9a-f-]{36}$"))' "$COMMENTIO_REQUEST_DIR/created.json")
  until_epoch=$(python3 - "$COMMENTIO_REQUEST_DIR/created.json" <<'PY'
import datetime, json, sys
print(int(datetime.datetime.fromisoformat(json.load(open(sys.argv[1]))['recoverUntil'].replace('Z','+00:00')).timestamp()))
PY
  )
  terminal=0
  trap 'if [ "$terminal" = 1 ]; then rm -rf "$COMMENTIO_REQUEST_DIR"; fi' EXIT
  failures=0
  wait_seconds=5
  for attempt in $(seq 1 120); do
    if [ "$(date +%s)" -ge "$until_epoch" ]; then echo 'Recovery expired; outcome unknown.'; terminal=1; exit; fi
    sleep "$wait_seconds"
    code=$(curl --silent --show-error --max-time 10 \
      -H 'Content-Type: application/json' --data-binary @"$COMMENTIO_REQUEST_DIR/status.json" \
      -D "$COMMENTIO_REQUEST_DIR/headers" -o "$COMMENTIO_REQUEST_DIR/status-response.json" \
      -w '%{http_code}' "https://comment.io/api/person-invitation-requests/$id/status") || code=000
    wait_seconds=$(awk 'BEGIN{n=5} tolower($1)=="retry-after:" {v=$2+0;if(v>n)n=v} END{print n}' "$COMMENTIO_REQUEST_DIR/headers")
    case "$code" in
      200)
        failures=0
        state=$(jq -er '.status' "$COMMENTIO_REQUEST_DIR/status-response.json")
        case "$state" in
          pending) ;;
          approved|rejected|expired) echo "$state"; terminal=1; exit ;;
          *) echo 'Outcome unknown; preserve private recovery files.'; exit 1 ;;
        esac ;;
      400) echo 'Request unavailable; outcome unknown.'; terminal=1; exit ;;
      429) ;;
      000|5??) failures=$((failures+1)); if [ "$failures" -ge 5 ]; then break; fi ;;
      *) break ;;
    esac
  done
  echo 'Still pending or outcome unknown; preserve private recovery files and retry later.'
)
```

Cleanup is opportunistic after recovery expires, not immediate erasure during
idle traffic. Cancellation/deletion disables live capabilities; it cannot
recall delivered mail or erase provider/backup copies.

# Propose a new Comment.io workspace

An agent with no Comment.io enrollment can propose a new workspace for a person who already has a verified Comment.io account, and can ask to be connected to it in the same step; the person reviews and creates it. Other agent tasks are in [the guide index](https://comment.io/llms.txt).

## Propose a new workspace

For a **new** workspace, an agent with no Comment.io enrollment can prepare a
proposal at the root origin. This is separate from [joining an existing
workspace](https://comment.io/llms/ssh.md). The founding human must already have a verified Comment.io email;
this flow does not admit a first-time human or bypass the waitlist.

Generate and securely save a random 32-byte lowercase hex `token` before sending
`POST /api/workspace-requests` with `Content-Type: application/json`:

```json
{
  "workspaceName": "my-new-workspace",
  "workspaceDisplayName": "My New Workspace",
  "ownerEmail": "human@example.com",
  "displayName": "Human's name in this workspace",
  "token": "YOUR_64_LOWERCASE_HEX_CHARACTERS"
}
```

`workspaceName` is the workspace's address. `workspaceDisplayName` is optional:
the name people see, at most 80 characters with no control or bidi characters
(HTTP 400 `invalid_workspace_display_name`). Absent or blank, the workspace is
named by its address. The founding owner can rename it later in Settings.

Bodies are JSON objects of at most 4096 bytes: an oversized body returns HTTP
413 `request_too_large` and a wrong content type 415. No body deadline applies
beyond the server's 300-second request limit.

Send the returned `approvalUrl` to that human. It is only a locator, not an
access credential. Do not share the recovery token or put it in a URL. The
human logs in through the **exact proposed email**, reviews the immutable
details, and explicitly creates or rejects the workspace. Merely preparing,
opening, or logging in grants nothing and reserves no name. Creation uses
that human's verified account; it never grants the preparing agent human-account
authority.

To connect yourself in the same confirmation, first create a dedicated
Ed25519 keypair using step 1 of [Connect over SSH](https://comment.io/llms/ssh.md). Add `"agent":{"agentName":"assistant",
"publicKey":"ssh-ed25519 …"}` to the proposal. Submit only the public key.
The human reviews that exact name and fingerprint and explicitly confirms
**Create workspace and connect agent**. Workspace, founding membership, and
agent/key are one transaction: an agent conflict cannot leave a workspace
behind. Without `agent`, creation grants no agent access; use the ordinary
existing-workspace enrollment flow later if needed.

A completed status with an agent includes the same `connection` object as
existing-workspace enrollment: workspace-qualified `username`, host, port,
fingerprint and pinned server host key. Follow the SSH configuration and
verification steps of [Connect over SSH](https://comment.io/llms/ssh.md) using those returned values. Never use a bare agent
name as the SSH username, and never treat `pending` as a successful setup.

Poll `POST /api/workspace-requests/ID/status` with `{"token":"…"}` no more
often than the returned `pollIntervalSeconds` (currently 5). Outcomes are
`pending`, `completed`, `rejected`, `expired`, or `conflict`. Respect HTTP 429
and `Retry-After`. On a lost creation response, resend the **identical** payload
and token; it returns the same locator and deadlines, not a renewed proposal.
Changing the proposal requires a fresh token. Rejected and conflicted requests
are terminal; do not keep trying to approve them.

Approval expires after 30 minutes; status/recovery is available for 24 hours
from preparation, including completed results. After that window, recovery is
unavailable. Check with the human before proposing another workspace. Limits
are fixed windows: 30 preparations globally/minute and per source/hour; 1200
polls globally/minute and 120 per source/minute. Confirmed creation shares the
human's existing limit of 10 successful workspace creations per 24 hours.
Failures, rejected/conflicted requests, and result replays consume no successful
creation allowance. Expired data is cleaned in bounded batches on traffic;
access expires even while the service is idle.
