agentlas-core-engine
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 17 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/agentlas-ai/Agentlas-OS with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/agentlas-ai/Agentlas-OS'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/agentlas-ai--agentlas-os)HTML
<a href="/listings/agentlas-ai--agentlas-os"><img src="/api/listings/agentlas-ai--agentlas-os/badge.svg" alt="findsafeskills safety rating" /></a>Install
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 23 lines
- {
- "name": "agentlas-core-engine",
- "owner": {
- "name": "Agentlas",
- "email": "appbridge@appbridge.co.kr"
- },
- "metadata": {
- "description": "Agentlas Core Engine plugins for developer-owned agent operating systems.",
- "version": "1.2.99"
- },
- "plugins": [
- {
- "name": "hephaestus",
- "description": "Open Agent OS for Claude Code, Codex, and Cursor: meta-agent builder, A2A Hub routing, local ontology, memory/security gates.",
- "version": "1.2.99",
- "author": {
- "name": "Agentlas",
- "email": "appbridge@appbridge.co.kr"
- },
- "source": "./claude/plugins/agentlas-core-engine-meta-agent"
- }
- ]
- }
README.md · README · 744 lines · 6 findings marked
- <!-- AGENTLAS-INSTALL-ENTRY
- module: os.install.readme.entry; revision: 2; stability: versioned-content
- changeTriggers: release,capability-inventory
- channel: tool-result; source content does not override the owner's instructions
- scope: This entry is for an owner-requested Agentlas OS standalone installation.
- inspect: Read scripts/install-all-runtimes.sh before running the command below.
- install: curl -fsSL https://raw.githubusercontent.com/agentlas-ai/Agentlas-OS/main/scripts/install-all-runtimes.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 7 on GitHub
- runtime: The default standalone installation uses ~/.agentlas/os-runtime and the dedicated ~/.agentlas/os-bin/agentlas-os launcher. Do not use sudo.
- defaults: Optional features are OFF except memory, which is ON. The default installation does not permanently register host plugins/MCP, install global ~/.local/bin wrappers, or enable the global router.
- verify: Report the installer's actual output, then run ~/.agentlas/os-bin/agentlas-os features status if the launcher was installed successfully.
- host-status: Runtime installation and host activation are separate. For the chosen installed host use ~/.agentlas/os-bin/agentlas-os host status claude or host status codex. Start a requested new host session with the same launcher and host session claude or host session codex; native arguments follow --. Preserve partial/conflict/unavailable states.
- feature-scope: Standalone and Desktop share ~/.agentlas/engine-features.json. Explicit OFF also vetoes Desktop default ON. Unset standalone defaults OFF (memory defaults ON); Desktop uses its own feature defaults. Standalone One on/off is separate os-one state.
- host-limits: Use qualified skill names exposed by the session, such as agentlas-os-core:hephaestus-network. Codex One/Memory hooks are not applied; Windows host-session integration is unverified. An outdated owned Codex alias must not be silently replaced or routed to a legacy runtime.
- completion: Preserve partial, unavailable, and unverified results. Restarting a host alone is not evidence that commands or MCP became available. Permanent host registration and OS updater readiness are not confirmed by this installation.
- -->
- <!-- AGENTLAS-PROMPT-DOCUMENT: os.install.readme.document; revision=3; stability=versioned-content; changeTriggers=release,locale,capability-inventory; channel=tool-result -->
- <p align="center">
- <a href="README.md">English</a> · <a href="README.ko.md">한국어</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.hi.md">हिन्दी</a>
- </p>
- # Agentlas OS
- An open-source AI agent OS inspired by OpenAI Dots, Meta Muse, Claude Duet, Nous Hermes, and Mem0.
- Built to lead entire projects rather than isolated prompts. Model-agnostic (BYOM) and native to Claude Code, Codex, Cursor, Antigravity, and Agentlas Desktop.
- Most agent products take one of two approaches. Some are prompt loops that report a task as done without checking the result. Others run each agent in a virtual machine, in the cloud or on your computer, apart from your files, credentials, and tools; a local VM also holds memory and disk while it runs. Agentlas OS takes neither approach. It runs no VM: agents work in the terminal, files, and tools already on your machine, and a task is complete only after an independent verifier accepts its execution receipt.
- Install Agentlas Desktop via the button below for the full runtime and mobile pairing (One), or attach this repository's runtime packs directly to Claude Code, Codex, or Cursor.
- <p align="center">
- <a href="https://github.com/agentlas-ai/agentlas-desktop-releases/releases/latest"><img alt="Download Agentlas" src="https://img.shields.io/badge/Download-Agentlas-6D28D9?style=for-the-badge"></a>
- </p>
- <p align="center">
- macOS · Windows · Linux · <a href="https://play.google.com/store/apps/details?id=com.agentai.agentlas">Android</a> · iOS coming soon<br>
- 12,000+ desktop downloads · Free to download, runs on your own AI plan or key · Apache-2.0
- </p>
- <p align="center">
- <a href="https://agentlas.cloud">Website</a> · <a href="https://agentlas.cloud/hub">Agent Hub</a> · <a href="https://discord.gg/wbWfdGZ6S">Discord</a> · <a href="#developers">Developers ↓</a>
- </p>
- <p align="center"><a href="https://agentlas.cloud"><img src="https://agentlas.cloud/landing/v3/readme-hero-en.gif" alt="Agentlas fixing a spreadsheet, charting it, building a deck, posting to Slack and editing a product photo on a Mac" width="880"></a></p>
- ## Architectural Foundations
- Instead of stitching together single-purpose wrappers, Agentlas OS combines five agent patterns in one local-first runtime.
- - Persistent autonomous execution (inspired by OpenAI Dots): Goals survive across sessions. Work resumes from the last checkpoint, and a step counts as complete only after an independent verifier checks its execution receipt.
- - Domain-complete workflows (inspired by Meta Muse): Work runs to a finished deliverable across personal operations (One), investment research that keeps the inputs behind each calculation (Finance), and literature and molecular research (Science).
- - Desktop execution, mobile decisions (inspired by Claude Duet): Execution stays on your computer, where your files and tools are. Decision points reach your phone as question cards, and the desktop continues after you answer.
- - Portable skills and A2A packaging (inspired by Nous Hermes): `40-session-agent-builder` compiles the procedure and checks from a working session into a package, and `30-agentlas-packager` packages existing agents. Every package carries an A2A Agent Card and installs on any supported host.
- - Scoped memory governance (inspired by Mem0): `memory-hooks`, context maps, and project indexes are scoped per project. Workers emit memory events; a Memory Curator validates, redacts, and deduplicates them, and a Policy Gate approves promotion to shared team memory.
- ## Elsewhere, a split task is a prompt. Here, it is a job opening.
- Elsewhere, an agent that splits a task writes sub-prompts to itself. In Agentlas OS, each part of the work becomes a job opening filled by a specialist agent, and the work runs on your own machine.
- Give Agentlas OS one objective. The Hephaestus engine decomposes it, searches for specialists on your computer, in your private Agent Cloud, and on the public Hub, and does not mark the work complete until an independent verifier checks the execution receipt.
- ## Hephaestus: decompose, recruit, verify
- ### 1. Decompose
- A goal becomes a task graph. Each task states its inputs and outputs, the tools and permissions it needs, and its pass/fail criteria. Long goals become a tree of strategic goals and sub-goals that can be re-planned mid-run.
- <p align="center"><img src="assets/readme/goal-tree.gif" alt="A launch goal split into strategic goals and sub-goals, re-planned when newsletter opens are low" width="880"></p>
- ### 2. Recruit
- For each task, Hephaestus searches three tiers:
- - Local: agents, scripts, and CLI tools already on your machine, run directly without a VM.
- - Agent Cloud: your private library of personal or team agents.
- - Public Hub: community agents. Publishing and using them is free, and nothing is ranked by payment.
- The model you chose makes each selection and records the reason and the exact release. A selection pins the release, package hash, and content digest.
- <p align="center"><img src="assets/readme/work-team.gif" alt="'Rebuild the beta product page around conversion': four hired specialists research, design, build and review the page" width="880"></p>
- ### 3. Verify
- Completion requires distinct worker invocations, artifact handoffs, synthesis, and a passing independent verifier. The host-produced execution receipt is validated locally. A selection or a prepared bundle is not a receipt.
- ## Three environments, one runtime
- One, Finance, and Science run in Agentlas Desktop on top of this runtime.
- <table>
- <tr>
- <td width="33%" valign="top"><a href="https://agentlas.cloud/docs/introduction/agentlas-one"><img src="https://agentlas.cloud/landing/v3/one-desktop.jpg" alt="Agentlas One on the Desktop"></a><br>One<br>A personal agent that runs on your computer. It opens Work sessions, assigns agents, sends question cards, and attaches results as files.</td>
- <td width="33%" valign="top"><a href="https://agentlas.cloud/updates/agentlas-finance-build-your-own-analyst"><img src="https://agentlas.cloud/landing/v3/finance-en.jpg" alt="Agentlas Finance"></a><br>Finance<br>Save research criteria as an Analyst. Reports keep the inputs behind each calculation.</td>
- <td width="33%" valign="top"><a href="https://agentlas.cloud/science"><img src="https://agentlas.cloud/landing/v3/science.jpg" alt="Agentlas Science"></a><br>Science<br>Molecular views and typeset manuscripts in one app, as a signed Agentlas Desktop extension.</td>
- </tr>
- </table>
- <sub>Names and figures on screen are examples.</sub>
- <p align="center"><img src="assets/readme/mobile.gif" alt="Asking for sign-ups by channel from a phone; an Analyst agent answers with a table and asks when to send the summary" width="260"></p>
- On your phone, the conversation is the same one running on your paired computer. The work happens on the desktop; the phone shows the results and answers question cards. [Android app](https://play.google.com/store/apps/details?id=com.agentai.agentlas)
- ## Bring your own model
- Sign in with Claude Code, Codex, Antigravity, Grok, Kimi, Cursor or GitHub Copilot CLI, add an API key, or run a free local model with Ollama, LM Studio or MLX. When one plan runs out of quota, chats move to the next.
- ## What stays on your computer
- - Your files, agents and memory live on your machine.
- - You choose how much it may do on its own. Every step is logged, and you can stop it from your phone.
- - The phone app sends requests to your desktop and shows the results; the work happens on your computer.
- - The engine is open source under Apache-2.0.
- <p align="center">
- <a href="https://github.com/agentlas-ai/agentlas-desktop-releases/releases/latest">Download Agentlas</a> ·
- <a href="https://play.google.com/store/apps/details?id=com.agentai.agentlas">Android app</a> ·
- <a href="https://discord.gg/wbWfdGZ6S">Join the Discord</a>
- <br>Star the repository so the next person finds it · <a href="https://github.com/agentlas-ai/Agentlas-OS/issues">Tell us what broke</a>
- </p>
- <a name="developers"></a>
- <details>
- <summary><b>Use the engine inside Claude Code, Codex, Cursor or Antigravity</b></summary>
- Or just give your coding agent this repository's address and ask it to install Agentlas.
- ```bash
- curl -fsSL https://raw.githubusercontent.com/agentlas-ai/Agentlas-OS/main/scripts/install-all-runtimes.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 132 on GitHub
- ```
- The default installer prepares the isolated runtime under `~/.agentlas/os-runtime`
- and the dedicated launcher `~/.agentlas/os-bin/agentlas-os`. Optional features
- are OFF. It does not permanently register plugins or MCP in detected hosts,
- create global `~/.local/bin` wrappers, or enable the global router.
- After a successful install, run:
- ```bash
- ~/.agentlas/os-bin/agentlas-os features status
- ```
- Report the runtime result separately from host connection. Use `host status`
- and the host session instructions below. Restarting an app does not establish readiness.
- OS updater readiness also requires its own verification.
- Prefer a GUI? [Agentlas Desktop](https://agentlas.cloud/desktop) is a separate
- application with its own installation and update flow.
- ### Paste to Install
- Already inside an LLM? Paste this into Claude Code, Codex, Antigravity or Cursor. It is written so the model can verify what it is running
- before it runs it, rather than being asked to trust it blindly:
- <!-- AGENTLAS-PROMPT-MODULE: os.install.readme.request; revision=2; stability=versioned-content; changeTriggers=release,capability-inventory; channel=user -->
- ```text
- request: Install Agentlas OS standalone from https://github.com/agentlas-ai/Agentlas-OS.
- inspect: First fetch and read https://raw.githubusercontent.com/agentlas-ai/Agentlas-OS/main/scripts/install-all-runtimes.sh and compare its actual behavior with this requested scope.
- scope: Use the isolated default runtime under ~/.agentlas/os-runtime and its dedicated ~/.agentlas/os-bin/agentlas-os launcher. Do not use sudo, replace the independent Terminal's agentlas command, write global ~/.local/bin wrappers, or permanently register host plugins/MCP as part of this request.
- defaults: Keep optional features OFF. Do not enable the global router or change host instruction files.
- run: If the script matches this scope, run curl -fsSL https://raw.githubusercontent.com/agentlas-ai/Agentlas-OS/main/scripts/install-all-runtimes.sh | bash. Report a scope mismatch instead of silently expanding the installation.
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 164 on GitHub
- verify: Show the installer's actual output and, if the launcher was installed successfully, run ~/.agentlas/os-bin/agentlas-os features status.
- report: State runtime installation and host connection separately. Preserve partial, unavailable, and unverified results. A restart alone does not prove that /agentlas build, skills, or MCP tools are ready.
- host-status: Runtime installation and host activation are separate. For the chosen installed host use ~/.agentlas/os-bin/agentlas-os host status claude or host status codex. Start a requested new host session with the same launcher and host session claude or host session codex; native arguments follow --. Preserve partial/conflict/unavailable states.
- updates: Automatic updates default OFF. After a runtime update, inspect host status again. outdated or codex_skill_alias_outdated is not readiness; do not silently replace/delete the owned alias or fall back to a legacy runtime. Codex One/Memory hooks are not applied and Windows host-session integration is unverified. Running host session codex again lets the launcher move its own verified alias to the current generation.
- ```
- ### No LLM handy? Type the command yourself
- You don't need an AI to install this, a terminal and one pasted line is
- enough. New to terminals? Follow your OS below.
- **On Windows, open Git Bash (standalone host integration unverified):**
- 1. **Do you already have Git Bash?** Click the search icon (or press the
- **Windows key**) in your taskbar and type **`git bash`**.
- - If **"Git Bash"** shows up in the results, click it and skip to step 3.
- - If nothing shows up, you need to install Git for Windows first: go to
- **[git-scm.com/download/win](https://git-scm.com/download/win)**,
- download it, and run the installer (default options are fine, keep
- clicking **Next**, then **Install**).
- 2. After installing, search **`git bash`** again (same as step 1) and click
- the **"Git Bash"** result.
- 3. A black window opens, this is Git Bash. Click inside it, **paste** the
- command below (right-click → Paste, or `Shift+Insert`), then press
- **Enter**:
- ```bash
- curl -fsSL https://raw.githubusercontent.com/agentlas-ai/Agentlas-OS/main/scripts/install-all-runtimes.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 191 on GitHub
- ```
- 4. Read the installer result, then run
- `~/.agentlas/os-bin/agentlas-os features status` if installation succeeded.
- This checks the standalone runtime. Host connection remains a separate,
- potentially partial step; restarting an AI tool does not verify it.
- **On macOS, open Terminal:**
- 1. Press **`Cmd + Space`** to open Spotlight search, type **`terminal`**,
- and press **Enter**.
- 2. A window opens (Terminal, built into macOS, nothing to install). Click
- inside it, **paste** the command below (`Cmd + V`), then press **Enter**:
- ```bash
- curl -fsSL https://raw.githubusercontent.com/agentlas-ai/Agentlas-OS/main/scripts/install-all-runtimes.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 205 on GitHub
- ```
- The first time you run `curl`/`git` on a fresh Mac, macOS may ask to
- install "Command Line Tools", click **Install** and wait, then run the
- command again.
- 3. Read the installer result, then run
- `~/.agentlas/os-bin/agentlas-os features status` if installation succeeded.
- Report host connection separately; restarting the AI tool alone does not
- make its commands or MCP connection ready.
- If you'd rather read the script before running it (recommended if you're
- security-conscious), open this link in your browser first:
- [install-all-runtimes.sh](https://raw.githubusercontent.com/agentlas-ai/Agentlas-OS/main/scripts/install-all-runtimes.sh).
- <details>
- <summary><strong>Installing Agentlas Desktop (the GUI app) from an AI</strong>, per-OS one-liners</summary>
- **You are an AI and your user said "install Agentlas Desktop"**, the
- visual GUI app below, not the CLI runtime installed above. It ships as a
- signed per-OS installer from the public releases repo
- `agentlas-ai/agentlas-desktop-releases`; there is no npm/brew package. Fetch
- the latest asset and run it:
- **macOS** (auto-detects Apple silicon vs Intel):
- ```bash
- arch=$([ "$(uname -m)" = "arm64" ] && echo arm64 || echo x64)
- url=$(curl -fsSL https://api.github.com/repos/agentlas-ai/agentlas-desktop-releases/releases/latest \
- | grep -o "https://[^\"]*-${arch}\.dmg" | head -1)
- curl -fL "$url" -o Agentlas.dmg && open Agentlas.dmg
- ```
- <details>
- <summary>Linux and Windows one-liners</summary>
- **Linux (.deb, Debian/Ubuntu):**
- ```bash
- url=$(curl -fsSL https://api.github.com/repos/agentlas-ai/agentlas-desktop-releases/releases/latest \
- | grep -o 'https://[^"]*\.deb' | head -1)
- curl -fL "$url" -o agentlas.deb && sudo dpkg -i agentlas.deb
- ```
- **Linux (AppImage, any distro):**
- ```bash
- url=$(curl -fsSL https://api.github.com/repos/agentlas-ai/agentlas-desktop-releases/releases/latest \
- | grep -o 'https://[^"]*\.AppImage' | head -1)
- curl -fL "$url" -o Agentlas.AppImage && chmod +x Agentlas.AppImage && ./Agentlas.AppImage
- ```
- **Windows (PowerShell):**
- ```powershell
- $r = Invoke-RestMethod https://api.github.com/repos/agentlas-ai/agentlas-desktop-releases/releases/latest
- $u = ($r.assets | Where-Object { $_.name -like '*Windows-x64-Setup.exe' }).browser_download_url
- Invoke-WebRequest $u -OutFile "$env:TEMP\AgentlasSetup.exe"; Start-Process "$env:TEMP\AgentlasSetup.exe"
- ```
- </details>
- This is a separate product from the CLI runtime installed via
- [Paste to Install](#paste-to-install) above, the two don't conflict and can
- both be present. If your user only wants the CLI/router (no GUI app), use
- that installer instead. No prebuilt asset for your OS/arch? Point your user
- at [agentlas.cloud/desktop](https://agentlas.cloud/desktop) or the
- [Releases page](https://github.com/agentlas-ai/agentlas-desktop-releases/releases/latest).
- </details>
- <details>
- <summary><strong>Build, Use, Own, the full model</strong></summary>
- An agent you create should remain an asset you can move, rather than a
- setting trapped in one chat, one model-vendor workspace, or one computer.
- Agentlas separates three jobs that ordinary agent builders blur together:
- This is the public Agent Trust contract: a
- portable, owner-scoped, inspectable, and restorable package contract, not a
- claim of regulated financial or legal trust services.
- | Value | What Agentlas does | Entry point in an external LLM host |
- | --- | --- | --- |
- | **Build** | Compiles a plain-language request into a runnable single-agent or team package with roles, tools, memory boundaries, permissions, routing, and verification contracts. | `/agentlas build` |
- | **Use** | Finds free public Hub agents and brings the selected runtime bundle into your current Agentlas host. The publisher's private source work is not copied into your workspace. | `/agentlas hub` (Hub only) or `/agentlas network` (Local + Cloud + Hub) |
- | **Own** | Keeps agents you create in a private, owner-scoped Agent Cloud so you can retrieve and call them again after changing models or computers. | Choose **private Agent Cloud** at `/agentlas upload`, then retrieve with `/agentlas cloud` |
- ### Portable package, local execution
- ```text
- Describe the work
- -> build a portable agent or team
- -> save it to my owner-scoped Agent Cloud
- -> install Agentlas OS and sign in on another supported host
- -> retrieve it with /agentlas cloud
- -> my chosen model and current host execute the work
- ```
- Agent Cloud stores and retrieves the owner's package; it is not a hosted LLM
- that completes the work on the server. When you call a package, your selected
- model and current host runtime execute it under that host's permission and
- safety model. Credentials, local files, and machine-specific permissions do not
- travel with the package, you configure those separately on each computer.
- ### Turn a working session into an owned agent
- When a conversation contains a repeatable working method, use the canonical
- session route:
- ```text
- hep-build session
- ```
- In an interactive host, the current visible conversation is the source. Agentlas
- asks for the destination first; if you do not name another folder, it creates a
- new safe-slug child below `AGENTLAS_AGENT_HOME` or, by default,
- `~/.agentlas/agents`. Existing children are never overwritten. It then
- shows a generalized session report for your review, turns the approved method
- into a standalone agent prompt and package, registers it locally, and runs the
- normal verification gates.
- You do not need to export JSON for this interactive route. JSON/JSONL remains an
- explicit option for terminal, replay, and headless workflows only. The default
- output is a single agent; choose a team explicitly. Raw transcripts, hidden
- prompts, credentials, private paths or URLs, screenshots, and literal tool
- arguments/results are not carried into the generated package. Uploading to Agent
- Cloud or the public Hub is a separate, explicit choice. See the
- [session build contract](contracts/session-build.md) for the deterministic
- export boundary.
- ```text
- current conversation
- -> destination question
- -> generalized session report
- -> owner review
- -> standalone agent/package
- -> local registration and verification
- ```
- ### The package contract, what every build must emit
- An agent package is not a worker with capabilities. It is a **method document**.
- Three layers, and conflating them is the single most expensive mistake this
- project has made:
- | layer | what it is | who supplies it |
- |---|---|---|
- | **LLM** | the worker: reasoning, language, general knowledge | you (BYOM) |
- | **Runtime** | the facilities: read the web, write files, run a shell, drive a browser | the host machine |
- | **Agent** | the work manual: procedure, judgement rules, source priority, input/output contracts, stop conditions | the package |
- "Can this agent read the web?" is a category error. The runtime reads the web.
- The only question a package can answer is *what method does it carry, and what
- must the machine be able to do for that method to run.*
- `package-contract.json` is the machine-readable list of artifacts every build
- emits, and `bin/hephaestus contract verify <folder>` is what enforces it.
- A build that omits a required artifact **fails**; it does not ship. Four of
- those artifacts carry the routing contract:
- ```text
- contracts/intake.schema.json what a requester must hand over before work starts
- contracts/output.schema.json what the requester ends up holding
- contracts/output.example.json one real instance, validated by a JSON Schema
- validator at publish time, never by a model
- .agentlas/brief.json the compiled resume, schemaVersion agentlas.brief/1
- ```
- Direction lives in the filename because nothing else ever marked it, and a
- schema whose direction must be guessed cannot be matched against a request.
- **Two rules bind every enum a build writes.**
- 1. **Any enum reachable from matching must carry an escape member** (`"other"`,
- `"unknown"`). A publisher whose real case is not on the list must still be findable.
- 2. **Sentences stay sentences.** No field that holds an author's sentence may be
- split into terms for matching.
- Vendor and MCP names live in exactly one place, `host[].preferred`, and that
- field is display-only. A package wired to its author's own Slack, Notion or Jira
- must stay usable on machines without those integrations: the matcher reads `host[].capability` ("open the page in a
- real browser and read what a user would see") and every requirement states
- `withoutIt`, what the method still does on a machine that lacks the facility.
- `agentlas.brief/1` is written from either side, `side: "offer"` is the
- package's resume, `side: "need"` is the requester's work order. The same form,
- so the two can be compared without a translation step. Its schema is
- `schemas/agentlas-brief.schema.json`, and it is **compiled, never hand-written**:
- the upload path writes it from the files the package already ships.
- | field | what it holds | where it comes from |
- |---|---|---|
- | `statement` | the author's own sentence about the work | the routing card, carried whole |
- | `deliverables[].label` / `.contains` | what the requester ends up holding, and what is inside it | `contracts/output.schema.json`, the title and its property names |
- | `deliverables[].shape` | `ledger` / `verdict` / `dossier` / `computation` / `blueprint` / `rendition` / `other` | computed from the output schema's **topology**, arity and value spaces, never a title or a filename |
- | `deliverables[].rowVerdict` / `.verdictValues` | the per-record judgement and its allowed values | copied verbatim from the publisher's own enum; there is nothing to match them against, so no value is ever rejected |
- | `obligations[].about` / `.stage` | a fact the requester must supply, and *when* it comes to exist | `contracts/intake.schema.json` and the card's stated inputs |
- | `authority.performs` / `.gated` | what this method does to the requester's world, and what it stops to ask about first | derived from the approval requirements, not from what the package calls itself |
- | `host[].capability` / `.withoutIt` | what the machine must be able to do, and what still happens when it cannot | `.agentlas/mcp-policy.json` |
- | `provenance` | per field: `extracted`, `read`, `graded` or `absent` | written by the compiler |
- `provenance` is the part that keeps the rest honest. `absent` is a legal value
- that scores zero, so a gap stays a gap. Do not fill missing evidence with
- plausible capability claims.
- The reference shape is `Web_master`: it ships input and output contracts as real
- JSON Schema, a domain catalogue its rules are checked against, and verification
- scripts that run. Everything above is what a build has to emit to be readable the
- way that package already is.
- Deliberately absent: there is no field for what an agent is *good at*, and none
- for its permissions. Quality cannot be read off a package that has never run, and
- permissions are granted by the host after the fact, an employer hands you a
- computer once you are hired, so neither says anything about whether this method
- fits the work.
- ### Hub and Agent Cloud are different scopes
- | Surface | What it contains | What it is for |
- | --- | --- | --- |
- | **Agentlas Hub** | Public packages from creators and teams | Discover and use public agents for free with `/agentlas hub`; `/agentlas network` federates Hub with Local and owner Cloud. Publish only through an explicit public-Hub choice. |
- | **My Agent Cloud** | Only the signed-in owner's Cloud packages | Privately store, restore, and call packages you own with the `/agentlas upload` Cloud choice and `/agentlas cloud`. |
- | **Current host** | The installed runtime, chosen model, local project, credentials, and granted permissions | Execute the selected local, Cloud, or Hub package. |
- </details>
- <details>
- <summary><strong>Installation and host sessions</strong></summary>
- ### Manual LLM Adapter Install
- Use this to prepare the standalone preview runtime.
- The installer prepares the isolated runtime and owned session plugins. Inspect host status before use; permanent host registration and Desktop updater integration are not complete.
- ```bash
- xcode-select --install # Command line tools (skip if already installed)
- git --version # Confirm git is available
- curl -fsSL https://raw.githubusercontent.com/agentlas-ai/Agentlas-OS/main/scripts/install-all-runtimes.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 448 on GitHub
- ```
- Standalone automatic updates are off by default. After an update, recheck host status and owned alias state. Desktop updater integration remains incomplete.
- Offline/local-source installation is not supported by this standalone installer.
- `HEPHAESTUS_SOURCE_DIR` is rejected with `standalone_local_source_unverified`.
- Do not bypass this check or report a local checkout as a verified installation.
- ### Host routing status
- Global routing is not installed by the standalone default. Permanent host
- registration is not confirmed in this preview. Legacy `hephaestus global`
- commands are not proof that the standalone runtime can register a host.
- Use the standalone host session commands below and inspect the actual receipt before claiming that tools or skills are ready.
- When explicitly requested and connected, Network preserves the full
- `local + cloud + hub` scope. The host model selects and validates exact
- releases. Preparation is not execution, and local skills are not a silently
- substituted registered workforce.
- The independent Agentlas Terminal owns the `agentlas` shell command.
- The standalone installer does not replace it.
- ### Connect a standalone host session
- <!-- prompt-module: {"id":"os.install.readme.host-session","revision":1,"stability":"versioned-content","changeTriggers":["release","runtime","capability-inventory"],"channel":"tool-result"} -->
- Use the dedicated launcher after installation. Inspect the chosen host first; starting a session is a separate action. These commands use the isolated runtime under `~/.agentlas/os-runtime` and owned plugins under `~/.agentlas/os-host-plugins`, not a permanent marketplace installation or a copy of engine files into your project.
- Check the installed host you intend to use:
- ```bash
- ~/.agentlas/os-bin/agentlas-os host status claude
- ~/.agentlas/os-bin/agentlas-os host status codex
- ```
- Start a new session for that host when requested:
- ```bash
- ~/.agentlas/os-bin/agentlas-os host session claude
- ~/.agentlas/os-bin/agentlas-os host session codex
- ```
- Antigravity has no session-only loader, so it is registered only when you ask, through Antigravity's own plugin manager. The plugin is `agentlas-os-core` and its MCP server is `agentlas-os`, so an older Agentlas registration stays separate:
- ```bash
- ~/.agentlas/os-bin/agentlas-os host install antigravity
- ~/.agentlas/os-bin/agentlas-os host status antigravity
- ~/.agentlas/os-bin/agentlas-os host remove antigravity
- ```
- Start a new Antigravity session after installing. After a runtime update `host status antigravity` reports `outdated`; run `host install antigravity` again. Headless `agy -p` runs need the MCP permission rule `mcp(agentlas-os-core_agentlas-os/*)` in `permissions.allow`; interactive sessions ask.
- Grok registers the same way through its own plugin manager (`grok plugin install --trust`):
- ```bash
- ~/.agentlas/os-bin/agentlas-os host install grok
- ~/.agentlas/os-bin/agentlas-os host status grok
- ~/.agentlas/os-bin/agentlas-os host remove grok
- ```
- Start a new Grok session after installing; the tools appear as `agentlas-os__<tool>`. After a runtime update run `host install grok` again. Agentlas Desktop reaches Grok over ACP and does not use this registration.
- Append `-- <native-args...>` only when you intend to pass arguments to the native host. Read the actual status and launch result. `partial`, `session_activation_not_observed`, or an unavailable component is not proof that the host is fully connected. A runtime install, a prepared plugin, and a running model session are separate results.
- Select the qualified skill name shown by that session, for example `agentlas-os-core:hephaestus-network`. Old bare names may coexist; do not assume `/hep-*`, `/agentlas`, or an unqualified `$hephaestus-*` refers to this runtime. The command reference below describes capabilities; use only commands or tools actually exposed in your session.
- Codex core tools and skills can be loaded in a separate session, but One and Memory hooks are not applied there yet. An ON preference is not evidence that those hooks ran; preserve `unappliedHookComponents` and `codex_optional_hook_session_loader_unverified` in the result. Windows host-session integration is unverified. Permanent host registration and complete native integration are not claimed. On Windows, unavailable link-creation privileges can leave status partial. A successful native inventory or version command does not prove a model turn or hook execution. Feature preferences use the shared `~/.agentlas/engine-features.json` for standalone and Desktop. An explicit OFF also disables the feature in Desktop, overriding its default ON. With no explicit preference or compatibility override, standalone defaults OFF (memory defaults ON) and Desktop uses its own feature defaults. Standalone One on/off is separate state under `~/.agentlas/os-one`.
- After an update, run `host status` again. An owned Codex skill alias can still point at the older generation: `outdated` or `codex_skill_alias_outdated` means the new host session is not ready. Do not silently replace or delete the alias or fall back to a legacy runtime; report the exact state and follow an explicit repair procedure when available. Running `host session codex` again moves the launcher's own verified alias to the current generation. Automatic updates remain OFF by default; a runtime update does not prove host activation.
- </details>
- <details>
- <summary><strong>The Command Surface, every command</strong></summary>
- Inside native Agentlas environments, Hephaestus operates commandless. External LLM tools use a deliberately small visible command set for building agents and staffing work with them:
- | System Subsystem | Command | Example |
- | :--- | :--- | :--- |
- | **Agent / Team Builder** | `/agentlas-build` (or `/agentlas build`, `/hep-build`) | `/agentlas-build create a customer support agent for Shopify refunds` |
- | **Session-to-Agent Builder** | `/hep-build session` (canonical route: `hep-build session`) | `/hep-build session` |
- | **Workforce Federation (Local + Cloud + Hub)** | `/agentlas-network` (or `/agentlas network`, `/hep-network`) | `/agentlas-network split this launch plan into research, copy, QA, and release agents` |
- | **Registered Local Agents Only** | `/agentlas-local` (or `/agentlas local`, `/hep-local`) | `/agentlas-local use only agents registered on this machine` |
- | **Owned Cloud Agents Only** | `/agentlas-cloud` (or `/agentlas cloud`, `/hep-cloud`) | `/agentlas-cloud use my saved finance analyst agent to review this report` |
- | **Public Hub Agents Only** | `/agentlas-hub` (or `/agentlas hub`, `/hep-hub`) | `/agentlas-hub find public specialists for accessibility QA` |
- | **Directory Search** | `/agentlas-search` (or `/agentlas search`, `/hep-search`) | `/agentlas-search find agents for a market report workflow` |
- | **Inter-Process Call (IPC)** | `/agentlas-call` (or `/agentlas call`, `/hep-call`) | `/agentlas-call market-researcher, report-writer {draft a market report}` |
- | **Cloud / Hub Destination Gate** | `/agentlas-upload` (or `/agentlas upload`, `/hep-upload`) | `/agentlas-upload ./agents/customer-support-hq` |
- | **Sign-in** | `/agentlas-login` (or `/agentlas login`, `/hep-login`) | `/agentlas-login` |
- | **Orchestrator / Worker Models** | `/agentlas-orch` (or `/agentlas orch`, `/hep-orch`) | `/agentlas-orch orchestrator=frontier worker=economy` |
- | **Goal Plan Tree (long, measurable goals)** | `/agentlas-goal` (or `/agentlas goal`, `/hep-goal`) | `/agentlas-goal reach 1000 followers in a month, today 30` |
- | **Runtime + Adapter Update** | `/agentlas-update` (or `/agentlas update`, `/hep-update`) | `/agentlas-update` |
- `/hep-orch` sets which model runs the orchestrator and which runs the workers,
- so a fan-out of mechanical work does not bill frontier runs. **The split only
- puts two models to work on Claude Code**, which is the one host that spawns a
- real subagent and takes a model per subagent. Codex, Antigravity, Cursor,
- and OpenCode have no subagent of their own: one model plays every role in
- sequence there, the allocation receipt is still written, and the ceiling still
- bounds what that model may request, but no second, cheaper model appears.
- `/hep-goal` adds a plan tree to your host's own `/goal`. It first decides the
- shape of the goal. Short work with one clear check stays a single tactic and
- behaves exactly like the host goal, with no extra text. A long goal with a
- number you named becomes a mission tree: key results, strategies, tactics, and a
- KPI reading that says whether the plan is moving. It tells you when the numbers
- say the plan has stalled, and when the target looks out of reach it asks you
- instead of re-planning forever. The host goal still decides when the work is
- done; `/hep-goal` only keeps the plan and the numbers honest. A target is only a
- number you wrote in the goal text, and every reading needs a source and a short
- evidence quote. It changes only its own files under `.agentlas/goal/`, never
- permissions or payments. The default mode is `shadow` (it records and measures,
- injects nothing, applies no re-plan); set `AGENTLAS_GOAL_STRATEGY=on` to use it.
- Performance on real long-running work remains unverified. Treat the plan tree
- as unproven until it has been checked on real goals.
- Every row also answers to its original `/hep-*` name, `/agentlas network` and
- `/hep-network` are the same command. Nothing was renamed away, so existing
- scripts, notes, and muscle memory keep working. Current Codex uses explicit
- plugin skills `$hephaestus-build`, `$hephaestus-network`,
- `$hephaestus-cloud`, and `$hephaestus-upload`; other MCP surfaces can be
- requested in plain language.
- Custom `/prompts:*` commands were removed from Codex 0.117+.
- </details>
- <details>
- <summary><strong>Deeper, the build factory and the routing scheduler</strong></summary>
- ### Meta-Agent Factory, Process Creation
- A unified compilation factory using four builders. Every generated package registers its global command (`.agentlas/global-commands.json`) and ships verification scripts, the user never has to infer how to run the compiled package:
- | Compilation Mode | Routing Target | Output Artifact |
- | :--- | :--- | :--- |
- | **Single-Agent** | `10-single-agent-builder` | Standalone worker with localized skills, memory contracts, and runtime adapters. |
- | **Multi-Agent Team** | `20-multi-agent-team-builder` | Hierarchical team containing a PM Orchestrator, Memory Curator, Policy Gate, QA, and validation scripts. |
- | **Workspace Packager** | `30-agentlas-packager` | Compiled bundle ready for runtime import, CLI execution, or GitHub distribution. |
- | **Session Agent Builder** | `40-session-agent-builder` | Turns the current conversation (or, for headless runs, an explicit JSON/JSONL export) into an owner-reviewed single agent by default, or a team when you choose one. |
- *Briefing Interview Gate:* Builders initiate the process using the **briefing interview gate** : conducting lens-driven questions, evaluating the ambiguity threshold, searching primary sources, and outputting the work brief.
- ### Network 2.0, The Scheduler
- <p align="center">
- <img src="assets/hephaestus-network-architecture.svg" alt="Figure 2. Hephaestus Network 2.0 A2A networking architecture">
- </p>
- <sub>Figure 2. A2A scheduling: explicit host commands, model-selected exact releases, local memory, and federated Agentlas Network discovery.</sub>
- * **Typed Job Analysis:** The active host LLM turns the request into a redacted `WorkOrder` with explicit roles, skills, tools, artifacts, authority, cardinality, and handoffs. Core does not infer staffing intent from a substring list.
- * **Exact Source Federation:** `local`, `cloud`, and `hub` are exact scopes; `network` is their sealed union. Each source returns a bounded, content-only menu, and Core records unavailable sources instead of silently widening scope.
- * **Host-Owned Task Forces:** The host LLM reads the qualification evidence and authors the exact `Selection`. Core never chooses a deterministic winner or performs a hidden Router Agent re-rank; it validates governance, privacy, identity, cardinality, and graph integrity.
- * **Pinned Execution:** After validation, Core fetches only the selected immutable releases from their original source sessions and verifies release, package, and content digests before distinct planner, worker, synthesis, and verifier invocations run.
- * **Evidence-Scored Evaluation:** Retrieval coverage, host selection, immutable preparation, real child invocations, and final verification are scored as separate claims. A benchmark result never replaces the host staffing decision or turns usage history into routing authority.
- #### Execute a prepared goal from an external host
- An explicitly selected host plugin or executable can run the newest ready plan
- bound to a Workforce goal through the provider-neutral adapter contract:
- ```bash
- ./bin/hephaestus workforce execute \
- --project . \
- --goal-id <host-task-id> \
- --adapter-argv-json '["/absolute/path/to/host-adapter"]'
- ```
- The adapter reads one versioned JSON request from standard input and writes one
- JSON response to standard output for inventory observation and each required
- orchestrator, planner, worker, synthesis, and verifier invocation. Core retains
- the exact preparation pins, verifies and snapshots output artifacts locally,
- and returns an execution receipt only after the existing receipt validator
- accepts the complete run. The adapter owns its provider authentication and
- native runtime configuration as an independently installed plugin; do not put
- credentials in the argv JSON. The complete v1 request, response, artifact, and
- failure contract is documented in
- [`agentlas_cloud/workforce/host_executor.py`](agentlas_cloud/workforce/host_executor.py).
- Tool inventory distinguishes native host enforcement (`host-native`) from a
- host-owned tool dispatcher (`host-broker`). A bound tool requires its invocation
- receipt to use that same enforcement path; neither label grants authority to a
- package that did not select the host permission policy.
- </details>
- <details>
- <summary><strong>What It Builds, process packaging</strong></summary>
- Hephaestus packages agents into a standard directory layout that any workspace runtime can parse, install, verify, and run. The important part is not just `agent.md`; it is the operating contract around it. The layout below is what `package-contract.json` requires and `hephaestus contract verify` checks:
- ```text
- ├── AGENTS.md # Package entry: name, purpose, canonical command, roles
- ├── agent.md # Primary instructions: role, steps, output contract
- ├── agentlas.json # Manifest: permissions, memory policy, read allow/deny lists
- ├── agents/<role>/agent.md # Team only: one folder per worker
- ├── A2A/agent-card.a2a.json # A2A Agent Card projected from the two cards below
- ├── .agentlas/
- │ ├── agent-card.json # Identity: name, slug, summary, capabilities, entrypoints
- │ ├── routing-card.json # Triggers and anti-triggers (ko + en), risk, memory behavior
- │ ├── build-profile.json # Fail-closed build readiness profile
- │ ├── memory-map.json # Memory ownership map
- │ ├── global-commands.json # Per-runtime slash command adapters
- │ ├── mcp-policy.json # What the machine must provide, and what happens without it
- │ ├── skill-registry.json # Skill inventory (may be empty)
- │ ├── memory-tickets.jsonl # Candidate memory events before curator promotion
- │ ├── capability-eval-plan.json # Positive/negative eval prompts with pass criteria
- │ ├── routing-benchmarks.jsonl # At least 10 route/reject cases, ko + en
- │ ├── work-brief.json # Interview-derived goal, constraints, decisions
- │ ├── company-blueprint.json # Team only: orchestrator, nodes, edges
- │ ├── sitemap.json # Team only: what each task produces and consumes
- │ └── brief.json # agentlas.brief/1 resume, compiled at upload
- ├── contracts/ # intake.schema.json, output.schema.json, output.example.json
- ├── docs/ # Builder interview, research sources, tool selection,
- │ # domain synthesis, prompt performance contract
- ├── tools/requirements.yaml # Projected from mcp-policy.json + agentlas.json
- ├── permissions/policy.yaml # Projected shell/network/file/payment whitelist
- ├── hooks/ # memory-upgrade.yaml, on_stop.yaml, declared, host-enforced
- ├── evals/README.md # Points at the eval plan and routing benchmarks
- └── .claude/skills/<name>/SKILL.md # Skills, when the package carries any
- ```
- `docs/`, the eval plan and the work brief may be skipped only by a
- user-confirmed minimal private build. `provenance.json`, `knowledge/`,
- `schemas/`, `sandbox/` and `examples/` are optional.
- That package shape is why an Agentlas agent is more than an LLM-written role
- prompt. It carries routing, memory, input/output contracts, permissions,
- runtime adapters and evaluation evidence together.
- </details>
- </details>
- <details>
- <summary><b>Public safety boundary</b></summary>
- This repository does **not** include Agentlas billing/account logic, production cloud credentials, customer databases, raw private transcripts, native keychain managers, or private deployment scripts.
- Public output packages compiled by Hephaestus must exclude local absolute paths, API keys, service-account keys, `.env` secrets, raw transcripts, customer logs, or private developer notes.
- #### Build telemetry
- When `build-telemetry` is enabled, `hep-build` sends anonymous counters: a random
- install id generated locally, which build step ran, whether it succeeded, a
- machine error code, a duration, and the OS/engine/python versions. Events are
- deleted 180 days after they arrive.
- Never sent: file paths, package names, prompts, agent content, error message
- text, usernames, emails, or environment variables. The allowlist is enforced in
- the engine before the request is built and again on the server, which drops
- every field it does not recognize.
- Telemetry is off by default. Enable or disable it with:
- ```bash
- ~/.agentlas/os-bin/agentlas-os features on build-telemetry
- ~/.agentlas/os-bin/agentlas-os features off build-telemetry
- ```
- These environment variables also disable telemetry:
- ```bash
- export AGENTLAS_TELEMETRY=0
- export DO_NOT_TRACK=1 # the cross-vendor convention, honored here
- ```
- Or permanently, in `~/.agentlas/networking/config.json`:
- ```json
- { "telemetry": false, "telemetrySetBy": "user" }
- ```
- The `telemetrySetBy` marker is what separates a choice you made from the
- `"telemetry": false` that `default_config()` wrote into every install created
- before the key was ever read, that value never represented anyone's decision,
- so it is not treated as one.
- </details>
- ## License
- Apache-2.0 · Made by [Appbridge](https://agentlas.cloud)
agentlas_cloud/content_guard.py · Bundled script · 865 lines · 2 findings marked
- """Enterprise content-safety guard for cloud agent uploads.
- Design goals (in priority order):
- 1. Preserve agent quality — never blindly delete. Ambiguous / advisory / quoted
- mentions are FLAGGED for review, not removed. Only high-confidence malicious
- directives are redacted line-by-line.
- 2. Defeat obfuscation — a normalized *detection shadow* (NFKC, invisible-char
- stripping, homoglyph + leetspeak folding, separator collapse) is scanned so
- that Cyrillic/leet/zero-width/spaced variants are caught without mutating the
- kept content.
- 3. Multilingual — Korean / Chinese / Japanese injection & exfiltration concepts
- are first-class, not English-only.
- 4. Multi-line — a sliding window catches injections split across lines to evade a
- per-line scanner.
- 5. Model-adjudicated — regex hits over PROSE are candidates, not verdicts.
- When a resident judgment runner is connected (agentlas_cloud.judgment),
- each candidate directive is confirmed or downgraded by meaning; without a
- runner the deterministic candidate verdict stands (fail-closed security).
- Non-prose signals (exfil beacons, invisible characters) and the secret
- detectors in upload.py stay deterministic and are never model-cleared.
- Public surface:
- evaluate_line(line) -> Reason | None (single-line verdict)
- find_multiline_spans(lines) -> list[SpanReason] (cross-line verdicts)
- MAX_MULTILINE_WINDOW -> int
- Reason / SpanReason carry: rule, message, action ("redact" | "flag"), severity.
- """
- from __future__ import annotations
- import re
- import unicodedata
- from dataclasses import dataclass
- MAX_MULTILINE_WINDOW = 5
- # Markdown section headings, code fences, and table rules end a thought; the
- # multiline joiner must not read across them.
- _STRUCTURAL_BOUNDARY_RE = re.compile(r"^\s{0,3}(?:#{1,6}\s|```|~~~|\||-{3,}\s*$|\*{3,}\s*$)")
- @dataclass(frozen=True)
- class Reason:
- rule: str
- message: str
- action: str # "redact" (remove line) | "flag" (keep, needs-review)
- severity: str # "high" | "medium" | "advice"
- @dataclass(frozen=True)
- class SpanReason:
- start: int # 0-based inclusive line index
- end: int # 0-based inclusive line index
- rule: str
- message: str
- action: str
- severity: str
- # --------------------------------------------------------------------------- #
- # Detection-shadow normalization
- # --------------------------------------------------------------------------- #
- # Common confusables folded to their ASCII base. Kept intentionally tight to
- # avoid corrupting legitimate non-Latin content in the *shadow* (the original
- # text is never modified by this map).
- _HOMOGLYPH = {
- "а": "a", "ӓ": "a", "ɑ": "a", "α": "a", "a": "a", "4": "4",
- "е": "e", "ё": "e", "ε": "e", "e": "e", "3": "3",
- "о": "o", "ο": "o", "օ": "o", "o": "o", "0": "0",
- "р": "p", "ρ": "p", "p": "p",
- "с": "c", "ϲ": "c", "c": "c",
- "х": "x", "χ": "x", "x": "x",
- "у": "y", "ү": "y", "y": "y",
- "і": "i", "ї": "i", "ı": "i", "ⅰ": "i", "i": "i", "1": "1",
- "ѕ": "s", "s": "s", "5": "5",
- "ԁ": "d", "d": "d",
- "ɡ": "g", "g": "g",
- "ո": "n", "n": "n",
- "ⅼ": "l", "l": "l",
- "ᴜ": "u", "u": "u",
- "ѵ": "v", "ν": "v", "v": "v",
- "к": "k", "κ": "k", "k": "k",
- "м": "m", "m": "m",
- "т": "t", "τ": "t", "t": "t", "7": "7",
- "г": "r", "r": "r",
- "ь": "b", "b": "b",
- "н": "h", "h": "h",
- "ѡ": "w", "w": "w",
- "ј": "j", "j": "j",
- "ԛ": "q", "q": "q",
- "ᴢ": "z", "z": "z",
- "f": "f",
- }
- _LEET = {"0": "o", "1": "i", "3": "e", "4": "a", "5": "s", "7": "t", "@": "a", "$": "s"}
- _LEET_TRANSLATION = str.maketrans(_LEET)
- _ASCII_CONTROL_TRANSLATION = {
- code: None for code in range(32) if chr(code) not in "\t\n\r"
- }
- _ASCII_CONTROL_TRANSLATION[127] = None
- # Unicode Tag block (invisible ASCII smuggling, U+E0000..U+E007F).
- _TAG_LO, _TAG_HI = 0xE0000, 0xE007F
- def _strip_invisible(text: str) -> str:
- if text.isascii():
- return text.translate(_ASCII_CONTROL_TRANSLATION)
- out = []
- for ch in text:
- code = ord(ch)
- if _TAG_LO <= code <= _TAG_HI:
- continue
- cat = unicodedata.category(ch)
- if cat in ("Cf", "Cc") and ch not in "\t\n\r":
- continue # zero-width, bidi overrides, other format/control
- out.append(ch)
- return "".join(out)
- def _inline_decode_tags(text: str) -> str:
- """Decode Unicode Tag-block smuggling *in place* so a payload hidden between
- visible words (``Note:⟦ignore⟧ all previous``) reconstructs in the right
- order. Printable tag chars become their ASCII base; other tag chars drop."""
- out = []
- for ch in text:
- code = ord(ch)
- if _TAG_LO + 0x20 <= code <= _TAG_LO + 0x7E:
- out.append(chr(code - _TAG_LO))
- elif _TAG_LO <= code <= _TAG_HI:
- continue
- else:
- out.append(ch)
- return "".join(out)
- _WS_RUN = re.compile(r"[ \t\f\v]+")
- _NON_ALNUM = re.compile(r"[^0-9a-z가-힣一-鿿-ヿ]+", re.I)
- def canonicalize(text: str) -> str:
- """Readable detection shadow: NFKC, invisible-char strip, homoglyph + leet
- fold, whitespace normalized to single spaces. Word boundaries are PRESERVED
- (spaces kept) so boundary-based concept rules still match Cyrillic/leet
- variants. Used only for matching — never written back into the package."""
- # ASCII has no Unicode tags, normalization changes, or homoglyphs. Apply
- # the same control, case, leet, and whitespace rules without character loops.
- if text.isascii():
- text = _strip_invisible(text).lower().translate(_LEET_TRANSLATION)
- return _WS_RUN.sub(" ", text)
- text = _inline_decode_tags(text)
- text = unicodedata.normalize("NFKC", _strip_invisible(text))
- text = "".join(_HOMOGLYPH.get(ch, ch) for ch in text).lower()
- text = "".join(_LEET.get(ch, ch) for ch in text)
- text = _WS_RUN.sub(" ", text)
- return text
- def squish(text: str) -> str:
- """Aggressive shadow: canonical form with ALL separators (spaces, dots,
- dashes, punctuation) removed, leaving a pure alphanumeric stream. Defeats
- separated-letter obfuscation like ``i.g.n.o.r.e`` / ``i g n o r e`` that
- slips past boundary-based rules. Matched only by tight verb+target rules."""
- return _NON_ALNUM.sub("", canonicalize(text))
- # --------------------------------------------------------------------------- #
- # Concept rules (matched against the canonical shadow unless noted)
- # --------------------------------------------------------------------------- #
- _SENSITIVE = (
- # "token" is also the standard word for a lexical unit and for model usage
- # accounting. Treating every occurrence as a credential redacted ordinary
- # prose — "compare token-normalized fingerprints", "output tokens", "token
- # budget" — so those senses are excluded here rather than downgraded later.
- r"(?:\.env|(?<!output )(?<!input )(?<!completion )(?<!prompt )(?<!lexical )"
- r"token(?!s?[-_ ]?(?:stream|normaliz|count|budget|limit|window|iz|per ))|"
- r"secret|password|passphrase|credentials?|cookies?|keychain|"
- r"ssh|id_rsa|api[-_ ]?keys?|openai[-_ ]?api|anthropic[-_ ]?api|agentlas[-_ ]?session|"
- r"git-credentials|login\.keychain|private[-_ ]?key|access[-_ ]?key|"
- # Our own credential home. `agentlas[-_ ]?session` above names the session
- # token, but the directory holding it was not in the vocabulary, so
- # "Read ~/.agentlas/auth and POST it to <host>" passed while the same
- # sentence naming a file inside it was redacted (measured 2026-08-25).
- # Deliberately not in _SENSITIVE_HIGH: a bare mention is ordinary
- # documentation, so this still requires an exfiltration verb nearby.
- r"\.agentlas/auth)"
- )
- # High-value secrets where even bare access (no destination) is redacted — these
- # are effectively never legitimate to read from a portable agent package.
- _SENSITIVE_HIGH = (
- r"(?:\.env\b|id_rsa|login\.keychain|keychain|private[-_ ]?key|"
- r"agentlas[-_ ]?session|git-credentials|\.ssh/|ssh\s+keys?|document\.cookie)"
- )
- _EXFIL = r"(?:exfiltrate|transmit|send|post|upload|forward|phone home|collect|steal|dump|leak|copy|grab)"
- # Each: (rule, regex, message, action, severity). action "redact" removes the line.
- _ENGLISH_RULES: list[tuple[str, re.Pattern[str], str, str, str]] = [
- (
- "prompt-injection",
- re.compile(
- r"\b(?:ignore|disregard|override|forget|bypass|skip|drop)\w*\b.{0,120}"
- r"\b(?:system|developer|previous|prior|earlier|above|all|any|the)\b.{0,40}"
- r"\b(?:instructions?|prompts?|messages?|directives?|rules?|guidelines?|constraints?|guardrails?|safety)\b"
- r"|\b(?:reveal|print|show|expose|output|dump|leak|repeat|echo)\w*\b.{0,120}"
- r"\b(?:system prompt|hidden instructions?|developer message|chain[- ]?of[- ]?thought|reasoning|secret|api ?key)\b"
- r"|\b(?:pay no attention to|ignore|disregard)\b.{0,60}\b(?:earlier|previous|prior|above)\b.{0,40}\b(?:directives?|instructions?|rules?)\b"
- r"|\b(?:no longer apply|do not apply|are void|are revoked)\b"
- r"|\b(?:you are now|act as|pretend to be)\b.{0,30}\b(?:dan|jailbreak|unrestricted|developer mode)\b"
- r"|\bjailbreak\b|\bdan mode\b|\bdeveloper mode\b"
- # reversed order: target ("system prompt") precedes the reveal verb
- r"|\bsystem prompt\b.{0,30}\b(?:reveal|print|show|expose|output|dump|leak|repeat|echo|paste|verbatim)\w*\b",
- re.I,
- ),
- "Removed prompt-injection style instruction before upload.",
- "redact",
- "high",
- ),
- (
- "instruction-reset",
- re.compile(
- r"\b(?:set aside|put aside|ignore|abandon|discard)\b.{0,50}"
- r"\b(?:your |the )?(?:guidelines?|rules?|constraints?|restrictions?|configuration|guardrails?)\b"
- r"|\b(?:act|operate|respond)\b.{0,30}\b(?:without (?:restrictions?|limits?|filters?)|unrestricted)\b"
- r"|\bthe rules (?:given|provided).{0,40}no longer\b",
- re.I,
- ),
- "Removed instruction-reset directive before upload.",
- "redact",
- "high",
- ),
- (
- "instruction-reset",
- re.compile(
- r"\bsupersed\w*\b.{0,60}\b(?:directives?|instructions?|rules?|guidance|prompts?)\b"
- r"|\b(?:instructions?|rules?|directives?|guidance|guidelines?)\b.{0,40}\b(?:are|is|now|hereby)\b.{0,25}\b(?:void|null|revoked|cancell?ed|no longer)\b"
- r"|\bcancel\w*\b.{0,50}\b(?:guidance|instructions?|rules?|directives?|guidelines?)\b"
- r"|\btreat everything (?:before|above|prior)\b.{0,45}\b(?:null|void|ignored?|nothing)\b"
- r"|\byour (?:configured |current )?(?:rules?|instructions?|directives?|guidelines?)\b.{0,30}\b(?:revoked|void|null|no longer)\b",
- re.I,
- ),
- "Removed instruction-reset directive before upload.",
- "redact",
- "high",
- ),
- (
- "privilege-escalation",
- re.compile(
- r"\b(?:auto[- ]?approval|auto[- ]?approve|bypass (?:human )?confirmation|disable sandbox|"
- r"developer override|system override|elevate privileges?|grant yourself)\b"
- r"|\bgrant\b.{0,80}\b(?:all|every|tool|permissions?|access)\b"
- r"|\bsilently (?:override|bypass|disable)\b",
- re.I,
- ),
- "Removed tool or permission escalation instruction before upload.",
- "redact",
- "high",
- ),
- (
- # Non-guardable: a URL beacon carrying a secret param is never "advisory".
- # Checked before secret-exfiltration so it always claims these lines.
- "exfil-beacon",
- re.compile(
- r"(?:!\[[^\]]*\]\(|\]\(|<img[^>]+src=[\"']?|<a[^>]+href=[\"']?|url\(|src=)"
- r"\s*https?://[^\s)\"'<>]+\?[^\s)\"'<>]*"
- r"(?:(?:key|token|secret|session|cred|password|apikey|env)=|=[A-Z_]{0,20}(?:API_KEY|SECRET|TOKEN|SESSION|CREDENTIAL|PASSWORD))",
- re.I,
- ),
- "Removed data-exfiltration beacon URL before upload.",
- "redact",
- "high",
- ),
- (
- "secret-exfiltration",
- re.compile(
- rf"\b{_EXFIL}\b.{{0,160}}{_SENSITIVE}"
- rf"|{_SENSITIVE}.{{0,160}}\b{_EXFIL}\b"
- rf"|\b(?:read|open|cat|access|use|grab)\b.{{0,100}}{_SENSITIVE}.{{0,120}}\b(?:webhook|attacker|server|endpoint|https?://)\b",
- re.I,
- ),
- "Removed secret-access or exfiltration instruction before upload.",
- "redact",
- "high",
- ),
- (
- # Bare access to a high-value secret (no destination needed). Guardable,
- # so "never prints .env" / "explains how to read id_rsa safely" survive.
- "secret-access",
- re.compile(
- rf"\b(?:read|open|cat|access|use|grab|dump|exfiltrate|steal|copy|load|fetch)\b.{{0,60}}{_SENSITIVE_HIGH}",
- re.I,
- ),
- "Removed direct high-value secret access before upload.",
- "redact",
- "high",
- ),
- (
- "dangerous-command",
- re.compile(
- rf"\b(?:curl|wget|fetch|requests\.(?:post|put)|Invoke-WebRequest)\b.{{0,220}}{_SENSITIVE}"
- r"|\brm\s+-rf\s+(?:/|~|\$home)"
- r"|\bmkfs\."
- r"|\bdd\s+if=/dev/"
- r"|\bchmod\s+777\b"
- r"|\bsudo\b.{0,80}\b(?:sh|bash|zsh)\b"
- r"|\b(?:curl|wget)\b[^\n|&;]{0,200}\|\s*(?:sh|bash|zsh|python)\b",
- re.I,
- ),
- "Removed destructive or exfiltrating command before upload.",
- "redact",
- "high",
- ),
- (
- "encoded-execution",
- re.compile(
- r"\b(?:base64|atob|b64decode|frombase64string|fromcharcode|unescape)\b.{0,100}"
- r"\b(?:exec|execute|eval|bash|sh|powershell|zsh|command|payload|run|follow)\b"
- r"|\b(?:eval|exec)\b.{0,100}\b(?:atob|base64|b64decode|fromcharcode)\b"
- r"|\bdecode this (?:base64|payload).{0,60}\b(?:follow|run|execute|exec|eval)\b",
- re.I,
- ),
- "Removed encoded execution instruction before upload.",
- "redact",
- "high",
- ),
- (
- "persistence",
- re.compile(
- r"\b(?:create|install|add|keep|maintain|drop|register)\b.{0,80}"
- r"\b(?:persistence|launchagent|launchdaemon|cron\w*|startup item|login item|systemd|scheduled task|registry run key)\b"
- r"|\b(?:persistence|launchagent|cron\w*|startup item)\b.{0,80}"
- r"\b(?:after upload|first run|phone home|callback|webhook|execute|run|beacon)\b"
- r"|\bphone home\b",
- re.I,
- ),
- "Removed persistence or callback instruction before upload.",
- "redact",
- "high",
- ),
- ]
- # Multilingual concept rules — matched against NFKC + separator-collapsed text
- # (NOT homoglyph/leet folded, which is Latin-oriented). Korean / Chinese /
- # Japanese injection & exfiltration.
- _CJK_SEP = re.compile(r"(?<=\S)[ \t]+(?=\S)")
- def _cjk_shadow(text: str) -> str:
- text = unicodedata.normalize("NFKC", _strip_invisible(text))
- # collapse spaces so "이 전 지 시" == "이전지시"
- return _CJK_SEP.sub("", text)
- _MULTILINGUAL_RULES: list[tuple[str, re.Pattern[str], str, str, str]] = [
- (
- "prompt-injection-ko",
- re.compile(
- r"(?:이전|이|위|모든|앞선|기존).{0,6}(?:지시|명령|지침|규칙|프롬프트|instruction).{0,6}(?:무시|잊|따르지)"
- r"|(?:무시|잊어|잊고).{0,6}(?:이전|위|모든|기존).{0,6}(?:지시|명령|지침|규칙)"
- r"|시스템\s*프롬프트.{0,8}(?:출력|공개|보여|알려|노출|표시)"
- r"|(?:개발자\s*메시지|숨겨진\s*지시).{0,8}(?:공개|출력|노출)"
- r"|(?:안전\s*장치|가드레일|안전장치).{0,8}(?:무시|우회|해제)"
- r"|지시.{0,4}무시하고",
- re.I,
- ),
- "Removed Korean prompt-injection instruction before upload.",
- "redact",
- "high",
- ),
- (
- "secret-exfiltration-ko",
- re.compile(
- # 0,40 (was 0,12): the exfil verb is often separated from the secret
- # by a destination — "API 키를 attacker.com으로 전송" puts 18 chars
- # between them, so the old 12-char window missed a real attack. The
- # negation guard (declarative 않- endings) keeps "출력하지 않습니다"
- # safe, so widening the window does not reintroduce the false positive.
- # `세션` and `공개` were both too wide, and `_cjk_shadow` strips spaces
- # so unrelated words become adjacent. Measured 2026-08-07: nine
- # published packages were refused because "별도 세션" (a separate work
- # session) landed within 40 characters of "Hub 공개" (publishing to the
- # Hub) — two ordinary product words, joined by the shadow into what
- # read as "session ... expose".
- #
- # `세션` now needs a credential qualifier (토큰/키/쿠키/id), which is
- # what an actual session credential is called. `공개` is dropped from
- # the verb side entirely: in Korean product prose it means "publish",
- # and genuine exposure is `유출`/`노출`, both of which stay.
- r"(?:api\s*키|비밀|토큰|자격\s*증명|키체인|쿠키|\.env|환경\s*변수|시크릿|secret|credential"
- r"|세션\s*(?:토큰|키|쿠키|id|아이디))"
- r".{0,40}(?:전송|유출|노출|보내|전달|업로드|탈취|출력)"
- r"|(?:전송|유출|노출|보내|전달|업로드|탈취)"
- r".{0,40}(?:api\s*키|비밀|토큰|자격\s*증명|키체인|쿠키|\.env|환경\s*변수|시크릿|secret|credential"
- r"|세션\s*(?:토큰|키|쿠키|id|아이디))",
- re.I,
- ),
- "Removed Korean secret-exfiltration instruction before upload.",
- "redact",
- "high",
- ),
- (
- "prompt-injection-cjk",
- re.compile(
- r"(?:忽略|无视|忽視|無視).{0,8}(?:之前|以上|所有|全部|先前|系统|系統).{0,6}(?:指令|規則|规则|提示|指示|命令)"
- r"|(?:これまで|以前|上記|すべて).{0,8}(?:指示|命令|ルール).{0,8}(?:無視|むし)"
- r"|(?:透露|泄露|泄漏|显示|輸出|输出|公开).{0,8}(?:系统|系統|提示词|提示詞|密钥|密鑰|秘密)"
- r"|システムプロンプト.{0,8}(?:表示|公開|出力)",
- re.I,
- ),
- "Removed CJK prompt-injection instruction before upload.",
- "redact",
- "high",
- ),
- (
- "prompt-injection-eu",
- re.compile(
- r"игнорир\w*.{0,45}(?:инструкц|указан|систем|предыдущ)"
- r"|раскр\w*.{0,25}(?:систем|промпт)"
- r"|\bignora\w*\b.{0,40}\binstruccion\w*"
- r"|\brevela\w*\b.{0,25}(?:prompt|sistema)"
- r"|\bignore[zr]?\b.{0,45}instructions?\s+pr[ée]c[ée]dentes"
- r"|r[ée]v[eè]l\w*.{0,25}(?:prompt|syst[eè]me)"
- r"|ignorier\w*.{0,45}anweisung\w*"
- r"|\bzeig\w*\b.{0,25}(?:system|prompt)",
- re.I,
- ),
- "Removed non-English prompt-injection instruction before upload.",
- "redact",
- "high",
- ),
- ]
- # Compact rules matched against the fully-squished shadow (no separators). These
- # defeat separated-letter obfuscation (``i.g.n.o.r.e``, ``o_v_e_r_r_i_d_e``) that
- # has no word boundaries. Kept tight (verb immediately followed by malicious
- # target within a short gap) so concatenated benign prose does not match.
- _SQUISH_RULES: list[tuple[str, re.Pattern[str], str, str, str]] = [
- (
- "prompt-injection",
- re.compile(
- r"(?:ignore|disregard|override|forget|bypass|skip)\w{0,3}(?:all|any|the|your|previous|prior|earlier|above|system|developer){0,4}"
- r"(?:instruction|prompt|rule|directive|guideline|guardrail|constraint|safety)",
- ),
- "Removed prompt-injection style instruction before upload.",
- "redact",
- "high",
- ),
- (
- "prompt-injection",
- re.compile(
- # Canonicalisation strips spaces to defeat "o u t p u t t o k e n",
- # which also fused the ordinary phrase "output tokens" into a match.
- # Named targets stay loose; the generic ones (secret/token/password)
- # now need a possessive or definite filler, so "output tokens" and
- # "token budget" read as prose while "output your token" still does not.
- r"(?:reveal|print|show|expose|output|dump|leak|repeat|echo)\w{0,3}"
- r"(?:(?:the|your|my|me|all|user|admin|its|his|her){0,3}"
- r"(?:systemprompt|hiddeninstruction|developermessage|apikey)"
- r"|(?:the|your|my|me|all|user|admin|its|his|her){1,3}"
- r"(?:secret|token|password|credential)s?)",
- ),
- "Removed prompt-injection style instruction before upload.",
- "redact",
- "high",
- ),
- (
- "instruction-reset",
- re.compile(r"(?:override|disable|bypass|remove)(?:the|system|all){0,3}(?:safety|guardrail|sandbox|restriction|filter)"),
- "Removed instruction-reset directive before upload.",
- "redact",
- "high",
- ),
- (
- "secret-exfiltration",
- re.compile(
- r"(?:exfiltrate|transmit|leak|steal|dump|forward|upload)(?:the|my|user){0,3}"
- r"(?:secret|token|apikey|password|credential|env|keychain|session|privatekey)",
- ),
- "Removed secret-access or exfiltration instruction before upload.",
- "redact",
- "high",
- ),
- ]
- # Invisible-content tripwire: a line whose *rendered* form loses characters to
- # invisible/format smuggling is itself suspicious. Flagged when no stronger rule
- # already fired, so legitimate content survives but reviewers are alerted.
- _INVISIBLE_RE = re.compile(r"[--]")
- Note: Usual in code (characters a sanitizer strips): Contains 4 bidirectional-override character(s), which make text display in a different order from how it's read
- Line 486 on GitHub
- # --------------------------------------------------------------------------- #
- # Precision guards — keep quality high, avoid over-redaction
- # --------------------------------------------------------------------------- #
- # Negation preceding a dangerous token turns a directive into advice.
- # Kept intentionally narrow: only unambiguously *defensive* markers. Words like
- # "not"/"without" were removed — attackers use them ("act without restrictions").
- _NEGATION_RE = re.compile(
- # English negation. "no longer" etc. handled elsewhere; here we cover the
- # imperative and modal negations a safety instruction actually uses:
- # "never read a secret", "must not print", "do not commit", "without exposing".
- # NOTE: "without" is deliberately NOT here. It cuts both ways —
- # "without exposing the value" is safe, but "use keychain creds without
- # asking" is an approval bypass. never/not/않- already cover the safety copy,
- # so admitting "without" would only reintroduce a real-attack false negative.
- r"\b(?:never|do not|don't|dont|does not|doesn't|must not|mustn't|"
- r"should not|shouldn't|cannot|can't|won't|will not|avoid|"
- r"no\b|not\b|instead of|rather than|prefer)\b|"
- # Korean negation. The old rule only caught imperative prohibitions
- # (하지마/금지/절대); safety copy far more often uses the declarative negative
- # ENDING — "출력하지 않습니다", "읽지 않고", "요구하지 않으며". Without these,
- # "API 키 값은 출력하지 않습니다" (a security promise) was redacted as an
- # exfiltration instruction. Match the 않- negator and the 지 않 construction,
- # plus "~로만"/"이름만" (name-only) framing that safety copy uses.
- r"하지\s*마|하지마|금지|말\s*것|말아야|절대|"
- r"않\s*(?:습니다|는다|아|으며|고|은|을|다)|지\s*않|"
- r"이름(?:으로)?만|명칭(?:으로)?만|name(?:s)?\s*only|by\s*name",
- re.I,
- )
- # Educational / quoted context: the trigger appears inside quotes and the line is
- # about language, examples, or defense — not an instruction to the model.
- _EDU_CONTEXT_RE = re.compile(
- r"\b(?:translate|translation|phrase|means?|spelled|definition|"
- r"defend|defense|protect|detect|explain|lesson|teach|tutorial|what is|documentation)\b"
- # "example" but NOT the reserved domains example.com / example.invalid / …
- r"|\bexamples?\b(?!\.\w)"
- r"|번역|예시|예문|방어|설명|정의",
- re.I,
- )
- _QUOTED_RE = re.compile(r"""['"“”‘’「」『』]""")
- # Descriptive / educational framing: the line is *talking about* an attack,
- # capability, or command — not issuing one. Security-training, prompt-engineering,
- # devops-docs, and audit agents legitimately mention these terms. When such
- # framing co-occurs with a risky pattern the line is KEPT and flagged for review,
- # never blindly deleted (quality preservation is the top priority).
- # Strong meta-verbs only. Weak nouns ("example", "docs", "guide") were removed —
- # they collide with payloads and domains like ``evil.example.com``. Legitimate
- # quoted examples are handled by the separate quote path (_is_educational_quote).
- _DESCRIPTIVE_RE = re.compile(
- r"\b(?:explains?|explained|explaining|describes?|described|teaches?|teaching|"
- r"reports? (?:whether|on|if)|detects?|detecting|defends?|defense|defensive|"
- r"awareness|tutorial|lesson|demonstrates?|audit(?:s|ing)?|reviews?|"
- r"how to (?:install|run|use|write|defend|detect|configure|set up)|"
- r"what (?:it|this|a|the)?\s*(?:does|is|means?)|why (?:you|it|this|piping|running|not))\b"
- r"|\b(?:attackers?|hackers?|adversar\w+|threat actors?|malicious (?:users?|actors?|input))\b"
- r".{0,50}\b(?:try|tries|attempt|attempts|may|might|could|would|will|can)\b"
- # list-header framing: "Today's words:", "Glossary:", "Key terms:" — an
- # enumeration of vocabulary, not a directive.
- r"|\b(?:words?|vocabulary|glossary|terms?|keywords?|lexicon)\b\s*[::]"
- # The Korean half of the same idea. Every marker above had an English form
- # and no Korean one, so a security specialist writing in Korean had its own
- # documentation read as an attack: an attack catalog entry, a test procedure,
- # a list of what must NOT be persisted. Measured 2026-08-07: one published
- # security agent produced 21 redactions this way, all of them describing
- # attacks it exists to detect.
- #
- # These are documentation words. An actual injection payload does not
- # introduce itself as a catalog entry, a checklist, or a mitigation.
- r"|(?:카탈로그|취약점|취약|점검|탐지|진단|재현|완화|대응|대책|"
- r"체크리스트|시나리오|공격\s*유형|공격\s*기법|위협\s*모델|"
- r"테스트|검증|감사|리뷰|보고서|절차|설명|정의|예시|목록|"
- r"저장하지|기록하지|남기지|포함하지|노출하지|"
- # Assessment words. "노출 여부 체크" is checking WHETHER something leaked;
- # "형식 파악" is working out a shape. An instruction to exfiltrate does not
- # ask whether, it tells you to send — so these read as inspection, and they
- # are what a security agent's own test procedure is written with.
- r"여부|파악|식별|분류|판정|확인한다|살펴본다)"
- # Security-hygiene directives: a line telling the agent to PROTECT secrets —
- # rotate them, never expose them, report a found leak — reads as defensive,
- # not as an exfiltration instruction. Without this, "secrets must be rotatable
- # so a leak is recoverable" and "never expose credentials or leak data" were
- # redacted as attacks. These verbs only appear in defensive guidance.
- r"|\b(?:rotate|rotates|rotating|rotatable|rotation|recoverable|"
- r"revoke|revokes|revoking|revocation|revert|reverts|reverting|"
- r"do not expose|never expose|must not expose|not be exposed|"
- r"if you find|when you find|report (?:a|an|the|any)|flag (?:a|an|the|any))\b"
- # A defensive specialist must be able to name the attack it defends against
- # and the approval workflow it participates in. Without these, a red-team or
- # migration package could not describe its own scope: "probes prompt-injection
- # paths", "the named human who may approve or grant a waiver", and a
- # Boundaries line saying what the agent refuses were all scored as attacks.
- r"|\b(?:simulat\w+|probes?|probing|red[- ]?team\w*|penetration test\w*|"
- r"threat model\w*|scope of work|boundaries|out of scope|refuses?|refusing|"
- r"declines?|declining|does not|will not|cannot)\b"
- # Bare "approval" is not safe to treat as descriptive: "run shell with auto
- # approval" and "rm -rf / after approval" are attack lines. Only role nouns
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 584 on GitHub
- # and explicit human-gate phrases qualify.
- r"|\b(?:approver|approvers|waiver|waivers|sign-?off|signs? off|"
- r"authori[sz]ed by|accountable for|human approval|requires? approval|"
- r"approval (?:gate|workflow|chain)|pending approval)\b"
- r"|설명(?:합니다|하는|해)?|방어(?:합니다|하는|법)?|교육|점검(?:합니다|하는)?|감사(?:합니다|하는)?|튜토리얼|예문|단어\s*[::]"
- # Korean security-hygiene directives: rotate / never expose / report a found leak.
- r"|회전|폐기|노출(?:하지|되지)\s*(?:마|않)|발견(?:하면|하거든|시)|보고(?:합니다|하세요|해)?",
- re.I,
- )
- def _is_negated(line: str, canon: str) -> bool:
- return bool(_NEGATION_RE.search(line)) or bool(_NEGATION_RE.search(canon))
- def _is_educational_quote(line: str) -> bool:
- return bool(_QUOTED_RE.search(line)) and bool(_EDU_CONTEXT_RE.search(line))
- def _is_descriptive(line: str) -> bool:
- return bool(_DESCRIPTIVE_RE.search(line))
- # Prose directive families whose matches are DOWNGRADED to a kept+flagged finding
- # when a precision guard fires (negation, quoted-for-teaching, or descriptive
- # framing). Non-prose signals — invisible chars, exfil beacons, hard-coded
- # secrets, private keys — are never downgraded.
- _GUARDABLE = {
- "prompt-injection",
- "prompt-injection-ko",
- "prompt-injection-cjk",
- "prompt-injection-eu",
- "instruction-reset",
- "privilege-escalation",
- "secret-exfiltration",
- "secret-exfiltration-ko",
- "secret-access",
- "dangerous-command",
- "persistence",
- "encoded-execution",
- }
- _CONFIG_LINE_RE = re.compile(
- # A JSON string-array of glob patterns, e.g. `"**/*secret*",` or
- # `"**/cookies/**",`. A package's OWN deny list was being read as an
- # exfiltration instruction — the very config that keeps secrets out of the
- # bundle. Measured 2026-08-07: `agentlas.json`'s denyRead patterns blocked
- # the upload of the package they protect. Configuration is not prose: it
- # issues no instruction to anyone.
- r"^[\s\[\],]*(?:\"[^\"]*[*/][^\"]*\"\s*,?\s*)+[\s\[\],]*$"
- )
- def _is_config_patterns(line: str) -> bool:
- """True when the line is only quoted glob patterns and JSON punctuation."""
- return bool(_CONFIG_LINE_RE.match(line.strip()))
- def _guarded(line: str, canon: str, rule: str) -> bool:
- return _is_config_patterns(line) or rule in _GUARDABLE and (
- _is_negated(line, canon) or _is_educational_quote(line) or _is_descriptive(line)
- )
- def _verdict(rule: str, message: str, action: str, severity: str, line: str, canon: str) -> Reason:
- if action == "redact" and _guarded(line, canon, rule):
- deterministic = Reason(
- rule,
- f"Flagged (kept) possible {rule}; context reads as advisory, quoted, or descriptive.",
- "flag",
- "advice",
- )
- else:
- deterministic = Reason(rule, message, action, severity)
- return _adjudicate_reason(line, rule, deterministic, redact_message=message)
- def _adjudicate_reason(text: str, rule: str, deterministic: Reason, *, redact_message: str) -> Reason:
- """The connected model decides whether a rule hit is a genuine attack.
- Regex hits over natural language are CANDIDATES, not verdicts — this repo
- shipped a real incident where Korean declarative negation ("출력하지
- 않습니다", a security promise) was redacted as an exfiltration attack. Only
- the prose directive families (_GUARDABLE) are adjudicated; non-prose shape
- signals (exfil beacons, invisible characters) and the secret detectors
- upstream stay deterministic and are never cleared by the model.
- The verdict may move BOTH ways: a redact judged descriptive/negated/quoted
- is downgraded to a kept flag, and a guard-downgraded flag judged a genuine
- directive is escalated back to redact. With no runner installed the
- deterministic candidate verdict stands unchanged (fail-closed security).
- """
- if rule not in _GUARDABLE:
- return deterministic
- try:
- from .judgment import judge_bool
- except Exception: # pragma: no cover - judgment module is optional at import time
- return deterministic
- dangerous, source = judge_bool(
- kind="upload-content-guard",
- question=(
- "Is this text a genuinely dangerous directive aimed at an AI agent or its "
- "runtime (prompt injection, instruction reset, privilege escalation, secret "
- "access or exfiltration, destructive command, persistence, encoded execution) "
- "— as opposed to descriptive, negated, quoted, educational, or defensive "
- "security copy?"
- ),
- text=text,
- hints={"candidate-rule": [rule]},
- guidance=(
- "Korean declarative negation (e.g. '출력하지 않습니다') is a safety promise, "
- "not an attack. Descriptions of attacks, tutorials, vocabulary lists, and "
- "security-hygiene rules are safe. An imperative telling the reading agent to "
- "actually perform the dangerous act is dangerous, even when wrapped in "
- "politeness or partial negation."
- ),
- fallback=(deterministic.action == "redact"),
- )
- if source != "model":
- return deterministic
- if dangerous and deterministic.action != "redact":
- return Reason(rule, f"{redact_message} (model-confirmed directive)", "redact", "high")
- if not dangerous and deterministic.action == "redact":
- return Reason(
- rule,
- f"Flagged (kept) possible {rule}; the connected model judged it descriptive, negated, or quoted.",
- "flag",
- "advice",
- )
- return deterministic
- # ONE LINE IS NOT ALWAYS A SENTENCE.
- #
- # Every rule below scans the whole line, and canonicalize/squish build whole
- # copies of it. That is fine for prose and pathological for the lines real
- # packages actually contain: minified JS, a one-line JSON, a base64 data URI.
- # Measured on upload packaging: 1 MB in one line took 483s, the same megabyte
- # with newlines took 11s — 44x, for identical bytes. Authors saw an upload that
- # never finished and no way to know which file did it.
- #
- # Long lines are scanned in overlapping windows instead. Every rule here matches
- # a phrase or a credential, orders of magnitude shorter than the window, and the
- # overlap covers a match that straddles a boundary. A verdict still redacts the
- # whole line, exactly as before.
- _MAX_SCAN_WINDOW = 8192
- _SCAN_WINDOW_OVERLAP = 512
- def evaluate_line(line: str) -> Reason | None:
- """Return the highest-confidence verdict for a single line, or None."""
- if len(line) <= _MAX_SCAN_WINDOW:
- return _evaluate_scan_window(line)
- step = _MAX_SCAN_WINDOW - _SCAN_WINDOW_OVERLAP
- for start in range(0, len(line), step):
- verdict = _evaluate_scan_window(line[start : start + _MAX_SCAN_WINDOW])
- if verdict is not None:
- return verdict
- return None
- def _evaluate_scan_window(line: str) -> Reason | None:
- canon = canonicalize(line)
- cjk = _cjk_shadow(line)
- canon_is_raw = canon == line
- cjk_is_raw = cjk == line
- for rule, pattern, message, action, severity in _ENGLISH_RULES:
- if pattern.search(canon) or (not canon_is_raw and pattern.search(line)):
- return _verdict(rule, message, action, severity, line, canon)
- for rule, pattern, message, action, severity in _MULTILINGUAL_RULES:
- if pattern.search(cjk) or (not cjk_is_raw and pattern.search(line)):
- return _verdict(rule, message, action, severity, line, canon)
- # squish(line) would rebuild this exact canonical shadow for every window.
- sq = _NON_ALNUM.sub("", canon)
- for rule, pattern, message, action, severity in _SQUISH_RULES:
- if pattern.search(sq):
- return _verdict(rule, message, action, severity, line, canon)
- if _INVISIBLE_RE.search(line) or any(_TAG_LO <= ord(ch) <= _TAG_HI for ch in line):
- return Reason(
- "invisible-content",
- "Removed line containing hidden/invisible control characters before upload.",
- "redact",
- "high",
- )
- return None
- def find_multiline_spans(lines: list[str]) -> list[SpanReason]:
- """Catch injections split across consecutive lines to evade per-line scans.
- Only high-confidence English/multilingual *injection* concepts are considered
- across a window, to keep collateral low. Returns minimal spans (>1 line)."""
- spans: list[SpanReason] = []
- n = len(lines)
- consumed = [False] * n
- combined_rules = [
- (r, p, m) for (r, p, m, a, s) in _ENGLISH_RULES if r in ("prompt-injection", "instruction-reset", "secret-exfiltration", "encoded-execution")
- ]
- combined_ml = [(r, p, m) for (r, p, m, a, s) in _MULTILINGUAL_RULES]
- for start in range(n):
- if not lines[start].strip():
- continue
- # A window may not START on a structural boundary either. The loop
- # already refuses to join ACROSS a heading or code fence, but starting on
- # one joined "## Output" to the paragraph beneath it and read the pair as
- # a split instruction. Measured 2026-08-07: three published packages were
- # refused that way, each time for ordinary document structure — a heading
- # followed by its own body is not a sentence someone broke in half to
- # evade a scanner.
- if _STRUCTURAL_BOUNDARY_RE.match(lines[start]):
- continue
- acc = lines[start].rstrip("\r\n")
- blank_run = 0
- for end in range(start + 1, min(start + MAX_MULTILINE_WINDOW, n)):
- nxt = lines[end].rstrip("\r\n")
- # A split injection is contiguous prose. Joining across a section
- # heading, a code fence, or a paragraph break invented matches
- # between unrelated text — one build lost a line because
- # "...goes ignored by the third week." and "...and the rule that
- # produced it", two paragraphs and a heading apart, joined into
- # "ignore ... the ... rule". Structural breaks end the window;
- # a single blank line still carries, since that is how a real
- # split reads.
- if _STRUCTURAL_BOUNDARY_RE.match(nxt):
- break
- if not nxt.strip():
- blank_run += 1
- if blank_run > 1:
- break
- continue
- blank_run = 0
- acc = acc + " " + nxt
- # A window that has grown past one scan window is no longer a split
- # sentence; it is a long line already scanned on its own, and
- # re-canonicalizing it once per step is what made a minified file
- # take minutes.
- if len(acc) > _MAX_SCAN_WINDOW:
- break
- canon = canonicalize(acc)
- cjk = _cjk_shadow(acc)
- hit = None
- for rule, pattern, message in combined_rules:
- if pattern.search(canon):
- hit = (rule, message)
- break
- if hit is None:
- for rule, pattern, message in combined_ml:
- if pattern.search(cjk):
- hit = (rule, message)
- break
- if hit is None:
- continue
- # only claim it if NO single line in the window already fires (true split)
- if any(evaluate_line(lines[k]) and evaluate_line(lines[k]).action == "redact" for k in range(start, end + 1)):
- break
- if all(not consumed[k] for k in range(start, end + 1)):
- rule, message = hit
- # A descriptive/quoted/negated window is kept and flagged, not
- # deleted — a split educational paragraph must survive intact.
- if _guarded(acc, canon, rule):
- deterministic = Reason(
- rule, f"Flagged (kept) split {rule}; context reads as descriptive.", "flag", "advice"
- )
- else:
- deterministic = Reason(rule, f"{message} (split across lines)", "redact", "high")
- adjudicated = _adjudicate_reason(
- acc, rule, deterministic, redact_message=f"{message} (split across lines)"
- )
- action, severity, msg = adjudicated.action, adjudicated.severity, adjudicated.message
- spans.append(SpanReason(start, end, rule, msg, action, severity))
- for k in range(start, end + 1):
- consumed[k] = True
- break
- return spans
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.