# localize.work — sign in as an agent

localize.work manages an app's translations. As an agent you can sign up
the person you work for, create a project, upload the app's strings, add
translations, publish them, and connect the app.

Ask the person which email address to use. The approval link you give them
signs them in (or creates their account); there they choose the
organization you work in and what you may do, and see the code to read
back to you.

Before you run the steps below: in step 5, store the refresh response only
if it contains `identity.assertion` (as step 3 checks); on an error keep
the saved credentials and retry later.

You are an agent. This service allows you to register for an identity and exchange it for credentials.

Run these commands in order. **Don't print secret values and don't write your own scripts** — the commands below persist secrets and surface only non-secret fields. Commands are macOS (`curl`, `security`, `jq`); adapt as needed for Linux (`secret-tool`, reads stdin) or Windows (PowerShell `Set-Secret`/`Get-Secret`). Only `security` takes the secret on argv — `secret-tool`/`Set-Secret` don't, so don't carry its "rotate if exposed" caveat to them.

Set once:

```bash
ISSUER="https://adventurous-pearl-62.authkit.app"
SVC="${ISSUER#https://}"        # keychain service label (issuer host)
EMAIL="<user-email>"           # login_hint, and keychain account for email-based methods
```

## 1. Check for an existing registration — reuse before creating a new one

```bash
if   security find-generic-password -s "$SVC" -a "$EMAIL"  -w >/dev/null 2>&1; then ACCT="$EMAIL"
fi
# ACCT set -> skip to step 4 (Exchange). ACCT unset -> continue to step 2.
```

## 2. Register — pick the method that fits; capture into `$REG`, never print it

```bash
# service_auth — you have the user's email (claim ceremony required):
REG="$(curl -sS "$ISSUER/agent/identity" -H 'Content-Type: application/json' \
  -d "{\"type\":\"service_auth\",\"login_hint\":\"$EMAIL\"}")"
ACCT="$EMAIL"
# errors: invalid_request -> fix the body; invalid_login_hint -> fix EMAIL; service_auth_registration_disabled -> method not enabled for this environment.
```

**Don't persist `$REG` yet** — the service_auth response holds only a short-lived `claim.token`. Keep it in memory; persist after the claim verifies (step 3).

## 3. Claim ceremony — service_auth (required)

Mint an attempt and give the user its link. They sign in there and the page shows them a code; once they read it back to you, complete the claim with it.

```bash
CLAIM_TOKEN="$(printf '%s' "$REG" | jq -r .claim.token)"
ATT="$(curl -sS "$ISSUER/agent/identity/claim" -H 'Content-Type: application/json' \
  -d "{\"type\":\"service_auth\",\"claim_token\":\"$CLAIM_TOKEN\",\"login_hint\":\"$EMAIL\"}")"
# errors: invalid_claim_token -> restart at step 2; invalid_login_hint -> fix EMAIL; claim_expired | claim_revoked | already_claimed -> restart at step 2; auth_method_disabled -> method was disabled; too_many_attempts -> wait for a pending attempt to expire.

# give the user this link (non-secret); the code is shown to them on the page, not here:
printf '%s' "$ATT" | jq '{verification_uri:.attempt.verification_uri}'

# the user reads the code off that page and gives it to you; submit it with the claim token:
USER_CODE="<code the user read off the claim page>"
VER="$(curl -sS "$ISSUER/agent/identity/claim/complete" -H 'Content-Type: application/json' \
  -d "{\"claim_token\":\"$CLAIM_TOKEN\",\"user_code\":\"$USER_CODE\"}")"

# success returns the verified identity once — persist it; an error returns {code,message}:
printf '%s' "$VER" | jq -e .identity.assertion >/dev/null && security add-generic-password -U -s "$SVC" -a "$ACCT" -w "$VER"
# errors: claim_not_confirmed -> user hasn't finished on the page yet, wait and retry; invalid_user_code -> wrong code, ask the user again; user_code_expired -> re-run this step for a fresh link; claim_expired | already_claimed -> restart at step 2; claim_denied -> user denied the claim, restart at step 2; auth_method_disabled -> method was disabled; organization_selection_required | stale_organization_selection -> user must re-select an organization on the claim page.
```

## 4. Exchange the assertion for an access token

