Local WASM and managed cloud runtimes with bounded dynamic workflows, live capability discovery and session-local mod policy.

Agent runtimes for ruflo — one mental model, two backends (a third planned):
| Runtime | Tools | Runs on | Trust | Best for |
|---|---|---|---|---|
WASM (rvagent) | wasm_agent_* / wasm_gallery_* | local WASM sandbox | sandboxed — no host fs/net | untrusted code; portable/replayable RVF containers; fast, free, offline |
| Managed (Anthropic cloud) | managed_agent_* | Anthropic-managed container | cloud-isolated | long-running/async tasks; real container with packages + network; persistent filesystem + transcript across turns; no local setup |
| SDK (planned — ADR-116) | sdk_agent_* | your process / your filesystem | full host trust | a real Claude agent loop (hooks, subagents, MCP, sessions, skills) on the local repo — the in-process version of claude -p; the killer combo is mcpServers: { ruflo: { command: "npx", args: ["ruflo","mcp","start"] } } (a local stdio MCP server → the agent gets ruflo's 314 tools, zero deployment) |
wasm_agent_* is the safe default (sandboxed). managed_agent_* needs ANTHROPIC_API_KEY (or CLAUDE_API_KEY) + Claude Managed Agents beta access — every managed_agent_* tool degrades gracefully with a structured "use wasm_agent_create for a local no-key runtime" error when the key is absent.
Design: ADR-115 (the cloud runtime + the planned SDK runtime); ADR-070 (the WASM runtime); plugin contract docs/adrs/0001-wasm-contract.md.
Renamed from
ruflo-wasm(it only covered the local WASM runtime). Thewasm_agent_*/wasm_gallery_*tool names are unchanged.
/plugin marketplace add ruvnet/ruflo
/plugin install ruflo-agent@ruflo
/wasm — list running WASM agents and browse the gallery (local runtime)/managed-agent — list Managed Agent cloud sessions, check status, fetch a transcript, clean up (cloud runtime)wasm-agent — create and manage sandboxed WASM agents (local)wasm-gallery — browse and publish agents in the community gallerymanaged-agent — run an Anthropic Claude Managed Agent (cloud) — create / prompt / status / events / list / terminatenested-subagents — spawn nested sub-agent trees (depth ≤ 5) via Claude Code's native Task tool for context-managed deep delegationwasm_agent_*, 13 wasm_gallery_*, 10 managed_agent_*)v3/@claude-flow/cli/src/mcp-tools/wasm-agent-tools.ts (27 in total; the main ones)| Tool | Purpose |
|---|---|
wasm_agent_create | Spin up a sandboxed WASM agent |
wasm_agent_prompt | Send a prompt to the agent |
wasm_agent_tool | Invoke a tool inside the sandbox |
wasm_agent_list | List active WASM agents |
wasm_agent_terminate | Stop a WASM agent |
wasm_agent_files | Read/write files in the sandbox |
wasm_agent_export | Export agent state (RVF container) |
wasm_gallery_list | Browse community-published WASM agents |
wasm_gallery_search | Search the gallery |
wasm_gallery_create | Publish a WASM agent to the gallery |
v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts (10, ADR-115, ADR-0003, ADR-0004)| Tool | Purpose | WASM counterpart |
|---|---|---|
managed_agent_control | Inspect, interrupt or terminate through fresh host allowlist and provider checks | Console confirm card |
managed_agent_learning | Quarantine outcomes, verify host receipts, recommend, compare, index and recall evidence | Learning page |
managed_agent_capabilities | Local adapter requirements and integration boundaries; no key or network needed | /agent-mod capabilities |
managed_agent_create | Provision Agent + Environment + Session (POST /v1/agents, /v1/environments, /v1/sessions). Accepts model / system / name / networking / packages / initScript / mcpServers / skills. | wasm_agent_create |
managed_agent_prompt | Send a user turn (POST /v1/sessions/{id}/events), poll until the session goes idle (default 180 s, cap 600 s) → {finished, status, stopReason, assistantText, toolUses[], eventCount} | wasm_agent_prompt |
managed_agent_status | Session lifecycle state (idle/running/error, title, last error) | — |
managed_agent_events | Full server-persisted event log + a summary (the transcript/artifact view) | wasm_agent_files |
managed_agent_list | List Managed Agent sessions on the org (id, status, title) — see which are still billing | wasm_agent_list |
managed_agent_interrupt | Queue a pause request; never confirms workflow cancellation | wasm_agent_terminate |
managed_agent_terminate | DELETE /v1/sessions/{id} (± the environment) — always call when done; running sessions consume runtime and tokens | wasm_agent_terminate |
Beta API (
anthropic-beta: managed-agents-2026-04-01);multiagent/define-outcomeson the agent config are research preview.mcpServersfor a cloud agent must point at a publicly reachable URL — a localruflo mcp startis not reachable from Anthropic's cloud (deploy/tunnel an HTTP ruflo MCP server first). Managed sessions cost LM tokens + container time and are rate-limited per org.
@claude-flow/cli v3.6 major+minor.@ruvector/rvagent-wasm + @ruvector/ruvllm-wasm (declared in @claude-flow/cli's optionalDependencies per ADR-070). Without those packages, the wasm_agent_* tools fall through to graceful-degradation no-ops.fetch against the Managed Agents REST API — no extra SDK dependency. Without ANTHROPIC_API_KEY / CLAUDE_API_KEY, every managed_agent_* tool returns a structured error pointing at the wasm_agent_* fallback (the CLI/MCP server stays up).bash plugins/ruflo-agent/scripts/smoke.sh is the contract (16 structural checks). CI: .github/workflows/ruflo-agent-smoke.yml. Behavioral guard for the cloud tools: v3/@claude-flow/cli/__tests__/managed-agent-tools.test.ts (no-network).WASM agents run with no host filesystem access by default; wasm_agent_files exposes a sandboxed virtual filesystem only. Managed agents run in Anthropic's cloud container (isolated from your machine). The planned SDK runtime would run in your process with full host trust — which is why wasm_agent_* stays the default and the SDK runtime, when built, will be opt-in.
For prompt-injection defense on output flowing back to the host LLM, the ruflo-aidefence 3-gate pattern applies.
This plugin owns the wasm-gallery AgentDB namespace (kebab-case, per ruflo-agentdb ADR-0001 §"Namespace convention"). Reserved namespaces (pattern, claude-memories, default) MUST NOT be shadowed. wasm-gallery indexes published WASM agents (manifest, version, signature, download count); accessed via memory_* (namespace-routed).
bash plugins/ruflo-agent/scripts/smoke.sh
# Expected: "16 passed, 0 failed"
ADR-0001 — ruflo-agent plugin contract (WASM runtime: 10-tool MCP surface, ADR-070 integration, sandbox isolation, smoke as contract)ADR-115 — Claude Managed Agents as the cloud runtime (+ the planned SDK runtime, ADR-116)ruflo-agentdb — namespace convention ownerruflo-aidefence — 3-gate pattern applies to agent output flowing back to the host LLMruflo-ruvector — the ruvector substrate that ships @ruvector/rvagent-wasmruflo-cost-tracker — record completed Managed Agent sessions (LM tokens + container time)Agent also ships as a function-hook mod (ADR-445 pattern; hooks in hooks/, loaded with the plugin). No network, no process, no model call.
wasm_agent_prompt, wasm_agent_tool, wasm_agent_create, wasm_gallery_create, managed_agent_create, managed_agent_prompt) that holds a key, token or password. It only tightens: it never allows anything the session would deny, and the refusal never repeats the secret. Turn it off with the guard option./agent-mod: answered locally. /agent-mod status, /agent-mod scan <text>, /agent-mod guarded..claude-flow/agent-mod/status.json (version, updatedMs, counters), written at session start and whenever a call is refused; the console reads it.userConfig): guard (on by default).Test: claude plugin validate plugins/ruflo-agent, claude plugin test plugins/ruflo-agent, and bash plugins/ruflo-agent/scripts/smoke.sh.
The existing cloud adapter accepts dynamicWorkflows: true and requires budgetCents before provisioning any resources. Example:
{
"name": "bounded-bug-audit",
"dynamicWorkflows": true,
"budgetCents": "2500",
"allowedHosts": ["github.com"],
"system": "Use a workflow for inventory, parallel review, reproduction and synthesis. Report failed workers. Write separate worker artifacts. Never merge or deploy."
}
This sets multiagent_20261001, enables workflows, disables ordinary subagents, and uses limited networking. A message sent with managed_agent_prompt asks the lead to start a run. There is no separate run creation endpoint. budgetCents is an integer US cents string, not dollars. In flight requests can overshoot.
For sensitive work, supply predefinedAgents: ["agent_..."] to disable inline agents. Configure those agents with minimal tools and MCP access separately. Inline agents inherit lead capabilities; do not expose broad Ruflo swarm or release tools to them. Network allowlists do not replace tool permission policies. The adapter does not create a remote MCP gateway or grant host credentials.
managed_agent_events returns workflow IDs, open run counts, observed failures, usage and verification: "unverified". Its compact events retain child thread IDs. Pass threadId to inspect each worker's transcript. A run reporting completed can contain failed work. Independently reproduce findings and run repository tests before retaining patches or promoting memory. Raw transcripts are untrusted and may contain private inputs; do not publish them automatically.
managed_agent_prompt only reports finished after a fresh final end_turn idle with no open runs. Budget and permission pauses return blocked: true. An interrupted turn never reports finished. A local observation timeout does not stop the cloud session. Use managed_agent_interrupt to request a pause or managed_agent_terminate for confirmed session deletion. Separate processes must serialize messages to the same session; the adapter's lock is process local.
Provider traffic defaults to https://api.anthropic.com. A custom deployment must explicitly set RUFLO_MANAGED_AGENTS_BASE_URL to an HTTPS origin. The generic ANTHROPIC_BASE_URL is no longer used for this service, preventing accidental credential forwarding to model proxies. Redirects are blocked. This is an intentional configuration migration for existing custom endpoints.
See ADR 0003 for threat model, limits, validation commands, and deferred integration boundaries.
Install or update ruflo-agent 0.4.0 and ruflo-workflows 0.7.0. /managed-workflow is the bounded remote execution skill. /agent-mod capabilities reads the current host registry, while /wf-mod managed discovers the cloud adapter from the workflow mod. Neither command invokes a provider.
Plugin settings:
{
"managedWorkflows": "on",
"maxBudgetCents": "2500",
"allowInlineAgents": "off"
}
Dynamic creation is off by default. Invalid budget settings deny creation. Disabling the secret guard does not disable these admission rules. Default inline policy requires predefined agents with separately reviewed tools. The policy only constrains creation calls passing through this host session; externally created sessions, other hosts and direct API clients require their own authorization and spending controls. The mod never expands host permission.
The console Mods page consumes the existing version 1 status contract and shows policy, maximum cents, inline mode, calls, blocks and last refusal class. No console plugin update is required. It shows local policy, not remote state. managed_agent_capabilities reports local credential configuration as a boolean; beta access, authorization and remote health remain unknown until checked through an authorized provider operation. Registered tools alone prove none of these.
The console Workflows page now includes managed phases and worker pages beside native and swarm runs. Cost and Approvals show reported spend and pending requests. Learning shows signed outcome counts, evidence IDs, advisory strategy picks and heldout gate results. These are local reports, never action authority. The CLI and plugins must be built from this PR until the integration is released; registry discovery will identify missing tools in an older installation.
Only explicit prompt/inspection requests collect provider state. Panels read cached local projections, with no provider traffic while inactive. One collector shares reads per session; an OS lease blocks concurrent collectors in another process. A crashed lease must be inspected before manual recovery. Sessions have separate freshness timestamps and partial worker pages retain aggregate counts.
Host controls:
RUFLO_MANAGED_CONTROL=1
RUFLO_MANAGED_CONTROL_SESSIONS=sesn_example
RUFLO_MANAGED_LEARNING=1
RUFLO_MANAGED_VERIFIER_PUBLIC_KEY=<trusted Ed25519 public PEM from host configuration>
These settings are off or absent by default. A console confirmation cannot supply them. Control dispatch rechecks both host policy and fresh provider state. Learning accepts only closed metadata; raw transcripts, arbitrary commands and caller trust labels are rejected. Unsigned observations remain quarantined. The independent host verifier signs source/artifact/policy/corpus/evaluator identities, measured cost/latency and actual test results. The private key never belongs in an agent prompt or MCP argument.
managed_agent_learning actions: status, record, recommend, evaluate, index, recall. Recommendations use training receipts only. Heldout results cannot teach the recommender or enter the memory index. Evaluation requires a complete paired frozen corpus, at least three trials, equal admitted budgets, at least 10% better successes per dollar, and safety/quality/latency gates plus the existing MetaHarness conjunction. It never changes routing defaults. Native append-only memory indexing and semantic recall are optional; absent embeddings or backends are reported instead of being called a successful vector integration. See ADR 0004.
The host runs scripts/managed-outcome-verifier.mts with a reviewed, owned manifest and private signing key held outside test environments. Separate acceptance, safety, replay and adversarial checks measure actual exits; source, artifact and cost bindings are checked before signing. This trusted host utility is not an arbitrary command tool for agents.
managed_agent_learning action cycle admits up to 24 signed measured outcomes, records one atomic batch, optionally indexes six training outcomes, recalls, recommends and evaluates a complete paired holdout. Its result is advisory; it never starts model work or promotes defaults. scripts/e2e-managed-loop.mts exercises the verifier and feedback path. scripts/e2e-managed-provider.mts is a separate opt-in live canary and exits blocked without provider credentials and predefined worker IDs. The native memory worker isolates crashes and timeouts; it does not provide an operating-system memory sandbox. See ADR 0004.
hooks/register.ts 66 lines1import type { Hook, Register } from 'claude-code'
2
3import { answer } from './command'
4import { owns, verdict } from './guard'
5import { managedCapabilities, managedName, managedVerdict } from './managed'
6import { readOptions } from './options'
7import { newStats, STATUS_PATH, statusText, type Stats } from './status'
8import type { ModOptions } from './options'
9
10type Dollar = Parameters<Hook<'session.start'>>[0]
11
12/** Everything one session of the mod keeps: its settings, counters and the project root. */
13type Session = { readonly opts: ModOptions; readonly stats: Stats; root?: string }
14
15async function flush($: Dollar, s: Session): Promise<void> {
16 if (s.root === undefined) return
17 try {
18 await $.fs.write(`${s.root}/${STATUS_PATH}`, statusText(s.stats, s.opts, await $.clock.now()))
19 } catch {
20 /* the status file is a courtesy */
21 }
22}
23
24/**
25 * Agent as a mod (ADR-445 pattern): a tighten-only guard on text sent into an agent runtime (`wasm_agent_prompt`, `wasm_agent_tool`, `wasm_agent_create`, `wasm_gallery_create`, `managed_agent_create`, `managed_agent_prompt`), `/agent-mod`, and a status file the console reads.
26 * No network, no process: only the hooks API.
27 */
28export const register: Register = (on, options) => {
29 const s: Session = { opts: readOptions(options), stats: newStats() }
30
31 on('session.start', async ($, e, next) => {
32 const result = await next(e)
33 s.root = (await $.session.root()) as string | undefined
34 s.stats.startedMs = await $.clock.now()
35 try {
36 await $.command.register({ name: 'agent-mod', description: 'Agent mod: status, scan <text>, guarded, capabilities' })
37 } catch {
38 /* a name taken by another plugin must not stop the mod */
39 }
40 await flush($, s)
41 return result
42 })
43
44 {
45 on('tool.call', async ($, e, next) => {
46 if (!owns(e.tool, e) && !managedName(e.tool)) return next(e)
47 s.stats.calls++
48 const policyReason = managedVerdict(e.tool, e, s.opts)
49 const reason = policyReason ?? (s.opts.guard ? verdict(e.tool, e) : undefined)
50 if (reason !== undefined) { s.stats.blocked++; s.stats.lastDenied = policyReason ? 'policy' : 'secret' }
51 await flush($, s)
52 return reason === undefined ? next(e) : { deny: reason }
53 })
54 }
55
56 /** `/agent-mod` (a markdown command of the plugin cannot be answered by a hook, so the mod owns this name). */
57 on('command.run', { command: 'agent-mod' }, async ($, e) => {
58 const args = typeof e.args === 'string' ? e.args : ''
59 if (args.trim() === 'capabilities') {
60 try { return { text: managedCapabilities((await $.tool.list()).map(t => t.name), s.opts) } }
61 catch { return { text: 'Tool discovery unavailable; managed runtime readiness is unknown.' } }
62 }
63 return { text: answer(args, { opts: s.opts, stats: s.stats }) }
64 })
65}
66hooks/command.ts 32 lines1import { scan } from './screen'
2import type { ModOptions } from './options'
3import type { Stats } from './status'
4
5/** `/agent-mod` is answered locally and takes no model turn. */
6export type CommandDeps = { readonly opts: ModOptions; readonly stats: Stats }
7
8const HELP = ['/agent-mod status', '/agent-mod scan <text>', '/agent-mod guarded', '/agent-mod capabilities'].join('\n')
9
10export function answer(args: string, deps: CommandDeps): string {
11 const [verb = '', ...rest] = args.trim().split(/\s+/)
12 const arg = rest.join(' ')
13 const { opts, stats } = deps
14
15 if (verb === '' || verb === 'help') return HELP
16
17 if (verb === 'status') {
18 return `guard ${opts.guard ? 'on' : 'off'} · calls guarded ${stats.calls} · blocked ${stats.blocked}\nManaged workflow policy ${opts.managedWorkflows ? 'on' : 'off'}; maximum ${opts.maxBudgetCents} US cents; inline ${opts.allowInlineAgents ? 'on' : 'off'}`
19 }
20
21 if (verb === 'scan') {
22 if (arg === '') return 'usage: /agent-mod scan <text>'
23 const found = scan(arg)
24 const parts = [found.secrets.length ? `secrets: ${found.secrets.join(', ')}` : '', found.injection.length ? `injection phrasing: ${found.injection.join(', ')}` : ''].filter(Boolean)
25 return parts.length ? `The guard would refuse a write of that (${parts.join('; ')}).` : 'Nothing found: the guard would let that through.'
26 }
27
28 if (verb === 'guarded') return 'Guarded tools: wasm_agent_prompt, wasm_agent_tool, wasm_agent_create, wasm_gallery_create, managed_agent_create, managed_agent_prompt.'
29
30 return `Unknown: ${verb}\n${HELP}`
31}
32hooks/guard.ts 24 lines1import { hasSecret } from './screen'
2import { textsOf } from './screen'
3export { textsOf }
4
5/** `mcp__<server>__<tool>` into its two halves; tool names never hold a double underscore. */
6export function splitName(name: string): { server: string; tool: string } | undefined {
7 if (!name.startsWith('mcp__')) return undefined
8 const at = name.lastIndexOf('__')
9 return at > 5 ? { server: name.slice(5, at), tool: name.slice(at + 2) } : undefined
10}
11
12/** True for the tool calls this plugin guards: text sent into an agent runtime (`wasm_agent_prompt`, `wasm_agent_tool`, `wasm_agent_create`, `wasm_gallery_create`, `managed_agent_create`, `managed_agent_prompt`). */
13export function owns(tool: string, input: unknown): boolean {
14 const parts = splitName(tool)
15 const name = parts?.tool ?? tool
16 return ['wasm_agent_prompt', 'wasm_agent_tool', 'wasm_agent_create', 'wasm_gallery_create', 'managed_agent_create', 'managed_agent_prompt', 'managed_agent_learning'].includes(name)
17}
18
19/** The reason a call is refused, or undefined when it may go. Never names or echoes the secret. */
20export function verdict(tool: string, input: unknown): string | undefined {
21 if (!owns(tool, input)) return undefined
22 return textsOf(input).some(hasSecret) ? "ruflo-agent: this agent input holds what looks like a secret (a key, token or password). An agent runtime, and a cloud one above all, must not be handed the value; pass a reference instead." : undefined
23}
24hooks/managed.ts 58 lines1import type { ModOptions } from './options'
2import { splitName } from './guard'
3
4export const MANAGED_TOOLS = ['managed_agent_capabilities', 'managed_agent_learning', 'managed_agent_control', 'managed_agent_create', 'managed_agent_prompt', 'managed_agent_status', 'managed_agent_events', 'managed_agent_list', 'managed_agent_interrupt', 'managed_agent_terminate'] as const
5
6const record = (v: unknown): Record<string, unknown> | undefined => v !== null && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : undefined
7
8/** Argument wrappers a host may use. Only these are read; arbitrary descendants are never scanned as policy. */
9const WRAPPERS = ['input', 'arguments', 'tool_input', 'params', 'args', 'parameters'] as const
10
11/**
12 * Host tool envelopes may be flat or hold the arguments in one wrapper. A wrapper that is not an object, two wrappers, or a wrapper
13 * next to a flat `dynamicWorkflows` are ambiguous, so they are refused (undefined) rather than read as an envelope with no policy fields.
14 */
15export function managedInput(event: unknown): Record<string, unknown> | undefined {
16 const e = record(event)
17 if (!e) return undefined
18 const present = WRAPPERS.filter(k => k in e)
19 if (present.length === 0) return e
20 if (present.length > 1 || e.dynamicWorkflows !== undefined) return undefined
21 return record(e[present[0]!])
22}
23
24export function managedName(tool: string): string | undefined {
25 const name = splitName(tool)?.tool ?? tool
26 return (MANAGED_TOOLS as readonly string[]).includes(name) ? name : undefined
27}
28
29/** Tightens dynamic creation only; ordinary managed sessions retain their existing behavior. */
30export function managedVerdict(tool: string, event: unknown, opts: ModOptions): string | undefined {
31 if (managedName(tool) !== 'managed_agent_create') return undefined
32 const input = managedInput(event)
33 if (!input) return 'ruflo-agent: malformed managed tool input'
34 if (input.dynamicWorkflows === undefined || input.dynamicWorkflows === false) return undefined
35 if (input.dynamicWorkflows !== true) return 'ruflo-agent: dynamicWorkflows must be boolean'
36 if (!opts.managedWorkflows) return 'ruflo-agent: dynamic workflow policy is off; enable managedWorkflows in plugin settings'
37 if (typeof input.budgetCents !== 'string' || !/^[1-9][0-9]{0,8}$/.test(input.budgetCents) || Number(input.budgetCents) > opts.maxBudgetCents) return 'ruflo-agent: dynamic workflow budget exceeds plugin policy or is invalid'
38 if (input.networking !== undefined && input.networking !== 'limited') return 'ruflo-agent: dynamic workflow network policy requires limited networking'
39 if (!opts.allowInlineAgents && (!Array.isArray(input.predefinedAgents) || input.predefinedAgents.length === 0)) return 'ruflo-agent: plugin policy requires predefined agents; inline agents are off'
40 return undefined
41}
42
43/** Registration is observable; beta access, authorization and remote health are not inferred. */
44export function managedCapabilities(tools: readonly string[], opts: ModOptions): string {
45 const available = new Set(tools.map(t => splitName(t)?.tool ?? t))
46 const present = MANAGED_TOOLS.filter(t => available.has(t))
47 const missing = MANAGED_TOOLS.filter(t => !available.has(t))
48 return [
49 `Managed workflow policy: ${opts.managedWorkflows ? 'on' : 'off'}; maximum ${opts.maxBudgetCents} US cents; inline agents ${opts.allowInlineAgents ? 'on' : 'off'}.`,
50 `Registered managed tools (${present.length}/${MANAGED_TOOLS.length}): ${present.join(', ') || 'none'}.`,
51 `Registry names: ${tools.filter(t => MANAGED_TOOLS.includes((splitName(t)?.tool ?? t) as typeof MANAGED_TOOLS[number])).slice(0, 32).map(t => t.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 160)).join(', ') || 'none'}.`,
52 'Duplicate tool suffixes across servers are ambiguous; select the trusted Ruflo server explicitly.',
53 ...(missing.length ? [`Missing: ${missing.join(', ')}. Install or update ruflo-core and ruflo-agent.`] : []),
54 'Local registration is not authorization, beta access, credential readiness or remote health.',
55 'Use managed_agent_capabilities for runtime configuration facts. Use ruflo-workflows for persisted pipelines, wasm_agent_* for local sandboxing, memory_* only for independently verified evidence.',
56 ].join('\n')
57}
58hooks/options.ts 25 lines1import type { PluginOptions } from 'claude-code'
2
3/** The plugin's `userConfig`, validated: a bad value is the default (guard on). */
4export type ModOptions = {
5 readonly guard: boolean
6 readonly managedWorkflows: boolean
7 readonly maxBudgetCents: number
8 readonly allowInlineAgents: boolean
9}
10
11// BEGIN SHARED FLAG (generated by scripts/sync-mod-screen.mjs; edit plugins/ruflo-agentdb/hooks/options.ts)
12export const flag = (value: unknown, fallback: boolean) =>
13 value === true || value === 'true' || value === 'on' ? true : value === false || value === 'false' || value === 'off' ? false : fallback
14// END SHARED FLAG
15
16export function readOptions(options: PluginOptions | undefined): ModOptions {
17 const o = options ?? {}
18 return {
19 guard: flag(o.guard, true),
20 managedWorkflows: flag(o.managedWorkflows, false),
21 maxBudgetCents: typeof o.maxBudgetCents === 'string' && /^[1-9][0-9]{0,8}$/.test(o.maxBudgetCents) ? Number(o.maxBudgetCents) : o.maxBudgetCents === undefined ? 2500 : 0,
22 allowInlineAgents: flag(o.allowInlineAgents, false),
23 }
24}
25hooks/status.ts 12 lines1/** Counters the mod keeps for the session and writes to `.claude-flow/agent-mod/status.json` for the console. */
2export type Stats = { calls: number; blocked: number; startedMs: number; lastDenied?: string }
3
4export const newStats = (): Stats => ({ calls: 0, blocked: 0, startedMs: 0 })
5
6export const STATUS_PATH = '.claude-flow/agent-mod/status.json'
7
8/** The file's text; `version` lets the console refuse a shape it does not know. */
9export function statusText(stats: Stats, mode: { guard: boolean; managedWorkflows?: boolean; maxBudgetCents?: number; allowInlineAgents?: boolean }, nowMs: number): string {
10 return `${JSON.stringify({ version: 1, updatedMs: nowMs, mod: 'agent', modVersion: '0.4.0', guard: mode.guard, summary: `Managed workflows ${mode.managedWorkflows ? 'on' : 'off'}; budget ${mode.maxBudgetCents ?? 2500} cents; inline ${mode.allowInlineAgents ? 'on' : 'off'}; secrets ${mode.guard ? 'on' : 'off'}`, ...stats }, null, 2)}\n`
11}
12hooks/screen.ts 274 lines1/**
2 * Pure text screening for the AgentDB mod (ADR-445). Two jobs: find secrets (so none is stored) and find prompt-injection phrasing (so
3 * retrieved memory cannot instruct the model). Findings are NAMES only: the matched text is never returned, logged or counted by value.
4 */
5
6// BEGIN SHARED SCREEN (generated from plugins/ruflo-agentdb/hooks/screen.ts by scripts/sync-mod-screen.mjs; do not edit in a copy)
7export type Rules = readonly (readonly [string, RegExp])[]
8
9/** The secret shapes every mod screens for. A plugin adds its own after these, outside the markers. */
10export const COMMON_SECRETS: Rules = [
11 ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
12 ['aws access key', /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/],
13 ['github token', /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/],
14 ['slack token', /\bxox[abprs]-[A-Za-z0-9-]{10,}/],
15 ['slack webhook', /\bhooks\.slack\.com\/services\/T[A-Z0-9]{6,}\/B[A-Z0-9]{6,}\/[A-Za-z0-9]{16,}/],
16 ['google api key', /\bAIza[0-9A-Za-z_-]{35}\b/],
17 ['anthropic or openai key', /\bsk-(?:(?:ant|proj|svcacct|admin)-[A-Za-z0-9_-]{20,}|(?=[A-Za-z]{0,40}\d)[A-Za-z0-9]{32,})/],
18 ['stripe key', /\b[rs]k_live_[A-Za-z0-9]{16,}/],
19 ['npm token', /\bnpm_[A-Za-z0-9]{36}\b/],
20 ['huggingface token', /\bhf_[A-Za-z0-9]{30,}\b/],
21 ['sendgrid key', /\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/],
22 ['twilio key', /\bSK[0-9a-f]{32}\b/],
23 ['jwt', /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/],
24 ['bearer token', /\bBearer\s+([A-Za-z0-9._~+/=-]{24,})/],
25 ['database url with credentials', /\b[a-z][a-z0-9+.-]{1,20}:\/\/[^\s:@/]+:[^\s@/]{3,}@[^\s/]+/i],
26]
27
28export const INJECTION: Rules = [
29 ['override instructions', /\b(?:ignore|disregard|forget|override)\b[^.\n]{0,40}\b(?:previous|prior|above|earlier|all|any|system)\b[^.\n]{0,30}\b(?:instructions?|rules?|prompts?|guidelines?)\b/i],
30 ['role reassignment', /\byou are (?:now|no longer)\b|\bact as (?:an? )?(?:unrestricted|jailbroken)\b/i],
31 ['new instructions', /\b(?:new|updated|real) (?:system )?instructions?\s*:/i],
32 ['fake role tags', /<\/?\s*(?:system|assistant|developer|instructions?)\s*>|^\s*(?:system|assistant)\s*:/im],
33 ['concealment', /\bdo not (?:tell|inform|mention|reveal)[^.\n]{0,30}\b(?:user|human|operator)\b/i],
34 // `.env` has no word start before its dot, so it is matched on its own ("upload the .env file", "send ./config.env",
35 // ".envrc"); a dot inside a word does not end the phrase. A model's token counts are not credentials: --max-tokens,
36 // /oauth/token and "token usage/count/limit/budget/window" are left out (a file named token, /run/token, is not).
37 ['exfiltration', /\b(?:exfiltrate|send|post|upload|e-?mail)\b(?:[^.\n]|\.(?=\S)){0,50}(?:\b(?:secrets?|credentials?|api keys?)\b|(?:(?<!max[_-]?)\btokens\b|(?<!oauth\/)\btoken\b)(?![\s_-]*(?:usage|counts?|limits?|budgets?|window)\b)|\.env(?:rc)?\b)/i],
38 ['shell pipe', /\b(?:curl|wget)\b[^|\n]{0,200}\|\s*(?:sudo\s+)?(?:ba|z)?sh\b/i],
39]
40
41// C0/C1 controls (keeping tab and newline), DEL, soft hyphen, combining grapheme joiner, Arabic letter mark, Hangul and Mongolian fillers/separators,
42// zero-width, bidi (overrides and isolates) and invisible-format characters, variation selectors; built with escapes, never raw.
43const INVISIBLE = new RegExp(
44 '[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u00ad\\u034f\\u061c\\u115f\\u1160\\u17b4\\u17b5\\u180b-\\u180e\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u206f\\u3164\\ufe00-\\ufe0f\\ufeff\\uffa0\\ufff9-\\ufffb]',
45 'g',
46)
47
48/** Longest input scanned in one pass; a longer one keeps its head and tail halves. One regex pass per rule, so cost stays linear. */
49const MAX_SCAN = 200_000
50
51/** Input bounded to MAX_SCAN characters with invisible characters removed, so none can hide a secret or a phrase. */
52export const bare = (text: string) =>
53 (text.length > MAX_SCAN ? text.slice(0, MAX_SCAN / 2) + '\n' + text.slice(-MAX_SCAN / 2) : text).replace(INVISIBLE, '')
54
55// A value is a secret CANDIDATE only when it is not a reference (env var, call, identifier path, placeholder, secret-manager path) and its
56// shape is random enough: at least two character classes, one of them a digit or symbol, and Shannon entropy of at least 2.5 bits per character.
57const PLACEHOLDER = /placeholder|your[-_ ]|example|changeme|change[-_]?me|redacted|dummy|replace[-_]?me|insert[-_]|\*{3,}|x{5,}|\.{3}|^(?:none|null|undefined|true|false)$/i
58const REFERENCE =
59 /^(?:\$(?:\{[^}]*\}|\(|[A-Za-z_]\w*$)|%[^%]*%$|<[^>]*>$|\{\{|process\.env|os\.environ|env[.[]|import\.meta|System\.getenv|secrets?\.|vault:|op:\/\/|ref\+|arn:|projects\/[^/]+\/secrets\/|gcp:|kms:|aws:|file:)/i
60const CALL = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\(|^[A-Za-z_$][\w$]*\[/
61const IDENT_PATH = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/
62const UUID = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i
63const NAME_LIKE = /^[a-z][a-z0-9]*(?:[-_./][a-z0-9]+){2,}$/
64/** A ./ ../ or ~/ path to a file with an extension names where a secret lives; it is not one. */
65const RELATIVE_FILE = /^(?:\.{1,2}|~)\/[A-Za-z0-9_./-]*\.[A-Za-z0-9]{1,8}$/
66/** A secret-manager reference: NAME:latest, or name-with-separators:3, optionally as NAME=ref (--set-secrets=NAME=ref:latest). A bare literal:3 is not excused. */
67const SECRET_REF = /^(?:[A-Za-z][A-Za-z0-9_-]*=)?(?:[A-Za-z][A-Za-z0-9]*(?:[_-][A-Za-z0-9]+)*:latest|[A-Za-z][A-Za-z0-9]*(?:[_-][A-Za-z0-9]+)+:\d{1,4})$/
68
69function entropy(v: string): number {
70 const counts = new Map<string, number>()
71 for (const ch of v) counts.set(ch, (counts.get(ch) ?? 0) + 1)
72 let h = 0
73 for (const n of counts.values()) h -= (n / v.length) * Math.log2(n / v.length)
74 return h
75}
76
77/** True when `v` is a name, call, path or placeholder rather than a literal credential. */
78function isReference(v: string): boolean {
79 if (PLACEHOLDER.test(v) || REFERENCE.test(v) || CALL.test(v) || IDENT_PATH.test(v) || URL_NO_CREDS.test(v) || RELATIVE_FILE.test(v) || SECRET_REF.test(v)) return true
80 return NAME_LIKE.test(v) && v.replace(/\D/g, '').length / v.length < 0.15
81}
82
83export function plausibleSecret(v: string): boolean {
84 if (v.length < 8 || v.length > 256 || /\s/.test(v) || UUID.test(v) || isReference(v)) return false
85 const symbol = /[^A-Za-z0-9]/.test(v)
86 const digit = /\d/.test(v)
87 const classes = [/[a-z]/.test(v), /[A-Z]/.test(v), digit, symbol].filter(Boolean).length
88 return classes >= 2 && (digit || symbol) && entropy(v) >= 2.5
89}
90
91/** Under a secret-named key a literal this long is a secret even with one character class or a UUID shape, unless it is a clear reference. */
92const KEYED_MIN = 20
93const PLACEHOLDER_WORD = /(?:^|[^a-z])(?:your|placeholder|changeme|change[-_]?me|example|redacted|dummy|replace[-_]?me|insert)(?:[^a-z]|$)|\*{3,}|x{5,}|\.{3}|^(?:none|null|undefined|true|false)$/i
94const URL_NO_CREDS = /^[a-z][a-z0-9+.-]{1,20}:\/\/[^\s@]*$/i
95
96/** Three or more lowercase hyphen-separated words (no hex or digit-only run of 8+, few digits), such as my-k8s-secret-name-for-database. */
97function hyphenName(v: string): boolean {
98 const parts = v.split('-')
99 return parts.length >= 3 && parts.every(p => /^[a-z0-9]{2,}$/.test(p) && !/^[0-9a-f]{8,}$/.test(p)) && v.replace(/\D/g, '').length / v.length < 0.15
100}
101
102function keyedSecret(v: string): boolean {
103 if (v.length < KEYED_MIN || v.length > 256 || /\s/.test(v)) return false
104 return !(PLACEHOLDER_WORD.test(v) || REFERENCE.test(v) || CALL.test(v) || IDENT_PATH.test(v) || URL_NO_CREDS.test(v) || RELATIVE_FILE.test(v) || SECRET_REF.test(v) || (!UUID.test(v) && hyphenName(v)))
105}
106
107const KEY_NAME = /(?:api[_-]?key|secret|token|passw(?:or)?d|passwd|pwd|credential|private[_-]?key|auth(?!or))s?[A-Za-z0-9_-]{0,40}["']?\s*[:=]\s*/gi
108const QUOTED = /(["'\x60])((?:(?!\1)[^\n]){1,256})\1/y
109const BARE_VALUE = /[^\s"'\x60,;]{1,256}/y
110const QUERY_VALUE = /[^\s"'\x60,;&]{1,256}/y
111
112/** A secret-named key assigned a literal value: env style, JSON, YAML, code. Values that are calls, references or placeholders do not count.
113 * A key that is itself a multi-word hyphenated name is an entry's name, not a credential field (an agentdb write is `{ key: name, value: note }`),
114 * so the value is not judged by its key; the secret shapes above still screen the text as a whole (#4202). */
115function assignmentSecret(text: string): boolean {
116 let valueEnd = 0
117 for (const m of text.matchAll(KEY_NAME)) {
118 if (m.index < valueEnd) continue // a key-looking word inside the previous value, such as secretsmanager in an ARN
119 const at = m.index + m[0].length
120 let back = m.index
121 while (back > 0 && m.index - back < 64 && /[A-Za-z0-9_.-]/.test(text.charAt(back - 1))) back--
122 if (hyphenName((text.slice(back, m.index) + m[0]).replace(/["']?\s*[:=]\s*$/, ''))) {
123 valueEnd = at
124 continue
125 }
126 const re = /["'\x60]/.test(text.charAt(at)) ? QUOTED : /[?&]/.test(text.charAt(back - 1)) ? QUERY_VALUE : BARE_VALUE
127 re.lastIndex = at
128 const hit = re.exec(text)
129 const v = hit && (hit[2] ?? hit[0])
130 valueEnd = hit ? at + hit[0].length : at
131 if (v && (plausibleSecret(v) || keyedSecret(v))) return true
132 }
133 return false
134}
135
136/** A password in a URL's userinfo that is not a placeholder such as user:password or ${DB_PASSWORD}. */
137function urlCredential(url: string): boolean {
138 const pass = /^[^:]+:\/\/[^\s:@/]+:([^\s@/]+)@/.exec(url)?.[1]
139 if (!pass || /\$\{|\{\{|%\(|%s/.test(pass)) return false
140 return !/^(?:password|passwd|pass|pwd|secret|changeme|dbpassword|db_password|\$\w*|<.*>|\{.*\}|\*+|x+)$/i.test(pass) && !PLACEHOLDER.test(pass)
141}
142
143const CHECKS: Readonly<Record<string, (m: RegExpMatchArray) => boolean>> = {
144 'bearer token': m => !isReference(m[1] ?? ''),
145 'database url with credentials': m => urlCredential(m[0]),
146 'database url with password': m => urlCredential(m[0]),
147}
148const globals = new WeakMap<RegExp, RegExp>()
149
150function matches(name: string, re: RegExp, text: string): boolean {
151 if (name === 'key assignment') return assignmentSecret(text)
152 const check = CHECKS[name]
153 if (!check) return re.test(text)
154 let g = globals.get(re)
155 if (!g) globals.set(re, (g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g')))
156 for (const m of text.matchAll(g)) if (check(m)) return true
157 return false
158}
159
160/**
161 * The text textsOf appends when it had to drop input (a node, character or per-string budget ran out). It is never matched against a rule:
162 * `names` reports it as a finding of its own, so every guard that asks "is there a secret in these texts" refuses what it could not read in full.
163 */
164export const TRUNCATED = 'ruflo-screen: input exceeded the screening budget'
165export const TRUNCATED_NAME = 'input too large to screen'
166
167/** Names of the rules that match `text` (already bare'd). A rule named 'key assignment' is judged by assignmentSecret, whatever its regex. */
168export const names = (rules: Rules, text: string) => text === TRUNCATED ? [TRUNCATED_NAME] : rules.filter(([name, re]) => matches(name, re, text)).map(([name]) => name)
169
170export type Findings = { readonly secrets: readonly string[]; readonly injection: readonly string[] }
171
172/** Names of every secret shape in `secrets` and every injection phrase found in `text`. Cost is linear in the capped input. */
173export function screenWith(secrets: Rules, text: string): Findings {
174 const bounded = bare(text)
175 return { secrets: names(secrets, bounded), injection: names(INJECTION, bounded) }
176}
177
178export const hasSecretIn = (secrets: Rules, text: string) => names(secrets, bare(text)).length > 0
179
180/** Makes stored text safe to show: no control or bidi characters, whitespace collapsed, at most `max` characters. */
181export function tidy(text: string, max: number): string {
182 const flat = text.replace(INVISIBLE, '').replace(/\s+/g, ' ').trim()
183 return flat.length > max ? `${flat.slice(0, Math.max(0, max - 1))}…` : flat
184}
185/** Bounds for textsOf: nodes visited, characters returned, the longest string read in full, the size of one returned chunk, chunk overlap. */
186export type TextLimits = { readonly nodes?: number; readonly chars?: number; readonly perString?: number }
187const NODES = 20_000
188const CHARS = 2_000_000
189const PER_STRING = 1_500_000
190const OVERLAP = 2_048
191const BARE_KEY_MIN = 8
192
193/** A string as texts the screen can read whole: one text up to MAX_SCAN, else overlapping MAX_SCAN windows so a secret anywhere is inside one. */
194function windows(text: string, out: string[]): void {
195 if (text.length <= MAX_SCAN) {
196 out.push(text)
197 return
198 }
199 for (let at = 0; ; at += MAX_SCAN - OVERLAP) {
200 out.push(text.slice(at, at + MAX_SCAN))
201 if (at + MAX_SCAN >= text.length) return
202 }
203}
204
205/**
206 * Every string in a tool input, for the screen to read: iterative (no recursion, so nesting 5000 deep cannot overflow the stack) and
207 * breadth-first (siblings before depth, so a long list cannot hide a nested value). A string under an object key comes back as `key=value`,
208 * so a secret-named key is judged with its value; a key whose value is not a string is returned bare. Strings longer than the screen window
209 * come back as overlapping windows; one over `perString` keeps its head and tail. Work is bounded by `nodes` slots and `chars` characters.
210 * Anything dropped (slots or characters ran out, or a string lost its middle) is reported by a final TRUNCATED text, which `names` and
211 * `hasSecretIn` count as a finding, so the screen fails closed instead of passing what it did not read.
212 */
213export function textsOf(input: unknown, limits: TextLimits = {}): string[] {
214 const out: string[] = []
215 let slots = limits.nodes ?? NODES
216 let chars = limits.chars ?? CHARS
217 const perString = limits.perString ?? PER_STRING
218 let truncated = false
219 const take = (text: string): void => {
220 if (chars <= 0) {
221 truncated = true
222 return
223 }
224 if (text.length <= Math.min(perString, chars)) {
225 chars -= text.length
226 windows(text, out)
227 return
228 }
229 truncated = true
230 const half = Math.floor(Math.min(perString, chars) / 2)
231 chars -= 2 * half
232 windows(text.slice(0, half), out)
233 windows(text.slice(-half), out)
234 }
235 const queue: unknown[] = [input]
236 let head = 0
237 for (; head < queue.length && chars > 0; head++) {
238 const node = queue[head]
239 if (typeof node === 'string') take(node)
240 else if (Array.isArray(node)) {
241 let i = 0
242 for (; i < node.length && slots > 0; i++, slots--) if (i in node) queue.push(node[i])
243 if (i < node.length) truncated = true
244 } else if (typeof node === 'object' && node !== null) {
245 for (const k in node) {
246 if (slots-- <= 0) {
247 truncated = true
248 break
249 }
250 if (!Object.prototype.hasOwnProperty.call(node, k)) continue
251 const v = (node as Record<string, unknown>)[k]
252 if (typeof v === 'string') queue.push(k + '=' + v)
253 else {
254 if (k.length >= BARE_KEY_MIN) take(k)
255 queue.push(v)
256 }
257 }
258 }
259 }
260 if (queue.length > head) truncated = true
261 if (truncated) out.push(TRUNCATED)
262 return out
263}
264// END SHARED SCREEN
265
266const SECRETS: Rules = [
267 ...COMMON_SECRETS,
268 ['key assignment', /\b(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i],
269]
270
271export const scan = (text: string): Findings => screenWith(SECRETS, text)
272
273export const hasSecret = (text: string) => hasSecretIn(SECRETS, text)
274