Repository navigation
feat(core): per-user capability surface with grant trimming for tools, groups and skills - #3500
Conversation
…ools, groups and skills Introduce a server-side CapabilityResolver that resolves an immutable, per-call CapabilitySurface from the caller identity. The surface trims what the model sees (tool schemas, skill visibility, reset_equipped_tools enum/description) and is enforced by hard execution gates for tools, skill loading and group activation. System-marked capabilities bypass trimming; all model-facing denials are byte-identical to not-found wording; a missing surface means a trusted direct path (unrestricted).
- Builder.copy() now carries capabilityResolver (main's copy()-based build dropped it, silently disabling the grant layer) - reset_equipped_tools keeps the RuntimeContext param while adopting ToolResultBlock.success from agentscope-ai#2751 - externalToolSchema and rewriteResetToolSchema carry the new deferLoading schema field - grant tests observe the call-scoped rc (main isolates the caller rc) and assert the suspended external result
The 2-arg getToolSchemas is package-private since the grant layer landed; pass a null surface (un-trimmed compose) for the EXTERNAL_ONLY assertion.
This comment was marked as outdated.
This comment was marked as outdated.
Unify the skill identifier vocabulary to skillName (the business identity,
unique per agent catalog) end to end; the composite name_source skillId is
now an internal storage detail:
- Grant surface: allowedSkills holds skill names; the skill tool-group
naming convention derives from skillName ("_skill_tools"), so granting a
skill reliably releases its tools without any id<->name translation
- SkillRegistry keys by name and enforces per-catalog uniqueness
(re-registering the same instance is idempotent; a different instance
under a used name is rejected)
- Loading: load_skill_through_path now takes a "skillName" parameter in
both core and harness; prompts emit <skill-name>; not-found and denial
wordings updated to match
- AgentSkill.getName() documents the industry-standard unique identity;
getSkillId() is deprecated for removal
- Harness skill chain (catalog keying, load tool, prompt builder, usage
middleware) aligned to the same vocabulary, closing the grant/addressing
mismatch surfaced in review
- Synced docs/v2 pages (zh/en) and tests; full mvn test green
…urface A SkillToolGroup bound to a granted skill (activateOnSkill) is now added to allowedToolGroups once at call entry, so granting a skill implicitly grants its custom-bound tool groups alongside the naming-convention group. The expansion is a mechanical whitelist union performed while the entry holds both the surface and the toolkit: the surface stays pure data, every gate keeps consuming only the query methods, and groups bound to ungranted skills stay denied. It is idempotent — the same instance is returned when nothing is added, so sub-agents reusing an inherited surface keep reference equality across toolkits with identical bindings.
skillId equals the skill name normally, extended to name__s__source only when a source differentiates same-named skills. Grant entries accept both forms (lazy failure on unknown sources); model-facing vocabulary back to skillId; the "custom" source default is removed.
Registry, dynamic middleware and harness catalogs key by skillId: same-named skills from different repositories coexist, the same skillId re-registration replaces (version override), and lookups are exact (a bare name is the source-less id form). SkillFilter matches the exact skillId; upload subdirs and load echoes use skillId.
# Conflicts: # agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java
main's bare-name SkillFilter tests asserted the old composite skillId format (name_source, default source "custom") and failed after the merge. Update the literals to the dual-form scheme (name when no source, name__s__source when sourced) and give the disable-by-name test an explicit source so it still exercises hiding a composite-id skill. Test intent is unchanged: filters match the skill name.
…at/capability-surface
Resolve the grant surface at the harness call/stream entry, before the sandbox acquire, so marketplace skill staging materialises granted-only files; the inner delegate keeps the surface without re-resolving and an inherited surface is never overwritten in place. Also fix the stale catalog-key sentence and document the activateOnSkill grant rule in capability-grant.md (zh/en).
Conflict resolution in HarnessAgent#forceCompactAndRetry: keep main's overflow-retry rework (agentscope-ai#3661 — persist compacted state via updateAgentState, retry with retryInput to avoid duplicate input) and re-apply the capability-surface re-prepare on the retry call so the grant surface survives the overflow path. Adapt HarnessSkillMiddlewareGrantTest to main's agentscope-ai#3691 change: the skills block now rides a tail runtime material (harness:skills) instead of the system prompt, so grant-visibility assertions move there.
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
activePeersSurviveEvictionOfIdleOnes asserted evictIdlePeers() == 1, but
a >=100ms overshoot of the 900ms sleep let allow("active-peer") fire the
piggybacked sweep first (one full window+cooldown interval had elapsed),
evicting idle-peer before the explicit call and flipping the count to 0.
Restage so the sweep is the deterministic eviction path: idle-peer sits
past the threshold before active-peer's first event, so that allow()
always sweeps it and the explicit call finds nothing. Overshoots only
push the idle peer further past the threshold. Verified 5 consecutive
runs green.
Conflict resolution in SkillPromptBuilder.java: took main's slim-view usage header verbatim (041ce17 rewrote the block that carried the branch's leftover 'skillName=' example typo; the branch-side dual-form skillId semantics live in getSkillId(), unaffected). Adapted main's new SkillRuntimeTest.defaultRendersSlimViewWithinByteBudget to the branch's dual-form skillId convention: data-analysis_workspace -> data-analysis__s__workspace, consistent with every other skill-id assertion in the file. Verified: mvn -T1C -pl agentscope-harness -am test (1415 tests, 0 failures); spotless:check clean.
…ability-surface # Conflicts: # agentscope-core/src/main/java/io/agentscope/core/skill/AgentSkill.java # agentscope-core/src/main/java/io/agentscope/core/skill/DynamicSkillMiddleware.java # agentscope-core/src/main/java/io/agentscope/core/skill/SkillBox.java # agentscope-core/src/main/java/io/agentscope/core/skill/SkillRegistry.java # agentscope-core/src/test/java/io/agentscope/core/skill/AgentSkillPromptProviderTest.java # agentscope-core/src/test/java/io/agentscope/core/skill/AgentSkillTest.java # agentscope-core/src/test/java/io/agentscope/core/skill/DynamicSkillMiddlewareTest.java # agentscope-core/src/test/java/io/agentscope/core/skill/SkillBoxTest.java # agentscope-core/src/test/java/io/agentscope/core/skill/SkillBoxToolsTest.java # agentscope-core/src/test/java/io/agentscope/core/skill/SkillUtilTest.java # agentscope-extensions/agentscope-extensions-channel/agentscope-extensions-channel-common/src/test/java/io/agentscope/extensions/channel/common/BotLoopGuardTest.java
…ability-surface # Conflicts: # agentscope-core/src/main/java/io/agentscope/core/tool/Toolkit.java # agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillLoadTool.java
…nsolidation The notificationReachesModelRequestUnderRealScheduling test asserts on MockModel.getLastMessages() right after call().block() returns. The default memory hooks schedule a background consolidation model call after the reply completes; on a fast Linux runner that call can win the race and become the recorded "last" request, failing the assertion with the consolidation prompt. Disable memory hooks in this test so the only model request is the reasoning call under test. Fixes the ubuntu-latest failure in PR CI run 41024248628.
# Conflicts: # agentscope-core/src/main/java/io/agentscope/core/tool/AgentTool.java
…mory pipeline Main's new memoryRead_* isolation tests assert MEMORY.md contents immediately after call(), but the fire-and-forget flush -> consolidation pipeline reuses the stub model: its fixed response gets extracted, appended to the daily ledger and then consolidated into MEMORY.md, racing the assertions (CI Linux saw 'done' where '' was expected). These two tests target namespace isolation, not flush behaviour — disable memory hooks so they are deterministic.
|
[P2] 已修复优化 |
juruoO-o
left a comment
There was a problem hiding this comment.
复审基于 dcda800f5eed4e7c3dfe3f1337ba4d16bbac18ee。
感谢继续修复。需求和主要设计方向仍然值得支持;本次已实测确认,之前直接使用 DynamicSkillMiddleware、未配置授权时丢失 Skill 目录的兼容问题已经修复。静态提示词裁剪和按调用缩小沙箱缓存投影也是有效改进。
不过,前两项尚未覆盖完整调用链,另外发现一个新的源码兼容问题,因此仍建议 Request changes:
-
[P1] 静态 Skill 仍通过 loader schema 暴露目录。 静态提示词已按 surface 裁剪,但静态
load_skill_through_path的skillId.enum仍来自完整 SkillRegistry。独立探针实测:继承DENY_ALL时,模型提示词已不包含秘密 Skill,模型收到的 loader schema 却仍包含beta_market。请同步裁剪模型可见的 loader schema,或采用不携带完整目录的 schema,并增加同时检查 messages 和 tool schemas 的回归用例。
相关位置:SkillHook.java:57-59;SkillToolFactory.java:223-238。 -
[P1] 缩小投影范围不能撤销复用沙箱中的旧 Skill 文件。 新实现限制本次投影 archive 的内容,但
AbstractBaseSandbox.applyWorkspaceProjectionIfChanged只 hydrate 新文件,未清理此前投影进入 workspace、如今已不再授权的文件。使用实际 AbstractBaseSandbox 生命周期和本地模拟后端复现:首次投影 beta,stop 后将 includeRoots 缩为空,再次 start,沙箱 workspace 中的 beta/run.sh 仍可读取。当前 projection-narrowing 测试主要断言传给 manager 的 spec,无法发现目标 workspace 残留。请覆盖复用 workspace 和快照恢复路径,确保当前调用的可访问内容符合授权;清理不能破坏其他并发调用。本次未执行真实云端沙箱测试。
相关位置:SandboxLifecycleMiddleware.narrowSkillsCacheProjection;AbstractBaseSandbox.applyWorkspaceProjectionIfChanged。 -
[P2] 新增公开重载使原有 null 调用无法编译。 原有 SkillFilter 参数明确支持 null 表示全部可见。新增
getSkillPrompt(CapabilitySurface)和getSkillSystemPrompt(Predicate<AgentSkill>)后,以下原有调用都会因重载歧义而编译失败:box.getSkillPrompt(null); provider.getSkillSystemPrompt(null);
已用 javac 验证:上一评审版本可编译,当前版本报 ambiguous method reference。建议将新方法改为不同名称,或仅作为内部方法使用,保留原有源码调用的兼容性。
相关位置:SkillBox.java:178;AgentSkillPromptProvider新增 Predicate 重载。
验证:本次运行 10 个相关测试类,共 143 项通过;另外通过模型输入/schema 捕获、本地模拟沙箱生命周期和 javac 编译探针复现上述问题。未运行全量测试或真实云端沙箱测试。
整体设计不需要因这几项问题推倒重来,但需要把展示、实际文件访问和兼容性这几个边界补齐后再合入。
…keep null-call source compat - rewriteMetaToolSchema now also rewrites the load tool's skillId enum when the surface is restricted: candidates come from the schema itself, filtered by allowsSkill(id); empty result removes the enum key. The static skillBox path baked the full registry into the enum at build time, so a restricted surface (incl. inherited DENY_ALL) enumerated unauthorized skills to the model. Unrestricted surfaces and external request-config overrides pass through untouched. - SkillBox.getSkillPrompt(CapabilitySurface) and the provider's Predicate<AgentSkill> overload become package-private: the public same-arity overloads documented 'null treated as all', and a public addition made external getSkillPrompt(null) / getSkillSystemPrompt(null) calls ambiguous (javac-confirmed source break). - golden assertions now check messages AND tool schemas; a cross-package uncast null call locks the source-compat contract.
…sandboxes Workspace projection is now authoritative instead of overlaying: the applied manifest (projectedWorkspacePaths, persisted on SandboxState) drives revocation of every previously projected file the current call no longer authorizes — covering the reused-workspace path (Branch A) and snapshot restores (Branches B/C force the pass past the hash check). Manifest paths are untrusted input: a strict character whitelist plus single-quoted rm -f operands leaves no shell expansion vector, and deletion failures abort the start (fail-closed). Emptied parent dirs are rmdir-pruned chunked, deepest-first, so revoked skill names do not linger as empty trees. Default primitive runs through doExec (the only channel for remote backends); host-backed sandboxes may override with native deletion. Docs (zh/en) updated to state entered files are revoked.
…ew nits - pin the generated deletion command shape (rm -f -- with single-quoted operands, never rm -r) so the containment cannot regress silently - end-to-end fail-closed test: a traversal entry in the persisted projection manifest aborts the sandbox start - guard the DENY_ALL loader-enum assertion against a vacuous pass when the loader schema is absent entirely - O(1) set lookup for the projected-path diff on every start
|
三项都已修复:
提交: |
juruoO-o
left a comment
There was a problem hiding this comment.
复审基于 5fd49e5e0f25e55b080d2c2cdd0d775eae4c5ca1。
感谢继续修复。上轮三个问题的直接复现场景已通过:静态 loader schema 不再枚举未授权 Skill;有新投影清单的复用 workspace 可以撤销旧文件;原有 getSkillPrompt(null) / getSkillSystemPrompt(null) 恢复源码兼容。授权能力和主要设计方向仍然值得支持。
目前仍建议 Request changes。新增撤销逻辑还存在以下升级和兼容性问题:
-
[P1] 旧 SDK 的 workspace 没有投影清单,升级后首次收紧授权仍可能留下旧脚本。 新增
projectedWorkspacePaths在旧状态中不存在,但applyWorkspaceProjectionIfChanged将 null 清单当作没有需要撤销的文件。独立探针实测:保留含 beta 脚本的 workspace、模拟旧状态(projectedWorkspacePaths=null),将当前投影收为空后重新启动,beta/run.sh 仍存在且可读取。需要明确处理缺少可信清单的旧 workspace:安全重建、建立可信清单,或明确拒绝不支持的组合;不能把缺少元数据当作已完成隔离。当前快照测试先经过新版 start,已经有清单,未覆盖这一升级场景。
位置:AbstractBaseSandbox.java:425-434。 -
[P1] 合法资源文件名会导致后续启动失败。
requireSafeProjectedPath只接受[A-Za-z0-9._/-]+,但投影构建和资源加载并没有禁止空格、中文等合法文件名。独立探针实测:user guide.md首次可以正常投影,后续撤销时却抛出unsafe projected path in manifest并中止启动;中文路径也会被该规则拒绝。这套逻辑作用于所有 projection-managed 文件,而非仅开启授权的调用,因此旧用户未启用授权也可能受影响。建议将路径边界验证与 shell 参数安全编码分开,支持既有合法路径,不能把合法文件名当作篡改清单。
位置:AbstractBaseSandbox.java:392-399。 -
[P2] 新增清单字段改变了既有公开构造器。
WorkspaceProjectionApplier.ProjectionPayload从三参数 record 改成四参数,原公开构造器消失。已用 javac 验证:原有new ProjectionPayload("hash", new byte[0], 0)在上轮版本可编译,在当前版本无法编译;已编译调用方也存在链接兼容风险。建议保留原有构造入口,或将新增内部元数据与既有公开契约分离。
位置:WorkspaceProjectionApplier.java:159-160。
从维护范围看,请特别注意:修复调用级授权不应无条件改变所有用户的通用 workspace 投影语义。撤销范围和启用条件需要清楚,保持未启用新授权时的兼容行为。
验证:本次运行 11 个相关测试类,共 150 项通过;另以实际 AbstractBaseSandbox 生命周期、本地 filesystem/shell 后端探针和 javac 编译探针验证上述问题。未运行全量测试或真实云端沙箱测试。
…it path validation from shell encoding Review round 3, scope rule: fixing the authorization boundary must not change the generic workspace projection semantics for everyone else. - WorkspaceProjectionEntry.authorizationManaged (transient): set only by the grant-aware narrowing in SandboxLifecycleMiddleware. Managed specs apply authoritatively (manifest-diff revocation, upgrade refusal when a hash exists without a manifest); unmanaged specs keep the historic overlay semantics — hydrate only, never delete, never refuse. An unmanaged content change invalidates the recorded manifest so a later managed pass cannot under-revoke against stale bookkeeping. - Path validation now checks boundaries only (absolute, ./.. segments, backslash, NUL); every legal filename — spaces, unicode, shell metacharacters — round-trips. Command safety moved to POSIX single-quote escaping (shellQuote), so legal resource names can no longer break subsequent starts (previously rejected by the charset whitelist, affecting users who never enabled authorization). - ProjectionPayload regains the public three-argument constructor (paths default empty) for source and binary compatibility. - Tests: unmanaged overlay semantics, legacy-state refusal (unchanged projection still runs), manifest invalidation on unmanaged change, legal-filename round-trip, boundary rejections, compat constructor.
…ting missing bookkeeping Three independent audits (security/compat/correctness) converged on one root cause: a missing revocation manifest was treated as 'nothing to revoke' whenever the hash was null too, so the resume-failure fallback (fresh state + carried-over snapshot), entry-less specs and pre-manifest upgrades all failed open. - managed pass without a manifest now REBUILDS: wipes the managed namespaces (new revokeRoots on WorkspaceProjectionEntry, set by the grant-aware narrowing to the .skills-cache tree) via doDeleteWorkspaceRoots (recursive by design, but on validated spec-declared roots only, quoted and fail-closed), then re-projects and records a fresh manifest — no stale file of any earlier era survives, no user-facing refusal - marked entry without revokeRoots fails closed (cannot be made safe) - unmanaged pass without a projection entry leaves all bookkeeping untouched (the diff baseline survives); the workspace-root probe is now shell-quoted - cache-root matching tolerates variant spellings (./x, x/) so narrowing is never silently disabled; a WARN fires when the projection-aware callback cannot narrow the sandbox - authorizationManaged is @JsonIgnore (per-call runtime intent); ProjectionPayload keeps the 3-arg constructor (source/binary compat) - tests: rebuild scenarios replace refusals (legacy state, unmanaged overlay, resume carry-over), force pinned by an unchanged-spec restore, apostrophe filenames via a POSIX-accurate fake operand parser, chunk-boundary and trailing/duplicate-slash rejections
Second independent audit round (compliance / regression / integration) converged on residual issues; all fixed here: - force revived with real semantics: a managed snapshot restore never hash-skips and always rebuilds — restored archives are untrusted events (persist-order skew, concurrent last-write-wins, backend snapshot rebinding can leave wider-era content no bookkeeping describes). The parameter had become dead in 9fa7d54, which both auditors and a maintainer-replay audit flagged; docs and the start() comment now match the behavior, and the restore test pins it with an intact manifest (deleting force turns it red) - managed semantics gated on authorization being engaged (a restricted capability surface on the call context): stager presence alone no longer enables revocation/rebuild — deployments that never enable the grant layer keep the generic overlay projection semantics entirely - .skills-cache declared an exclusively managed namespace (javadoc) and a test pins that rebuild clears foreign files there on purpose - narrowed projection entry now copies the inherited ephemeral flag - cache-root matching normalized via Path comparison (interior // and . variants no longer silently disable narrowing); the no-cache-entry log demoted to debug when the grant list is empty; a WARN fires when grant narrowing is derived for an external-sandbox context (silently discarded by the external acquire priorities) - revokeRoots is @JsonIgnore like the marker (per-call runtime intent) - external-sandbox semantics documented on SandboxContext - tests: legacy manifest-less state narrowed to empty (the reviewer's literal probe), foreign-file ownership, marker gating in the middleware; the fake's tar writer pins UTF-8 entry names to match the extractor (with the applier, whose tar output is now UTF-8 too)
…ON shape, comment) - force rebuilds log mode=rebuild (was mislabeled diff) - isCacheRoot treats platform-illegal root spellings as a non-match instead of an InvalidPathException failing the call - projectedWorkspacePaths is @JsonInclude(NON_NULL): deployments that never engage the grant layer keep the exact pre-grant persisted-state shape (removes the rollback-deserialization hazard for them) - narrowing comment states its provenance accurately (the maintainer-requested per-call projection constraint), not 'historic behaviour'
…stale javadoc Same class as the projection-tar fix: this archive is extracted container-side where tar decodes names as UTF-8, so the platform default mangles non-ASCII paths on non-UTF-8 JVMs. Also fixes the acquireForCall javadoc that referenced a caller that does not exist. The GLOBAL isolation-scope state-slot sharing question is left for upstream (changing the slot key would alter existing sharing semantics).
… concurrency posture Fourth audit round (probe replay x2 + scope convergence): PROBE-1-PASS, PROBE-2-PASS, SCOPE-HELD. Closing the residual gaps: - SandboxProjectionStateShapeTest pins the serialization contract: a null manifest is omitted (grant-free persisted state keeps the exact pre-grant JSON shape, safe to roll back), a recorded manifest persists, and a projection entry never serializes the managed marker or revoke roots (per-call runtime intent; tampered persisted state can neither self-declare managed semantics nor inject revoke roots) - legal-filename test pins projected existence for every name - docs (zh/en): grant state is never persisted; grant-free rollbacks are shape-identical; grant-enabled downgrades degrade to WARN + workspace recreate; multi-instance deployments should configure a real execution guard (default Noop is last-write-wins)
|
三个问题均已修复,处理方式如下: [P1] 旧状态投影清单 — 采用您给出的"安全重建"选项:清单缺失时不再当作"无可撤销",而是清除受管命名空间(收窄接线随标记声明 [P1] 合法文件名 — 校验与编码已分离:路径校验只拒绝边界违规(绝对路径、 [P2] 构造器 — 三参构造器已恢复(委托 范围规则:撤销/重建/拒绝语义仅在调用带受限授权面时启用;未配置 resolver 的部署保持纯叠加投影——零删除、零拒绝,持久化 JSON 与旧版逐字段一致( |
juruoO-o
left a comment
There was a problem hiding this comment.
复审基于 44cf311112fe5b3956ea0cb4b61f09b7b4d78e81,此前提出的阻塞项已修复,本轮未发现新的合入阻塞。
已验证:静态 Skill 提示词和 loader schema 均按授权裁剪;直接使用动态 Skill 中间件保持旧行为;旧 workspace 缺失投影清单时,受限授权路径会安全重建受管缓存;空格、中文和撇号文件名可正确撤销;原有 null 参数调用和 ProjectionPayload 三参数构造器保持源码兼容,旧编译产物的构造器调用也通过验证。
修复范围已收敛:未启用授权时保持原来的叠加投影,不执行撤销删除;受限授权下才启用撤销和重建,独立探针确认受管目录外文件保持不变。
需求值得框架支持,当前设计与已有过滤机制、Permission 的职责关系已明确,实现状态可以接受。
验证:165 项定向测试通过;额外本地探针、源码/二进制兼容探针及 diff 检查通过;GitHub Linux/Windows 构建通过。未执行真实云端沙箱测试,外部自管沙箱和多实例并发需遵守文档中的约束。
Approve。
…m RuntimeContext grant-resolution (agentscope-ai#3500) alongside reload lever + per-scope entry-delivery dedup; loadSkillResourceImpl signature gains rc, scope, reload
… capability surface onto the version-contract architecture Merge main (capability-surface agentscope-ai#3500 + 4 unrelated fixes) into feat/skill-mirror-1-version-contract. Textual conflicts resolved in 5 files; grant-layer mounting points re-attached semantically: - DynamicSkillMiddleware: keep the branch rewrite (per-call box, version routing) as the skeleton; re-add applyCapabilityFilter from agentscope-ai#3500 adapted to the SkillEntry view (surface.allowsSkill(entry.skill)), mounted in reloadSkills after the filterVisible hook and before buildBox — surface absent = unchanged, present = grants filter, filter error = fail-closed empty set; empty result yields no box. Dropped the stale boxCache/signature tail (box cache is retired). - HarnessSkillMiddleware: keep agentscope-ai#3500 prestageForProjection / applyCapabilityFilter / catalog-install filtering and the branch mergeRepositories serving rules side by side; capability filter still runs after applySkillFilter at both prestage and install sites. - AgentSkill: unified seven-arg constructor (metadata, skillContent, resources, source, originDir, version, system); public six-arg (…, version) delegates system=false; Builder carries both fields and toBuilder/copy preserve both (system = grant bypass, version = provenance). - ReActAgent: capabilityResolver and skillVersionPolicy fields coexist; build-time ISE check (capabilityResolver × dynamicSkillsEnabled=false) and the call-entry surface funnel survive verbatim. - DynamicSkillMiddlewareTest: branch structure kept; the surface present/absent minimal smoke tests (restrictedSurfaceStillFiltersOn- DirectUse / directUseWithoutSurfaceKeepsVisibleSkills) cover agentscope-ai#3500 semantics; the routing test stubs the version-route primitives.
…rsion-contract serving rules (S4) Plain repositories are no longer enumerated without an explicit SkillFilter.only selection, so the agentscope-ai#3500 grant tests' plain stubs served an empty catalog (a serving-rule artifact, not an authorization one). The stubs now implement RuntimeContextSkillRepository with a per-request getAllSkills(ctx) — assertion semantics unchanged: - CapabilityGrantIntegrationTest.StubRepo: context-scoped; the same-name-merge fixture now uses two repositories (the documented later-wins merge is a cross-repository rule; the serving primitive is name-addressed within one repo), assertions untouched. - SystemCapabilityMarkerTest.EmptyRepo: implements the serving primitive getSkill(name, version); still serves nothing. - HarnessAgentCapabilityResolverTest.StubRepo, HarnessSkillMiddlewareGrantTest.StubRepo, SandboxLifecycleMiddlewareCallbackTest.StubSkillRepository: context-scoped so prestage/catalog paths enumerate them per request. §5.3 tripwire table green: core 171+23 (incl. ReActAgentHitlTest), harness 51.
… name (§4-S8) Audited both pages against the version-contract architecture after merging agentscope-ai#3500: no conflicting "box cache" / "getAllSkills" statements exist (the pages never mention them; per-call boxes and the no-enumeration serving rule leave the documented behaviors intact). One deliberate decision was missing and is now written down symmetrically in EN and ZH: one grant entry covers every VERSION of the name — PIN-anchored old versions, mirror-cache-resident historical versions and the current latest — because version references never participate in grant matching (per-version authorization is a future requirement, not a current behavior). docs npm test + validate green; broken-links reports the known local false positives (2230 across 328 files, pre-existing on this machine).
…of the ordering flake
GracefulShutdownManager.resetForTesting() restored state, requests, savers
and the monitor but not the config field, so any test that setConfig()s a
custom timeout (e.g. shutdownTimeoutSignal's 100ms) leaked it into every
later test sharing the singleton JVM — full-load runs then failed
StateAndConfigTests.defaultConfig (expected null, saw PT0.1S) whenever the
method order put it afterwards, while isolation runs passed. Resetting to
GracefulShutdownConfig.DEFAULT mirrors the initial state the method
already promises ("restores initial state") and kills the ordering
dependence at its root.
Diagnosed during the agentscope-ai#3500 merge self-check's full verify; reproduced
twice under -T1C full load, green in isolation before the fix, 51/51
after.
Address kernel-level failure modes found in bench trajectories so agents recover from bounded outputs, stale ownership and incomplete memory work instead of looping or losing facts. - RepeatedFailureGuard: initialize per invocation at ON_AGENT_STATE_READY and track ownership with a private InvocationToken that survives Core RuntimeContext copies; missing and ungranted tools stay indistinguishable. - ReActAgent/MiddlewareBase: deliver producer events and post-acting feedback to middleware consistently. - Shell: bounded capture with archive, raw digest and cancellation cleanup. - Subagents: dynamic snapshots, owner-registry gating and context-aware gateway exposure with materializer recovery. - Thread history pagination, memory_get long-line recovery, and memory commit veto for incomplete flush/consolidation. - Docs (EN/ZH) updated for middleware, harness architecture, context, filesystem, memory, session-log and subagent behavior. Constraint: Preserve agentscope-ai#3500 - missing vs ungranted tools indistinguishable Constraint: Kernel only; adapter, PI, H2/H3 and business rules untouched Rejected: Ctx-reference ownership | Core copies RuntimeContext mid-call Confidence: high Scope-risk: moderate Not-tested: Real Java 17 runtime (built with JDK 21, release 17) Not-tested: Windows/Linux, e2e group, GitSkillRepositoryTest, WeixinLiveSmokeTest Not-tested: Real model semantics for memory pipeline; historical bench replay
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.
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(...), 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.activatedGroups) — a session-level switch over already-granted capabilities; stacks independently with grant.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 anullsurface); its javadoc now recommends the 3-arg overload (getToolSchemas(activeGroups, requestConfig, surface), surface read from the rc viarc.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(...)ordynamicSkillsEnabled(false)) throwsIllegalStateException— 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 (
CapabilitySurfacequery methods); gates never re-derive authorization logic.CapabilityResolver(functional interface) computes pure whitelists fromRuntimeContext(userId), optionally per agent. Resolved once atcall()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.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; thereset_equipped_toolsenum and description are rebuilt from activatable groups only, so cut-off group names and descriptions do not leak.DynamicSkillMiddlewarefilters visible skills fail-closed (empty set on missing surface or filter error); the filtered list drives signature, box cache, prompt and loading alike.ToolExecutor.requireToolGranted(backend only)SkillToolFactoryconvergence point (allowsSkill(AgentSkill)— full decision incl. system bypass; the id-based overload remains the grant-set-only fallback)resetEquippedToolsImplisSystem()marking chain (@Toolannotation →ToolBase/ToolGroup/SkillToolGroup/AgentSkillbuilders, with copy/toBuilder retention) bypasses grant trimming; framework meta tools are marked; everysystem=trueregistration leaves an INFO audit trail.call()are trusted assembler code (the agent funnel always writes a surface); the same stance applies at read points and gates.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 (HarnessSkillMiddlewareprompt/catalog,load_skill_through_path, staging) observes the same surface; harness sub-agents reuse the inherited surface without re-resolving.Security properties
Known residual exposure
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 useskillRepositories(...).generate_responsestructured-output tool executes outside the executor (system-equivalent response mechanism).