Skip to content

同步更新 - #3

Merged
coderzhn merged 53 commits into
coderzhn:mainfrom
agentscope-ai:main
Nov 24, 2026
Merged

coderzhn merged 53 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

dependabot Bot and others added 30 commits November 16, 2026 13:44
…ut cleanup (#4078)

## AgentScope-Java Version

2.1.0-SNAPSHOT (upstream `main` @ `a63c625`)

## Description

Fixes #4073.

### The bug

In the fallback structured-output path,
`compressStructuredOutputContext` removes a whole `Msg` whenever
`isStructuredOutputRelated(msg)` is true. That classifier returns true
if **any** `ToolUseBlock` in the message is `generate_response`.

So when a model returns a business tool call and the synthetic
`generate_response` call in the **same** assistant response:

- the whole assistant message is dropped — including the business
`ToolUseBlock`;
- the business `ToolResultBlock` lives in its own message and is not
classified as structured, so it stays;
- the `generate_response` result message is dropped as before.

The next model request then sees a `tool_result` without its `tool_use`.
Providers reject that, and the session state is corrupted. Explicit
`InMemoryAgentStateStore` reads show the same corruption. Returning the
two calls in separate rounds works; swapping their order in one batch
does not.

### The fix

`agentscope-core/.../ReActAgent.java` — for messages that **mix**
internal structured-output blocks with business tool blocks, rebuild the
message with **only** the `generate_response`
`ToolUseBlock`/`ToolResultBlock` removed, instead of deleting the whole
message. Everything else (text, thinking, business tool blocks) and the
message identity (`id` / `name` / `role` / `timestamp` / `metadata` /
`usage`) are preserved, so the business `tool_use`/`tool_result` pair
stays intact.

Pure structured-output messages (and synthetic reminder messages) keep
the existing whole-message removal, exactly as before.
`isStructuredOutputRelated` is deliberately left unchanged:
`collectAggregatedUsage` and `collectLastThinking` reuse it and run
before compression, so usage/thinking extraction is unaffected. Tool
dispatch, permissions and the native `response_format` fallback are
untouched — this only changes post-hoc context cleanup.

Two small helpers back this up:

- `stripStructuredOutputBlocks(Msg)` — returns `null` for pure/reminder
messages (caller drops them), otherwise the rebuilt message.
- `isStructuredOutputBlock(ContentBlock)` — matches `ToolUseBlock` /
`ToolResultBlock` named `generate_response`.

### Tests


`agentscope-core/src/test/java/io/agentscope/core/agent/StructuredMixedBatchAuditTest.java`
(new, no network / API key / real model):

- 6 parameterized scenarios from the issue (business-first /
structured-first / separate-rounds control × default state / explicit
`InMemoryAgentStateStore`). A fake `Model` rejects any orphan
`tool_result` on the next turn, so the fixture fails on exactly the
corrupted pairing rather than on an assertion about a private field. It
also asserts the structured result is returned and the business tool ran
once.
- 1 extra test guarding the rebuild: the kept business call is still an
`AssistantMessage` with the original id/name, its non-tool text
survives, and no `generate_response` `tool_use` survives cleanup.

Verified that the tests are genuine regressions: reverting only the
`ReActAgent.java` change makes 5 of the 7 fail (the 4 mixed-batch cases
and the identity test) while the 2 separate-rounds controls pass; with
the fix all 7 pass.

### Checks

- `mvn -B -T1C -pl agentscope-core -am test
-Dtest=StructuredMixedBatchAuditTest` → 7 tests, 0 failures, 0 errors.
- `mvn -B -T1C clean verify` → full 99-module reactor: `AgentScope Java
- Core` SUCCESS, `Harness` SUCCESS, spotless clean, all modules that ran
green except one pre-existing unrelated flake
(`AnthropicModelProviderTest.createWithAuthTokenOptionSendsBearerHeader`,
a 10s timeout against a local MockWebServer under parallel load). That
test passes 7/7 when run in isolation; the same test also fails on
unmodified `main` under the same parallel load, so it is not caused by
this change.
- `mvn -B -T1 clean verify` (sequential, no parallel-load contention) →
92 modules including Core, Harness and **Anthropic all SUCCESS**
(anthropic now passes, confirming the `-T1C` failure was a load-induced
timeout, not a real failure). The only failure is `agentscope-paw`'s
`npm install` (`EPERM: root-owned files in ~/.npm`), a local
frontend-tooling environment issue unrelated to Java or this change.
Upstream CI `build (ubuntu-latest)` and `build (windows-latest)` are
both green.
- `mvn -pl agentscope-core spotless:apply` applied; `spotless:check`
clean.

### Scope

- `agentscope-core` only; no public API, builder, serialized state,
event payload, or docs change (docs describe the cleanup contract, not
the internal message shape).
- No behavior change for pure structured-output messages, for
separate-round calls, or for the native structured-output path.

## 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 (N/A — internal cleanup
only, no user-visible API or documented behavior change)
- [x]  Code is ready for review

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

Fixes #4140.

Native thread journals configured through `RemoteFilesystemSpec` were
silently written to the local workspace.
`CompositeFilesystem.journalStorage()` looked up `agents/`, which cannot
match the more specific `agents/<agentId>/sessions/` route.

