# Artificial Mind Engine (AME) B2B API Integration Manual (EN)

> **Version:** `API 1.2.0 / Kernel 4.5.1` (`OpenAPI 3.1`, 100% backward-compatible with `v1.1.0`) · **Production SaaS:** `https://artificialmind.me/ame-api` · **Keyless Sandbox:** `https://artificialmind.me/ame-demo` · **Interactive Web Manual:** [`docs/api-manual.html`](./api-manual.html) · **Korean Manual:** [`API_MANUAL_KO.md`](./API_MANUAL_KO.md)

AME keeps conversation state for each Mind. The API supports memory deletion and returns public telemetry.

In Mode B, the application sends its LLM key only to the provider. AME prepares the prompt before the stream and settles the completed reply afterward.

---

## 1. Mode B (Zero-Key) Architecture Flow

![AME B2B Mode B (Zero-Key) Architecture Flow](./charts/ame_mode_b_api_flow_en.svg)

### 3-Step Execution Loop

1. Call `/prepare` with `userInput`. The result contains messages, `systemPrompt`, cache hints and a `turnTicketId`.
2. Stream from the provider directly to your application. AME is not in the streaming path.
3. Submit the complete nonempty reply, ticket and reported token usage to `/settle`. **Wait for settlement before preparing the next turn of the same Mind.** A `409 ticket_revision_stale` requires a fresh prepare and new completion; do not attach the old reply to a new ticket.

---

## 2. Environments, Authentication, Idempotency & Rate Limits

| Environment | Base URL | Purpose | Auth |
| :--- | :--- | :--- | :--- |
| **Production B2B SaaS** | `https://artificialmind.me/ame-api` | Live Mode B / Sealed Kernel (`v4.5.1`) | `X-AME-API-Key` or `Authorization: Bearer` |
| **Hosted sandbox** | `https://artificialmind.me/ame-demo` | Shared demo; do not enter personal data | Public |
| **Local Contract Sandbox** | `http://127.0.0.1:8090` | Local `npm run sandbox` CI & integration | Optional `AME_API_KEY` |

The updated sandbox console sends a random `X-AME-Visitor-Token` per browser. For sandbox scripts, configure `visitorToken` (TS) or `visitor_token` (Python) with a random UUID and keep it for later calls. Without it the list is empty; unaffiliated Minds cannot be opened or deleted. `GET /` serves HTML in the sandbox. Mock replies and cache estimates are illustrative.

### Supported Auth Headers

```http
X-AME-API-Key: <YOUR_AME_API_KEY>
```

or standard Bearer authentication:

```http
Authorization: Bearer <YOUR_AME_API_KEY>
```

### Idempotency (`Idempotency-Key`) & Rate-Limit Headers

- Use one `Idempotency-Key` (up to 255 characters) per logical POST to `/v1/minds`, `/prepare`, `/settle`, `/turn`, `/idle-tick`, `/connectors/{connectorId}/revoke`, or `/simulate-batch`. Retry the same body with the same key. A different body gets `409 idempotency_key_reuse`.
- Replay is not guaranteed indefinitely or after deletion. A replayed response includes `X-Idempotent-Replay: true`.
- When the per-minute limit is enabled, inspect `X-RateLimit-Limit` and `X-RateLimit-Remaining`. Wait at least `Retry-After` seconds when that header is present. Batch-concurrency and quota errors need not include a delay.
- JSON body limit: 1 MiB (1,048,576 bytes). `userInput`, `rawReply` and `backstory`: 32,000 UTF-16 code units each. Labels (including model, speaker, persona name/role and tags): 256. Up to 32 tags, voice examples, traits or custom fields; each voice example allows 2,000 code units. Provider order: 16 entries; LLM key: 8,192; base URL: 2,048.
- `eventTimestampIso` and `occurredAt` require a full datetime with `Z` or an explicit offset, from the Unix epoch through 366 days after the current time. Omit the field to use the Mind clock.

---

SDKs retry transient failures only for GET, DELETE, or POST with a nonblank idempotency key. The default request timeout is 180 seconds; configure `timeoutMs` / `timeout`. The default server-delay cap is 60 seconds (`maxRetryAfterMs` / `max_retry_after`). A longer server delay returns the error without retrying early.

## 3. Endpoint reference

