dsh-companion-heartbeat
Manifest validDecision-based heartbeat for AI companions: three needs drift while nobody talks and drop on a reply, deciding per chat whether the persona speaks first — delivered through a JSON file, WeChatAgent, o
dsh-companion-heartbeat
A small impulse engine for AI companions, packaged as a DeepSeek Harness (DSH) plugin.
Repository: https://github.com/Joe-Miller-1314/dsh-companion-heartbeat · License: MIT · Node.js 20+
Most companion setups only react: a message arrives, the persona answers. dsh-companion-heartbeat gives the persona a slow internal clock instead. Three needs — missing the other person, wanting company, being curious — rise quietly over time, get satisfied when the other person actually writes, and once in a while spike for no reason at all. Every few seconds the plugin asks one question:
Does the persona want to say something right now, and how soon may it speak again?
The answer is written somewhere a host application can read: a plain JSON file, or the proactive-message switch of a chat host app. Nothing else is coupled to the plugin.
needs ──► impulse ──► (suppression) ──► decision ──► adapter ──► your app
▲
activity from the chat buffer (who spoke last, and when)
What it does
- Decides when to speak. A decision per chat every tick, expressed as "allowed to speak in N minutes".
- Feels like time passes. Needs grow while nobody talks, drop when the other person answers, and decay after the persona itself speaks.
- Has bad timing on purpose. Bursts, follow-ups, quiet hours and a daily cap keep it from looking like a cron job.
- Remembers the day (optional). Once a week it asks a DSH session to turn the last day of chat into speaking habits, a few memories, and a short first-person narrative.
- Watches one video now and then (optional). Picks something from a public video API, remembers what it saw, and notes it in the persona file.
It needs no API key, no account and no database. State is a few JSON files in one directory.
How a decision is made
Each tick (default every 10 s), per chat:
- Growth —
miss += minutes × missRate, likewisesocialandcurious, clamped to 0..1. With aburstChanceprobability a sudden spike is added. - Satisfaction — if the buffer shows a new incoming message:
miss ×= 0.25,social ×= 0.35,curious −= 0.2. If it shows a new proactive outgoing message: count it against the daily cap,miss ×= 0.4,social ×= 0.5, and possibly open a chatty window. - Impulse —
0.5 × miss + 0.3 × social + 0.2 × curious. - Suppression —
+0.6if the persona spoke less than 3 min ago,+0.25under 20 min,+0.3if it spoke and got no answer for 90+ min,+0.5if the other person is still typing-distance recent,+1during quiet hours. - Decision — speak when
(follow-up || burst || impulse − suppression > threshold ± noise), while idle long enough, aftergapMin, and under the daily cap.
Speaking writes speakIntervalMinutes (default 2) as the allowed gap; staying quiet writes holdIntervalMinutes (default 1440). Both accept a [min, max] pair for jitter.
Install
The package is a DSH bundle: package.json declares dsh.bundle.patch, and cordis.patch.yml inserts one plugin row.
- Pack it —
npm packin this directory producesdsh-companion-heartbeat-1.2.0.tgz. - Install the tarball as a bundle in DSH (Plugin Manager, or the equivalent
install_bundleaction), then enable it.
It also runs as an ordinary ES module — import apply and hand it a context with on / effect, which is what the smoke test does.
Node 20+ (uses global fetch and AbortSignal.timeout).
Configuration
Every path, name and host-app detail is configuration; nothing about a particular machine is compiled in. Paths accept ~ and ${ENV_VAR}.
- insert:
- id: heartbeat
name: dsh-companion-heartbeat
config:
persona: 'companion'
dataDir: '~/.dsh/heartbeat'
chats: ['demo']
rolePath: '~/my-app/roles/companion.md'
bufferPath: '~/my-app/state/messages.json'
tickSeconds: 10
adapter:
type: json
path: '~/my-app/state/proactive.json'
quietStart: 0 # shorthand: top-level tuning keys are merged too
| Key | Default | Meaning |
|---|---|---|
persona | companion | Display name; used in the consolidation prompt. |
dataDir | ~/.dsh/heartbeat | Where state, log, tuning and memories live ($DSH_HOME respected). |
chats | [] | Chat keys to track. Empty means "ask the adapter" (the wechatagent adapter reads its whitelist). A selection saved in the panel is stored in config.json and wins from then on. |
panel.enabled | true | Serve the local "who should the persona keep in mind?" page. |
panel.port | 43110 | Loopback port for that page. The URL with its token is printed in heartbeat.log. |
rolePath | — | Persona markdown file. Gets the NOW / LEARNED / WATCHED blocks. Optional. |
bufferPath | — | JSON message buffer used to read activity. Optional: without it the persona is simply always idle. |
bufferFormat | auto | auto understands outgoing, isSend: 1 and message_id: "out-…". |
tickSeconds | 10 | Decision interval, minimum 1. |
tuning | see below | Numbers for the decision engine. |
adapter | { type: 'json' } | Where the decision goes — see below. |
life.enabled | true | Refresh the "what I am doing right now" block. |
life.slots / life.file | built-in | Replace the rotation of daily scenes (same shape: [{from,to,items:[[tag,text]]}]). |
life.minMinutes / maxMinutes | 100 / 180 | Random pause between scene changes. |
life.template | Now: {text}\nMood: {tag} | Text inside the NOW block. |
consolidate.enabled | true | Weekly memory pass. |
consolidate.intervalHours | 168 | Missed runs are caught up on the next tick. |
consolidate.sessionId | heartbeat-memory | DSH session used for the prompt. Created on demand. |
consolidate.cwd | process cwd | Working directory for that session. |
consolidate.promptFile | — | Replace the built-in prompt ({{persona}}, {{life}}, {{habits}}, {{said}}, {{heard}}). |
watch.enabled | false | Occasional video. |
watch.intervalMinutes | 150 | Minimum gap. |
watch.hours | [9, 1] | Allowed hours, wraps midnight. |
watch.interests | broad list | Keywords that rank candidate videos. |
watch.credentialPath | — | Optional local credential JSON (sessdata, bili_jct, buvid3, dedeuserid). Anonymous calls work without it. |
Live tuning
On first run the engine writes its numbers to <dataDir>/config.json and re-reads that file every tick. Edit it to change the mood without restarting DSH:
{ "missRate": 0.026, "threshold": 0.16, "dailyCap": 20, "quietStart": 1, "quietEnd": 7 }
Lower threshold or raise missRate for a clingier persona; the opposite for a distant one.
Choosing who to keep in mind
Inside DeepSeek Harness the list is its own page in Settings (Settings → Keep in mind, id companion-heartbeat), registered through the settings.section slot. It talks to the host half over loopback, so nothing else has to be opened.
Outside the GUI the plugin also serves one local page, bound to 127.0.0.1 and protected by a per-install token:
http://127.0.0.1:43110/?token=<contents of <dataDir>/panel-token.txt>
It lists every chat the adapter knows about — the host whitelist plus every chat that has messages in the buffer — with the chat's name and how long ago it was active. Tick the ones the heartbeat may reach out to, press 保存. The selection is written to <dataDir>/config.json as chats, and the loop follows it on the next tick; nothing restarts and the host config is not touched by hand.
Chat keys may also be typed in by hand (wechat:private:<id>, wechat:group:<id>), which is useful before the first message exists.
Touch files
<dataDir>/consolidate-now triggers a memory pass on the next tick; <dataDir>/watch-now triggers a video. Both are deleted after use.
Adapters
| Type | Behaviour |
|---|---|
json (default) | Writes { updatedAt, chats: { key: { allowed, intervalMinutes, decision } } } to adapter.path. Good for any app, and for trying the plugin without a host app. |
wechatagent | Updates only the wechat.proactive block of a chat host config (enabled, intervalMinutes, idleMinutes, jitterMinutes, startTime, endTime, mode, per-chat allow list). Every other key in that file is left untouched. Keys come from chats, or from wechat.whitelist.private/groups when chats is empty. |
module | adapter.module points at a JS file exporting apply(plans, decisions, options). |
dshim | Sends the message itself through @xmanrui/dsh-im: the plugin writes one short line and POSTs it to the host's /api/dsh-im/delivery/messages. |
Delivering through dsh-im
dsh-im is a delivery pipe, so with this adapter the heartbeat no longer only writes a policy — it composes the line and hands it over. Map a chat key to a dsh-im target id:
adapter:
type: dshim
baseUrl: http://127.0.0.1:3080 # the DSH host web server
botId: bot_9577c8572d454122a4ef7fb4d8420a91
targets:
wechat:private:165338666: release-alerts
format: plain # or markdown
minGapMinutes: 30 # adapter-side floor against spam
compose:
mode: session # session = let the model write it
sessionId: heartbeat-delivery
maxChars: 120
With compose.mode: template no model call happens; the text is a template with {life}, {tag}, {persona} and {chat}:
compose:
mode: template
template: "{life}"
In session mode the plugin asks sessionController for one short, in-character line, using persona (or the first lines of rolePath) and the current life scene as context. If that service is missing, it logs sessionController unavailable and falls back to the template. Either way a delivery only happens when the engine decides speak, and never twice for the same chat within minGapMinutes; the last send times live in <dataDir>/dshim-delivery.json.
Data files
<dataDir>/
state.json needs, per-chat counters, last decision, current scene
config.json live tuning values, and the chat selection saved by the panel
heartbeat.log one line per tick, rotated at 512 KiB
panel-token.txt token required by the local settings page
consolidate.json last memory pass
watch.json seen videos
proactive.json json adapter output
dshim-delivery.json dshim adapter: last send time per chat
memory/
memories.json
self-narrative.md
The persona file, when configured, gets three replaceable blocks: <!-- HEARTBEAT:NOW -->, <!-- HEARTBEAT:LEARNED -->, <!-- HEARTBEAT:WATCHED -->. Each is rewritten in place, so hand-written personality text around them survives.
Notes on the design
- Why needs instead of a timer. A fixed interval produces a heartbeat nobody believes. Growing needs with suppression mean the same code can be clingy in one chat and quiet in another without retuning.
- Why thresholds are noisy.
thresholdNoisemakes the same internal state produce different outcomes, which is what "almost said something" looks like from outside. - Why the engine is pure.
lib/engine.jshas no I/O: it mutates the state it is handed. The tick is therefore testable without waiting for wall-clock time. - Why adapters. The interesting part is the decision, not the integration. Keeping the integration small is what makes the plugin portable.
Limitations
- It does not send messages. It only writes a decision; your host app has to honour it.
- Memory quality depends on the model. Consolidation asks for strict JSON and is tolerant but not infallible; a malformed reply is logged and skipped.
- Consolidation needs
sessionController. The plugin declares no hard service dependencies (inject = []), so it loads in any profile; only the weekly memory pass needs that service. Without it the pass logssessionController unavailableand skips itself, everything else keeps running. - The weekly pass is not per-chat. It merges everything in the buffer across chats.
- Video watching targets bilibili's public web APIs. Rates, regions and availability can change without notice.
- The UI is one local page, not part of the DSH window. It is served on loopback so it works with any host app and needs no client build; bookmark it. Where a host app has its own console, that console stays the place to watch conversations.
Disclaimer
Automating a chat platform, and reading a local signed-in cookie file, may conflict with that platform's terms of service. This plugin ships no credentials and no account data, and the video feature works anonymously by default. Use it on accounts you own and at your own risk. The bundled daily scenes are generic placeholders, not a persona.
Development
node test/smoke.mjs
The suite covers the engine, config resolution, activity parsing, both adapters, the life block, one end-to-end tick, and a scan that no machine-specific path or name leaked into the sources.
License
MIT. See LICENSE.
中文简介
给陪伴型人格装一颗"心跳":三条需求(想念 / 想有人陪 / 好奇)随时间缓慢上涨,对方回话就被满足,偶尔毫无理由地跳一下。每隔几秒算一次"此刻想不想开口、多久后可以再开口",结论交给适配器——可以是一个普通 JSON 文件,也可以是聊天宿主应用里的主动发言开关。
所有路径、人格名、宿主应用细节都来自配置,代码里没有绑定任何一台机器。数据只有 <dataDir> 下的几个 JSON 文件。可选功能:每周把一天的聊天沉淀成说话习惯与记忆;偶尔刷一条视频记下来。默认不发任何消息,只做决定。
Comments
Loading…
Similar plugins
by LittleBlackTong
Interval heartbeat that wakes each root agent itself (followup injection) to proactively report progress, risks or blockers: busy-safe queuing, no stacking, auto-pauses when no human replies, re-arms
★ 4
↓ 584/wk
MIT
JavaScript
Nov 11, 2026
dsh plugin --profile web add dsh-plugin-heartbeatby lemoncat7
Long-lived AI companions with isolated memory, WeChat channels, Skills, schedules, heartbeat concerns, and a dependency-aware task board.
★ 3
↓ 1.5k/wk
MIT
TypeScript
Nov 2, 2026
dsh plugin --profile web add @lemoncat7/dsh-partnerby Kanadego
Heartbeat loop for DeepSeek Harness: every 20 minutes (by default) the agent wakes on its own to keep a local profile of your interests and preferences, search the web for things you care about, and k
★ 33
↓ 3.2k/wk
MIT
TypeScript
Nov 18, 2026
dsh plugin --profile web add @kanadego/dsh-heartbeatby Alan2Z
一种能让你的harness开口说话的方案/Make your AI harness speak — a verified voice-announcement solution
★ 20
↓ 366/wk
MIT
JavaScript
Oct 27, 2026
dsh plugin --profile web add dsh-speakby xain
Web Audio agent-heartbeat cues for the DSH web GUI: a low working hum while an agent is busy, ticks on streaming output, and a chime when a session awaits input or work finishes, with per-voice volume
★ 0
↓ 252/wk
MIT
TypeScript
Sep 27, 2026
dsh plugin --profile web add @xain_npm/dsh-client-ui-beepby Yuuyuko-uu
给 AI 伙伴一个会自己判断、你看得见的心情 —— 每轮聊完自动判断涨跌,右下角挂饰看数值、情绪和时间线
★ 273
↓ 6k/wk
MIT
JavaScript
Nov 17, 2026
dsh plugin --profile web add dsh-feiyu-mood