@linxin666/dsh-pet 0.1.1 → 0.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
@@ -76,7 +76,10 @@ conversation.input.selector.context 槽位 <-- 轮询 800ms -- pet-client(浏
76
76
  推荐直接安装全家桶聚合包 `@linxin666/dsh-web-ui-all`(一个包装齐全部功能插件与皮肤),或单独安装本插件:
77
77
 
78
78
  ```sh
79
- # 当前(插件尚未发布到 npm):克隆全家桶仓库后安装
79
+ # 推荐:直接从 npm 安装
80
+ dsh plugin --profile web add @linxin666/dsh-pet
81
+
82
+ # 或从仓库安装(开发调试)
80
83
  git clone https://github.com/zhu1090093659/dsh-web-ui.git
81
84
  cd dsh-web-ui
82
85
  pnpm install && pnpm -r build
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","names":["styles","styles","css"],"sources":["../../../packages/dsh-pet/src/client/pet-store.ts","../../../packages/dsh-pet/src/client/spritesheet.ts","../../../packages/dsh-pet/src/client/WhalePet.tsx","../../../packages/dsh-pet/src/client/PetDockEntry.tsx","../../../packages/dsh-pet/src/client/PluginSettingsCard.tsx","../../../packages/dsh-pet/src/client/settings-form.ts","../../../packages/dsh-pet/src/client/PetSettingsCard.tsx","../../../packages/dsh-pet/src/client/locales.ts","../../../packages/dsh-pet/src/client/index.ts"],"sourcesContent":["/**\n * Browser-side pet store: the pet state snapshot plus transient UI feedback\n * (reaction bubbles), written only through the store's audit actions. The\n * RPC polling and interactions live in the plugin apply body; components\n * only ever read snapshots.\n * @module @linxin666/dsh-pet/client/pet-store\n */\n\nimport { defineStore } from '@deepseek-ai/dsh-client-runtime/client'\nimport type { EngineStoreHandle, EngineStoreInstance } from '@deepseek-ai/dsh-client-runtime/client'\nimport type { PetStateView } from '../service.ts'\nimport type { PetInteraction } from '../affinity.ts'\n\n/** One transient reaction bubble on the pet. */\nexport interface PetFeedback {\n /** Bubble copy. */\n text: string\n /** Interaction kind driving the reaction animation. */\n kind: PetInteraction | 'none'\n /** Epoch ms when the bubble appeared (for expiry). */\n at: number\n}\n\n/** Pet UI state as consumers see it. */\nexport interface PetUiState {\n /** Latest host snapshot; null before the first successful fetch. */\n snapshot: PetStateView | null\n /** Fetch lifecycle. */\n state: 'loading' | 'ready' | 'error'\n /** Transport error message (for the debug surface), when any. */\n error: string | null\n /** Active reaction bubble, if any. */\n feedback: PetFeedback | null\n}\n\n/** Store write set. */\nexport type PetUiActions = {\n /** Replace the host snapshot (poll result). */\n setSnapshot: (draft: PetUiState, snapshot: PetStateView) => void\n /** Mark the fetch lifecycle. */\n setState: (draft: PetUiState, state: PetUiState['state'], error: string | null) => void\n /** Show a reaction bubble. */\n setFeedback: (draft: PetUiState, feedback: PetFeedback | null) => void\n}\n\n/** Create the pet store handle (apply world only; never module-level). */\nexport function createPetStore(): EngineStoreHandle<PetUiState, PetUiActions> {\n return defineStore({\n init: (): PetUiState => ({\n snapshot: null,\n state: 'loading',\n error: null,\n feedback: null,\n }),\n actions: {\n setSnapshot: (draft, snapshot) => {\n draft.snapshot = snapshot\n draft.state = 'ready'\n draft.error = null\n },\n setState: (draft, state, error) => {\n draft.state = state\n draft.error = error\n },\n setFeedback: (draft, feedback) => {\n draft.feedback = feedback\n },\n },\n })\n}\n\nexport type { PetInteraction }\n\n/**\n * A live pet store instance (one per host, owned by the plugin apply body —\n * the pet itself is host-global, so its UI state must not ride the slot\n * system's per-session store scoping).\n */\nexport type PetStoreInstance = EngineStoreInstance<PetUiState, PetUiActions>\n\n","/**\n * Whale-girl spritesheet geometry and animation tracks.\n *\n * The atlas follows the Codex/hatch-pet contract: 8 columns × 9 rows of\n * 192×208 cells (1536×1872 total), rows in this order:\n * 0 idle, 1 running-right, 2 running-left, 3 waving, 4 jumping,\n * 5 failed, 6 waiting, 7 running, 8 review\n *\n * Frame counts and per-frame durations are per-track definitions below; the\n * whale-girl atlas is produced by the hatch-pet pipeline, so calibrate\n * `TRACKS` against the actual run (`pet_request.json` frame counts) when the\n * asset lands. Tracks that do not loop hand off to `fallback`.\n * @module @linxin666/dsh-pet/client/spritesheet\n */\n\nimport type { PetAnimation } from '../state.ts'\n\n/** Atlas cell size in px (Codex contract). */\nexport const FRAME_WIDTH = 192\nexport const FRAME_HEIGHT = 208\n/** Columns per row (max frames per track). */\nexport const FRAME_COLUMNS = 8\n\n/** One animation track: frame indices into the row + per-frame durations. */\nexport interface TrackDef {\n /** Frame indices (columns) played in order; must be < FRAME_COLUMNS. */\n frames: readonly number[]\n /** Per-frame duration in ms; same length as frames. */\n durations: readonly number[]\n /** Whether the track loops; a non-looping track hands off to fallback. */\n loop: boolean\n /** Track to play after a non-looping track finishes. */\n fallback?: PetAnimation\n}\n\n/**\n * Track definitions for the whale-girl. Durations are tuned for a soft,\n * slow-healing feel (roughly 2.5× the earlier fast draft — the pet should\n * breathe, not race); calibrate frame counts against the hatch-pet run when\n * the asset lands (rows may carry 4–8 frames).\n */\nexport const TRACKS: Record<PetAnimation, TrackDef> = {\n idle: { frames: [0, 1, 2, 3, 4, 5], durations: [400, 400, 500, 400, 400, 500], loop: true },\n 'running-right': { frames: [0, 1, 2, 3, 4, 5, 6, 7], durations: [225, 225, 225, 225, 225, 225, 225, 225], loop: true },\n 'running-left': { frames: [0, 1, 2, 3, 4, 5, 6, 7], durations: [225, 225, 225, 225, 225, 225, 225, 225], loop: true },\n waving: { frames: [0, 1, 2, 3], durations: [350, 350, 350, 350], loop: true },\n jumping: { frames: [0, 1, 2, 3, 4], durations: [300, 300, 300, 350, 350], loop: false, fallback: 'idle' },\n failed: { frames: [0, 1, 2, 3, 4, 5, 6, 7], durations: [450, 450, 450, 500, 550, 600, 450, 450], loop: false, fallback: 'idle' },\n waiting: { frames: [0, 1, 2, 3, 4, 5], durations: [450, 450, 500, 450, 450, 500], loop: true },\n running: { frames: [0, 1, 2, 3, 4, 5], durations: [250, 250, 250, 250, 250, 250], loop: true },\n review: { frames: [0, 1, 2, 3, 4, 5], durations: [550, 550, 550, 550, 550, 550], loop: true },\n}\n\n/** Row index of one animation track (mirrors state.ts rowOf). */\nexport function rowOfTrack(animation: PetAnimation): number {\n const rows: Record<PetAnimation, number> = {\n idle: 0,\n 'running-right': 1,\n 'running-left': 2,\n waving: 3,\n jumping: 4,\n failed: 5,\n waiting: 6,\n running: 7,\n review: 8,\n }\n return rows[animation]\n}\n\n/**\n * Background-position (px) of one frame cell within the scaled atlas.\n * The background image is scaled by `scale` (element size ÷ cell size), and\n * background-position offsets are applied in SCALED coordinates — using raw\n * atlas coordinates here would drift each frame by the scale factor and\n * render torn/overlapping frames.\n */\nexport function framePosition(row: number, col: number, scale = 1): { x: number; y: number } {\n return { x: -col * FRAME_WIDTH * scale, y: -row * FRAME_HEIGHT * scale }\n}\n\n/** Total duration of one track, ms. */\nexport function trackDuration(track: TrackDef): number {\n return track.durations.reduce((sum, d) => sum + d, 0)\n}\n\n/**\n * Detect how many frames each row actually carries by scanning the decoded\n * atlas for non-transparent cells (hatch-pet rows may hold 4–8 frames; the\n * unused trailing cells are fully transparent). Rows whose every sample is\n * transparent report 0.\n * @param image - the fully decoded spritesheet (natural size 1536×1872).\n * @returns per-row frame counts, length 9.\n */\nexport function detectFrameCounts(image: HTMLImageElement): number[] {\n const canvas = document.createElement('canvas')\n canvas.width = image.naturalWidth\n canvas.height = image.naturalHeight\n const ctx = canvas.getContext('2d')\n if (ctx === null) return Array.from({ length: 9 }, () => FRAME_COLUMNS)\n ctx.drawImage(image, 0, 0)\n const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data\n const counts: number[] = []\n const stride = FRAME_COLUMNS * FRAME_WIDTH\n const probeStep = 8\n const margin = 12\n for (let row = 0; row < 9; row++) {\n let count = 0\n for (let col = 0; col < FRAME_COLUMNS; col++) {\n let hasContent = false\n const x0 = col * FRAME_WIDTH\n const y0 = row * FRAME_HEIGHT\n for (let y = y0 + margin; y < y0 + FRAME_HEIGHT - margin && !hasContent; y += probeStep) {\n for (let x = x0 + margin; x < x0 + FRAME_WIDTH - margin && !hasContent; x += probeStep) {\n const idx = (y * stride + x) * 4\n if ((data[idx + 3] ?? 0) > 8) hasContent = true\n }\n }\n if (hasContent) count += 1\n }\n counts.push(count)\n }\n return counts\n}\n\n/**\n * Trim a track to the actual frame count of its row. A row with 0 detected\n * frames degrades to the first frame (the atlas is still loading or corrupt)\n * so the pet never renders blank.\n */\nexport function trimTrack(track: TrackDef, frameCount: number): TrackDef {\n const n = Math.max(1, Math.min(frameCount, track.frames.length))\n return {\n frames: track.frames.slice(0, n),\n durations: track.durations.slice(0, n),\n loop: track.loop,\n ...(track.fallback === undefined ? {} : { fallback: track.fallback }),\n }\n}\n","/**\n * Whale-girl companion component — the browser half's centerpiece. Renders a\n * fixed-position floating sprite (React portal onto document.body), plays\n * the spritesheet track matching the host animation snapshot, and exposes\n * the interaction surface: click to pet, hover panel with feed/hide, drag to\n * reposition (persisted via setConfig).\n * @module @linxin666/dsh-pet/client/WhalePet\n */\n\nimport { useEffect, useRef, useState } from 'react'\nimport type { PointerEvent as ReactPointerEvent, ReactPortal } from 'react'\nimport { createPortal } from 'react-dom'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PetDisplayConfig } from '../persist.ts'\nimport type { PetStateView } from '../service.ts'\nimport type { PetFeedback } from './pet-store.ts'\nimport { framePosition, FRAME_WIDTH, FRAME_HEIGHT, FRAME_COLUMNS, TRACKS, rowOfTrack, trimTrack, detectFrameCounts } from './spritesheet.ts'\nimport type { PetAnimation } from '../state.ts'\nimport { NS } from './locales.ts'\nimport styles from './pet.module.css'\n\n/** Browser URL of the whale-girl atlas (served by the host half's own route). */\nexport const PET_SPRITESHEET_URL = '/pet/whale/spritesheet.webp'\n\n/** Browser URL of the whale-girl manifest (authoritative per-row frame counts). */\nexport const PET_MANIFEST_URL = '/pet/whale/pet.json'\n\n/** Props injected by the slot registration (store actions + locale). */\nexport interface WhalePetProps {\n /** Latest host snapshot; null while loading. */\n snapshot: PetStateView | null\n /** Display configuration (persisted by the host). */\n display: PetDisplayConfig\n /** Active reaction bubble, if any. */\n feedback: PetFeedback | null\n /** Pet the whale girl (click). */\n onPet: () => void\n /** Feed the whale girl (panel button). */\n onFeed: () => void\n /** Hide the whale girl (panel button). */\n onHide: () => void\n /** Persist a drag position. */\n onDragEnd: (right: number, bottom: number) => void\n /** Rename the pet (persisted by the host). */\n onRename: (name: string) => void\n /** Clear the reaction bubble (after its CSS animation). */\n onFeedbackDone: () => void\n /** Locale translate seat (namespace-bound). */\n t: TranslateNS<typeof NS>\n}\n\n/** Clamp a drag offset inside the viewport with a margin. */\nfunction clampOffset(value: number, max: number): number {\n return Math.max(0, Math.min(max, value))\n}\n\n/**\n * The floating pet. The spritesheet frame advances on requestAnimationFrame\n * with per-frame durations from TRACKS; the atlas image is loaded once and\n * the background position is written straight to the sprite element (no\n * per-frame React state).\n */\nexport function WhalePet(props: WhalePetProps): ReactPortal {\n const { snapshot, display, feedback } = props\n const spriteRef = useRef<HTMLDivElement | null>(null)\n const floatRef = useRef<HTMLDivElement | null>(null)\n const [imageReady, setImageReady] = useState(false)\n const [frameCounts, setFrameCounts] = useState<number[] | null>(null)\n const [hovered, setHovered] = useState(false)\n const [renaming, setRenaming] = useState(false)\n const [nameDraft, setNameDraft] = useState('')\n const [dragPos, setDragPos] = useState<{ right: number; bottom: number } | null>(null)\n const dragRef = useRef<{ startX: number; startY: number; right: number; bottom: number } | null>(null)\n const frameRef = useRef<{ track: PetAnimation | null; index: number; elapsed: number }>({\n track: null,\n index: 0,\n elapsed: 0,\n })\n\n // Load the atlas once; then resolve per-row frame counts so tracks never\n // play the transparent trailing cells of a short row. One decoded Image\n // feeds both the sprite render and the frame-count detection. The counts\n // prefer the authoritatively recorded `frames` field on the pet.json\n // manifest route and only fall back to the getImageData atlas scan when\n // that field is absent (older manifests).\n useEffect(() => {\n let cancelled = false\n const img = new Image()\n img.onload = () => {\n if (cancelled) return\n setImageReady(true)\n fetch(PET_MANIFEST_URL)\n .then((res) => (res.ok ? res.json() : Promise.resolve<{ frames?: unknown }>({})))\n .then((manifest: { frames?: unknown }) => {\n if (cancelled) return\n const frames = manifest.frames\n if (Array.isArray(frames) && frames.length === 9 && frames.every((n) => typeof n === 'number')) {\n setFrameCounts(frames as number[])\n } else {\n setFrameCounts(detectFrameCounts(img))\n }\n })\n .catch(() => {\n if (!cancelled) setFrameCounts(detectFrameCounts(img))\n })\n }\n img.src = PET_SPRITESHEET_URL\n return () => {\n cancelled = true\n img.onload = null\n }\n }, [])\n\n // Frame loop: advance the current track and write background-position.\n // Offsets must be in SCALED coordinates (background-position applies to the\n // scaled background image), so the current sprite scale rides a ref that\n // the loop reads every tick. Under prefers-reduced-motion the sprite holds\n // its track's first frame instead of animating (presentation-only; the\n // animation state machine is untouched).\n const spriteScale = display.size / FRAME_HEIGHT\n const animation = snapshot?.animation ?? 'idle'\n const scaleRef = useRef(spriteScale)\n scaleRef.current = spriteScale\n useEffect(() => {\n const reduceMotion = typeof window !== 'undefined'\n && window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true\n // Paint one static sprite frame up front either way, so the pet is never\n // blank while the loop heat-up runs.\n const row = rowOfTrack(animation)\n const track = frameCounts === null\n ? TRACKS[animation]\n : trimTrack(TRACKS[animation], frameCounts[row] ?? TRACKS[animation].frames.length)\n const leadCol = track.frames[0]!\n const lead = framePosition(row, leadCol, scaleRef.current)\n if (spriteRef.current !== null) {\n spriteRef.current.style.backgroundPosition = `${lead.x}px ${lead.y}px`\n }\n if (reduceMotion) return\n let raf = 0\n let last = performance.now()\n const tick = (ts: number): void => {\n const delta = ts - last\n last = ts\n // Trim the track to the row's real frame count (transparent cells\n // would render as a vanishing pet).\n const row = rowOfTrack(animation)\n const track = frameCounts === null\n ? TRACKS[animation]\n : trimTrack(TRACKS[animation], frameCounts[row] ?? TRACKS[animation].frames.length)\n const st = frameRef.current\n if (st.track !== animation) {\n st.track = animation\n st.index = 0\n st.elapsed = 0\n }\n st.elapsed += delta\n const maxIndex = track.frames.length - 1\n while (st.elapsed >= (track.durations[st.index] ?? 0) && st.index < maxIndex) {\n st.elapsed -= track.durations[st.index] ?? 0\n st.index += 1\n }\n if (st.elapsed >= (track.durations[st.index] ?? 0)) {\n if (track.loop) {\n st.elapsed = 0\n st.index = 0\n } else {\n st.index = maxIndex // hold the final frame; the host switches tracks\n }\n }\n const col = track.frames[st.index]!\n const { x, y } = framePosition(row, col, scaleRef.current)\n if (spriteRef.current !== null) {\n spriteRef.current.style.backgroundPosition = `${x}px ${y}px`\n }\n raf = requestAnimationFrame(tick)\n }\n raf = requestAnimationFrame(tick)\n return () => cancelAnimationFrame(raf)\n }, [animation, frameCounts])\n\n // Auto-clear the feedback bubble after its CSS animation. The callback\n // rides a ref so re-renders never reset the timer: the 800ms poll rebuilds\n // `props` every tick, and depending on it would starve the timeout.\n const feedbackDoneRef = useRef(props.onFeedbackDone)\n feedbackDoneRef.current = props.onFeedbackDone\n useEffect(() => {\n if (feedback === null) return\n const timer = window.setTimeout(() => feedbackDoneRef.current(), 2600)\n return () => window.clearTimeout(timer)\n }, [feedback])\n\n // Dragging: pointer events on the sprite; position is right/bottom based.\n // `draggedRef` records whether the pointer actually moved, so the browser's\n // trailing click (fired after pointerup) does not pet the whale.\n const draggedRef = useRef(false)\n const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>): void => {\n e.preventDefault()\n ;(e.target as HTMLElement).setPointerCapture?.(e.pointerId)\n const current = dragPos ?? { right: display.right, bottom: display.bottom }\n dragRef.current = { startX: e.clientX, startY: e.clientY, ...current }\n draggedRef.current = false\n setHovered(false)\n }\n const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>): void => {\n const drag = dragRef.current\n if (drag === null) return\n const dx = e.clientX - drag.startX\n const dy = e.clientY - drag.startY\n if (Math.abs(dx) > 4 || Math.abs(dy) > 4) draggedRef.current = true\n const right = clampOffset(drag.right - dx, window.innerWidth - 40)\n const bottom = clampOffset(drag.bottom - dy, window.innerHeight - 40)\n setDragPos({ right, bottom })\n }\n const onPointerUp = (): void => {\n if (dragRef.current === null) return\n dragRef.current = null\n if (dragPos !== null) props.onDragEnd(dragPos.right, dragPos.bottom)\n }\n\n const pos = dragPos ?? { right: display.right, bottom: display.bottom }\n const spriteWidth = Math.round(FRAME_WIDTH * spriteScale)\n const spriteHeight = Math.round(FRAME_HEIGHT * spriteScale)\n\n const float = (\n <div\n ref={floatRef}\n className={styles.float}\n style={{ right: pos.right, bottom: pos.bottom, zIndex: 2147483000 }}\n onPointerEnter={() => setHovered(true)}\n onPointerLeave={(e) => {\n // The panel and bubble render OUTSIDE the container's box (absolute,\n // above the sprite), so moving onto them fires pointerleave on the\n // container. Treat a target still inside the container's DOM (the\n // overflowed panel) as \"still hovering\".\n const next = e.relatedTarget\n if (next instanceof Node && floatRef.current?.contains(next)) return\n setHovered(false)\n }}\n >\n <div\n ref={spriteRef}\n className={styles.sprite}\n style={{\n width: spriteWidth,\n height: spriteHeight,\n backgroundImage: imageReady ? `url(${PET_SPRITESHEET_URL})` : undefined,\n backgroundSize: `${FRAME_WIDTH * FRAME_COLUMNS * spriteScale}px ${FRAME_HEIGHT * 9 * spriteScale}px`,\n backgroundRepeat: 'no-repeat',\n backgroundPosition: '0 0',\n cursor: dragRef.current === null ? 'grab' : 'grabbing',\n }}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onClick={() => {\n // A pointer sequence that moved (dragged) still fires a trailing\n // click; skip the pet when that happened.\n if (draggedRef.current) return\n props.onPet()\n }}\n role=\"button\"\n aria-label=\"whale girl\"\n />\n {feedback !== null && (\n <div key={feedback.at} className={`${styles.bubble} ${feedback.kind === 'feed' ? styles.bubbleFeed : styles.bubblePet}`}>\n {feedback.text}\n </div>\n )}\n {hovered && dragRef.current === null && (\n <div className={styles.panel}>\n {renaming ? (\n <div className={styles.renameRow}>\n <input\n className={styles.nameInput}\n value={nameDraft}\n maxLength={20}\n placeholder={props.t('pet.namePlaceholder')}\n autoFocus\n onChange={(e) => setNameDraft(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n const trimmed = nameDraft.trim()\n if (trimmed !== '') {\n props.onRename(trimmed)\n setRenaming(false)\n }\n } else if (e.key === 'Escape') {\n setRenaming(false)\n }\n }}\n />\n <button\n type=\"button\"\n className={styles.action}\n onClick={() => {\n const trimmed = nameDraft.trim()\n if (trimmed !== '') {\n props.onRename(trimmed)\n setRenaming(false)\n }\n }}\n >\n {props.t('pet.confirm')}\n </button>\n </div>\n ) : (\n <>\n <div className={styles.rankRow}>\n <span className={styles.nameCell}>{snapshot?.name ?? '鲸鱼娘'}</span>\n <span>{props.t('pet.rank', { rank: snapshot?.affinity.rank ?? '?' })}</span>\n </div>\n <div className={styles.rankRow}>\n <span>{props.t('pet.treats', { n: snapshot?.treats.stocked ?? 0 })}</span>\n <span>{props.t('pet.points', { points: snapshot?.affinity.points ?? 0 })}</span>\n </div>\n <div className={styles.actions}>\n <button type=\"button\" className={styles.action} onClick={props.onFeed}>\n {props.t('pet.feed')}\n </button>\n <button\n type=\"button\"\n className={styles.action}\n onClick={() => {\n setNameDraft(snapshot?.name ?? '')\n setRenaming(true)\n }}\n >\n {props.t('pet.rename')}\n </button>\n <button type=\"button\" className={styles.action} onClick={props.onHide}>\n {props.t('pet.hide')}\n </button>\n </div>\n </>\n )}\n </div>\n )}\n </div>\n )\n\n return createPortal(float, document.body)\n}\n","/**\n * Dock anchor inside `conversation.input.selector.context`: the input\n * selector row mounts in EVERY conversation phase (no-session cold start,\n * the blank-session hero, and the active seat), so the floating pet stays on\n * screen on the new-conversation screen too. While visible it mounts the\n * floating WhalePet (portal); while hidden it renders the summon button.\n * @module @linxin666/dsh-pet/client/PetDockEntry\n */\n\nimport { useEffect, useSyncExternalStore, type ReactElement } from 'react'\nimport type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { PetDisplayConfig } from '../persist.ts'\nimport type { PetStoreInstance } from './pet-store.ts'\nimport { WhalePet } from './WhalePet.tsx'\nimport { NS } from './locales.ts'\nimport styles from './pet.module.css'\n\n/** Injected actions handed to the dock entry component. */\nexport interface PetInjected {\n /** The app-wide pet store instance (snapshot + feedback). */\n store: PetStoreInstance\n /** Ensure the first snapshot is fetched (called on mount). */\n ensure: () => void\n /** Pet the whale girl (click). */\n pet: () => void\n /** Feed the whale girl. */\n feed: () => void\n /** Hide the whale girl. */\n hide: () => void\n /** Summon the hidden whale girl back. */\n summon: () => void\n /** Persist a drag position. */\n dragEnd: (right: number, bottom: number) => void\n /** Rename the pet (persisted by the host). */\n rename: (name: string) => void\n /** Clear the reaction bubble. */\n feedbackDone: () => void\n}\n\n/** Composed props of the dock entry (runtime + locale + injected). */\nexport type PetDockEntryProps =\n PropsRuntime<'conversation.input.selector.context'>\n & PetInjected\n & PropsLocale<typeof NS>\n\nconst DEFAULT_DISPLAY: PetDisplayConfig = { visible: true, size: 160, right: 24, bottom: 20 }\n\n/**\n * Dock entry: while the pet is visible, mount the floating WhalePet (it\n * portals itself onto document.body); while hidden, render the summon\n * button so the pet can always come back. The store is the plugin-owned\n * single instance — the slot system provides none because the pet is\n * host-global, not session-scoped.\n */\nexport function PetDockEntry(props: PetDockEntryProps): ReactElement {\n const { store, ensure } = props\n const ui = useSyncExternalStore(store.subscribe, store.getSnapshot)\n const snapshot = ui.snapshot\n const feedback = ui.feedback\n const visible = snapshot?.display.visible ?? true\n\n useEffect(() => {\n ensure()\n }, [ensure])\n\n if (visible) {\n return (\n <span data-pet-dock data-testid=\"pet-dock\">\n <WhalePet\n snapshot={snapshot}\n display={snapshot?.display ?? DEFAULT_DISPLAY}\n feedback={feedback}\n onPet={props.pet}\n onFeed={props.feed}\n onHide={props.hide}\n onDragEnd={props.dragEnd}\n onRename={props.rename}\n onFeedbackDone={props.feedbackDone}\n t={props.t}\n />\n </span>\n )\n }\n return (\n <button\n type=\"button\"\n className={styles.summon}\n onClick={props.summon}\n data-testid=\"pet-summon\"\n >\n {props.t('pet.summon', { name: snapshot?.name ?? '鲸鱼娘' })}\n </button>\n )\n}\n","/**\n * Shared chrome for the plugin settings card: a disclosure header naming the\n * plugin and what its settings govern, the controls inside, and the save that\n * writes them. Renders nothing while the namespace is unavailable — a\n * deployment that does not compose the owning plugin should show no trace of\n * it. Mirrors the official ui-plugin-config PluginCard in a self-contained\n * slice (this package must not depend on a sibling UI package).\n */\n\nimport { useState, type ReactNode } from 'react'\nimport type { CardShell } from './settings-form.ts'\nimport type { SettingsCardKey } from './locales.ts'\nimport css from './settings-card.module.css'\n\n/** Card chrome shared by every plugin settings card. */\nexport interface PluginSettingsCardProps {\n /** Locale reader for this card's copy. */\n t: (key: SettingsCardKey) => string\n /** Locale key of the plugin's name. */\n titleKey: SettingsCardKey\n /** Locale key of the line describing what this plugin's settings govern. */\n descriptionKey: SettingsCardKey\n /** The card's form state: availability, writability, and what a save would do. */\n state: CardShell\n /** Write every staged edit. */\n onSave: () => void\n /** Drop every staged edit. */\n onDiscard: () => void\n /** The plugin's controls. */\n children: ReactNode\n}\n\n/**\n * Render one plugin settings card.\n * @param props - the plugin's copy keys, its form state, and its controls.\n * @returns the card, or nothing when the namespace is unavailable.\n */\nexport function PluginSettingsCard(props: PluginSettingsCardProps) {\n const [open, setOpen] = useState(false)\n const { state } = props\n if (!state.available) return null\n const title = props.t(props.titleKey)\n const blocked = !state.dirty || state.invalid || state.saving\n return (\n <li className={css.card}>\n <button\n type=\"button\"\n className={css.header}\n aria-expanded={open}\n aria-label={`${props.t(open ? 'settings.collapse' : 'settings.expand')}: ${title}`}\n onClick={() => { setOpen(!open) }}\n >\n <span className={css.headText}>\n <span className={css.name}>{title}</span>\n <span className={css.description}>{props.t(props.descriptionKey)}</span>\n </span>\n {state.dirty ? <span className={css.pending}>{props.t('settings.unsaved')}</span> : null}\n <span className={open ? css.chevronOpen : css.chevron}>▾</span>\n </button>\n {open\n ? (\n <div className={css.body}>\n {!state.writable ? <p className={css.readOnly} role=\"status\">{props.t('settings.readOnly')}</p> : null}\n {props.children}\n <div className={css.footer}>\n {state.failed ? <p className={css.failed} role=\"status\">{props.t('settings.saveFailed')}</p> : null}\n <button\n type=\"button\"\n className={css.discard}\n disabled={!state.dirty || state.saving}\n onClick={props.onDiscard}\n >\n {props.t('settings.discard')}\n </button>\n <button\n type=\"button\"\n className={css.save}\n disabled={blocked}\n onClick={props.onSave}\n >\n {props.t(!state.saving ? 'settings.save' : 'settings.saving')}\n </button>\n </div>\n </div>\n )\n : null}\n </li>\n )\n}\n\n/** Props every field control needs regardless of its value type. */\nexport interface FieldProps {\n /** Stable id associating the label with its control. */\n id: string\n /** Visible label. */\n label: string\n /** One-line explanation rendered under the control. */\n hint: string\n /** Draft text this control renders. */\n text: string\n /** True when saving would leave a user-layer entry for this field. */\n overridden: boolean\n /** True when the draft is not a value this field accepts. */\n invalid: boolean\n /** Copy for the overridden badge. */\n overriddenLabel: string\n /** Copy for the reset control. */\n resetLabel: string\n /** Copy shown in place of the hint while the draft is invalid. */\n invalidLabel: string\n /** Disables every control (read-only document, or an unavailable namespace). */\n disabled: boolean\n /** Stage draft text. */\n onEdit: (text: string) => void\n /** Stage a clear so the field re-inherits the composition layer. */\n onReset: () => void\n}\n\n/** A staged value field. `numeric` only hints the keypad: which drafts a field accepts is decided by its spec. */\nexport function ValueField(props: FieldProps & {\n /** Hints a numeric keypad without narrowing what the control accepts. */\n numeric?: boolean\n /** Placeholder shown while the draft is empty. */\n placeholder?: string\n}) {\n return (\n <div className={css.field}>\n <div className={css.head}>\n <label className={css.label} htmlFor={props.id}>{props.label}</label>\n {props.overridden\n ? (\n <span className={css.badges}>\n <span className={css.badge}>{props.overriddenLabel}</span>\n <button\n type=\"button\"\n className={css.reset}\n disabled={props.disabled}\n onClick={props.onReset}\n >\n {props.resetLabel}\n </button>\n </span>\n )\n : null}\n </div>\n <input\n id={props.id}\n className={props.invalid ? css.inputInvalid : css.input}\n type=\"text\"\n {...props.numeric === true ? { inputMode: 'numeric' as const } : {}}\n {...props.invalid ? { 'aria-invalid': true } : {}}\n value={props.text}\n placeholder={props.placeholder ?? ''}\n disabled={props.disabled}\n onChange={(event) => { props.onEdit(event.target.value) }}\n />\n <p className={props.invalid ? css.invalid : css.hint}>\n {props.invalid ? props.invalidLabel : props.hint}\n </p>\n </div>\n )\n}\n\n/** A staged boolean field: 继承 / 开 / 关. */\nexport function BooleanField(props: FieldProps & {\n /** Copy for the inherit option. */\n inheritLabel: string\n /** Copy for the on option. */\n onLabel: string\n /** Copy for the off option. */\n offLabel: string\n}) {\n return (\n <div className={css.field}>\n <div className={css.head}>\n <label className={css.label} htmlFor={props.id}>{props.label}</label>\n {props.overridden\n ? (\n <span className={css.badges}>\n <span className={css.badge}>{props.overriddenLabel}</span>\n <button\n type=\"button\"\n className={css.reset}\n disabled={props.disabled}\n onClick={props.onReset}\n >\n {props.resetLabel}\n </button>\n </span>\n )\n : null}\n </div>\n <select\n id={props.id}\n className={css.select}\n value={props.text}\n disabled={props.disabled}\n onChange={(event) => { props.onEdit(event.target.value) }}\n >\n <option value=\"\">{props.inheritLabel}</option>\n <option value=\"true\">{props.onLabel}</option>\n <option value=\"false\">{props.offLabel}</option>\n </select>\n <p className={css.hint}>{props.hint}</p>\n </div>\n )\n}\n","/**\n * Staged form model behind the plugin settings card. A card stages what the\n * user types and writes it only when they save — the settings write is a\n * durable, revision-fenced document mutation, so staging keeps what is on\n * screen exactly what a save would store. Mirrors the official\n * ui-plugin-config card-store pattern in a self-contained slice: this\n * package must not depend on a sibling UI package.\n */\n\nimport type { SettingsScope, SettingsScopeSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'\nimport { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'\n\n/** The write one field's staged text performs when the card is saved. */\nexport type FieldWrite =\n | { kind: 'set'; value: unknown }\n | { kind: 'clear' }\n\n/** How one field converts between its stored value and its draft text. */\nexport interface FieldSpec {\n /** Field name inside the namespace section. */\n field: string\n /** Render a stored value as draft text; the empty string when the section carries none. */\n format: (value: unknown) => string\n /**\n * The write this draft text stages, or undefined when the text is not a\n * value this field accepts — which blocks the save rather than discarding it.\n */\n parse: (text: string) => FieldWrite | undefined\n}\n\n/** One field as the card renders it. */\nexport interface FieldState {\n /** Draft text the control renders. */\n text: string\n /** Whether saving would leave a user-layer entry for this field. */\n overridden: boolean\n /** Whether the draft is not a value this field accepts, which blocks saving. */\n invalid: boolean\n}\n\n/** Form state every plugin settings card shares. */\nexport interface CardShell {\n /** False while the namespace is not served to this client; the card renders nothing. */\n available: boolean\n /** Whether the Host document accepts writes. */\n writable: boolean\n /** Whether the form holds edits that a save would write. */\n dirty: boolean\n /** Whether any staged draft is invalid, which blocks the save. */\n invalid: boolean\n /** Whether a save is crossing the wire. */\n saving: boolean\n /** Whether the last save did not land as staged; cleared by the next edit or save. */\n failed: boolean\n}\n\n/** The write actions the card's slot entry injects. */\nexport interface CardActions {\n /** Stage draft text for one field. */\n edit: (field: string, text: string) => void\n /** Stage a clear, so saving lets the field re-inherit the composition layer. */\n resetField: (field: string) => void\n /** Write every staged edit, then re-seed from what the Host accepted. */\n save: () => void\n /** Drop every staged edit. */\n discard: () => void\n}\n\n/** One field's staged edit. */\ninterface StagedEdit {\n /** Draft text the control renders. */\n text: string\n /** True when this edit clears the field whatever text it shows. */\n clear: boolean\n}\n\n/** One staged edit resolved into the write a save performs. */\ninterface PlannedWrite {\n /** Field this entry writes. */\n field: string\n /** Perform the write and report whether the Host holds the staged value afterwards. */\n run: (() => Promise<boolean>) | undefined\n}\n\n/** A whole-number field. An empty draft clears the field; any other draft that is not a finite number blocks the save. */\nexport function numberField(field: string): FieldSpec {\n return {\n field,\n format: value => typeof value === 'number' ? String(value) : '',\n parse: (text) => {\n const trimmed = text.trim()\n if (trimmed === '') return { kind: 'clear' }\n const parsed = Number(trimmed)\n return Number.isFinite(parsed) ? { kind: 'set', value: parsed } : undefined\n },\n }\n}\n\n/** A free-text field. An empty draft clears the field. */\nexport function textField(field: string): FieldSpec {\n return {\n field,\n format: value => typeof value === 'string' ? value : '',\n parse: (text) => {\n const trimmed = text.trim()\n return trimmed === '' ? { kind: 'clear' } : { kind: 'set', value: trimmed }\n },\n }\n}\n\n/** A boolean field, edited through true/false draft text. */\nexport function booleanField(field: string): FieldSpec {\n return {\n field,\n format: value => typeof value === 'boolean' ? String(value) : '',\n parse: (text) => {\n if (text === 'true') return { kind: 'set', value: true }\n if (text === 'false') return { kind: 'set', value: false }\n return undefined\n },\n }\n}\n\n/**\n * Stages one card's edits over one settings namespace and writes them on save.\n *\n * The Host is the only authority on whether a value was accepted — its\n * validators own the constraints no schema can express — so the outcome is\n * read back from the section rather than predicted here. A save that did not\n * land keeps its drafts, so the user can correct them instead of retyping.\n */\nexport class CardForm<T> {\n private readonly specs: Map<string, FieldSpec>\n private readonly staged = new Map<string, StagedEdit>()\n private readonly listeners = new Set<() => void>()\n private saving = false\n private failed = false\n\n /** @param scope - the bound settings scope for this card's namespace. */\n constructor(\n private readonly scope: SettingsScope<T>,\n specs: FieldSpec[],\n ) {\n this.specs = new Map(specs.map(spec => [spec.field, spec]))\n scope.subscribe(() => { this.publish() })\n }\n\n /** Publish a projection of this form, rebuilt whenever the scope or a draft changes. */\n bind<S>(project: () => S): SnapshotStore<S> {\n const store = createSnapshotStore(project())\n this.listeners.add(() => { store.set(project()) })\n return store\n }\n\n /** Read the card-level state: what the Host serves, and what a save would do. */\n shell(): CardShell {\n const snapshot = this.scope.getSnapshot()\n const plan = this.plan()\n return {\n available: snapshot.status === 'ready',\n writable: snapshot.writable,\n dirty: plan.length > 0,\n invalid: plan.some(item => item.run === undefined),\n saving: this.saving,\n failed: this.failed,\n }\n }\n\n /** Read one field's state from the effective section and its staged draft. */\n field(field: string): FieldState {\n const spec = this.specOf(field)\n const staged = this.staged.get(field)\n if (staged === undefined) {\n return { text: spec.format(this.sectionValue(field)), overridden: this.stored(field), invalid: false }\n }\n const write = staged.clear ? { kind: 'clear' as const } : spec.parse(staged.text)\n return {\n text: staged.text,\n overridden: write?.kind === 'set',\n invalid: write === undefined,\n }\n }\n\n /** The actions the card's slot registration injects. */\n actions(): CardActions {\n return {\n edit: (field, text) => { this.stage(field, { text, clear: false }) },\n resetField: (field) => {\n this.stage(field, { text: this.specOf(field).format(this.baseValue(field)), clear: true })\n },\n save: () => { void this.save() },\n discard: () => {\n if (this.staged.size === 0 && !this.failed) return\n this.staged.clear()\n this.failed = false\n this.publish()\n },\n }\n }\n\n /**\n * Write every staged edit, then re-seed from what the Host accepted.\n * @returns settlement after every write and the read-back.\n */\n async save(): Promise<void> {\n const plan = this.plan()\n const writes = plan.flatMap(item => item.run === undefined ? [] : [item.run])\n if (plan.length === 0 || this.saving || writes.length !== plan.length) return\n this.saving = true\n this.failed = false\n this.publish()\n let landed = true\n for (const write of writes) {\n landed = await write() && landed\n }\n if (landed) this.staged.clear()\n this.saving = false\n this.failed = !landed\n this.publish()\n }\n\n /**\n * Every staged edit a save would write. An entry whose draft is not a value\n * its field accepts carries no write: the form is still dirty, and the save\n * refuses rather than dropping the edit. A staged edit that matches the\n * effective section is not a write at all.\n * @returns the planned writes, in the order the fields were staged.\n */\n private plan(): PlannedWrite[] {\n const plan: PlannedWrite[] = []\n for (const [field, staged] of this.staged) {\n const spec = this.specOf(field)\n if (staged.clear) {\n if (this.stored(field)) plan.push({ field, run: () => this.clear(field) })\n continue\n }\n if (staged.text === spec.format(this.sectionValue(field))) continue\n const write = spec.parse(staged.text)\n if (write === undefined) plan.push({ field, run: undefined })\n else if (write.kind === 'clear') plan.push({ field, run: () => this.clear(field) })\n else plan.push({ field, run: () => this.store(field, write.value) })\n }\n return plan\n }\n\n private async clear(field: string): Promise<boolean> {\n await this.scope.unset(field)\n return !this.stored(field)\n }\n\n private async store(field: string, value: unknown): Promise<boolean> {\n await this.scope.set(field, value)\n return this.userLayer()?.[field] === value\n }\n\n private stage(field: string, edit: StagedEdit): void {\n this.staged.set(field, edit)\n this.failed = false\n this.publish()\n }\n\n private specOf(field: string): FieldSpec {\n const spec = this.specs.get(field)\n // Every call site names a field this card declared; a missing one is a\n // wiring mistake that must not degrade into a silently inert control.\n if (spec === undefined) throw new Error(`settings card has no field ${field}`)\n return spec\n }\n\n private snapshotOf(): SettingsScopeSnapshot<T> {\n return this.scope.getSnapshot()\n }\n\n private sectionValue(field: string): unknown {\n return (this.snapshotOf().value as Record<string, unknown> | undefined)?.[field]\n }\n\n private baseValue(field: string): unknown {\n return (this.snapshotOf().base as Record<string, unknown> | undefined)?.[field]\n }\n\n private userLayer(): Record<string, unknown> | undefined {\n return this.snapshotOf().user as Record<string, unknown> | undefined\n }\n\n private stored(field: string): boolean {\n const user = this.userLayer()\n return user !== undefined && Object.hasOwn(user, field)\n }\n\n private publish(): void {\n for (const listener of this.listeners) listener()\n }\n}\n","/**\n * The pet settings card: display layout and name, bound to the `pet` settings\n * namespace the host plugin registers. Registered into the\n * `settings.plugin.item` slot the plugin-configuration section renders.\n */\n\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { SettingsScope, SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'\nimport { PluginSettingsCard, ValueField, BooleanField } from './PluginSettingsCard.tsx'\nimport { CardForm, booleanField, numberField, textField, type CardActions, type CardShell, type FieldState as CardFieldState } from './settings-form.ts'\n\n/** The pet's settings fields this card edits (the namespace's full schema). */\nexport interface PetSettings {\n /** Master switch for the plugin. */\n enabled?: boolean\n /** Master switch. */\n visible?: boolean\n /** Scale of the rendered pet in px (sprite cell height). */\n size?: number\n /** Horizontal inset from the viewport right edge, px. */\n right?: number\n /** Vertical inset from the viewport bottom edge, px. */\n bottom?: number\n /** User-customizable pet display name. */\n name?: string\n}\n\n/** What the pet settings card renders. */\nexport interface PetSettingsCardState extends CardShell {\n /** Plugin master switch. */\n enabled: CardFieldState\n /** Master switch. */\n visible: CardFieldState\n /** Pet scale. */\n size: CardFieldState\n /** Right inset. */\n right: CardFieldState\n /** Bottom inset. */\n bottom: CardFieldState\n /** Pet name. */\n name: CardFieldState\n}\n\n/** The registration-side face the card's slot entry injects. */\nexport interface PetSettingsCardFace extends CardActions {\n hooks: {\n /** Card snapshot bound by the renderer as usePetSettingsCard. */\n petSettingsCard: SnapshotStore<PetSettingsCardState>\n }\n}\n\n/** Bridges the `pet` scope onto the card's staged form. */\nexport class PetSettingsCardController {\n private readonly form: CardForm<PetSettings>\n private readonly store: SnapshotStore<PetSettingsCardState>\n\n /** @param scope - the bound settings scope for the `pet` namespace. */\n constructor(scope: SettingsScope<PetSettings>) {\n this.form = new CardForm(scope, [\n booleanField('enabled'),\n booleanField('visible'),\n numberField('size'),\n numberField('right'),\n numberField('bottom'),\n textField('name'),\n ])\n this.store = this.form.bind(() => this.projection())\n }\n\n private projection(): PetSettingsCardState {\n return {\n ...this.form.shell(),\n enabled: this.form.field('enabled'),\n visible: this.form.field('visible'),\n size: this.form.field('size'),\n right: this.form.field('right'),\n bottom: this.form.field('bottom'),\n name: this.form.field('name'),\n }\n }\n\n /**\n * Build the face the card's slot registration injects.\n * @returns the card's snapshot and its form actions.\n */\n inject(): PetSettingsCardFace {\n return { hooks: { petSettingsCard: this.store }, ...this.form.actions() }\n }\n}\n\n/** Props the renderer binds for the pet settings card. */\nexport type PetSettingsCardProps =\n PropsRuntime<'web-ui.plugin.item'>\n & PropsLocale<'pet'>\n & InjectFace<PetSettingsCardFace>\n\n/**\n * Render the pet settings card.\n * @param props - locale copy, the card snapshot, and its form actions.\n * @returns the card.\n */\nexport function PetSettingsCard(props: PetSettingsCardProps) {\n const { t } = props\n const state = props.usePetSettingsCard(snapshot => snapshot)\n const disabled = !state.writable\n const fieldProps = {\n overriddenLabel: t('settings.overridden'),\n resetLabel: t('settings.reset'),\n invalidLabel: t('settings.invalidNumber'),\n disabled,\n }\n return (\n <PluginSettingsCard\n t={t}\n titleKey=\"settings.title\"\n descriptionKey=\"settings.description\"\n state={state}\n onSave={props.save}\n onDiscard={props.discard}\n >\n <BooleanField\n id=\"settings-pet-enabled\"\n label={t('settings.enabled')}\n hint={t('settings.enabledHint')}\n inheritLabel={t('settings.inherit')}\n onLabel={t('settings.on')}\n offLabel={t('settings.off')}\n {...fieldProps}\n {...state.enabled}\n onEdit={(text) => { props.edit('enabled', text) }}\n onReset={() => { props.resetField('enabled') }}\n />\n <BooleanField\n id=\"settings-pet-visible\"\n label={t('settings.visible')}\n hint={t('settings.visibleHint')}\n inheritLabel={t('settings.inherit')}\n onLabel={t('settings.on')}\n offLabel={t('settings.off')}\n {...fieldProps}\n {...state.visible}\n onEdit={(text) => { props.edit('visible', text) }}\n onReset={() => { props.resetField('visible') }}\n />\n <ValueField\n id=\"settings-pet-size\"\n label={t('settings.size')}\n hint={t('settings.sizeHint')}\n numeric\n {...fieldProps}\n {...state.size}\n onEdit={(text) => { props.edit('size', text) }}\n onReset={() => { props.resetField('size') }}\n />\n <ValueField\n id=\"settings-pet-right\"\n label={t('settings.right')}\n hint={t('settings.rightHint')}\n numeric\n {...fieldProps}\n {...state.right}\n onEdit={(text) => { props.edit('right', text) }}\n onReset={() => { props.resetField('right') }}\n />\n <ValueField\n id=\"settings-pet-bottom\"\n label={t('settings.bottom')}\n hint={t('settings.bottomHint')}\n numeric\n {...fieldProps}\n {...state.bottom}\n onEdit={(text) => { props.edit('bottom', text) }}\n onReset={() => { props.resetField('bottom') }}\n />\n <ValueField\n id=\"settings-pet-name\"\n label={t('settings.name')}\n hint={t('settings.nameHint')}\n {...fieldProps}\n {...state.name}\n onEdit={(text) => { props.edit('name', text) }}\n onReset={() => { props.resetField('name') }}\n />\n </PluginSettingsCard>\n )\n}\n","/**\n * dsh-pet locale dictionaries (zh/en).\n * @module @linxin666/dsh-pet/client/locales\n */\n\n/** Dictionary namespace this package registers. */\nexport const NS = 'pet'\n\n/** Chinese copy. */\nexport const zh = {\n 'pet.feed': '喂食',\n 'pet.hide': '隐藏',\n 'pet.rename': '改名',\n 'pet.confirm': '确定',\n 'pet.namePlaceholder': '输入新名字',\n 'pet.summon': '召唤{name}',\n 'pet.rank': '亲密度 {rank}',\n 'pet.points': '{points} 点',\n 'pet.treats': '小鱼干 ×{n}',\n 'pet.state.loading': '鲸鱼娘正在赶来…',\n 'pet.state.error': '鲸鱼娘迷路了(连接失败)',\n // 插件设置卡片(settings.plugin.item 席位)。\n 'settings.title': '宠物',\n 'settings.description': '鲸鱼娘的显示布局与名字。',\n 'settings.enabled': '启用宠物',\n 'settings.enabledHint': '关闭后隐藏宠物并停止轮询,可在设置里重新启用。',\n 'settings.visible': '显示宠物',\n 'settings.visibleHint': '关闭后宠物隐藏,可从聊天输入区重新召唤。',\n 'settings.size': '大小(px)',\n 'settings.sizeHint': '精灵单元高度,范围 32–512。',\n 'settings.right': '距右侧(px)',\n 'settings.rightHint': '距视口右边缘的水平内缩距离。',\n 'settings.bottom': '距底部(px)',\n 'settings.bottomHint': '距视口底边的垂直内缩距离。',\n 'settings.name': '名字',\n 'settings.nameHint': '宠物显示名,1–20 个字符。',\n 'settings.inherit': '继承',\n 'settings.on': '开',\n 'settings.off': '关',\n 'settings.overridden': '已覆盖',\n 'settings.reset': '恢复默认',\n 'settings.readOnly': '当前部署的设置只读。',\n 'settings.expand': '展开设置',\n 'settings.collapse': '收起设置',\n 'settings.save': '保存',\n 'settings.saving': '保存中…',\n 'settings.discard': '放弃',\n 'settings.unsaved': '未保存',\n 'settings.saveFailed': '部署未接受这些值,已保留供你修改。',\n 'settings.invalidNumber': '请输入数字,留空则使用默认值。',\n} as const\n\n/** English copy. */\nexport const en = {\n 'pet.feed': 'Feed',\n 'pet.hide': 'Hide',\n 'pet.rename': 'Rename',\n 'pet.confirm': 'OK',\n 'pet.namePlaceholder': 'Enter a new name',\n 'pet.summon': 'Summon {name}',\n 'pet.rank': 'Affinity {rank}',\n 'pet.points': '{points} pts',\n 'pet.treats': 'Treats ×{n}',\n 'pet.state.loading': 'The whale girl is on her way…',\n 'pet.state.error': 'The whale girl is lost (connection failed)',\n // Plugin settings card (the `settings.plugin.item` seat).\n 'settings.title': 'Pet',\n 'settings.description': 'The whale girl\\u2019s display layout and name.',\n 'settings.enabled': 'Enable the pet',\n 'settings.enabledHint': 'When off, the pet hides and polling stops; re-enable it here.',\n 'settings.visible': 'Show the pet',\n 'settings.visibleHint': 'When off, the pet hides; summon it again from the input row.',\n 'settings.size': 'Size (px)',\n 'settings.sizeHint': 'Sprite cell height, 32\\u2013512.',\n 'settings.right': 'Right inset (px)',\n 'settings.rightHint': 'Horizontal inset from the viewport right edge.',\n 'settings.bottom': 'Bottom inset (px)',\n 'settings.bottomHint': 'Vertical inset from the viewport bottom edge.',\n 'settings.name': 'Name',\n 'settings.nameHint': 'The pet\\u2019s display name, 1\\u201320 characters.',\n 'settings.inherit': 'Inherit',\n 'settings.on': 'On',\n 'settings.off': 'Off',\n 'settings.overridden': 'Overridden',\n 'settings.reset': 'Reset to default',\n 'settings.readOnly': 'This deployment stores settings read-only.',\n 'settings.expand': 'Show settings',\n 'settings.collapse': 'Hide settings',\n 'settings.save': 'Save',\n 'settings.saving': 'Saving\\u2026',\n 'settings.discard': 'Discard',\n 'settings.unsaved': 'Unsaved',\n 'settings.saveFailed': 'The deployment did not accept these values; they were left for you to correct.',\n 'settings.invalidNumber': 'Enter a number, or leave blank to use the default.',\n} as const\n\n/** Key union for this namespace. */\nexport type PetKey = keyof typeof zh\n\n/** The settings-card slice of the pet dictionary. */\nexport type SettingsCardKey = PetKey\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** dsh-pet UI copy. */\n pet: PetKey\n }\n}\n","/**\n * dsh-pet browser half — registers the whale-girl into the conversation\n * input selector row (the same every-phase row the git branch chip uses) and\n * drives it from the host's same-origin `/api/pet/*` JSON endpoints: poll the\n * host snapshot (~800 ms), forward interactions, persist drag positions. The\n * row anchor mounts the floating pet via portal; when the pet is hidden the\n * anchor becomes the summon button. Anchoring in the selector row (rather\n * than the session-only composer dock band) keeps the pet floating on the\n * new-conversation screen too, where no session exists to scope a slot by.\n * @module @linxin666/dsh-pet/client\n */\n\nimport type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\n// Type-only: pulls the settings-surface Context merge (ctx.settingsScope).\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-slots'\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { PetDisplayConfig } from '../persist.ts'\nimport type { PetInteractResult, PetStateView } from '../service.ts'\nimport type { PetInteraction } from '../affinity.ts'\nimport { createPetStore, type PetStoreInstance } from './pet-store.ts'\nimport { PetDockEntry, type PetInjected } from './PetDockEntry.tsx'\nimport { PetSettingsCard, PetSettingsCardController, type PetSettings } from './PetSettingsCard.tsx'\nimport { NS, en, zh } from './locales.ts'\n\n/** The host pet API as the browser sees it (same-origin JSON endpoints). */\ninterface PetHttpApi {\n state(): Promise<PetStateView>\n interact(kind: PetInteraction): Promise<PetInteractResult>\n setVisible(visible: boolean): Promise<{ ok: true; display: PetDisplayConfig }>\n setConfig(patch: Partial<PetDisplayConfig>): Promise<{ ok: true; display: PetDisplayConfig }>\n setName(name: string): Promise<{ ok: true; name: string } | { ok: false; error: string }>\n}\n\n/** Same-origin JSON fetch helper (GET without body, POST with JSON body). */\nasync function petFetch<T>(path: string, body?: unknown): Promise<T> {\n const response = await fetch(path, body === undefined\n ? {}\n : {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!response.ok) {\n throw new Error(`pet ${path} failed: ${response.status}`)\n }\n return (await response.json()) as T\n}\n\n/** The live host API instance (always defined; failures surface per call). */\nconst petApi: PetHttpApi = {\n state: () => petFetch('/api/pet/state'),\n interact: (kind) => petFetch('/api/pet/interact', { kind }),\n setVisible: (visible) => petFetch('/api/pet/set-visible', { visible }),\n setConfig: (patch) => petFetch('/api/pet/set-config', patch),\n setName: (name) => petFetch('/api/pet/set-name', { name }),\n}\n\n/** Poll interval for the host snapshot. */\nconst POLL_MS = 800\n\n/** Settings namespace the pet settings card edits (the Host plugin registers it). */\nconst PET_SETTINGS_NS = 'pet'\n\n/** Required services. */\nexport const inject = ['slots', 'locale', 'connection', 'settingsScope', 'remote']\n\n/** Re-exported for consumers that type against the injected face. */\nexport type { PetInjected, PetDockEntryProps } from './PetDockEntry.tsx'\nexport type { PetUiState, PetFeedback } from './pet-store.ts'\nexport type { PetSettingsCardFace, PetSettingsCardState } from './PetSettingsCard.tsx'\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface SlotMap {\n /**\n * The child slot the Web UI plugin group declares; this card registers\n * into the group instead of the top-level `settings.plugin.item` list.\n * Spelled here with the same shape so this package can register without\n * depending on the sibling UI package.\n */\n 'web-ui.plugin.item': { kind: 'list'; scope: 'root'; owner: SettingsPluginItemOwnerProps }\n }\n}\n\n/** Owner share of a plugin card (the group card supplies nothing). */\nexport interface SettingsPluginItemOwnerProps {\n /** Marker field: card owner props are intentionally empty. */\n children?: never\n}\n\n/**\n * Client plugin body: register dictionaries, mount the dock entry and poll\n * loop while the plugin is enabled, and seat the settings card in the Web UI\n * plugin group.\n * @param ctx - client root context.\n */\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'pet: dictionaries')\n\n const settingsScope = ctx.settingsScope.bind<PetSettings>({ namespace: PET_SETTINGS_NS })\n const enabled = (): boolean => {\n const snapshot = settingsScope.getSnapshot()\n return snapshot.status === 'ready'\n ? snapshot.value?.enabled ?? true\n : snapshot.status === 'unavailable'\n }\n\n // Plugin configuration card: one staged form over the `pet` settings\n // namespace, contributed to the Web UI plugin group.\n const petSettings = new PetSettingsCardController(settingsScope)\n ctx.slots.inject('web-ui.plugin.item', () => ctx.slots.register({\n name: 'web-ui.plugin.item',\n id: 'pet-settings',\n order: 140,\n locale: NS,\n inject: () => petSettings.inject(),\n }, PetSettingsCard))\n\n // The dock entry, its store, and the poll loop live while the plugin is\n // enabled; toggling the setting off hides the pet and stops polling.\n let disposeUi: (() => void) | undefined\n const syncUi = (): void => {\n if (enabled() && disposeUi === undefined) {\n // ONE store instance for the whole app, owned by this apply body. The\n // pet is host-global (state/display/interactions are /api/pet/*\n // endpoints with no session dimension), so the slot system's per-session\n // store scoping would only reset the pet on session switches and leave\n // it stateless on the new-conversation screen (no session to scope by).\n const petStore: PetStoreInstance = createPetStore().create()\n const setSnapshot = petStore.actions.setSnapshot\n const setState = petStore.actions.setState\n const setFeedback = petStore.actions.setFeedback\n\n const pollNow = (): void => {\n petApi.state().then((snapshot) => {\n setSnapshot(snapshot)\n }, () => {\n setState('error', 'pet.state transport error')\n })\n }\n\n const disposePoll = ctx.effect(() => {\n // Poll only while the tab is visible: the host snapshot does not\n // change while the page is hidden, so a background interval would\n // only burn RPCs (browser throttling is an unreliable backstop).\n // Coming back to the tab refreshes the pet immediately instead of\n // waiting out the next 800 ms cycle.\n let timer: number | undefined\n const stop = (): void => {\n if (timer !== undefined) {\n window.clearInterval(timer)\n timer = undefined\n }\n }\n const start = (): void => {\n if (timer === undefined && document.visibilityState === 'visible') {\n timer = window.setInterval(pollNow, POLL_MS)\n }\n }\n const onVisibility = (): void => {\n if (document.visibilityState === 'visible') {\n pollNow()\n start()\n } else {\n stop()\n }\n }\n start()\n document.addEventListener('visibilitychange', onVisibility)\n return () => {\n stop()\n document.removeEventListener('visibilitychange', onVisibility)\n }\n }, 'pet: poll')\n\n const injected = (): PetInjected => ({\n store: petStore,\n ensure: pollNow,\n pet: () => {\n petApi.interact('pet').then((result) => {\n setFeedback({\n text: result.reaction,\n kind: 'pet',\n at: Date.now(),\n })\n }, () => {\n // Ignore transport errors on interactions; the next poll resyncs.\n })\n },\n feed: () => {\n petApi.interact('feed').then((result) => {\n setFeedback({\n text: result.reaction,\n kind: 'feed',\n at: Date.now(),\n })\n }, () => {\n // Ignore transport errors on interactions; the next poll resyncs.\n })\n },\n hide: () => {\n petApi.setVisible(false).then(() => {\n pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n summon: () => {\n petApi.setVisible(true).then(() => {\n pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n dragEnd: (right, bottom) => {\n petApi.setConfig({ right, bottom }).then(() => {\n pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n rename: (name) => {\n petApi.setName(name).then((result) => {\n if (result.ok) pollNow()\n }, () => {\n // Ignore; next poll resyncs.\n })\n },\n feedbackDone: () => {\n setFeedback(null)\n },\n })\n\n // The input selector row mounts in EVERY conversation phase (cold\n // start, blank-session hero, active seat) — the composer dock band\n // only renders for an active session, which is why the pet used to\n // vanish on the new-conversation screen.\n const disposeDock = ctx.slots.inject('conversation.input.selector.context', () =>\n ctx.slots.register({\n name: 'conversation.input.selector.context',\n id: 'pet',\n order: 110,\n inject: injected,\n locale: NS,\n }, PetDockEntry))\n\n disposeUi = () => {\n disposeDock()\n disposePoll()\n disposeUi = undefined\n }\n } else if (!enabled() && disposeUi !== undefined) {\n disposeUi()\n disposeUi = undefined\n }\n }\n settingsScope.subscribe(syncUi)\n syncUi()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;EA8CA,SAAgB,iBAA8D;GAC5E,QAAA,GAAA,uCAAA,YAAA,CAAmB;IACjB,aAAyB;KACvB,UAAU;KACV,OAAO;KACP,OAAO;KACP,UAAU;IACZ;IACA,SAAS;KACP,cAAc,OAAO,aAAa;MAChC,MAAM,WAAW;MACjB,MAAM,QAAQ;MACd,MAAM,QAAQ;KAChB;KACA,WAAW,OAAO,OAAO,UAAU;MACjC,MAAM,QAAQ;MACd,MAAM,QAAQ;KAChB;KACA,cAAc,OAAO,aAAa;MAChC,MAAM,WAAW;KACnB;IACF;GACF,CAAC;EACH;;;;;;;EC5BA,MAAa,SAAyC;GACpD,MAAM;IAAE,QAAQ;KAAC;KAAG;KAAG;KAAG;KAAG;KAAG;IAAC;IAAG,WAAW;KAAC;KAA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;QAClC,QAAQ;OACV,SAAS,CAET,CAAC;MACH;MACA,cAAc;OACZ,OAAO,WAAW,IAAI,CAAC,CAAC,WAAW;QACjC,QAAQ;OACV,SAAS,CAET,CAAC;MACH;MACA,UAAU,OAAO,WAAW;OAC1B,OAAO,UAAU;QAAE;QAAO;OAAO,CAAC,CAAC,CAAC,WAAW;QAC7C,QAAQ;OACV,SAAS,CAET,CAAC;MACH;MACA,SAAS,SAAS;OAChB,OAAO,QAAQ,IAAI,CAAC,CAAC,MAAM,WAAW;QACpC,IAAI,OAAO,IAAI,QAAQ;OACzB,SAAS,CAET,CAAC;MACH;MACA,oBAAoB;OAClB,YAAY,IAAI;MAClB;KACF;KAMA,MAAM,cAAc,IAAI,MAAM,OAAO,6CACnC,IAAI,MAAM,SAAS;MACjB,MAAM;MACN,IAAI;MACJ,OAAO;MACP,QAAQ;MACR,QAAA;KACF,GAAG,YAAY,CAAC;KAElB,kBAAkB;MAChB,YAAY;MACZ,YAAY;MACZ,YAAY,KAAA;KACd;IACF,OAAO,IAAI,CAAC,QAAQ,KAAK,cAAc,KAAA,GAAW;KAChD,UAAU;KACV,YAAY,KAAA;IACd;GACF;GACA,cAAc,UAAU,MAAM;GAC9B,OAAO;EACT"}
@@ -0,0 +1,217 @@
1
+ //#region lib/types/affinity.js
2
+ /**
3
+ * Affinity score — pure, clock-injected. The pet grows closer the more you
4
+ * work together and care for it: every completed turn earns a small reward,
5
+ * petting earns a tiny one (cooldown-gated), feeding earns the most.
6
+ * Persistence lives in the service; this module only computes transitions.
7
+ * @module @deepseek-ai/dsh-pet/affinity
8
+ */
9
+ const AFFINITY_MAX = 100;
10
+ /** Affinity ranks by points; the pet visibly grows with its rank. */
11
+ const AFFINITY_RANKS = [
12
+ {
13
+ min: 0,
14
+ name: "幼鲸",
15
+ emoji: "🐣"
16
+ },
17
+ {
18
+ min: 25,
19
+ name: "伙伴",
20
+ emoji: "🐬"
21
+ },
22
+ {
23
+ min: 50,
24
+ name: "挚友",
25
+ emoji: "🐳"
26
+ },
27
+ {
28
+ min: 80,
29
+ name: "深海羁绊",
30
+ emoji: "💙"
31
+ }
32
+ ];
33
+ const defaultAffinityConfig = {
34
+ turnReward: 1,
35
+ petReward: 1,
36
+ petCooldownMs: 1e4,
37
+ feedReward: 5,
38
+ feedCooldownMs: 3e4
39
+ };
40
+ function emptyAffinity() {
41
+ return {
42
+ points: 0,
43
+ lastPetAt: 0,
44
+ lastFeedAt: 0,
45
+ pets: 0,
46
+ feeds: 0,
47
+ turns: 0
48
+ };
49
+ }
50
+ /** Rank for a point total. */
51
+ function rankOf(points) {
52
+ let rank = AFFINITY_RANKS[0];
53
+ for (const candidate of AFFINITY_RANKS) if (points >= candidate.min) rank = candidate;
54
+ return rank;
55
+ }
56
+ function clamp(points) {
57
+ return Math.min(100, Math.max(0, points));
58
+ }
59
+ /**
60
+ * Apply one interaction to a copy of the state (immutable style: returns a
61
+ * new object; the caller replaces the persisted state). Cooldowns only
62
+ * apply once the pet has been interacted with at least once (last*At === 0
63
+ * means "never", so the first pet/feed always lands).
64
+ */
65
+ function applyInteraction(state, kind, nowMs, config = defaultAffinityConfig) {
66
+ const next = { ...state };
67
+ if (kind === "pet") {
68
+ if (state.lastPetAt !== 0 && nowMs - state.lastPetAt < config.petCooldownMs) return {
69
+ affinity: state,
70
+ delta: 0,
71
+ reaction: "摸过头啦,让鲸鱼娘歇口气~",
72
+ accepted: false
73
+ };
74
+ next.lastPetAt = nowMs;
75
+ next.pets += 1;
76
+ next.points = clamp(state.points + config.petReward);
77
+ return {
78
+ affinity: next,
79
+ delta: config.petReward,
80
+ reaction: "咕噜咕噜~被摸摸好舒服!",
81
+ accepted: true
82
+ };
83
+ }
84
+ if (kind === "feed") {
85
+ if (state.lastFeedAt !== 0 && nowMs - state.lastFeedAt < config.feedCooldownMs) return {
86
+ affinity: state,
87
+ delta: 0,
88
+ reaction: "吃饱啦,晚点再喂~",
89
+ accepted: false
90
+ };
91
+ next.lastFeedAt = nowMs;
92
+ next.feeds += 1;
93
+ next.points = clamp(state.points + config.feedReward);
94
+ return {
95
+ affinity: next,
96
+ delta: config.feedReward,
97
+ reaction: "呜哇!小鱼干好好吃!",
98
+ accepted: true
99
+ };
100
+ }
101
+ return {
102
+ affinity: state,
103
+ delta: 0,
104
+ reaction: "",
105
+ accepted: false
106
+ };
107
+ }
108
+ /** Reward one completed turn (called by the host on `done`). */
109
+ function applyTurnReward(state, config = defaultAffinityConfig) {
110
+ const next = { ...state };
111
+ next.turns += 1;
112
+ next.points = clamp(state.points + config.turnReward);
113
+ return next;
114
+ }
115
+ //#endregion
116
+ //#region lib/types/state.js
117
+ /**
118
+ * Pet state machine — pure, clock-injected. Maps the DSH `activity/status`
119
+ * phase vocabulary (session events) onto the 9-state Codex pet
120
+ * animation contract, plus the session lifecycle transitions the web UI
121
+ * exposes (turn end celebration, no-session idle).
122
+ *
123
+ * The machine is deliberately dumb: it holds the last input phase, the
124
+ * animation decision, and a one-shot "celebration" window after `done` so the
125
+ * pet visibly jumps before settling back to idle. Everything here is a pure
126
+ * function of (input, nowMs); persistence and RPC live in the service.
127
+ * @module @deepseek-ai/dsh-pet/state
128
+ */
129
+ const defaultPetStateConfig = { celebrateMs: 2400 };
130
+ /**
131
+ * Map one activity phase onto the animation contract.
132
+ * - thinking / tool → `running` (focused work), with `running-right` as the
133
+ * side-alternating variant the client may use for tool activity.
134
+ * - waiting → `waiting` (expectant pose, needs user input).
135
+ * - done → `jumping` (celebration), then back to `idle` after the window.
136
+ * - idle → `idle` (calm breathing loop).
137
+ * `failed` has no DSH phase source yet; the machine keeps the mapping table
138
+ * so a future error event can light it up.
139
+ */
140
+ function animationForPhase(phase) {
141
+ switch (phase) {
142
+ case "thinking": return "running";
143
+ case "tool": return "running-right";
144
+ case "waiting": return "waiting";
145
+ case "done": return "jumping";
146
+ case "idle": return "idle";
147
+ }
148
+ }
149
+ /** The spritesheet row index for one animation track. */
150
+ function rowOf(animation) {
151
+ return {
152
+ "idle": 0,
153
+ "running-right": 1,
154
+ "running-left": 2,
155
+ "waving": 3,
156
+ "jumping": 4,
157
+ "failed": 5,
158
+ "waiting": 6,
159
+ "running": 7,
160
+ "review": 8
161
+ }[animation];
162
+ }
163
+ /**
164
+ * PetStateMachine — one instance per host process. Holds only the latest
165
+ * input snapshot and the celebration timing; no storage, no side effects.
166
+ */
167
+ var PetStateMachine = class {
168
+ config;
169
+ now;
170
+ phase = "idle";
171
+ line;
172
+ phrase;
173
+ sessionActive = false;
174
+ doneAt;
175
+ constructor(config = defaultPetStateConfig, now = Date.now) {
176
+ this.config = config;
177
+ this.now = now;
178
+ }
179
+ /** Consume one `activity/status` session event. */
180
+ onActivityStatus(input) {
181
+ this.phase = input.phase;
182
+ this.line = input.line;
183
+ this.phrase = input.phrase;
184
+ if (input.phase === "done") this.doneAt = this.now();
185
+ }
186
+ /** A session became the active one (or a fresh session started). */
187
+ onSessionActive() {
188
+ this.sessionActive = true;
189
+ }
190
+ /** The active session was disposed (or none left). */
191
+ onSessionDisposed() {
192
+ this.sessionActive = false;
193
+ this.phase = "idle";
194
+ this.line = void 0;
195
+ this.phrase = void 0;
196
+ this.doneAt = void 0;
197
+ }
198
+ /** Render the current animation decision. */
199
+ render() {
200
+ const nowMs = this.now();
201
+ let animation = animationForPhase(this.phase);
202
+ if (this.phase === "done" && this.doneAt !== void 0) {
203
+ if (nowMs - this.doneAt < this.config.celebrateMs) animation = "jumping";
204
+ else animation = "idle";
205
+ }
206
+ const bubble = this.phrase ?? this.line;
207
+ return {
208
+ animation,
209
+ ...bubble === void 0 ? {} : { bubble },
210
+ animationStartedAt: nowMs,
211
+ phase: this.phase,
212
+ sessionActive: this.sessionActive
213
+ };
214
+ }
215
+ };
216
+ //#endregion
217
+ export { AFFINITY_MAX as a, applyTurnReward as c, rankOf as d, rowOf as i, defaultAffinityConfig as l, animationForPhase as n, AFFINITY_RANKS as o, defaultPetStateConfig as r, applyInteraction as s, PetStateMachine as t, emptyAffinity as u };
@@ -0,0 +1,196 @@
1
+ //#region src/affinity.ts
2
+ const AFFINITY_MAX = 100;
3
+ /** Affinity ranks by points; the pet visibly grows with its rank. */
4
+ const AFFINITY_RANKS = [
5
+ {
6
+ min: 0,
7
+ name: "幼鲸",
8
+ emoji: "🐣"
9
+ },
10
+ {
11
+ min: 25,
12
+ name: "伙伴",
13
+ emoji: "🐬"
14
+ },
15
+ {
16
+ min: 50,
17
+ name: "挚友",
18
+ emoji: "🐳"
19
+ },
20
+ {
21
+ min: 80,
22
+ name: "深海羁绊",
23
+ emoji: "💙"
24
+ }
25
+ ];
26
+ const defaultAffinityConfig = {
27
+ turnReward: 1,
28
+ petReward: 1,
29
+ petCooldownMs: 1e4,
30
+ feedReward: 5,
31
+ feedCooldownMs: 3e4
32
+ };
33
+ function emptyAffinity() {
34
+ return {
35
+ points: 0,
36
+ lastPetAt: 0,
37
+ lastFeedAt: 0,
38
+ pets: 0,
39
+ feeds: 0,
40
+ turns: 0
41
+ };
42
+ }
43
+ /** Rank for a point total. */
44
+ function rankOf(points) {
45
+ let rank = AFFINITY_RANKS[0];
46
+ for (const candidate of AFFINITY_RANKS) if (points >= candidate.min) rank = candidate;
47
+ return rank;
48
+ }
49
+ function clamp(points) {
50
+ return Math.min(100, Math.max(0, points));
51
+ }
52
+ /**
53
+ * Apply one interaction to a copy of the state (immutable style: returns a
54
+ * new object; the caller replaces the persisted state). Cooldowns only
55
+ * apply once the pet has been interacted with at least once (last*At === 0
56
+ * means "never", so the first pet/feed always lands).
57
+ */
58
+ function applyInteraction(state, kind, nowMs, config = defaultAffinityConfig) {
59
+ const next = { ...state };
60
+ if (kind === "pet") {
61
+ if (state.lastPetAt !== 0 && nowMs - state.lastPetAt < config.petCooldownMs) return {
62
+ affinity: state,
63
+ delta: 0,
64
+ reaction: "摸过头啦,让鲸鱼娘歇口气~",
65
+ accepted: false
66
+ };
67
+ next.lastPetAt = nowMs;
68
+ next.pets += 1;
69
+ next.points = clamp(state.points + config.petReward);
70
+ return {
71
+ affinity: next,
72
+ delta: config.petReward,
73
+ reaction: "咕噜咕噜~被摸摸好舒服!",
74
+ accepted: true
75
+ };
76
+ }
77
+ if (kind === "feed") {
78
+ if (state.lastFeedAt !== 0 && nowMs - state.lastFeedAt < config.feedCooldownMs) return {
79
+ affinity: state,
80
+ delta: 0,
81
+ reaction: "吃饱啦,晚点再喂~",
82
+ accepted: false
83
+ };
84
+ next.lastFeedAt = nowMs;
85
+ next.feeds += 1;
86
+ next.points = clamp(state.points + config.feedReward);
87
+ return {
88
+ affinity: next,
89
+ delta: config.feedReward,
90
+ reaction: "呜哇!小鱼干好好吃!",
91
+ accepted: true
92
+ };
93
+ }
94
+ return {
95
+ affinity: state,
96
+ delta: 0,
97
+ reaction: "",
98
+ accepted: false
99
+ };
100
+ }
101
+ /** Reward one completed turn (called by the host on `done`). */
102
+ function applyTurnReward(state, config = defaultAffinityConfig) {
103
+ const next = { ...state };
104
+ next.turns += 1;
105
+ next.points = clamp(state.points + config.turnReward);
106
+ return next;
107
+ }
108
+ //#endregion
109
+ //#region src/state.ts
110
+ const defaultPetStateConfig = { celebrateMs: 2400 };
111
+ /**
112
+ * Map one activity phase onto the animation contract.
113
+ * - thinking / tool → `running` (focused work), with `running-right` as the
114
+ * side-alternating variant the client may use for tool activity.
115
+ * - waiting → `waiting` (expectant pose, needs user input).
116
+ * - done → `jumping` (celebration), then back to `idle` after the window.
117
+ * - idle → `idle` (calm breathing loop).
118
+ * `failed` has no DSH phase source yet; the machine keeps the mapping table
119
+ * so a future error event can light it up.
120
+ */
121
+ function animationForPhase(phase) {
122
+ switch (phase) {
123
+ case "thinking": return "running";
124
+ case "tool": return "running-right";
125
+ case "waiting": return "waiting";
126
+ case "done": return "jumping";
127
+ case "idle": return "idle";
128
+ }
129
+ }
130
+ /** The spritesheet row index for one animation track. */
131
+ function rowOf(animation) {
132
+ return {
133
+ "idle": 0,
134
+ "running-right": 1,
135
+ "running-left": 2,
136
+ "waving": 3,
137
+ "jumping": 4,
138
+ "failed": 5,
139
+ "waiting": 6,
140
+ "running": 7,
141
+ "review": 8
142
+ }[animation];
143
+ }
144
+ /**
145
+ * PetStateMachine — one instance per host process. Holds only the latest
146
+ * input snapshot and the celebration timing; no storage, no side effects.
147
+ */
148
+ var PetStateMachine = class {
149
+ config;
150
+ now;
151
+ phase = "idle";
152
+ line;
153
+ phrase;
154
+ sessionActive = false;
155
+ doneAt;
156
+ constructor(config = defaultPetStateConfig, now = Date.now) {
157
+ this.config = config;
158
+ this.now = now;
159
+ }
160
+ /** Consume one `activity/status` session event. */
161
+ onActivityStatus(input) {
162
+ this.phase = input.phase;
163
+ this.line = input.line;
164
+ this.phrase = input.phrase;
165
+ if (input.phase === "done") this.doneAt = this.now();
166
+ }
167
+ /** A session became the active one (or a fresh session started). */
168
+ onSessionActive() {
169
+ this.sessionActive = true;
170
+ }
171
+ /** The active session was disposed (or none left). */
172
+ onSessionDisposed() {
173
+ this.sessionActive = false;
174
+ this.phase = "idle";
175
+ this.line = void 0;
176
+ this.phrase = void 0;
177
+ this.doneAt = void 0;
178
+ }
179
+ /** Render the current animation decision. */
180
+ render() {
181
+ const nowMs = this.now();
182
+ let animation = animationForPhase(this.phase);
183
+ if (this.phase === "done" && this.doneAt !== void 0) if (nowMs - this.doneAt < this.config.celebrateMs) animation = "jumping";
184
+ else animation = "idle";
185
+ const bubble = this.phrase ?? this.line;
186
+ return {
187
+ animation,
188
+ ...bubble === void 0 ? {} : { bubble },
189
+ animationStartedAt: nowMs,
190
+ phase: this.phase,
191
+ sessionActive: this.sessionActive
192
+ };
193
+ }
194
+ };
195
+ //#endregion
196
+ export { AFFINITY_MAX as a, applyTurnReward as c, rankOf as d, rowOf as i, defaultAffinityConfig as l, animationForPhase as n, AFFINITY_RANKS as o, defaultPetStateConfig as r, applyInteraction as s, PetStateMachine as t, emptyAffinity as u };