Introducing a new way to review your PRs.

Read the announcement

sheeki03 / tirith

Terminal security for developers and AI agents. Intercepts homograph URLs, pipe-to-shell, ANSI injection, obfuscated payloads, data exfiltration, and malicious AI skills/configs before they execute.

View on GitHub

19 documents · Updated Nov 23, 2026

docs / agent-context-and-prompt-safety

Agent context and prompt safety

Tirith adds caller context and content safety signals to command checks used by AI agents. It identifies the likely caller, resolves the operational target, compares a stated intent with command behavior, scans agent-facing content for prompt attacks, and keeps signed command claims separate from enforcement. It also helps operators detect unsafe changes to AI configuration files. These signals feed verdicts, warnings, audit records, and agent-readable responses, but caller identity and cloud context remain operator-trust signals rather than authentication.

Caller origin

The caller origin describes who Tirith believes initiated an analysis. The CLI records this origin on the verdict before policy post-processing, so the same value is available to enforcement and audit consumers. The parent page, Agent and MCP protection, describes how this signal fits with MCP traffic; MCP gateway and content controls covers MCP request and response handling.

Origin categories

The origin model uses a closed set of categories. A category can include a caller-claimed name or version, but the category itself cannot be invented through an environment variable.

CategoryMain signalMeaning
agentTIRITH_INTEGRATIONAn AI coding tool identifies itself.
mcpMCP initialize.clientInfoAn MCP client identifies itself.
ciNamed CI variables or CIA CI runner is detected.
humanInteractive flag or terminal checkNo stronger caller signal is present.
gatewayGateway request pathTirith is acting as a gateway.
ideReserved categoryAn IDE origin can be represented, but current IDE integrations use the agent path.

The CLI gives explicit agent identification priority over CI detection. If neither is present, it records a human origin with the interactive state. Names and versions are projected through the public-paste redaction path, sanitized, and bounded before they reach logs or terminal output. This protects observability data from secret and control-byte leakage, but it does not prove that the named tool is really the caller.

References: crates/…/agent_origin.rs• L36-94 crates/…/agent_origin.rs• L146-181 crates/…/agent_origin.rs• L282-355 crates/…/agent_origin.rs• L384-412

Origin policy decisions

Agent policy rules let an operator allow or deny an origin category or a caller-claimed name. A deny match forces a Block verdict and adds an AgentDeniedByPolicy finding. A matching allow entry does not reduce a warning or remove an existing block, so the origin policy can tighten trust but cannot override command findings.

The decision order is deny first, then allow, then unspecified. A missing origin is unspecified. The tirith agent current, sessions, explain, policy init, allow, and block commands make these decisions visible or produce policy snippets, while the snippets do not change policy files by themselves. This keeps a trust change under operator review.

The origin is caller-claimed. A process running as the same user can set the environment or client metadata used to produce it. Use origin rules for governance and separation of expected callers, not as a hostile-process boundary.

References: crates/…/policy.rs• L596-654 crates/…/escalation.rs• L391-451 crates/…/agent.rs• L856-1032 crates/…/check.rs• L224-230 crates/…/check.rs• L347-353

Operational context

Operational context connects a command to the cloud or cluster target it will affect. Tirith detects the active context for Kubernetes, AWS, Google Cloud, and Azure, then compares the result with operator labels such as critical, production, or staging.

Context sources

Each provider produces a small context name rather than reading credentials. Kubernetes uses the current kubeconfig context. AWS uses the selected profile. Google Cloud combines the active account and project when both exist. Azure uses the active subscription name or ID.

The detector runs only when relevant to the command or when the operator requests a status view. It bounds cloud CLI calls and caches results for a short period. Changes to relevant environment values or configuration files invalidate the cached view. Changes to provider selection also clear the cache before the next command. This keeps checks responsive without allowing a recent context switch to remain hidden for the full cache period.

Command-scoped selectors take precedence over the process's ambient context. If a command selects an explicit profile, project, kubeconfig, or subscription, Tirith evaluates that target. If it cannot resolve the selected target safely, it reports incomplete analysis rather than silently using a different default.

