@agy-daddy/plugin-context 1.0.0 → 1.1.2

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.
package/README.md CHANGED
@@ -1,14 +1,100 @@
1
1
  # @agy-daddy/plugin-context
2
2
 
3
- Agy-Daddy Layer-2 官方插件:顶栏上下文圆环与测速、详情与附件审计浮窗、底部 Pulse 实时能量胶囊。
3
+ Agy-Daddy 官方 Layer 2 上下文监测插件:上下文环、审计面板、附件检查器与输入框实时脉冲胶囊。
4
4
 
5
- ## 提供能力
6
- - 服务:`context`(Node 域:`getSnapshot`、`rescan`、`getRecentCalls`、`auditAttachments`、`getMobileSnapshot`)与 `context-ui`(主世界域)
7
- - 事件:`telemetry:generator-calls@1`(按 `callId` 去重供 `usage` 等消费者入账与延迟补拉)
8
- - 状态:`state:context.snapshot@1`
9
- - 可选消费:`usage.estimateCallsCost()`(未安装 `usage` 时安全降级)
5
+ - **npm 包名**:`@agy-daddy/plugin-context`
6
+ - **Layer 层级**:Layer 2(会话洞察与监控层)
7
+ - **信任等级**:官方 `T0`(声明 `dom:read`、`dom:write`、`rpc:read`、`fs:brain-read`、`bridge:route`、`native:install` 权限)
8
+ - **适用场景**:实时监测对话 Token 上下文大小、预警 240K/328K 提示缓存断崖,以及输入框生成速度与附件审计。
10
9
 