```bash
ASSERTION="$(security find-generic-password -s "$SVC" -a "$ACCT" -w | jq -r .identity.assertion)"
CRED="$(curl -sS "$ISSUER/oauth2/token" -H 'Content-Type: application/x-www-form-urlencoded' \
  -d grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \
  --data-urlencode "assertion=$ASSERTION")"
ACCESS_TOKEN="$(printf '%s' "$CRED" | jq -r .access_token)"
# errors: invalid_request -> assertion could not be decoded; invalid_grant -> assertion expired/revoked, restart at step 2; invalid_target -> resource URI not recognized; unsupported_grant_type -> use the grant above.
```

Send it as `Authorization: Bearer $ACCESS_TOKEN`. **Don't persist the access token** — it's short-lived (~5 minutes). When it expires, re-run this step from the stored assertion; when the assertion itself expires, refresh (step 5).

## 5. Refresh — when the stored assertion nears expiry

```bash
RT="$(security find-generic-password -s "$SVC" -a "$ACCT" -w | jq -r .identity.refresh_token.value)"
REG="$(curl -sS "$ISSUER/agent/identity" -H 'Content-Type: application/json' \
  -d "{\"type\":\"refresh\",\"refresh_token\":\"$RT\"}")"
printf '%s' "$REG" | jq -e .identity.assertion >/dev/null && security add-generic-password -U -s "$SVC" -a "$ACCT" -w "$REG"   # rotates the refresh token; saved only on success
# errors: invalid_refresh_token -> restart at step 2.
```

Then re-run step 4 with the fresh assertion.

## 6. Revoke — when the registration is no longer needed

```bash
RT="$(security find-generic-password -s "$SVC" -a "$ACCT" -w | jq -r .identity.refresh_token.value)"
curl -fsS "$ISSUER/oauth2/revoke" -H 'Content-Type: application/x-www-form-urlencoded' \
  -d token_type_hint=refresh_token --data-urlencode "token=$RT" \
  && security delete-generic-password -s "$SVC" -a "$ACCT" >/dev/null   # forget it only once the server said 200
# 200 means the registration is gone (also returned for an unknown or already-revoked token). 5xx -> nothing is deleted; back off and retry.
```

This revokes the whole registration — the assertion, the refresh token, and every access token minted from it — and can't be undone; restart at step 2 for a new identity. To revoke a single access token and keep the registration, send it with `token_type_hint=access_token`.

## Any request

`5xx` -> back off and retry the same request. `rate_limit_exceeded` -> wait `retry_after` seconds. A `4xx` not listed above -> fix per the response body; don't replay.

## 7. Use localize.work

API origin: `https://api.localize.work`. Send `Authorization: Bearer $ACCESS_TOKEN` (step 4).
The token lasts about five minutes: when a request answers 401, mint a new
one from the stored assertion (step 4) and retry.

You work for one organization: the one the person picked on the approval
page. Start by reading it:

```bash
curl -sS "https://api.localize.work/v1/account" -H "Authorization: Bearer $ACCESS_TOKEN"
```

Check that its `organization` is the one the person wants this work in. A
registration you saved earlier (step 1) may have been approved for another
one. If it is not the right organization, write nothing: register again
(step 2) so the person can approve you for the right organization. Keep each
organization's registration under its own credential-store account: on a
later run, look for `$EMAIL#<organization>` before step 1's `$EMAIL` (if it
is there, set `ACCT` to it and go to step 4), and whenever you run step 2
for an organization other than the one saved under `$EMAIL` — including a
restart at step 2 after a refused assertion or refresh token — set
`ACCT="$EMAIL#<organization>"` right after step 2, so step 3 does not
overwrite another organization's registration; use that `ACCT` for steps
4–6.

### Choose the project

List the organization's projects first:

```bash
curl -sS "https://api.localize.work/v1/projects" -H "Authorization: Bearer $ACCESS_TOKEN"
```

While the answer's `nextCursor` is not null, read the next page with
`?cursor=<nextCursor>`. If one of the projects is already this app's, work
in it. Only when none is, create one:

```bash
curl -sS -X POST "https://api.localize.work/v1/projects" -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"name":"My app","sourceLocale":"en","locales":["de","fr"]}'
```

