[Bug]:ASKING 状态会被持久化到状态存储中
[Bug]: plan_exit ASKING state persists across runs when enablePendingToolRecovery + enablePlanMode + PermissionMode.BYPASS are combined
AgentScope-Java Version: 2.0.1
Describe the bug
When HarnessAgent is configured with enablePlanMode(true) + enablePendingToolRecovery(true) + PermissionMode.BYPASS + a persistent AgentStateStore (MySQL), a plan_exit tool call can remain in ASKING state after a run is interrupted (timeout / cancellation / exception). The ASKING state is persisted to the state store. When a new request reuses the same sessionId without carrying ConfirmResult metadata, the framework throws a hard error and the new run fails immediately.
This is a follow-up edge case to #2534 / PR #2109. The 2.0.1 fix correctly prevents pending recovery from consuming HITL approvals when the new input carries ConfirmResult. However, when the new request is a normal user message (no ConfirmResult), the leftover ASKING state from a previous run is neither auto-cleared nor gracefully handled — it blocks the new run entirely.
Agent configuration:
HarnessAgent.builder()
.name("testx-" + threadId)
.enablePendingToolRecovery(true)
.permissionContext(PermissionContextState.builder().mode(PermissionMode.BYPASS).build())
.enablePlanMode(true)
.stateStore(mysqlAgentStateStore) // custom AgentStateStore backed by MySQL
.defaultSessionId(threadId)
// ... other settings
.build();
Reproduction flow:
Run A (sessionId = T1):
1. Agent starts → enters Plan Mode
2. LLM generates plan → calls plan_exit to start execution
3. plan_exit enters ASKING state (awaiting HITL confirmation)
4. Request is interrupted (timeout / user cancel / exception)
5. AgentState (including ASKING plan_exit) persisted to MySQL
↓
Run B (sessionId = T1, NEW request, normal user message, no ConfirmResult):
1. Agent restores state from MySQL
2. Detects plan_exit in ASKING state
3. New request has NO ConfirmResult in metadata
4. Framework throws hard error — new request FAILS immediately
To Reproduce
Steps to reproduce the behavior:
- Configure a
HarnessAgentwithenablePlanMode(true)+enablePendingToolRecovery(true)+PermissionMode.BYPASS+ a persistentAgentStateStore - Send a request that triggers the agent to enter Plan Mode and call
plan_exit - Interrupt the run (cancel / timeout) while
plan_exitis in ASKING state - Send a new request with the same
sessionId(normal user message, noConfirmResult) - See error
Expected behavior
Two possible fixes:
-
plan_exitshould not enter ASKING state underPermissionMode.BYPASS. Since BYPASS means "skip all permission checks", framework-internal plan tools (plan_enter/plan_write/plan_exit) should never require HITL confirmation. -
When a new request arrives without
ConfirmResultand the restored state contains ASKING tool calls from a previous run, the framework should auto-clear the orphaned ASKING state (or emit a warning event and skip it) instead of throwing a hard error.
Error messages
Agent is paused for human-in-the-loop confirmation: the following tool call(s) are in ASKING state and need your approval before the agent can continue: [plan_exit (id=call_f178664a2cf04251ae4afd19)]. This call supplied no confirmation, so it cannot proceed. To resume, send a follow-up message that carries a List under the metadata key "agentscope_confirm_results", e.g.: UserMessage.builder() .metadata(Map.of(Msg.METADATA_CONFIRM_RESULTS, List.of(new ConfirmResult(true, toolCall)))) .build(); Tip: capture the ToolUseBlocks from the RequireUserConfirmEvent emitted when the agent paused. If you did NOT expect a pending confirmation here, a previous run most likely paused on one of these tool calls and persisted that state under the same (agentId, sessionId); start a fresh session, clear the persisted state, or use an in-memory state store to begin clean.
Environment
- AgentScope-Java Version: 2.0.1
- Java Version: 17
- OS: Linux (production) / Windows (development)
Additional context
- Related: #2534 (人工介入与PendingToolRecovery不兼容), fixed by PR #2109 in 2.0.1. The 2.0.1 fix handles the case where the new input carries
ConfirmResult. This issue covers the different scenario where a normal new request encounters leftover ASKING state with noConfirmResultto provide. - RC2 release notes mention "Plan Mode 优化 — 改进计划文件持久化与恢复机制,优化 plan_enter / plan_write / plan_exit 工具链的交互体验,增强 HITL 审批流程的稳定性" — this issue suggests there are still edge cases in that interaction.
- All our HarnessAgent-based agents are affected because they all use the same combination of
enablePlanMode(true)+enablePendingToolRecovery(true)+PermissionMode.BYPASS. - Current workaround: manually delete the persisted AgentScope state for the affected sessionId before each new run, or switch to
InMemoryAgentStateStore(sacrificing session recovery).
Issue Evaluation
Category: bug | Status: Partially confirmed — real defect, but not via the reported trigger
Verified against main @ 846d3c3 (same PermissionEngine logic as 2.0.1).
Confirmed
- Orphaned
ASKINGstate is persisted and re-applied on restore, and a plain follow-up message hard-fails:ReActAgent.java:1879(validateAndAcceptConfirmResults) throwsIllegalStateExceptionwhenaskingToolCalls()is non-empty and the incoming msgs carry noMsg.METADATA_CONFIRM_RESULTS. enablePendingToolRecovery(true)does not rescue this case. The ASKING check runs before recovery (ReActAgent.java:1794vs:1803, ordering is intentional per the comment at:1800-1802), andmaybePatchPendingToolCallsexplicitly excludesstate == ASKING(ReActAgent.java:2098). So there is no auto-clear / degradation path at all.ASKINGsurvives persistence: written viaupdateToolCallStates(ReActAgent.java:2906-2925), serialized asToolUseBlock.state(ToolUseBlock.java:100-105), and saved on both normal pause (ReActAgent.java:475-497) and failure (:511-528).
Not as reported
plan_exit does not enter ASKING under a fresh PermissionMode.BYPASS session. PlanModeTools.PlanExitTool#checkPermissions returns an unconditional ASK (PlanModeTools.java:186-192), but PermissionDecision.ask(...) leaves decisionReason unset (PermissionDecision.java:105-107), so it is not "safety"-bypass-immune and falls through to the BYPASS ALLOW fallback (PermissionEngine.java:156-177, :188-196). Proposed fix #1 in the issue is therefore already the current behaviour.
Likely actual root cause
AgentState serializes permission_context (AgentState.java:54, :114), and loadOrCreateAgentStateForSlot returns the persisted state as-is whenever it exists (ReActAgent.java:432-436) — the builder's permissionContext(...) is only used to seed a fresh state (:459-461). The engine is then rebuilt from the restored context (ReActAgent.java:685). If that persisted context is the trivial default, evaluatePermissions takes the lightweight pre-2.0 path (ReActAgent.java:3222, :3264-3279), where the tool's own ASK does gate execution — which produces exactly the reported ASKING → persisted → next-run-fails loop despite BYPASS being configured on the builder.
Suggested direction
- Reconcile the restored
permission_contextwith the builder-configuredpermissionContext(...)(or document that the state store wins and make the precedence explicit), so a BYPASS-configured agent does not silently revert to the lightweight path after a restore. - Give orphaned
ASKINGtool calls a graceful path when the incoming message is a normal message: auto-expire / cancel-with-warning (emit an event, synthesize a cancelled tool result) instead ofIllegalStateException, consistent with whatenablePendingToolRecoveryalready does for other orphaned pending calls.
Question for the reporter
- Was the affected
sessionIdcreated beforePermissionMode.BYPASSwas configured on this agent? Dumping the persistedagent_staterow'spermission_contextfor that session would confirm the root cause above. - Which
AgentStateStorebuild is the custom MySQL store derived from — does it round-trippermission_contextunchanged?
Automated evaluation by github-manager-bot
@oss-maintainer Thank you for the thorough evaluation. Here are the answers to your questions:
Q1: Was the affected sessionId created before PermissionMode.BYPASS was configured?
No. BYPASS has always been configured from day one. Every HarnessAgent builder in our project hardcodes PermissionMode.BYPASS — there is no dynamic configuration or conditional logic around it:
All use the identical pattern:
.permissionContext(PermissionContextState.builder().mode(PermissionMode.BYPASS).build())
So the persisted permission_context should always contain BYPASS. This makes the "lightweight pre-2.0 path" hypothesis less likely — unless the serialized BYPASS context, after a JSON round-trip, somehow loses fidelity (see Q2).
Q2: Which AgentStateStore build is the custom MySQL store derived from?
Our AgentScopeMysqlSession implements AgentStateStore directly (not derived from any built-in implementation). It does a transparent JSON round-trip with no special handling for permission_context:
// Save: full State object → JSON string → DB content column
private final JsonCodec jsonCodec = JsonUtils.getJsonCodec();
@Override
public void save(String userId, String sessionId, String key, State value) {
// delete old + insert new in same transaction
chatMemoryMessageMapper.deleteBySessionIdAndMessageType(sessionId, messageType(key));
chatMemoryMessageMapper.insert(buildStateMessage(sessionId, messageType(key),
value.getClass().getName(), 0, jsonCodec.toPrettyJson(value)));
}
// Load: DB content column → JSON string → typed State object
@Override
public <T extends State> Optional<T> get(String userId, String sessionId, String key, Class<T> type) {
List<ChatMemoryMessage> rows = chatMemoryMessageMapper.selectStateBySessionIdAndMessageType(sessionId, messageType(key));
if (rows.isEmpty()) return Optional.empty();
return Optional.ofNullable(jsonCodec.fromJson(rows.get(rows.size() - 1).getContent(), type));
}
Key observations:
- No field filtering or transformation — the entire
Stateobject (includingpermission_contextwhen part ofAgentState) is serialized as-is by Jackson viaJsonCodec. stateClassis stored in themetadatacolumn (value.getClass().getName()), but it is only used for informational purposes — the actual deserialization target type is theClass<T> typeparameter passed by the framework.- The round-trip is lossy if
PermissionContextStatehas fields that Jackson cannot deserialize correctly (e.g., missing no-arg constructor,@JsonIgnoreon critical fields, or polymorphic types without type info).
So to directly answer your question: yes, the store round-trips permission_context unchanged at the JSON text level, but whether the deserialized PermissionContextState object is semantically identical to the original depends entirely on the framework's Jackson codec behavior. We have no visibility into that from the application side.
Additional observation that may help
Since BYPASS was always configured, and the store does a transparent round-trip, there are two possible explanations for the ASKING state appearing despite BYPASS:
Hypothesis A: The plan_exit tool's checkPermissions() returns an unconditional ASK (as you confirmed at PlanModeTools.java:186-192), and under certain conditions the BYPASS fallback in PermissionEngine does not override it. For example, if the PermissionContextState restored from JSON has a different internal structure than a freshly-built one (e.g., mode field deserializes correctly but some derived/cached field does not), the engine might take the lightweight path you described at ReActAgent.java:3222, :3264-3279.
Hypothesis B: The ASKING state was produced not by the permission engine but by a different code path — e.g., the plan_exit tool itself has an internal HITL gate that is independent of PermissionEngine. If PlanExitTool.checkPermissions() always returns ASK regardless of the engine's decision, then BYPASS would be irrelevant for this specific tool.
If you could share the relevant code paths (PlanModeTools.PlanExitTool#checkPermissions and the PermissionEngine BYPASS fallback logic), I can cross-check against our runtime logs to determine which hypothesis matches.
Issue Evaluation — follow-up (answers received)
Category: bug | Status: Confirmed defect — root cause narrowed; framework round-trip cleared
Thanks for the detailed answers, @huang4953 — they rule out the timeline hypothesis. Re-verified against main @ e15d8e251.
Answers to your questions (the code paths you asked for)
PlanModeTools.PlanExitTool#checkPermissions(PlanModeTools.java:186-192) → unconditionalPermissionDecision.ask(...).PermissionEngineBYPASS fallback (PermissionEngine.java:156-177,:188-196) → returns ALLOW whencontext.getMode() == BYPASS;PermissionDecision.ask()leavesdecisionReasonunset (PermissionDecision.java:105-107), so it is not safety-bypass-immune and is overridden.PlanModeMiddlewareputsplan_exitinALWAYS_ALLOWED(PlanModeMiddleware.java:60-65,:239-242), so there is no second HITL gate independent of the permission engine — your Hypothesis B is ruled out.
Hypothesis A — narrowed, but not inside the framework's own codec
PermissionContextState round-trips losslessly through the stock Jackson codec:
@JsonCreatorfactory carriesmode/working_directories/allow_rules/deny_rules/ask_rules(PermissionContextState.java:54-73);PermissionModehas@JsonValue+@JsonCreator(PermissionMode.java:46-49,:58-70);isTrivial()is a@JsonIgnorederived getter (PermissionContextState.java:106-113), andJacksonJsonCodeconly relaxesFAIL_ON_UNKNOWN_PROPERTIES(JacksonJsonCodec.java:74) — no silent field loss.
The branch selector is !state.getPermissionContext().isTrivial() (ReActAgent.java:3222), and isTrivial() is true only when mode == DEFAULT and rules/dirs are empty. The restored (persisted) context — not the builder's — is what the rebuilt engine uses (ReActAgent.java:432-436, :459-461, :687). So the failure still requires mode to reach the framework as DEFAULT; since the framework codec preserves it, the discriminator sits in the concrete persisted payload.
One concrete check that settles it
Dump the raw permission_context JSON from the affected agent_state row and look at mode:
"mode": "bypass"(orBYPASS) → state fidelity is fine, and this becomes a genuine framework bug worth fixing here — we would want a repro on a stock store;"mode": "default"/ key absent / context{}→ the round-trip through the custom store's codec is dropping the mode, and that also explains why the engine silently falls back to the lightweight path.
Two independent defects remain, regardless of the answer above
- Orphaned
ASKINGstate has no graceful path:validateAndAcceptConfirmResultsthrowsIllegalStateExceptionbefore recovery runs (ReActAgent.java:1879; ordering at:1794/:1803), andmaybePatchPendingToolCallsdeliberately skipsstate == ASKING(ReActAgent.java:2098) — so a plain follow-up message permanently wedges the session. Suggested: auto-expire / cancel-with-warning plus a synthetic cancelled tool result, matching whatenablePendingToolRecoveryalready does for other orphaned pending calls. - Builder
permissionContext(...)is silently ignored once a persisted state exists. Precedence should either reconcile the two or be documented explicitly.
Direction 1 in the original report (plan tools should not ASK under BYPASS) is already current behaviour and needs no change.
Automated evaluation by github-manager-bot
+1:生产环境数据点——持久化的 ASKING 残留 + #3361 方向正确但需延伸
我们在 AgentScope Java(2.0.x,MySQL AgentStateStore)上的多 Agent 差旅助手实测到与本 issue 相同的行为,补充两个数据点供根因收窄:
1. 残留的不仅是状态位,还是"活锁" ASKING 残留随 (userId, sessionId) 分桶持久化后,同一会话后续所有 turn 都带病启动(工具一调即挂),不是"恢复一次即好"——日志统计单窗口 21 次工具挂起 / 4 次恢复失败。唯一清零手段是换 sessionId,对生产用户等于"让客户重开会话"。
2. 与权限上下文持久化的交互
我们也观察到权限模式(含 BYPASS)会被 AgentState 持久化并在重建 Agent 后沿用旧值——即 #3361(declared rules authoritative,11-04 已合 master)修的那族问题。#3361 的"重建时显式 context 权威覆盖存量 slot 状态"方向完全正确,但请注意 plan/ASKING 语义状态(PendingToolState 等)并不在 permissionContext 覆盖范围内,需要同样的"权威覆盖/清理"处理,否则 plan 场景的残留依旧。
诉求
- 优先把 #3361 的覆盖语义延伸到 plan/ASKING 残留状态(提供等价的"重建即纠偏"路径);
- 短期给一个官方清理手段(API 或 SQL 口径),别让生产用户靠换 sessionId 自救;
- 该 issue 与 #1910(白名单×权限不联动)在生产上通常一起发作,建议作为 Plan Mode 可用性整体排期。
我们因这两个 issue 已整体停用 enablePlanMode(详见 #1910 我们的评论),期待修复后回归。
Verified against main at commit 81b109c (2026-11-05). Two updates to the diagnosis above:
- Hypothesis B is ruled out.
PlanModeMiddleware.ALWAYS_ALLOWEDincludesplan_exit, so there is no second HITL gate independent ofPermissionEngine. And on a fresh BYPASS session fix (1) is already the current behaviour:PlanExitTool#checkPermissionsreturns an unconditional ASK, butPermissionDecision.ask()leavesdecisionReasonunset, so it is not safety-bypass-immune and falls through to the BYPASS ALLOW fallback inPermissionEngine. The ASK only gates on the lightweight path, when the restoredpermission_contextis trivial (mode == DEFAULT, no rules). - PR #3361 (merged 2026-11-04,
d0ce778) changes the precedence part. A non-null builderpermissionContextnow replaces the slot's persisted context on first activation, so a rebuilt agent no longer silently reverts to the lightweight path. But #3361 only coverspermissionContext— it does not touch an already-persisted orphaned ASKING state. That is the defect that is still live:validateAndAcceptConfirmResultsthrowsIllegalStateExceptionbefore recovery runs, andmaybePatchPendingToolCallsexplicitly skipsstate == ASKING, so a plain follow-up message permanently wedges the session. This matches the production data point from @ly19911114 (2026-11-04): every subsequent turn in the same session fails until the sessionId is changed.
Proposed first contribution, following the #3361 precedent: give orphaned ASKING a graceful path when enablePendingToolRecovery is on and the new message carries no ConfirmResult — auto-expire / cancel with a warning event and a synthetic cancelled tool result, instead of throwing. Happy to implement that once a maintainer confirms the direction — or, if you prefer a different shape (e.g. an explicit cleanup API), I will follow that instead.