| Method & Path | Auth | Purpose |
| :--- | :---: | :--- |
| `GET /` | Public | Service, version and probe paths |
| `GET /v1/health` | Public | Gateway health, runtime mode (`sealed-kernel` / `sandbox-contract`), and version (`4.5.1`) |
| `GET /v1/livez` | Public | Lightweight liveness probe (`{ ok: true, status: "alive" }`) |
| `GET /v1/readyz` | Public | Readiness, storage and process-lifetime `persistFailures` / `readFailures` |
| `GET /v1/usage` | Required | Tenant Mind, turn and token counts (Mode B tokens are caller-reported) |
| `GET /v1/minds` | Required | Paginated list; telemetry is omitted when the stored snapshot lacks measurements |
| `POST /v1/minds` | Required | Create a Mind within the configured tenant quota (`domain`: `game_npc`, `companion_chat`, `counseling_coach`, `personal_agent`, `custom`) |
| `GET /v1/minds/{mindId}` | Required | Retrieve Mind metadata and `SafeTelemetry` |
| `DELETE /v1/minds/{mindId}` | Required | Delete the Mind and return a scoped receipt |
| `POST /v1/minds/{mindId}/prepare` | Required | **Mode B Step 1**: Compute prefix-stable prompt package, `providerCacheHints`, `turnTicketId`, and optional `actionRiskGate` (`actionCandidate` + `connectorContext`) |
| `POST /v1/minds/{mindId}/settle` | Required | **Mode B Step 2**: Settle raw LLM completion, `usage`, and optional `connectorContext` / `actionOutcome` into memory, affect, and `domainOutput` |
| `POST /v1/minds/{mindId}/turn` | Required | Mode A: prepare, call the provider, evaluate optional `actionRiskGate`, and settle in one request |
| `POST /v1/minds/{mindId}/idle-tick` | Required | **D2**: Offline circadian/homeostatic progression (`0..720h`), `proactiveHint`, and optional `proactiveVerdict` (`proactiveTriggerInput`) |
| `POST /v1/minds/{mindId}/connectors/{connectorId}/revoke` | Required | **D3 Connector Cascade**: Revoke OAuth/MCP connector memories (`{ reason?, cascadeMemories? }`, supports `Idempotency-Key`) |
| `POST /v1/minds/{mindId}/egress-check` | Required | **D4 Egress Firewall**: Scan outbound `payloadText` for `D4` markers, raw credentials, revoked IDs, and `expectedEpoch` mismatch |
| `GET /v1/minds/{mindId}/memories` | Required | List memories filtered by `epistemicTier`, `connectorId`, `category`, `includeRevoked`, `limit`, `offset` → `{ mindId, revocationEpoch, memories, total, limit, offset }` |
| `POST /v1/minds/{mindId}/memories` | Required | Ingest external memory (`201`, `connectorId`, `category`, `tags`, `epistemicTier`) → flat `{ ...MemoryRecord, mindId, revocationEpoch }` (`turnIndex: 0`) |
| `POST /v1/minds/{mindId}/memories/search` | Required | Hybrid search across memories (`limit`, `epistemicTier`, `connectorId`, `category`, `includeRevoked`; aliases `topK`/`epistemicTiers` accepted) → `{ mindId, query, revocationEpoch, totalMatches, results }` |
| `DELETE /v1/minds/{mindId}/memories/{memoryId}` | Required | Delete the specified memory and return a scoped receipt |
| `GET /v1/minds/{mindId}/telemetry` | Required | **D4**: Public telemetry snapshot with unconscious vectors strictly redacted (`d4Redacted: true`) |
| `POST /v1/minds/{mindId}/simulate-batch` | Required | Deterministic simulation, 0 LLM calls; OFF arms are fixed-rule references, not measured behaviors |

---

## 4. Payloads

### 4.1 Local sealed gateway: actual `/prepare` response

Selected fields from a local sealed-gateway response. IDs and cache values vary; opaque prompt text and memory context are omitted.

```json
{
  "turnTicketId": "tkt_example",
  "mindId": "mind_example",
  "domain": "companion_chat",
  "providerCacheHints": {
    "promptCacheKey": "example-prefix-0",
    "staticPrefixHash": "example-prefix-hash",
    "openai": {
      "prompt_cache_key": "example-prefix-0",
      "prompt_cache_retention": "24h"
    },
    "anthropic": {
      "cache_control": {
        "type": "ephemeral",
        "ttl": "1h"
      },
      "systemCacheControl": {
        "type": "ephemeral",
        "ttl": "1h"
      },
      "historyBreakpointIndex": null
    },
    "gemini": {
      "cachedContentHint": "example-prefix-0",
      "systemInstructionHash": "example-prefix-hash"
    },
    "deepseek": {
      "prefixCacheKey": "example-prefix-0"
    },
    "openrouter": {
      "prompt_cache_key": "example-prefix-0",
      "stickyProviderRecommended": true
    },
    "vllm": {
      "prefixCacheKey": "example-prefix-0"
    }
  }
}
```