Context helpers must also come from a trusted executable source. A missing helper means that no provider signal is available. A shadowed or failed helper is an operational detection failure, not permission to use an unverified result.

References: crates/…/context_detect.rs• L1-30 crates/…/context_detect.rs• L117-145 crates/…/context_detect.rs• L217-313 crates/…/context_detect.rs• L514-576

Context guard

The context guard is enabled by policy and only acts when labels exist for the command's provider. It classifies a provider command as read-only, write, destructive, or credential-changing. A labeled critical context then produces a finding for write or higher-impact work, with destructive and credential changes treated as high severity.

The guard also handles context-changing commands. It does not warn against the old context after a command changes the provider selection, and it clears cached context so the next command uses the new selection. An unknown command shape or an unsafe wrapper resolution produces an AnalysisIncomplete finding when a labeled provider may be involved. This prevents an ambiguous command from passing as safe merely because Tirith could not classify it.

The operator can inspect detected contexts with tirith context status, enable or disable the guard, and assign labels at user or repository scope. Labels are declarations of the operator's environment. They are not proof supplied by the cloud provider.

flowchart LR
    C[Cloud or cluster command] --> S[Resolve explicit selectors]
    S --> A[Find active provider context]
    A --> L[Compare with context labels]
    L --> V{Critical label and mutating action?}
    V -- No --> P[Continue normal verdict]
    V -- Yes --> F[Context finding]
    S -- Cannot resolve safely --> I[Analysis incomplete finding]

References: crates/…/context.rs• L1-40 crates/…/context.rs• L42-170 crates/…/context.rs• L57-117 crates/…/context.rs• L182-226

Intent handling

Intent handling checks whether a command's high-impact behavior fits a short statement of purpose. It is an advisory view over the same command signals used by the safety engine, so it helps an agent or operator spot a surprising action without changing the command's real security verdict.

Intent comparison

tirith intend recognizes broad intent classes such as install, download, run a script, test, build, format, clean, deploy, and configure. It also maps command findings into behavior groups such as remote-download execution, privilege use, credential or data export, shell-profile writes, package installation, base64 execution, and root shells.

The comparison is deliberately narrow. For example, “install a formatter” can justify a package install, but it does not justify piping an unknown remote script into a shell. An unrecognized intent matches no class, so high-impact command behavior is treated as unjustified. The --explain form shows the matched intent class and the reason for each mismatch.

The result is Info-level and never blocks. Exit status 1 means that the advisory comparison found a mismatch. Agents must still call tirith check for the enforcement verdict.

References: crates/…/intent.rs• L1-13 crates/…/intent.rs• L22-128 crates/…/intent.rs• L131-286 crates/…/intent.rs• L401-470 crates/…/intent.rs• L1-57

Prompt-injection defenses

Prompt-injection defenses inspect text that an agent may read from a tool, log, paste, or streamed process output. They produce findings when content resembles an instruction that tries to replace system rules, change the agent's role, extract hidden instructions, or use a model message delimiter.

Seed detection

The detector uses a built-in set of case-insensitive seed patterns. It separates direct instruction overrides such as “ignore previous instructions” from broader role-override and jailbreak phrases. It also recognizes selected chat-template markers and gated system-prompt extraction phrases. The gates reduce false positives for normal prose while keeping high-signal attack forms visible. For example, conditional role-play prose is allowed unless its continuation carries a jailbreak signal.

Operators can add custom seeds through policy. Custom patterns use the same placeholder and bounded compilation path as built-in seeds. Tirith limits both the number and total source size of custom patterns, and it rejects patterns whose compiled form exceeds the safety budget. Invalid patterns produce safe indexed diagnostics rather than exposing the pattern text or regex error to a CLI or MCP consumer.

The detector scans raw text and bounded normalized forms. Normalization can expose base64 or hex content, confusable characters, invisible-character tricks, spacing changes, or leetspeak. A phrase found only after normalization receives a distinct high-severity obfuscation finding. Oversized encoded candidates produce an analysis-incomplete high finding instead of being treated as clean. This catches common evasion forms, but it does not make arbitrary agent output safe.