To add or remove languages later, send `PATCH /v1/project` with the full
list, `{"locales":["de","fr","es"]}`. The source language is always kept,
and a removed language's text is hidden, not deleted.

### Work in a project

Every project route takes the project's id or slug in the
`localize-project` header. The full list of routes is at
https://localize.work/docs/api/rest/.

- Upload the app's strings: `POST /v1/imports` with
  `{"mode":"apply","files":[{"locale":"en","namespace":"common","contentJson":"<the file>"}]}`.
  Use the app's own file and namespace names.
- Wait for each import to finish before the next import or a publish. The
  answer's `jobStatus` says where it stands:
  - `completed` (HTTP 200): done.
  - `queued` or `running` (HTTP 202, with an `importId`): poll
    `GET /v1/imports/{importId}` every few seconds while its `status` is
    `queued` or `running`.
  - `failed`, in the first answer or while polling: read its `error`, then
    `POST /v1/imports/{importId}/resume` or `/cancel`. Until then the
    project takes no other import and cannot be published (409).
  - `cancelled`: someone stopped it. What it wrote so far is kept; import
    the rest again.
- Translate the text yourself, with the context localize.work's own AI
  translation uses (see Translate below), and import it with
  `"status":"translated"`, never `"reviewed"`: a reviewed import would
  replace text that a person approved after you read it.
  If `/v1/account` lists `translations:review` among your scopes, approve
  your text key by key afterwards (below); otherwise a person approves it in
  the editor.
- Check the import's `totals.skipped` and its files' warnings. In a
  language other than the source, an import as `"translated"` never
  replaces text that is already approved; it skips it. (A source file does
  replace the source text stored before the import started.) To change such
  a string, read it with
  `GET /v1/keys?namespace=<namespace>&locale=<locale>&q=<key name>` (for a
  name outside 3–500 characters leave out `q`, page with `cursor` and match
  the exact name) and send
  `PUT /v1/keys/{keyId}/translations/{locale}` with the new text — `value`
  for a plain key, or `values` keyed by plural form when the key's
  `isPlural` is true — and `expectedUpdatedAt` mapping each `pluralForm` you
  replace (`""` for a plain key) to the `updatedAt` you read; it then waits
  for approval.
- Publish only approved text: a release leaves out unapproved text and keeps
  what was live before, and an import leaves a string's status alone when its
  text is unchanged. So before publishing, list
  `GET /v1/keys?locale=<locale>&status=translated` and `&status=draft` for
  each language, following `cursor` until `nextCursor` is null (on a 422
  `response_too_large`, use a smaller `limit`, or pass the error's
  `details.skipCursor` as `cursor` and leave that key to the person): your
  keys there are not approved yet. With `translations:review`, approve each
  one whose text is yours with
  `POST /v1/keys/{keyId}/translations/{locale}/approve` and
  `{"expectedUpdatedAt":{"<pluralForm>":"<updatedAt>",…}}` mapping every
  `pluralForm` of that language in the listing (`""` for a plain key), so
  only the text you read is approved; on a 409, read it again and check it
  before approving. Approvals count as saves, at most about 120 a minute, and
  every request counts toward a similar limit: on a 429, wait the seconds in
  its `Retry-After` header (or `details.retryAfterSeconds`) and continue.
  Otherwise ask the person to approve them in the editor and check again.
- Publish, if `/v1/account` lists `releases:publish` among your scopes:
  `POST /v1/releases` with
  `{"confirmProjectSlug":"<slug>","requestId":"<a new UUID>"}`. While the
  answer says `"publicationStatus":"pending"`, send the same request again,
  with the same `requestId`, after a few seconds; `active` or `superseded`
  means it is finished. Without that scope, first note the newest release's
  `createdAt` in `GET /v1/releases` (if any), then ask the person to publish
  in the editor, and check `GET /v1/releases` until a release created after it
  is active (an older one becoming active is a rollback, not your release).
- Before connecting the app, check what is live: read
  `https://cdn.localize.work/<slug>/latest.json` for its `version`, then
  `https://cdn.localize.work/<slug>/<version>/<locale>/<namespace>.json`, and look for a few
  of your new strings. If they are missing, the live release does not have
  them yet: publish again (or ask the person to) once they are approved.

### Translate

