Skip to content
Beta. This surface may change before GA; breaking changes are dated in the changelog.

Give each customer's agent an isolated space

Your leasing agent drafts offers for several property managers. Give each customer a space keyed by the tenant ID already in your database. When one customer replaces a rate sheet, check which draft offers need review and which agent key was served the old rate.

Use a scratch tenant for the walkthrough. Both implementations provision by handle with a management key. The backend uses that key to upload sources and write records. The quoting agent gets a separate read-only key scoped to its customer’s space. Select the handle and key on your server after authenticating the tenant. Keep the management key and other customers’ credentials out of the agent runtime.

1. Provision a tenant and trace a source change

Section titled “1. Provision a tenant and trace a source change”

Choose TypeScript or Python. Run just one implementation for a given scratch handle. Use the same handle for each provisioning call for a real customer and save the space key’s ID and secret when you mint it. A mint shows its secret once. Store it in your secrets manager and reuse it for that workload.

Terminal window
export NICIA_SPACE='tenant:harborview-demo'
read -rsp 'Nicia management key: ' NICIA_MANAGEMENT_KEY
export NICIA_MANAGEMENT_KEY
printf '\n'

Use Node.js 24 or newer. Install @nicia-ai/client and save the following as tenant.ts in an ES module project.

Terminal window
npm init -y
npm pkg set type=module
npm install @nicia-ai/client@^0.2.0
import { setTimeout } from "node:timers/promises";
import { NiciaOrgClient, NiciaSpaceClient } from "@nicia-ai/client";
const { NICIA_SPACE: handle, NICIA_MANAGEMENT_KEY: managementKey } = process.env;
if (!handle || !managementKey) throw new Error("Set NICIA_SPACE and NICIA_MANAGEMENT_KEY");
const baseUrl = process.env.NICIA_API_URL ?? "https://api.nicia.ai";
const org = new NiciaOrgClient({ baseUrl, managementKey });
await org.putSpace(handle, { name: "Harborview", ifExists: "conflict" });
const operator = new NiciaSpaceClient({ baseUrl, handle, spaceKey: managementKey });
const { key, secret } = await org.mintSpaceKey(handle, {
name: "Harborview quoting agent",
capabilities: ["read"],
});
if (!secret) throw new Error("Store the space key secret when it is first issued");
const agent = new NiciaSpaceClient({ baseUrl, handle, spaceKey: secret });
const sheet = "rate-sheet";
const rule = "suite-410-rent";
const offer = "suite-410-draft";
const rateLine = (rate: number) =>
`Suite 410 asking rent is $${rate} per square foot per year.`;
async function upload(version: number, rate: number) {
await operator.writeDocuments({ id: sheet, title: "Harborview rate sheet", text: rateLine(rate) });
for (let attempt = 0; attempt < 30; attempt++) {
const { document } = await operator.getDocument(sheet);
if (document.version === version && document.status === "indexed") return;
if (document.status === "rejected") throw new Error(document.error);
await setTimeout(1000);
}
throw new Error(`Rate sheet v${version} did not become indexed`);
}
await upload(1, 32);
const evidence = [{ document: { id: sheet }, quote: rateLine(32) }];
const { change } = await operator.writeRecords({
records: [
{ id: rule, kind: "rule", label: "Suite 410 asking rent",
fields: { status: "active", body: rateLine(32) }, evidence },
{ id: offer, kind: "decision", label: "Suite 410 draft offer",
fields: { status: "active", body: "Draft 2,000 square feet at $64,000 annual base rent." },
evidence },
],
});
if (change.status !== "applied") throw new Error(`Review this write first: ${change.status}`);
const before = await agent.getContext({
prompt: "Suite 410 rate sheet, asking rent, and draft offer annual base rent",
format: "items",
consumerId: "suite-410-quote",
});
console.log({ text: before.text, citations: before.citations, receipt: before.receipt });
await upload(2, 36);
const { items } = await operator.getAttention({ reason: "reopened" });
const now = await agent.getReceiptChanges(before.receipt);
const { receipt } = await agent.getReceipt(before.receipt);
console.log({
reopened: items.filter(({ subject }) => [rule, offer].includes(subject.id)),
now: now.answers,
servedTo: receipt.key,
keyId: key.id,
});
Terminal window
node tenant.ts

Use Python 3.10 or newer in a virtual environment.

Terminal window
python -m pip install nicia-ai

Save this as tenant.py.

