> For the complete documentation index, see [llms.txt](https://nytshift.gitbook.io/nytshift-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nytshift.gitbook.io/nytshift-docs/agents-identity-and-data/agent-automation.md).

# Agent Pro policy-bound automation

## Capability boundary

Agent Pro automation can replace the operator's per-order click only on Hyperliquid testnet. It does not give an agent a wallet key, signer token, cancellation right, retry loop, mainnet scope or policy-editing authority.

The operator creates a revocable, maximum-24-hour policy for one active Agent Pro credential, one exact testnet account and one client-held P-256 public key. Every order must remain inside the credential mandate, the stricter automation policy, fresh live venue/account evidence, AEGIS, the configured fill-only NIGHTSHIFT builder fee and an explicit current-leg total-fee ceiling. NIGHTSHIFT makes at most one signer submission for an automation request ID. After that claim, every replay is reconciliation-only against the retained CLOID.

The machine-readable client contract is `packages/contracts/generated/nightshift-agent-automation-api-v2.openapi.json`. The isolated signer's additive policy-bound DTO is `POST /v3/automation/orders`; clients cannot call that loopback service directly.

## Prerequisites

1. Provision the additive signed `nsl_v2` Agent Pro automation entitlement using [`agent-pro-entitlements.md`](/nytshift-docs/agents-identity-and-data/agent-pro-entitlements.md). A proposal-only `nsl_v1` license cannot create a policy or submit an automation request.
2. Issue a normal Agent Pro credential whose symbols, stances, proposal notional and lifetime cover the intended policy. The token is still displayed once and remains secret.
3. Configure the isolated Hyperliquid signer for testnet, the exact lowercase account and builder scope, testnet eligibility, the symbol allowlist and an inactive execution kill switch. Mainnet is rejected even if another runtime flag is set.
4. Generate a P-256 key pair in the agent's own secret manager or hardware-backed keystore. Give NIGHTSHIFT only the public JWK fields `kty`, `crv`, `x` and `y`. Never paste the private key into Terminal, source, `.env`, `config.json`, browser storage, logs, analytics or a prompt.

## Generate a local client identity

The bundled Node client removes the need to implement DPoP by hand. Store its identity outside the repository. These commands refuse an existing file, symlinked path or repository path and never print private key material:

```powershell
$private = "$env:USERPROFILE\.nightshift-agent\automation-private.pem"
$public = "$env:USERPROFILE\.nightshift-agent\automation-public.json"
pnpm agent-automation:keygen -- --private-key $private --public-jwk $public
Get-Content $public
```

Paste only the four public JWK fields into the policy form. Keep the private PEM in the automation process's secret boundary. On Windows, also restrict the containing directory with the account's normal ACL controls; POSIX mode bits alone are not a Windows ACL.

## Create a policy

Unlock Terminal **Safety settings**, then use **Agent Pro automation** to choose the active credential and enter:

* exact account, symbols and buy/sell sides;
* entry and reduce-only permissions;
* per-order and UTC-day notional caps;
* leverage, daily-loss, drawdown, slippage, builder-fee and reviewed-total-fee caps;
* hourly/day order limits and an expiry from 15 minutes through 24 hours;
* the agent's public P-256 JWK.

Policy creation requires the operator session, same-origin CSRF and JSON. It rejects `mainnet`, an expired/revoked credential, a scope wider than the credential mandate, a weak/invalid key, or an expiry beyond the credential. The returned projection includes a JWK thumbprint and policy digest but not the JWK coordinates.

## Authenticate each agent request

Use both headers:

```
Authorization: DPoP <one-time-displayed Agent Pro token>
DPoP: <fresh ES256 proof JWT>
Content-Type: application/json
```

The current local profile intentionally accepts one exact RFC 9449-style proof shape:

* protected header: exactly `alg: ES256`, `typ: dpop+jwt`, and the registered public `jwk`;
* payload: exactly `ath`, `htm`, `htu`, `iat` and `jti`;
* `ath`: base64url SHA-256 of the ASCII access token;
* `htm`: the uppercase HTTP method;
* `htu`: exact `scheme://host/path`, without query or fragment;
* `iat`: current whole Unix seconds, no more than five minutes old or five seconds in the future;
* `jti`: a new 8-200 character value matching `[A-Za-z0-9._~-]+` for every HTTP request;
* signature: P-256 SHA-256 using the 64-byte IEEE-P1363 `r || s` encoding.

NIGHTSHIFT validates the public-key thumbprint, access-token hash, method, URI, age and signature, then durably consumes the proof ID. A `jti` replay fails even if the earlier business request failed. Generate a new proof for every submit or status request; never generate a new automation request ID merely to bypass an unknown result.

## Submit one bounded order

`POST /api/agent/v2/automation` accepts only schema version `2` and an exact limit order. The request contains a fresh `automationRequestId`, the operator-created `policyId`, a current `requestedAtMs`, a strict `TradeProposal`, and exact-decimal order fields. Proposal symbol/stance/entry/stop/size must cover the exact order, and the request must occur inside proposal validity.

After valid credential and DPoP authentication, every new request ID consumes one unit from the signed UTC-month automation allowance in the same atomic write that records policy authorization or rejection. An exact retained replay does not consume a second unit, and GET status/reconciliation is not charged. Overage is retained as `AUTOMATION_ENTITLEMENT_MONTHLY_LIMIT`, returns without a signer attempt and still counts as an attempted automation call. Never rotate IDs to evade a quota or ambiguous outcome.

An authorized request is not blindly forwarded. NIGHTSHIFT deterministically derives the intent ID and CLOID, atomically reserves policy quota/notional, re-reads the testnet signer, market metadata, book, account, portfolio, fees, builder approval and account mode, then runs AEGIS with the stricter policy limits. The conservative current-leg fee model includes the live account rate, configured builder fee and exact HIP-3 deployer scale/growth mode without assuming referral or aligned-quote discounts. It rejects an excess before claiming the signer, then rechecks the same exact limit during the atomic signer claim. It submits the policy digest and DPoP thumbprint to the signer only after every check passes.

The total-fee ceiling is not a Hyperliquid fill-time guarantee. The venue does not embed a protocol-fee maximum in a resting order, so a GTC fill can occur after the account or HIP-3 fee state changes. A later protective-child fill has its own fee and is outside the parent's reviewed current leg.

Treat the response states as follows:

* `accepted`: signer accepted the one order request; continue status/reconciliation until venue finality.
* `rejected`: do not retry the same economic action under a new ID; fix the policy, input or live risk condition deliberately.
* `unknown`: never submit again. Poll the retained request ID so NIGHTSHIFT reconciles only its deterministic CLOID.
* `authorized` with a transient pre-signer failure: the request remains reserved; use the same body/request ID and a new DPoP proof. NIGHTSHIFT may repeat reads, but cannot make more than one signer attempt.

`GET /api/agent/v2/automation/{automationRequestId}` requires a new DPoP proof for that exact GET URI and returns only the calling agent's action. It cannot cancel or change the order.

### Use the bundled CLI

Prepare an absolute-path JSON file that passes `AgentAutomationOrderRequestSchema`. Set the token only in the automation process environment—never place it in a command argument, URL, request file, repository, shell profile or NIGHTSHIFT web configuration:

```powershell
$env:NIGHTSHIFT_AGENT_TOKEN = '<one-time-displayed Agent Pro token>'
$request = 'C:\absolute\private\automation-request.json'
pnpm agent-automation:submit -- --private-key $private --request $request
pnpm agent-automation:status -- --private-key $private --request-id '<same automationRequestId>'
Remove-Item Env:NIGHTSHIFT_AGENT_TOKEN
```

The optional `--base-url` and `NIGHTSHIFT_AGENT_BASE_URL` accept only `http://127.0.0.1:<port>`; the default is `http://127.0.0.1:3000`. The client refuses redirects, cookies, remote hosts, unbounded bodies and malformed responses. It generates a fresh DPoP JTI per call and reports fixed error codes without server detail. There is intentionally no `cancel` command and no automatic retry loop. On `unknown`, timeout or network failure, use `status` with the same request ID; do not submit a replacement economic action.

## Revoke and stop

* **Revoke** stops one policy before another proof or signer claim can pass.
* **Stop all automation** revokes every active policy in one durable operator mutation.
* `EXECUTION_KILL_SWITCH=true` remains an independent execution stop.
* Revoking the underlying Agent Pro credential also makes authentication fail.
* Stopping the isolated signer prevents submission while preserving action/CLOID evidence for reconciliation.

After suspected token or client-key compromise, revoke the policy and credential, stop the agent, preserve both checkpoints, and inspect fixed-code events. Do not delete a store to simulate revocation.

## Health, backup and recovery

`/api/health` exposes only automation state, retention/capacity settings, aggregate active/retained counts, commercial entitlement state and the current attempt/limit. It never returns a token, license/subject ID, public-key coordinates, policy body, order body, account, CLOID or path. After operator unlock, **Copy automation usage** exports the private aggregate statement from `/api/automations/usage`. Invalid automation configuration makes health unsafe.

The atomic checkpoint is `%USERPROFILE%\.nightshift\data\agent-automation-v1.json` on Windows and `~/.nightshift/data/agent-automation-v1.json` elsewhere. Store schema v3 adds the explicit total-fee ceiling to schema-v2 aggregate commercial usage, policy public keys, digests, bounded action/audit state and consumed proof hashes; it stores no license token, agent token, order body or private key. Strict schema-v1/v2 checkpoints migrate without invented historical usage. Because they never recorded a total-fee ceiling, their policies are assigned the old builder cap conservatively, re-digested and revoked during migration. Create a new explicit policy before resuming automation. The normal verified backup includes this checkpoint. Stop the supervisor before restore:

```powershell
pnpm backup:create
pnpm backup:list
pnpm backup:verify -- <backup-id>
pnpm local:stop
pnpm backup:restore -- <backup-id>
pnpm local:start
pnpm local:health
```

Restoring an older checkpoint may restore an older revocation view, so keep the execution kill switch active, inspect policies, and use **Stop all automation** before allowing execution again.

## Deployment rule

The reviewed deployment is loopback-only HTTP with a separate loopback signer. Do not expose these endpoints through Cloudflare, a tunnel, port forwarding or a public reverse proxy. A hosted automation product requires reviewed TLS, centralized entitlement/revocation, managed sender-constrained credentials, abuse controls, jurisdiction/compliance decisions, monitoring and independent emergency stops before it may be called production mainnet automation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://nytshift.gitbook.io/nytshift-docs/agents-identity-and-data/agent-automation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
