Skip to content

同步最新代码 - #1

Merged
coderzhn merged 41 commits into
coderzhn:mainfrom
agentscope-ai:main
Nov 13, 2026
Merged

coderzhn merged 41 commits into
coderzhn:mainfrom
agentscope-ai:main

Conversation

@coderzhn

Copy link
Copy Markdown
Owner

AgentScope-Java Version

[The version of AgentScope-Java you are working on, e.g. 1.0.12, check your pom.xml dependency version or run mvn dependency:tree | grep agentscope-parent:pom(only mac/linux)]

Description

[Please describe the background, purpose, changes made, and how to test this PR]

Checklist

Please check the following items before code is ready to be reviewed.

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.)
  • Code is ready for review

ningmao-hlyz and others added 30 commits November 10, 2026 15:52
… acquisition (#4072)

## Description

`Mono.usingWhen` only releases a resource it has already received.
`ReActAgent.acquireCallExecution` creates the `SessionRecorder` — the
constructor takes the journal writer lease — and then starts the
journal,
both before the resource is emitted. A subscriber that cancels in that
window has nothing to release and produces no value, so `doOnDiscard`
never
sees it either. The lease stays taken, and any call on the same
`userId`/`sessionId` is rejected with `Session already has an active
writer`
until it expires.

Cancelling while the model streams is unaffected: the `usingWhen`
cancellation handler already runs `releaseCallExecution(scope,
"cancelled")`.

Fixes #4070

Co-authored-by: jujn <[email protected]>
## Summary

Fixes #4092

The shared `fileExists` helper intentionally excludes directories, so a
normal clone's `.git` directory was not recognized. A subsequent browse
or install attempted another clone into the non-empty cache and failed
with exit status 128.

- Check `.git` existence directly, accepting both directories and
gitfiles without changing the shared helper.
- Keep the existing fast-forward refresh behavior and preserve cache
contents on failure.
- Add local Git regression tests for initial cloning, repeated browsing,
installation-source reading, remote updates, gitfile compatibility, and
invalid cache preservation.
- Document cache refresh behavior in the English and Chinese workspace
guides.
…ed (#3961)

## Problem

Every streamed chunk crosses `LegacyHookDispatcher.fireReasoningChunk`,
which snapshots the whole answer so far into a `Msg` before the dispatch
loop runs:

```java
if (content instanceof TextBlock) {
    accumulatedContent = TextBlock.builder().text(context.getAccumulatedText()).build();
}
...
return Flux.fromIterable(agent.getSortedHooks()).flatMap(hook -> hook.onEvent(event)).then();
```

With no hook registered, that snapshot is built and discarded for every
chunk — one full copy of the answer prefix per token, quadratic over a
stream. The chunk pipeline makes it worse by subscribing from inside the
per-chunk stage:

```java
hookDispatcher.fireReasoningChunk(msg, context, name).contextWrite(...).subscribe();
```

which allocates a `Mono`, copies the Reactor context and starts a
subscription per chunk, only for the result to be `Mono.empty()`.

This is the first item in #3929. It was measured there at −5.7 s of
chain time on a 500-stream run against 2.0.4; on today's `main` the same
guard measures **−3.6 s**, with the difference accounted for by main's
own drift since that tag — see *Independent measurement* below.
…lewares are auto-detected (#3579)

Fixes #3576

### Summary

`MiddlewareBase#activePoints()` keeps its `default` — **fully source-
and binary-compatible: no compile errors, precompiled third-party jars
keep running** — but the contract is now three-tier:

1. **Explicit declarations win.** A non-null set is authoritative, read
once at agent construction: exactly these points participate.
`EnumSet.noneOf(...)` keeps registration with zero participation
(runtime switch); `EnumSet.allOf(...)` explicitly opts into every point.
2. **Undeclared (`null`, the default) = auto-detection.** Participation
is inferred per class — computed once and cached — from the hook methods
the class actually implements; implementations inherited from
superclasses count. `ExtensionPoint` constants now carry their hook
method name to drive detection.
3. **Every middleware should declare explicitly.** The javadoc says so
for humans and AI coding tools alike; the `null` default exists solely
for API compatibility with middlewares written before this contract and
may change in a future release — do not rely on it. All in-repo
middlewares declare.

New `ActivePointsResolver` owns participation in both dimensions:
`resolve`/`infer` (middleware → points) and `middlewaresAt(point,
Supplier)`/`groupByPoint` (points → middleware). `ReActAgent` delegates
its construction-time grouping to it; its frozen snapshot and public
`middlewaresAt(point)` behavior are unchanged.

### Why

- Under the old all-points default, every middleware that didn't
override `activePoints()` participated at every point — including points
added in future releases — so `middlewaresAt(point)` mixed real
participants with middlewares swept in by default, and the documented
"no participants → no wrapper" optimization was unreachable on any real
chain.
- Auto-detection makes the participation set truthful without breaking
anyone: an undeclared middleware now participates exactly where it has
logic; its vacuous participation elsewhere disappears with zero
observable behavior change (those hooks ran pass-through defaults
anyway).
- Explicit declaration remains the recommended statement of intent — it
expresses what inference cannot: intentional opt-out, or participating
at a point without implementing its hook.
- Review rule for future points: activation with side effects beyond the
declaring middleware requires an explicit declaration or an explicit
switch — never `!middlewaresAt(point).isEmpty()`.

### Behavioral note (compatible, but visible)

- `null` previously meant "all points"; it now means "auto-detect from
implemented hooks". For code that relied on the old default this only
removes vacuous participation (pass-through slots); hooks that are
actually implemented keep firing. `middlewaresAt()` results shrink
accordingly — that is the fix.
- Known inference boundary: a hook overridden only by a pass-through
base class still lights up its point; the escape hatch is an explicit
declaration.

### Changes

- **Core:** new `ActivePointsResolver` (explicit-wins resolution,
per-class `ClassValue`-cached hook detection, point-dimension queries);
`activePoints()` default returns `null` with rewritten javadoc;
`ExtensionPoint` constants carry their hook method name; `ReActAgent`
groups via the resolver at construction (frozen map and public behavior
unchanged).
- **All in-repo implementations** (core, harness, extensions, examples,
service-dataplane) declare exactly the points they hook.
- **Tests:** inference semantics (null/default declarations, inherited
implementations, zero-hook middlewares stay out, empty set,
construction-time freezing, per-point filtering), resolver unit tests,
and declaration-consistency checks (shipped middlewares declare every
point whose hook they implement) folded into the core and harness
`*ActivePointsTest`s.
- **Docs:** EN/ZH middleware guide updated to the three-tier contract.

---------

Co-authored-by: juruoO-o <[email protected]>
…4048)

## Description

Fix two production failures observed in a long-running deployment using
a NAS-backed `JsonFileAgentStateStore`.

### 1. Concurrent state persistence

A fixed `<file>.tmp` sibling let concurrent saves consume or overwrite
each other's temporary file, causing `NoSuchFileException` and corrupt
state. Unique temporary names alone did not protect concurrent
replacement of the target, particularly on Windows.

The complete fix now includes:

- Unique temporary siblings with cleanup in `finally`, including
serialization failures.
- JVM-wide, per-session `ConcurrentHashMap<Path, ReentrantLock>` locking
across store instances. Unrelated sessions no longer share a stripe.
Lock entries are retained so queued operations and later writes cannot
acquire different locks after session deletion.
- Root creation followed by `toRealPath()` so stores opened through root
aliases use the same lock key.
- The same session lock around reads, saves, key/session deletion,
`exists()`, and each deletion performed by `clearAllSessions()`. Save
creates its session directory inside the lock. Each per-session
operation resolves its session directory once and derives both its lock
and its file paths from that value.
- Append serialization and UTF-8 encoding completed before opening the
live list file, preventing a serialization failure from publishing a
partial tail. I/O write failures attempt truncation to the original
length and preserve rollback errors as suppressed exceptions.
- Key deletion removes the single state, list, and hash files, then
removes the session directory if empty. The directory stream is closed
before deletion for Windows compatibility.

Concurrency boundaries: these are JVM locks, not cross-process locks;
each session must be owned by one process. Shared multi-process sessions
should use a database-backed store. Separate read-modify-write calls
remain last-writer-wins. Listing is weakly consistent, and clearing
sessions is synchronized per deletion rather than as a global
transaction. List and hash writes are not a two-file transaction:
hash-write or interrupted-I/O failures can leave changed data with a
stale hash until the next save.

### 2. Missing tool-call names

`ToolRequestConfig.resolveTool` previously passed a null model-supplied
name into an immutable map, causing an NPE during permission evaluation.
Null names now resolve to not-found, matching the executor's existing
`Tool not found` behavior.
## Description

Fixes #4108

`HarnessAgent` forwards `setPermissionMode(...)` and
`getPermissionMode(...)` to the wrapped `ReActAgent`, but not
`replacePermissionContext(...)`. A shared `HarnessAgent` that serves
several users can therefore switch the mode per session, but has to go
through `getDelegate()` to install per-session allow/deny/ask rules.

Changes:

- Add `HarnessAgent.replacePermissionContext(userId, sessionId,
permissionContext)`, forwarding to
`ReActAgent#replacePermissionContext`.
- Add a test that replaces the context for one `(userId, sessionId)` and
checks that another user's session is not affected.
- Document the method in the runtime permission switching section of
`plan-mode.md` (EN and ZH).

Not included: the `getAgentState(RuntimeContext)` /
`getAgentState(String, String)` overloads mentioned in the issue. The
deprecated `HarnessAgent.getAgentState()` already points to
`getDelegate()` for those, so I left that as is.
#3377)

{"body": "## Description\n\nFixes #3369.\n\nWhen a `ConfirmResult`
accepts a tool call together with rules to remember, those rules were
only registered with the in-memory `PermissionEngine`
(`ReActAgent.applyConfirmResults`) and never reached
`AgentState.permissionContext`. With an `AgentStateStore` configured,
every call reloads the state from the store and rebuilds the engine from
`permissionContext`, so an accepted rule was lost at the next call
boundary: \"always allow for this session\" did not outlive the call
that granted it.\n\n### Fix\n\n-
`PermissionContextState.withAddedRules(...)`: returns a copy with the
given rules routed by behavior into the allow/deny/ask tables
(PASSTHROUGH and null entries ignored; the instance is never mutated)\n-
`AgentState.updatePermissionContext(...)`: replaces the persisted
context\n- `ReActAgent.applyConfirmResults`: after registering accepted
rules with the engine, merges them into `state.permissionContext` so the
existing `saveStateToSession` persists them \u2014 no change to the save
path or rule format (they land in the existing rule tables of
`permission_context`)\n\nThe design question raised in the issue \u2014
whether runtime-accepted rules should be persisted \u2014 comes down on
the side the issue's own \"Expected\" section describes: a remembered
rule applies on the next call. The permission context is already the
persistence structure for rules; this change makes runtime acceptance
feed it.\n\n\n### Persistence boundary\n\nSessions persisted **before**
this fix never shrink: `fromJson` \u2192 `Builder.appendRule` does not
de-duplicate, so duplicates already written to a state store are
reloaded as-is and preserved by every later `withAddedRules`. That is a
deliberate no-migration choice \u2014 existing stores are left
untouched; only new accepts are subject to the dedup.\n## Testing\n\n-
new `ReActAgentHitlTest.confirmedRulesPersistAcrossCallsWithStateStore`:
with `InMemoryAgentStateStore` configured \u2014 call 1 pauses with
`PERMISSION_ASKING`; call 2 confirms with an ALLOW rule; the rule is
asserted present in the **persisted** state's permission context; call 3
with the same tool runs without re-asking\n- `ReActAgentHitlTest`: 20
passed\n"}
## AgentScope-Java Version

2.0.4-SNAPSHOT (contribution based on main at `3c1c29c0`)

## Description

Fixes #3285.

Fixes cases where `ShellCommandTool` accepts a whitelisted executable
but allows shell syntax in its arguments to trigger additional execution
or file writes without approval. It also makes empty-whitelist behavior
consistent with the tool description.

### Before

With `echo` whitelisted:

```text
echo "$(printf marker)"
  -> executable matches whitelist
  -> validation passes
  -> sh evaluates the substitution without approval

echo marker > marker.txt
  -> executable matches whitelist
  -> validation passes
  -> shell writes the file without approval

Empty whitelist
  -> validation allows every command
  -> approval callback is bypassed
```

### After

```text
Ordinary whitelisted command
  -> validation passes
  -> execute

Command requiring approval
  -> validation rejects automatic execution
  -> approval callback
       approved                 -> execute the original command
       denied, unavailable,
       null result, or exception -> return SecurityError

Empty whitelist
  -> require approval through the same callback path
```

### Implementation

- Detect Unix command substitution, variable expansion, redirection, and
grouping syntax before automatic execution.
- Correct Unix quote handling: backslashes are literal inside single
quotes, while substitutions remain active inside double quotes.
- Detect Windows variable expansion, redirection, grouping, and line
separators; account for caret handling and outer-quote stripping by
`cmd.exe /c`.
- Reject unbalanced quoting and ambiguous quoted executable prefixes.
- Require relative executables to match the whitelist after passing the
existing path-safety check.
- Route null or empty whitelists through the existing approval
mechanism.
- Update API/class Javadocs, the tool description, and English and
Chinese tool documentation.
- Add regression tests without introducing dependencies.

### Compatibility and behavior boundaries

- **Breaking behavior change:** `new ShellCommandTool()` rejects
commands until its whitelist is configured. Applications needing
callback-based execution can use `new ShellCommandTool(allowedCommands,
approvalCallback)`.
- Clearing the whitelist now requires subsequent commands to receive
approval.
- Relative executables must match the whitelist; remaining within the
current directory alone no longer grants permission.
- Commands using the newly detected shell syntax require approval even
when their executable is whitelisted.
- Approved commands still execute through `sh -c` or `cmd.exe /c`.
Approval therefore authorizes the complete original command.
- These changes apply to the default validators. Custom validators
remain responsible for their own validation policy.
- A command whitelist is not a sandbox: allowed programs may themselves
execute code or access files.

### Tests

- `CommandValidatorTest`: 66 cases covering Unix and Windows shell
syntax, literal arguments, quote/escape handling, empty whitelists,
executable boundaries, relative paths, and Windows outer-quote
stripping.
- `ShellCommandToolTest`: 10 cases covering default rejection, ordinary
whitelisted execution, approval acceptance/denial/failure, empty and
cleared whitelists, and prevention of unapproved file writes.

### Verification

Environment: Windows 11, OpenJDK 21.

- `mvn -B -pl agentscope-core -am spotless:apply
"-DspotlessFiles=.*coding.*[.]java"` — passed.
- `mvn -B -pl agentscope-core -am verify
"-Dtest=CommandValidatorTest,ShellCommandToolTest"` — passed, including
Spotless checks, packaging, and Javadoc generation.
- Focused tests: 76 total, 75 passed, 0 failures, 0 errors, 1 skipped.
The skipped test requires Unix shell execution; both platform validators
were tested directly.
- `mvn -B -pl agentscope-core -am verify` — 2,532 tests, 0 assertion
failures, 2 errors, 9 skipped. The errors occurred in existing
`DangerousPathBypassTest` symlink tests because the Windows account
lacks symbolic-link creation privileges.
- `git diff --check` — passed.

The full repository reactor and native Linux execution have not been
verified locally.

## Checklist

- [x] Code has been formatted with `mvn spotless:apply`
- [ ] All tests are passing (`mvn test`) — full core verification
encountered the two Windows permission errors described above
- [x] Javadoc comments are complete and follow project conventions
- [x] Related documentation has been updated
- [x] Code is ready for review
## AgentScope-Java Version

2.1.0-SNAPSHOT,验证基线为 `main` 的
`5baff2613401bf87b3a967b185f2f14945ec594e`。

## Description

Fixes #4073.

### 问题与修复

降级结构化输出路径允许模型在同一响应中返回业务工具调用与内部 `generate_response` 调用。原来的
`compressStructuredOutputContext`
会删除整个混合消息,业务工具结果却仍保留,导致持久化历史以及下一轮请求出现没有对应 `tool_use` 的 `tool_result`。

本 PR 仅调整该清理方法:

- 混合消息只移除内部输出工具内容块,保留业务调用及其配对结果,以及原消息的 ID、名称、角色、时间戳、非 usage
metadata、text 和 thinking。
- 纯输出工具消息和内部提醒继续按原规则删除;无关消息(包括空消息)原样保留。
- 清理前已归集到最终结构化结果的 usage,不再保留到混合消息副本中,避免同一份使用量在历史里重复计数;最终返回值的 usage
不变,也不修改原消息对象。

不修改共用分类函数、usage/thinking 收集器、工具调度、权限、重试、native structured-output 路径或公共
API;不迁移此前已损坏的历史。

### 回归测试

新增 `ReActAgentStructuredOutputCleanupTest`,使用假模型和真实本地 Java
工具,不需要网络或模型凭证:

- 输出工具在业务工具之前/之后、业务与输出分轮、纯输出四种情况,分别使用默认状态和显式 `InMemoryAgentStateStore`,共
8 个参数化场景。
- 验证工具调用与结果的 ID 配对、内部输出工具内容被清理、业务工具不重复执行。
- 读回持久化状态并重建 Agent,验证下一轮模型收到的历史仍完整。
- 验证消息身份、非 usage 元数据、text/thinking、最终返回 usage,以及历史 usage
总量不重复;原消息对象保持不变。
- 未修复实现上,4 个混合批次场景失败,4 个对照场景通过;修复后 8 个全部通过。

同步补充中英文 Agent 文档中的历史清理行为说明。

### 验证结果与边界

以下 Maven 检查在上述基线加本提交上完成,本地使用离线缓存和 central-only settings:

```sh
mvn -B -T1C -pl agentscope-core -am test
mvn -B -T1C -pl agentscope-core -am spotless:check
```

- Core 全量:3031 项,0 failures、0 errors、9 skipped,BUILD SUCCESS。跳过项为现有的 7
个流契约占位测试、1 个需显式开启的压力测试、1 个仅 Windows 的测试。
- 结构化输出相关针对性测试:37 项,0 failures、0 errors、1 skipped。
- Spotless 与 `git diff --check` 通过。
- Docs:`npm test` 13 项通过,`npm run validate` 通过,`npm run broken-links`
未发现坏链接。

尚未执行全仓库 `clean verify`、Windows 或真实模型厂商集成测试;不将这些列为已验证。

### 与相关 PR 的协调

提交前注意到 #4078 也针对 #4073 提供了实现,两个 PR 存在重叠。本实现同时包含非零 usage
的历史总量断言、原消息不变性和持久化后重建 Agent 的回归检查,保留混合消息时不再重复携带已归集到最终结果的
usage。这里说明本实现的设计与验证范围,并非对 #4078 未验证行为的缺陷判断。

欢迎维护者比较、选择或整合合适的实现与测试;不需要合并两个重复修复。

## Checklist

- [x] Code has been formatted; Spotless checks pass.
- [ ] All repository tests are passing (`mvn test`) — 已验证上述 core
范围,未执行全仓库测试。
- [x] Javadoc comments follow project conventions — 未新增公共 API。
- [x] Related documentation has been updated in English and Chinese.
- [x] Code is ready for review.
fix(harness): anchor memory reads to the caller's namespace

## Description

`WorkspaceManager.readWithOverride` falls back to
`workspace.resolve(relativePath)` when the filesystem layer returns no
content, which drops the per-identity namespace that layer applies. For
memory files this makes two reads cross the boundary:

- `memory_get("alice/MEMORY.md")` as bob resolves to
`bob/alice/MEMORY.md`
  in the filesystem layer (miss), then falls back to the un-namespaced
  `workspace/alice/MEMORY.md` and returns alice's content - the `./`
  spelling reaches the same file once normalized.
- A root-level `MEMORY.md` left over from a pre-namespace workspace is
  served to every identified caller, while `memory_search` cannot list
  it - the read and search surfaces disagree.

### What changed

- Reads of per-identity runtime data (memory files, task records) use a
namespace-anchored fallback: filesystem first, then the local disk
inside
the caller's namespace. The filesystem layer already resolves per
caller,
so a user-level copy overrides the shared one; what changes here is the
  fallback, which no longer reads the workspace root. Contexts with no
namespace at all, or without a configured filesystem, keep the
historical
root read (the write path does not namespace either then). The namespace
  is resolved once per read and shared with `resolveRuntimeDataPath`.
- Task records (`agents/<agentId>/tasks/<sessionId>.json`) take the same
anchored fallback. Their write path already namespaces them, so the read
path was the odd one out: a root-level leftover record was served to any
  identity that named the file.
- `memory_get` rejects `..` up front through the workspace manager's own
rule (`WorkspaceManager.requireSafeRelativePath`, promoted from private
so
  the tool reuses it instead of mirroring the normalization - leading
  whitespace and slashes cannot smuggle the segment past the check) and
validates containment against the resolved, namespaced path. A rejected
path is a tool error instead of a failed turn, and errors from the read
  itself are not translated.
- Its tool description said the path was relative to the workspace. It
now
  says the caller's memory namespace, which is where the path resolves -
  the model reads that string when deciding what to pass.
- A root-level leftover is reported once per path per manager, so an
  operator upgrading an existing workspace knows to move it; it is no
  longer served.
- `docs/v2/{zh,en}/docs/harness/workspace.md` state the two-layer rule
as one
table - the filesystem layer resolves per caller, and the fallback
differs
  by who owns the data - so per-identity data is a row rather than a
memory-only special case, keep the upgrade note, and drop the namespace
  annotations repeated on every layout tree;
  `docs/v2/{zh,en}/docs/harness/filesystem.md` points at that rule.

### Compatibility

An identified caller no longer reads the workspace-root `MEMORY.md`.
That
file belongs to no identity, so serving it was the leak. Two scopes are
unaffected: single-tenant setups without `userId`/`sessionId` - or
without
a configured filesystem - keep the root read, and a
`<project>/MEMORY.md`
served through the project layer of
an overlay stays shared - that layer is the deliberately shared project
tier (same level as `AGENTS.md` and `knowledge/`), not a per-identity
fallback. Task records follow the same rule: a record left at the
workspace root is no longer served to an identified caller.

### Tests

- New: a sibling-namespace read is rejected through both the workspace
  manager and `memory_get`, in the plain, the `./` and the
  leading-whitespace `..` spelling - the last failing the whole turn on
the previous code. Each `memory_get` case asserts the `ERROR` state and
  that the tool output never contains the sibling's content.
- New: a root-level `MEMORY.md` is not served to identified callers,
while
  an identity-less read still returns it.
- New: a task record is read from the caller's namespace, and a
root-level
leftover copy of the same record is not served to another identity. Both
  fail on the previous code.
- `HarnessAgentIntegrationExampleTest` materializes `MEMORY.md` under
the
  call's namespace, matching where the file is resolved.
- `mvn -pl agentscope-harness test`: 1625 tests, 0 failures.

Fixes #4052
)

## AgentScope-Java Version

2.1.0-SNAPSHOT
## Description

When users a and b shared a task repository and used the same parent
session ID,
b could look up or cancel a's background task if b knew its task ID. The
workspace
kept their persisted records separate, but the local cache only checked
the
session ID and task ID.

This change includes the task storage namespace in the local cache key.
Task
lookup, cancellation, recovery, and maintenance now follow the same
isolation
rules as the stored records. Workspaces configured to share tasks still
do so.

Added regression tests for cross-user lookup and cancellation, shared
workspaces,
anonymous users, and remote task recovery.


To run the focused tests:

`mvn -pl agentscope-harness -am "-Dtest=WorkspaceTaskRepository*Test"
"-Dsurefire.failIfNoSpecifiedTests=false" test`

## Checklist

Please check the following items before code is ready to be reviewed.

- [x]  Code has been formatted with `mvn spotless:apply`
- [x]  All tests are passing (`mvn test`)
- [x]  Javadoc comments are complete and follow project conventions
- [x] Related documentation has been updated (e.g. links, examples,
etc.)
- [x]  Code is ready for review
Fixes #4045

## AgentScope-Java Version

`2.1.0-SNAPSHOT`;本地验证提交:`000386c816507cf3fbbc39fc95e0a7accadc4da0`(基于
`85fa9a60257ceb1570e6a195d0588ceba1e8a8c2`)。

## Description

并行工具批次中,已完成工具的 `action/end` 可以先于批次结果写入 canonical
context。若工具更新了会话状态,此时硬取消产生的新 checkpoint
会遮蔽已记录的完成结果;显式核对真正不确定的兄弟工具并恢复后,已成功工具可能再次执行。完整复现及四组对照见 #4045。

本 PR 将改动限定在取消收尾:

- 在 `SessionRecorder` 中保留本轮完成工具结果的冻结副本。
- 仅在 `finish(..., "cancelled")` 时,向恢复快照补入当前仍有未配对本地调用的完成结果。
- 不修改 live context,不覆盖 canonical 已有结果,不补 suspended 或已移除的调用。
- 不改变正常批次、middleware/PostActing 的执行顺序;未知工具仍要求显式 reconciliation。

生产代码只改 `SessionRecorder.java`(35 行新增、1 行删除),另加两个测试文件;无公共
API、事件格式、依赖或配置变化。不修改 `SessionProjection` 或恢复扫描锚点。

### 验证

在 macOS / Microsoft OpenJDK 21.0.7(源码 release 17)上,对本 PR 实际提交树完成干净构建:

```sh
mvn -B -T1C -pl agentscope-core -am clean test spotless:check
```

本地使用 Maven Central settings 和离线缓存;结果:

```text
Tests run: 3031, Failures: 0, Errors: 0, Skipped: 9
BUILD SUCCESS
```

- 新增 15 项回归全部通过:call/streamEvents ×
状态变化/不变;已改写结果优先且不重复;移除调用/状态回退不复活旧结果;未知结果仍不确定;suspended、ERROR/DENIED
和旧结果编码兼容;live state 不被修改。
- 9 项为仓库现有条件跳过:7 项 stream ordering 占位测试、1 项需显式开启的结构化输出竞争测试、1 项
Windows-only 测试。
- Spotless 与 `git diff --check` 通过。
- 未执行全仓 `verify`;以上是本地验证,不代表上游 CI 已通过。

### 范围边界

本修复确保成功写出的取消 checkpoint 保留本轮已确认结果,不承诺任意进程崩溃下的
exactly-once,也不迁移或修复已经产生的受损日志。hard cancellation 不保证协作中断回复/保存路径的现有契约不变。

## Checklist

- [x] 已格式化并通过 Spotless 检查。
- [x] 完整 `agentscope-core` 测试通过,条件跳过与未执行的全仓验证已在上面明确列出。
- [x] 无新增公共 API,现有 Javadoc 契约不变;新增内部逻辑有范围说明。
- [x] 已核对文档影响:本次修正取消恢复缺陷,不新增 API/配置或更改现有中断契约,无文档变更。
- [x] 代码已完成本地 review,可供维护者审阅。
…he session (#4033)

## AgentScope-Java Version

2.1.0-SNAPSHOT (`main` at `85fa9a60`)

## Description

A managed Turn that fails (model error, budget exceeded, max iterations)
is terminal in the public Session API, but the dataplane still holds it
ahead of later Turns until it is resumed or cancelled
(`SessionTurnCommandRepository.findDispatchable`). The control plane
gave no way to release it:

- `createServiceCommand` rejected every command on a terminal invocation
with `409 invocation has ended`;
- `requestServiceCancellation` returned early for terminal invocations,
so `cancel` never reached the dataplane;
- `resume` only accepts `interrupted` dataplane turns, and the
projection stops refreshing terminal invocations.

As a result every later Turn in the Session stayed `queued` forever.

This PR adds an explicit discard path in the control plane. Neither
state machine changes:

- When the public Turn is `failed` and its dataplane turn is still
`failed`, accept `/cancel` and forward it to the dataplane
`/turns/{id}/cancel`. That endpoint already runs `cancelPending` and
moves the turn to `cancelled`, which releases the Session queue.
- The public Turn keeps its `failed` status. No terminal state is
reopened and no tool call is replayed.
- Turn `/capabilities` lists `cancel` in `available_commands` for such a
Turn.
- Other commands on such a Turn still return 409, now pointing to
`cancel` instead of suggesting a new invocation.
- The EN and ZH `service/session-event-log` pages describe the discard
step.

Resuming a failed Turn would require reopening a terminal invocation and
its projection, so it is out of scope here.

### Validation

- New `TestPublicManagedSessionCancelDiscardsFailedTurn` walks through
the whole path with a fake dataplane: failure is projected, only
`cancel` is offered, `resume` gets 409, `cancel` gets 202, the sweep
forwards exactly one dataplane cancel, the command completes, the Turn
stays `failed`, and a second `cancel` gets 409. It fails on `main`
without this change.
- `go test -p 1 ./...` and `go vet ./...` in `service-controlplane` pass
against PostgreSQL 17 with `CONTROL_PLANE_TEST_POSTGRES_DSN` set,
matching the service source check workflow. `gofmt -l` is clean.
- The dataplane is unchanged; its existing `cancel()` handling of
`failed` turns was read but not exercised end to end against a live
deployment. Documentation checks (`npm test`, `npm run validate`) were
not run locally.

Fixes #4011

## Checklist

- [x] Code has been formatted (`gofmt`; no Java files changed, so `mvn
spotless:apply` does not apply)
- [x] All tests are passing (`go test -p 1 ./...` in
`service-controlplane`; `mvn test` not affected)
- [x] Javadoc comments are complete and follow project conventions (no
Java changes)
- [x] Related documentation has been updated
- [x] Code is ready for review

AI assistance: developed with help from Claude Code. I reviewed the
change, and the checks listed under Validation were run locally.

Co-authored-by: Claude Opus 5.5 <[email protected]>
…rsed arguments (#3886)

## AgentScope-Java Version

2.1.0-SNAPSHOT (based on `main` @ `e190a8d1b`)

## Description

`ToolCallsAccumulator` fabricated `content = "{}"` whenever a tool call
arrived **without streamed
argument fragments** — the shape produced by providers and custom
`Model` implementations that
emit the complete call in one chunk with the parsed `input` only (the
in-repo e2e fixtures
themselves construct exactly this shape). The intact `input` map
survived beside the fabricated
content, but every **content-first** consumer of
`JsonUtils.resolveToolCallArgsJson` resolved the
arguments to `{}` — the empty object is *valid* JSON, so the resolver's
existing fallbacks
(null/empty/invalid content) never fired:

- **Required-parameter validation** (`ToolExecutor`) rejected the call
before execution — any tool
declaring `required` parameters was 100% rejected on this path, with the
model told to "correct"
  arguments it had actually supplied;
- **Request builders** (e.g. the OpenAI message converter) replayed the
assistant's tool call to
the provider with empty arguments, so later turns showed the model a
call it never made;
- **Compaction** serialized the same empty arguments into summaries.

Nothing warned or logged; calls to tools without required parameters
even executed correctly
(the invocation path reads the input map), which made the failure look
model-sided.

Three coordinated changes close the fabrication, the blind spot, and the
direct-path execution
gap:

1. **Source** — the accumulator serializes the parsed arguments instead
of fabricating an empty
object (`toJsonFallbackEmptyObject`, the shared guarded entry point also
used for input
serialization; a serialization failure falls back to `"{}"` instead of
failing the reply
stream). The content-always-valid-JSON invariant and the
malformed-marker paths (truncated or
invalid raw content) are unchanged; a true no-argument call still
produces `"{}"`.
2. **Resolution** — `resolveToolCallArgsJson` no longer lets an
empty-object content mask intact
parsed arguments: when the content is an empty JSON object (any
whitespace form) and
`getInput()` carries arguments, the input is used. This covers blocks
that were **already
persisted** with the fabricated value (resumed sessions never pass
through the accumulator
again) and blocks constructed directly by application code, for all
three consumers at once
(validation, request builders, compaction). First-party adapters derive
both fields from the
same source, so the branch is unreachable for well-formed provider
output; an empty-object
   content with an empty input resolves to `"{}"` exactly as before.
3. **Malformed-argument blocks** (truncated/corrupt raw content, marked
by the accumulator) are
   exempt from the input recovery in both the resolver and the executor:
`resolveToolCallArgsJson` keeps their content when it is valid JSON and
sanitizes
null/empty/invalid content to `"{}"` — never the merged input, never
invalid JSON; and
`ToolExecutor` (the single funnel behind direct `Toolkit.callTool`
paths) now refuses any
malformed-marked call before schema validation. The merged input beside
the marker may even
look complete and schema-valid — without the guard such a call would
execute on paths the
agent loop already refuses (red-verified: it executed and returned its
result).

### Compatibility

- Behavior change is confined to blocks that carried a **fabricated**
`"{}"` while a non-empty
input map sat beside it: they now resolve to the real arguments
everywhere. No consumer loses
information; no-argument calls and non-empty content behave exactly as
before (pinned by the
existing suites). Malformed/interrupted fragments keep their agent-loop
behaviour (the loop
already refuses them); on direct `Toolkit` paths they now return an
ERROR result instead of
possibly executing from the merged input — the same refusal the loop
applies.
- A serialization failure still surfaces to the model as the generic
parameter-correction message
when schema validation rejects the `{}` fallback (tools without required
constraints keep
executing from the input map); a dedicated "arguments could not be
serialized" reason is left
  as a follow-up.
- No public signatures, serialized state formats, or event payloads
change.

### Known residual (deliberately out of scope)

- `content` (raw JSON text) and `input` (parsed map) remain two
representations on a tool
call. First-party adapters keep them consistent, and this PR removes the
one divergence the
framework itself created (the fabricated `"{}"`). But the accumulator's
pre-existing merge
rule (streamed content fragments only fill keys missing from the input
map, and the raw text
is kept as content) means a provider emitting **both** representations
with conflicting
values still yields a block where content-first consumers (validation,
replay, compaction)
see one value while execution merges the other. Unifying the
representations (e.g. content ≡
serialized input at accumulation time) trades away raw-payload replay
fidelity and changes
  persisted state — a contract decision left out of this PR on purpose.
- Executor-side schema validation ahead of the permission gate
(including the same
empty-object-with-args predicate) is #3321's track; with this PR's
resolver change the two
  converge on the same outcome and do not conflict.
- A serialization failure does not yet produce a dedicated failure
reason/marker (see above).

## Tests

Sixteen new cases. The core ones were red-verified against pre-fix code
— verbatim failure
output:

```
ToolCallsAccumulatorTest.testInputOnlyCompleteBlockSerializesInputAsContent:367
  content: {} ==> expected: <true> but was: <false>
JsonUtilsTest.testEmptyObjectContentWithArgsFallsBackToInput
  result: {} ==> expected: <true> but was: <false>
ReActAgentNewLoopE2ETest.inputOnlySingleChunkToolCallWithRequiredArgsExecutes
  (ToolResultEndEvent state: expected SUCCESS but was ERROR — parameter validation failed)
ToolExecutorTest.shouldNotExecuteMalformedCallWithValidContent:200
  malformed calls must not execute even when the merged input looks complete: 30
  ==> expected: <ERROR> but was: <RUNNING>
```

| Test | Asserts |
|---|---|
| `testInputOnlyCompleteBlockSerializesInputAsContent` | a single-chunk
input-only block builds with content carrying the parsed arguments
(valid JSON containing them) and the input map preserved |
| `testUnserializableInputFallsBackToEmptyObjectContent` | an
unserializable input value never throws out of the accumulator: content
falls back to `"{}"` and the input map stays available to a call that
passes schema validation |
| `testTruncatedInputOnlyBlockWithArgsIsNotMalformed` | an output-limit
stop (`truncated=true`) after the parsed input arrived complete leaves
the call unmarked and executable — truncation alone is not malformation
|
| `testTruncatedInputOnlyBlockWithoutArgsIsMalformed` | an output-limit
stop on an argument-less input-only start cannot establish a complete
no-arg call, so the malformed marker is set |
| `testNoArgInputOnlyBlockStaysUnmarked` | the other matrix cell: no
fragments and no arguments on a completed stream is a legitimate no-arg
call — `"{}"` content, no marker |
| `testEmptyObjectContentWithArgsFallsBackToInput` | the resolver uses
the input when the content is exactly `"{}"` and arguments are present
(legacy/directly constructed blocks) |
| `testWhitespaceEmptyObjectContentWithArgsFallsBackToInput` |
whitespace-padded empty objects (`"{ \n }"`) fall back to the input too
— the predicate is structural, not a literal |
| `testEmptyObjectContentWithoutArgsStaysEmpty` | an empty-object
content with an empty input still resolves to `"{}"` |
| `testMalformedBlockKeepsContentDespiteInput` | malformed-argument
blocks keep their content even with a non-empty input — the merged input
must not leak through |
| `testMalformedBlockWithoutUsableContentResolvesEmpty` | malformed
blocks with null, empty, or invalid content resolve to `"{}"` (never
invalid JSON, never the merged input) |
| `testMalformedBlockWithValidContentKeepsContent` | malformed blocks
with valid non-empty content keep that content — replay/compaction see
the raw payload; the marker blocks execution, it does not rewrite
history |
| `inputOnlySingleChunkToolCallWithRequiredArgsExecutes` | through the
full ReAct loop, a tool with `required: ["query"]` called via a
single-chunk input-only response executes successfully and receives the
argument (`search:alpha`), instead of a validation rejection |
| `unserializableInputCompletesTurnWithRecoverableErrorResult` | an
unserializable input does not fail the reply stream: the turn ends with
`AgentEndEvent`, and a paired `ToolResultEndEvent` for `c1` exists with
state `ERROR` and the same id in the context |
| `shouldNotExecuteMalformedCallWithPartialInput` | through a direct
`Toolkit.callTool` (no agent-loop malformed filter), a truncated call
whose merged input looks complete is refused instead of executed —
red-verified pre-guard (`not executed from merged input: 30`); the error
message pins the guard (not schema validation) as the rejecting layer |
| `shouldNotExecuteMalformedCallWithBlankContent` | a malformed marker
with no usable content is also refused on direct `Toolkit` paths
(content sanitizes to `"{}"`; no fall-back to the merged input);
message-pinned to the guard as well |
| `shouldNotExecuteMalformedCallWithValidContent` | a malformed marker
whose content and merged input are both complete and schema-valid is
still refused before validation — red-verified pre-guard (`looks
complete: 30 ==> expected: <ERROR> but was: <RUNNING>`) |

The existing malformed/interrupted-content tests (`"{}"` + empty input,
malformed markers) and the
resolver's null/empty/invalid-content fallback tests stay green
unchanged, pinning that only the
fabricated-empty-object path changed.

Regression: full `agentscope-core` suite — 2963 tests, 0 failures, 8
pre-existing skips;
`spotless:check` clean.
## AgentScope-Java Version

2.1.0-SNAPSHOT, based on main
`c3959cea69c40e2c44fd2365dfbdeed4bc53e951`.

## Description

Fixes #3642.

Two concurrent `submit` calls with the same task ID can both observe no
running future and schedule an agent run, despite the documented
idempotency contract. A persisted PENDING record does not prevent the
second submission from passing the check before the first future is
registered. This can duplicate model/tool execution and leave only one
of the runs addressable by task ID.

Use the existing per-task monitor (already used by `resume`) around the
submission checks, pending persistence and future registration. Actual
agent execution remains asynchronous; different task IDs retain
independent registration. Keep the existing identity-based future
cleanup and terminal-task rejection behavior. Update the English and
Chinese protocol guides to state the single-instance scope.

The regression pauses the first PENDING save after it reaches a real
temporary workspace repository. A second submission then either
completes registration on the old code or blocks on the first thread's
task monitor after the fix. The agent stream is held open until
assertions finish. A separate different-ID case requires the second
submission to finish before the first save is released, guarding against
accidental global serialization. Completion and rejection of a completed
ID are also checked.

### Validation

Java 17.0.20.1, Maven 3.9.12, Windows, from the repository root:

```shell
mvn -B -T1 -pl agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agent-protocol -am -Dtest=AgentProtocolTaskStoreConcurrentSubmitTest -Dsurefire.failIfNoSpecifiedTests=false spotless:apply test
mvn -B -T1 -pl agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agent-protocol -am "-Dtest=AgentProtocol*Test,WorkspaceProtocolTaskRepositoryTest" -Dsurefire.failIfNoSpecifiedTests=false spotless:apply test
mvn -B -T1 -pl agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agent-protocol -am spotless:check
```

- Final regression tests with the original production implementation: 2
tests, 1 failure (`one registration per logical task ==> expected: <1>
but was: <2>`); the different-ID control passes.
- Fixed implementation: all 35 protocol module tests pass, including
existing HITL resume tests; no failures, errors or skips.
- Spotless and `git diff --check` pass.
- In `docs/`, `npm test`: 13 pass; `npm run validate`: passes (430
pages, 584 redirects plus Mintlify build validation).
- `npm run broken-links`: exits 1 with 2,208 reported links in 326
files. Re-running with the original EN/ZH pages gives the same file/link
entries; no new reports from this change.

Scope: coordination within one `AgentProtocolTaskStore`, not
cross-replica exactly-once execution. This reuses the existing task-lock
registry and its lifecycle; cancellation and persisted-task recovery
semantics are unchanged. Full-repository `clean verify` and
real-model/HTTP integration tests were not run.

AI assistance: investigation, implementation and test execution were
performed with Codex. The final diff was checked against the
reproduction and the validation above; this is not a claim of
independent human review.

## Checklist

- [x] Code has been formatted with `mvn spotless:apply`
- [ ] All tests are passing (`mvn test`) — all 35 protocol module tests
pass; full-repository suite not run
- [x] Javadoc comments are complete and follow project conventions
- [x] Related documentation has been updated
- [x] Code is ready for review
…rruption (#3208)

## AgentScope-Java Version

2.0.4-SNAPSHOT

## Description

### Background

The `write_text_file` tool accepted invalid `ranges` values. After
parsing `[start, end]` it only checked `start <= fileLength`; it did not
check `start >= 1` or `start <= end`, and it did not handle negative
indexes (even though the sibling `view_text_file` tool documents and
supports `-100,-1` style ranges).

Because the `ranges` argument is generated by the model during
autonomous file editing, malformed values occur in practice:

- Reversed range `[5,2]` on a 5-line file silently duplicated lines
(result: `one two three four NEW three four five`) and still reported
success.
- Zero-based range `[0,2]` silently deleted the first lines.
- Negative range `[-3,-1]` threw an `IndexOutOfBoundsException` from
`subList(-1, 5)` with an unhelpful message.

This is silent data corruption in a destructive tool, which makes the
agent keep working on a damaged file.

### Changes

- Validate `start >= 1` and `start <= end` before any file mutation;
return a clear error result and leave the file untouched otherwise,
matching the validation already performed by `view_text_file`.
- Add `WriteFileToolTest` covering valid replacement, reversed range,
zero-based start, negative range, start beyond file length, and new-file
creation. The class previously had no unit tests.

### How to test

`mvn -pl agentscope-core test
-Dtest='io.agentscope.core.tool.file.*Test'` — 11 tests pass (6 new + 5
existing).

## Checklist

- [x] Code has been formatted with `mvn spotless:apply`
- [x] All tests are passing (`mvn test`)
- [x] Javadoc comments are complete and follow project conventions
- [x] Related documentation has been updated (e.g. links, examples,
etc.)
- [x] Code is ready for review

---------

Co-authored-by: ”zhuzhiyu.zzy“ <[email protected]>
## AgentScope-Java Version

2.0.4-SNAPSHOT (based on main at `857e3e6`)

## Description

Fixes #3313.

`MarketplaceStager` previously used unchecked skill names and source
namespaces to construct staging directories. An absolute-path name could
redirect resource writes and stale-file cleanup outside the cache.
Relative traversal could also redirect cleanup even when resource
writing was blocked.

This change validates both path components before any per-skill
filesystem mutation.

**Implementation**

- Normalize the workspace root before resolving cache paths.
- Require skill names and source namespaces to resolve to direct child
directories.
- Reject path separators, drive/stream syntax, traversal aliases, and
names ending in a dot or space.
- Handle invalid paths through the existing per-skill failure handling,
returning `StageResult.NONE` while continuing to stage valid entries.
- Preserve supported names containing uppercase letters, internal
spaces, underscores, and dots.
- Update API Javadoc and the English and Chinese skill documentation.

Validation remains local to the staging boundary. This patch addresses
path-name traversal; it does not introduce symlink-safe filesystem
operations.

**Tests**

Added 31 regression cases covering:

- Absolute-path writes, overwrites, and cleanup outside the cache.
- Relative traversal and normalized path aliases.
- Unsafe source namespaces, including repository-source fallback.
- Unsafe names loaded from actual `SKILL.md` frontmatter.
- Continued staging of valid skills after an invalid entry.
- Normal resource staging, binary resources, stale-file cleanup, and
default namespaces.

**Verification**

Executed on Windows with OpenJDK 21:

```shell
mvn -B -ntp -pl agentscope-harness -am verify "-Dtest=MarketplaceStagerPathTest,MarketplaceStagerExecBitTest,MarketplaceStagerOrphanGcTest,SharedWorkspaceSkillStagingE2ETest,SkillRuntimeTest,SandboxLifecycleMiddlewareCallbackTest" "-Djacoco.append=false"
```

- Focused suite: 79 tests, zero failures or errors; one POSIX-permission
test skipped on Windows.
- All 31 new regression cases passed.
- Changed executable lines: 16/16 covered.
- New resolver branches: 11/12 covered locally; Windows rejects trailing
spaces during path parsing before the explicit guard.
- Spotless formatting and checks passed.
- Javadoc generation passed.
- Documentation validation passed: 411 pages and 479 redirects.
- `git diff --check` passed.

The full repository test suite was not run locally.

## Checklist

- [x] Code has been formatted with `mvn spotless:apply`
- [ ] All tests are passing (`mvn test`)
- [x] Javadoc comments are complete and follow project conventions
- [x] Related documentation has been updated
- [x] Code is ready for review

---------

Co-authored-by: ”zhuzhiyu.zzy“ <[email protected]>
… local filesystem (#3292)

## Summary

With `LocalFilesystemSpec` and a per-session/per-user `IsolationScope`,
absolute paths bypass the session namespace entirely: the namespace
prefix only scopes *relative* keys (`applyNamespacePrefix` passes
absolute keys through), and the `ROOTED` acceptance check treats the
workspace root as an implicit allowed root. One session could therefore
enumerate and read another session's directory under the shared
workspace root (`MEMORY.md`, `memory/`, `agents/`, generated artifacts)
with a plain absolute path — making `IsolationScope.SESSION` a path
*prefix* rather than an access *boundary*.

Fixes #3261. It implements the "reject absolute keys that resolve inside
another namespace" direction from the issue evaluation; happy to rework
if maintainers prefer the effective-root design.

## Changes

- **`LocalFilesystem`** gains an opt-in `namespaceBoundary(boolean)`.
When enabled, in `ROOTED` mode an absolute path that resolves under
`cwd` must resolve under `cwd/<namespace>` to be accepted; anything else
is rejected with a `SecurityException` that names the namespace root.
The leading-slash virtual form (`/foo` → `<workspace>/foo`) is covered
too, since it resolves under `cwd` the same way.
- Paths under `PathPolicy` roots that lie outside `cwd` (the read-only
project layer, `additionalRoots`) are unaffected.
- With no namespace active for the call (`AGENT`/`GLOBAL` scope, or
missing user/session identifiers) the check is a no-op.
- The boundary is off by default for direct `LocalFilesystem` users;
`LocalFilesystemSpec` enables it for the workspace layer when `mode ==
ROOTED` (the spec default). `SANDBOXED` already re-roots absolute paths
under the workspace; `UNRESTRICTED` is documented to pass absolute paths
through.
- Relative keys are untouched: they are prefixed into the own namespace,
and `..` segments are already rejected by
`AbstractFilesystem.validatePath`.

## Behavior change to be aware of

With a namespace active, absolute access to *shared* directories sitting
at the workspace root (e.g. `skills/`, `knowledge/`) is now rejected as
well — from the filesystem alone those are indistinguishable from a
sibling session's directory. Shared content remains reachable through
workspace-relative paths, which the overlay resolves against the
read-only project layer; the injected workspace prompt already steers
the model to relative paths. If maintainers would rather keep a
shared-areas carve-out (e.g. a configurable allowlist of shared dir
names), I'm glad to iterate.

As noted in the issue evaluation, `execute()` still runs host shell
commands and is out of scope here — the local + shell mode is documented
for trusted single-process hosts.

## Testing

- `LocalFilesystemModeTest`: new cases for sibling-namespace rejection,
own-namespace allowance, workspace-root absolute rejection,
leading-slash virtual form rejection, default-off back-compat, and the
no-active-namespace no-op. The previous
`rooted_leadingSlashWithNamespace` assertion encoded the vulnerable
behavior and now asserts the refusal.
- Full `agentscope-harness` suite: `Tests run: 1062, Failures: 0,
Errors: 0, Skipped: 14`.
- `mvn spotless:check` passes.

---------

Co-authored-by: ”zhuzhiyu.zzy“ <[email protected]>
Fixes #3280

## AgentScope-Java Version

2.0.4-SNAPSHOT (contribution based on `main` at `fefc196`)

## Description

Fixes a race in which concurrent `WorkspaceMessageBus.queueDrain` calls
can both return the same entry. It also prevents drainers from seeing a
queue entry before its payload write has completed.

### Before

```text
Producer:   write E.json --------------------------------> complete
Drainer A:  list E -> read E ---------------------------> return E -> delete E
Drainer B:        list E -> read E -> return E -> delete E
```

### After

```text
Producer:   write E.payload -> finish -> publish E.ready

Drainer A:  list E.ready -> create E.ready.claim (atomic) -> winner
Drainer B:  list E.ready -> create E.ready.claim (atomic) -> conflict/skip

Winner:     read payload -> delete ready + payload -> delete claim
```

### Implementation

- Write queue payloads to `{entryId}.payload`; publish `{entryId}.ready`
only after the payload write succeeds.
- Preserve draining of legacy `{entryId}.json` entries.
- Acquire an atomic create-if-absent claim before reading an entry.
- Release a claim after a read failure so a later drain can retry.
- Retain a claim when entry deletion fails, avoiding another delivery
when the first result may already have been returned.
- Surface unexpected claim-storage failures instead of treating them as
an empty queue; preserve entries already drained before a later claim
failure.
- Centralize already-exists results in `WriteResult`, so routed
filesystem paths do not make a normal claim conflict look like a storage
failure.
- Keep `MemoryStoreFilesystem` explicitly non-atomic and unsuitable as a
queue backend; its change only adopts the shared already-exists result
factory.

The queue claim contract depends on the selected filesystem backend
providing atomic create-if-absent writes. This change does not add
leases, automatic recovery, or an acknowledgment/retry protocol.

### Compatibility and behavior boundaries

- New entries use `.payload` and `.ready`; older consumers that only
scan `.json` will not see entries published by this version.
- The new implementation can still drain legacy `.json` entries.
Mixed-version consumers must not concurrently drain the same queue
because older consumers do not understand the new format or claim
markers.
- Claims are not leased. A process crash after claiming can leave an
entry unavailable until operator-led recovery.
- `queueDrain` remains destructive; this does not provide end-to-end
exactly-once processing.
- The API/class Javadocs were updated. No separate documentation page
was changed because the existing distributed-storage guidance remains
applicable.

### Tests

- `WorkspaceMessageBusTest` (27 tests): concurrent drains for new and
legacy entries, publish/read interleaving, legacy draining, missing
payloads, claim-storage failures, partial results, and routed claim
conflicts.
- `BaseSandboxFilesystemTest` (28 tests): exclusive claims,
existing-path conflicts, error classification and diagnostics, cleanup
failures, and placeholder upload behavior.
-
`DockerSandboxFileTransferIntegrationTest.filesystemWriteUploadsOverExclusivePlaceholder`
verifies the real Docker-backed placeholder/upload behavior.
- `ManagedMemoryAccessTest` (2 tests) covers the MemoryStore-related
change.

### Verification

- `mvn -ntp -pl agentscope-harness,agentscope-service/service-dataplane
spotless:apply` — passed; no files needed formatting.
- `mvn -ntp -pl agentscope-harness,agentscope-service/service-dataplane
spotless:check` — passed.
- `WorkspaceMessageBusTest`: 27 tests, 0 failures, 0 skipped.
- `BaseSandboxFilesystemTest`: 28 tests, 0 failures; 5 skipped by macOS
platform conditions.
- `ManagedMemoryAccessTest`: 2 tests, 0 failures, 0 skipped.
- Docker integration test: 10 tests, 0 failures, 0 skipped.

### Checklist

- [x] Code has been formatted with `mvn spotless:apply`
- [ ] All tests are passing (`mvn test`)
- [x] Javadoc comments are complete and follow project conventions
- [x] Related documentation has been updated (API/class Javadocs)
- [x] Code is ready for review

---------

Co-authored-by: ”zhuzhiyu.zzy“ <[email protected]>
## AgentScope-Java Version

2.0.4-SNAPSHOT (main @ 9c8b10d)

## Description

Fixes #2475.

**Problem.** With an `AgentStateStore` configured, `saveStateToSession`
recovered `(userId, sessionId)` by splitting the slot key `(userId or
"__anon__") + "/" + sessionId` at its last `/`, while loads used the
caller's real pair. For a sessionId containing `/` (e.g. a Base64
DingTalk `openConversationId`), saves and loads therefore addressed
different pairs:
- A trailing `/` split into a blank sessionId, so the save failed
(`sessionId must not be blank`).
- On stores that key user and session separately (InMemory, JsonFile,
JDBC/MySQL/PostgreSQL, Mongo), each call started from an empty history,
`getAgentState(uid, sid)` returned a fresh state, and state was written
under made-up user ids such as `u1/cid...`, which also polluted per-user
queries like `listSessionIds`. On versioning stores, every save from the
second turn on also hit a spurious CAS conflict (the default OVERWRITE
logs a warning; `FAIL` throws).
- Redis/OSS/COS join user and session with `/`, so both pairs mapped to
the same storage key and the history loss was masked there.

**Fix.** `CallExecution` now carries the resolved `(userId, sessionId)`
as final fields and derives `slotKey` from them. `saveStateToSession`
passes that pair to the store. Every per-call save goes through this one
method: normal completion, both structured-output paths, the failure
path, user interrupt, and `streamEvents`. `SlotRef` and the unused 3-arg
constructor are removed. The slot-key format is unchanged; it stays an
opaque cache/serialization key.

Identities without `/` still land on the same rows: saves now pass the
caller's raw userId, so a blank or literal `"__anon__"` userId is no
longer rewritten to `null`, and every in-repo store maps null, blank and
`"__anon__"` to the same bucket.

**Tests** (`ReActAgentPerSessionStateTest`):
- Parameterized over `("u1", base64 id)`, `("u1", "tenant/chat/42")`,
`("u1", "conv/")`, `(null, base64 id)`: state is readable under the
caller's pair, and `agent_state` is written under exactly that pair.
- Two turns on one session: no CAS conflict, and a rebuilt agent replays
both turns.

Without the fix, the new cases fail (4 failures, 1 error).

**How to test:** `mvn -pl agentscope-core verify`

**Out of scope (happy to follow up separately):**
- The slot key is still not injective: `("u1/a", "b")` and `("u1",
"a/b")` share a key. This needs a userId containing `/`.
- Rows written under corrupted pairs before this fix stay orphaned on
the stores that key user and session separately (plus the JPA store in
agentscope-service). This may be worth a release note.

Credit: same approach as #2476 by @waterWang; the regression-test idea
comes from @gxgeek-n.

## Checklist

- [x] Code has been formatted with `mvn spotless:apply`
- [x] All tests are passing: agentscope-core `verify` (2491 tests) and
agentscope-harness (1057 tests) locally; full repo left to CI
- [x] Javadoc comments are complete and follow project conventions
- [ ] Related documentation has been updated (N/A, no public API change)
- [x] Code is ready for review

---------

Co-authored-by: ”zhuzhiyu.zzy“ <[email protected]>
…ancelled (#3888)

## Problem

`SessionRecorder.flush()` schedules storage work like this:

```java
public Mono<Void> flush() {
    return Mono.<Void>fromRunnable(this::flushNow).subscribeOn(Schedulers.boundedElastic());
}
```

`flushNow()` calls `log.renew(writer, LEASE)` and then
`log.commit(...)`. Reactor's `boundedElastic` runs the task on a
`ScheduledThreadPoolExecutor`, and disposing the subscription **cancels
the task with interruption**. A caller that cancels a flush — a request
whose subscriber goes away, a `Mono.using` cleanup, a timeout —
therefore interrupts the thread while it is inside `renew` or `commit`.

That is worse than a lost write: the durable outcome becomes *unknown*.
A commit that was interrupted halfway may or may not have been applied,
and automatically retrying a partially applied commit is not safe.

`finish()` had the same shape for `close()` (`.then(...)` plus the
`onErrorResume` path), so a cancellation could also interrupt
`log.release(writer)`.

## Change

Storage work is now submitted so that **only the signal can be
cancelled**: the runnable runs to completion on the elastic pool, and
the returned `Mono` still reports completion, failure or cancellation to
its subscriber as before.

```java
private static Mono<Void> uninterruptible(Runnable work) {
    return Mono.<Void>create(
            sink -> Schedulers.boundedElastic().schedule(() -> {
                try {
                    work.run();
                    sink.success();
                } catch (Throwable error) {
                    sink.error(error);
                }
            }));
}
```

`flush()` and both `close()` call sites in `finish()` use it. No
signature, sequencing or error-propagation change beyond "cancelling no
longer aborts an in-flight write".

I deliberately did **not** touch the second problem in the report (a
cancelled initialization can leave the recorder's writer lease held).
That is a lifecycle question about when `close()` is guaranteed to run,
and it deserves its own change rather than being folded in here.

## Regression


`SessionRecorderFlushCancellationTest.disposingFlushDoesNotInterruptJournalIo`
wraps the journal in a spy whose `renew` blocks on a latch, queues one
event, subscribes to `flush()`, disposes the subscription while the
journal call is in flight, and then asserts:

- the thread executing journal I/O was **not** interrupted;
- the queued event still reached the journal.

Before the change it fails with:

```
disposing flush interrupted the thread executing journal I/O ==> expected: <false> but was: <true>
```

## Verification

- `mvn -B -pl agentscope-core -Dtest='io.agentscope.core.session.*Test'
test`: 23 tests, 0 failures.
- `mvn -B -pl agentscope-core test`: 2959 tests, 0 failures, 0 errors
other than the two pre-existing `DangerousPathBypassTest` Windows
symlink errors, which also fail on unmodified `main`.
- `mvn -B -pl agentscope-core spotless:check`: BUILD SUCCESS.

Addresses the first problem in #3815.

### Maintainer integration validation

Merged `main` at `9d4f86426470f06a5b15e0788efd4bad5eab6253` into this
original PR branch. Resolved the add/add test conflict with #4046 by
retaining its `SessionRecorderCancellationTest` and naming this PR's
original regression `SessionRecorderFlushCancellationTest`; no
production behavior was added beyond the original cancellation-safe
storage change.

On integration commit `b82ed745f75be301a732853dc09df15c56e08d6f`, `mvn
-B -T1C -pl agentscope-core -am test spotless:check` passed locally on
JDK 21 (source release 17): 3250 tests, 0 failures/errors, 11 skipped.
Skips are 3 Windows-only tests, 1 opt-in structured-output race test,
and 7 pre-existing disabled stream-contract tests. Both cancellation
suites ran (11 checkpoint cases and 1 flush-cancellation case), as did
the 4 native tool cancellation cases. Full repository verification and
Windows execution are left to the new CI run.

Co-authored-by: juruoO-o <[email protected]>
Fixes #4080

## Summary

This fixes two E2B sandbox defects on `main`:

1. `E2bSandboxClient` ignored `WorkspaceSpec.root`, so
`E2bSandbox.doExec` ran with the options default root (`/home/user`)
instead of the configured workspace root. `resume()` also kept the stale
persisted root, and volume coverage was computed from the wrong root.
2. `E2bSandboxClient` did not override the two-argument
`deserializeState`, so a deserialized `RemoteSandboxSnapshot` kept
`client == null` and failed with `RemoteSnapshotClient is not bound to
snapshot id: ...`.

Co-authored-by: jujn <[email protected]>
…, groups and skills (#3500)

Resolves #3298 #1963 #3443 #2247

## Summary

Multi-tenant agents currently expose the same tool/skill inventory to
every user. This PR introduces a server-side **capability surface**: an
immutable, per-call grant enumeration resolved from the caller identity
and enforced at both what the model *sees* (schema/prompt trimming) and
what it can *execute* (hard gates) — without mutating the shared
toolkit.

```java
/**
 * Example resolver: computes the granted skill / tool capability list
 * dynamically, based on the current logged-in user's role.
 */
public class RoleBasedCapabilityResolver implements CapabilityResolver {

    @OverRide
    public CapabilitySurface resolve(RuntimeContext ctx, Agent agent) {
        // Read the caller's userId from the framework's ctx (RuntimeContext)
        String userId = ctx.getUserId();

        // The project team loads the skill/tool capability list for the user's
        // role based on userId — e.g. from its own permission system / RBAC
        // service (fixed values below stand in for the lookup result)
        // Grants grants = permissionService.findGrantsByUserId(userId);

        // Wrap the list as CapabilitySurface(allowedSkills, allowedToolGroups, allowedTools)
        return new CapabilitySurface(
                Set.of("pdf_export"),     // allowed skill name (one entry covers every source copy)
                Set.of("search"),         // allowed ToolGroup
                Set.of("web_read"));      // allowed individual tool name
    }
}

// ===== Assembling the agent: new the resolver separately, then pass it as an object =====
CapabilityResolver resolver = new RoleBasedCapabilityResolver();

ReActAgent agent = ReActAgent.builder()
        .capabilityResolver(resolver)
        // ... other configuration (model, tools, skills, etc.)
        .build();

// resolver returning null → unrestricted (same as not configured); throwing → the call aborts
```

Harness agents configure the same resolver via
`HarnessAgent.builder().capabilityResolver(...)` — resolved before the
sandbox acquire and skill pre-staging, so staged skill files, the prompt
catalog and every gate observe the same surface.

## Relation to existing layers

The grant layer composes with the existing mechanisms rather than
paralleling them. One line: a capability actually executes only if it
passes, in order — **configuration intent (SkillFilter) → user grant
(this PR) → current activation → per-call Permission approval**. Each
layer answers exactly one question; they intersect, they never overlap.

- **SkillFilter / dynamic visibility** (`skillFilter(...)`, rc overlay,
`filterVisible`) — configuration intent: what the agent is designed to
show; runtime overlays may widen or tighten (canary, temporary toggles).
Grant runs after it: effective skills = SkillFilter ∩ grant, and
overlays cannot raise the grant surface. Grant is deliberately not
folded into SkillFilter: authorization may only narrow, while
SkillFilter's overlay algebra is intentionally bidirectional (widening
is a legitimate canary use) — anything runtime code can raise is not an
authorization boundary.
- **Activation** (`activatedGroups`) — a session-level switch over
already-granted capabilities; stacks independently with grant.
- **Permission** — execution-time approval (ALLOW / DENY / ASK) within
the granted set; grant trims up-front, Permission decides the individual
call.

Full layer table (incl. external tools):
`docs/v2/en/docs/building-blocks/capability-grant.md` (EN/ZH aligned).

## API compatibility

**No existing public API is narrowed or removed.** The pre-existing
`Toolkit.getToolSchemas(Collection<String>, ToolRequestConfig)` keeps
its public visibility and behavior (untrimmed compose, equivalent to the
new 3-arg overload with a `null` surface); its javadoc now recommends
the 3-arg overload (`getToolSchemas(activeGroups, requestConfig,
surface)`, surface read from the rc via
`rc.get(CapabilitySurface.class)`) for model-facing synthesis inside an
agent call.

One new combination is rejected at build time: `capabilityResolver(...)`
together with the static skill path (`skillBox(...)` or
`dynamicSkillsEnabled(false)`) throws `IllegalStateException` — the
static path has no per-call skill-visibility filtering, and an
authorization setting must never silently degrade to an untrimmed agent.
Both APIs are new in this PR, so no existing build can break.

## How it works

The grant layer is a funnel with a single decision source
(`CapabilitySurface` query methods); gates never re-derive authorization
logic.

1. **Declaration** — `CapabilityResolver` (functional interface)
computes pure whitelists from `RuntimeContext` (userId), optionally per
agent. Resolved once at `call()` entry and carried on the rc for the
whole chain; sub-agents inherit the parent surface without re-resolving
(derived rc — no parent pollution). Concurrent calls with different
users never cross surfaces.
2. **Tri-state surface** — three dimensions (skills / tool groups /
per-name tools). All-null = unrestricted; any dimension set (even to an
empty set) turns the surface into a complete enumeration; default deny.
3. **Read points** (model-visible):
- `Toolkit.getToolSchemas(groups, requestConfig, surface)` —
grant-filtered compose in a single pass; trimmed backend tools are
treated as non-existent; external (request-config) tools stay
caller-controlled; the `reset_equipped_tools` enum *and* description are
rebuilt from activatable groups only, so cut-off group names and
descriptions do not leak.
- `DynamicSkillMiddleware` filters visible skills fail-closed (empty set
on missing surface or filter error); the filtered list drives signature,
box cache, prompt and loading alike.
4. **Hard gates** (execution, orthogonal to activation checks):
   - tools: `ToolExecutor.requireToolGranted` (backend only)
- skill loading: `SkillToolFactory` convergence point
(`allowsSkill(AgentSkill)` — full decision incl. system bypass; the
id-based overload remains the grant-set-only fallback)
   - group activation: `resetEquippedToolsImpl`
5. **System capabilities** — `isSystem()` marking chain (`@Tool`
annotation → `ToolBase` / `ToolGroup` / `SkillToolGroup` / `AgentSkill`
builders, with copy/toBuilder retention) bypasses grant trimming;
framework meta tools are marked; every `system=true` registration leaves
an INFO audit trail.
6. **Missing surface = unrestricted** — direct executions that never
entered an agent `call()` are trusted assembler code (the agent funnel
always writes a surface); the same stance applies at read points and
gates.
7. **Harness agents** — `HarnessAgent.builder().capabilityResolver(...)`
resolves at the harness call/stream entry, before the sandbox acquire
and marketplace pre-staging: only granted skill files are materialised
into `.skills-cache`, and the harness skill chain
(`HarnessSkillMiddleware` prompt/catalog, `load_skill_through_path`,
staging) observes the same surface; harness sub-agents reuse the
inherited surface without re-resolving.

## Security properties

- All model-facing denials are **byte-identical to not-found wording**
(tools, skills, groups) — the model channel cannot distinguish "exists
but ungranted" from "missing", and cannot relay "no permission" to the
end user. The truthful cause is logged with userId/sessionId/agentId at
each gate.
- The tool grant gate runs before the activation gate, so ungranted
probes never reach activation wording; the activation message only
speaks for granted-but-inactive tools (the designed self-healing path).

## Known residual exposure

- Management/observation planes (aistio adapter, example REST
controllers) intentionally export the full inventory —
registration-time, not per-user.
- The static `skillBox()` path cannot be combined with a resolver (the
build fails explicitly, see above); it has no per-call prompt trimming
at all. Multi-tenant setups should use `skillRepositories(...)`.
- The per-call `generate_response` structured-output tool executes
outside the executor (system-equivalent response mechanism).
…4088)

## Background

Second change of the three measured in #3929: *"Replace the
interruption-check `concatMap` with a synchronous check
(`handle`/`map`)"*. It was measured at −5.1 s mean chain time against
2.0.4, and it is one of the two we deliberately left out of #3961 so
each one stays individually verifiable.

`checkInterrupted()` was only

```java
return Mono.defer(() -> interruption.isInterrupted()
        ? Mono.error(new InterruptedException("Agent execution interrupted"))
        : Mono.empty());
```

— a field read wearing a `Mono` — and both streamed stages fed every
chunk through `concatMap(chunk ->
checkInterrupted().thenReturn(chunk))`. So a chunk crossed an
asynchronous boundary to reach a field access.

## Change

`CallExecution.untilInterrupted(Flux<T>)`, used by the reasoning stream
and the summary stream:

```java
private <T> Flux<T> untilInterrupted(Flux<T> upstream) {
    return upstream.handle((item, sink) -> {
        if (interruption.isInterrupted()) {
            sink.error(new InterruptedException("Agent execution interrupted"));
            return;
        }
        sink.next(item);
    });
}
```

Same flag, same error, same sequential processing — `handle` processes
one element at a time, so ordering and backpressure are untouched. The
per-chunk `Mono` allocation, its subscription and the handoff around it
are gone. `checkInterrupted()` itself stays, and the per-step call sites
are unchanged.

Refs #3929
## Description

`RedisSnapshotSpec` / `RedisRemoteSnapshotClient` only accepted a Jedis
`UnifiedJedis`
client, although the module already ships a Lettuce dependency (used by
`LettuceClientAdapter` for state storage). Applications that standardize
on Lettuce had
to keep a second Redis client around just for sandbox snapshots.

This PR adds a Lettuce implementation of the same snapshot/spec
contract:

- New `LettuceRemoteSnapshotClient` — a `RemoteSnapshotClient` backed by
Redis binary
  values through Lettuce. It accepts `RedisCommands<byte[], byte[]>`
(standalone/Sentinel) or `RedisAdvancedClusterCommands<byte[], byte[]>`
(cluster),
mirroring the client types already supported by `LettuceClientAdapter`.
- `RedisSnapshotSpec` gains two overloaded constructors taking those
Lettuce sync
command APIs. The existing Jedis constructor and
`RedisRemoteSnapshotClient` are
  untouched.

The observable behavior matches the Jedis implementation exactly: key
layout
`<prefix><snapshotId>.tar`, default prefix
`agentscope:sandbox:snapshots:`, prefix
normalization (trailing `:` appended when missing), TTL semantics (null
or <= 0 means no
TTL), `FileNotFoundException` on missing snapshot download, and the
blank-snapshotId
guard.

Fixes #1596
#4149)

## Summary

Scanned the last 5 pages of PRs (#3941–#4147, 125 PRs): 14 had red CI,
and 9 of those failed on exactly one OS while the other OS stayed green
on the same commit — the classic `-T1C` parallel-build starvation
signature (the both-OS failures were compile/spotless issues and are out
of scope). This PR fixes every distinct flaky test class found that way,
plus two narrowly-scoped hardenings the fixes depend on.

| Test / class | Failed OS | Victim PRs | Evidence | Fix |
|---|---|---|---|---|
| `AguiMvcControllerTest#eventStreamSignals…` | ubuntu ×2 | #4112, #4143
| 5s latch deadline hit while sibling tests in the class ran 5–9s under
the same load | shared 30s await constant (all waits in the class share
the same executor starvation exposure) |
| `SubagentRunIdChainTest` (both methods) | windows ×3 | #4091, #4025,
#4142 | blocking read starved just past 10s (10.04–10.84s elapsed); same
test 0.414s on ubuntu | block budget 10s → 30s |
| `InboxMiddlewareTest#notificationReaches…` | ubuntu ×2 | #3991, #4093
| assertion matched the memory-consolidation prompt instead of the
reasoning request | `MockModel` recordings made thread-safe (see below)
|
| `GatewayEventsWebSocketTest#sameOrigin…` | windows ×2 | #4072, #4094 |
~0.1s clean close with no frames; job log shows the preceding 403'd
upstream upgrade left a dying pooled socket (`Connection prematurely
closed BEFORE opening handshake is complete`) that the next proxied
socket reused | stand-in control plane now answers rejected upgrades
with `Connection: close` so the gateway pool discards the socket |
| `TurnLeaseServiceTest#heartbeatErrors…` | windows | #4075 |
`await(70ms) isFalse` anchored to when the starved test thread resumes,
not to lease acquisition | bounds re-anchored to
elapsed-time-since-acquisition (fires within 2s, not before 120ms;
deadline 150ms, ticks 50ms) |
| `SandboxConnectorRedirectTest#commandWaits…` | windows | #4058 |
capability probe inherited the 200ms command-transport budget and died
at 199ms before any command was submitted | probe budget floor (see
CommandExecutor below) |
| `GracefulShutdownManager` singleton leak | local | found during
verification | `resetForTesting()` reset every field except `config`, so
a `PT0.1S` config leaked across tests and failed `defaultConfig`
whenever filesystem class order placed it after `shutdownTimeoutSignal`
| reset now also restores `GracefulShutdownConfig.DEFAULT` |

## Shared test-util fix

`MockModel` recorded calls from whichever thread drives the agent — the
turn thread and background memory maintenance — into a plain `ArrayList`
plus unsynchronized `int`/`last*` fields. Two concurrent adds race the
`elementData[size] / size++` update and can silently drop an entry; that
is exactly the #4093/#3991 signature (the reasoning request vanished,
only the post-call consolidation request survived). Recordings are now a
`CopyOnWriteArrayList` with `AtomicInteger`/`volatile` siblings —
order-preserving, atomic per add, stable to iterate while a call is in
flight. Complements the iteration fix proposed in #4133.

## Non-test changes (called out explicitly)

- **`CommandExecutor`** — the `/capabilities` pre-flight probe now uses
`max(configured per-attempt, 2s)` for its budgets. Strictly a widening:
identical for default (60s) and ≥2s configurations; only sub-2s configs
change, and only for the probe — command exchanges keep the configured
budget. Side benefit: the old code passed the same 200ms as the shared
exchange deadline, which made the intended `CAPABILITY_MAX_ATTEMPTS = 3`
retry dead code; the floor lets the retry actually run. The test-only
alternative (raising the test's 200ms config and the server delays to
match) would add ~1.5–2s of real test wall time, so the 2-line
production fix is the smaller change.
- **`GracefulShutdownManager.resetForTesting`** — one added line
restoring `config` to default, inside a method documented "Intended for
testing and demo purposes only" (no production callers; production code
never calls `setConfig`).

## Constraint compliance

- **No happy-path slowdown:** every widened number is a failure-path
deadline only; all awaits/latches return the moment the signal arrives,
and no sleeps were added (`TurnLeaseServiceTest` actually drops a forced
70ms wait).
- **Minimal widenings, anchored to measurements:** 5s→30s (deadline hit
twice; repo precedent from #3726 for CI-starvation waits), 10s→30s (3×
the observed 10.04–10.84s), probe floor 2s (10× the 199ms miss),
TurnLease window [120ms, 2s] (bug population ~50ms vs legitimate
≥150ms).

## Test plan

- [x] Full reactor `mvn -B -T2C clean verify` green locally (4m38s wall
clock; all seven fixed areas' suites green)
- [x] `JsonFileAgentStateStoreTest` (8 symlink cases) excluded locally
only — pre-existing Windows-symlink-privilege limitation, reproduced
identically on a pristine `main` baseline, unrelated to this diff
- [ ] CI on both OSes

Follow-up noted during review: the production control-plane hub behind
`/api/v1/events` lives outside this repo; if it also answers rejected
upgrades with a keep-alive 403 and closes, the gateway can still poison
a subsequent proxied socket in production — worth checking against the
real hub separately.
…irmation (#4143)

## Description

Closes #4113.

**Background.** When a `ReActAgent` behind `AgentScopeA2aServer` stops
to ask the user to confirm a tool call
(`GenerateReason.PERMISSION_ASKING`), the executor still finished the
task: a streaming request ended as `completed`, a blocking request
returned a plain message. The client could not tell that the agent was
waiting, and there was no way to continue the run.
Cancelling a queued subscription to a reused Gateway publisher could
close the lease of a different, still-active turn. Keep each acquired
lease and its cleanup inside that subscription's `defer` boundary for
both `run` and `runStream`; defer the agent supplier too so synchronous
failures still release the lease.

Fixes #3549. Independent of #3533: no changes to `LocalSessionTurnGate`.

Verification: both public Gateway cancellation controls fail on current
main and #3533, then pass with this change. Ten focused cases cover
queued cancellation and
completion/error/supplier-failure/active-cancellation paths for Mono and
Flux. `mvn -T1 -pl
agentscope-harness,agentscope-extensions/agentscope-extensions-controlplane
-am clean verify` passes: 4,401 tests, zero failures/errors, 27 skips
across seven modules, including formatting. This is scoped local
verification with a fake agent and real local gate, not the full
repository or a live deployment.
fengyue-xve and others added 11 commits November 12, 2026 22:24
The default JacksonJsonCodec accepts the first root JSON value and
ignores remaining input. Consequently JsonUtils.isValidJsonObject
accepts raw tool-call arguments such as `{"x":1} garbage` or `{"x":1}
{}`, and resolveToolCallArgsJson preserves malformed arguments instead
of falling back to the structured input. Providers can then reject the
tool history.

Use a per-call ObjectReader with FAIL_ON_TRAILING_TOKENS for both Class
and TypeReference deserialization. Valid trailing JSON whitespace
remains accepted. A custom ObjectMapper keeps its own configuration
unchanged.

Validation: native Maven regression on the original code
reports5failed/1passed. After the fix, native `agentscope-core -am`
tests for JacksonJsonCodecTrailingContentTest, JacksonJsonCodecTest and
JsonUtilsTest pass:44tests,0failures,0skips. Cases cover trailing
garbage, a second object, null/number roots after an object, both
overloads, actual tool-argument fallback, whitespace and custom mapper
configuration. Project Spotless and diff checks pass. Matching
English/Chinese tool docs updated. Full repository verification was not
run.


CI follow-up: Windows failed in unchanged
`channel-common/BotLoopGuardTest.activePeersSurviveEvictionOfIdleOnes`
(`expected 1 but was 0`), [job
log](https://github.com/agentscope-ai/agentscope-java/actions/runs/39552196458/job/119063683279).
Its900ms sleep can overshoot the1000ms idle/sweep threshold, so
`allow(active-peer)` automatically evicts the idle peer before the later
explicit sweep. A standalone run against the unchanged baseline source
with a1100ms first sleep reproduces removed=0 while the active peer
remains and trackedPeers=1. The JSON module tests pass locally. A rerun
attempt currently returns `job cannot be rerun`; the Ubuntu job is still
running. This failure is recorded explicitly pending a rerun rather than
modifying unrelated channel logic in this PR.

---------

Signed-off-by: fengyue-xve <[email protected]>
Co-authored-by: fengyue-xve <[email protected]>
## 问题

Fixes #3621.

基于 main `8cc6795b076d49c49bd9b617038dd4c58e22671c`(2.1.0-SNAPSHOT)。

权限门将工具标记为 ASKING 并记录确认 replyId 后,当前实现立即向订阅者发布
`RequireUserConfirmEvent`,状态保存却在调用尾部执行。原生日志中的 `interaction/requested`
也可能仍在 recorder 缓冲区。提示已可见而暂停状态尚不可恢复,会留下崩溃恢复窗口。

## 修改

- 仅在 acting 的授权请求边界,先记录事件,再等待现有状态保存成功,最后向订阅者或父代理转发提示;保持停止事件的顺序。
- 原生 Session Log 在同一提交中写入待确认请求与状态检查点,不重复记录请求;旧状态存储复用现有 CAS
路径。保存失败时传播错误,不发布授权提示。
- 新增中途保存后,更新本次执行的 context 合并基线,并保留 APPEND_MERGE
已合并的历史,避免调用尾再次保存时重复追加或覆盖并发消息。
- 更新对应中英文权限文档。不增加公共 API、依赖或通用 mid-turn checkpoint 功能。

## 验证

使用确定性模型和本地存储替身,无真实模型或凭证。旧状态存储与原生日志均有覆盖:事件可见时恢复 ASKING 和
replyId、原生待确认请求恰好一次、保存门闩阻止提前发布、保存失败、父代理转发、call
路径,以及提示处取消后重建实例批准/拒绝。两个并发写入测试分别覆盖第一次保存和调用尾保存的 APPEND_MERGE 冲突。

- 修复前的两个顺序探针均失败;初始中途保存实现的两个并发合并测试也均失败(分别丢失并发输入、重复工具调用)。
- 最终新增 16 个参数化测试实例与原有 19 个 HITL 测试,35 个全部通过。
- 完整 core 套件:2758 个测试,0 失败、0 错误,9 个条件跳过。
- 本地 JaCoCo 检查:ReActAgent.java 新增的 16 个可执行行均有覆盖,无未覆盖分支。最终覆盖率以 CI 报告为准。
- 文档 `npm test`:13 个通过;`npm run validate`、`npm run broken-links` 通过。

执行命令(从仓库根目录,Maven 使用临时 Maven Central 镜像设置):

```sh
mvn -T1C -pl agentscope-core -am -Dtest=ReActAgentPermissionPersistenceTest,ReActAgentHitlTest -Dsurefire.failIfNoSpecifiedTests=false test
mvn -B -T1C clean verify
```

最终版本的全仓 `clean verify` 通过(99 个模块,4 分 45 秒)。首轮构建曾在未改动的 Service
`ToolConfirmationCoordinatorTest.managedTimeoutWaitsForControlPlaneCancelledDecision`
上出现 `RESOLVED` / `OWNER_UNAVAILABLE` 不一致;该测试类在未修改主线快照中单独运行 10
个通过,最终全仓重跑中 Service 的 135 个测试也通过(2 个条件跳过)。未为此修改 Service 或弱化断言。

## 范围与限制

测试验证持久化 ACK 与事件可见性的顺序,以及实例重建后的恢复;未进行实际进程崩溃、跨节点数据库或 SSE
端到端测试。跨进程恢复仍要求持久化后端。保存成功后断连可能留下已持久化但未展示的请求,不保证提示恰好一次送达,也不改变原生 writer
租约和取消清理机制。

不处理 #3619、外部执行暂停、所有类型的暂停事件或 Service 授权协调协议。

## Checklist

- [x] 最小生产改动及回归测试
- [x] Spotless 与差异空白检查
- [x] 对应 EN/ZH 文档
- [x] 完整构建结果与首轮失败情况已记录
## What
Agentscope Service External 应用在约一分钟后由 ready 变成 unavailable;不启用 gRPC
时,ControlPlane 无法与其消息对话,提示 `asdp: instance not connected`。

## Why
实例心跳健康检查失败后没有重新注册到 ControlPlane,状态停留在失败态,后续请求被拒。

## Fix
心跳失败时触发实例重新注册(re-register),恢复其在 ControlPlane 的可用状态,使非 gRPC 通道的消息对话恢复正常。

Fixes #3703

Co-authored-by: xzxiaoshan <[email protected]>
…) (#3832)

Fixes #3771

## Root cause

Under `BUILDER_AGENT_API_LEGACY_HISTORY=true` (AgentStateStore slots, no
SessionLog), the `RuntimeContext` can carry a `SessionExecution`
**without** a `SessionRecorder`. Three sites dereferenced the recorder
unconditionally:

1. `SessionExecution.beforeStep(recorder, state)` —
`recorder.acceptedMessageIds()` → the reported NPE. Note the stack
attribution: the trace middleware's `doOnError` *logs* it under its name
(`[opencode-coding-p]`), but the throw site is in core.
2. `settleSession` →
`execution.continueOrClose(SessionRecorder.from(rc))`.
3. `closeFailedSessionExecution` → `recorder.close()` — an NPE inside
the error-cleanup path itself.

## Fix

Null-guards at all three sites: when the recorder is absent, the journal
bookkeeping is skipped (legacy mode has no journal to maintain) —
matching the existing discipline at `releaseCallExecution` (`if
(recorder == null) return Mono.empty()`). Legacy turns execute and write
state snapshots normally.

## Verification

The exact repro (legacy mode, first and subsequent turns) requires the
service dataplane + Redis compose stack; the guard shape mirrors
already-proven null-checks in the same file's lifecycle methods. A
unit-level repro of the beforeStep path with a null recorder is
straightforward if maintainers want it — happy to add on request.
…d leak) (#3833)

Fixes #3714

## Root cause (code-level confirmation from my earlier analysis on the
issue)

Without an injected `webHttpClient`, every `HarnessAgent.build()`
allocated **two fresh `java.net.http.HttpClient` instances** (one per
web tool). On Java 17-20 those clients have no `close()` (added in 21),
so each retains its selector/executor threads as long as the tool
objects stay reachable from the toolkit. Repeated builds — per-session
agent factories, config reloads, multi-instance deployments — accumulate
clients linearly, matching the MAT dominator picture and the
web_fetch/web_search observation from @chenxb-888.

## Fix

The no-arg constructors now share one process-wide
`SHARED_DEFAULT_CLIENT`: repeated builds become idempotent (zero
additional clients), and the shared client's lifecycle intentionally
matches the process — a singleton client is the JDK-documented usage
pattern and `HttpClient` is thread-safe. Caller-supplied clients via
`webHttpClient(...)` / the explicit constructors are untouched: their
lifecycle remains the caller's.

## Note

@joman-jiang's `GracefulShutdownManager` map hypothesis may be a
separate retention node — this PR closes the confirmed per-build client
accumulation; if the MAT report still shows growth after this, that map
deserves its own investigation.
…drain (#3840)

## AgentScope-Java Version

2.1.0-SNAPSHOT (`main` at 4b6c59a)

## Description

Fixes #3836.

`SessionRecorder.exportCommitted()` returned immediately when another
drain was already running (`exporting.compareAndSet(false, true)`
failed), without remembering that a new drain was needed. An event
committed during that drain therefore had no follow-up trigger. Once
`close()` disposed the heartbeat, the final `message/assistant`,
`turn/output` and `run/end` records stayed in the `SessionLog` but were
only accepted by the retry path — or not at all if the process exited
first.

The recorder now records the request (`exportRequested`) and the running
drain keeps draining until no request is left, re-scheduling itself if a
request arrives between the loop exit and clearing `exporting`.

Files:

-
`agentscope-core/src/main/java/io/agentscope/core/session/SessionRecorder.java`
-
`agentscope-core/src/test/java/io/agentscope/core/session/SessionRecorderExportTest.java`
(new)

## How to test

```
mvn -pl :agentscope-core test -Dtest=SessionRecorderExportTest
```

Result: `Tests run: 1, Failures: 0, Errors: 0`.

The test follows the reproduction in the issue: a sink that blocks the
first `accept()`, an event committed while that drain is blocked,
`close()` to dispose the heartbeat, then release. It fails on `main`
(the second event is never accepted; `secondAccepted.await` times out)
and passes with the change.

## Checklist

- [x] Code has been formatted with `mvn spotless:apply`
- [ ] All tests are passing (`mvn test`) — the new test passes as shown
above; the full reactor suite was not run locally
- [x] Javadoc comments are complete and follow project conventions
- [x] Related documentation has been updated (e.g. links, examples,
etc.) — no documentation change needed
- [x] Code is ready for review

## AI assistance

Prepared with an AI coding agent (DeepSeek Harness / deepseek-flash) and
verified with the run above.

The whole io.agentscope.core.session test package also passes with the
change:`mvn -pl :agentscope-core test
-Dtest=io.agentscope.core.session.*Test` -> 23 tests, 0 failures.
## AgentScope-Java Version

2.1.0-SNAPSHOT, based on main
`c416c378e0b4c1f4849bf75d66084c00bff62cef`.

## Description

Fixes #3595.

When snapshot restoration opens an archive and `doSetupWorkspace()`
subsequently throws, `AbstractBaseSandbox.start()` currently never
closes that stream: setup runs before the try-with-resources block. This
affects both lost-workspace recovery and initial snapshot restoration.

Move setup inside the existing resource scope in both branches,
retaining setup-before-hydration ordering. Add parameterized regressions
through the public `start()` method for both branches, verifying stream
closure, unchanged failure state, no hydration after failed setup, and
preservation of the setup exception when closing also throws. Update the
matching English and Chinese sandbox docs.

### Validation

Latest test-only update: 31 focused tests pass (6 snapshot cleanup + 23
pending-tool recovery + 2 run-id chain). Local JaCoCo 0.8.14 records
both changed production lines 90 and 108 as covered (`mi=0, ci=2` each).
The original exception-only cases reached setup but left these
invocation lines unmarked; the successful restoration cases close that
coverage gap.

Initial CI: Ubuntu, license, docs and module sync passed. Windows failed
on three 10-second blocking timeouts in
`SubagentPendingToolRecoveryTest` and `SubagentRunIdChainTest`; the four
cleanup regressions passed there. The affected 25 subagent tests passed
in both local follow-up runs. The remote timeout root cause is not
established; the new commit starts fresh CI.

- Regression on original production code: 4 tests, 4 failures (archive
`close()` never called), 0 errors.
- With the fix: all 4 regression cases pass. The follow-up adds 2
successful-restore cases to assert setup -> hydration -> close ordering
and ready/running state; all 6 now pass.
- On the initial patch (48410b7), all 161 Harness `*Test.java` classes
selected explicitly: 1,249 tests, 0 failures/errors, 18 skipped (1,231
passed). The skips remain reported; this is not a full-repository test
run.
- Existing `E2bSandboxRecoveryTest`: 8 passed.
- Spotless and `git diff --check`: pass.
- Documentation link check reports 2,208 broken links in 326 files on
both original main docs and the patch; the reported entries match. No
links are added by this change.
- Documentation: 13 tests pass; `npm run validate` passes, including 430
pages / 584 redirects and Mint build validation.

Commands (PowerShell; Java 17, Maven 3.9.12):

```powershell
mvn -B -T1 -pl agentscope-harness -am '-Dtest=AbstractBaseSandboxSnapshotCleanupTest' '-Dsurefire.failIfNoSpecifiedTests=false' spotless:apply test
$classes = (Get-ChildItem agentscope-harness/src/test -Recurse -Filter '*Test.java' | ForEach-Object BaseName) -join ','
mvn -B -T1 -pl agentscope-harness -am "-Dtest=$classes" '-Dsurefire.failIfNoSpecifiedTests=false' test
mvn -B -T1 -pl agentscope-extensions/agentscope-extensions-sandbox/agentscope-extensions-sandbox-e2b -am '-Dtest=E2bSandboxRecoveryTest' '-Dsurefire.failIfNoSpecifiedTests=false' test
```

AI assistance (Codex) was used for source review, implementation, and
tests. Reproductions were executed locally and the final diff was
checked against the surrounding code and stream-ownership contract.

## Checklist

- [x] Code has been formatted with `mvn spotless:apply`
- [ ] All tests are passing (`mvn test`) — relevant module checks are
above; full repository and live-provider tests were not run
- [x] Javadoc comments are complete and follow project conventions (no
API changes)
- [x] Related documentation has been updated
- [x] Code is ready for review

---------

Co-authored-by: juruoO-o <[email protected]>
## AgentScope-Java Version

2.1.0-SNAPSHOT, based on main
`40a4a57ad79e82f8505572d3b195d0264ec7efcb`.

## Description

Fixes #3645.

The sandbox workspace paragraph and file-tool path normalizer used
`/workspace` even when the active sandbox used a different directory.
E2B also kept its execution root and workspace manifest root
independent, including the default `/home/user` versus `/workspace`
mismatch.

### Changes

- Resolve the sandbox root from the acquisition bound to the current
`RuntimeContext`, not a shared filesystem field. Use this for the
workspace paragraph and registered filesystem/artifact path
normalization. Restored state takes precedence over build-time defaults;
released acquisitions are rejected.
- Preserve nonmatching and relative paths for the existing filesystem
policy. Match prefix boundaries and handle trailing slashes and the
filesystem root.
- Align E2B's effective workspace specification and execution options.
Keep `/home/user` as the default; either root setter can configure the
directory. Copy the caller's specification so entries/environment
survive without mutating it.
- When constructing an E2B sandbox from older state, retain its saved
execution directory and align only the manifest. No files are moved, and
no lifecycle or snapshot algorithm is changed.
- Add regression tests and matching English/Chinese sandbox
documentation. Docker's default remains `/workspace`.

### Compatibility decision for review

As asked in the issue comment, this implementation rejects explicitly
conflicting `workspaceRoot(...)` and `workspaceSpec(...).root` values
when building the context, independent of setter order (trailing slashes
are ignored). This policy is **proposed for review, not yet
maintainer-approved**. Existing persisted E2B state is handled
differently: its saved execution root stays authoritative so resuming
does not relocate the workspace. Please confirm whether fail-fast is
preferred for new conflicting configurations.

### Validation

JDK 21, Java 17 compilation target, Maven 3.10.0. No real model or E2B
service was contacted.

Before the fix, three new offline assertions failed: the prompt
advertised `/workspace` for an active `/home/user` sandbox, and
default/custom E2B roots did not reach the workspace specification. The
two existing sandbox-prompt tests passed.

Final command from the repository root:

```shell
mvn -o -B -T1 -ntp \
  -pl agentscope-extensions/agentscope-extensions-sandbox/agentscope-extensions-sandbox-e2b -am \
  '-Dtest=SandboxWorkspaceRootTest,WorkspaceContextMiddleware*Test,HarnessAgentTest,*Sandbox*Test,FilesystemToolTest' \
  -Dsurefire.failIfNoSpecifiedTests=false spotless:apply test
```

- Harness: 224 tests, 0 failures/errors, 17 skipped.
- E2B: 57 tests, 0 failures/errors, 1 skipped.
- Total: 263 passed, 18 skipped. The selection includes existing sandbox
recovery, file-transfer and Harness tests; this is not a full-repository
result.
- Regression coverage includes default/custom roots, setter
order/conflicts, invalid roots, legacy-state resume, caller-owned
manifest preservation, per-call root isolation, the registered
`read_file` tool, prefix boundaries and released acquisitions.
- Spotless checks and `git diff --check` passed.
- In `docs/`: `npm test` passed 13 tests; `npm run check` passed for 430
pages/584 redirects; `npm run broken-links` reported no broken links.

Remaining validation gaps: full-repository offline `clean verify` could
not start because `maven-clean-plugin:3.5.0` was not cached. `npm run
validate` passed the local checker but the Mintlify build did not
complete (initial network-check exception, then a network-enabled retry
remained at `validating build` and was interrupted). No full-suite or
remote-sandbox success is claimed.

## Checklist

- [x] Code has been formatted with `mvn spotless:apply`
- [ ] All tests are passing (`mvn test`) — targeted results above; full
suite not completed
- [x] Javadoc comments are complete and follow project conventions
- [x] Related documentation has been updated
- [x] Code is ready for review, including the explicit
configuration-conflict policy question above

---------

Co-authored-by: juruoO-o <[email protected]>
## Description

Fixes #4098

`session_search` only caps the number of matches (#3270), not their
size. Each match embeds a whole stored message, so a handful of matches
can exceed the eviction threshold. Because `session_search` was in
`ToolResultEvictionConfig.DEFAULT_EXCLUDED_TOOLS`, such results were
never offloaded and could push the next model request over budget.

Changes:
- Remove `session_search` from
`ToolResultEvictionConfig.DEFAULT_EXCLUDED_TOOLS`. Results under the
threshold (80K chars by default) are unchanged; larger ones get the
usual head/tail preview and a `read_file` pointer. Long single-line
offload files are readable since #3821.
- Update the `SessionSearchTool` comment that relied on the exclusion.
- Update the default exclusion list in
`docs/v2/{en,zh}/docs/harness/context.md`.

The prune exclusion in `CompactionConfig.PruneConfig` is left unchanged:
once a large result is offloaded, only the preview stays inline.
@coderzhn
coderzhn merged commit 289b247 into coderzhn:main Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.