Module contents
Stage 5 of 9Advanced 100 min

Tools, calling protocol and sandboxed execution

Design the agent's tools for corpus search, reading a chunk, arXiv search, and Python execution with JSON schemas, argument validation, and informative errors. Isolate code execution with time, memory, working-directory, and network limits and test it with hostile code.

After this lesson you can

  • Define tools with JSON schemas and descriptions that a small model uses correctly.
  • Implement a call dispatcher with validation, timeouts, and errors returned to the model.
  • Isolate code execution with limits and no access to the network or external files.
  • Measure the local model's valid-call rate with different tool descriptions.

Before you start

When the answer requires an action

Lesson three’s search and lesson four’s cited generation already let us build an answer from passages. Now imagine a request requiring two different searches and a calculation. The model must decide what to request, the program must check it, the tool must run within its own limits, and the result must return to the conversation associated with the correct call. The ability to produce JSON does not authorize an operation or guarantee success.

InteractiveA call makes a round trip

This simulation uses three fictional cards. The buscar tool requires a nonempty query and an integer k from 1 through 5. It matches the query as a case-insensitive substring in the original Spanish cards.

1. Proposed calls
{
  "id": "A",
  "name": "buscar",
  "args": {
    "consulta": "contexto",
    "k": 2
  }
}
{
  "id": "B",
  "name": "buscar",
  "args": {
    "k": 2
  }
}
2. Responses by ID
B: validation error
consulta debe ser una cadena no vacía.

consulta must be a nonempty string.

A: simulated search
[f3] El límite de salida reduce el texto que ocupa

Truncated content: 50 of 74 characters.

The limit truncates the content of successful results only. It preserves the ID, status, truncation flag, and errors. The ID pairs each response with its call regardless of delivery order. The limit counts characters.

50
Delivery order
Calls accepted by the schema1/2
Truncated responses1
This explicit simulation illustrates messages, validation, and result association; it does not run tools or measure the model. Change arguments and output limit and observe what happens when two results return in a different order.

A tool’s interface is part of the learning problem: it describes the operation, inputs, and how to interpret output. Toolformer studies when to call different APIs, with what arguments, and how to incorporate results; printing a function name is not enough. The work fine-tunes a 6.7-billion-parameter GPT-J and its section 3 describes five tools: question answering, Wikipedia search, calculator, calendar, and translation. SWE-agent studies interface design for models navigating and modifying repositories. Neither result demonstrates that our local model will correctly use our tools: that requires measuring custom tasks.

In SWE-agent table 3, for SWE-bench Lite with GPT-4 Turbo, the interface with summarized search solved 18.0% of tasks, versus 12.0% with iterative search and 15.7% without the specific search tool. These are results for that configuration and dataset, not our model’s rates or evidence that more tools always help. The study illustrates why both output form and available catalog should be evaluated.

Call protocol: proposal, execution, and observation

An interaction has an observable sequence. First the application announces a catalog of names, descriptions, and schemas. Then the model returns one or more proposals. Each gets a unique identifier, name, and arguments; the dispatcher decides whether it can execute. Finally the application adds a result message with the matching identifier and lets the model continue. A final answer is another message type and should not be confused with a proposal awaiting execution.

APIs differ in their fields and representations of arguments and results. Some servers offer native calls; others support structured JSON output interpreted by the application as a proposal. In p05-l01’s constrained output, the local server does not declare tool support for the phi3:mini used there. We can request a structured object and write our own adapter, but that is not proof of native compatibility. The application retains control even when format is correct.

Two independent calls can run in parallel; they are not guaranteed to finish in emission order. Identifier association avoids delivering search B’s answer as if it belonged to search A. A call needing another’s result is not independent: it must wait before formulating arguments. A duplicate, missing, or unknown identifier is a protocol error, not an invitation to guess the association. For operations with side effects, a retry after timeout can cause the effect twice: use idempotency keys or a status query and do not retry blindly.

In a trace record execution ID, calls and identifiers, schema version, accepted or rejected arguments, authorization decisions, status, timing, and bounded result. Distinguish text returned to the model from the audit log, which must also minimize and protect sensitive data. Retaining the full sequence reveals whether selection, validation, tool, result reading, or subsequent response failed. Measuring only final text hides those causes.

Small catalog and precise contracts

For the research assistant we propose four separate capabilities. buscar_corpus takes a query and bounded result count and returns IDs and excerpts. leer_fragmento takes an existing ID and returns text and metadata of that version. buscar_arxiv performs an external search with a bounded query and returns metadata with provenance. ejecutar_python accepts code for a calculation in an isolated environment without credentials or network access. Each has its own conditions and limits: an external search may need network access in the trusted process; that does not give the Python executor network access.

A useful description answers four questions: what it does, when to use it, what it needs, and what it returns. “Search the corpus by text and return up to k chunks with identifiers” is more specific than “manage knowledge.” Use stable names, explicit units, and reasonable ranges. If k must be an integer from 1 to 20, specify both bounds; if an empty query makes no sense, prohibit it. A strict schema should reject unknown fields rather than silently discard them when doing so would hide an error. Pydantic documentation describes model validation and extra-field configuration; coercion depends on configuration and version.

Validation has layers. First check for parseable JSON and a registered tool. Then validate types and limits without conversions the interface did not authorize. Next apply semantic and access rules: the chunk belongs to the permitted collection, query stays within budget, and requested operation is appropriate for the user. Finally execute at the corresponding boundary. A string representing a number is not necessarily a permitted integer; in Python, bool is also a subclass of int, so a custom validator must explicitly decide whether to accept True as a number.

Errors are an interface too. Return a stable category and specific correction, for example “field k: expected an integer between 1 and 20,” without secrets, internal traces, or private argument content. Distinguish unknown tool, invalid JSON, invalid argument, access denied, timeout, and execution failure. A transient failure does not become correct by changing arguments; a validation error may be correctable by the model. Limit retries so a useful message does not become an infinite loop.

What the valid-call rate measures

Prepare development tasks with an expected operation and arguments or a deterministic verifier. Freeze task list, catalog, model, template, and decoder. To compare two descriptions, present the same tasks in both conditions and record all proposals, including those that do not parse or call a tool. Selecting only parseable calls can hide many failures in the valid-argument proportion conditional on that subset.

Report correct selection, parseable JSON, valid arguments, authorization, successful execution, and task success separately. The rate of valid arguments among parseable calls answers a different question from valid-call tasks among all scheduled tasks. If aiming to exceed 95% on development, publish denominator, errors, intervals, and case design; that threshold does not turn development examples into an independent test. Repeating deterministic generation does not replace task variation or demonstrate robustness to other templates. The p05-l02 custom evaluation still awaits human review and must not be presented here as verified.

Dispatch without losing control

