jianmu.guard¶
适用对象:安全策略作者 / 应用集成者 / 核心维护者
是否必读:按需
相关模块:jianmu.execution, jianmu.tool, jianmu.skill
1. 模块职责¶
jianmu.guard 负责把预算、速率、确认、工具策略等约束整合成统一守卫层。
它的定位不是替代执行层,而是在执行前后提供可组合的策略判定与审批机制。
2. 适合查什么¶
- 统一约束类型:
GuardConstraints、BudgetConstraints - 守卫入口:
GuardEnforcer - 审批相关对象:
ApprovalManager、ApprovalRequest - 内置 checker:预算、确认、速率、工具策略
3. 使用建议¶
- 应用侧通常组合
Constraints + GuardEnforcer - 需要人工审批流时,再引入
ApprovalManager - 新策略优先通过 checker 协议扩展,而不是在节点内部散落校验逻辑
4. 最小示例¶
from jianmu.config.constraints import Constraints
from jianmu.guard.types import GuardConstraints, BudgetConstraints
constraints = Constraints(
guard=GuardConstraints(
max_tool_calls=5,
tool_policy={"bash": "confirm"},
budget=BudgetConstraints(total_tokens=20000),
),
)
5. 常见入口¶
- 想快速给 agent 加限制:看
GuardConstraints - 想接人工审批:看
ApprovalManager - 想自己拼 checker:看
GuardEnforcer
6. API 参考¶
决策与约束¶
Decision
¶
Bases: Enum
Possible outcomes of a policy check.
BudgetConstraints
dataclass
¶
BudgetConstraints(
total_tokens: Optional[int] = None,
prompt_tokens: Optional[int] = None,
completion_tokens: Optional[int] = None,
)
Token budget limits shared across one agent run or loop.
Any field left as None is treated as unlimited. Most applications only
set total_tokens; the prompt/completion split is useful when a provider
reports the components separately and you want finer control.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
total_tokens |
Optional[int]
|
Overall token ceiling across the whole run. |
prompt_tokens |
Optional[int]
|
Optional prompt-token ceiling across all model calls. |
completion_tokens |
Optional[int]
|
Optional completion-token ceiling across all model calls. |
GuardConstraints
dataclass
¶
GuardConstraints(
tool_policy: dict[str, str] = None,
tool_rules: list[ToolRule] = None,
default_policy: str = "allow",
max_tool_calls: Optional[int] = None,
budget: BudgetConstraints = None,
permission: PermissionConstraints | None = None,
)
Guard-domain constraints for policy, budget, and approval decisions.
from_dict
classmethod
¶
Build guard constraints from a plain mapping.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
dict | None
|
The |
必需 |
返回:
| 类型 | 描述 |
|---|---|
'GuardConstraints'
|
The resulting |
源代码位于: jianmu/guard/types.py
守卫入口¶
GuardEnforcer
¶
Bases: GuardProtocol
Compose multiple guard checkers into one decision point.
Most users should configure Constraints and let Jianmu build an
enforcer automatically. This class is mainly useful when you need explicit
checker composition or a custom enforcement pipeline.
Compose a list of guard checkers into one enforcer.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
checkers
|
List[CheckerProtocol]
|
Ordered guard checkers evaluated for each action. |
必需 |
源代码位于: jianmu/guard/enforcer.py
check
async
¶
Run all registered checkers and stop at the first hard deny.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
action
|
str
|
Action string to check. |
必需 |
context
|
CheckContextLike
|
Typed or legacy context environment. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tuple[Decision, str]
|
Tuple containing the final Decision and reason. |
源代码位于: jianmu/guard/enforcer.py
reset
¶
dump_resume_state
¶
Return checker-local state for checkpoint resume.
源代码位于: jianmu/guard/enforcer.py
restore_resume_state
¶
Restore checker-local state from checkpoint metadata.
源代码位于: jianmu/guard/enforcer.py
from_guard_constraints
classmethod
¶
from_guard_constraints(
constraints: GuardConstraints | None,
tool_aliases: dict[str, str] | None = None,
approval_manager: ApprovalManager | None = None,
permission_grant_store: PermissionGrantStoreProtocol
| None = None,
permission_scope_key: str = "",
) -> "GuardEnforcer"
Build a guard enforcer from guard-domain constraint settings.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
constraints
|
GuardConstraints | None
|
Guard-domain constraints specifying policies/limits. |
必需 |
tool_aliases
|
dict[str, str] | None
|
Optional dictionary of tool name aliases. |
None
|
approval_manager
|
ApprovalManager | None
|
Optional ApprovalManager instance. |
None
|
permission_grant_store
|
PermissionGrantStoreProtocol | None
|
Optional saved Permission V2 allow store. |
None
|
permission_scope_key
|
str
|
Opaque host scope used to load saved rules. |
''
|
返回:
| 类型 | 描述 |
|---|---|
'GuardEnforcer'
|
An instance of GuardEnforcer. |
The resulting checker chain typically includes tool policy, call-rate limits, budget checks, and approval confirmation.
源代码位于: jianmu/guard/enforcer.py
CheckerProtocol
¶
Bases: Protocol
Single checker that decides allow/deny/confirm for an action.
check
async
¶
Validate one constraint and return (decision, reason).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
action
|
str
|
Action string to check. |
必需 |
context
|
CheckContextLike
|
Typed or legacy dictionary context parameters. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tuple[Decision, str]
|
Tuple containing the Decision and a reason string. |
源代码位于: jianmu/guard/base.py
GuardProtocol
¶
Bases: Protocol
Composed guard made of multiple checkers.
check
async
¶
Validate the composed guard and return (decision, reason).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
action
|
str
|
Action string to check. |
必需 |
context
|
CheckContextLike
|
Typed or legacy dictionary context parameters. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tuple[Decision, str]
|
Tuple containing the Decision and a reason string. |
源代码位于: jianmu/guard/base.py
检查上下文¶
ToolCheckContext
dataclass
¶
ToolCheckContext(
tool_name: str,
args: dict[str, Any],
thread_id: str = "",
node_locator: str = "",
tool_call_id: str = "",
command_text: str = "",
command_prefix: str = "",
target_path: str = "",
resource_kind: str = "",
risk_tags: list[str] = list(),
matched_rule: dict[str, Any] | None = None,
permission: PermissionCheck | None = None,
)
Typed tool-call context consumed by guard checkers.
ApprovalCheckEffect
dataclass
¶
ApprovalCheckEffect(
progress_state: str = "",
request_id: str = "",
approval_result: Any | None = None,
clear_progress: bool = False,
pending: bool = False,
)
Mutable approval-check side effects produced by a checker.
ApprovalCheckContext
dataclass
¶
ApprovalCheckContext(
request_id: str,
reason: str = "",
progress_state: str = "",
pop_resolved: Callable[[str], dict[str, Any] | None]
| None = None,
needs_confirm: bool = False,
effect: ApprovalCheckEffect = ApprovalCheckEffect(),
)
Typed approval state consumed and mutated during one guard check.
GuardCheckContext
dataclass
¶
GuardCheckContext(
action: str,
usage: dict[str, Any] = dict(),
metadata: dict[str, Any] = dict(),
tool: ToolCheckContext | None = None,
approval: ApprovalCheckContext | None = None,
)
Typed guard context that still behaves like a legacy mapping.
get
¶
Return one legacy-style value from the typed context.
to_legacy_context
¶
Materialize the typed context into one legacy mutable mapping.
源代码位于: jianmu/guard/context.py
审批流¶
ApprovalManager
¶
ApprovalManager(
callback: Optional[
Callable[
[ApprovalRequest],
Awaitable[ApprovalResult | bool | str]
| ApprovalResult
| bool
| str,
]
] = None,
*,
tool_callback: Optional[
Callable[
[str, dict | None],
Awaitable[ApprovalResult | bool | str]
| ApprovalResult
| bool
| str,
]
] = None,
node_callback: Optional[
Callable[
[str, str, dict | None],
Awaitable[ApprovalResult | bool | str]
| ApprovalResult
| bool
| str,
]
] = None,
audit_hook: Optional[
Callable[[ApprovalRequest, bool], None]
] = None,
runtime_event_bus: RuntimeEventBus | None = None,
pending_store: ApprovalStoreProtocol | None = None,
non_tty_pending_enabled: bool = False,
permission_grant_store: PermissionGrantStoreProtocol
| None = None,
permission_scope_key: str = "",
)
Unified approval entry point.
Resolution order: 1) explicit callback passed to manager 2) tool/node specific fallback callback 3) built-in defaults from guard.approval.defaults
Configure generic, tool, and node-level approval callbacks.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
callback
|
Optional[Callable[[ApprovalRequest], Awaitable[ApprovalResult | bool | str] | ApprovalResult | bool | str]]
|
Primary callback for normalized approval requests. |
None
|
tool_callback
|
Optional[Callable[[str, dict | None], Awaitable[ApprovalResult | bool | str] | ApprovalResult | bool | str]]
|
Tool-specific fallback callback. |
None
|
node_callback
|
Optional[Callable[[str, str, dict | None], Awaitable[ApprovalResult | bool | str] | ApprovalResult | bool | str]]
|
Node-specific fallback callback. |
None
|
audit_hook
|
Optional[Callable[[ApprovalRequest, bool], None]]
|
Optional observer invoked after final resolution. |
None
|
runtime_event_bus
|
RuntimeEventBus | None
|
Optional bus for approval lifecycle events. |
None
|
pending_store
|
ApprovalStoreProtocol | None
|
Durable store for request and result records. |
None
|
non_tty_pending_enabled
|
bool
|
Whether non-interactive defaults may
return |
False
|
源代码位于: jianmu/guard/approval/manager.py
request
async
¶
Run the configured approval callback for a generic request.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
req
|
ApprovalRequest
|
The ApprovalRequest instance to process. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ApprovalRecord
|
Durable approval record reflecting the current lifecycle state. |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
If |
源代码位于: jianmu/guard/approval/manager.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
confirm_tool
async
¶
confirm_tool(
tool_name: str,
params: dict | None = None,
*,
reason: str = "",
context: dict[str, Any] | None = None,
request_id: str = "",
) -> ApprovalRecord
Request approval for a tool invocation.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
tool_name
|
str
|
Name of the tool. |
必需 |
params
|
dict | None
|
Optional dictionary of arguments passed to the tool. |
None
|
reason
|
str
|
Explanation for the approval request. |
''
|
context
|
dict[str, Any] | None
|
Context dictionary. |
None
|
返回:
| 类型 | 描述 |
|---|---|
ApprovalRecord
|
Durable approval record for the tool request. |
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
If durable tool approval is requested without a
precomputed |
源代码位于: jianmu/guard/approval/manager.py
approve_node
async
¶
approve_node(
node_name: str,
description: str = "",
context: dict[str, Any] | None = None,
request_id: str = "",
) -> ApprovalRecord
Request approval for a node-level action.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
node_name
|
str
|
Name of the node. |
必需 |
description
|
str
|
Description of the node action. |
''
|
context
|
dict[str, Any] | None
|
Context dictionary. |
None
|
返回:
| 类型 | 描述 |
|---|---|
ApprovalRecord
|
Durable approval record for the node request. |
源代码位于: jianmu/guard/approval/manager.py
resolve_request
¶
resolve_request(
request_id: str,
approved: bool,
*,
reason: str = "",
payload: dict[str, Any] | None = None,
) -> ApprovalResult | None
Resolve one pending request stored by the manager.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
request_id
|
str
|
Identifier for request. |
必需 |
approved
|
bool
|
The |
必需 |
reason
|
str
|
The |
''
|
payload
|
dict[str, Any] | None
|
Payload data for the operation. |
None
|
返回:
| 类型 | 描述 |
|---|---|
ApprovalResult | None
|
The resolved value, or |
源代码位于: jianmu/guard/approval/manager.py
reply_request
¶
reply_request(
request_id: str,
reply: PermissionReply | str,
*,
reason: str = "",
feedback: str = "",
scope_key: str = "",
) -> ApprovalResult | None
Resolve a pending permission request as once, always, or reject.
源代码位于: jianmu/guard/approval/manager.py
get_pending_request
¶
Return one pending request stored by the manager.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
request_id
|
str
|
Identifier for the approval request. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ApprovalRequest | None
|
The pending approval request, or |
源代码位于: jianmu/guard/approval/manager.py
get_result
¶
Return one resolved result stored by the manager without consuming it.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
request_id
|
str
|
Identifier for the approval request. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ApprovalResult | None
|
The resolved approval result, or |
源代码位于: jianmu/guard/approval/manager.py
get_record
¶
Return one durable approval record by request id.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
request_id
|
str
|
Identifier for the approval request. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ApprovalRecord | None
|
The durable approval record, or |
源代码位于: jianmu/guard/approval/manager.py
ack_result
¶
Mark one resolved result as consumed but not yet pruned.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
request_id
|
str
|
Identifier for the approval request. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ApprovalResult | None
|
The acknowledged result, or |
源代码位于: jianmu/guard/approval/manager.py
prune_result
¶
Delete one resolved result after checkpoint durability is established.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
request_id
|
str
|
Identifier for the approval request. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ApprovalResult | None
|
The pruned result, or |
源代码位于: jianmu/guard/approval/manager.py
drain_result
¶
Backward-compatible alias that ack/prunes one resolved result.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
request_id
|
str
|
Identifier for the approval request. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ApprovalResult | None
|
The drained result, or |
源代码位于: jianmu/guard/approval/manager.py
subscribe_resolution
¶
subscribe_resolution(
request_id: str,
callback: Callable[[ApprovalResult], None],
) -> Callable[[], None]
Subscribe one callback to one internal approval request id.
The subscription is race-safe for resolve-before-subscribe: if the result already exists, the callback is delivered immediately and the returned unsubscribe is a no-op.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
request_id
|
str
|
Identifier for the approval request. |
必需 |
callback
|
Callable[[ApprovalResult], None]
|
Listener invoked with the final approval result. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Callable[[], None]
|
A callable that removes the subscription when invoked. |
源代码位于: jianmu/guard/approval/manager.py
ApprovalRequest
dataclass
¶
ApprovalRequest(
kind: str,
target: str,
request_id: str = "",
description: str = "",
context: dict[str, Any] = dict(),
permission: PermissionCheck | None = None,
)
Normalized approval request shared by node/tool HITL flows.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
kind |
str
|
Approval category such as |
target |
str
|
Unique target identifier, usually a tool or node name. |
request_id |
str
|
Framework-generated internal request id used for suspend, store, resume, and listener correlation. |
description |
str
|
Human-readable summary shown to approvers. |
context |
dict[str, Any]
|
Extra structured payload needed by the approval UI or policy. |
ApprovalResult
dataclass
¶
ApprovalResult(
approved: bool,
request_id: str = "",
reason: str = "",
payload: dict[str, Any] = dict(),
)
Normalized final approval resolution.
Approval
¶
Approval(
*,
child: Behaviour,
description: str = "",
phase: str = "before",
callback: Optional[
Callable[[ApprovalRequest], Awaitable[bool] | bool]
] = None,
context_fn: Optional[Callable[[], dict | None]] = None,
on_reject: str = "failure",
name: Optional[str] = None,
)
Bases: Decorator
Node-level human approval gate.
phase
- "before": approve before child executes
- "after": approve after child finishes
- "both": approve before and after
Configure a human-approval gate around a child behaviour.
源代码位于: jianmu/guard/approval/decorator.py
initialise
¶
Reset decorator-local approval state before a fresh tick cycle.
源代码位于: jianmu/guard/approval/decorator.py
terminate
¶
Cancel any pending approval task when the decorator stops.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
new_status
|
Status
|
The execution status the node is transitioning to. |
必需 |
源代码位于: jianmu/guard/approval/decorator.py
update
¶
Return the decorated child status for py_trees compatibility.
返回:
| 类型 | 描述 |
|---|---|
Status
|
The execution Status of the decorated child node. |
源代码位于: jianmu/guard/approval/decorator.py
tick
¶
Drive pre/post approval phases around the decorated child tick.
源代码位于: jianmu/guard/approval/decorator.py
内置 Checker¶
ToolPolicyChecker
¶
ToolPolicyChecker(
policy: dict[str, str],
default: str = "allow",
aliases: dict[str, str] | None = None,
tool_rules: list[ToolRule] | None = None,
)
Bases: CheckerProtocol
Policy-based tool checker.
policy: mapping tool_name -> "allow" | "deny" | "confirm" default: fallback policy aliases: optional mapping input_name -> canonical name
Normalize tool policy rules and alias mappings.
源代码位于: jianmu/guard/checkers/tool_policy.py
check
async
¶
Apply allow/deny/confirm policy rules to a tool action.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
action
|
str
|
The action string to check. |
必需 |
context
|
CheckContextLike
|
Context dictionary representing the execution environment. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tuple[Decision, str]
|
Tuple of Decision and reason string. |
源代码位于: jianmu/guard/checkers/tool_policy.py
RateLimitChecker
¶
Bases: CheckerProtocol
Limit tool_call action count.
Configure the maximum number of permitted tool calls.
源代码位于: jianmu/guard/checkers/rate_limit.py
check
async
¶
Enforce a simple per-run tool call count limit.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
action
|
str
|
The action string to check. |
必需 |
context
|
dict[str, Any]
|
Context dictionary. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tuple[Decision, str]
|
Tuple of Decision and reason string. |
源代码位于: jianmu/guard/checkers/rate_limit.py
reset
¶
dump_resume_state
¶
restore_resume_state
¶
Restore checker-local state from checkpoint metadata.
BudgetChecker
¶
Bases: CheckerProtocol
Placeholder budget checker.
Expects context to carry usage dict
{'prompt_tokens': int, 'completion_tokens': int, 'total_tokens': int}.
Bind the checker to a fixed token budget specification.
源代码位于: jianmu/guard/checkers/budget.py
check
async
¶
Reject requests that would exceed the configured token budget.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
action
|
str
|
The action string to check. |
必需 |
context
|
CheckContextLike
|
Context dictionary containing usage details. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tuple[Decision, str]
|
Tuple of Decision and reason string. |
源代码位于: jianmu/guard/checkers/budget.py
ConfirmChecker
¶
Bases: CheckerProtocol
Perform user confirmation when context marks _needs_confirm.
Bind the checker to an approval manager.
源代码位于: jianmu/guard/checkers/confirm.py
check
async
¶
Reject risky actions until explicit confirmation is provided.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
action
|
str
|
The action string to check. |
必需 |
context
|
CheckContextLike
|
Context dictionary representing the execution environment. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tuple[Decision, str]
|
Tuple of Decision and reason string. |