### 4.2 `/settle` request

```json
{
  "turnTicketId": "tkt_example",
  "rawReply": "Let me check our active memories carefully.",
  "providerUsed": "openai",
  "modelUsed": "gpt-4o-mini",
  "usage": {
    "promptTokens": 420,
    "completionTokens": 28,
    "cachedTokens": 310
  }
}
```

---

## 5. Integration examples

The SDKs are not published on npm or PyPI. Install the SDK from a reviewed checkout, not by registry package name. From your application directory:

```bash
git clone https://github.com/bearrhee/artificial-mind-engine.git
npm install ./artificial-mind-engine/packages/sdk-ts
python -m pip install ./artificial-mind-engine/packages/sdk-python
```

### 5.1 cURL quickstart

```bash
export AME_BASE_URL="https://artificialmind.me/ame-api"
export AME_API_KEY="<YOUR_AME_API_KEY>"

CREATE_KEY=$(node -p "crypto.randomUUID()")
TURN_KEY=$(node -p "crypto.randomUUID()")
MIND_ID=$(curl -fsS -X POST "$AME_BASE_URL/v1/minds" \
  -H "Authorization: Bearer $AME_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $CREATE_KEY" \
  -d '{
    "domain": "companion_chat",
    "persona": { "name": "Aria", "role": "AI Companion", "language": "en" }
  }' | node -e "console.log(JSON.parse(require('fs').readFileSync(0,'utf8')).mindId)")

PREP=$(curl -fsS -X POST "$AME_BASE_URL/v1/minds/$MIND_ID/prepare" \
  -H "X-AME-API-Key: $AME_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: prepare-$TURN_KEY" \
  -d '{ "userInput": "Do you remember my favorite tea?" }')

TICKET_ID=$(echo "$PREP" | node -e "console.log(JSON.parse(require('fs').readFileSync(0,'utf8')).turnTicketId)")

curl -fsS -X POST "$AME_BASE_URL/v1/minds/$MIND_ID/settle" \
  -H "X-AME-API-Key: $AME_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: settle-$TICKET_ID" \
  -d "{
    \"turnTicketId\": \"$TICKET_ID\",
    \"rawReply\": \"Let me check our active memories carefully.\",
    \"providerUsed\": \"openai\",
    \"modelUsed\": \"gpt-4o-mini\",
    \"usage\": { \"promptTokens\": 420, \"completionTokens\": 28, \"cachedTokens\": 310 }
  }"
```

```bash
# Mode A alternative (mock provider, no external LLM call).
TURN_KEY=$(node -p "crypto.randomUUID()")
curl -fsS -X POST "$AME_BASE_URL/v1/minds/$MIND_ID/turn" \
  -H "Authorization: Bearer $AME_API_KEY" -H 'Content-Type: application/json' \
  -H "Idempotency-Key: turn-$TURN_KEY" \
  -d '{"userInput":"Hello","llm":{"provider":"mock","model":"mock"}}'
```

### 5.2 TypeScript: provider SSE, serialized per Mind

On one worker, this queue keeps a completed reply pending until settlement succeeds. Before preparing another turn for the same Mind, it resends the original ticket, body and idempotency key. If replay fails, the new turn does not start. A terminal `400`, `404`, or `409` settle error clears the pending entry and reports the unconfirmed turn: an expired, stale, or invalid ticket cannot be retried with the same payload, though a lost `200` response before a `404`/`409` may mean the ticket was already consumed. A prepare or stream failure rejects only that call. To recover across workers or restarts, persist pending entries and serialize access to them per Mind.