Add an optional explicit journal backend to `CompositeFilesystem` and
have `RemoteFilesystemSpec` pass its sessions backend. File routing and
the existing two-argument constructor retain their behavior. Journals
now use the remote sessions namespace and its configured isolation
scope. Existing local journals are not migrated automatically.

Rebased onto main at `a4306d63d` and adapted to the journal API
introduced by #4154: `journalStorage`, `AtomicJournalStorage`,
`ThreadKey`, `JournalEvent`, and `WorkspaceThreadJournalStore`.
Regression tests are in the journal package and the English and Chinese
guides are updated under `docs/dev`.
## Summary

Fixes #4027. Existing Kubernetes sandbox runtimes can initialize
workspaces and execute commands after an SDK upgrade without new
configuration.

```text
GET /capabilities
  200 + valid contract -> send command + timeout_seconds
  404                  -> send legacy command-only request
  other failure        -> reject before submission
```

Legacy HTTP waiting uses the previous timeout + 30 second allowance plus
the connector perAttemptTimeout (addressing review feedback). Submitted
commands remain single-attempt; HTTP or protocol failures report an
unknown execution outcome. English and Chinese runtime-contract docs
describe the negotiated behavior.

## Evidence

- **Before:** a runtime returning 404 for capabilities is rejected
before workspace initialization submits mkdir.
- **After:** the legacy-runtime regression verifies a successful
command-only POST; another test verifies that a failed legacy POST
remains UNKNOWN and is submitted once. Existing capability-validation
and modern timeout-contract tests remain in place.
- Targeted upstream-main tests: `mvn -T1C -pl
agentscope-extensions/agentscope-extensions-sandbox/agentscope-extensions-sandbox-kubernetes
-am test
-Dtest=CommandExecutorTest,KubernetesSandboxTest,SandboxConnectorRedirectTest
-Dsurefire.failIfNoSpecifiedTests=false` passed (45 tests), including
Spotless.
- Docs: `npm test` passed (13/13); `npm run validate` passed. `npm run
broken-links` reports Service-page links outside the changed runtime
paragraphs.
- Full-repository `mvn -B -T1C clean verify` on the integration checkout
failed in
`SandboxConnectorRedirectTest.commandWaitsPastConfiguredPerAttemptTimeoutForHeaders`:
its capability GET exceeded the 200ms network budget under the parallel
build. The full test class passed in the targeted upstream-main rerun;
the assertion and production timeout remain unchanged. Full-repository
verification has not passed.

## Merge Danger

**Door:** two-way — reverting restores mandatory capability negotiation.

**Blast Radius:** Kubernetes — legacy fallback bounds client waiting
only and cannot guarantee remote process termination. A capability 404
may also be caused by routing; the SDK logs the fallback and preserves
subsequent execution failures.
## Description

Closes #4211.

`JevClient` hardcodes `/v1/systemone` as the request path, which blocks
deployments against compatible gateways and inner providers that expose
a different path (e.g. `/v1/decisions`).

Changes:

- `JevClient.Builder` gains `endpointPath(String)`, mirroring
`OpenAIChatModel.Builder#endpointPath`. When set, the path replaces
`/v1/systemone` and is appended to the base URL (a missing leading slash
is normalized; a base URL that already ends with the path is not
duplicated). When unset, behavior is unchanged.
- Spring Boot starter: new `agentscope.jev.endpoint-path` property wired
through `JevAutoConfiguration`.
- Tests: 4 new `JevClientTest` cases (custom path, no duplication, slash
normalization, blank rejection) and starter coverage for both custom and
default paths.
- Docs: EN/ZH client guides updated with an example and the new
property.