References: crates/…/prompt_injection.rs• L1-30 crates/…/prompt_injection.rs• L112-199 crates/…/prompt_injection.rs• L251-296 crates/…/prompt_injection.rs• L329-476 crates/…/prompt_injection_seeds.txt• L1-74

Output scanning

Output scanning runs as a streaming process so a long tool result does not need to remain in full memory. Tirith keeps a bounded overlap between chunks, detects phrases split across boundaries, and deduplicates repeated findings. Finalization checks the retained tail for attacks that arrive at the end of the stream.

Prompt-injection checks are active for agent-facing output and pasted content. Repository file scans do not apply this rule by default because documentation may quote attack phrases as examples. The output path also shares related checks for output-side data exfiltration and terminal deception, so a tool result can be unsafe even when it contains no known prompt seed.

Treat a clean result as “no known signal,” not as proof that the content is trustworthy. Encoded or paraphrased attacks can evade a seed corpus, and agents should keep external content separate from instructions.

References: crates/…/engine.rs• L646-721 crates/…/engine.rs• L723-833 crates/…/engine.rs• L887-932 crates/…/engine.rs• L2776-2825

Command cards

Command cards are signed attestations about a command. They let a maintainer state the command or a privacy-safe command binding, expected domains, possible writes, script hash, sudo need, and expiry so a user can compare the command with a trusted published claim.

Card trust

Cards use Ed25519 signatures and operator-installed public keys. A card verifies only when its signature uses the supported algorithm, its key is trusted, its signed content is intact, its schema is semantically valid, and its expiry is current. Unknown card fields are rejected so unsigned data cannot sit outside the signed claim.

New privacy-safe cards bind the exact command to a shell dialect with a domain-separated digest instead of retaining the raw command. Legacy cards remain readable for older attestations. Web3-capable cards add exact network, policy, signer, operation, destination, and artifact bindings; they must not carry raw private or interactive signer material. A legacy card can remain useful for diagnostics, but it cannot authorize a Web3 operation without the newer exact bindings.

Cards can be supplied as a local sidecar or through a leading # tirith-card: marker. The marker is metadata only in supported shells and is removed from the command before comparison. A URL in that marker is only a reference during tirith check; the check path never fetches it. The operator must fetch it explicitly before local verification. This keeps remote I/O out of the command safety hot path.

References: crates/…/command_card.rs• L58-142 crates/…/command_card.rs• L175-235 crates/…/command_card.rs• L248-311 crates/…/command_card.rs• L490-565 crates/…/command_card.rs• L764-785 crates/…/command_card.rs• L1090-1148

Card outcomes

Card verification is attestation-only for ordinary command checks. A valid card for the exact command adds an Info verification finding, but it does not suppress a warning or turn a blocked command into an allowed one. A trusted card for a different command or shell produces a high-severity mismatch. An unsigned, expired, untrusted, malformed, unreadable, or remote-only card produces an Info unverified note and the command is evaluated as if it had no card.

Exact Web3 approval is stricter than ordinary card verification. The verified card must match the runtime shell, network, policy identity, signer set, operation order, destinations, and artifact hashes. Any mismatch prevents the card from authorizing that operation.

The engine strips only the leading card marker before comparing the command. It preserves command content and treats a marker inside a command body as content. For cmd, the marker is not treated as metadata because # can be part of a real command. This keeps the attested command aligned with the shell that will execute it.

References: crates/…/command_card.rs• L617-705 crates/…/command_card.rs• L805-927 crates/…/command_card.rs• L1293-1404 crates/…/command_card.rs• L327-477

AI configuration safeguards

AI configuration safeguards help an operator detect and isolate changes to files that shape an agent's behavior. They use the existing AI-file scan results rather than creating a separate detection model, then make a trusted baseline and later drift visible.

Configuration drift

tirith ai scan checks the repository's AI-facing configuration surface. tirith ai explain-config identifies a recognized tool configuration and describes the capabilities or risks signaled by its content. These views help an operator understand what an agent may be instructed or allowed to do before accepting a change.

tirith ai snapshot --update records a last-known-safe baseline only after each file is read and scanned consistently. It refuses to bless High-or-higher findings unless the operator uses --force, and it refuses to record a file that could not be scanned or changed during the scan. tirith ai diff compares the current configuration with the repository-specific baseline and reports added, removed, or changed instruction content together with new risk findings.