11
- ## 测试
10
+ ---
11
+
12
+ ## 核心功能与安全默认值
13
+
14
+ - **实时上下文环与速率脉冲**:实时计算当前会话的总 Token 占用与生成速率(~tok/s),支持在输入框下方或顶栏展示动态环形指示器。
15
+ - **缓存断崖梯级预警**:支持 240K 预警与 328K 断崖阈值,自动标记超限风险,预防上下文溢出。
16
+ - **附件审计面板**:就近弹出详情面板,清晰呈现历史轮次、Prompt Cache 命中率及附件大小。
17
+ - **安全默认值**:
18
+ - `compactPolicy: "remind"`:默认仅提醒,绝不在用户输入中或模型生成时强行中断会话;
19
+ - `autoCompactOnCacheDrop: false`:默认关闭丢缓存强制压缩,必须由用户自主配置。
20
+
21
+ ---
22
+
23
+ ## 安装与启用方式
24
+
25
+ ### 1. 随官方全量安装
26
+ ```sh
27
+ agy-daddy plugin install --official
28
+ ```
29
+
30
+ ### 2. 单独安装
31
+ ```sh
32
+ agy-daddy plugin install npm:@agy-daddy/plugin-context
33
+ ```
34
+
35
+ ### 3. 宿主设置中心与顶栏/输入框交互
36
+ 安装后自动激活(`onStartup`)。默认在输入框下方挂载上下文脉冲胶囊,或在顶栏(order: 10)挂载环形图元。点击就近弹出审计面板,亦可在设置中心「上下文与实时速度」进行策略定制。
37
+
38
+ ---
39
+
40
+ ## 配置项说明表
41
+
42
+ 对照 `settings.schema.json`:
43
+
44
+ | Key | 类型 | 默认值 | 说明 |
45
+ |---|---|---|---|
46
+ | `displayLocation` | `enum` | `"composer"` | 胶囊显示位置:二选一:`composer`(仅在输入框下方)或 `topbar`(仅在顶栏显示实时胶囊),点击就近弹出详情面板 |
47
+ | `showSpeed` | `boolean` | `true` | 显示生成速度:在胶囊中实时显示流式估算速率 (~tok/s) 及完成后的精确速率 |
48
+ | `showCost` | `boolean` | `true` | 显示会话参考成本:在胶囊与详情面板中展示当前会话预估 API 参考费用(需启用用量插件;未启用时自动隐藏) |
49
+ | `pollIntervalMs` | `number` | `3000` | 轮询采样间隔:定期读取当前会话记录并重算 Token 构成的时间间隔(毫秒) |
50
+ | `warnThreshold` | `string` | `"240K"` | 预警阈值:支持绝对值(如 240K / 240000)或窗口百分比(如 50%);达到后胶囊变橙提醒 |
51
+ | `cliffThreshold` | `string` | `"328K"` | 断崖阈值:支持绝对值(如 328K / 328000)或窗口百分比(如 70%);达到后标记高风险断崖 |
52
+ | `compactPolicy` | `enum` | `"remind"` | 压缩触发策略:可选 `remind`(仅提醒)、`suggest`(空闲显示一键压缩)、`auto`(达断崖等本步结束自动发 /compact)、`both`(A+B 同时开启) |
53
+ | `autoCompactOnCacheDrop` | `boolean` | `false` | 丢缓存强行触发压缩:开启后若检测到缓存断崖且处于空闲状态,强制触发压缩提示 |
54
+
55
+ ### 声明式操作(Actions)
56
+ - **立即重新扫描会话 (`rescan`)**:触发命令 `context.rescan`。
57
+
58
+ ---
59
+
60
+ ## 提供的服务 / 事件 / 命令 / 扩展位
61
+
62
+ 严格依据 `agy-plugin.json` 声明:
63
+
64
+ - **Permissions**:`dom:read`、`dom:write`、`rpc:read`、`fs:brain-read`、`bridge:route`、`native:install`
65
+ - **Requires Anchors**:
66
+ - `topbar.rightCluster`:顶栏右侧集群锚点(用于挂载顶栏上下文环)
67
+ - `composer.root`:输入框根容器锚点(用于挂载输入框脉冲胶囊)
68
+ - **Services (provides)**:
69
+ - `context`(版本 `1.0.0`,realm: `node`)
70
+ - `context-ui`(版本 `1.0.0`,realm: `page-isolated`)
71
+ - **Consumes Services**:
72
+ - `usage`(版本 `^1.0.0`,optional: `true`)
73
+ - **Events (provides)**:
74
+ - `telemetry:generator-calls@1`:生成器调用遥测事件
75
+ - `context:auto-compact-triggered@1`:自动压缩触发事件
76
+ - **States (provides)**:
77
+ - `state:context.snapshot@1`:上下文快照状态
78
+ - **Commands (contributes)**:
79
+ - `context.rescan`:重新扫描会话
80
+ - **Topbar Units & Popovers (contributes)**:
81
+ - Topbar Unit: `ring`(order: `10`)
82
+ - Topbar Popover: `context-panel`(anchorId: `ring`)
83
+ - **Remote Panels (contributes["remote.panels"])**:
84
+ - `context`(绑定服务 `context`,为移动端 PWA 远程面板提供上下文快照)
85
+ - **Native Extension (contributes.native)**:
86
+ - MCP 服务器配置:`./native/mcp.json`(向宿主注入上下文治理 MCP 工具)
87
+ - Skills 技能目录:`./native/skills`(注入 context-governance 技能包)
88
+
89
+ ---
90
+
91
+ ## 使用示例与本地测试
92
+
93
+ ### 使用示例
94
+ 在长会话编码过程中,输入框下方的实时胶囊会动态变色(绿色正常、橙色预警、红色危险)并展示生成速度。当上下文接近 240K 时点击胶囊,审计面板会列出附件占比及各轮次 Token 消耗,方便针对性精简。
95
+
96
+ ### 本地测试
97
+ 在插件目录下执行自动化单元测试:
12
98
  ```sh
13
99
  npm test
14
100
  ```
package/agy-plugin.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "schemaVersion": 1,
3
3
  "id": "agy-daddy.context",
4
4
  "publisher": "agy-daddy",
5
- "version": "1.0.0",
5
+ "version": "1.1.2",
6
6
  "license": "MIT",