Co-authored-by: jujn <[email protected]>
…se and spacing (#4208)

## Summary
- `SubAgentTool.sanitizeName` skipped its collision-avoidance hash based
on a regex over the
already lower-cased name that treated whitespace as safe. Because
sanitization is lossy
(case folding, whitespace/punctuation → `_`, underscore collapsing),
`"Researcher"`/
`"researcher"` and `"data analyst"`/`"data_analyst"` collapsed to the
same tool name with no
hash on either side, and fail-fast `Toolkit` registration then threw a
duplicate-tool error.
  - Treat a name as collision-free only when sanitizing it lost nothing
(`originalName.equals(safePart)`), so any lossy transform appends the
existing deterministic
    hash. Already-canonical names keep their stable tool name.

  Closes #4207
…overy (#4237)

## Description

Fixes #4235.

In snapshot mode (`journalEnabled(false)`), context-overflow recovery
retries structured requests through the plain call overload. The call
can complete after emergency compaction without the structured data
requested through Class or JsonNode schema parameters.

Preserve the original invocation through the recovery chain while
passing the adjusted retry input. This retains the requested output
format and the existing protection against duplicate user input.

Add four regression cases covering Class/schema calls with and without
overflow, and update the English and Chinese context-management
documentation.
…4170)

## Description

A sandbox whose host process is killed stays claimed until someone
deletes the `SandboxClaim` by hand. This exposes the SDK's existing
`shutdownAfterSeconds` option through the Kubernetes harness client and
the filesystem spec, so an application can hand reclamation to the
controller when it exits without shutting its sandbox down. The default
stays `null`, i.e. claims are created without a lifecycle exactly as
before.

- `KubernetesSandboxClientOptions.setShutdownAfterSeconds(Long)` rejects
zero and negative values;
`KubernetesFilesystemSpec.shutdownAfterSeconds(Long)` exposes the same
option while building a filesystem.
- `create(...)` writes `spec.lifecycle = {shutdownTime, Delete}` only
when the value is set. `copy(...)` and `merge(...)` preserve it, and a
per-call `null` inherits the client template.
- The lifetime starts at creation; resuming a claim does not renew it.
- `docs/dev/{en,zh}/docs/harness/{sandbox,filesystem}.md` describe the
setting and the workspace/snapshot boundary it interacts with.
## Description

**Background.** `io.agentscope.core.util.ExceptionUtils` had zero test
coverage despite being used on cancellation and error paths in
`ReActAgent`, `ToolExecutor`, and `ToolMethodInvoker`. Its
circular-cause guard and message fallback chain are exactly the logic
that silently breaks interrupt handling when regressed.

**Changes.** Adds `ExceptionUtilsTest` (17 tests, test-only, no
production code changes):

- `getErrorMessage`: null throwable, own message, whitespace-only
message, cause-message fallback (empty/null own message), class-name
fallback (no cause / empty or null cause message), and the single-level
cause contract (no deep-chain search).
- `containsInterruptedException`: null, direct, nested, deep chain,
absent, mutual circular causes, `InterruptedException` inside a cycle,
and a self-returning `getCause()`.
The stable 2.0 navigation lists three topics that describe unreleased
2.1 features. Move both language versions to `dev` and update the
navigation, translation links, and integration overviews. Redirect the
previous URLs and existing resumable-chat aliases directly to the new
pages.
Fixes #4161
Co-authored-by: jujn <[email protected]>
## Description

Fixes #4231.

`HarnessAgent.Builder.instruction(String, String)` is available only in
the 2.1 development line (present in `v2.1.0-BETA1` and `main`). The
Harness context guide showed the `instruction` example with no version
boundary, so readers who followed a direct `/dev/` link while depending
on a released 2.0.x version hit a compile error.

This adds a version-availability callout beside the example on the
English and Chinese dev pages: `instruction` is available in 2.1 and
later, and 2.0.x applications should keep their existing system prompt
and add the rule to `sysPrompt` instead. The 2.0 versioned docs are
unchanged because they do not contain this page.
## Summary

```text
compact(prefix)
  retain the fixed summary sections and all pending tasks
  label prior summaries and framework-injected messages by source
  escape transcript-like labels inside message bodies
  preserve active security constraints and clarify preserved-tail ordering
```

Closes #4242.

## Evidence

- **Before:** assistant-quoted role labels and framework-injected USER
messages could be read as genuine user requests; the summary had no
complete pending-task section.
- **After:** `ConversationCompactorSummaryShapeTest` covers assistant
label spoofing, prior summaries, framework-injected messages, prompt
sections, and preserved-tail notes.
- **Checks:** `mvn -B -T1C -pl agentscope-harness -am
-Dtest=ConversationCompactorSummaryShapeTest
-Dsurefire.failIfNoSpecifiedTests=false test spotless:check` passed (16
tests, Spotless clean); docs `npm test` and `npm run validate` passed.

- **Validation gap:** `npm run broken-links` reports 2,750 broken links
across 483 files in the repository; this change adds no links.

## Merge Danger

**Door:** two-way

**Blast Radius:** low

The change updates the default compaction prompt and transcript
rendering. It does not change public APIs or serialized state.
…4248)

Closes #4247.

## AgentScope-Java Version

`2.1.0-SNAPSHOT`

## Description

Follow-up to #3691. Place the Harness skill catalog where the shared
request prefix can include it as conversation history grows.

## Summary

```text
main      System -> history -> runtime materials (including skills) and task state -> references
fork/kst  System -> runtime materials (including skills) -> history -> task state -> references
Proposed  System -> skill catalog -> history -> other runtime materials and task state -> references
```

The earlier fork groups the catalog with session facts and per-call
values from `ContextBlock.runtime(...)`. A changing value can end the
shared prefix before the conversation. [Fork commit
`eb50ccd96`](Buktal@eb50ccd)

`HarnessContextBuilder` uses the existing `harness:skills` source ID to
render the catalog as a request-only User message. The catalog remains
required during compaction. If putting it before history would leave an
Assistant message last, Harness places the catalog at the end as a User
message.

## Evidence

- **Before** `skillCatalogPrecedesGrowingHistoryAndChangingRuntimeState`
fails on `main` (`c1d482900`) because the catalog follows history.
- **After** The ordering, empty-input continuation, and compaction
regressions pass. System text matches across all three requests. The
first two share the same catalog text, and the third reflects the
changed skill description. Changing runtime values follow history.
Provider cache hits and savings remain unmeasured.
- **Maven** Spotless and the full reactor pass with the Windows CI
command below. Harness reports 1,841 tests, 39 skipped, and zero
failures or errors.
- **Docs** All 20 docs tests pass, and `npm run validate` passes. The
`npm run broken-links` report matches the baseline's 2,750 existing
broken links.

```sh
mvn -B -T1C "-Dmaven.javadoc.skip=true" "-Dmaven.source.skip=true" "-Djacoco.skip=true" "-DskipDurableWindowsTests=true" clean verify
```

