fusion-plugins-ecosystem 0.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. fusion_plugins_ecosystem/__init__.py +137 -0
  2. fusion_plugins_ecosystem/agent_adapter.py +131 -0
  3. fusion_plugins_ecosystem/audit_events.py +144 -0
  4. fusion_plugins_ecosystem/builtin/__init__.py +4 -0
  5. fusion_plugins_ecosystem/builtin/caveman_compress.py +166 -0
  6. fusion_plugins_ecosystem/builtin/caveman_compress.tool.json +36 -0
  7. fusion_plugins_ecosystem/claude_adapter.py +74 -0
  8. fusion_plugins_ecosystem/claude_gateway.py +390 -0
  9. fusion_plugins_ecosystem/cluster_bridge.py +164 -0
  10. fusion_plugins_ecosystem/config.py +237 -0
  11. fusion_plugins_ecosystem/connector.py +658 -0
  12. fusion_plugins_ecosystem/connector_packs.py +316 -0
  13. fusion_plugins_ecosystem/console_app.py +423 -0
  14. fusion_plugins_ecosystem/desk_runtime.py +497 -0
  15. fusion_plugins_ecosystem/extensions_console.py +1922 -0
  16. fusion_plugins_ecosystem/hook_adapter.py +99 -0
  17. fusion_plugins_ecosystem/jsonrpc.py +815 -0
  18. fusion_plugins_ecosystem/lifecycle.py +656 -0
  19. fusion_plugins_ecosystem/logging_setup.py +116 -0
  20. fusion_plugins_ecosystem/marketplace.py +268 -0
  21. fusion_plugins_ecosystem/mcp_exporter.py +152 -0
  22. fusion_plugins_ecosystem/metrics.py +176 -0
  23. fusion_plugins_ecosystem/plugin_bundle.py +134 -0
  24. fusion_plugins_ecosystem/proctitle.py +38 -0
  25. fusion_plugins_ecosystem/registry.py +265 -0
  26. fusion_plugins_ecosystem/rest_connector.py +348 -0
  27. fusion_plugins_ecosystem/sandbox.py +577 -0
  28. fusion_plugins_ecosystem/schema.py +77 -0
  29. fusion_plugins_ecosystem/server.py +331 -0
  30. fusion_plugins_ecosystem/shell_registry.py +213 -0
  31. fusion_plugins_ecosystem/skill_adapter.py +225 -0
  32. fusion_plugins_ecosystem/token_meter.py +494 -0
  33. fusion_plugins_ecosystem/tool_manifest.py +241 -0
  34. fusion_plugins_ecosystem/transport.py +701 -0
  35. fusion_plugins_ecosystem/web/app.css +225 -0
  36. fusion_plugins_ecosystem/web/extensions.html +921 -0
  37. fusion_plugins_ecosystem/web/manifest.json +27 -0
  38. fusion_plugins_ecosystem/web/shell.js +98 -0
  39. fusion_plugins_ecosystem-0.10.0.dist-info/METADATA +698 -0
  40. fusion_plugins_ecosystem-0.10.0.dist-info/RECORD +44 -0
  41. fusion_plugins_ecosystem-0.10.0.dist-info/WHEEL +5 -0
  42. fusion_plugins_ecosystem-0.10.0.dist-info/entry_points.txt +3 -0
  43. fusion_plugins_ecosystem-0.10.0.dist-info/licenses/LICENSE +190 -0
  44. fusion_plugins_ecosystem-0.10.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,137 @@