```ts
import { AmeApiError, AmeClient, applyCacheHints, type SettleTurnRequest } from '@ame/sdk';
import { randomUUID } from 'node:crypto';

const ame = new AmeClient({ baseUrl: 'https://artificialmind.me/ame-api', apiKey: process.env.AME_API_KEY });
const queues = new Map<string, Promise<void>>();
const pending = new Map<string, { body: SettleTurnRequest; idempotencyKey: string }>();

async function settlePending(mindId: string) {
  const entry = pending.get(mindId);
  if (!entry) return;
  try {
    await ame.settle(mindId, entry.body, { idempotencyKey: entry.idempotencyKey });
  } catch (error) {
    if (error instanceof AmeApiError && (error.status === 400 || error.status === 404 || error.status === 409)) {
      pending.delete(mindId);
      throw new Error(`Turn ${entry.body.turnTicketId}: terminal settle error (${error.status}); commit not confirmed`, { cause: error });
    }
    throw error; // Keep the exact body and key for the next attempt.
  }
  pending.delete(mindId);
}

export function streamModeBTurn(mindId: string, userInput: string, onDelta: (text: string) => void) {
  const previous = queues.get(mindId) ?? Promise.resolve();
  const next = previous.catch(() => {}).then(async () => {
    await settlePending(mindId);
    const key = randomUUID();
    const prep = await ame.prepare(mindId, { userInput }, { idempotencyKey: `prepare-${key}` });
    const hints = applyCacheHints(prep, 'openai');
    const res = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
      body: JSON.stringify({ model: 'gpt-4o-mini', stream: true, stream_options: { include_usage: true },
        messages: [{ role: 'system', content: prep.systemPrompt }, ...prep.messages], ...hints.bodyPatch }),
    });
    if (!res.ok || !res.body || !res.headers.get('content-type')?.startsWith('text/event-stream')) {
      throw new Error(`Expected an SSE response; HTTP ${res.status}`);
    }
    let fullReply = '', buffer = '', done = false;
    let usage: { promptTokens?: number; completionTokens?: number; cachedTokens?: number } | undefined;
    function line(raw: string) {
      const value = raw.trim();
      if (!value.startsWith('data:')) return;
      const data = value.slice(5).trim();
      if (data === '[DONE]') { done = true; return; }
      const event = JSON.parse(data);
      if (event.error) throw new Error('Provider stream failed');
      const delta = event.choices?.[0]?.delta?.content;
      if (delta) { fullReply += delta; onDelta(delta); }
      if (event.usage) usage = { promptTokens: event.usage.prompt_tokens,
        completionTokens: event.usage.completion_tokens, cachedTokens: event.usage.prompt_tokens_details?.cached_tokens };
    }
    for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
      const lines = (buffer + chunk).split('\n');
      buffer = lines.pop()!;
      for (const item of lines) line(item);
    }
    if (buffer.trim()) line(buffer);
    if (!done || !fullReply.trim()) throw new Error('Empty or incomplete stream; not settled');
    pending.set(mindId, { idempotencyKey: `settle-${prep.turnTicketId}`, body: {
      turnTicketId: prep.turnTicketId, rawReply: fullReply, providerUsed: 'openai', modelUsed: 'gpt-4o-mini', usage } });
    await settlePending(mindId);
  });
  queues.set(mindId, next);
  return next.finally(() => { if (queues.get(mindId) === next) queues.delete(mindId); });
}
```

### 5.3 Python: synchronous Mode B (not SSE)

```python
import os
from uuid import uuid4
from ame_sdk import AmeClient, create_llm_adapter

ame = AmeClient(base_url="https://artificialmind.me/ame-api", api_key=os.environ["AME_API_KEY"])
mind = ame.create_mind(domain="companion_chat", persona={"name": "Aria", "role": "Companion"},
                       idempotency_key=str(uuid4()))
prep = ame.prepare(mind["mindId"], user_input="Do you remember my favorite tea?", idempotency_key=str(uuid4()))
adapter = create_llm_adapter(provider="openai", model="gpt-4o-mini", api_key=os.environ["OPENAI_API_KEY"])
reply = adapter.generate(prep)
if not reply or not reply.strip():
    raise RuntimeError("Empty completion; not settled")
ame.settle(mind["mindId"], turn_ticket_id=prep["turnTicketId"], raw_reply=reply,
           provider_used=adapter.provider, model_used=adapter.model, usage=adapter.last_usage,
           idempotency_key="settle-" + prep["turnTicketId"])
```

### 5.4 Fastify: stream with the helper from §5.2

```js
app.post('/api/chat/:mindId/stream', async (request, reply) => {
  // Authenticate the client and check Mind ownership in your application before this handler.
  reply.hijack();
  const out = reply.raw;
  out.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
  try {
    await streamModeBTurn(request.params.mindId, request.body.userInput, (token) => {
      out.write(`data: ${JSON.stringify({ token })}\n\n`);
    });
    out.end('event: done\ndata: {}\n\n');
  } catch {
    out.end('event: error\ndata: {"message":"Turn did not complete"}\n\n');
  }
});
```