The dispatcher is an application-controlled table, not a dynamic search for arbitrary functions by name. Its steps are: receive a proposal, check shape, resolve name in registry, validate arguments, check authorization and budget, execute under the appropriate timeout, bound output, and construct a result with the same identifier. Do not evaluate a string as host code to select a function.

A trusted function can run with a client having its own timeout. However, a timeout while waiting for a thread does not guarantee work has ended or cancel a remote operation. Untrusted code needs a boundary that can terminate all its processes and verify cleanup. Calls with side effects should not run in parallel unless order and concurrency are safe. Authorization is checked on the server, not through a description the model promises to obey.

Output needs a double budget: limit what the tool can produce during execution and what reaches model context. Truncating only after collecting unlimited output can exhaust memory before the cut. A truncated result must say so and retain identifier, status, and provenance; do not present an excerpt as the entire document. If cutting bytes, avoid corrupting UTF-8; if limiting tokens, use the model’s real tokenizer. Empty search, error, and a merely truncated response are different states.

If five definitions occupy 100 tokens each and are included in full in each of four steps, cumulative input is 5⋅100⋅4=20005\cdot100\cdot4=2000 tokens. This does not mean the simultaneous context window must hold 2000 tokens: each step has 500 definition tokens in this example. Billable cost and time also cannot be inferred without cache, implementation, and price. The following code verifies the arithmetic; its numbers are teaching assumptions.

[ ]Cumulative definition budgetBrowser
herramientas, tokens_por_definicion, pasos = 5, 100, 4
por_paso = herramientas * tokens_por_definicion
print('tokens por paso:', por_paso)
print('tokens acumulados:', por_paso * pasos)

Isolating Python: process, resources, and privileges

A subprocess allows observing output and terminating a process, but normally inherits its user’s permissions, environment, and file access unless additional mechanisms are configured. Changing working directory does not prevent opening an absolute path; removing Python function names is not an operating-system security boundary. A CPU timeout alone does not block network, file reads, child processes, or memory consumption. Do not run generated code with credentials or a mounted home directory.

One possible architecture uses an ephemeral Linux container with an unprivileged user, read-only root, limited temporary directory, no host mounts or engine socket, no additional capabilities or privilege escalation, and memory and process limits. Supply only needed input and collect bounded output. The none network retains a loopback interface within the container, according to the network driver documentation; the goal is to prevent external network access, not claim no local socket exists. Docker security documentation describes namespaces, control groups, and engine surface. A container shares the host kernel and its configuration matters: for stricter threats consider an isolated, updated virtual machine.

The trusted supervisor must control wall time as well as CPU quotas and terminate the whole container if exceeded. Configure hard memory, process-count, temporary-disk, and output limits; verify on the platform that limits actually apply. Docker resource constraints distinguish memory and swap; options may depend on system configuration. When work ends, verify no processes or containers of that execution remain and remove its ephemeral directory. An executor exception must not open an alternative path that runs code directly on the host.

Trust policy must also cover read and search tools. External output can contain instructions attempting to divert the model; treat it as data, not system instruction. Search or a document does not gain permission to invoke a side-effecting tool by appearing in context. Attack-surface analysis and least privilege are completed in the agent security lesson. Prompt instructions can help behavior, but do not replace permission restrictions enforced outside the model.

A battery is bounded evidence

Before testing potentially harmful code, check actual isolation availability and configuration. If a precondition fails, stop execution and report the result as unevaluated. Never run the battery outside the boundary to obtain a figure. Use only synthetic data and canary files, without private user paths or credentials. Cover time, memory, processes, external test-file access, excessive output, and network access, with observable criteria for each; accompany each negative test with a harmless calculation that should work. Denial differs from harness failure or a test that never ran.

For a battery of 20 attempts, define blocking in advance and count blocked cases, escapes, harness failures, and unexecuted cases. Twenty blocked out of twenty executed supports only that result for that battery and configuration: it does not prove absence of vulnerabilities. Do not use the proportion blocked among cases that did run to hide failed preconditions. A reasonable harness also checks positive utility control: blocking everything, including legitimate calculations, is not useful.

Prepare the local environment

You need a Python environment, Ollama running, and a Linux Docker daemon with cgroup v2 and resource controllers available. On Windows these commands prepare Python in PowerShell and use Docker inside WSL. If you already have an appropriate virtual environment, skip its creation and use its interpreter; pin its dependencies in the project being prepared. Versions shown are those used to verify these cells.

py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install requests==2.34.2 pydantic==2.14.1 pytest==9.2.0
ollama pull qwen2.5:3b-instruct
wsl --exec docker pull python@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f
wsl --exec docker image inspect python@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f --format '{{.Id}}'

On the platform of this run, the last command returns sha256:9e87977b867847e186d066f531ef783b006d582a985c341c269446088d90f2c4, the ID required by the cell. The digest identifies the downloaded reference and local ID identifies the image resolved for the platform: check both, since another architecture may resolve a different image. If the ID differs, stop and verify image and platform before changing code. ollama pull downloads the model; keep the server listening on 127.0.0.1:11434. The cell records the actual model digest and checks declared tool capability, so an updated tag is not automatically confused with the earlier run.

On Linux, use python3 -m venv .venv, install the same packages with .venv/bin/python -m pip, and run Docker commands directly without the wsl --exec prefix. Do not run tests on the host if Docker or its controls are unavailable.

Does the model propose the intended call?

The next cell evaluates two descriptions of the same catalog using qwen2.5:3b-instruct, whose local server declares native tool compatibility. The model used in p05-l01, phi3:mini, does not declare that capability. It needs Ollama with that model downloaded, requests, and Pydantic v2 locally. The 20 tasks per condition are synthetic, literally specify operation and arguments, and always use the short description first and detailed one second. The cell records all proposals and checks one call, stop termination, strict schema, correct name, and exact arguments. Failures count among scheduled tasks. Proposed tools are not executed here.

In one run both variants achieved 20 of 20 complete, structurally valid calls with expected names and arguments; there were no request errors. This simple battery does not establish superiority of either description or generalization to harder tasks. Both conditions use the dispatcher’s same four JSON schemas but do not invoke the dispatcher; it additionally rejects whitespace-only queries as a later semantic rule. The comparison does not evaluate tool result quality or use the custom set awaiting human review. The prompt-evaluation counter is not interpreted as general cost because the server may reuse cache.

[ ]Two descriptions, same callsLocal GPU
"""Dos descripciones, mismas 20 tareas sintéticas fijadas antes de inferir.

No ejecuta herramientas ni usa datos privados. Requiere requests, pydantic v2 y
Ollama local con la etiqueta ya instalada. Fallos cuentan en el denominador.
"""
import hashlib
import json
import os
from pathlib import Path
import tempfile
import time