References: crates/…/ai.rs• L121-139 crates/…/ai.rs• L183-342 crates/…/ai.rs• L1125-1148 crates/…/ai.rs• L1214-1348

Configuration quarantine

tirith ai quarantine gives an operator a controlled way to isolate a suspected AI configuration file. The default action copies the file and leaves the original untouched. The destructive --move action requires confirmation and keeps the original when it cannot prove that the source remained the same during the operation.

The quarantine result includes the destination, content hash, and restore command. The store uses restrictive access and non-clobbering names, so an isolation action does not silently overwrite earlier evidence. Human-facing error and status text is sanitized because file names and file content can carry terminal-control characters.

References: crates/…/ai.rs• L477-575 crates/…/ai.rs• L578-751 crates/…/ai.rs• L753-879 crates/…/ai.rs• L907-1003 crates/…/ai.rs• L1422-1499

Warning mechanisms

Warnings give agents and operators a durable view of why commands or content need attention. The immediate verdict controls the current action. Session state, approval prompts, escalation, and warning displays add context without weakening a block.

Verdict and acknowledgement

The command check produces an action from its findings and then applies caller policy, approvals, paranoia filtering, and escalation. Interactive strict-warn mode can ask a human to acknowledge a warning. Non-CLI callers cannot answer a prompt, so a required approval becomes a block. This prevents an agent or gateway from treating an unanswered human step as consent.

An agent-facing finding can include a concise refusal or context message. For example, a critical-context finding explains the target and action category, while an agent policy denial explains that the caller origin matched a deny rule. These messages support safe recovery without pretending that a warning is an approval.

References: crates/…/verdict.rs• L1127-1154 crates/…/escalation.rs• L453-514 crates/…/escalation.rs• L621-671 crates/…/check.rs• L578-640 crates/…/check.rs• L815-830

Session warnings

Session warnings retain recent warning events and hidden lower-severity findings for the current session. They support repeat-count escalation, per-rule cooldowns, summaries, and later inspection with tirith warnings. Repeated warning display can collapse noise, but it does not change the stored verdict, exit code, audit entry, approval state, or block action.

The session also keeps a bounded event history for cross-command patterns. A repeated or combined pattern can trigger a blocking escalation even when each individual command would have produced only a warning. Session writes are best-effort for presentation and accounting; enforcement must not become an allow decision because warning history could not be saved.

sequenceDiagram
    participant A as Agent or shell
    participant T as Tirith check
    participant S as Session warning state
    participant O as Operator
    A->>T: Submit command or tool action
    T->>T: Detect findings and apply origin/context policy
    T->>S: Read recent warning history
    S-->>T: Counts and correlation view
    T-->>A: Allow, warn, acknowledgement, or block
    T->>S: Record visible and hidden warning history
    O->>S: Review with tirith warnings

References: crates/…/session_warnings.rs• L34-114 crates/…/session_warnings.rs• L136-183 crates/…/session_warnings.rs• L407-461 crates/…/session_warnings.rs• L617-725 crates/…/warnings.rs• L21-118

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep every producer of caller metadata aligned with the closed AgentOrigin categories and the caller-trust warning. A new integration must not look like authentication.
  • Keep origin stamping before agent policy and audit processing. A late stamp can make the enforced caller differ from the recorded caller.
  • Keep origin labels projected through the redaction and terminal-safe path before they enter audit, JSON, or human output.
  • Keep command-scoped provider selectors ahead of ambient context detection. Otherwise an explicit production target can be checked against the wrong profile or context.
  • Keep provider helper provenance and timeout failures fail-closed. A missing or shadowed helper must not become a trusted context result.
  • Keep prompt seed compilation and policy validation on the same path. A pattern accepted by validation but rejected at runtime silently removes a stated defense.
  • Keep custom seed count, source, and compiled-size budgets aligned across policy and runtime diagnostics. Rejected patterns must remain visible without exposing their source text.
  • Keep streaming output scans aligned between chunk processing and finalization. Changes to the retained overlap must preserve matches that cross chunk boundaries.
  • Keep command-card schema fields inside the signed claim. Privacy-safe command matching must use the runtime shell, and verified cards must not suppress independent findings.
  • Keep Web3 card approval comparisons exact across shell, network, signer, policy, operation, destination, and artifact bindings. A legacy diagnostic card must not become an authorization token.
  • Keep warning presentation separate from enforcement. Cooldowns and hidden-finding views may reduce noise, but they must not remove blocks or alter exit actions.
  • Keep AI snapshot validation tied to the exact bytes that are recorded. A file that changes during scanning or cannot be scanned must not become a trusted baseline.