1
+ """fusion-plugins-ecosystem — 基于 fusion-cowork 的插件生态上层模块。
2
+
3
+ 架构定位:fusion-cowork runtime 的子模块,负责插件注册、生命周期、
4
+ Claude 全链路适配。所有进程托管/权限/硬件调度仍由 fusion-cowork 统一提供。
5
+
6
+ Lazy Import 机制(与 fusion-cowork 一致):
7
+ - import fusion_plugins_ecosystem 保持快速
8
+ - 首次访问属性时自动加载对应模块
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ __version__ = "0.10.0"
14
+ __app_name__ = "Fusion-Plugins-Ecosystem"
15
+
16
+ # ── Lazy Import 注册表 ──
17
+ # 键:公开属性名,值:模块路径
18
+ _LAZY_IMPORTS: dict[str, str] = {
19
+ # 注册中心
20
+ "PluginRegistry": "fusion_plugins_ecosystem.registry",
21
+ "PluginManifest": "fusion_plugins_ecosystem.registry",
22
+ "PluginCapability": "fusion_plugins_ecosystem.registry",
23
+ "PluginCategory": "fusion_plugins_ecosystem.registry",
24
+ "PluginParam": "fusion_plugins_ecosystem.registry",
25
+ # Tool manifest interchange (issue #68)
26
+ "ToolManifest": "fusion_plugins_ecosystem.tool_manifest",
27
+ "ToolApiSpec": "fusion_plugins_ecosystem.tool_manifest",
28
+ "ToolManifestError": "fusion_plugins_ecosystem.tool_manifest",
29
+ "parse_tool_manifest": "fusion_plugins_ecosystem.tool_manifest",
30
+ "load_tool_manifest": "fusion_plugins_ecosystem.tool_manifest",
31
+ "manifest_to_mcp": "fusion_plugins_ecosystem.tool_manifest",
32
+ "manifest_from_mcp": "fusion_plugins_ecosystem.tool_manifest",
33
+ # 生命周期
34
+ "PluginLifecycle": "fusion_plugins_ecosystem.lifecycle",
35
+ "PluginState": "fusion_plugins_ecosystem.lifecycle",
36
+ # Token 计量
37
+ "TokenMeter": "fusion_plugins_ecosystem.token_meter",
38
+ "TokenRecord": "fusion_plugins_ecosystem.token_meter",
39
+ "TokenKind": "fusion_plugins_ecosystem.token_meter",
40
+ # Claude 适配
41
+ "ClaudeSkillAdapter": "fusion_plugins_ecosystem.claude_adapter",
42
+ "SkillAdapter": "fusion_plugins_ecosystem.skill_adapter",
43
+ "SkillBundle": "fusion_plugins_ecosystem.skill_adapter",
44
+ "AgentAdapter": "fusion_plugins_ecosystem.agent_adapter",
45
+ "PluginBundle": "fusion_plugins_ecosystem.plugin_bundle",
46
+ "PluginBundleGenerator": "fusion_plugins_ecosystem.plugin_bundle",
47
+ "HookAdapter": "fusion_plugins_ecosystem.hook_adapter",
48
+ "HookDef": "fusion_plugins_ecosystem.hook_adapter",
49
+ "HookEvent": "fusion_plugins_ecosystem.hook_adapter",
50
+ "MCPExporter": "fusion_plugins_ecosystem.mcp_exporter",
51
+ "ClaudeGateway": "fusion_plugins_ecosystem.claude_gateway",
52
+ "SubagentTask": "fusion_plugins_ecosystem.claude_gateway",
53
+ "CLAUDE_DESKTOP": "fusion_plugins_ecosystem.claude_gateway",
54
+ "CLAUDE_CODE": "fusion_plugins_ecosystem.claude_gateway",
55
+ "CLAUDE_WEB": "fusion_plugins_ecosystem.claude_gateway",
56
+ "CLAUDE_VOLCENGINE": "fusion_plugins_ecosystem.claude_gateway",
57
+ # Desk runtime
58
+ "DeskRuntime": "fusion_plugins_ecosystem.desk_runtime",
59
+ # 可观测性指标
60
+ "MetricsRegistry": "fusion_plugins_ecosystem.metrics",
61
+ # 集群分布式状态桥接(企业级多节点)
62
+ "cluster_bridge": "fusion_plugins_ecosystem.cluster_bridge",
63
+ # 外部 MCP 连接器框架 + 市场
64
+ "ConnectorRegistry": "fusion_plugins_ecosystem.connector",
65
+ "ConnectorPack": "fusion_plugins_ecosystem.connector",
66
+ "ConnectorToolSpec": "fusion_plugins_ecosystem.connector",
67
+ "ExternalMCPClient": "fusion_plugins_ecosystem.connector",
68
+ "RiskLevel": "fusion_plugins_ecosystem.connector",
69
+ # Extensions 控制台(issue #30 E3:声明式连接器 + MCP intake + 插件 tick)
70
+ "ExtensionsConsole": "fusion_plugins_ecosystem.extensions_console",
71
+ "rest_connector": "fusion_plugins_ecosystem.rest_connector",
72
+ # shell 模块注册(issue #30 验收补充:fusion-gateway 侧边栏入口)
73
+ "shell_registry": "fusion_plugins_ecosystem.shell_registry",
74
+ "proctitle": "fusion_plugins_ecosystem.proctitle",
75
+ "Marketplace": "fusion_plugins_ecosystem.marketplace",
76
+ "MarketplaceEntry": "fusion_plugins_ecosystem.marketplace",
77
+ # 配置
78
+ "EcosystemConfig": "fusion_plugins_ecosystem.config",
79
+ # Schema
80
+ "PluginParamType": "fusion_plugins_ecosystem.schema",
81
+ "SandboxMode": "fusion_plugins_ecosystem.schema",
82
+ "MCPAnnotations": "fusion_plugins_ecosystem.schema",
83
+ "AsyncMeasureContext": "fusion_plugins_ecosystem.token_meter",
84
+ # MCP Server
85
+ "MCPServer": "fusion_plugins_ecosystem.server",
86
+ "MCPHandler": "fusion_plugins_ecosystem.jsonrpc",
87
+ "StdioTransport": "fusion_plugins_ecosystem.transport",
88
+ "SSETransport": "fusion_plugins_ecosystem.transport",
89
+ "HTTPTransport": "fusion_plugins_ecosystem.transport",
90
+ "create_transport": "fusion_plugins_ecosystem.transport",
91
+ # Sandbox
92
+ "PluginSandbox": "fusion_plugins_ecosystem.sandbox",
93
+ "SandboxHealth": "fusion_plugins_ecosystem.sandbox",
94
+ "ResourceLimits": "fusion_plugins_ecosystem.sandbox",
95
+ }
96
+
97
+ _lazy_cache: dict[str, object] = {}
98
+
99
+
100
+ def __getattr__(name: str) -> object:
101
+ """延迟加载模块,仅在首次访问时导入。"""
102
+ if name in _lazy_cache:
103
+ return _lazy_cache[name]
104
+ if name in _LAZY_IMPORTS:
105
+ import importlib
106
+
107
+ mod_name = _LAZY_IMPORTS[name]
108
+ try:
109
+ mod = importlib.import_module(mod_name)
110
+ try:
111
+ obj = getattr(mod, name)
112
+ except AttributeError:
113
+ # 模块自身导出(如 cluster_bridge / rest_connector)
114
+ if mod_name.endswith("." + name):
115
+ _lazy_cache[name] = mod
116
+ return mod
117
+ raise
118
+ _lazy_cache[name] = obj
119
+ return obj
120
+ except (ImportError, AttributeError) as exc:
121
+ raise AttributeError(
122
+ f"module 'fusion_plugins_ecosystem' has no attribute {name!r} "
123
+ f"(lazy import {mod_name!r} failed: {exc})"
124
+ ) from None
125
+ raise AttributeError(f"module 'fusion_plugins_ecosystem' has no attribute {name!r}")
126
+
127
+
128
+ def __dir__() -> list[str]:
129
+ """列出所有可访问的属性。"""
130
+ return sorted(set([*dir(type("", (), {})), *__all__, *_LAZY_IMPORTS.keys()]))
131
+
132
+
133
+ __all__ = [
134
+ "__version__",
135
+ "__app_name__",
136
+ *_LAZY_IMPORTS.keys(),
137
+ ]
@@ -0,0 +1,131 @@
1
+ """Claude Code Agent 适配器。
2
+
3
+ 将具备 SUBAGENT 能力的 PluginManifest 导出为 Claude Code agent .md 文件,
4
+ 含 YAML frontmatter(name, description, model, color, tools)。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+
11
+ from fusion_plugins_ecosystem.registry import (
12
+ PluginCapability,
13
+ PluginCategory,
14
+ PluginManifest,
15
+ PluginRegistry,
16
+ )
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ _CATEGORY_COLORS: dict[PluginCategory, str] = {
21
+ PluginCategory.CODING_PLAN: "#4A90D9",
22
+ PluginCategory.CONTEXT_COMPRESS: "#7B68EE",
23
+ PluginCategory.MLX_INFERENCE: "#FF6B6B",
24
+ PluginCategory.TERMINAL_PROXY: "#FF8C00",
25
+ PluginCategory.FILE_INDEX: "#50C878",
26
+ PluginCategory.QUANTIZATION: "#E67E22",
27
+ PluginCategory.VISUAL_BACKEND: "#9B59B6",
28
+ PluginCategory.CUSTOM: "#95A5A6",
29
+ }
30
+
31
+ _CAPABILITY_TOOLS: dict[PluginCapability, str] = {
32
+ PluginCapability.MCP_TOOL: "mcp",
33
+ PluginCapability.CLAUDE_SKILL: "skill",
34
+ PluginCapability.SUBAGENT: "agent",
35
+ PluginCapability.FILE_ACCESS: "file_access",
36
+ PluginCapability.LONG_TASK: "long_task",
37
+ }
38
+
39
+
40
+ class AgentAdapter:
41
+ """插件 → Claude Code Agent .md 导出器。
42
+
43
+ 用法:
44
+ adapter = AgentAdapter(registry)
45
+ md = adapter.export_agent("my_agent_plugin")
46
+ all_agents = adapter.export_all()
47
+ """
48
+
49
+ def __init__(self, registry: PluginRegistry) -> None:
50
+ self._registry = registry
51
+
52
+ def export_agent(self, plugin_id: str) -> str | None:
53
+ manifest = self._registry.get(plugin_id)
54
+ if manifest is None:
55
+ logger.warning("agent_adapter: plugin %s not found", plugin_id)
56
+ return None
57
+ if PluginCapability.SUBAGENT not in manifest.capabilities:
58
+ logger.info(
59
+ "agent_adapter: %s lacks SUBAGENT capability, skipping", plugin_id
60
+ )
61
+ return None
62
+ return self._build_agent_md(manifest)
63
+
64
+ def export_all(self) -> list[str]:
65
+ agents: list[str] = []
66
+ for manifest in self._registry.list():
67
+ if PluginCapability.SUBAGENT not in manifest.capabilities:
68
+ continue
69
+ md = self._build_agent_md(manifest)
70
+ if md is not None:
71
+ agents.append(md)
72
+ return agents
73
+
74
+ def _build_agent_md(self, manifest: PluginManifest) -> str:
75
+ frontmatter = self._build_frontmatter(manifest)
76
+ body = self._build_agent_body(manifest)
77
+ return f"---\n{frontmatter}\n---\n\n{body}"
78
+
79
+ def _build_frontmatter(self, manifest: PluginManifest) -> str:
80
+ lines = [
81
+ f"name: {manifest.id}",
82
+ f"description: {self._escape_yaml(manifest.description)}",
83
+ "model: inherit",
84
+ f"color: {self._category_to_color(manifest.category)}",
85
+ ]
86
+ tools = self._capability_to_tools(manifest.capabilities)
87
+ if tools:
88
+ lines.append(f"tools: [{', '.join(tools)}]")
89
+ return "\n".join(lines)
90
+
91
+ def _build_agent_body(self, manifest: PluginManifest) -> str:
92
+ parts: list[str] = []
93
+ parts.append(f"# {manifest.name}\n")
94
+ parts.append(f"{manifest.description}\n")
95
+
96
+ if manifest.params:
97
+ parts.append("\n## Configuration\n")
98
+ for param in manifest.params:
99
+ req = " (required)" if param.required else ""
100
+ parts.append(
101
+ f"- **{param.name}** `{param.type.value}`{req}: {param.description}"
102
+ )
103
+
104
+ parts.append("\n## Behavior\n")
105
+ parts.append(
106
+ f"This agent wraps plugin `{manifest.id}` "
107
+ f"(v{manifest.version}, {manifest.category.value}). "
108
+ f"It executes the plugin entry point with the provided parameters."
109
+ )
110
+
111
+ return "\n".join(parts)
112
+
113
+ @staticmethod
114
+ def _category_to_color(category: PluginCategory) -> str:
115
+ return _CATEGORY_COLORS.get(category, "#95A5A6")
116
+
117
+ @staticmethod
118
+ def _capability_to_tools(capabilities: tuple[PluginCapability, ...]) -> list[str]:
119
+ tools: list[str] = []
120
+ for cap in capabilities:
121
+ tool_name = _CAPABILITY_TOOLS.get(cap)
122
+ if tool_name and tool_name not in tools:
123
+ tools.append(tool_name)
124
+ return tools
125
+
126
+ @staticmethod
127
+ def _escape_yaml(value: str) -> str:
128
+ if any(c in value for c in (":", "#", "'", '"', "\n")):
129
+ escaped = value.replace("'", "''")
130
+ return f"'{escaped}'"
131
+ return value
@@ -0,0 +1,144 @@
1
+ """能力操作审计事件流(issue #43 PC-3)。
2
+
3
+ hub 的 install / uninstall / OAuth 授权 / scope 策略变更事件写入
4
+ fusion-security 审计管道的 JSONL 落点(`~/.fusion_security/audit/audit_<tenant>.jsonl`,
5
+ 与 fusion_security.engine.tenant.audit.AuditLogger 同格式 — security#61
6
+ 审计工作台直接可检索),trace_id 串跨服务链路。
7
+
8
+ 只依赖文件契约,不 import fusion_security(跨工程零耦合)。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import logging
15
+ import os
16
+ import re
17
+ import time
18
+ import uuid
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ DEFAULT_TENANT = "system"
25
+
26
+ _TENANT_SAFE = re.compile(r"[^A-Za-z0-9._-]+")
27
+
28
+
29
+ def new_trace_id() -> str:
30
+ """跨服务链路 trace_id:fp-<uuid4 前 16 hex>。"""
31
+ return "fp-" + uuid.uuid4().hex[:16]
32
+
33
+
34
+ def _safe_tenant_slug(tenant_id: str) -> str:
35
+ slug = _TENANT_SAFE.sub("_", tenant_id or "").strip("._-")
36
+ return slug or "system"
37
+
38
+
39
+ def audit_log_dir() -> Path:
40
+ # 惰性读 env — import 时取值会让测试 monkeypatch 失效(事件漏进真实目录)
41
+ return Path(
42
+ os.environ.get(
43
+ "FUSION_PLUGIN_AUDIT_DIR",
44
+ str(Path.home() / ".fusion_security" / "audit"),
45
+ )
46
+ )
47
+
48
+
49
+ def _sink_enabled() -> bool:
50
+ # 关闭落盘(测试/离线场景):FUSION_PLUGIN_AUDIT_SINK=off
51
+ return os.environ.get("FUSION_PLUGIN_AUDIT_SINK", "on").lower() != "off"
52
+
53
+
54
+ def _default_tenant() -> str:
55
+ return os.environ.get("FUSION_PLUGIN_AUDIT_TENANT", DEFAULT_TENANT)
56
+
57
+
58
+ def emit(
59
+ action: str,
60
+ resource_type: str = "",
61
+ resource_id: str = "",
62
+ details: dict[str, Any] | None = None,
63
+ risk_level: str = "info",
64
+ trace_id: str = "",
65
+ actor: str = "hub-console",
66
+ tenant_id: str = "",
67
+ ) -> dict[str, Any]:
68
+ """追加一条审计事件(AuditEntry 同构 JSONL 行)。
69
+
70
+ 失败不拖垮业务流 — 审计落盘降级为告警日志。
71
+ """
72
+ entry = {
73
+ "action": action,
74
+ "actor": actor,
75
+ "tenant_id": tenant_id or _default_tenant(),
76
+ "resource_type": resource_type,
77
+ "resource_id": resource_id,
78
+ "details": details or {},
79
+ "timestamp": time.time(),
80
+ "ip_address": "",
81
+ "risk_level": risk_level,
82
+ "trace_id": trace_id or new_trace_id(),
83
+ }
84
+ if not _sink_enabled():
85
+ logger.debug("audit_events: sink off, drop %s %s", action, resource_id)
86
+ return entry
87
+ try:
88
+ path = audit_log_dir() / f"audit_{_safe_tenant_slug(entry['tenant_id'])}.jsonl"
89
+ path.parent.mkdir(parents=True, exist_ok=True)
90
+ with open(path, "a", encoding="utf-8") as f:
91
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
92
+ logger.info(
93
+ "audit_events: %s %s/%s risk=%s trace=%s",
94
+ action,
95
+ resource_type,
96
+ resource_id,
97
+ risk_level,
98
+ entry["trace_id"],
99
+ )
100
+ except OSError as exc:
101
+ logger.warning("audit_events: 审计落盘失败: %s", exc)
102
+ return entry
103
+
104
+
105
+ def query(
106
+ resource_id: str = "",
107
+ resource_type: str = "",
108
+ action: str = "",
109
+ actor: str = "",
110
+ trace_id: str = "",
111
+ limit: int = 100,
112
+ ) -> list[dict[str, Any]]:
113
+ """只读检索审计轨迹(逐行解析,缺字段兜底 — 对齐 audit_store._entry_from_line)。"""
114
+ hits: list[dict[str, Any]] = []
115
+ root = audit_log_dir()
116
+ if not root.is_dir():
117
+ return hits
118
+ files = sorted(root.glob("audit_*.jsonl"), reverse=True)
119
+ for path in files:
120
+ try:
121
+ lines = path.read_text(encoding="utf-8").splitlines()
122
+ except OSError:
123
+ continue
124
+ for line in reversed(lines):
125
+ try:
126
+ rec = json.loads(line)
127
+ except json.JSONDecodeError:
128
+ continue
129
+ if not isinstance(rec, dict) or not rec.get("action"):
130
+ continue
131
+ if resource_id and rec.get("resource_id") != resource_id:
132
+ continue
133
+ if resource_type and rec.get("resource_type") != resource_type:
134
+ continue
135
+ if action and rec.get("action") != action:
136
+ continue
137
+ if actor and rec.get("actor") != actor:
138
+ continue
139
+ if trace_id and rec.get("trace_id") != trace_id:
140
+ continue
141
+ hits.append(rec)
142
+ if len(hits) >= limit:
143
+ return hits
144
+ return hits
@@ -0,0 +1,4 @@
1
+ """内置插件包。
2
+
3
+ 对应 PRD「内置 caveman 等 token 压缩插件,默认挂载给 Claude 会话」。
4
+ """
@@ -0,0 +1,166 @@
1
+ """Caveman token 压缩插件(内置、默认挂载)。
2
+
3
+ 对应 PRD:
4
+ - 内置 caveman 等 token 压缩插件,默认挂载给 Claude 会话,降低 token 消耗
5
+ - 代码上下文压缩分类
6
+
7
+ 设计原则:
8
+ - 插件入口接受 (desk, params) 并返回 dict 结果
9
+ - 通过 PluginManifest 声明能力,由 ClaudeSkillAdapter / MCPExporter 自动转
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import re
16
+
17
+ from fusion_plugins_ecosystem import __version__ as _PKG_VERSION
18
+ from typing import Any
19
+
20
+ from fusion_plugins_ecosystem.registry import (
21
+ PluginCapability,
22
+ PluginCategory,
23
+ PluginManifest,
24
+ PluginParam,
25
+ )
26
+ from fusion_plugins_ecosystem.schema import PluginParamType
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ # ── 压缩策略 ──
32
+ # 简化的 caveman 风格压缩:去除冗余空白/注释,合并重复行
33
+ _COMMENT_RE = re.compile(r"^\s*(#|//|/\*|\*/)")
34
+ _URL_PREFIX_RE = re.compile(r"(https?://)")
35
+ _MULTI_BLANK_RE = re.compile(r"\n\s*\n\s*\n+")
36
+
37
+
38
+ def _compress_text(text: str, keep_comments: bool = False) -> str:
39
+ """对文本做 caveman 风格压缩。
40
+
41
+ Args:
42
+ text: 原始文本
43
+ keep_comments: 是否保留注释行
44
+
45
+ Returns:
46
+ 压缩后的文本
47
+ """
48
+ lines: list[str] = []
49
+ prev_blank = False
50
+ for line in text.splitlines():
51
+ stripped = line.strip()
52
+ # 注释处理:跳过注释行,但保留含 URL 的行
53
+ if not keep_comments and _COMMENT_RE.match(line):
54
+ if not _URL_PREFIX_RE.search(line):
55
+ continue
56
+ # 多个连续空行合并为一个
57
+ if not stripped:
58
+ if prev_blank:
59
+ continue
60
+ prev_blank = True
61
+ lines.append("")
62
+ continue
63
+ prev_blank = False
64
+ # 行内多空格合并
65
+ lines.append(re.sub(r"[ \t]{2,}", " ", line))
66
+ return "\n".join(lines).rstrip()
67
+
68
+
69
+ def caveman_compress(desk: Any, params: dict[str, Any]) -> dict[str, Any]:
70
+ """插件入口:对输入文本做 token 压缩。
71
+
72
+ Args (params):
73
+ text: 待压缩文本
74
+ keep_comments: 是否保留注释(默认 False)
75
+ strategy: 压缩策略(暂只支持 "caveman")
76
+
77
+ Returns:
78
+ {
79
+ "compressed": str, # 压缩结果
80
+ "original_chars": int, # 原始字符数
81
+ "compressed_chars": int, # 压缩后字符数
82
+ "ratio": float, # 压缩率(0-1)
83
+ "strategy": str,
84
+ }
85
+ """
86
+ text: str = params.get("text", "")
87
+ keep_comments_raw = params.get("keep_comments", False)
88
+ keep_comments: bool = keep_comments_raw is True or keep_comments_raw == "true"
89
+ strategy: str = params.get("strategy", "caveman")
90
+
91
+ if not text:
92
+ return {
93
+ "compressed": "",
94
+ "original_chars": 0,
95
+ "compressed_chars": 0,
96
+ "ratio": 0.0,
97
+ "strategy": strategy,
98
+ }
99
+
100
+ original_chars = len(text)
101
+ compressed = _compress_text(text, keep_comments=keep_comments)
102
+ compressed_chars = len(compressed)
103
+ ratio = compressed_chars / original_chars if original_chars > 0 else 0.0
104
+
105
+ # 通过 desk 统一日志(对应 PRD「插件日志统一汇总到 Desk」)
106
+ if desk is not None:
107
+ desk.log(
108
+ "caveman_compress",
109
+ "INFO",
110
+ "压缩完成",
111
+ original=original_chars,
112
+ compressed=compressed_chars,
113
+ ratio=ratio,
114
+ )
115
+
116
+ return {
117
+ "compressed": compressed,
118
+ "original_chars": original_chars,
119
+ "compressed_chars": compressed_chars,
120
+ "ratio": ratio,
121
+ "strategy": strategy,
122
+ }
123
+
124
+
125
+ # ── 插件清单 ──
126
+ CAVEMAN_MANIFEST = PluginManifest(
127
+ id="caveman_compress",
128
+ name="Caveman Token Compressor",
129
+ version=_PKG_VERSION,
130
+ category=PluginCategory.CONTEXT_COMPRESS,
131
+ description=(
132
+ "对输入文本做 caveman 风格 token 压缩:"
133
+ "去除冗余空白/注释,合并重复空行,降低 Claude 会话 token 消耗。"
134
+ ),
135
+ capabilities=(
136
+ PluginCapability.MCP_TOOL,
137
+ PluginCapability.CLAUDE_SKILL,
138
+ ),
139
+ params=(
140
+ PluginParam(
141
+ name="text",
142
+ type=PluginParamType.STRING,
143
+ description="待压缩的文本内容",
144
+ required=True,
145
+ ),
146
+ PluginParam(
147
+ name="keep_comments",
148
+ type=PluginParamType.BOOL,
149
+ description="是否保留注释行(默认 False,即移除注释)",
150
+ required=False,
151
+ default=False,
152
+ ),
153
+ PluginParam(
154
+ name="strategy",
155
+ type=PluginParamType.STRING,
156
+ description="压缩策略",
157
+ required=False,
158
+ default="caveman",
159
+ enum=("caveman",),
160
+ ),
161
+ ),
162
+ entry_point=caveman_compress,
163
+ default_mounted=True,
164
+ timeout_seconds=120,
165
+ vram_mb=0,
166
+ )
@@ -0,0 +1,36 @@
1
+ {
2
+ "identifier": "caveman_compress",
3
+ "meta": {
4
+ "name": "Caveman Token Compressor",
5
+ "description": "Caveman-style token compression for input text: strips redundant whitespace/comments, merges repeated blank lines, cuts Claude session token usage.",
6
+ "version": "0.10.0"
7
+ },
8
+ "api": [
9
+ {
10
+ "name": "compress",
11
+ "description": "Compress text caveman-style; returns the compressed text plus savings stats.",
12
+ "parameters": {
13
+ "type": "object",
14
+ "properties": {
15
+ "text": {
16
+ "type": "string",
17
+ "description": "Text to compress"
18
+ },
19
+ "keep_comments": {
20
+ "type": "boolean",
21
+ "description": "Keep comment lines (default false)",
22
+ "default": false
23
+ },
24
+ "strategy": {
25
+ "type": "string",
26
+ "description": "Compression strategy",
27
+ "enum": ["caveman"],
28
+ "default": "caveman"
29
+ }
30
+ },
31
+ "required": ["text"]
32
+ }
33
+ }
34
+ ],
35
+ "systemRole": "You compress text caveman-style: drop articles, filler and pleasantries; keep all technical substance, code and identifiers verbatim. Never invent abbreviations that save no tokens."
36
+ }