7
7
  "displayName": {
8
8
  "zh-CN": "上下文与实时速度",
@@ -19,20 +19,40 @@
19
19
  "main": "./src/node.js",
20
20
  "renderer": "./src/renderer.js",
21
21
  "world": "isolated",
22
- "activationEvents": ["onStartup"],
22
+ "activationEvents": [
23
+ "onStartup"
24
+ ],
23
25
  "requires": {
24
- "anchors": ["topbar.rightCluster", "composer.root"]
26
+ "anchors": [
27
+ "topbar.rightCluster",
28
+ "composer.root"
29
+ ]
25
30
  },
26
31
  "provides": {
27
32
  "services": {
28
- "context": { "version": "1.0.0", "realm": "node" },
29
- "context-ui": { "version": "1.0.0", "realm": "page-isolated" }
33
+ "context": {
34
+ "version": "1.0.0",
35
+ "realm": "node"
36
+ },
37
+ "context-ui": {
38
+ "version": "1.0.0",
39
+ "realm": "page-isolated"
40
+ }
30
41
  },
31
- "events": ["telemetry:generator-calls@1", "context:auto-compact-triggered@1"],
32
- "states": ["state:context.snapshot@1"]
42
+ "events": [
43
+ "telemetry:generator-calls@1",
44
+ "context:auto-compact-triggered@1"
45
+ ],
46
+ "states": [
47
+ "state:context.snapshot@1",
48
+ "state:context.live@1"
49
+ ]
33
50
  },
34
51
  "consumes": {
35
- "usage": { "version": "^1.0.0", "optional": true }
52
+ "usage": {
53
+ "version": "^1.0.0",
54
+ "optional": true
55
+ }
36
56
  },
37
57
  "permissions": [
38
58
  "dom:read",
@@ -43,16 +63,41 @@
43
63
  "native:install"
44
64
  ],
45
65
  "contributes": {
46
- "topbar.units": [{ "id": "ring", "order": 10 }],
47
- "topbar.popovers": [{ "id": "context-panel", "anchorId": "ring" }],
48
- "settings": { "schema": "./settings.schema.json" },
49
- "remote.panels": [{ "id": "context", "service": "context" }],
66
+ "topbar.units": [
67
+ {
68
+ "id": "ring",
69
+ "order": 10
70
+ }
71
+ ],
72
+ "topbar.popovers": [
73
+ {
74
+ "id": "context-panel",
75
+ "anchorId": "ring"
76
+ }
77
+ ],
78
+ "settings": {
79
+ "schema": "./settings.schema.json"
80
+ },
81
+ "remote.panels": [
82
+ {
83
+ "id": "context",
84
+ "service": "context"
85
+ }
86
+ ],
50
87
  "commands": [
51
- { "id": "context.rescan", "title": { "zh-CN": "重新扫描会话", "en": "Rescan session" } }
88
+ {
89
+ "id": "context.rescan",
90
+ "title": {
91
+ "zh-CN": "重新扫描会话",
92
+ "en": "Rescan session"
93
+ }
94
+ }
52
95
  ],
53
96
  "native": {
54
97
  "mcp": "./native/mcp.json",
55
- "skills": ["./native/skills"]
98
+ "skills": [
99
+ "./native/skills"
100
+ ]
56
101
  },
57
102
  "locales": "./locales"
58
103
  }
package/locales/en.json CHANGED
@@ -6,5 +6,8 @@
6
6
  "alert.warn240k": "Consider compacting (>240K cache degradation risk)",
7
7
  "alert.cliff328k": "High cliff zone (>=328K cache miss risk)",
8
8
  "alert.cacheDrop": "Context cache drop detected",
9
- "alert.compressed": "Auto-compaction detected"
9
+ "alert.compressed": "Auto-compaction detected",
10
+ "cost.label": "Reference cost",
11
+ "cost.unavailable": "Enable Usage plugin to view session reference cost",
12
+ "cost.unpriced": "Pricing unavailable for current model"
10
13
  }
@@ -6,5 +6,8 @@
6
6
  "alert.warn240k": "建议压缩上下文(>240K 缓存效率下降风险)",
7
7
  "alert.cliff328k": "高风险断崖区(>=328K 易丢缓存)",
8
8
  "alert.cacheDrop": "检测到上下文缓存失效",
9
- "alert.compressed": "已触发自动压缩"
9
+ "alert.compressed": "已触发自动压缩",
10
+ "cost.label": "参考费用",
11
+ "cost.unavailable": "未启用「用量」插件,已隐藏参考费用",
12
+ "cost.unpriced": "当前模型暂无公开单价"
10
13
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agy-daddy/plugin-context",
3
- "version": "1.0.0",
3
+ "version": "1.1.2",
4
4
  "description": "Agy-Daddy context ring, audit panel, attachment inspector, and composer pulse capsule plugin",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -25,7 +25,7 @@
25
25
  "access": "public"
26
26
  },
27
27
  "scripts": {
28
- "test": "AGY_DADDY_TEST_MODE=1 node --test test/*.test.js"
28
+ "test": "node -e \"const cp=require('node:child_process'),fs=require('node:fs'),p=require('node:path');const files=fs.readdirSync('test').filter(f=>f.endsWith('.test.js')).sort().map(f=>p.join('test',f));process.exit(cp.spawnSync(process.execPath,['--test',...files],{stdio:'inherit',env:{...process.env,AGY_DADDY_TEST_MODE:'1'}}).status??1)\""
29
29
  },
