JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(skill): correct dynamic approval behavior
huben8c432b59af1f
diff --git a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.pyindex 0f6dfb94be..1273bfef97 100644--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py@@ -69,17 +69,11 @@ def _has_active_skill_overlay() -> bool:判定失败按存在处理(返回 True,强制回落 engine),不放宽权限。"""try:- from jiuwenswarm.agents.harness.common.rails.permissions.config_loader import (- get_effective_permissions_config,- )from openjiuwen.harness.security.skill_authorization import (get_skill_authorization_context,get_skill_grant_store,- is_skill_authorization_enabled,)- if not is_skill_authorization_enabled(get_effective_permissions_config()):- return Falseauthz = get_skill_authorization_context()if authz is None or not authz.session_id or not authz.agent_scope_id:return Falsediff --git a/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization_permission_rail.py b/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization_permission_rail.pyindex afebc1894f..2eadc8b72f 100644--- a/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization_permission_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization_permission_rail.py@@ -15,6 +15,7 @@ resume 答案。openjiuwen 解析失败会再弹 ``匹配规则: N/A`` 的卡,from __future__ import annotations+import copyimport loggingfrom typing import Any, Optional@@ -34,6 +35,21 @@ def is_unparseable_permission_resume_text(user_input: Any) -> bool:return PermissionInterruptRail.parse_confirm_payload(user_input) is None+def _compose_active_skill_permissions(+ base_config: dict[str, Any],+ session_id: str,+ agent_scope_id: str,+ grant_store: Any,+) -> dict[str, Any]:+ """Compose the active Skill overlay into one permission snapshot."""+ from openjiuwen.harness.security.skill_authorization import compose_skill_permissions++ active = grant_store.get_active(session_id, agent_scope_id)+ if active is None or not active.overlay_snapshot:+ return copy.deepcopy(base_config)+ return compose_skill_permissions(base_config, active.overlay_snapshot)++class SkillAuthorizationPermissionRail(PermissionInterruptRail):"""PermissionInterruptRail 子类:Skill 门禁已裁决的调用跳过权限 Rail。"""@@ -61,6 +77,40 @@ class SkillAuthorizationPermissionRail(PermissionInterruptRail):ctx, tool_call, user_input, auto_confirm_config)+ def _refresh_permissions_for_tool_call(self, ctx: AgentCallbackContext) -> None:+ """Apply the active Skill overlay without mutating the static baseline."""+ from openjiuwen.harness.security.skill_authorization import (+ get_skill_authorization_context,+ get_skill_grant_store,+ )++ authorization = get_skill_authorization_context()+ if (+ authorization is None+ or not authorization.session_id+ or not authorization.agent_scope_id+ ):+ super()._refresh_permissions_for_tool_call(ctx)+ return+ grant_store = get_skill_grant_store()+ active = grant_store.get_active(+ authorization.session_id,+ authorization.agent_scope_id,+ )+ if active is None:+ super()._refresh_permissions_for_tool_call(ctx)+ return+ base_config = super()._get_permissions_snapshot(ctx)+ if base_config is None:+ base_config = self._static_config+ effective_config = _compose_active_skill_permissions(+ base_config,+ authorization.session_id,+ authorization.agent_scope_id,+ grant_store,+ )+ self._engine.update_config(effective_config)+def _skill_authorization_gate_handled(self, ctx: AgentCallbackContext) -> bool:"""本次 skill_tool/skill_complete 是否已被动态授权门禁接管。"""inputs = getattr(ctx, "inputs", None)diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillApprovalCard.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillApprovalCard.tsxindex c75c2b429b..7e6e1747a5 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillApprovalCard.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillApprovalCard.tsx@@ -21,15 +21,18 @@ import { useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import ReactMarkdown from 'react-markdown';import remarkGfm from 'remark-gfm';+import { isEnterprise } from '../../edition';import { webRequest } from '../../services/webClient';import { useChatStore } from '../../stores';import type { SkillApprovalAction, SkillApprovalCardPayload } from '../../types';import { shouldUnlockPendingApproval } from '../InteractionSlot/interactionSubmission';import {buildSkillSourceDisplayNameMap,+ buildSkillSourceTypeMap,resolveSkillSourceDisplayName,- shouldShowSkillTrustBadge,+ resolveSkillTrustBadge,type SkillSourceDisplayNames,+ type SkillSourceTypes,} from './skillApprovalPresentation';interface SkillApprovalCardProps {@@ -49,6 +52,7 @@ const ACTION_WIRE_LABELS: Record<SkillApprovalAction, string> = {};const sourceDisplayNameRequests = new Map<string, Promise<SkillSourceDisplayNames>>();+const sourceTypeRequests = new Map<string, Promise<SkillSourceTypes>>();function fetchSkillSourceDisplayNames(sessionId: string): Promise<SkillSourceDisplayNames> {const cached = sourceDisplayNameRequests.get(sessionId);@@ -67,6 +71,26 @@ function fetchSkillSourceDisplayNames(sessionId: string): Promise<SkillSourceDisreturn request;}+function fetchSkillSourceTypes(sessionId: string): Promise<SkillSourceTypes> {+ const inflight = sourceTypeRequests.get(sessionId);+ if (inflight) return inflight;++ const request = (async () => {+ try {+ const response = await webRequest<{+ skills?: Array<{ name?: unknown; skill_name?: unknown; source_type?: unknown }>;+ }>('skills.enterprise.list', { session_id: sessionId });+ return buildSkillSourceTypeMap(response.skills);+ } catch {+ return new Map<string, string>();+ } finally {+ sourceTypeRequests.delete(sessionId);+ }+ })();+ sourceTypeRequests.set(sessionId, request);+ return request;+}+/** 来源路径截断:只保留末尾两段,完整路径交给 title 悬停。 */function truncateSource(source: string): string {const parts = source.split(/[\\/]/).filter(Boolean);@@ -103,8 +127,14 @@ export function SkillApprovalCard({ onSubmit, card }: SkillApprovalCardProps) {const { t } = useTranslation();const activeSessionId = useChatStore(s => s.activeSessionId);const pendingQuestion = useChatStore(s => s.runtimes[activeSessionId ?? '']?.pendingQuestion ?? null);+ const approvalSkillName = card?.skill_name.trim() ?? '';const [submitted, setSubmitted] = useState(false);const [sourceDisplayName, setSourceDisplayName] = useState(card?.source ?? '');+ const [sourceTypeLookup, setSourceTypeLookup] = useState<{+ skillName: string;+ sourceType?: string;+ complete: boolean;+ }>({ skillName: '', complete: false });useEffect(() => {const sourceId = card?.source.trim() ?? '';@@ -120,6 +150,29 @@ export function SkillApprovalCard({ onSubmit, card }: SkillApprovalCardProps) {};}, [activeSessionId, card?.source, card?.trust]);+ useEffect(() => {+ const skillName = approvalSkillName;+ setSourceTypeLookup({ skillName, complete: false });+ if (!isEnterprise() || !skillName || !activeSessionId || card?.trust !== 'builtin') {+ setSourceTypeLookup({ skillName, complete: true });+ return undefined;+ }++ let active = true;+ void fetchSkillSourceTypes(activeSessionId).then(sourceTypes => {+ if (active) {+ setSourceTypeLookup({+ skillName,+ sourceType: sourceTypes.get(skillName),+ complete: true,+ });+ }+ });+ return () => {+ active = false;+ };+ }, [activeSessionId, approvalSkillName, card?.trust]);+const question = pendingQuestion?.questions[0];const availableActions = useMemo((): SkillApprovalAction[] => {if (card) return card.actions;@@ -157,7 +210,12 @@ export function SkillApprovalCard({ onSubmit, card }: SkillApprovalCardProps) {return null;}- const showTrustBadge = shouldShowSkillTrustBadge(card?.trust);+ const sourceTypeResolved =+ !isEnterprise() ||+ (sourceTypeLookup.skillName === approvalSkillName && sourceTypeLookup.complete);+ const trustBadge = sourceTypeResolved+ ? resolveSkillTrustBadge(card?.trust, sourceTypeLookup.sourceType)+ : null;const versionLabel = card?.version || t('chatUi.skillApproval.versionLocal');const cachedDecisionLabel = card?.cached_decision === 'session' ? t('chatUi.skillApproval.cachedSession') : t('chatUi.skillApproval.cachedLocal');@@ -215,7 +273,7 @@ export function SkillApprovalCard({ onSubmit, card }: SkillApprovalCardProps) {{t('chatUi.skillApproval.title')}{card ? `:${card.skill_name}` : ''}</span>- {card && showTrustBadge && (+ {card && trustBadge && (<spanclassName="text-[10px] px-1.5 py-0.5 rounded"style={{@@ -223,7 +281,11 @@ export function SkillApprovalCard({ onSubmit, card }: SkillApprovalCardProps) {border: '1px solid var(--color-feedback-success)',}}>- {t('chatUi.skillApproval.trustBuiltin')}+ {t(+ trustBadge === 'prebuilt'+ ? 'chatUi.skillApproval.trustPrebuilt'+ : 'chatUi.skillApproval.trustBuiltin',+ )}</span>)}</div>diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/skillApprovalPresentation.ts b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/skillApprovalPresentation.tsindex 30e1a0c059..23c044299e 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/skillApprovalPresentation.ts+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/skillApprovalPresentation.ts@@ -1,10 +1,18 @@export type SkillSourceDisplayNames = ReadonlyMap<string, string>;+export type SkillSourceTypes = ReadonlyMap<string, string>;+export type SkillTrustBadge = 'builtin' | 'prebuilt' | null;type SkillSourceProviderSummary = {source_id?: unknown;display_name?: unknown;};+type SkillInstallationSummary = {+ name?: unknown;+ skill_name?: unknown;+ source_type?: unknown;+};+export function buildSkillSourceDisplayNameMap(providers: readonly SkillSourceProviderSummary[] | undefined,): SkillSourceDisplayNames {@@ -24,6 +32,24 @@ export function resolveSkillSourceDisplayName(return displayNames.get(sourceId) || sourceId;}-export function shouldShowSkillTrustBadge(trust: string | undefined): boolean {- return trust === 'builtin';+export function buildSkillSourceTypeMap(+ skills: readonly SkillInstallationSummary[] | undefined,+): SkillSourceTypes {+ const sourceTypes = new Map<string, string>();+ for (const skill of skills ?? []) {+ const rawName = skill.name ?? skill.skill_name;+ const name = typeof rawName === 'string' ? rawName.trim() : '';+ const sourceType =+ typeof skill.source_type === 'string' ? skill.source_type.trim().toLowerCase() : '';+ if (name && sourceType) sourceTypes.set(name, sourceType);+ }+ return sourceTypes;+}++export function resolveSkillTrustBadge(+ trust: string | undefined,+ sourceType: string | undefined,+): SkillTrustBadge {+ if (trust !== 'builtin') return null;+ return sourceType?.trim().toLowerCase() === 'prebuilt' ? 'prebuilt' : 'builtin';}diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex d36e62ebc3..7c9c3ac65b 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -2343,6 +2343,7 @@"skillApproval": {"title": "Skill load approval","trustBuiltin": "builtin",+ "trustPrebuilt": "enterprise prebuilt","versionLocal": "local (no version)","source": "Source","version": "Version",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex f41bab0027..09cd5fcc11 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -2330,6 +2330,7 @@"skillApproval": {"title": "Skill 加载审批","trustBuiltin": "内置",+ "trustPrebuilt": "企业预置","versionLocal": "本地(无版本)","source": "来源","version": "版本",diff --git a/jiuwenswarm/channels/web/frontend/tests/skillApprovalPresentation.test.mjs b/jiuwenswarm/channels/web/frontend/tests/skillApprovalPresentation.test.mjsindex 4172851b51..2fe0166959 100644--- a/jiuwenswarm/channels/web/frontend/tests/skillApprovalPresentation.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/skillApprovalPresentation.test.mjs@@ -3,8 +3,9 @@ import test from 'node:test';import {buildSkillSourceDisplayNameMap,+ buildSkillSourceTypeMap,+ resolveSkillTrustBadge,resolveSkillSourceDisplayName,- shouldShowSkillTrustBadge,} from '../node_modules/.cache/skill-approval-presentation/components/ChatPanel/skillApprovalPresentation.js';test('registered source display name is used without changing its source id', () => {@@ -27,7 +28,28 @@ test('blank source display name falls back to the stable source id', () => {assert.equal(resolveSkillSourceDisplayName('customer-source', displayNames), 'customer-source');});-test('only builtin skills display a trust badge', () => {- assert.equal(shouldShowSkillTrustBadge('builtin'), true);- assert.equal(shouldShowSkillTrustBadge('other'), false);+test('enterprise prebuilt skill displays the enterprise prebuilt badge', () => {+ const sourceTypes = buildSkillSourceTypeMap([+ { name: 'enterprise-probe', source_type: 'prebuilt' },+ ]);++ assert.equal(resolveSkillTrustBadge('builtin', sourceTypes.get('enterprise-probe')), 'prebuilt');+});++test('repository builtin skill keeps the builtin badge', () => {+ assert.equal(resolveSkillTrustBadge('builtin', undefined), 'builtin');+});++test('untrusted skill does not display a trust badge', () => {+ assert.equal(resolveSkillTrustBadge('other', 'user'), null);+});++test('blank installation identity is ignored when building source types', () => {+ const sourceTypes = buildSkillSourceTypeMap([+ { name: ' enterprise-probe ', source_type: ' prebuilt ' },+ { name: ' ', source_type: 'prebuilt' },+ ]);++ assert.equal(sourceTypes.get('enterprise-probe'), 'prebuilt');+ assert.equal(sourceTypes.size, 1);});diff --git a/tests/unit_tests/agentserver/test_enterprise_config_reload_cache.py b/tests/unit_tests/agentserver/test_enterprise_config_reload_cache.pyindex c7407c186e..1174e0b0ec 100644--- a/tests/unit_tests/agentserver/test_enterprise_config_reload_cache.py+++ b/tests/unit_tests/agentserver/test_enterprise_config_reload_cache.py@@ -102,6 +102,7 @@ def test_skill_authorization_rail_uses_agent_template_without_request_context() -> None:from jiuwenswarm.server.runtime.agent_adapter import interface_deep+ monkeypatch.setenv("SKILL_AUTHORIZATION_ENABLED", "false")monkeypatch.setattr(interface_deep,"get_effective_permissions_config",diff --git a/uv.lock b/uv.lockindex 9af2f5723b..6f8ce83dc8 100644--- a/uv.lock+++ b/uv.lock@@ -3292,7 +3292,7 @@ wheels = [[[package]]name = "openjiuwen"version = "0.1.16"-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=dev-stable#f55d37f299ecb7d3658e910a5594b692481b7738" }+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=dev-stable#b3a263b709c32498db0f3c5e09018247d17bcc09" }dependencies = [{ name = "aiofiles" },{ name = "aiohttp" },