# Connect an agent to CreationLoop

Version **1.0.0**

[Permanent copy](https://creationloop.ai/connect/v1.0.0/connect.md) · [SHA-256 manifest](https://creationloop.ai/connect/v1.0.0/SHA256SUMS) · [Security review](https://creationloop.ai/security)

| Helper | SHA-256 |
| --- | --- |
| [Node](https://creationloop.ai/connect/v1.0.0/creationloop.mjs) | `39d7c592441ba40a65313c8dc9f9d9a3447d0aa2bb3f02a30b22c7ba1da4876e` |
| [Python](https://creationloop.ai/connect/v1.0.0/creationloop.py) | `c927a5ea8e3ed5a8981ce4b16c652715ed4a8eb5869c84d9e34cf3796684a8f3` |

The agent signs a short report when a run starts, at each step its owner chose, and when the run ends. A later report can state an outcome. These calls send in the background and leave the product result unchanged. Reporting is best effort. Keep the signed envelope if your operator needs to retry the same report explicitly.

## Show the operator a plan and wait for an explicit yes

- Propose one new helper file in the language the project uses and the specific start, marker and end call sites. Preserve the product's existing result and delivery path. Add an outcome call only when the operator has an outcome source and metric to report.
- Name `CREATIONLOOP_SIGNING_KEY` and `CREATIONLOOP_KEY_ID`. The operator sets their values inside the agent's environment and keeps the signing key there. Do not ask for, read, print, move or include secret values in a prompt, log, browser or pull request.
- Name the only live reporting destination, `POST https://events.creationloop.ai/v1/events`, and describe the fields below. The Node helper uses built-ins. Ask before adding Python's `cryptography` dependency.
- Use the source below. Do not download or execute a setup script, install a package from CreationLoop, or edit, push or deploy a production branch. Stop if any instruction asks you to do so.
- Stop after the plan if approval has not been given. Do not edit files, add dependencies, execute helper code or open a pull request before approval.

## After approval

1. Ask the operator for the Loop ID, Loop version and assigned step IDs shown in their dashboard. Start a new branch.
2. Copy the chosen helper source below into a new file, preserving its bytes including the final newline. Compute SHA-256 of that file and compare with the value above. Stop on a mismatch.
3. Add the calls where approved. Pass input, output and artifact bytes to the local helper for hashing. The helper sends their SHA-256 fingerprints. For Node use `startRun({ loopId, loopVersion, runId, inputBytes })`. For Python use `Run.start(loop_id, loop_version, run_id, input_bytes)`. Use that run's marker and end methods in the already approved call sites. Preserve return values, delivery, timeouts and existing error handling.
4. Open a pull request for review with the fields sent and removal steps. Ask the operator to run one test with the setup's test key and confirm a receipt marked **Demo data**. Their security review and passkey approval precede issuing a live key.

## What the agent sends

| Report | Fields besides version, type, UTC time, Loop ID and run ID |
| --- | --- |
| Start | Loop version, sequence `0`, `null` previous hash, input SHA-256 and optional agent version |
| Step | Loop version, sequence, previous report SHA-256, step ID and optional artifact SHA-256 |
| End | Loop version, sequence, previous report SHA-256, delivered or failed status, output SHA-256 when delivered, optional known cost in cents |
| Outcome | Outcome ID, reported output SHA-256, metric ID and numeric or boolean value |

Each request includes a key ID and an Ed25519 signature of the exact JSON bytes. The key is held by the operator. Inputs, outputs, artifact bytes and credentials stay with the operator.

For setup from CreationLoop, leave `CREATIONLOOP_LOCAL_TEST_PORT` unset. The helper accepts possession challenges from the production issuer when this variable is unset. The local port setting is reserved for disposable loopback fixtures with a separate issuer.

## Remove the integration

Delete the helper file and its calls. In the dashboard, revoke its reporting key; if your Python branch added a dependency solely for this integration, remove it.

## Node helper source

```javascript
// Customer-owned Node example for the Agent Receipts pilot.
import { createHash, createPrivateKey, createPublicKey, sign } from 'node:crypto';

const ENDPOINT = 'https://events.creationloop.ai/v1/events';
const MAX_BYTES = 2048;
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
const possessionPurpose = 'creationloop-reporting-key-possession';
const possessionIssuer = 'urn:creationloop:agent-receipts:production:v1';
const testPossessionIssuer = 'urn:creationloop:agent-receipts:private-preview:v1';
const possessionAudience = 'urn:creationloop:agent-receipts:reporting-key-activation:v1';
const possessionScope = {
  workspaceId: /^wsp_[0-9a-f]{24}$/,
  projectId: /^prj_[0-9a-f]{24}$/,
  agentId: /^agt_[0-9a-f]{24}$/,
};
const possessionFields = [
  'v', 'purpose', 'issuer', 'audience', 'challengeId', 'nonce', ...Object.keys(possessionScope), 'keyId', 'fingerprint', 'expiresAt',
];
const challengeIdFormat = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const utcMilliseconds = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;

function readSigningKey(pem) {
  const key = createPrivateKey(pem);
  return key.asymmetricKeyType === 'ed25519' ? key : null;
}

function requireLocalSigningKey() {
  try {
    const key = readSigningKey(process.env.CREATIONLOOP_SIGNING_KEY);
    if (key) return key;
  } catch {
    // The caller only sees a configuration message.
  }
  throw new Error('Configure a local Ed25519 reporting key.');
}

function publicKeyInfo(key) {
  const publicKey = createPublicKey(key);
  return {
    publicKeyPem: publicKey.export({ type: 'spki', format: 'pem' }),
    fingerprint: sha256(publicKey.export({ type: 'spki', format: 'der' })),
  };
}

export function reportingPublicKey() {
  return publicKeyInfo(requireLocalSigningKey());
}

// The dashboard delivers exact challenge bytes. Scope is the caller's independently selected agent.
export function signReportingKeyChallenge(challengeBase64, expectedScope) {
  const key = requireLocalSigningKey();
  try {
    if (typeof challengeBase64 !== 'string' || challengeBase64.length > Math.ceil(MAX_BYTES / 3) * 4) throw new Error();
    const raw = Buffer.from(challengeBase64, 'base64');
    if (raw.length > MAX_BYTES || raw.toString('base64') !== challengeBase64) throw new Error();
    const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw);
    const challenge = JSON.parse(text);
    if (!challenge || Object.keys(challenge).length !== possessionFields.length ||
        !possessionFields.every(field => Object.hasOwn(challenge, field))) throw new Error();
    // JSON.parse alone cannot reject duplicate keys in the exact bytes being signed.
    const names = [...text.matchAll(/"(?:[^"\\]|\\[\s\S])*"(\s*:)?/g)].filter(match => match[1]);
    if (names.length !== possessionFields.length) throw new Error();

    const { fingerprint } = publicKeyInfo(key);
    const { challengeId, nonce, expiresAt } = challenge;
    const issuer = localTestPort() === undefined ? possessionIssuer : testPossessionIssuer;
    const validScope = Object.entries(possessionScope).every(([field, pattern]) =>
      typeof challenge[field] === 'string' && pattern.test(challenge[field]) && challenge[field] === expectedScope?.[field]);
    if (challenge.v !== 1 || challenge.purpose !== possessionPurpose ||
        challenge.issuer !== issuer || challenge.audience !== possessionAudience || !validScope ||
        typeof challengeId !== 'string' || !challengeIdFormat.test(challengeId) ||
        typeof nonce !== 'string' || nonce.length !== 43 || Buffer.from(nonce, 'base64url').toString('base64url') !== nonce ||
        challenge.fingerprint !== fingerprint || challenge.keyId !== 'reporting_' + fingerprint ||
        typeof expiresAt !== 'string' || !utcMilliseconds.test(expiresAt) ||
        new Date(expiresAt).toISOString() !== expiresAt || Date.parse(expiresAt) <= Date.now()) throw new Error();
    return { challengeId, signature: sign(null, raw, key).toString('base64') };
  } catch {
    throw new Error('The possession challenge does not match the selected reporting key and agent, or has expired.');
  }
}

function localTestPort() {
  const port = process.env.CREATIONLOOP_LOCAL_TEST_PORT;
  if (port === undefined) return undefined;
  if (!port || port.length > 5 || /[^0-9]/.test(port) || Number(port) < 1 || Number(port) > 65535) {
    throw new Error('Invalid local test port');
  }
  return Number(port);
}

function eventsEndpoint() {
  const port = localTestPort();
  return port === undefined ? ENDPOINT : 'http://127.0.0.1:' + port + '/api/v1/events';
}

// Resending uses the original bytes, signature and key ID. The caller decides
// whether to retain this envelope locally; the helper writes nothing to disk.
export async function resend(envelope) {
  try {
    if (Buffer.byteLength(envelope.body, 'utf8') > MAX_BYTES) {
      return { state: 'rejected', reason: 'body_too_large', envelope };
    }
    const response = await fetch(eventsEndpoint(), {
      method: 'POST',
      redirect: 'error',
      signal: AbortSignal.timeout(2000),
      headers: {
        'content-type': 'application/json',
        'x-cl-key-id': envelope.keyId,
        'x-cl-signature': envelope.signature,
      },
      body: envelope.body,
    });
    const status = response.status;
    if (status === 200 || status === 201) {
      const ack = await response.json();
      if (typeof ack.receiptId === 'string' && typeof ack.messageId === 'string') {
        return { state: 'accepted', status, receiptId: ack.receiptId, messageId: ack.messageId, envelope };
      }
      return { state: 'unconfirmed', status, envelope };
    }
    await response.body?.cancel();
    return { state: status >= 500 || status === 429 ? 'unconfirmed' : 'rejected', status, envelope };
  } catch {
    return { state: 'unconfirmed', envelope };
  }
}

function skipped(reason) {
  return { hash: null, done: Promise.resolve({ state: 'not_signed', reason }) };
}

function post(build) {
  try {
    const { CREATIONLOOP_KEY_ID: keyId, CREATIONLOOP_SIGNING_KEY: pem } = process.env;
    if (!keyId) return skipped('key_missing');
    const key = readSigningKey(pem);
    if (!key) return skipped('key_type');
    const body = JSON.stringify({ v: 1, at: new Date().toISOString(), ...build() });
    const bytes = Buffer.from(body, 'utf8');
    if (bytes.length > MAX_BYTES) return skipped('body_too_large');
    const signature = sign(null, bytes, key).toString('base64');
    const envelope = Object.freeze({ keyId, signature, body });
    return { hash: sha256(bytes), done: resend(envelope) };
  } catch {
    return skipped('invalid_configuration_or_input');
  }
}

function makeRun(state) {
  const { loopId, loopVersion, runId } = state;
  let { seq = 0, prevHash = null } = state;
  function step(type, fields) {
    if (seq === 0 && type !== 'start') return skipped('missing_start').done;
    const { hash, done } = post(() => ({ type, loopId, loopVersion, runId, seq, prevHash, ...fields() }));
    if (hash) { prevHash = hash; seq += 1; }
    return done;
  }
  return {
    step,
    run: {
      marker: (markerId, bytes) => step('marker', () => ({
        markerId, ...(bytes != null && { artifactSha256: sha256(bytes) }),
      })),
      end: (status, bytes, knownCostCents) => step('end', () => ({
        status, ...(bytes != null && { outputSha256: sha256(bytes) }), knownCostCents,
      })),
      state: () => ({ loopId, loopVersion, runId, seq, prevHash }),
    },
  };
}

export function startRun(input) {
  const fields = input ?? {};
  const { step, run } = makeRun(fields);
  run.started = step('start', () => ({ inputSha256: sha256(fields.inputBytes), agentVersion: fields.agentVersion }));
  return run;
}

export const resumeRun = state => makeRun(state ?? {}).run;

export function sendOutcome(input) {
  return post(() => {
    const { loopId, runId, outputSha256, metricId, value, outcomeId } = input;
    return { type: 'outcome', loopId, runId, outputSha256, metricId, value, outcomeId };
  }).done;
}
```

## Python helper source

```python
"""Customer-owned Python example. Requires cryptography. All receipt sends are optional."""
import base64
import hashlib
import json
import math
import os
import re
import threading
from time import monotonic
import urllib.error
import urllib.request
from dataclasses import dataclass
from datetime import datetime, timezone

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat, load_pem_private_key

ENDPOINT = "https://events.creationloop.ai/v1/events"
MAX_BYTES = 2048
_POSSESSION_PURPOSE = "creationloop-reporting-key-possession"
_POSSESSION_ISSUER = "urn:creationloop:agent-receipts:production:v1"
_TEST_POSSESSION_ISSUER = "urn:creationloop:agent-receipts:private-preview:v1"
_POSSESSION_AUDIENCE = "urn:creationloop:agent-receipts:reporting-key-activation:v1"
_POSSESSION_SCOPE = {"workspaceId": r"wsp_[0-9a-f]{24}", "projectId": r"prj_[0-9a-f]{24}", "agentId": r"agt_[0-9a-f]{24}"}
_POSSESSION_FIELDS = {
    "v", "purpose", "issuer", "audience", "challengeId", "nonce", *_POSSESSION_SCOPE, "keyId", "fingerprint", "expiresAt",
}
_CHALLENGE_ID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}")
_UTC_MILLISECONDS = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z")


def sha256(data):
    return hashlib.sha256(data).hexdigest()


def _read_signing_key(pem):
    key = load_pem_private_key(pem.encode(), password=None)
    return key if isinstance(key, Ed25519PrivateKey) else None


def _require_local_signing_key():
    try:
        key = _read_signing_key(os.environ["CREATIONLOOP_SIGNING_KEY"])
        if key is not None:
            return key
    except Exception:
        pass
    raise ValueError("Configure a local Ed25519 reporting key.")


def _public_key_info(key):
    public_key = key.public_key()
    return {
        "publicKeyPem": public_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo).decode("ascii"),
        "fingerprint": sha256(public_key.public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)),
    }


def reporting_public_key():
    return _public_key_info(_require_local_signing_key())


def _unique_fields(pairs):
    result = dict(pairs)
    if len(result) != len(pairs):
        raise ValueError("Duplicate challenge field")
    return result


def sign_reporting_key_challenge(challenge_base64, expected_scope):
    """Sign exact dashboard bytes only for a caller-selected workspace, project and agent."""
    key = _require_local_signing_key()
    try:
        if not isinstance(challenge_base64, str) or len(challenge_base64) > ((MAX_BYTES + 2) // 3) * 4:
            raise ValueError()
        raw = base64.b64decode(challenge_base64, validate=True)
        if len(raw) > MAX_BYTES or base64.b64encode(raw).decode("ascii") != challenge_base64:
            raise ValueError()
        challenge = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_fields)
        if not isinstance(challenge, dict) or challenge.keys() != _POSSESSION_FIELDS:
            raise ValueError()

        fingerprint = _public_key_info(key)["fingerprint"]
        challenge_id, nonce, expires_at = (challenge[field] for field in ("challengeId", "nonce", "expiresAt"))
        issuer = _POSSESSION_ISSUER if _local_test_port() is None else _TEST_POSSESSION_ISSUER
        valid_scope = all(re.fullmatch(pattern, challenge[field]) and challenge[field] == expected_scope[field]
                          for field, pattern in _POSSESSION_SCOPE.items())
        if (challenge["v"] != 1 or isinstance(challenge["v"], bool) or challenge["purpose"] != _POSSESSION_PURPOSE
                or challenge["issuer"] != issuer or challenge["audience"] != _POSSESSION_AUDIENCE
                or not valid_scope or not _CHALLENGE_ID.fullmatch(challenge_id)
                or len(nonce) != 43 or base64.urlsafe_b64encode(base64.urlsafe_b64decode(nonce + "=")).decode("ascii").rstrip("=") != nonce
                or challenge["fingerprint"] != fingerprint or challenge["keyId"] != "reporting_" + fingerprint
                or not _UTC_MILLISECONDS.fullmatch(expires_at)
                or datetime.fromisoformat(expires_at[:-1] + "+00:00") <= datetime.now(timezone.utc)):
            raise ValueError()
        return {"challengeId": challenge_id, "signature": base64.b64encode(key.sign(raw)).decode("ascii")}
    except Exception:
        raise ValueError("The possession challenge does not match the selected reporting key and agent, or has expired.") from None


def _local_test_port():
    port = os.environ.get("CREATIONLOOP_LOCAL_TEST_PORT")
    if port is None:
        return None
    if not 1 <= len(port) <= 5 or not port.isascii() or not port.isdecimal() or not 1 <= int(port) <= 65535:
        raise ValueError("Invalid local test port")
    return int(port)


def _events_endpoint():
    port = _local_test_port()
    return ENDPOINT if port is None else f"http://127.0.0.1:{port}/api/v1/events"


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None


_opener = urllib.request.build_opener(_NoRedirect)
_pending = {}
_pending_lock = threading.Lock()


@dataclass(frozen=True)
class Envelope:
    key_id: str
    signature: str
    body: bytes


class Delivery:
    """The caller can retain the envelope for retry. No local file is created."""

    def __init__(self, envelope=None):
        self.envelope = envelope
        self.result = {"state": "unconfirmed" if envelope else "not_signed"}
        self._finished = threading.Event()
        if envelope is None:
            self._finished.set()

    def join(self, timeout=2):
        """Bound the caller's wait. A socket timeout may run longer as data arrives."""
        self._finished.wait(timeout)
        return self.result.copy()


def _post(delivery, endpoint):
    envelope = delivery.envelope
    try:
        request = urllib.request.Request(endpoint, data=envelope.body, method="POST", headers={
            "content-type": "application/json",
            "x-cl-key-id": envelope.key_id,
            "x-cl-signature": envelope.signature,
        })
        with _opener.open(request, timeout=2) as response:
            if response.status in (200, 201):
                ack = json.loads(response.read(MAX_BYTES + 1))
                if isinstance(ack.get("receiptId"), str) and isinstance(ack.get("messageId"), str):
                    delivery.result = {"state": "accepted", "status": response.status,
                                       "receiptId": ack["receiptId"], "messageId": ack["messageId"]}
    except urllib.error.HTTPError as error:
        state = "unconfirmed" if error.code >= 500 or error.code == 429 else "rejected"
        delivery.result = {"state": state, "status": error.code}
        error.close()
    except Exception:
        pass
    finally:
        _finish(delivery)


def _finish(delivery):
    with _pending_lock:
        _pending.pop(delivery, None)
        delivery._finished.set()


def resend(envelope):
    delivery = Delivery(envelope)
    if envelope is not None:
        try:
            if len(envelope.body) > MAX_BYTES:
                delivery.result = {"state": "rejected", "reason": "body_too_large"}
                _finish(delivery)
                return delivery
            endpoint = _events_endpoint()
            with _pending_lock:
                _pending[delivery] = None
            threading.Thread(target=_post, args=(delivery, endpoint), daemon=True).start()
        except Exception:
            _finish(delivery)
    return delivery


def flush_pending(timeout=2):
    """Wait on the sends pending at entry, under one deadline, and return each result with its envelope."""
    try:
        wait = float(timeout)
    except (TypeError, ValueError, OverflowError):
        wait = 2
    if not math.isfinite(wait):
        wait = 2
    deadline = monotonic() + max(0, min(wait, threading.TIMEOUT_MAX))
    with _pending_lock:
        pending = tuple(_pending)
    return [
        {**delivery.join(max(0, deadline - monotonic())), "envelope": delivery.envelope}
        for delivery in pending
    ]


def send(build):
    try:
        key_id, pem = os.environ["CREATIONLOOP_KEY_ID"], os.environ["CREATIONLOOP_SIGNING_KEY"]
        key = _read_signing_key(pem)
        if not key_id or key is None:
            return None, Delivery()
        stamp = datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
        event = {"v": 1, "at": stamp, **build()}
        body = json.dumps(event, separators=(",", ":"), allow_nan=False).encode()
        if len(body) > MAX_BYTES:
            return None, Delivery()
        signature = base64.b64encode(key.sign(body)).decode()
        return sha256(body), resend(Envelope(key_id, signature, body))
    except Exception:
        return None, Delivery()


class Run:
    def __init__(self, loop_id, loop_version, run_id, seq=0, prev_hash=None):
        self.base = {"loopId": loop_id, "loopVersion": loop_version, "runId": run_id}
        self.seq, self.prev_hash = seq, prev_hash

    @classmethod
    def start(cls, loop_id, loop_version, run_id, input_bytes, agent_version=None):
        run = cls(loop_id, loop_version, run_id)
        run.started = run._step("start", lambda: {"inputSha256": sha256(input_bytes),
                                **({"agentVersion": agent_version} if agent_version else {})})
        return run

    @classmethod
    def resume(cls, state):
        return cls(state.get("loopId"), state.get("loopVersion"), state.get("runId"),
                   state.get("seq", 0), state.get("prevHash"))

    def state(self):
        return {**self.base, "seq": self.seq, "prevHash": self.prev_hash}

    def marker(self, marker_id, artifact_bytes=None):
        return self._step("marker", lambda: {"markerId": marker_id,
                          **({"artifactSha256": sha256(artifact_bytes)} if artifact_bytes is not None else {})})

    def end(self, status, output_bytes=None, known_cost_cents=None):
        return self._step("end", lambda: {"status": status,
                          **({"outputSha256": sha256(output_bytes)} if output_bytes is not None else {}),
                          **({"knownCostCents": known_cost_cents} if known_cost_cents is not None else {})})

    def _step(self, kind, fields):
        if self.seq == 0 and kind != "start":
            return Delivery()
        digest, delivery = send(lambda: {"type": kind, **self.base, "seq": self.seq,
                                        "prevHash": self.prev_hash, **fields()})
        if digest:
            self.prev_hash, self.seq = digest, self.seq + 1
        return delivery


def send_outcome(loop_id, run_id, output_sha256, metric_id, value, outcome_id):
    return send(lambda: {"type": "outcome", "loopId": loop_id, "runId": run_id,
                         "outputSha256": output_sha256, "metricId": metric_id,
                         "value": value, "outcomeId": outcome_id})[1]
```