## Merge Danger

**Door** Two-way. Reverting restores the previous message order.

**Blast radius** Harness model requests with a visible skill catalog.

## Checklist

- [x] Spotless formatting checked.
- [x] Regression tests and Windows CI build pass.
- [x] Javadoc and the English and Chinese Harness guides describe the
request layout.
- [x] Tracking issue linked.
…2917)

## Summary

Fixes #2915

- Add explicit lifecycle control for spawned subagents.
- Add a required `reusable` flag to `agent_spawn`:
- `reusable=true` keeps the subagent addressable for later `agent_send`
calls until `agent_release` or parent shutdown.
- `reusable=false` creates a one-shot subagent that closes after its
task reaches a terminal state.
- Add `agent_release` for idle reusable subagents. Release is rejected
while a synchronous, asynchronous, remote, cancelled, or
timeout-promoted execution is still in flight.
- On successful release, close the child agent when possible, remove its
live key, label, and persisted spawn entry, and invalidate user-visible
Gateway handles.
- Scope live subagent registries by `(userId, parentSessionId)` so
concurrent callers and sessions do not address each other's subagents.
- Track execution ownership with leases across local, remote,
background, cancelled, and timeout-promoted executions.
- Serialize initialization for the same persistent subagent identity so
concurrent cache misses construct only one child while still waiting for
a fully initialized winner.
- Revoke exposed Gateway handles by child session, including persisted
handles backed by the durable subagent registry.
- Preserve compatibility for serialized spawn entries that predate the
`reusable` field; missing values default to reusable behavior.
- Preserve persistent session state when the parent `HarnessAgent`
closes, while still closing runtime child instances owned by the spawn
tool.
- Update the English and Chinese Harness subagent documentation in both
`docs/dev` and `docs/v2`.

## Behavior

`reusable=true` is for follow-up workflows:

```text
agent_spawn agent_id="reviewer" task="review the PR" label="pr-reviewer" reusable=true
agent_send label="pr-reviewer" message="also check the schema changes"
agent_release label="pr-reviewer"
```

`reusable=false` is for one-shot delegation:

```text
agent_spawn agent_id="reviewer" task="review every change" reusable=false
```

A one-shot subagent requires a task and cannot be combined with `label`,
`persistSession`, or `expose_to_user`, because those options imply later
addressing or reuse. No TTL, LRU, force-release, or automatic
retained-agent limit is introduced; retained lifecycle remains explicit.