from pydantic import BaseModel, ConfigDict, Field, ValidationError
import requests

OUT = Path(tempfile.mkdtemp(prefix='atlas-p05-l05-herramientas-'))
print('Directorio de trazas:', OUT, flush=True)
URL = 'http://127.0.0.1:11434'
MODEL = 'qwen2.5:3b-instruct'


class Strict(BaseModel):
    model_config = ConfigDict(extra='forbid', strict=True)


class SearchCorpus(Strict):
    consulta: str = Field(min_length=1, max_length=160)
    limite: int = Field(ge=1, le=5)


class ReadChunk(Strict):
    identificador: str = Field(min_length=1, max_length=64)


class SearchArxiv(Strict):
    consulta: str = Field(min_length=1, max_length=160)
    limite: int = Field(ge=1, le=5)


class RunPython(Strict):
    codigo: str = Field(min_length=1, max_length=300)


REGISTRY = {'buscar_corpus': SearchCorpus, 'leer_fragmento': ReadChunk,
            'buscar_arxiv': SearchArxiv, 'ejecutar_python': RunPython}
SHORT = {'buscar_corpus': 'Buscar.', 'leer_fragmento': 'Leer.',
         'buscar_arxiv': 'Buscar.', 'ejecutar_python': 'Ejecutar.'}
DETAILED = {'buscar_corpus': 'Busca en los fragmentos del corpus local. Recibe consulta y limite de 1 a 5. No busca en arXiv.',
            'leer_fragmento': 'Lee un fragmento del corpus local por su identificador exacto. No busca documentos.',
            'buscar_arxiv': 'Busca trabajos en arXiv por consulta y limite de 1 a 5. No busca en el corpus local.',
            'ejecutar_python': 'Ejecuta código Python inocuo con resultado de texto. Recibe el código exacto en codigo.'}

# Etiquetas y argumentos se congelan aquí antes de observar ninguna salida.
TASKS = []
for term, limit in [('attention',1),('graph neural networks',2),('quantization',3),('retrieval augmented generation',4),('diffusion models',5)]:
    TASKS.append({'prompt': f'Busca en mi corpus local exactamente la consulta «{term}» y devuelve como máximo {limit} resultados.',
                  'tool': 'buscar_corpus', 'arguments': {'consulta':term,'limite':limit}})
for identifier in ['paper-001#p4','paper-017#p2','notes-03#s1','paper-042#p8','notes-12#s3']:
    TASKS.append({'prompt': f'Lee el fragmento de mi corpus con identificador exacto «{identifier}».',
                  'tool': 'leer_fragmento', 'arguments': {'identificador':identifier}})
for term, limit in [('transformer',1),('language models',2),('contrastive learning',3),('neural information retrieval',4),('monte carlo tree search',5)]:
    TASKS.append({'prompt': f'Busca en arXiv exactamente la consulta «{term}» y devuelve como máximo {limit} resultados.',
                  'tool': 'buscar_arxiv', 'arguments': {'consulta':term,'limite':limit}})
for code in ['print(2 + 3)','print(6 * 7)','print(12 // 4)','print(5 ** 2)','print(9 - 4)']:
    TASKS.append({'prompt': f'Ejecuta exactamente este código Python inocuo: {code}',
                  'tool': 'ejecutar_python', 'arguments': {'codigo':code}})


def tools_for(descriptions):
    return [{'type':'function','function':{'name':name,'description':descriptions[name],
             'parameters':cls.model_json_schema()}} for name, cls in REGISTRY.items()]


def request(payload):
    for attempt in range(3):
        try:
            response = requests.post(URL+'/api/chat', json=payload, timeout=(5,180))
            if response.status_code >= 400 and 'out of memory' in response.text.lower() and attempt < 2:
                time.sleep(90)
                continue
            response.raise_for_status()
            return {'response':response.json(),'attempts':attempt+1}
        except (requests.RequestException, ValueError) as exc:
            return {'error':f'{type(exc).__name__}: {exc}', 'attempts':attempt+1}


def evaluate(item, raw):
    if 'error' in raw:
        return {'complete':False,'structure_valid':False,'selected_correctly':False,'arguments_exact':False,'success':False,'reason':'transport_or_server_error'}
    complete = raw['response'].get('done') is True and raw['response'].get('done_reason') == 'stop'
    message = raw['response'].get('message',{})
    calls = message.get('tool_calls') or []
    if len(calls) != 1:
        return {'complete':complete,'structure_valid':False,'selected_correctly':False,'arguments_exact':False,'success':False,'reason':'expected_one_call'}
    fn = calls[0].get('function',{})
    name, args = fn.get('name'), fn.get('arguments')
    chosen = name == item['tool']
    try:
        if name not in REGISTRY:
            raise ValueError('tool desconocida')
        parsed = REGISTRY[name].model_validate(args)
        structurally_valid = True
        exact = chosen and parsed.model_dump() == item['arguments']
        reason = 'ok' if exact else 'wrong_tool_or_arguments'
    except (ValidationError,ValueError,TypeError) as exc:
        structurally_valid = False
        exact = False
        reason = str(exc)
    return {'complete':complete,'structure_valid':structurally_valid,'selected_correctly':chosen,'arguments_exact':exact,
            'success':complete and structurally_valid and exact,'reason':reason if complete else 'incomplete'}