1. For each target language, read
   `GET /v1/translation-context?locale=<locale>` and follow `nextCursor`
   until it is null. Each page lists keys that still need translating, each
   with its source text, description, the plural forms to write (`forms`;
   `""` is a plain key), the glossary terms that occur in its source and
   similar approved translations (`references`), plus the language's
   `styleGuide` and the `instructions` to follow. Leave out text in
   `current` that is approved (`"status":"reviewed"`), not empty and not
   outdated; an empty form still needs text, except in a regional variant
   (`variant` is true), where an empty form shows the base text (or is an
   override's removal waiting for approval): leave it empty unless you were
   asked to override it. Skip a key whose `source` is empty, and in a
   regional variant write only the forms that should read differently from
   the base language (add
   `&missing=true` to list keys without an override there). To drop an
   override so the base text shows again, send `""` for that form with the
   PUT in step 4 (an import skips empty text in a variant). The old override
   stays live until the removal is approved: with `translations:review`,
   send that PUT as reviewed; otherwise it waits in the review queue.
2. Write each namespace as an i18next JSON file of that language: each key's
   `name` with its text, and for a plural key one entry per form,
   `<name>_<form>` (for example `items_one` and `items_other`). A file
   reads a plain key whose name ends in `_zero`, `_one`, `_two`, `_few`,
   `_many` or `_other` as a plural form of another key, and a plural key
   whose name ends in `_ordinal` as plain keys: set such a key's text with
   `PUT /v1/keys/{keyId}/translations/{locale}` instead (`values` keyed by
   form for a plural key).
3. Check each file before writing it: `POST /v1/imports` with
   `"mode":"dry-run"` and the same files. Correct every entry whose warning
   says its placeholders differ from the source, and run the dry run again
   until it reports no such warning. If the answer has
   `"warningsTruncated":true`, its list is incomplete: dry-run fewer keys at
   a time until it is false. Then import with `"mode":"apply"`.
4. For a single string, send `PUT /v1/keys/{keyId}/translations/{locale}`
   with `"status":"translated"`; without it, new text is saved as a draft
   that no reviewer is asked to approve. Send `"status":"reviewed"` only
   where step 1 or 5 says so. Pass
   `expectedUpdatedAt` with a token for every form in `values`: its
   `updatedAt` in `current`, or `null` for a form not in `current`; on a
   409, read the key again. With
   `"status":"reviewed"`, `values` must name every form of the key: resend
   approved forms unchanged from `current` (an outdated one only after
   checking it against its new source text), and in a regional variant send
   `""` for a form that keeps the base text. It refuses text whose
   placeholders differ from the source.
5. Then read `GET /v1/translation-context?locale=<locale>&outdated=true`
   the same way. It also lists approved text whose source text changed after
   it was approved. Bring each one in line with its new source text with the
   PUT in step 4 (an import skips approved text). If every form
   still fits its new source text and `/v1/account` lists
   `translations:review`, approve it again instead, with
   `expectedUpdatedAt` for every form as above (in a regional variant,
   send the reviewed PUT of step 4); without that scope, leave it for a
   person to approve.
   Approving covers every form of the key in that language, so do it only
   when each form is yours or approved text you checked against the new
   source.

### Connect the app

- Load published translations at runtime with the i18next backend
  `@localize-work/i18next-backend` (https://localize.work/docs/sdk/i18next-backend/), or
- keep files in the repository with the CLI `@localize-work/cli`
  (https://localize.work/docs/cli/). Create a key for it with
  `POST /v1/api-keys` (`localize-project` header,
  body `{"kind":"secret","name":"CLI","scopes":["project:read","translations:read","keys:write","translations:write"]}`)
  and pass it as `LOCALIZE_API_KEY`. Store it as a secret; it is shown once.
  A key you create works only while you have access: if the person revokes
  you, it stops. Tell them so; for a key that must outlive you (CI), they
  create one themselves under Project settings → API keys.

### MCP

The same access token works with the MCP server at `https://api.localize.work/mcp`
(Streamable HTTP). Its project tools take a `project` argument (id or
slug); call `get_account` first. To translate, read
`get_translation_context`, write with `import_translations` (a
`dry-run` first) or `set_translation` as `translated`, and approve with
`approve_translation` and `expectedUpdatedAt`.
