@agy-daddy/plugin-pet 0.0.0-stage → 1.1.1

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.
@@ -0,0 +1,231 @@
1
+ 'use strict';
2
+
3
+ const { createPetCanvasStage } = require('./shared/pet-canvas-stage');
4
+ const { getBuiltinThemes, getBuiltinThemeById } = require('./shared/themes');
5
+
6
+ let disposers = [];
7
+
8
+ async function mount(ctx) {
9
+ dispose();
10
+
11
+ const doc = globalThis.document;
12
+ let latestSnapshot = null;
13
+ let panelEl = null;
14
+ let canvasStage = null;
15
+ let lastSessionKey = '';
16
+
17
+ const stopStyles = ctx.styles.inject(`
18
+ #agy-pet-panel {
19
+ display: flex;
20
+ flex-direction: column;
21
+ gap: 10px;
22
+ padding: 10px 12px;
23
+ color: var(--ag-text-primary, #e4e4e7);
24
+ font-size: 12px;
25
+ }
26
+ .ag-pet-preview-row {
27
+ display: flex;
28
+ align-items: center;
29
+ gap: 12px;
30
+ padding: 8px;
31
+ border-radius: 10px;
32
+ background: rgba(167, 139, 250, 0.08);
33
+ border: 1px solid rgba(167, 139, 250, 0.22);
34
+ }
35
+ .ag-pet-btn-row {
36
+ display: flex;
37
+ flex-wrap: wrap;
38
+ gap: 6px;
39
+ }
40
+ .ag-pet-btn {
41
+ padding: 5px 10px;
42
+ border-radius: 8px;
43
+ border: 1px solid var(--ag-custom-token-accent, var(--ag-token-accent-default, #a78bfa));
44
+ background: rgba(167, 139, 250, 0.14);
45
+ color: inherit;
46
+ cursor: pointer;
47
+ font-size: 11px;
48
+ }
49
+ .ag-pet-themes {
50
+ display: grid;
51
+ grid-template-columns: repeat(3, minmax(0, 1fr));
52
+ gap: 6px;
53
+ }
54
+ .ag-pet-theme-btn {
55
+ padding: 5px 6px;
56
+ border-radius: 7px;
57
+ border: 1px solid rgba(161, 161, 170, 0.25);
58
+ background: transparent;
59
+ color: inherit;
60
+ cursor: pointer;
61
+ font-size: 11px;
62
+ text-align: left;
63
+ overflow: hidden;
64
+ text-overflow: ellipsis;
65
+ white-space: nowrap;
66
+ }
67
+ .ag-pet-theme-btn[data-active="true"] {
68
+ border-color: var(--ag-custom-token-accent, var(--ag-token-accent-default, #a78bfa));
69
+ background: rgba(167, 139, 250, 0.18);
70
+ }
71
+ `, { scope: 'shadow', id: 'pet-panel-styles' });
72
+
73
+ function renderPanel() {
74
+ if (!panelEl) return;
75
+ panelEl.textContent = '';
76
+
77
+ const petState = latestSnapshot?.state || {};
78
+ const curThemeId = petState.themeId || ctx.settings?.get?.()?.themeId || 'daddy-orb';
79
+ const curTheme = getBuiltinThemeById(curThemeId);
80
+ const themes = Array.isArray(latestSnapshot?.themes) && latestSnapshot.themes.length > 0
81
+ ? latestSnapshot.themes
82
+ : getBuiltinThemes();
83
+
84
+ const previewRow = doc.createElement('div');
85
+ previewRow.className = 'ag-pet-preview-row';
86
+
87
+ if (typeof doc.createElement === 'function') {
88
+ const canvas = doc.createElement('canvas');
89
+ canvas.width = 96;
90
+ canvas.height = 96;
91
+ previewRow.appendChild(canvas);
92
+ if (canvasStage) canvasStage.dispose();
93
+ canvasStage = createPetCanvasStage(canvas, {
94
+ width: 96,
95
+ height: 96,
96
+ scene: latestSnapshot?.scene || curTheme.scene,
97
+ state: {
98
+ animState: petState.motion?.animState || 'idle',
99
+ speedFactor: petState.motion?.speedFactor || 1.0
100
+ }
101
+ });
102
+ canvasStage.start();
103
+ }
104
+
105
+ const meta = doc.createElement('div');
106
+ const title = doc.createElement('div');
107
+ title.textContent = `${curTheme.name?.['zh-CN'] || curThemeId}`;
108
+ const sub = doc.createElement('div');
109
+ const tpsStr = petState.motion?.tps != null ? ` · ${petState.motion.tps} tok/s` : '';
110
+ sub.textContent = `状态:${petState.motion?.animState || 'idle'}${tpsStr}`;
111
+ meta.appendChild(title);
112
+ meta.appendChild(sub);
113
+ previewRow.appendChild(meta);
114
+ panelEl.appendChild(previewRow);
115
+
116
+ const btnRow = doc.createElement('div');
117
+ btnRow.className = 'ag-pet-btn-row';
118
+
119
+ const toggleDeskBtn = doc.createElement('button');
120
+ toggleDeskBtn.type = 'button';
121
+ toggleDeskBtn.className = 'ag-pet-btn';
122
+ toggleDeskBtn.textContent = petState.desktopVisible !== false ? '桌面置顶:开' : '桌面置顶:关';
123
+ toggleDeskBtn.addEventListener('click', () => {
124
+ void ctx.commands?.execute?.('pet.toggleDesktop');
125
+ });
126
+
127
+ const toggleWebBtn = doc.createElement('button');
128
+ toggleWebBtn.type = 'button';
129
+ toggleWebBtn.className = 'ag-pet-btn';
130
+ toggleWebBtn.textContent = petState.webVisible !== false ? 'PC-Web:开' : 'PC-Web:关';
131
+ toggleWebBtn.addEventListener('click', () => {
132
+ void ctx.commands?.execute?.('pet.toggleWeb');
133
+ });
134
+
135
+ const openSettingsBtn = doc.createElement('button');
136
+ openSettingsBtn.type = 'button';
137
+ openSettingsBtn.className = 'ag-pet-btn';
138
+ openSettingsBtn.textContent = '完整设置与白名单';
139
+ openSettingsBtn.addEventListener('click', () => {
140
+ void ctx.settings?.open?.({ pluginId: ctx.pluginId });
141
+ });
142
+
143
+ btnRow.appendChild(toggleDeskBtn);
144
+ btnRow.appendChild(toggleWebBtn);
145
+ btnRow.appendChild(openSettingsBtn);
146
+ panelEl.appendChild(btnRow);
147
+
148
+ const grid = doc.createElement('div');
149
+ grid.className = 'ag-pet-themes';
150
+ for (const th of themes.slice(0, 15)) {
151
+ const b = doc.createElement('button');
152
+ b.type = 'button';
153
+ b.className = 'ag-pet-theme-btn';
154
+ b.setAttribute('data-active', th.id === curThemeId ? 'true' : 'false');
155
+ b.textContent = th.name?.['zh-CN'] || th.name?.en || th.id;
156
+ b.addEventListener('click', () => {
157
+ void ctx.settings?.update?.({ themeId: th.id });
158
+ });
159
+ grid.appendChild(b);
160
+ }
161
+ panelEl.appendChild(grid);
162
+ }
163
+
164
+ function syncActiveSession() {
165
+ const cascadeId = ctx.hostDom?.getSessionId?.() || null;
166
+ const busy = Boolean(ctx.hostDom?.isAssistantBusy?.());
167
+ const key = `${cascadeId || ''}:${busy ? 1 : 0}`;
168
+ if (key === lastSessionKey) return;
169
+ lastSessionKey = key;
170
+ Promise.resolve(ctx.bridge?.post?.('/active-session', { cascadeId, busy })).catch(() => {});
171
+ }
172
+
173
+ const stopUnit = ctx.topbar.registerUnit({
174
+ id: 'pet-chip',
175
+ order: 35,
176
+ label: '桌宠',
177
+ iconSvg: '<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><circle cx="8" cy="8" r="5"/></svg>',
178
+ title: '桌面与 PC-Web 伴侣宠物'
179
+ });
180
+
181
+ const popoverHandle = ctx.topbar.registerPopover({
182
+ id: 'pet-panel',
183
+ anchorId: 'pet-chip',
184
+ title: '伴侣宠物控制台',
185
+ render(node) {
186
+ panelEl = node;
187
+ panelEl.id = 'agy-pet-panel';
188
+ renderPanel();
189
+ }
190
+ });
191
+
192
+ const stopStateSub = ctx.state?.subscribe?.('state:pet.state@1', () => {
193
+ void Promise.resolve(ctx.bridge?.post?.('/state', {}))
194
+ .then((snap) => {
195
+ if (snap && snap.ok) {
196
+ latestSnapshot = snap;
197
+ renderPanel();
198
+ }
199
+ })
200
+ .catch(() => {});
201
+ });
202
+
203
+ const stopActivePoll = ctx.schedule.every(1000, () => {
204
+ syncActiveSession();
205
+ });
206
+
207
+ syncActiveSession();
208
+ try {
209
+ latestSnapshot = await ctx.bridge.post('/state', {});
210
+ } catch {}
211
+
212
+ disposers.push(
213
+ stopStyles,
214
+ stopUnit,
215
+ () => popoverHandle?.dispose?.(),
216
+ () => { if (typeof stopStateSub === 'function') stopStateSub(); },
217
+ () => { if (typeof stopActivePoll === 'function') stopActivePoll(); },
218
+ () => { if (canvasStage) { canvasStage.dispose(); canvasStage = null; } }
219
+ );
220
+ }
221
+
222
+ function dispose() {
223
+ for (const fn of disposers.splice(0)) {
224
+ try { if (typeof fn === 'function') fn(); } catch {}
225
+ }
226
+ }
227
+
228
+ module.exports = {
229
+ mount,
230
+ dispose
231
+ };
@@ -0,0 +1,271 @@
1
+ 'use strict';
2
+
3
+ const CONFIRM_INTERACTION_FIELDS = [
4
+ 'approvalInteraction',
5
+ 'mcp',
6
+ 'openBrowserUrl',
7
+ 'executeBrowserJavaScript',
8
+ 'captureBrowserScreenshot',
9
+ 'clickBrowserPixel',
10
+ 'readUrlContent',
11
+ 'sendCommandInput'
12
+ ];
13
+
14
+ function stripMarkdownToPlain(text, maxLen = 68) {
15
+ const s = String(text || '')
16
+ .replace(/```[\s\S]*?```/g, ' ')
17
+ .replace(/`([^`]+)`/g, '$1')
18
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
19
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
20
+ .replace(/^#+\s+/gm, '')
21
+ .replace(/[*_~>]+/g, '')
22
+ .replace(/\s+/g, ' ')
23
+ .trim();
24
+ if (!s) return '';
25
+ if (s.length <= maxLen) return s;
26
+ return `${s.slice(0, Math.max(1, maxLen - 1))}…`;
27
+ }
28
+
29
+ function normalizePathKey(raw) {
30
+ if (!raw) return '';
31
+ let s = String(raw).trim();
32
+ if (s.startsWith('file://')) {
33
+ try { s = decodeURIComponent(new URL(s).pathname); } catch {}
34
+ }
35
+ return s.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
36
+ }
37
+
38
+ function resolveSessionOrgInfo(session = {}, orgSummary = null) {
39
+ const cascadeId = String(session.cascadeId || '').trim();
40
+ const projects = Array.isArray(orgSummary?.projects) ? orgSummary.projects : [];
41
+ const groups = Array.isArray(orgSummary?.groups) ? orgSummary.groups : [];
42
+ const projectGroupMap = orgSummary?.projectGroupMap || {};
43
+ const sessionGroupMap = orgSummary?.sessionGroupMap || {};
44
+ const sessionProjectOverrides = orgSummary?.sessionProjectOverrides || {};
45
+
46
+ let matchedProject = null;
47
+ const overridePid = sessionProjectOverrides[cascadeId];
48
+ if (overridePid) {
49
+ matchedProject = projects.find((p) => p.id === overridePid || (Array.isArray(p.aliases) && p.aliases.includes(overridePid))) || null;
50
+ }
51
+
52
+ if (!matchedProject) {
53
+ const wsKey = normalizePathKey(session.workspaceUri || session.workspacePath || '');
54
+ const explicitPid = String(session.projectId || '').trim();
55
+ if (explicitPid) {
56
+ matchedProject = projects.find((p) => p.id === explicitPid || (Array.isArray(p.aliases) && p.aliases.includes(explicitPid))) || null;
57
+ }
58
+ if (!matchedProject && wsKey) {
59
+ matchedProject = projects.find((p) => {
60
+ const pKey = normalizePathKey(p.rootPath || p.uri);
61
+ return pKey && (wsKey === pKey || wsKey.startsWith(`${pKey}/`));
62
+ }) || null;
63
+ }
64
+ }
65
+
66
+ const projectId = matchedProject?.id || (session.projectId ? String(session.projectId) : null);
67
+ const projectName = matchedProject?.name || session.projectName || null;
68
+ const groupId = sessionGroupMap[cascadeId] || (projectId ? projectGroupMap[projectId] : null) || matchedProject?.groupId || session.groupId || null;
69
+ const groupObj = groupId ? groups.find((g) => g.id === groupId) : null;
70
+
71
+ return {
72
+ projectId,
73
+ projectAliases: Array.isArray(matchedProject?.aliases) ? matchedProject.aliases : [],
74
+ projectName,
75
+ groupId,
76
+ groupName: groupObj?.name || null
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Deterministic 4D Watch Filter evaluation matching DESKTOP_PET_DESIGN.md Section 3.4:
82
+ * 1. Lifecycle exclusion (deleted / archived / isSubagent)
83
+ * 2. Hard exclusion (excludeCurrentSession && cascadeId === currentFocusSessionId)
84
+ * 3. Whitelist union (projectWhitelist ∪ groupWhitelist) or followCurrentSession
85
+ */
86
+ function isSessionWatched(session = {}, filterConfig = {}, orgSummary = null, currentFocusSessionId = null) {
87
+ const cascadeId = String(session.cascadeId || '').trim();
88
+ if (!cascadeId) return false;
89
+
90
+ // 1. Lifecycle exclusion
91
+ if (session.isSubagent === true) return false;
92
+ const deletedSet = new Set(Array.isArray(orgSummary?.deletedSessionIds) ? orgSummary.deletedSessionIds : []);
93
+ const archivedSet = new Set(Array.isArray(orgSummary?.archivedSessionIds) ? orgSummary.archivedSessionIds : []);
94
+ if (deletedSet.has(cascadeId) || archivedSet.has(cascadeId)) return false;
95
+
96
+ // 2. Highest-priority hard exclusion
97
+ const isCurrentFocus = Boolean(currentFocusSessionId && cascadeId === currentFocusSessionId);
98
+ if (filterConfig.excludeCurrentSession === true && isCurrentFocus) {
99
+ return false;
100
+ }
101
+
102
+ // 3. Whitelist evaluation
103
+ const projectWhitelist = Array.isArray(filterConfig.projectWhitelist) ? filterConfig.projectWhitelist.filter(Boolean) : [];
104
+ const groupWhitelist = Array.isArray(filterConfig.groupWhitelist) ? filterConfig.groupWhitelist.filter(Boolean) : [];
105
+ const hasWhitelist = projectWhitelist.length > 0 || groupWhitelist.length > 0;
106
+ const followCurrent = filterConfig.followCurrentSession !== false;
107
+
108
+ if (!hasWhitelist) {
109
+ return true;
110
+ }
111
+
112
+ const orgInfo = resolveSessionOrgInfo(session, orgSummary);
113
+ const projectMatch = orgInfo.projectId
114
+ ? (projectWhitelist.includes(orgInfo.projectId) || orgInfo.projectAliases.some((a) => projectWhitelist.includes(a)))
115
+ : false;
116
+ const groupMatch = orgInfo.groupId ? groupWhitelist.includes(orgInfo.groupId) : false;
117
+
118
+ if (projectMatch || groupMatch) return true;
119
+ if (followCurrent && isCurrentFocus) return true;
120
+ return false;
121
+ }
122
+
123
+ function classifyStepAttention(step, stepIndex, sessionMeta = {}) {
124
+ if (!step || typeof step !== 'object') return null;
125
+ const status = String(step.status || '').toUpperCase();
126
+ const type = String(step.type || '').toUpperCase();
127
+ const isPending = status.includes('PENDING') || status.includes('WAITING');
128
+ const cascadeId = String(sessionMeta.cascadeId || '');
129
+ const sessionTitle = String(sessionMeta.sessionTitle || cascadeId.slice(0, 8));
130
+
131
+ const req = step.requestedInteraction?.interaction || step.requestedInteraction;
132
+ if (isPending && req && typeof req === 'object') {
133
+ const matchedField = CONFIRM_INTERACTION_FIELDS.find((f) => req[f] !== undefined && req[f] !== null)
134
+ || (req.filePermission ? 'filePermission' : null)
135
+ || (req.runCommand ? 'runCommand' : null)
136
+ || (req.permission ? 'permission' : null);
137
+ if (matchedField) {
138
+ return {
139
+ id: `${cascadeId}:${stepIndex}:approval`,
140
+ kind: 'approval',
141
+ cascadeId,
142
+ sessionTitle,
143
+ projectId: sessionMeta.projectId || null,
144
+ projectName: sessionMeta.projectName || null,
145
+ groupId: sessionMeta.groupId || null,
146
+ stepIndex,
147
+ interactionType: matchedField,
148
+ summary: stripMarkdownToPlain(
149
+ req.runCommand?.commandLine || req.approvalInteraction?.summary || `等待人工审核 (${matchedField})`,
150
+ 76
151
+ ) || `等待人工审核 (${matchedField})`,
152
+ createdAt: Date.now()
153
+ };
154
+ }
155
+ }
156
+
157
+ if (isPending && type === 'CORTEX_STEP_TYPE_ASK_QUESTION' && (!Array.isArray(step.completedInteractions) || step.completedInteractions.length === 0)) {
158
+ return {
159
+ id: `${cascadeId}:${stepIndex}:approval`,
160
+ kind: 'approval',
161
+ cascadeId,
162
+ sessionTitle,
163
+ projectId: sessionMeta.projectId || null,
164
+ projectName: sessionMeta.projectName || null,
165
+ groupId: sessionMeta.groupId || null,
166
+ stepIndex,
167
+ interactionType: 'askQuestion',
168
+ summary: stripMarkdownToPlain(step.askQuestion?.question || '等待回答确认问题', 76) || '等待回答确认问题',
169
+ createdAt: Date.now()
170
+ };
171
+ }
172
+
173
+ if (type === 'CORTEX_STEP_TYPE_ERROR_MESSAGE' || status.includes('ERROR')) {
174
+ const errText = stripMarkdownToPlain(step.errorMessage?.message || step.error || '会话执行异常', 76);
175
+ if (errText) {
176
+ return {
177
+ id: `${cascadeId}:${stepIndex}:error`,
178
+ kind: 'error',
179
+ cascadeId,
180
+ sessionTitle,
181
+ projectId: sessionMeta.projectId || null,
182
+ projectName: sessionMeta.projectName || null,
183
+ groupId: sessionMeta.groupId || null,
184
+ stepIndex,
185
+ summary: errText,
186
+ createdAt: Date.now()
187
+ };
188
+ }
189
+ }
190
+
191
+ if (type === 'CORTEX_STEP_TYPE_PLANNER_RESPONSE' && status.includes('DONE')) {
192
+ const rawResp = step.plannerResponse?.modifiedResponse || step.plannerResponse?.response || '';
193
+ const summary = stripMarkdownToPlain(rawResp, 68);
194
+ if (summary) {
195
+ return {
196
+ id: `${cascadeId}:${stepIndex}:reply`,
197
+ kind: 'reply',
198
+ cascadeId,
199
+ sessionTitle,
200
+ projectId: sessionMeta.projectId || null,
201
+ projectName: sessionMeta.projectName || null,
202
+ groupId: sessionMeta.groupId || null,
203
+ stepIndex,
204
+ summary,
205
+ createdAt: Date.now()
206
+ };
207
+ }
208
+ }
209
+
210
+ return null;
211
+ }
212
+
213
+ function estimateTextTokens(text) {
214
+ const s = String(text || '');
215
+ if (!s) return 0;
216
+ let cjk = 0;
217
+ for (let i = 0; i < s.length; i++) {
218
+ const code = s.charCodeAt(i);
219
+ if ((code >= 0x4e00 && code <= 0x9fff) || (code >= 0x3040 && code <= 0x30ff) || (code >= 0xac00 && code <= 0xd7af)) {
220
+ cjk++;
221
+ }
222
+ }
223
+ return (s.length - cjk) / 4 + cjk * 1.2;
224
+ }
225
+
226
+ class TailStepTpsEstimator {
227
+ constructor(windowMs = 3000) {
228
+ this.windowMs = windowMs;
229
+ this.sessions = new Map();
230
+ }
231
+
232
+ sample(cascadeId, running, tailText, nowMs = Date.now()) {
233
+ if (!running) {
234
+ this.sessions.delete(cascadeId);
235
+ return null;
236
+ }
237
+ const curTokens = estimateTextTokens(tailText);
238
+ let rec = this.sessions.get(cascadeId);
239
+ if (!rec || curTokens < rec.lastTokens) {
240
+ rec = { samples: [{ t: nowMs, tokens: curTokens }], lastTokens: curTokens };
241
+ this.sessions.set(cascadeId, rec);
242
+ return null;
243
+ }
244
+ rec.lastTokens = curTokens;
245
+ rec.samples.push({ t: nowMs, tokens: curTokens });
246
+ const cutoff = nowMs - this.windowMs;
247
+ while (rec.samples.length > 2 && rec.samples[1].t <= cutoff) {
248
+ rec.samples.shift();
249
+ }
250
+ const anchor = rec.samples[0];
251
+ const dtSec = (nowMs - anchor.t) / 1000;
252
+ const dTok = curTokens - anchor.tokens;
253
+ if (dtSec >= 0.4 && dTok >= 2) {
254
+ return Number((dTok / dtSec).toFixed(1));
255
+ }
256
+ return null;
257
+ }
258
+
259
+ clear(cascadeId) {
260
+ this.sessions.delete(cascadeId);
261
+ }
262
+ }
263
+
264
+ module.exports = {
265
+ CONFIRM_INTERACTION_FIELDS,
266
+ stripMarkdownToPlain,
267
+ resolveSessionOrgInfo,
268
+ isSessionWatched,
269
+ classifyStepAttention,
270
+ TailStepTpsEstimator
271
+ };
@@ -0,0 +1,36 @@
1
+ export interface PetCanvasSceneLike {
2
+ sceneId: string;
3
+ viewBox?: { width: number; height: number };
4
+ fps?: { active?: number; idle?: number; sleep?: number };
5
+ hitBox?: { x: number; y: number; width: number; height: number };
6
+ particles?: { preset?: string; color?: string };
7
+ layers: Array<Record<string, unknown>>;
8
+ }
9
+
10
+ export interface PetCanvasStageState {
11
+ animState?: string;
12
+ speedFactor?: number;
13
+ flipX?: boolean;
14
+ scale?: number;
15
+ }
16
+
17
+ export interface PetCanvasStageInstance {
18
+ setScene(scene: PetCanvasSceneLike | null, nextAssets?: Record<string, string> | null): void;
19
+ setState(state: PetCanvasStageState): void;
20
+ resize(width?: number, height?: number): void;
21
+ drawFrame(nowMs?: number): void;
22
+ start(): void;
23
+ stop(): void;
24
+ dispose(): void;
25
+ }
26
+
27
+ export function createPetCanvasStage(
28
+ canvas: HTMLCanvasElement,
29
+ options?: {
30
+ width?: number;
31
+ height?: number;
32
+ scene?: PetCanvasSceneLike | null;
33
+ state?: PetCanvasStageState;
34
+ assetMap?: Record<string, string>;
35
+ },
36
+ ): PetCanvasStageInstance;