@agy-daddy/plugin-pet 0.0.0-stage → 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.
@@ -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;
@@ -0,0 +1,218 @@
1
+ 'use strict';
2
+
3
+ const { evaluatePetRig } = require('./pet-rig-evaluator');
4
+
5
+ /**
6
+ * Shared HTML5 Canvas Path2D + Sprite stage used by both PC-Web (<WebPetOverlay />)
7
+ * and Desktop Antigravity Settings/Popover live previews.
8
+ */
9
+ function createPetCanvasStage(canvas, options = {}) {
10
+ let scene = options.scene || null;
11
+ let state = options.state || { animState: 'idle', speedFactor: 1.0, flipX: false, scale: 1.0 };
12
+ let assetMap = options.assetMap || {};
13
+ let rafId = null;
14
+ let running = false;
15
+ let lastDrawAt = 0;
16
+ let logicalW = Number(options.width || 160);
17
+ let logicalH = Number(options.height || 160);
18
+
19
+ const pathCache = new Map();
20
+ const imageCache = new Map();
21
+
22
+ function getCachedPath(sceneId, layer) {
23
+ if (!layer?.d || typeof globalThis.Path2D !== 'function') return null;
24
+ const key = `${sceneId}:${layer.id}:${layer.d}`;
25
+ let p = pathCache.get(key);
26
+ if (!p) {
27
+ p = new globalThis.Path2D(layer.d);
28
+ pathCache.set(key, p);
29
+ }
30
+ return p;
31
+ }
32
+
33
+ function getCachedImage(srcKey) {
34
+ if (!srcKey || typeof globalThis.Image !== 'function') return null;
35
+ const resolved = assetMap[srcKey] || srcKey;
36
+ let entry = imageCache.get(resolved);
37
+ if (!entry) {
38
+ const img = new globalThis.Image();
39
+ entry = { img, loaded: false };
40
+ img.onload = () => { entry.loaded = true; };
41
+ img.src = resolved;
42
+ imageCache.set(resolved, entry);
43
+ }
44
+ return entry.loaded ? entry.img : null;
45
+ }
46
+
47
+ function resize(w = logicalW, h = logicalH) {
48
+ logicalW = Math.max(32, Number(w) || 160);
49
+ logicalH = Math.max(32, Number(h) || 160);
50
+ const dpr = Math.min(3, Math.max(1, Number(globalThis.devicePixelRatio || 1)));
51
+ canvas.width = Math.round(logicalW * dpr);
52
+ canvas.height = Math.round(logicalH * dpr);
53
+ if (canvas.style) {
54
+ canvas.style.width = `${logicalW}px`;
55
+ canvas.style.height = `${logicalH}px`;
56
+ }
57
+ }
58
+
59
+ function drawFrame(nowMs = Date.now()) {
60
+ const ctx = canvas.getContext?.('2d');
61
+ if (!ctx || !scene) return;
62
+ const dpr = Math.min(3, Math.max(1, Number(globalThis.devicePixelRatio || 1)));
63
+ ctx.save();
64
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
65
+ ctx.clearRect(0, 0, logicalW, logicalH);
66
+
67
+ const vbW = Math.max(1, Number(scene.viewBox?.width || 160));
68
+ const vbH = Math.max(1, Number(scene.viewBox?.height || 160));
69
+ const petScale = Math.max(0.5, Math.min(2.0, Number(state.scale || 1.0)));
70
+ const fitScale = Math.min(logicalW / vbW, logicalH / vbH) * petScale;
71
+ const ox = (logicalW - vbW * fitScale) / 2;
72
+ const oy = (logicalH - vbH * fitScale) / 2;
73
+
74
+ ctx.translate(ox, oy);
75
+ ctx.scale(fitScale, fitScale);
76
+ if (state.flipX) {
77
+ ctx.translate(vbW, 0);
78
+ ctx.scale(-1, 1);
79
+ }
80
+
81
+ const { transforms, particles } = evaluatePetRig(scene, state, nowMs);
82
+
83
+ for (const pt of particles) {
84
+ ctx.save();
85
+ ctx.globalAlpha = pt.opacity;
86
+ ctx.fillStyle = pt.color;
87
+ if (pt.preset === 'pixels') {
88
+ ctx.fillRect(pt.x - pt.size / 2, pt.y - pt.size / 2, pt.size, pt.size);
89
+ } else {
90
+ ctx.beginPath();
91
+ ctx.arc(pt.x, pt.y, pt.size, 0, Math.PI * 2);
92
+ ctx.fill();
93
+ }
94
+ ctx.restore();
95
+ }
96
+
97
+ for (const item of transforms) {
98
+ const l = item.layer;
99
+ ctx.save();
100
+ ctx.globalAlpha = item.opacity;
101
+ ctx.translate(item.pivotX + item.tx, item.pivotY + item.ty);
102
+ if (item.rotRad) ctx.rotate(item.rotRad);
103
+ if (item.scaleX !== 1 || item.scaleY !== 1) ctx.scale(item.scaleX, item.scaleY);
104
+ ctx.translate(-item.pivotX, -item.pivotY);
105
+
106
+ const hasFill = Boolean(l.fill && l.fill !== 'none');
107
+ const hasStroke = Boolean(l.stroke && l.stroke !== 'none');
108
+ if (hasFill) ctx.fillStyle = l.fill;
109
+ if (hasStroke) {
110
+ ctx.strokeStyle = l.stroke;
111
+ ctx.lineWidth = Number(l.strokeWidth ?? 1.5);
112
+ }
113
+
114
+ if (l.kind === 'path') {
115
+ const p2d = getCachedPath(scene.sceneId, l);
116
+ if (p2d) {
117
+ if (hasFill) ctx.fill(p2d);
118
+ if (hasStroke) ctx.stroke(p2d);
119
+ }
120
+ } else if (l.kind === 'circle') {
121
+ ctx.beginPath();
122
+ ctx.arc(Number(l.cx || 0), Number(l.cy || 0), Number(l.r || 8), 0, Math.PI * 2);
123
+ if (hasFill) ctx.fill();
124
+ if (hasStroke) ctx.stroke();
125
+ } else if (l.kind === 'ellipse') {
126
+ ctx.beginPath();
127
+ ctx.ellipse(Number(l.cx || 0), Number(l.cy || 0), Number(l.rx || 10), Number(l.ry || 8), 0, 0, Math.PI * 2);
128
+ if (hasFill) ctx.fill();
129
+ if (hasStroke) ctx.stroke();
130
+ } else if (l.kind === 'rect') {
131
+ const rx = Number(l.x || 0);
132
+ const ry = Number(l.y || 0);
133
+ const rw = Number(l.width || 10);
134
+ const rh = Number(l.height || 10);
135
+ const cr = Number(l.cornerRadius || 0);
136
+ ctx.beginPath();
137
+ if (typeof ctx.roundRect === 'function') {
138
+ ctx.roundRect(rx, ry, rw, rh, cr);
139
+ } else {
140
+ ctx.rect(rx, ry, rw, rh);
141
+ }
142
+ if (hasFill) ctx.fill();
143
+ if (hasStroke) ctx.stroke();
144
+ } else if (l.kind === 'sprite' && l.spritePath) {
145
+ const img = getCachedImage(l.spritePath);
146
+ if (img) {
147
+ ctx.drawImage(img, Number(l.x || 0), Number(l.y || 0), Number(l.width || vbW), Number(l.height || vbH));
148
+ }
149
+ }
150
+ ctx.restore();
151
+ }
152
+ ctx.restore();
153
+ }
154
+
155
+ function resolveTargetFps() {
156
+ const anim = state?.animState || 'idle';
157
+ if (anim === 'sleeping') return scene?.fps?.sleep || 4;
158
+ if (anim === 'idle') return scene?.fps?.idle || 12;
159
+ return scene?.fps?.active || 30;
160
+ }
161
+
162
+ function loop(ts) {
163
+ if (!running) return;
164
+ const minInterval = 1000 / Math.max(1, resolveTargetFps());
165
+ const now = typeof ts === 'number' ? ts : Date.now();
166
+ if (now - lastDrawAt >= minInterval) {
167
+ lastDrawAt = now;
168
+ drawFrame(Date.now());
169
+ }
170
+ if (typeof globalThis.requestAnimationFrame === 'function') {
171
+ rafId = globalThis.requestAnimationFrame(loop);
172
+ }
173
+ }
174
+
175
+ resize(logicalW, logicalH);
176
+
177
+ return {
178
+ setScene(nextScene, nextAssets = null) {
179
+ scene = nextScene || null;
180
+ if (nextAssets && typeof nextAssets === 'object') {
181
+ assetMap = nextAssets;
182
+ }
183
+ pathCache.clear();
184
+ drawFrame(Date.now());
185
+ },
186
+ setState(nextState) {
187
+ state = { ...state, ...(nextState || {}) };
188
+ drawFrame(Date.now());
189
+ },
190
+ resize,
191
+ drawFrame,
192
+ start() {
193
+ if (running) return;
194
+ running = true;
195
+ if (typeof globalThis.requestAnimationFrame === 'function') {
196
+ rafId = globalThis.requestAnimationFrame(loop);
197
+ } else {
198
+ drawFrame(Date.now());
199
+ }
200
+ },
201
+ stop() {
202
+ running = false;
203
+ if (rafId !== null && typeof globalThis.cancelAnimationFrame === 'function') {
204
+ globalThis.cancelAnimationFrame(rafId);
205
+ rafId = null;
206
+ }
207
+ },
208
+ dispose() {
209
+ this.stop();
210
+ pathCache.clear();
211
+ imageCache.clear();
212
+ }
213
+ };
214
+ }
215
+
216
+ module.exports = {
217
+ createPetCanvasStage
218
+ };
@@ -0,0 +1,172 @@
1
+ 'use strict';
2
+
3
+ function clamp(val, min, max) {
4
+ return Math.min(max, Math.max(min, val));
5
+ }
6
+
7
+ /**
8
+ * Maps live TPS + session state to animState, speedFactor, roam speed, and target FPS.
9
+ * Matches DESKTOP_PET_DESIGN.md Section 3.5 formula.
10
+ */
11
+ function mapTpsToMotion({
12
+ tps = null,
13
+ busy = false,
14
+ idleMs = 0,
15
+ hasApproval = false,
16
+ hasError = false
17
+ } = {}) {
18
+ if (hasApproval) {
19
+ return {
20
+ animState: 'approval',
21
+ rawSpeedFactor: 1.4,
22
+ roamSpeedPxPerSec: 0,
23
+ targetFps: 24
24
+ };
25
+ }
26
+ if (hasError) {
27
+ return {
28
+ animState: 'error',
29
+ rawSpeedFactor: 1.0,
30
+ roamSpeedPxPerSec: 0,
31
+ targetFps: 20
32
+ };
33
+ }
34
+ const numTps = typeof tps === 'number' && Number.isFinite(tps) && tps > 0 ? tps : null;
35
+ if (numTps !== null) {
36
+ const rawFactor = clamp(1.0 + 0.75 * Math.log2(1 + Math.max(0, numTps) / 15), 1.0, 3.5);
37
+ if (numTps > 65) {
38
+ return {
39
+ animState: 'sprinting',
40
+ rawSpeedFactor: Number(rawFactor.toFixed(2)),
41
+ roamSpeedPxPerSec: Math.round(95 + ((rawFactor - 2.35) / 1.15) * 55),
42
+ targetFps: 30
43
+ };
44
+ }
45
+ if (numTps > 25) {
46
+ return {
47
+ animState: 'trotting',
48
+ rawSpeedFactor: Number(rawFactor.toFixed(2)),
49
+ roamSpeedPxPerSec: Math.round(55 + ((rawFactor - 1.6) / 0.75) * 40),
50
+ targetFps: 30
51
+ };
52
+ }
53
+ return {
54
+ animState: 'walking',
55
+ rawSpeedFactor: Number(rawFactor.toFixed(2)),
56
+ roamSpeedPxPerSec: Math.round(32 + ((rawFactor - 1.0) / 0.6) * 23),
57
+ targetFps: 30
58
+ };
59
+ }
60
+ if (busy) {
61
+ return {
62
+ animState: 'thinking',
63
+ rawSpeedFactor: 1.0,
64
+ roamSpeedPxPerSec: 18,
65
+ targetFps: 20
66
+ };
67
+ }
68
+ if (Number(idleMs) > 45000) {
69
+ return {
70
+ animState: 'sleeping',
71
+ rawSpeedFactor: 0.35,
72
+ roamSpeedPxPerSec: 0,
73
+ targetFps: 4
74
+ };
75
+ }
76
+ return {
77
+ animState: 'idle',
78
+ rawSpeedFactor: 0.8,
79
+ roamSpeedPxPerSec: 12,
80
+ targetFps: 12
81
+ };
82
+ }
83
+
84
+ function createSpeedSmoother(alpha = 0.35) {
85
+ let ema = null;
86
+ return {
87
+ push(rawFactor) {
88
+ const val = clamp(Number(rawFactor) || 0.8, 0.25, 3.5);
89
+ if (ema === null) ema = val;
90
+ else ema = alpha * val + (1 - alpha) * ema;
91
+ return Number(ema.toFixed(2));
92
+ },
93
+ reset() {
94
+ ema = null;
95
+ }
96
+ };
97
+ }
98
+
99
+ function evaluatePetRig(sceneSpec, runtimeState = {}, timestampMs = Date.now()) {
100
+ const layers = Array.isArray(sceneSpec?.layers) ? sceneSpec.layers : [];
101
+ const animState = String(runtimeState.animState || 'idle');
102
+ const speedFactor = clamp(Number(runtimeState.speedFactor || 1.0), 0.25, 4.0);
103
+ const tSec = Number(timestampMs) / 1000;
104
+ const vbW = Number(sceneSpec?.viewBox?.width || 160);
105
+ const vbH = Number(sceneSpec?.viewBox?.height || 160);
106
+
107
+ const transforms = [];
108
+ for (const layer of layers) {
109
+ const allowedStates = layer.motion?.states;
110
+ if (Array.isArray(allowedStates) && !allowedStates.includes(animState)) {
111
+ continue;
112
+ }
113
+ const m = layer.motion || {};
114
+ const phase = Number(m.phaseRad || 0);
115
+ let tx = 0;
116
+ let ty = 0;
117
+ let rotRad = 0;
118
+ let scaleY = 1;
119
+
120
+ if (m.bobAmpY && m.bobFreqHz) {
121
+ ty += Number(m.bobAmpY) * Math.sin(2 * Math.PI * Number(m.bobFreqHz) * speedFactor * tSec + phase);
122
+ }
123
+ if (m.swayAmpX && m.swayFreqHz) {
124
+ tx += Number(m.swayAmpX) * Math.sin(2 * Math.PI * Number(m.swayFreqHz) * speedFactor * tSec + phase);
125
+ }
126
+ if (m.rotAmpDeg && m.rotFreqHz) {
127
+ rotRad = ((Number(m.rotAmpDeg) * Math.PI) / 180) * Math.sin(2 * Math.PI * Number(m.rotFreqHz) * speedFactor * tSec + phase);
128
+ }
129
+ if (m.blinkIntervalMs && Number(m.blinkIntervalMs) > 0) {
130
+ const cycle = Number(timestampMs) % Number(m.blinkIntervalMs);
131
+ if (cycle < 130) scaleY = 0.12;
132
+ }
133
+
134
+ transforms.push({
135
+ layer,
136
+ pivotX: Number(layer.pivotX ?? vbW / 2),
137
+ pivotY: Number(layer.pivotY ?? vbH / 2),
138
+ tx,
139
+ ty,
140
+ rotRad,
141
+ scaleX: 1,
142
+ scaleY,
143
+ opacity: layer.opacity !== undefined ? clamp(Number(layer.opacity), 0, 1) : 1
144
+ });
145
+ }
146
+
147
+ const preset = sceneSpec?.particles?.preset || 'none';
148
+ const particleColor = sceneSpec?.particles?.color || '#a78bfa';
149
+ const particles = [];
150
+ if (preset !== 'none' && animState !== 'sleeping') {
151
+ const count = animState === 'sprinting' ? 8 : (animState === 'trotting' ? 6 : 3);
152
+ for (let i = 0; i < count; i++) {
153
+ const p = ((tSec * speedFactor * 0.7 + i / count) % 1 + 1) % 1;
154
+ particles.push({
155
+ x: vbW * (0.2 + ((i * 37) % 60) / 100),
156
+ y: preset === 'exhaust' ? vbH * (0.65 + p * 0.3) : vbH * (0.45 - p * 0.4),
157
+ size: 2.2 + (i % 3),
158
+ opacity: Math.max(0.1, (1 - p) * 0.85),
159
+ color: particleColor,
160
+ preset
161
+ });
162
+ }
163
+ }
164
+
165
+ return { transforms, particles };
166
+ }
167
+
168
+ module.exports = {
169
+ mapTpsToMotion,
170
+ createSpeedSmoother,
171
+ evaluatePetRig
172
+ };