30
30
  "engines": {
31
31
  "node": ">=22.4.0"
@@ -21,6 +21,14 @@
21
21
  "label": { "zh-CN": "显示生成速度", "en": "Show generation speed" },
22
22
  "description": { "zh-CN": "在胶囊中实时显示流式估算速率 (~tok/s) 及完成后的精确速率", "en": "Show live estimated streaming rate (~tok/s) and final exact rate in the capsule" }
23
23
  },
24
+ {
25
+ "key": "showCost",
26
+ "type": "boolean",
27
+ "default": true,
28
+ "group": { "zh-CN": "显示位置与采样", "en": "Display & Sampling" },
29
+ "label": { "zh-CN": "显示会话参考成本", "en": "Show session reference cost" },
30
+ "description": { "zh-CN": "在胶囊与详情面板中展示当前会话预估 API 参考费用(需启用用量插件;未启用时自动隐藏)", "en": "Display estimated API reference cost for the current session in the capsule and panel (requires Usage plugin; auto-hidden when unavailable)" }
31
+ },
24
32
  {
25
33
  "key": "pollIntervalMs",
26
34
  "type": "number",
@@ -16,7 +16,15 @@ const TEXT_EXTENSIONS = new Set([
16
16
  function uriToLocalPath(uri) {
17
17
  if (!uri || typeof uri !== 'string') return null;
18
18
  if (uri.startsWith('inline:')) return null;
19
- if (uri.startsWith('file://')) {
19
+ if (/^file:\/\//i.test(uri)) {
20
+ if (/^file:\/\/\/?[A-Za-z]:[\\/]/i.test(uri)) {
21
+ const stripped = uri.replace(/^file:\/\/\/?/i, '');
22
+ try {
23
+ return decodeURIComponent(stripped);
24
+ } catch {
25
+ return stripped;
26
+ }
27
+ }
20
28
  try {
21
29
  return decodeURIComponent(new URL(uri).pathname);
22
30
  } catch {
@@ -998,6 +998,106 @@ function summarizeSessionGeneratorCalls(gmRows, options = {}) {
998
998
  };
999
999
  }
1000
1000
 
1001
+ function collectSessionGeneratorCalls(gmRows, options = {}) {
1002
+ const rows = Array.isArray(gmRows) ? gmRows : [];
1003
+ const cascadeId = options.cascadeId || null;
1004
+ const source = options.source || 'desktop';
1005
+ const deduped = [];
1006
+ const byCallId = new Map();
1007
+
1008
+ for (let i = 0; i < rows.length; i++) {
1009
+ const row = rows[i];
1010
+ if (!row || typeof row !== 'object') continue;
1011
+ const cm = row.chatModel || {};
1012
+ const modelRaw = String(cm.model || cm.modelOrAlias?.model || cm.responseModel || cm.modelDisplayName || row.model || row.modelId || '').trim();
1013
+ if (isShadowOrImageModel(modelRaw)) continue;
1014
+
1015
+ const parsed = parseGeneratorCall(row, cascadeId, source, i, options);
1016
+ if (!parsed || parsed.totalTokens <= 0) continue;
1017
+
1018
+ if (byCallId.has(parsed.callId)) {
1019
+ deduped[byCallId.get(parsed.callId)] = parsed;
1020
+ } else {
1021
+ byCallId.set(parsed.callId, deduped.length);
1022
+ deduped.push(parsed);
1023
+ }
1024
+ }
1025
+ return deduped;
1026
+ }
1027
+
1028
+ function formatCurrencyValue(amount, symbol = '$') {
1029
+ const safe = Math.max(0, Number(amount) || 0);
1030
+ if (safe === 0) return `${symbol}0.00`;
1031
+ if (safe >= 0.01) return `${symbol}${safe.toFixed(2)}`;
1032
+ if (safe < 0.0001) return `<${symbol}0.0001`;
1033
+ return `${symbol}${safe.toFixed(4).replace(/0+$/, '')}`;
1034
+ }
1035
+
1036
+ function formatReferenceCost(referenceCost) {
1037
+ if (!referenceCost || typeof referenceCost !== 'object') return null;
1038
+
1039
+ const callsCount = Math.max(0, Number(referenceCost.callsCount || 0) || 0);
1040
+ const hasPricedCount = referenceCost.pricedCount !== undefined && referenceCost.pricedCount !== null;
1041
+ const pricedCount = hasPricedCount ? Math.max(0, Number(referenceCost.pricedCount) || 0) : null;
1042
+ const unpricedCount = Math.max(0, Number(referenceCost.unpricedCount || 0) || 0);
1043
+
1044
+ const rawCurrency = String(referenceCost.currency || 'USD').trim().toUpperCase();
1045
+ const currency = rawCurrency || 'USD';
1046
+ const symbol = referenceCost.currencySymbol || (currency === 'CNY' ? '¥' : '$');
1047
+ const rate = Number(referenceCost.exchangeRate) > 0
1048
+ ? Number(referenceCost.exchangeRate)
1049
+ : (currency === 'CNY' ? 7.25 : 1);
1050
+
1051
+ const hasDisplay = referenceCost.totalDisplayCost !== undefined
1052
+ && referenceCost.totalDisplayCost !== null
1053
+ && Number.isFinite(Number(referenceCost.totalDisplayCost));
1054
+ const hasUsd = referenceCost.totalUsd !== undefined
1055
+ && referenceCost.totalUsd !== null
1056
+ && Number.isFinite(Number(referenceCost.totalUsd));
1057
+
1058
+ const amount = hasDisplay
1059
+ ? Math.max(0, Number(referenceCost.totalDisplayCost))
1060
+ : (hasUsd ? Math.max(0, Number(referenceCost.totalUsd) * rate) : null);
1061
+
1062
+ const unpriced = pricedCount === 0 && (amount === null || amount === 0);
1063
+ if (amount === null && !unpriced) return null;
1064
+
1065
+ const modelBreakdown = [];
1066
+ if (referenceCost.byModel && typeof referenceCost.byModel === 'object') {
1067
+ for (const [model, stat] of Object.entries(referenceCost.byModel)) {
1068
+ if (!stat || !stat.isPriced || !Number.isFinite(Number(stat.costUSD))) continue;
1069
+ const modelUsd = Math.max(0, Number(stat.costUSD));
1070
+ const modelAmt = modelUsd * rate;
1071
+ modelBreakdown.push({
1072
+ model,
1073
+ calls: Number(stat.calls || 0) || 0,
1074
+ tokens: Number(stat.tokens || 0) || 0,
1075
+ costUsd: modelUsd,
1076
+ amount: modelAmt,
1077
+ text: formatCurrencyValue(modelAmt, symbol)
1078
+ });
1079
+ }
1080
+ modelBreakdown.sort((a, b) => b.costUsd - a.costUsd);
1081
+ }
1082
+
1083
+ const formatted = unpriced ? '--' : formatCurrencyValue(amount, symbol);
1084
+ return {
1085
+ hasCost: !unpriced,
1086
+ unpriced,
1087
+ partial: !unpriced && unpricedCount > 0,
1088
+ amount: unpriced ? null : amount,
1089
+ currency,
1090
+ symbol,
1091
+ exchangeRate: rate,
1092
+ compactText: formatted,
1093
+ displayText: formatted,
1094
+ callsCount,
1095
+ pricedCount,
1096
+ unpricedCount,
1097
+ modelBreakdown
1098
+ };
1099
+ }
1100
+
1001
1101
  function getRingAccentToken(usagePercent, cacheAlert = {}) {
1002
1102
  if (cacheAlert.isCacheDrop || Number(usagePercent) >= 80) {
1003
1103
  return 'var(--ag-ring-danger, #ef4444)';
@@ -1018,6 +1118,8 @@ module.exports = {
1018
1118
  parseTimestampMs,
1019
1119
  parseDurationSec,
1020
1120
  formatTokensShort,
1121
+ formatCurrencyValue,
1122
+ formatReferenceCost,
1021
1123
  parseThresholdSpec,
1022
1124
  resolveThresholdTokens,
1023
1125
  formatThresholdLabel,
@@ -1031,6 +1133,7 @@ module.exports = {
1031
1133
  extractStepTimestampsFromTrajectory,
1032
1134
  extractCallId,
1033
1135
  parseGeneratorCall,
1136
+ collectSessionGeneratorCalls,
1034
1137
  summarizeSessionGeneratorCalls,
1035
1138
  getRingAccentToken
1036
1139
  };