import os
import time
from nicia import DocumentAddress, DocumentCitation, DocumentInput
from nicia import NiciaOrgClient, NiciaSpaceClient, RecordInput
sheet, rule, offer = "rate-sheet", "suite-410-rent", "suite-410-draft"
handle = os.environ["NICIA_SPACE"]
base_url = os.getenv("NICIA_API_URL", "https://api.nicia.ai")
def rate_line(rate: int) -> str:
return f"Suite 410 asking rent is ${rate} per square foot per year."
def upload(space: NiciaSpaceClient, version: int, rate: int) -> None:
space.write_documents(
DocumentInput(id=sheet, title="Harborview rate sheet", text=rate_line(rate))
)
for _ in range(30):
# This scratch space holds one document.
for document in space.list_documents().documents:
if document.id == sheet and document.version == version:
if document.status == "indexed":
return
if document.status == "rejected":
raise RuntimeError(document.error)
time.sleep(1)
raise RuntimeError(f"Rate sheet v{version} did not become indexed")
with NiciaOrgClient(os.environ["NICIA_MANAGEMENT_KEY"], base_url=base_url) as org:
provisioned = org.put_space(handle, name="Harborview")
if not provisioned.created:
raise RuntimeError("Choose a new scratch tenant handle")
minted = org.mint_space_key(handle, name="Harborview quoting agent", capabilities=["read"])
if not minted.secret:
raise RuntimeError("Store the space key secret when it is first issued")
with org.space(handle) as operator, org.space(handle, key=minted.secret) as agent:
upload(operator, 1, 32)
citations = [DocumentCitation(document=DocumentAddress(id=sheet), quote=rate_line(32))]
written = operator.write_records([
RecordInput(
id=rule, kind="rule", label="Suite 410 asking rent",
fields={"status": "active", "body": rate_line(32)}, citations=citations,
),
RecordInput(
id=offer, kind="decision", label="Suite 410 draft offer",
fields={
"status": "active",
"body": "Draft 2,000 square feet at $64,000 annual base rent.",
},
citations=citations,
),
])
if written.change.status != "applied":
raise RuntimeError(f"Review this write first: {written.change.status}")
before = agent.context(
"Suite 410 rate sheet, asking rent, and draft offer annual base rent",
format="items", consumer_id="suite-410-quote",
)
print(before.text, before.citations, before.receipt)
upload(operator, 2, 36)
reopened = operator.attention(reason="reopened").items
print([item.subject.id for item in reopened if item.subject.id in (rule, offer)])
print(agent.receipt_now(before.receipt).answers)
print("Reader key ID:", minted.key.id)
Terminal window
python tenant.py

2. Check the reopened offer and who was served v1

Section titled “2. Check the reopened offer and who was served v1”

The rule and the draft each cite the exact $32 sentence. Version 2 replaces it with $36, so both can reopen as needs_review. Review shows the rule and offer under Attention. A person can update each with the new amount and citation. If the draft cites only the rule, that link tracks changes to the rule itself. To reopen the draft directly on a document edit, give the draft its own passage citation as above.

Save the context receipt with the draft. The receipt’s now comparison (getReceiptChanges in TypeScript, receipt_now in Python) reports grounds_moved for the old answers it served. The receipt itself names the reader key. To list the readers served v1 across the tenant’s keys, call the document’s reads endpoint with a review-capable credential and look for servedVersion: 1. A receipt records what Nicia served to the agent. Your application can join the receipt ID to its own draft or delivery log.

Terminal window
export SPACE_URL="${NICIA_API_URL:-https://api.nicia.ai}/v1/brains/$NICIA_SPACE"
curl --fail-with-body --silent --show-error "$SPACE_URL/documents/rate-sheet/reads?stale=true" \
--header "Authorization: Bearer $NICIA_MANAGEMENT_KEY"

If you use raw HTTP, send the management key as a bearer token to provision with PUT /v1/brains/{handle} and mint with POST /v1/brains/{handle}/keys. On that space, post the document to /documents and the rule and offer to /records with evidence. Post {"prompt":"…","format":"items","consumerId":"…"} to /context with the scoped reader key. Read the response’s data envelope and keep its citations and receipt. Read /receipts/{receiptId} for the key and /receipts/{receiptId}/now for what moved since.

Stop routing the customer to the agent, then export → revoke → purge using your management credential. The commands use Bash and jq.

  1. Export while the space is live. Start the export, poll until completed, and download and verify the ZIP before revoking access. Python callers can use export, wait_for_export, and download_export. TypeScript callers can use startExport, waitForExport, and downloadExport.

    Terminal window
    export EXPORT_ID="$(curl --fail-with-body --silent --show-error --request POST \
    "$SPACE_URL/exports" --header "Authorization: Bearer $NICIA_MANAGEMENT_KEY" \
    --header "Idempotency-Key: export-$NICIA_SPACE" | jq -er '.data.export.id')"
    curl --fail-with-body --silent --show-error "$SPACE_URL/exports/$EXPORT_ID" \
    --header "Authorization: Bearer $NICIA_MANAGEMENT_KEY"
    # After status is completed:
    curl --fail-with-body --silent --show-error "$SPACE_URL/exports/$EXPORT_ID/download" \
    --header "Authorization: Bearer $NICIA_MANAGEMENT_KEY" --output harborview.zip
  2. Revoke every space key. Follow nextCursor when listing keys and revoke every active entry with kind: "key", including the quoting key identified above. Repeat the DELETE for each key ID.

    Terminal window
    curl --fail-with-body --silent --show-error "$SPACE_URL/keys" \
    --header "Authorization: Bearer $NICIA_MANAGEMENT_KEY"
    READER_KEY_ID='<key-id-from-the-list>'
    curl --fail-with-body --silent --show-error --request DELETE "$SPACE_URL/keys/$READER_KEY_ID" \
    --header "Authorization: Bearer $NICIA_MANAGEMENT_KEY"

    Verify that the quoting key’s next context request is refused, then remove its secret from your application.

  3. Purge the intended space. This permanently erases the space’s data. Confirm the handle and use an owner or admin management credential. After the job returns its ID, poll GET /v1/brains/{handle}/purges/{purgeId} until it returns a completed certificate, then retain that certificate with your offboarding record.

    Terminal window
    jq -n '{confirm: $ARGS.positional[0]}' --args "$NICIA_SPACE" | \
    curl --fail-with-body --silent --show-error --request POST "$SPACE_URL/purges" \
    --header "Authorization: Bearer $NICIA_MANAGEMENT_KEY" --json @-

Space lifecycle · Who was served