def main():
    info = requests.post(URL+'/api/show',json={'model':MODEL},timeout=20).json()
    if 'tools' not in info.get('capabilities', []):
        raise RuntimeError('El servidor no declara soporte de herramientas para esta etiqueta')
    tags = requests.get(URL+'/api/tags',timeout=20).json()
    matches = [x for x in tags['models'] if x['name']==MODEL]
    if len(matches)!=1:
        raise RuntimeError('No se encontró la etiqueta local exacta')
    specs = {'model':MODEL,'model_digest':matches[0]['digest'],'model_show':info,
             'tasks':TASKS,'tools_short':tools_for(SHORT),'tools_detailed':tools_for(DETAILED),
             'rule':'finalización stop; una llamada; estructura Pydantic estricta; nombre correcto y argumentos exactos; 20 tareas por condición',
             'options':{'temperature':0,'seed':42,'num_ctx':2048,'num_predict':160},
             'request_order':'cada tarea: corta y después detallada; no aleatorizada'}
    specification = json.dumps(specs, ensure_ascii=False,indent=2)+'\n'
    (OUT/'protocolo-fijado.json').write_text(specification,encoding='utf-8',newline='\n')
    print('PROTOCOLO',OUT,hashlib.sha256((OUT/'protocolo-fijado.json').read_bytes()).hexdigest(),flush=True)
    rows = []
    for i,item in enumerate(TASKS):
        for condition, tool_defs in [('breve',specs['tools_short']),('detallada',specs['tools_detailed'])]:
            payload = {'model':MODEL,'stream':False,'messages':[{'role':'system','content':'Usa exactamente una herramienta para cumplir la petición.'},{'role':'user','content':item['prompt']}],
                       'tools':tool_defs,'options':specs['options'],'keep_alive':'30s','truncate':False,'shift':False}
            raw = request(payload)
            judgement = evaluate(item,raw)
            row = {'task_index':i,'condition':condition,'request':payload,'result':raw,'evaluation':judgement}
            rows.append(row)
            with (OUT/'peticiones.jsonl').open('a',encoding='utf-8',newline='\n') as f:
                f.write(json.dumps(row,ensure_ascii=False)+'\n')
            print(i,condition,judgement['reason'],flush=True)
    summary = {}
    for condition in ('breve','detallada'):
        subset = [r for r in rows if r['condition']==condition]
        summary[condition] = {'planned':20,'rows':len(subset),
            **{key:sum(r['evaluation'][key] for r in subset) for key in ('complete','structure_valid','selected_correctly','arguments_exact','success')},
            'errors':sum('error' in r['result'] for r in subset),
            'prompt_eval_count':sum(r['result'].get('response',{}).get('prompt_eval_count',0) for r in subset),
            'eval_count':sum(r['result'].get('response',{}).get('eval_count',0) for r in subset)}
    (OUT/'resumen.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
    print(json.dumps(summary,ensure_ascii=False,indent=2),flush=True)


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Registry and isolated execution

This cell combines the battery and an operational four-tool dispatcher. It requires local Python, Pydantic v2, and pytest; on Windows use Ubuntu WSL with the Docker daemon available. The process-limit test needs cgroup v2 with the relevant controller. The Python image must be downloaded before running and match the ID and digest recorded in code: it is not automatically downloaded. Also check that Docker applies memory, process, and CPU limits in your environment. Results are written to a new temporary folder whose path is printed, independent of files from earlier runs.

The sandbox starts with network=none, read-only root filesystem, unprivileged user, removed capabilities, bounded temporary directory, and resource limits. The deadline includes creation, sending code, and waiting for the process; cleanup is supervised separately and infrastructure failure requires operator review. Output retained by the client is limited and daemon logging is disabled. Pytest checks criteria on raw results of that same run; it is not a second independent battery.

In one run of this configuration the criteria were met for 20 selected controls and three positive controls for calculation, temporary writing, and loopback; no escapes, inconclusive, or pending cases were observed. The bounded process test recorded limit 32, an event-counter increase from 0 to 1, and errno 11, corresponding to EAGAIN on that system. This tests those cases, not a security certificate or evidence about arbitrary code. If infrastructure fails, the cell retains a partial result with the inconclusive case and unexecuted ones and stops. An earlier repeat with a shorter memory-test deadline left one case inconclusive; only the observation deadline for memory controls was extended, keeping the 128 MiB limit. Rejection when attempting to write beyond /tmp size appeared as a system error; the code does not identify its specific cause. Interfaces and routes are inspected without turning that observation into exhaustive connectivity testing.

Search and reading use two fictional cards by default. To connect chunks generated in p05-l02, set P05_L05_CHUNKS to the chunks.jsonl path produced there before running the cell. The loader retains ID, document, strategy, split, ranges, and sources and prints the file fingerprint; that fingerprint alone does not verify the original manifest. Search is an in-memory substring match, not p05-l03 hybrid retrieval or index. The custom question set still awaits human review. The arXiv tool queries a fixed URL in a trusted process with time and size limits; it can fail from network or service unavailability. The Python tool runs only inside the container. If isolation or cleanup cannot be confirmed, dispatch stops accepting new Python executions pending review; a timeout of a clean execution returns an error. For corpus results, the limit keeps IDs and metadata intact for every included chunk, trims text, and marks omitted chunks. If even one chunk’s provenance does not fit, it returns an error. The default 2048 characters limit the content field; the envelope with ID and status is additional and ID is also bounded. For other tools, truncating the serialized string may leave incomplete JSON and is explicitly marked.

[ ]Defensive battery and tool dispatcherLocal GPU
"""Prueba defensiva acotada de una frontera Docker, no una garantía universal.

En Windows requiere WSL Ubuntu con daemon Docker accesible y la imagen indicada
ya descargada. No se montan carpetas del anfitrión ni se transmite su entorno.
Los 20 casos son controles seleccionados por el autor, no intentos exhaustivos.
"""
import hashlib
import errno
import json
import os
from pathlib import Path
import subprocess
import tempfile
import threading
import time
import uuid

OUT = Path(tempfile.mkdtemp(prefix='atlas-p05-l05-sandbox-'))
print('Directorio de trazas:', OUT, flush=True)
CANARY = OUT / 'canario-sintetico.txt'
CANARY.write_text('CANARIO-PUBLICO-P05-L05', encoding='utf-8')
IMAGE = 'sha256:9e87977b867847e186d066f531ef783b006d582a985c341c269446088d90f2c4'
DOCKER = ['wsl', '--exec', 'docker'] if os.name == 'nt' else ['docker']
try:
    canary_linux = subprocess.check_output(['wsl', '--exec', 'wslpath', '-a', str(CANARY)], text=True, timeout=10).strip() if os.name == 'nt' else str(CANARY)
    precondition_error = None
except (OSError, subprocess.SubprocessError) as exc:
    canary_linux = ''
    precondition_error = repr(exc)


def run_code(code, timeout=4, output_cap=8192):
    if len(code.encode('utf-8')) > 4096:
        raise ValueError('Código demasiado largo para esta demostración')
    name = 'atlas-p05-l05-' + uuid.uuid4().hex
    args = DOCKER + ['create', '--pull', 'never', '--name', name, '--network', 'none', '--log-driver', 'none',
                     '--memory', '128m', '--memory-swap', '128m', '--pids-limit', '32',
                     '--cpus', '0.5', '--read-only', '--tmpfs', '/tmp:rw,nosuid,nodev,noexec,size=8m',
                     '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges=true',
                     '--user', '65534:65534', '--workdir', '/tmp', '-i', IMAGE, 'python', '-I', '-']
    begin = time.monotonic()
    deadline = begin + timeout
    buffers = [bytearray(), bytearray()]
    discarded = [0, 0]

    def drain(stream, index):
        while True:
            block = stream.read(4096)
            if not block:
                return
            take = min(len(block), max(0, output_cap - len(buffers[index])))
            buffers[index].extend(block[:take])
            discarded[index] += len(block) - take

    timed_out = False
    process = None
    container_id = None
    readers = []
    writer = None
    writer_errors = []
    oom_killed = False
    try:
        # create no ejecuta el código. Se conserva el ID antes de start. Si la
        # creación agota tiempo, el daemon podría terminarla tras la inspección:
        # no ejecutar código y exigir revisión manual de los objetos del daemon.
        created = subprocess.run(args, capture_output=True, timeout=max(0.001, deadline - time.monotonic()), check=True)
        container_id = created.stdout.decode('ascii').strip()
        if len(container_id) != 64 or any(c not in '0123456789abcdef' for c in container_id):
            raise RuntimeError('Docker no devolvió un identificador válido')
        process = subprocess.Popen(DOCKER + ['start', '-a', '-i', container_id],
                                   stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        readers = [threading.Thread(target=drain, args=(stream, i), daemon=True)
                   for i, stream in enumerate((process.stdout, process.stderr))]
        for reader in readers:
            reader.start()

        def write_input():
            try:
                process.stdin.write(code.encode('utf-8'))
                process.stdin.close()
            except (OSError, ValueError) as exc:
                writer_errors.append(repr(exc))

        writer = threading.Thread(target=write_input, daemon=True)
        writer.start()
        try:
            process.wait(timeout=max(0.001, deadline - time.monotonic()))
        except subprocess.TimeoutExpired:
            timed_out = True
        if not timed_out:
            inspected_state = subprocess.run(DOCKER + ['inspect', '--format', '{{json .State}}', container_id],
                                             capture_output=True, text=True, check=True, timeout=15)
            oom_killed = bool(json.loads(inspected_state.stdout)['OOMKilled'])
    finally:
        # Terminar el cliente primero, retirar el ID y comprobar que no persiste.
        cleanup_errors = []
        if process is not None:
            try:
                if process.poll() is None:
                    process.kill()
            except (OSError, subprocess.SubprocessError) as exc:
                cleanup_errors.append('no se pudo terminar cliente: ' + repr(exc))
        target = container_id or name
        removed = False
        for attempt in range(2):
            try:
                subprocess.run(DOCKER + ['rm', '-f', target], capture_output=True, timeout=15)
                inspected = subprocess.run(DOCKER + ['inspect', target], capture_output=True, timeout=15)
                if inspected.returncode != 0 and b'No such' in inspected.stderr:
                    removed = True
                    break
                cleanup_errors.append('inspección no confirma ausencia: ' + inspected.stderr.decode('utf-8', 'replace'))
            except (OSError, subprocess.TimeoutExpired) as exc:
                cleanup_errors.append(repr(exc))
        if process is not None:
            try:
                process.wait(timeout=10)
            except (OSError, subprocess.SubprocessError) as exc:
                cleanup_errors.append('cliente no confirmado terminado: ' + repr(exc))
        if writer is not None:
            writer.join(timeout=10)
            if writer.is_alive():
                cleanup_errors.append('escritura de stdin no terminada')
        for reader in readers:
            reader.join(timeout=10)
            if reader.is_alive():
                cleanup_errors.append('lectura de salida no terminada')
        if not removed or cleanup_errors:
            raise RuntimeError('Limpieza no confirmada; fallo de infraestructura: ' + repr(cleanup_errors))
    if writer_errors and not timed_out:
        raise RuntimeError('Error al escribir el código: ' + repr(writer_errors))
    return {'exit': process.returncode, 'timeout': timed_out, 'oom_killed': oom_killed,
            'stdout': bytes(buffers[0]).decode('utf-8', 'replace'),
            'stderr': bytes(buffers[1]).decode('utf-8', 'replace'),
            'discarded_stdout': discarded[0], 'discarded_stderr': discarded[1],
            'elapsed_seconds': time.monotonic() - begin}


def deny_file(expression):
    return 'from pathlib import Path\np=Path(' + expression + ")\ntry:\n print('FUGA',p.read_text())\nexcept (OSError,UnicodeError):\n print('DENEGADO')"


CASES = [
    ('canario_absoluto', deny_file(repr(canary_linux)), 'denied'),
    ('canario_travesia_absoluta', deny_file(repr('/tmp/..' + canary_linux)), 'denied'),
    ('canario_symlink', "from pathlib import Path\np=Path('/tmp/canario');p.symlink_to(" + repr(canary_linux) + ")\ntry: print('FUGA',p.read_text())\nexcept OSError: print('DENEGADO')", 'denied'),
    ('canario_entorno', "import os; print('FUGA' if os.getenv('P05_L05_SYNTHETIC_CANARY') else 'DENEGADO')", 'denied'),
    ('limite_pids', "import json,os\nfrom pathlib import Path\ndef max_events(): return int(dict(x.split() for x in Path('/sys/fs/cgroup/pids.events').read_text().splitlines())['max'])\nlimite=Path('/sys/fs/cgroup/pids.max').read_text().strip();antes=max_events()\nr,w=os.pipe(); hijos=[]\ntry:\n for i in range(40):\n  try: pid=os.fork()\n  except OSError as e:\n   print(json.dumps({'limite':limite,'eventos_antes':antes,'eventos_despues':max_events(),'errno':e.errno}),flush=True); break\n  if pid==0:\n   os.close(w);os.read(r,1);os._exit(0)\n  hijos.append(pid)\n else: print('FUGA',flush=True)\nfinally:\n os.close(w);os.close(r)\n for pid in hijos: os.waitpid(pid,0)", 'pids'),
    ('canario_mnt', "from pathlib import Path; print('FUGA' if Path('/mnt/c').exists() else 'DENEGADO')", 'denied'),
    ('escritura_usr', "from pathlib import Path\ntry: Path('/usr/p05-l05-test').write_text('prueba');print('FUGA')\nexcept OSError: print('DENEGADO')", 'denied'),
    ('escritura_etc', "from pathlib import Path\ntry: Path('/etc/p05-l05-test').write_text('prueba');print('FUGA')\nexcept OSError: print('DENEGADO')", 'denied'),
    ('escritura_raiz', "from pathlib import Path\ntry: Path('/p05-l05-test').mkdir();print('FUGA')\nexcept OSError: print('DENEGADO')", 'denied'),
    ('montajes_no_usuario', "from pathlib import Path; print('FUGA' if '/mnt/c' in Path('/proc/mounts').read_text() else 'DENEGADO')", 'denied'),
    ('sin_interfaz_externa', "import socket; print('DENEGADO' if set(n for _,n in socket.if_nameindex()) <= {'lo'} else 'FUGA')", 'denied'),
    ('sin_ruta_default', "from pathlib import Path; r=Path('/proc/net/route').read_text().splitlines()[1:];print('FUGA' if any(x.split()[1]=='00000000' for x in r) else 'DENEGADO')", 'denied'),
    ('loopback_sin_servicio', "import socket;s=socket.socket();s.settimeout(0.3);e=s.connect_ex(('127.0.0.1',1));print('DENEGADO' if e else 'FUGA')", 'denied'),
    ('socket_crudo_sin_capacidad', "import socket\ntry: socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_ICMP);print('FUGA')\nexcept OSError: print('DENEGADO')", 'denied'),
    ('lazo_python', "print('INICIO',flush=True)\nwhile True: pass", 'timeout'),
    ('espera_indefinida', "import time\nprint('INICIO',flush=True)\ntime.sleep(60)", 'timeout'),
    ('memoria_192m', "x=bytearray(192*1024*1024);print('FUGA',len(x))", 'resource'),
    ('memoria_256m', "x=bytearray(256*1024*1024);print('FUGA',len(x))", 'resource'),
    ('escritura_tmp_mayor_8m', "from pathlib import Path\ntry: Path('/tmp/limite').write_bytes(b'x'*(12*1024*1024));print('FUGA')\nexcept OSError: print('DENEGADO')", 'denied'),
    ('salida_acotada', "print('x'*100000)", 'capped'),
]


def main():
    rows = []
    controls = {}
    stage = 'precondición'
    current_case = None
    output = {'image_id': IMAGE, 'image_repo_digest': 'python@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f',
              'docker_version': None,
              'network': 'none conserva loopback; se comprueban interfaces y rutas, no conectividad externa',
              'memory_limit_bytes': 128 * 1024 * 1024, 'pids_limit': 32, 'cpus': .5,
              'timeout_seconds': {'resource_or_pids': 10, 'other': 4}, 'timeout_scope': 'creación y ejecución; limpieza adicional con plazo propio',
              'docker_log_driver': 'none', 'stdout_stderr_limit_bytes_each': 8192,
              'controls': controls, 'rows': rows, 'planned': len(CASES),
              'note': 'Solo estos controles acotados. No demuestra seguridad para todo código ni aislamiento de kernel. Un create cuyo cliente agota tiempo puede terminar posteriormente en el daemon: no se inicia código sin ID y el operador debe revisar objetos pendientes.'}
    path = OUT / 'sandbox-resultados.json'
    try:
        if precondition_error:
            raise RuntimeError('No se pudo resolver el canario: ' + precondition_error)
        output['docker_version'] = subprocess.check_output(DOCKER + ['version', '--format', '{{.Server.Version}}'], text=True, timeout=10).strip()
        # Solo canario público; sirve para verificar que no heredamos variables del host.
        os.environ['P05_L05_SYNTHETIC_CANARY'] = 'CANARIO-PUBLICO-P05-L05'
        for label, code, expected in [('python', "print('CONTROL', 40+2)", 'CONTROL 42'),
                                      ('tmp_write', "from pathlib import Path;p=Path('/tmp/control');p.write_text('si');print(p.read_text())", 'si'),
                                      ('loopback', "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print('CONTROL LOOPBACK');s.close()", 'CONTROL LOOPBACK')]:
            stage = 'control positivo: ' + label
            control = run_code(code)
            controls[label] = control
            if control['exit'] != 0 or control['stdout'].strip() != expected or control['timeout']:
                raise RuntimeError('Control positivo falló: ' + label)
        for name, code, expected in CASES:
            current_case, stage = name, 'caso: ' + name
            result = run_code(code, timeout=10 if expected in ('resource', 'pids') else 4)
            if expected == 'denied':
                passed = result['exit'] == 0 and result['stdout'].strip() == 'DENEGADO' and not result['timeout']
            elif expected == 'pids':
                try:
                    proof = json.loads(result['stdout'])
                    passed = (result['exit'] == 0 and not result['timeout'] and proof['limite'] == '32'
                              and proof['errno'] == errno.EAGAIN and proof['eventos_despues'] > proof['eventos_antes'])
                except (ValueError, TypeError, KeyError):
                    passed = False
            elif expected == 'timeout':
                passed = result['timeout'] and result['stdout'].strip() == 'INICIO'
            elif expected == 'resource':
                passed = not result['timeout'] and result['exit'] != 0 and ('MemoryError' in result['stderr'] or result['oom_killed'])
            elif expected == 'capped':
                passed = result['exit'] == 0 and result['discarded_stdout'] > 0 and len(result['stdout'].encode('utf-8')) <= 8192
            else:
                raise ValueError('Criterio desconocido')
            outcome = 'cumplido' if passed else ('escape_observado' if result['stdout'].startswith('FUGA') else 'inconcluso')
            rows.append({'name': name, 'criterion': expected, 'passed': passed, 'outcome': outcome, 'result': result})
            current_case = None
            print(name, passed, flush=True)
        output['status'] = 'completo'
    except Exception as exc:
        output['status'] = 'fallo_infraestructura'
        output['infrastructure_failure'] = {'stage': stage, 'case': current_case, 'exception': repr(exc)}
        raise
    finally:
        output['total'] = len(rows)
        output['passed'] = sum(r['passed'] for r in rows)
        output['failed_criteria'] = len(rows) - output['passed']
        output['escapes_observed'] = sum(r['outcome'] == 'escape_observado' for r in rows)
        output['inconclusive'] = sum(r['outcome'] == 'inconcluso' for r in rows) + int(current_case is not None)
        output['not_run'] = len(CASES) - len(rows) - int(current_case is not None)
        output['not_run_cases'] = [c[0] for c in CASES[len(rows) + int(current_case is not None):]]
        data = (json.dumps(output, ensure_ascii=False, indent=2) + '\n').encode('utf-8')
        path.write_bytes(data)
        print('RESULTADO', output['passed'], '/', output['planned'], 'inconclusos', output['inconclusive'], 'no ejecutados', output['not_run'], 'sha256', hashlib.sha256(data).hexdigest(), flush=True)
    return output


if __name__ == '__main__':
    resultados_sandbox = main()

    # Pytest comprueba los resultados crudos de esta ejecución, sin ejecutar
    # otra batería ni importar un módulo guardado con anterioridad.
    import sys
    import types
    import pytest
    module = types.ModuleType('atlas_l05_resultados')
    module.rows = resultados_sandbox['rows']
    sys.modules[module.__name__] = module
    test_path = OUT / 'test_resultados.py'
    test_path.write_text('''import errno, json, pytest
from atlas_l05_resultados import rows
@pytest.mark.parametrize("row", rows, ids=[r["name"] for r in rows])
def test_criterio(row):
    r, criterion = row["result"], row["criterion"]
    if criterion == "denied":
        assert r["exit"] == 0 and r["stdout"].strip() == "DENEGADO" and not r["timeout"]
    elif criterion == "pids":
        proof = json.loads(r["stdout"])
        assert r["exit"] == 0 and not r["timeout"]
        assert proof["limite"] == "32" and proof["errno"] == errno.EAGAIN
        assert proof["eventos_despues"] > proof["eventos_antes"]
    elif criterion == "timeout":
        assert r["timeout"] and r["stdout"].strip() == "INICIO"
    elif criterion == "resource":
        assert not r["timeout"] and r["exit"] != 0 and ("MemoryError" in r["stderr"] or r["oom_killed"])
    elif criterion == "capped":
        assert r["exit"] == 0 and r["discarded_stdout"] > 0 and len(r["stdout"].encode("utf-8")) <= 8192
    else:
        pytest.fail("Criterio desconocido")
''', encoding='utf-8')
    previous_plugins = os.environ.get('PYTEST_DISABLE_PLUGIN_AUTOLOAD')
    os.environ['PYTEST_DISABLE_PLUGIN_AUTOLOAD'] = '1'
    try:
        exit_code = pytest.main(['-q', '-p', 'no:cacheprovider', str(test_path)])
    finally:
        sys.modules.pop(module.__name__, None)
        if previous_plugins is None:
            os.environ.pop('PYTEST_DISABLE_PLUGIN_AUTOLOAD', None)
        else:
            os.environ['PYTEST_DISABLE_PLUGIN_AUTOLOAD'] = previous_plugins
    if exit_code != 0:
        raise RuntimeError('Pytest detectó al menos un criterio incumplido.')
from pydantic import BaseModel, ConfigDict, Field, ValidationError
import json
import re
import subprocess
import sys


class StrictArgs(BaseModel):
    model_config = ConfigDict(extra='forbid', strict=True)


class SearchCorpus(StrictArgs):
    consulta: str = Field(min_length=1, max_length=160)
    limite: int = Field(ge=1, le=5)


class ReadChunk(StrictArgs):
    identificador: str = Field(min_length=1, max_length=64)


class SearchArxiv(StrictArgs):
    consulta: str = Field(min_length=1, max_length=160)
    limite: int = Field(ge=1, le=5)


class RunPython(StrictArgs):
    codigo: str = Field(min_length=1, max_length=300)


# El corpus por defecto es ficticio; la ruta opcional la proporciona el usuario.
def load_corpus():
    path = os.environ.get('P05_L05_CHUNKS')
    if not path:
        return {'f1': {'id': 'f1', 'text': 'La atención permite relacionar tokens.', 'origin': 'ficticio'},
                'f2': {'id': 'f2', 'text': 'Una búsqueda devuelve pasajes con identificadores.', 'origin': 'ficticio'}}
    with Path(path).open('rb') as source:
        raw = source.read(50 * 1024 * 1024 + 1)
    if len(raw) > 50 * 1024 * 1024:
        raise ValueError('El archivo de fragmentos excede 50 MiB para esta demostración.')
    records = {}
    for line in raw.decode('utf-8').splitlines():
        if not line.strip():
            continue
        item = json.loads(line)
        if not isinstance(item, dict):
            raise ValueError('Cada fragmento debe ser un objeto.')
        ident, text, doc_id = item.get('id'), item.get('text'), item.get('doc_id')
        if (not isinstance(ident, str) or not 1 <= len(ident) <= 64 or ident in records or
            not isinstance(text, str) or not isinstance(doc_id, str) or
            not isinstance(item.get('sources'), list)):
            raise ValueError('Fragmento inválido, identificador duplicado o procedencia ausente.')
        records[ident] = {key: item[key] for key in
                          ('id', 'text', 'doc_id', 'strategy', 'split', 'start', 'end', 'sources')
                          if key in item}
    if not records:
        raise ValueError('El corpus no contiene fragmentos.')
    print('Fragmentos cargados:', len(records), 'SHA-256 del archivo:', hashlib.sha256(raw).hexdigest())
    return records


CORPUS = load_corpus()


def find_local(consulta, limite):
    return [record for record in CORPUS.values()
            if consulta.casefold() in record['text'].casefold()][:limite]


def read_local(identificador):
    if identificador not in CORPUS:
        raise LookupError('Fragmento no encontrado.')
    return CORPUS[identificador]


ARXIV_WORKER = r'''
import json, sys, urllib.parse, urllib.request, xml.etree.ElementTree as ET
class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise ValueError('Redirección no permitida')
args = json.loads(sys.stdin.read())
query = urllib.parse.urlencode({'search_query': 'all:' + args['consulta'],
                                'start': 0, 'max_results': args['limite']})
request = urllib.request.Request('https://export.arxiv.org/api/query?' + query,
                                 headers={'User-Agent': 'AtlasLesson/1.0'})
with urllib.request.build_opener(NoRedirect()).open(request, timeout=5) as response:
    data = response.read(131073)
if len(data) > 131072:
    raise ValueError('Respuesta arXiv supera el límite.')
root = ET.fromstring(data)
ns = {'a': 'http://www.w3.org/2005/Atom'}
print(json.dumps([{'id': e.findtext('a:id', default='', namespaces=ns),
                   'title': e.findtext('a:title', default='', namespaces=ns).strip()}
                  for e in root.findall('a:entry', ns)][:args['limite']]))
'''


def find_arxiv(consulta, limite):
    # La URL está fijada por la aplicación; la consulta se codifica como parámetro.
    result = subprocess.run([sys.executable, '-c', ARXIV_WORKER],
                            input=json.dumps({'consulta': consulta, 'limite': limite}),
                            text=True, encoding='utf-8', capture_output=True,
                            timeout=8, check=True)
    return json.loads(result.stdout)


class SandboxInfrastructureError(Exception):
    pass


SANDBOX_STATE = {'ready': True}


def isolated_python(codigo):
    # run_code es la frontera Docker definida más arriba en esta misma celda.
    if not SANDBOX_STATE['ready']:
        raise SandboxInfrastructureError('Sandbox detenido hasta revisión.')
    try:
        result = run_code(codigo, timeout=4, output_cap=8192)
    except Exception as exc:
        SANDBOX_STATE['ready'] = False
        raise SandboxInfrastructureError('Aislamiento o limpieza no confirmados.') from exc
    if result['timeout']:
        raise TimeoutError('Tiempo límite agotado.')
    if result['exit'] != 0:
        raise RuntimeError('Python terminó con error.')
    return result


REGISTRO = {'buscar_corpus': (SearchCorpus, find_local),
            'leer_fragmento': (ReadChunk, read_local),
            'buscar_arxiv': (SearchArxiv, find_arxiv),
            'ejecutar_python': (RunPython, isolated_python)}


def bounded_corpus(value, limit):
    original = value if isinstance(value, list) else [value]
    included = []
    # Reserva metadatos intactos y marca por fragmento antes de añadir texto.
    for record in original:
        candidate = {key: val for key, val in record.items() if key != 'text'}
        candidate.update({'text': '', 'texto_recortado': bool(record['text'])})
        proposed = included + [candidate]
        envelope = {'fragmentos': proposed, 'omitidos': len(original) - len(proposed)}
        if len(json.dumps(envelope, ensure_ascii=False)) > limit:
            break
        included = proposed
    if original and not included:
        raise ValueError('La procedencia no cabe en el límite de salida.')
    for index, record in enumerate(included):
        source = original[index]['text']
        record['text'] = source
        record['texto_recortado'] = False
        envelope = {'fragmentos': included, 'omitidos': len(original) - len(included)}
        if len(json.dumps(envelope, ensure_ascii=False)) <= limit:
            continue
        record['text'] = ''
        record['texto_recortado'] = True
        low, high = 0, max(0, len(source) - 1)
        while low < high:
            middle = (low + high + 1) // 2
            record['text'] = source[:middle]
            record['texto_recortado'] = True
            envelope = {'fragmentos': included, 'omitidos': len(original) - len(included)}
            if len(json.dumps(envelope, ensure_ascii=False)) <= limit:
                low = middle
            else:
                high = middle - 1
        record['text'] = source[:low]
        record['texto_recortado'] = True
    envelope = {'fragmentos': included, 'omitidos': len(original) - len(included)}
    text = json.dumps(envelope, ensure_ascii=False)
    if len(text) > limit:
        raise ValueError('El límite no permite representar el resultado.')
    return text, bool(envelope['omitidos'] or any(r['texto_recortado'] for r in included))


def despachar(llamada, limite_caracteres=2048):
    if not isinstance(llamada, dict) or set(llamada) != {'id', 'name', 'arguments'}:
        return {'id': None, 'ok': False, 'error': 'Formato de llamada inválido.'}
    ident, name, args = llamada['id'], llamada['name'], llamada['arguments']
    if not isinstance(ident, str) or re.fullmatch(r'[A-Za-z0-9_-]{1,64}', ident) is None:
        return {'id': None, 'ok': False, 'error': 'ID inválido.'}
    if not isinstance(name, str) or name not in REGISTRO:
        return {'id': ident, 'ok': False, 'error': 'Herramienta desconocida.'}
    if not isinstance(args, dict):
        return {'id': ident, 'ok': False, 'error': 'arguments debe ser un objeto.'}
    schema, function = REGISTRO[name]
    try:
        clean = schema.model_validate(args)
    except ValidationError as exc:
        # No reenviar los valores originales ni información interna al modelo.
        fields = set(schema.model_fields)
        errors = [{'campo': e['loc'][0] if e['loc'] and e['loc'][0] in fields else 'campo no permitido',
                   'tipo': e['type']}
                  for e in exc.errors(include_url=False, include_input=False)[:5]]
        return {'id': ident, 'ok': False, 'error': 'Argumentos inválidos.', 'detalles': errors}
    # Regla semántica posterior, adicional al JSON Schema anunciado.
    if name in ('buscar_corpus', 'buscar_arxiv') and not clean.consulta.strip():
        return {'id': ident, 'ok': False, 'error': 'La consulta no puede ser solo espacios.'}
    try:
        value = function(**clean.model_dump())
    except (subprocess.TimeoutExpired, TimeoutError):
        return {'id': ident, 'ok': False, 'error': 'Tiempo límite agotado.'}
    except SandboxInfrastructureError:
        return {'id': ident, 'ok': False, 'error': 'Aislamiento o limpieza no confirmados; requiere revisión del operador.', 'requiere_revision': True}
    except LookupError:
        return {'id': ident, 'ok': False, 'error': 'Fragmento no encontrado.'}
    except Exception:
        return {'id': ident, 'ok': False, 'error': 'La herramienta no pudo completarse.'}
    if name in ('buscar_corpus', 'leer_fragmento'):
        try:
            text, truncated = bounded_corpus(value, limite_caracteres)
        except ValueError:
            return {'id': ident, 'ok': False, 'error': 'Los metadatos no caben en el límite de salida.'}
        return {'id': ident, 'ok': True, 'resultado': text, 'recortado': truncated}
    text = json.dumps(value, ensure_ascii=False)
    return {'id': ident, 'ok': True, 'resultado': text[:limite_caracteres],
            'recortado': len(text) > limite_caracteres}


if __name__ == '__main__':
    # Caso frontera: el contenido completo cabe exactamente en el presupuesto.
    sample = {'id': 'control', 'text': 'Texto con comillas "y acentos áé".'}
    exact = json.dumps({'fragmentos': [{**sample, 'texto_recortado': False}],
                        'omitidos': 0}, ensure_ascii=False)
    result, truncated = bounded_corpus([sample], len(exact))
    assert result == exact and not truncated
    smaller, truncated = bounded_corpus([sample], len(exact) - 1)
    assert len(smaller) <= len(exact) - 1 and truncated
    print('Control de límite exacto: correcto')
    print('búsqueda:', despachar({'id': 'a', 'name': 'buscar_corpus', 'arguments': {'consulta': 'búsqueda', 'limite': 2}}))
    print('lectura:', despachar({'id': 'b', 'name': 'leer_fragmento', 'arguments': {'identificador': next(iter(CORPUS))}}))
    print('rechazo:', despachar({'id': 'c', 'name': 'buscar_corpus', 'arguments': {'consulta': 'x', 'limite': True}}))
    print('python:', despachar({'id': 'd', 'name': 'ejecutar_python', 'arguments': {'codigo': 'print(2 + 3)'}}))
    print('arxiv:', despachar({'id': 'e', 'name': 'buscar_arxiv', 'arguments': {'consulta': 'attention', 'limite': 1}}))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericDefinitions at each step
Eight tool definitions of 150 tokens each are included in twelve requests. How many definition tokens are sent in total, assuming they are resent in full with each request?
QuizChoosing tools
A small model must query a read-only corpus to search texts, read chunks, and inspect metadata. Which interface most directly controls authorized operations?
QuizAn incomplete boundary
A process executing generated code has a CPU time limit but retains user permissions and network. Which statement is correct?
CodeDispatch with useful errors
Implement dispatch(call, registry). call must be a dictionary with name and arguments; registry maps names to (validator, function) pairs. The validator returns None for valid arguments and an error message otherwise. Return {ok: False, error: message} for a malformed call, unknown name, or invalid arguments, without executing the function. If valid, return {ok: True, result: value}; arguments are a dictionary passed with **arguments. Assume registered functions do not raise exceptions. This exercise addresses validation and dispatch, not isolation or authorization.
def dispatch(call, registry):
  pass
Shift+Enter to run
Key idea

A structured call is a proposal. The dispatcher validates and authorizes; isolation limits what code can do; a trace and evaluation with explicit denominators show what happened. None replaces the others.