---

## 6. Provider prefix cache hints

| Provider | Hint Mapping | Effect |
| :--- | :--- | :--- |
| OpenAI | `openai.prompt_cache_key`, `openai.prompt_cache_retention` | For models that support extended retention, opt in with supportsExtendedRetention (TS) or supports_extended_retention (Python). |
| Anthropic | `anthropic.cache_control`, `anthropic.historyBreakpointIndex` | Apply the cache directive to the static system block; use a history breakpoint if present. |
| DeepSeek / OpenRouter / vLLM | `deepseek.prefixCacheKey`, `openrouter.prompt_cache_key`, `vllm.prefixCacheKey` | Check provider support. A hint does not measure cache hits. |
| Google Gemini | `gemini.cachedContentHint`, `gemini.systemInstructionHash` | Identifiers only. Create a provider-side `cachedContents` resource yourself for explicit caching. |

---

## 7. Errors, deletion receipts and usage

`error` is lowercase; `code` is its uppercase alias. The RPM response includes both `retryAfterSec` and `retryAfterSeconds`.

| HTTP | Code | Action |
|---|---|---|
| `400` | `INVALID_REQUEST` / `BAD_REQUEST` / `INVALID_LLM_BASE_URL` / `MISSING_BASE_URL` | Check schema, timestamps, field limits, URL, and ensure `tokenSurrogateRef` contains an opaque surrogate ID (raw credentials `sk-`, `ghp_`, `Bearer`, JWT `eyJ...` are rejected with `400`). |
| `401` | `UNAUTHORIZED` | Check the API key. |
| `404` | `NOT_FOUND` / `MIND_NOT_FOUND` / `MEMORY_NOT_FOUND` / `TICKET_NOT_FOUND` | Check path and tenant; tickets may be expired or consumed. |
| `409` | `TICKET_REVISION_STALE` / `IDEMPOTENCY_INVALIDATED` | Prepare again against current state. |
| `409` | `IDEMPOTENCY_KEY_REUSE` | Use the original body or start a distinct operation with a new key. |
| `413` | `BAD_REQUEST` | Reduce the body to 1 MiB or less. |
| `429` | `RATE_LIMITED` / `MIND_QUOTA_EXCEEDED` / `PENDING_TICKET_QUOTA_EXCEEDED` | Wait for a free batch slot or the rate window; free a Mind or settle pending tickets for quotas. Pending ticket limit: 50 per tenant. |
| `429` | `MIND_QUOTA_UNAVAILABLE` | The store could not confirm the quota. Check readiness before retrying. |
| `500` | `INTERNAL_ERROR` / `MIND_DELETE_INCOMPLETE` | Do not treat an error as a deletion receipt. |
| `502` | `UPSTREAM_LLM_ERROR` / `UPSTREAM_LLM_EMPTY` | Check provider availability before retrying. |
| `503` | `AUTH_NOT_CONFIGURED` / `DATABASE_UNREACHABLE` / `SESSION_CAPACITY_BUSY` | Check auth, readiness or session capacity. |

- A deletion request removes the specified Mind or memory from the service. A receipt is not certification or an independent audit.
- A Mind or memory receipt reports `residualCount` within `verificationScope` (`process-memory` or `process-memory+postgres`). `residualLeakCheck` is a legacy pass/fail marker, not a measured percentage. The receipt does not cover backups, replicas, other processes or provider storage. After Mind deletion, tenant usage totals remain without the Mind ID.
- D4 filters internal vectors from `TurnResult.telemetry` and `/telemetry`; these responses set `d4Redacted: true`.
- `/usage` returns `totalMinds`, `totalTurns` (settle + proxy turns), `totalPromptTokens`, `totalCompletionTokens` and `totalCachedTokens`. `estimatedCacheHitPct` is a token ratio, not cost savings. Successful creation or settlement does not confirm persistence: check the process-lifetime `persistFailures` counter in `/v1/readyz`.

---

## 8. Personal Agent & Explicit Memory APIs (`v1.2.0`)

`v1.2.0` is 100% backward-compatible with `v1.1.0` and ships five built-in domains (`"game_npc"`, `"companion_chat"`, `"counseling_coach"`, `"personal_agent"`, `"custom"`) plus dedicated Personal Agent & Memory Management capabilities:

### 8.1 Pre-Action Risk Gate (`/prepare`, `/turn`, `/settle`)
Pass `actionCandidate` and `connectorContext` on `/prepare` or `/turn` (and `connectorContext` / `actionOutcome` on `/settle`) to receive `actionRiskGate`:

```json
{
  "actionRiskGate": {
    "decision": "require_hitl",
    "confidence": 0.91,
    "epiplexityMargin": 0.24,
    "reasonCode": "irreversible_external_write_needs_hitl",
    "requiresUserConfirmation": true
  }
}
```
- `decision`: `"allow" | "allow_with_audit" | "require_hitl" | "abstain_block"`.
- `actionOutcome.status` (on `/settle`): `"executed" | "cancelled" | "hitl_pending" | "failed" | "blocked"`.
- **Credential Hygiene (`400`)**: Passing raw credentials (`sk-`, `ghp_`, `Bearer`, JWT `eyJ...`, etc.) inside `connectorContext.tokenSurrogateRef` is rejected with HTTP `400`.

### 8.2 Connector Cascade Revocation, Proactive Wakeup, Egress Firewall & Memory Management

```bash
# 1. Cascade D3 revocation on OAuth/MCP disconnect (supports Idempotency-Key)
curl -fsS -X POST "$AME_BASE_URL/v1/minds/$MIND_ID/connectors/conn_gmail_01/revoke" \
  -H "X-AME-API-Key: $AME_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: revoke-$(node -p 'crypto.randomUUID()')" \
  -d '{"reason":"user_disconnected_oauth","cascadeMemories":true}'
# -> { mindId, connectorId, revokedAtIso, revocationEpoch, invalidatedMemoriesCount, status: "revoked" }

# 2. Off-VM proactive wakeup verdict on /idle-tick
curl -fsS -X POST "$AME_BASE_URL/v1/minds/$MIND_ID/idle-tick" \
  -H "X-AME-API-Key: $AME_API_KEY" -H "Content-Type: application/json" \
  -d '{"elapsedHours":6.5,"proactiveTriggerInput":{"triggerKind":"calendar_due","urgencyScore":0.85,"userFocusState":"idle"}}'
# -> proactiveVerdict: { shouldWakeUp, channel: "silent"|"digest"|"push", reason, cooldownSeconds }

# 3. Outbound D4 egress firewall before VM dispatch
curl -fsS -X POST "$AME_BASE_URL/v1/minds/$MIND_ID/egress-check" \
  -H "X-AME-API-Key: $AME_API_KEY" -H "Content-Type: application/json" \
  -d '{"targetChannel":"email","payloadText":"Confirmed for 3 PM tomorrow.","expectedEpoch":1}'
# -> { mindId, targetChannel, verdict: "pass"|"redact"|"block", redactions: [{ rule, match, replacement }], matchedRules, revocationEpoch, checkedAtIso, sanitizedPreview? }

# 4. Explicit memory management (without advancing turnIndex)
curl -fsS -X POST "$AME_BASE_URL/v1/minds/$MIND_ID/memories" \
  -H "X-AME-API-Key: $AME_API_KEY" -H "Content-Type: application/json" \
  -d '{"content":"Prefers morning meetings.","connectorId":"conn_gcal_01","category":"preference","tags":["calendar"],"epistemicTier":"T1_verified_user"}'
# -> flat IngestMemoryResponse: { memoryId, summary, content, salience, turnIndex: 0, ..., mindId, revocationEpoch }

curl -fsS "$AME_BASE_URL/v1/minds/$MIND_ID/memories?connectorId=conn_gcal_01&limit=20&offset=0" \
  -H "X-AME-API-Key: $AME_API_KEY"
# -> { mindId, revocationEpoch, memories, total, limit, offset }

curl -fsS -X POST "$AME_BASE_URL/v1/minds/$MIND_ID/memories/search" \
  -H "X-AME-API-Key: $AME_API_KEY" -H "Content-Type: application/json" \
  -d '{"query":"morning meeting preference","limit":5,"connectorId":"conn_gcal_01","includeRevoked":false}'
# -> { mindId, query, revocationEpoch, totalMatches, results } (aliases topK/epistemicTiers also accepted)
```

### 8.3 SDK Methods (`v1.2.0`)
- **TypeScript (`@ame/sdk`)**: `defineDomainProfile({ id: "personal_agent" })`, `revokeConnector`, `checkEgress`, `listMemories`, `ingestMemory`, `searchMemories`.
- **Python (`ame_sdk` / `ame-sdk`)**: `DOMAIN_PROFILES["personal_agent"]`, `revoke_connector`, `check_egress`, `list_memories`, `ingest_memory`, `search_memories`.