Important failure modes

TriggerConsequenceGuard
A process sets TIRITH_INTEGRATION or MCP client metadata to a trusted nameOrigin policy may classify a hostile same-user process as an expected callerTreat origin as operator-trust and layer execution or host controls for hostile-process threats
A caller includes secrets or terminal controls in its claimed name or versionAudit or display data can leak the secret or alter terminal outputProject through the public-paste redaction path, sanitize control and invisible characters, and bound the value
A command selects a provider context that cannot be resolved safelyThe command receives an analysis-incomplete high finding instead of falling back to ambient stateKeep explicit selectors authoritative and fail closed on unresolved values
A provider helper is shadowed on PATH or times outContext detection cannot safely establish the active targetResolve helpers by trusted provenance, enforce a hard timeout, and surface a detection failure
Prompt text is encoded or paraphrased without a known seedSeed detection can miss the attackTreat all agent output as untrusted even when no prompt finding fires
A custom seed exceeds a count, source, or compiled-size budgetThe seed is not active, while a careless diagnostic could leak policy contentReject it with an indexed categorical diagnostic and review the policy result
A signed card names a different command, shell, network, signer, or operationThe card is a high-severity mismatch or cannot authorize the operationVerify trust, expiry, exact shell-aware command binding, and all required semantic bindings
A card carries raw signer material or an old schema is used for Web3 approvalThe card cannot safely represent the approval and must not authorize itRefuse secret-bearing bindings and require privacy-safe exact Web3 bindings
Repeated warnings are collapsed in displayThe screen shows less detail while the underlying verdict remains unchangedInspect tirith warnings; do not use display suppression as an enforcement result
A file changes while tirith ai snapshot --update scans itThe baseline could bless bytes that were not validatedCompare the content before and after the scan and abort the update on a change
tirith ai quarantine --move cannot confirm or safely preserve the sourceThe original could be deleted or evidence could be overwrittenRequire confirmation, reserve a destination, and retain the original when the safety check fails

Key files

FileWhy to read it
crates/…/agent_origin.rsDefines caller categories, precedence, redaction, sanitization, and the trust boundary.
crates/…/policy.rsDefines origin matching and context-related policy data.
crates/…/context_detect.rsExplains the supported provider context signals, helper trust, cache behavior, and failure states.
crates/…/context.rsShows how labeled contexts become command findings.
crates/…/intent.rsDefines the advisory intent-versus-command comparison.
crates/…/prompt_injection.rsDefines raw, normalized, custom-seed, and bounded prompt-injection detection.
crates/…/prompt_injection_seeds.txtShows the built-in prompt-injection seed families and their false-positive gates.
crates/…/command_card.rsDefines card trust, privacy-safe exact matching, schema rules, and attestation outcomes.
crates/…/engine.rsShows where output, context, and card signals enter analysis.
crates/…/escalation.rsShows the order of agent policy, approval, escalation, and warning effects.
crates/…/session_warnings.rsDefines persistent warning history and cross-command correlation.
crates/…/aifile.rsDefines the AI-facing file risk signals used by repository scans and snapshots.
crates/…/check.rsShows CLI origin stamping and the user-facing verdict flow.
crates/…/agent.rsShows origin inspection and policy scaffold commands.
crates/…/context.rsShows context status, guard, and label workflows.
crates/…/intent.rsShows the advisory intent command and its output contract.
crates/…/command_card.rsShows card creation, signing, verification, migration, and explicit fetch behavior.
crates/…/ai.rsShows AI-config scanning, drift snapshots, and quarantine workflows.
crates/…/warnings.rsShows warning summaries, hidden findings, and session review output.