Co-authored-by: jujn <[email protected]>
…) (#4196)

## Summary

Reading a binary file through a sandbox filesystem returns a payload
with embedded newline characters.

Root cause: POSIX `base64` wraps output at 76 columns with newline
separators, but `BaseSandboxFilesystem.read` only `.strip()`s the outer
edges before handing the string to `FileData(content, "base64")`. The
local and remote backends emit single-line base64
(`Base64.getEncoder().encodeToString`), so the sandbox backend is both
inconsistent across backends and undecodable with the strict
`Base64.getDecoder()` (which rejects line separators), while the model
also sees broken payload text.

## Fix

Strip **all** whitespace from the command output before constructing
`FileData` — the POSIX base64 output is exactly the base64 alphabet plus
separators, so `\\s+` removal changes nothing for well-formed payload
bytes.

## Regression

`read_binary_wrappedBase64Output_strippedToSingleLinePayload`: an
80-byte fixture force-wrapped by `Base64.getMimeEncoder(76, newline)`
must come back single-line and round-trip through the strict
`Base64.getDecoder()`.

Full harness module suite green on the merged batch state (1833/1833).
## AgentScope-Java Version

`2.1.0-SNAPSHOT`,基线为官方 `main` 的
`a4306d63d8ac737b535657f56a0ad5496503d4d8`。

## Description

Fixes #4162.

当自定义模型分片返回一次没有原始 ID 的工具调用时,累加器在构建流式快照和最终消息时会分别按时间戳补
ID。工具只执行一次,但消费端无法用同一个 `toolCallId` 拼接参数并关联执行结果。

本 PR 在单次工具调用的累加状态中生成并复用一个备用 ID。备用 ID 保留 `tool_call_` 前缀并使用
UUID,避免不同累加状态恰好在同一毫秒生成相同的 ID。模型提供的原始 ID 保持不变。不改分片路由、工具调度、权限或事件字段;不扩展到原始
ID 迟到的语义。

### 验证

- 端到端回归覆盖缺少原始 ID 和已有原始 ID:开始、参数分片、结束、执行结果及历史使用同一 ID,拼接后的参数能得到预期工具结果。
- 单元测试验证同一调用多次构建时 ID 保持稳定、不同调用不共享备用 ID,以及累加器重置后不复用旧 ID。
- 在未修复基线上,缺 ID 的新回归用例因分片 ID 不一致而失败;带原始 ID 的对照通过。应用补丁后两个场景均通过。
- `mvn -B -T1C -pl agentscope-core -am test`:3452 项,0 failures、0
errors、11 skipped。实际在本机使用 Maven Central 临时 settings 与离线缓存;Spotless
通过。未运行全仓测试或 Windows。
- 已同步中英文 dev 事件文档。文档单测 20 项通过,导航、语法、本地链接及资源检查通过,`npm run broken-links`
未发现坏链。Mintlify 完整构建校验被本地预览缓存的文件权限阻止,待 CI 验证。

### 相关 PR

#4163 也处理 #4162 的同一根因。本 PR 额外验证不同调用与重置之间不复用备用
ID,并补充双语事件文档。两份修复不需要同时合并,请维护者选择合适的实现。

## Checklist

- [x] Code has been formatted with `mvn spotless:apply`.
- [ ] All repository tests are passing (`mvn test`) — 已验证 Core,未运行全仓。
- [x] Javadoc comments follow project conventions — 无新增公共 API。
- [x] Related documentation has been updated.
- [x] Code is ready for review.
## Summary

- route parent cancellation through a `HarnessAgent` to its `ReActAgent`
delegate
- interrupt the spawned `sub-*` session context instead of the parent
run context
- preserve cancellation-by-disposal for ordinary `Agent` implementations
and timeout promotion behavior

## Root cause

`AgentSpawnTool.interruptAgent` only handled direct `ReActAgent`
instances, so a synchronously spawned `HarnessAgent` ignored parent
cancellation. It also called `interrupt` with the parent
`RuntimeContext`, while the child runs under a newly generated `sub-*`
session.

This fix stays local to `AgentSpawnTool` and does not change the shared
`Agent` interrupt API or the `HarnessAgent` facade, avoiding overlap
with #1685 and #1990.

Closes #2408
Co-authored-by: jujn <[email protected]>
…#4274)

## Background

Swept the last 125 PRs (#4272→#4075) for single-OS CI failures under
`mvn -B -T1C clean verify` (one build OS red, the other green on the
same commit = flake suspect). Cross-PR repeats and main's own red run on
2026-11-19 (ubuntu, run 44516464414) pinpoints four still-broken test
classes; all fixes are test-side only (no `src/main` changes).

## Fixes and evidence

| Test class | Victims | Signature | Fix |
|---|---|---|---|
| `RocketMqExecutionTest` | #4182, #4192, #4103 + main run 44516464414
(2026-11-19, ubuntu) | `turn reaches SUCCEEDED did not become true
within 10s` while the turn kept progressing (modelCalls complete, acks
climbing, lastFailure=none) — deadline breakthrough under starvation,
not a lost turn | shared `waitUntil` deadline 10s→30s (repo tier
#3726/#3774) |
| `AgentScopeAdapterTest` | #4204 (same-commit re-run green = confirmed
flake), #4191, #4246 | `Timed out observing Turn` at 6.7–8.5s elapsed;
resume/recovery one step from terminal | `turn.await(5s)`→30s at all 3
sibling sites via `TURN_DEADLINE`, outer `get` budgets +5s margin |
| `WorkerRuntimeTest` | #4219, #4224, #4255 (windows) | (a) `Worker
lease lost` after 2.4s — 1s claim leases expired between claim and
release; (b) `renewed.await(5s)` missed at 6.5s while the recovery lane
was healthy; (c) `Interrupted sleep interrupted` —
`WorkerRuntime.process()` interrupts the calling thread on lease-renewal
failure and manual `tick()` runs it on the test thread | (a) claim
leases 1s→30s (staleness under test still comes from `release(ZERO)` +
re-claim); (b) latches 5s→30s; (c) raw `Thread.sleep`→interrupt-proof
`pause()` at 5 sites, mirroring the #4176 fix for the same signature in
`ProcessRecoveryTest` |
| `ChatSessionsTest.await` (shared with `ChatControllerTest`) | #4233,
#4182 (stuck-RUNNING at 40.8s/46.4s), #4268, #4163 (poll threw `Durable
database transaction failed`) | two surfaces of one cause: every
snapshot poll opens a writing sqlite transaction contending with the
runtime's own writes, and windows runners starve turns past 30s (same
file already measured 56.6s starvation and uses 120s elsewhere, #3726) |
deadline 30s→120s (aligned tier) + tolerate transient `UNAVAILABLE`
store exceptions while polling; persistent failure rethrows at the
deadline, FAILED-turn fast-fail unchanged |
| `CommandExecutorTest.missingExitCodeIsUnknown` | local -T2C full-repo
stress (2026-11-19; pristine-main baseline of the same class green) |
the 2s network budget fired on scheduler starvation before the instant
fake response was processed, misclassifying the failure as a deadline
miss instead of a missing exit code (2.97s elapsed) | budget 2s→30s for
this non-deadline-semantics test; the two deadline-semantics tests keep
their tight budgets |

## Constraint compliance

- Happy path zero cost: every change only extends failure-path deadlines
or hardens helpers; no new sleeps, no weakened assertions.
- Minimal widening anchored to measured data (each comment cites victims
+ measured values); 30s follows the repo's established deflake tier,
120s follows this file's own previously measured starvation tier.
- Structural hardening preferred: `pause()` helper, transient-lock
retry, lease decoupling from the tested invariant.
- No `src/main` changes.

## Observed but deliberately not fixed here

-
`ProcessRecoveryTest.replacementCollectsOriginalResultWithoutRepeatingEffect`
(#4214: `expected: 2 but was: 3`): recovery-semantics race (model re-run
without effect re-run after abrupt halt) — a product question for the
durable recovery work, not a deadline flake.
-
`JevEvidenceProcessorTest.filterFailureIsWithheldButRankFailureFollowsScoredEvidence`
(#4265: delivered `[]` on a 25×-slowed runner): root cause not
established; single occurrence.
- Already fixed upstream, victims predate the fix:
`AgentScopeAgentExecutorInputRequiredTest` (#4157/#4187/#4152 all
predate #4176's `BaseReActAgentRunner` change), `InboxMiddlewareTest`
(#4093 predates #3738), `HarnessAgentSubagentStreamEventsTest` (#4183
predates #2917).
- `SkillBoxTest$UploadContainment` quartet (#4201/#4202/#4212/#4229):
test does not exist on main (fork stack only); deterministic cross-drive
path bug, not load flakiness.
- #4184/#4185: both-OS compile breaks from dependency major bumps
(dependabot), out of scope.

Also applied during review: sibling sites with the identical measured
mechanism were widened in the same pass — the remaining 1s fixture claim
leases in `WorkerRuntimeTest` (fenced begin/update/release sequences,
same #4219 signature), the start/PAUSED 5s budgets in the same
`AgentScopeAdapterTest` method as the victims, and the 5s/4s observe
budgets in
`completeLocalBackendRunsNativeAgentWhileManagedObserverIsBlocked`.

## Test plan

- [x] Full local `mvn -B -T2C clean verify` green (stricter than CI's
-T1C). Locally excluded, each verified to fail identically on pristine
main on this machine (Windows/git-bash) while passing on CI:
`JsonFileAgentStateStoreTest` (symlink permissions), the
`agentscope-extensions-durable-sandbox` trio plus
`ToolInSandboxExampleTest`/`SandboxRoundTripTest` (sandbox shell heredoc
incompatible with local git-bash python3), and the
`AgentScopeAdapterTest`/`ProcessRecoveryTest`/`HarnessExternalToolProcessRecoveryTest`
trio (durable-adapter classes whose Windows runs are skipped on CI; the
same named tests fail on pristine main locally).
- [ ] CI green on both OS.
Closes #4271.

## AgentScope Java Version

2.1.0-SNAPSHOT

## Summary

```text
ReAct iteration limit
  Prepare SUMMARY request
    Offload oversized tool results when configured
    Compact eligible history and retain the closing instruction
    Validate the final input budget
  Send the prepared request
```

The shared compactor keeps at least one recent message in message-count
mode. The English and Chinese Harness context guides describe the
fallback and tail retention.

## Evidence

- **Before:** An over-budget SUMMARY reached budget validation without
compaction and raised `ContextBudgetExceededException`. Enabling
compaction alone could also remove the closing instruction with
zero-message retention.
- **After:** All 35 tests in `HarnessContextBudgetTest` and
`ConversationCompactorTest` pass. The new cases cover successful
compaction, zero-message retention, tool-result offloading, and
rejection of an irreducible request. The Harness module and its Maven
dependencies pass the full module test run (mvn -B -T1C -pl
agentscope-harness -am test). Spotless, the docs tests, and `npm run
validate` pass. Mintlify's separate Windows link checker reports
site-wide broken links. The documentation diff changes prose only.

## Merge Danger

**Door** · Two-way. Reverting the commit restores the previous
preparation and retention rules.

**Blast Radius** · Harness. SUMMARY requests now use configured
reductions, and shared message-count compaction keeps one recent message
when configured to retain zero.
## Problem

The fine-grained streaming API (`ReActAgent#streamEvents(...)`) — the
recommended replacement for the deprecated coarse-grained `stream(...)`
— has **no structured-output overloads**. Only `call(msgs, schema/class,
ctx)` (non-streaming) and the deprecated `stream(msgs, options,
schema/class, ctx)` support `outputSchema`.

`buildAgentStream(...)` is private, so downstream code cannot inject a
schema variant of `streamEvents` without forking the framework or
relying on the deprecated API (which returns the legacy
`io.agentscope.core.agent.Event` instead of the fine-grained
`io.agentscope.core.event.AgentEvent`).

Closes #1717.
Co-authored-by: jujn <[email protected]>
…erializing (#4276)

## Description

Fixes #4275.

Workspace files lost their POSIX permissions on the way into the
sandbox: a script that is `0755` on the host arrived `0644`, and running
it from the workspace failed with `Permission denied`. Two paths
materialize host files and both dropped the mode.

**Projection tar.** `WorkspaceProjectionApplier` builds the payload the
backend extracts with `tar -xf`, so the entry mode is exactly what the
file ends up with, but every entry was created with `new
TarArchiveEntry(rel)` and never called `setMode`. Entries now carry the
source file's nine permission bits, and the mode participates in the
projection hash, so a `chmod` that leaves the bytes alone re-projects
instead of being skipped.

**Direct materialization.** `WorkspaceSpecApplier` copied
`LocalFileEntry`/`LocalDirEntry` bytes with `Files.copy` and no
attributes, which creates the target with the platform default
permissions. It now inherits the source mode.

Both go through one package-private helper, `TarFileModes`
(`modeOf`/`applyTo`), which `WorkspaceArchiveExtractor` uses as well, so
every path that puts a host file into a workspace agrees on one rule:

- inherit the source's nine permission bits;
- fall back to `0644` where the host filesystem cannot express POSIX
permissions (Windows), or when the source vanished between the read and
the stat;
- leave inline `FileEntry` content at the platform default — it has no
source to inherit from;
- keep directories at the platform default: inheriting a `0555`
directory would reject the files copied into it here and on the next
materialization.

Setuid/setgid/sticky bits are dropped, so a projected file cannot gain
privilege in the sandbox. Symlinked files are still materialized and
symlinked include roots are still skipped; the change is limited to the
permission bits.

Co-authored-by: jujn <[email protected]>
## 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
#4278)

## Summary

- Mark `task_output` and `wait_async_results` as `timeoutManaged`.
- Keep each tool's existing self-bounded wait budget authoritative,
instead of allowing the ordinary tool execution timeout to interrupt the
wait first.
- Add focused regression coverage for a short Toolkit-level timeout that
must not cut short a longer managed wait.
- Update the English and Chinese subagent documentation.

Fixes #1451.

## Background

`task_output(block=true)` accepts a wait timeout up to 600 seconds,
while the default ordinary tool timeout is 5 minutes. As a result, a
valid `task_output` wait could be interrupted by the outer
`ExecutionConfig.TOOL_DEFAULTS` timeout before its own deadline.

`agent_spawn` and `agent_send` already use the existing `timeoutManaged`
mechanism introduced by #3879. This change applies the same semantics to
the two SubAgent result-waiting tools:

- `task_output(block=true)` owns its bounded wait timeout.
- `wait_async_results` owns its existing 60-second default / 120-second
maximum wait budget.

`wait_async_results` is not affected by the default 5-minute ordinary
timeout, but a shorter application-configured tool timeout can currently
interrupt its own bounded wait. Marking it as timeout-managed makes the
behavior consistent.

## Behavior

- `task_output(block=true)` continues to use its existing timeout
parameter, default, and 600-second cap.
- `wait_async_results` continues to use its existing timeout parameter,
default, 120-second cap, and consecutive-empty-wait guardrails.
- Non-blocking operations such as `task_output(block=false)`,
`task_cancel`, and `task_list` are unchanged.
- Ordinary tools continue to use the normal `ExecutionConfig` timeout.
…ry (#4305)

## Description

**Problem.** `DashScopeConversationMerger.mergeToMessage` — the
careful/text merge path used by `DashScopeMultiAgentFormatter` — handles
`TextBlock`, `HintBlock`, `ImageBlock`, `VideoBlock`, `DataBlock`,
`DocumentBlock`, `ThinkingBlock` and `ToolResultBlock`, but has no
branch for `AudioBlock`. An audio block therefore falls off the end of
the if-else chain and is silently dropped from the merged text history:
the model never sees it and no log or placeholder is emitted.
#4299)

## Description

The default tool result converter JSON-serializes every return value
into a text block, apart from a returned `ToolResultBlock` that passes
through. A tool wanting to produce typed output — say an `ImageBlock`
with inline Base64 data — therefore had to wrap it in
`ToolResultBlock.of(...)` itself; returning the block directly degraded
it to a JSON string.

The converter now recognizes a returned `ContentBlock`, or a non-empty
list whose elements are all `ContentBlock`s, and wraps it as the
result's typed output. Mixed or empty lists keep the JSON path, so
existing behavior is unchanged for ordinary values.

Co-authored-by: jujn <[email protected]>
xzxiaoshan and others added 23 commits November 21, 2026 15:14
## Description

The AG-UI protocol defines three source types for media parts — `url`,
`data` (inline Base64), and `file` (provider-issued handle) — and the
inbound direction accepts all three. The outbound path from #4003,
however, serialized URL sources only: media blocks carrying a
`Base64Source` or `FileIdSource` were dropped silently, with no log or
fallback. Media sent as inline data or a file handle therefore
disappears from `MESSAGES_SNAPSHOT` history on reconnects, refreshes,
and session switches.

This change maps all three AgentScope source types on the outbound path,
mirroring the document handling #3979 established in
`toDocumentInputContent`.

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

`FeishuOutboundClient.send` dropped the thread ID when forwarding each
message to the common request builder. With a threaded address, even a
successful batch went to the parent chat. Pass the address's thread ID
through the existing sequential send path so it uses the same reply
endpoint and body as a receipt-based send. A chat address continues to
use the create-message endpoint.

Two loopback tests check the actual HTTP request URIs. The threaded case
sends two messages and checks that both post to
`/open-apis/im/v1/messages/om-root/reply`. The unthreaded control checks
the create-message URI and its `receive_id_type=chat_id` query. The
EN/ZH Feishu channel guides now describe when each endpoint is used.
## Description

Fixes #4292.

Any agent that declares a filesystem route loses `shell_execute`. The
builder wrapped the primary filesystem in a `CompositeFilesystem`, which
routes paths but implements none of the capabilities it wraps — no
`execute`/`id`, no `AbstractSandboxFilesystem` marker, no sandbox
workspace prefix — so every probe that reads the filesystem concluded
"this workspace has no shell":

- `shell_execute` was never registered (`HarnessAgent` probed the marker
on the wrapper);
- the skill shell policy resolved to `NO_SHELL`, so every skill lost its
`<files-root>` and code-execution block;
- in local mode the same loss hit `LocalFilesystemWithShell` + a route.

A subagent with `workspace.mode=shared` over a sandbox-backed parent is
the reported case: it inherits the parent filesystem, gets routes
applied, and ends up with no shell.

**Composition.** `filesystemRoute`'s javadoc already promises "when the
primary filesystem is sandbox-backed, the route is applied via
`RoutedSandboxFilesystem` so `shell_execute` still targets the sandbox"
— that held for the sandbox-spec branch but not for an injected primary.
`withFilesystemRoutes` now applies the same rule to any primary that
executes commands in a sandbox, so a custom `BaseSandboxFilesystem` (the
`SharedSandboxFilesystem` shape) and an overlay over a sandbox keep
`execute`/`id`. A host shell stays on a plain composite:
`LocalFilesystemWithShell` implements `AbstractSandboxFilesystem` too,
and routing it would make the probes read host paths as `/workspace`
paths.

**Probes.** Shell tool registration and the skill shell policy now
resolve the filesystem through `FilesystemUtils.primaryBackend`, which
peels `CompositeFilesystem` and `RoutedSandboxFilesystem`. The two also
agree on the same marker now: registration has always used
`AbstractSandboxFilesystem`, the policy used the narrower
`SandboxBackedFilesystem`, so a routed custom sandbox filesystem got a
shell tool while every skill was told there was none.
…et (#4346)

`JevEvidenceProcessorTest.filterFailureIsWithheldButRankFailureFollowsScoredEvidence`
failed on a loaded ubuntu runner (seen on PR #4343) with `expected:
<[scored, unranked]> but was: <[]>`: the class's 2s supervision budget
expired before any assessment completed, so the timeout fallback
reported every passage as UNSCREENED and delivered nothing. The mocks
reply instantly, so the budget is never the property under test.

Raise the class budget from 2s to 6s and advance the two virtual-time
TIMEOUT assertions past it (7s), matching the supervision-test fix in
#3672. Virtual-clock awaits cost no real time and instant-mock tests are
unaffected, so total test time is unchanged.
The AG-UI protocol defines an optional `name` field (sender name) on
messages, but `AguiMessage` had no binding for it: inbound names were
dropped by Jackson, and outbound `Msg.name` never reached the wire. This
broke speaker attribution in multi-agent chats over the AG-UI channel.

- `AguiMessage`: add the nullable `name` field to the `@JsonCreator`
constructor, keep the existing 5/6-param constructors as delegating
overloads, and add name-carrying factory overloads. The key is omitted
from JSON when null.
- `AguiMessageConverter`: map `name` both ways — inbound wire `name`
populates `Msg.name`; every outbound AG-UI message (standard, reasoning
split, per-tool-result split) carries `Msg.name`.
- `AguiMessageConverterTest`: 8 new cases covering inbound/outbound
mapping, JSON round-trip, null-key omission, and the split paths.

The field is optional on the wire: messages without a name serialize
exactly as before, and old peers are unaffected.
…lists (#4294)

Closes #4293.

## Summary

```text
Tool registration
  Declare @tool(evictable) / @tool(prunable) — default true
  Expose via AgentTool.isEvictable()/isPrunable() and ToolBase
Consumers
  Eviction merges toolkit declarations with excludedToolNames(...)
  Pruning folds declarations into the effective config (withPruneExclusions)
Defaults
  Built-in tools declare themselves (read_file, write_file, edit_file,
  memory_search, memory_get; thread_search declares prunable=false)
  Config name lists become empty-default user overrides
  DEFAULT_EXCLUDED_TOOLS deprecated for source compatibility
```

A custom tool sharing a built-in name is no longer silently exempt: an
undeclared tool of that name is now evicted and pruned like any other,
while the built-in tools keep their prior default protection through
their own declarations.

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

`web_fetch` percent-encodes stray `%` signs in URL paths and queries,
while preserving valid `%HH` escapes.

Closes #4342.

## Evidence

- **Before:** `?format=%l:+%c` fails with `Malformed escape pair`.
- **After:** bare percent signs are sent as `%25`; valid escapes remain
unchanged.
- **Validation:** `WebToolsTest` — 17 tests passed.

## Merge Danger

**Door:** Two-way

**Blast Radius:** Low
## AgentScope-Java Version

2.1.0-SNAPSHOT (current main)

## Description

Publish the Chinese blog article **AgentScope Durable:让企业 Agent
持续、可靠地运行**, authored by 刘军 and 朱志宇.

Source article:
https://mp.weixin.qq.com/s/iDpIiF4UNAvUEq1KV1NuLw

Changes:

- Add `docs/v2/zh/blogs/agentscope-durable.md` with the complete
article.
- Add four diagrams under `docs/imgs/v2/`.
- Add the article to the Publications navigation in `docs/docs.json`.
- Preserve the original section numbering, code examples, table,
captions, and links.

Verification:

- `npm test`: 20/20 passed.
- `npm run validate`: 660 pages and 1011 redirects checked; Mintlify
build validation passed.
- `npm run broken-links`: no broken links found.
- Previewed the article and images locally with Mintlify.

This is a documentation-only change; no Java code or runtime behavior is
affected.

## Checklist

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

Co-authored-by: juruoO-o <[email protected]>
@coderzhn
coderzhn merged commit 3054b19 into coderzhn:main Nov 24, 2026
5 checks passed
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.