oc-discord-rpc 0.0.0-stage → 0.4.0
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/CHANGELOG.md +40 -0
- package/LICENSE +21 -0
- package/README.md +114 -2
- package/package.json +46 -4
- package/src/epoch.mjs +97 -0
- package/src/index.js +643 -0
- package/src/ipc.mjs +517 -0
- package/src/presence.mjs +252 -0
- package/src/state.mjs +329 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [0.4.0] - 2026-11-29
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- The plugin now ships a bundled Discord application id (`1576225438995316886`) and works on install with no Developer Portal setup. Resolution order is `appId` option, then `OC_DISCORD_APP_ID`, then the bundled default; an explicit `appId: ""`, `null` or `false` stays inert. The bundled app is named `OpenCode`, is community-run and unverified (not an official anomalyco application), and its public id is permanent by policy.
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- The card now renders `details: Coding with <model display name>` and `state: Reasoning <Level>` instead of a single combined line. `details` no longer repeats the header name; `state` is omitted entirely at `default` (any case) or with no variant.
|
|
19
|
+
- The model's human name comes from `ctx.model.list()` (matching `modelID` before `id` inside the session's `providerID`), with a deterministic prettifier fallback instead of the raw id. A catalogue name that arrives late replaces the fallback on the next send.
|
|
20
|
+
- Levels use display names (`Low`, `Medium`, `High`, `XHigh`, `Max`, `Minimal`) with first-letter capitalisation for anything else; no middle dot or parentheses remain on the text lines.
|
|
21
|
+
- `assets.large_text` carries `<providerID> · <version>` from `ctx.app.version`, omitted when neither part is known. `type` is explicitly `0` (`Playing`).
|
|
22
|
+
- The clock still runs from when OpenCode opened with no end timestamp, mode or command, but its epoch is now stable: `timestamps.start` survives `/reload` and, within a 12-hour freshness window, a host restart.
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- The presence clock no longer restarts from zero on `/reload`. `openedAt` resolves once at setup from a fresh persisted record (`~/.local/state/opencode/discord-rpc.json`, 12-hour maximum age) or from the host process start time, and refreshes `hostPid`/`updatedAt` on reuse. Missing, corrupt and unwritable state files are ignored without throwing.
|
|
27
|
+
- The model catalogue is now one bounded snapshot per provider (one-hour TTL, 60-second miss cooldown) instead of a permanent per-model cache: a failed or empty fetch no longer poisons the name, and a model added mid-day appears without a restart.
|
|
28
|
+
- A boot sweep that seeds no model now retries on a bounded schedule (2 s, 5 s, 15 s, 60 s, then every five minutes, capped) and falls back to an unfiltered query when the directory-scoped query finds no model. A live model event cancels the retries; cleanup leaves no timer armed.
|
|
29
|
+
- The last shown model, provider and effort are sticky, and a current session revealed as a child recovers the previous non-child session instead of blanking the card. A model change without a variant clears the old effort.
|
|
30
|
+
- A card that would remove `details`, `state` or buttons is held for a five-second grace instead of being published immediately; it is published if the field stays gone. Upgrades and clears bypass the hold, and cleanup leaves no grace timer armed.
|
|
31
|
+
|
|
32
|
+
[Unreleased]: https://github.com/nathwn12/oc-collections/compare/oc-discord-rpc-v0.1.0...HEAD
|
|
33
|
+
|
|
34
|
+
## [0.1.0] - 2026-11-28
|
|
35
|
+
|
|
36
|
+
### Added
|
|
37
|
+
|
|
38
|
+
- The first release: a Discord IPC transport over the local discord-ipc-0 through discord-ipc-9 sockets, a presence model with the app name as details, the explicitly selected model with effort as state, and a clock from when OpenCode opened that keeps counting, plus the plugin wiring that registers it with OpenCode.
|
|
39
|
+
|
|
40
|
+
[0.1.0]: https://github.com/nathwn12/oc-collections/releases/tag/oc-discord-rpc-v0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nathan <137482711+nathwn12@users.noreply.github.com>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,115 @@
|
|
|
1
|
-
|
|
1
|
+
<h1 align="center">oc-discord-rpc</h1>
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<p align="center"><strong>An OpenCode plugin that publishes a Discord Rich Presence card with the app name, the selected model's human name and a clock that runs from when OpenCode opened.</strong></p>
|
|
4
|
+
|
|
5
|
+
<p align="center">
|
|
6
|
+
<a href="https://www.npmjs.com/package/oc-discord-rpc"><img src="https://img.shields.io/npm/v/oc-discord-rpc" alt="npm version"></a>
|
|
7
|
+
<img src="https://img.shields.io/badge/platform-windows--linux-2b3137" alt="platform">
|
|
8
|
+
<a href="https://github.com/nathwn12/oc-collections/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="MIT"></a>
|
|
9
|
+
</p>
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
Add the plugin to `~/.config/opencode/opencode.jsonc` and restart OpenCode:
|
|
14
|
+
|
|
15
|
+
```json
|
|
16
|
+
{ "plugins": ["oc-discord-rpc"] }
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
That is all: the plugin ships with a bundled application id and publishes a card out of the box. No Discord Developer Portal account or setup step is needed.
|
|
20
|
+
|
|
21
|
+
To use your own application for different branding, create an application in the Discord Developer Portal, **enable Rich Presence** for it, and pass its id as `appId` (or set `OC_DISCORD_APP_ID`). A custom application without Rich Presence enabled cannot publish a card; the bundled one already has it enabled.
|
|
22
|
+
|
|
23
|
+
```jsonc
|
|
24
|
+
{
|
|
25
|
+
"plugins": [
|
|
26
|
+
{
|
|
27
|
+
"package": "oc-discord-rpc",
|
|
28
|
+
"options": { "appId": "<your Discord application id>" }
|
|
29
|
+
}
|
|
30
|
+
]
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
To stay inert, set `"enabled": false`, or pass `appId: ""`, `appId: null` or `appId: false`. An explicit empty or false option is an opt-out: it does not fall back to the bundled id, and the plugin logs one line and sends nothing.
|
|
35
|
+
|
|
36
|
+
## About the bundled app
|
|
37
|
+
|
|
38
|
+
The bundled application is named `OpenCode`. It is community-run and unverified, and is **not** an official anomalyco application. Its id (`1576225438995316886`) is public by design: it appears in OAuth URLs and is not a secret.
|
|
39
|
+
|
|
40
|
+
The id is stable by policy — it will not be removed or renamed — so you can rely on the default without configuring anything, and a presence outage will not come from the id disappearing.
|
|
41
|
+
|
|
42
|
+
## What it shows
|
|
43
|
+
|
|
44
|
+
The header and the mark are drawn by Discord; three fields come from the payload:
|
|
45
|
+
|
|
46
|
+
```text
|
|
47
|
+
Playing OpenCode activity.name, from appName
|
|
48
|
+
[mark] OpenCode drawn by Discord, not a second text line
|
|
49
|
+
Coding with DeepSeek V4.1 Flash 1017 details: model display name
|
|
50
|
+
Reasoning High state: reasoning level
|
|
51
|
+
0:31 timestamps.start, from when OpenCode opened
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`type` is `0` (`Playing`). `details` is `Coding with <model display name>` — no effort on that line, and no duplicate of the header. The model name is resolved from `ctx.model.list()` by matching `modelID` before `id` inside the session's `providerID`; when the catalogue has no match or is unavailable, a deterministic prettifier turns an id such as `deepseek-v4.1-flash` into `DeepSeek V4.1 Flash`. The model is whatever the session you are in is using: read from the session list when the plugin loads into a session that already exists, seeded on `session.created`, and overridden the moment you pick a different model. Both `details` and `state` are omitted when nothing is known. A catalogue name that arrives after the first card was built replaces the fallback on the next send.
|
|
55
|
+
|
|
56
|
+
`state` is `Reasoning <Level>` on its own line. Levels are `low` → `Low`, `medium` → `Medium`, `high` → `High`, `xhigh` → `XHigh`, `max` → `Max` and `minimal` → `Minimal`; any other value keeps its text with the first letter capitalised. When the variant is `default` (any case), missing or empty, the `state` field is omitted entirely — never `Reasoning Default`. There is no middle dot and no parentheses on either text line.
|
|
57
|
+
|
|
58
|
+
`assets.large_text` is `<providerID> \u00b7 <version>`, for example `opencode-go · 2.4.2`, where the version comes from `ctx.app.version`. It is omitted when neither part is known.
|
|
59
|
+
|
|
60
|
+
The last shown model and reasoning level are sticky: a session event with no model cannot strip either line, a new model-less session cannot evict a current session that has one, and a current session revealed as a child falls back to the previous non-child. A genuine model change with no variant clears the old effort. A card that would remove a visible field (`details`, `state` or buttons) is held for five seconds instead of being published at once; if the field does not return, that settled card is published after the grace. Upgrades and clears are never held.
|
|
61
|
+
|
|
62
|
+
The clock is `timestamps.start`, set when OpenCode opens, and it counts up perpetually, idle or not. There is no end timestamp and no mode or option that moves the anchor: the timer is the length of time OpenCode has been open. Discord advances the timer on its own from `timestamps.start`, so keeping it running costs no updates — the same epoch second sent again continues the same clock instead of restarting it.
|
|
63
|
+
|
|
64
|
+
That epoch is stable. It is resolved once at setup from a persisted record when that record is fresh (within 12 hours), otherwise from the host process start time (`now - process.uptime()`), never from a bare load-time `Date.now()`. The record lives at `~/.local/state/opencode/discord-rpc.json` and holds `{ openedAt, hostPid, updatedAt }`; writing it is best-effort, so an unwritable or corrupt file never blocks the plugin. A `/reload` reuses the same epoch and the clock keeps running. A host restart reuses it too while the record is fresh, as long as the 12-hour window has not passed; after a longer gap (a sleep or a machine off for days) the clock re-anchors to the new host start.
|
|
65
|
+
|
|
66
|
+
## Privacy
|
|
67
|
+
|
|
68
|
+
The card never carries the current tool name or a tool's input. A tool name alone says almost nothing, and a tool's input carries file paths. It never carries message text, prompts, or file contents either.
|
|
69
|
+
|
|
70
|
+
## Image
|
|
71
|
+
|
|
72
|
+
The chosen image is `https://raw.githubusercontent.com/anomalyco/opencode/2204311ec6e966db8d67988ab3638ad95a811a46/packages/ui/src/assets/favicon/apple-touch-icon-v3.png` — the official mark, pinned to an immutable commit so it cannot move. It is a third-party URL that Discord fetches through its media proxy; this package ships no image file. Set `largeImage` to that URL to use it, or to another full `https://` URL or an uploaded asset key to use a different image. Leave `largeImage` empty and no image is sent at all; Discord then shows your app's own icon.
|
|
73
|
+
|
|
74
|
+
The alternative is `https://raw.githubusercontent.com/lobehub/lobe-icons/refs/heads/master/packages/static-avatar/avatars/opencode.webp`: the same mark from the lobehub icon set, 1280×1280, on a moving branch.
|
|
75
|
+
|
|
76
|
+
## Limits
|
|
77
|
+
|
|
78
|
+
- The Discord desktop client must be running on the same machine. The plugin speaks Discord's local IPC socket (`discord-ipc-0` through `discord-ipc-9`) and does nothing when no client is up.
|
|
79
|
+
- Updates are coalesced at a minimum interval (`minIntervalMs`, default 15 seconds) because Discord rate-limits activity updates. The card is a status line, not a live log.
|
|
80
|
+
- The bundled id works out of the box. A custom `appId` must already exist with Rich Presence enabled; the plugin does not create Discord applications for you. Explicit `appId: ""`, `null` or `false`, and `enabled: false`, keep the plugin inert.
|
|
81
|
+
- The header line reads `activity.name` and is not taken from `details`. Discord's docs only say that the App Name is configured in the app's settings ("You can't set App Name when setting presence—it's always the name configured in your app's settings"), but the live card contradicts that: over the local IPC path `activity.name` is honoured, so a registered portal app named `OpenCode` is **not** required for the header. This was observed with the app id still naming a different program. The icon still comes from the application registered against your `appId`.
|
|
82
|
+
|
|
83
|
+
## Known limitations
|
|
84
|
+
|
|
85
|
+
- Real-host restart behaviour is proven in unit tests but not yet on a live Discord host: the tests inject pid, uptime and the state file, so an actual OpenCode restart with Discord watching the card has not been observed.
|
|
86
|
+
|
|
87
|
+
## Options
|
|
88
|
+
|
|
89
|
+
- `appId` — a custom Discord application id for different branding; also settable with `OC_DISCORD_APP_ID`. Defaults to the bundled `1576225438995316886` when neither is set; pass `""`, `null` or `false` to stay inert.
|
|
90
|
+
- `enabled` — default `true`; `false` disables the plugin without uninstalling it.
|
|
91
|
+
- `minIntervalMs` — minimum gap between presence updates, default `15000`; positive values under `1000` clamp up to `1000`.
|
|
92
|
+
- `largeImage` — a full `https://` URL or an uploaded asset key for `large_image`; empty sends no image.
|
|
93
|
+
- `buttons` — up to two `{label, url}` buttons; none by default.
|
|
94
|
+
- `appName` — the `activity.name` header; default `OpenCode`. `details` carries the model instead.
|
|
95
|
+
|
|
96
|
+
## Tracing
|
|
97
|
+
|
|
98
|
+
Set the environment variable `OC_DISCORD_RPC_TRACE=1` to print a trace of every decision the plugin makes. It is not a config key.
|
|
99
|
+
|
|
100
|
+
## Requirements
|
|
101
|
+
|
|
102
|
+
- OpenCode V2.
|
|
103
|
+
- Node 20 or newer, or Bun.
|
|
104
|
+
- The Discord desktop client, running locally on the same machine.
|
|
105
|
+
|
|
106
|
+
## Status
|
|
107
|
+
|
|
108
|
+
**Unverified** — as-is, use at your own risk.
|
|
109
|
+
|
|
110
|
+
## Links
|
|
111
|
+
|
|
112
|
+
- [Issues](https://github.com/nathwn12/oc-collections/issues)
|
|
113
|
+
- [Releases](https://github.com/nathwn12/oc-collections/releases)
|
|
114
|
+
- [Package source](https://github.com/nathwn12/oc-collections/tree/main/packages/oc-discord-rpc)
|
|
115
|
+
- [MIT licence](https://github.com/nathwn12/oc-collections/blob/main/LICENSE)
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oc-discord-rpc",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "An OpenCode plugin that publishes a Discord Rich Presence card for the running turn.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"opencode",
|
|
7
|
+
"opencode-plugin",
|
|
8
|
+
"plugin",
|
|
9
|
+
"discord",
|
|
10
|
+
"discord-rpc",
|
|
11
|
+
"rich-presence",
|
|
12
|
+
"presence"
|
|
13
|
+
],
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"author": "nathwn12",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/nathwn12/oc-collections.git",
|
|
19
|
+
"directory": "packages/oc-discord-rpc"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://github.com/nathwn12/oc-collections/tree/main/packages/oc-discord-rpc",
|
|
22
|
+
"bugs": "https://github.com/nathwn12/oc-collections/issues",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"main": "./src/index.js",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"import": "./src/index.js",
|
|
28
|
+
"default": "./src/index.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"src",
|
|
33
|
+
"README.md",
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"CHANGELOG.md"
|
|
36
|
+
],
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=20"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"check": "node --check src/index.js && node --check src/epoch.mjs && node --check src/ipc.mjs && node --check src/presence.mjs && node --check src/state.mjs && node --test \"test/**/*.test.js\"",
|
|
42
|
+
"test": "node --test \"test/**/*.test.js\"",
|
|
43
|
+
"prepublishOnly": "node ../../scripts/check-version-cell.mjs . && bun run check"
|
|
44
|
+
},
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/epoch.mjs
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// The stable epoch behind timestamps.start.
|
|
2
|
+
//
|
|
3
|
+
// OpenCode re-evaluates a plugin on /reload, so a per-load Date.now() restarts
|
|
4
|
+
// the Discord timer from zero. Discord draws elapsed time from the epoch second
|
|
5
|
+
// we send, so re-sending the same epoch keeps the card's clock running. The
|
|
6
|
+
// epoch is resolved once at setup, from a persisted record when it is fresh and
|
|
7
|
+
// from the host process start time otherwise; resolution never uses a bare
|
|
8
|
+
// per-load now. Every dependency is injectable, so the whole decision is
|
|
9
|
+
// provable offline without touching the real state file.
|
|
10
|
+
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import os from 'node:os';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
|
|
15
|
+
// A fresh record is trusted for half a day. Older means the machine slept or
|
|
16
|
+
// the app was closed long ago, so the clock is re-derived from uptime.
|
|
17
|
+
export const OPENED_AT_MAX_AGE_MS = 12 * 60 * 60 * 1000;
|
|
18
|
+
|
|
19
|
+
// The host state home used elsewhere in this repo is ~/.local/state/opencode
|
|
20
|
+
// (oc-talk publishes service.json there). Reuse it; do not invent a new root.
|
|
21
|
+
export function defaultStateFile() {
|
|
22
|
+
return path.join(os.homedir(), '.local', 'state', 'opencode', 'discord-rpc.json');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function finite(value) {
|
|
26
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function readRecord(file) {
|
|
30
|
+
try {
|
|
31
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
32
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
|
33
|
+
} catch {
|
|
34
|
+
// Missing, corrupt or unreadable: all the same answer to the resolver.
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function writeRecord(file, record) {
|
|
40
|
+
try {
|
|
41
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
42
|
+
const temporary = file + '.' + process.pid + '.tmp';
|
|
43
|
+
fs.writeFileSync(temporary, JSON.stringify(record), 'utf8');
|
|
44
|
+
// Atomic replace: a crash mid-write must leave the previous record intact.
|
|
45
|
+
fs.renameSync(temporary, file);
|
|
46
|
+
} catch {
|
|
47
|
+
// Persistence is best effort. An unwritable state home never blocks setup.
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Resolve the epoch that anchors timestamps.start.
|
|
53
|
+
* @param {{now?: () => number, uptime?: () => number, pid?: number,
|
|
54
|
+
* stateFile?: string, read?: (file: string) => any,
|
|
55
|
+
* write?: (file: string, record: object) => void,
|
|
56
|
+
* trace?: (message: string) => void}} [options]
|
|
57
|
+
* @returns {number} epoch ms; may be non-finite when every clock source is
|
|
58
|
+
* broken, in which case presence.mjs omits the timestamps key.
|
|
59
|
+
*/
|
|
60
|
+
export function resolveOpenedAt(options = {}) {
|
|
61
|
+
const cfg = options && typeof options === 'object' ? options : {};
|
|
62
|
+
const now = typeof cfg.now === 'function' ? cfg.now : Date.now;
|
|
63
|
+
const uptime = typeof cfg.uptime === 'function' ? cfg.uptime : () => process.uptime();
|
|
64
|
+
const hostPid = finite(cfg.pid) ? cfg.pid : process.pid;
|
|
65
|
+
const stateFile = typeof cfg.stateFile === 'string' && cfg.stateFile
|
|
66
|
+
? cfg.stateFile : defaultStateFile();
|
|
67
|
+
const read = typeof cfg.read === 'function' ? cfg.read : readRecord;
|
|
68
|
+
const write = typeof cfg.write === 'function' ? cfg.write : writeRecord;
|
|
69
|
+
const trace = typeof cfg.trace === 'function' ? cfg.trace : () => {};
|
|
70
|
+
|
|
71
|
+
const at = now();
|
|
72
|
+
let record = null;
|
|
73
|
+
try { record = read(stateFile); } catch { record = null; }
|
|
74
|
+
|
|
75
|
+
const stored = record && record.openedAt;
|
|
76
|
+
const age = finite(stored) && finite(at) ? at - stored : NaN;
|
|
77
|
+
let openedAt;
|
|
78
|
+
let source;
|
|
79
|
+
if (age <= OPENED_AT_MAX_AGE_MS) {
|
|
80
|
+
// NaN fails this comparison, so a broken clock re-derives instead.
|
|
81
|
+
openedAt = stored;
|
|
82
|
+
source = 'persisted record';
|
|
83
|
+
} else {
|
|
84
|
+
openedAt = at - Math.round(uptime() * 1000);
|
|
85
|
+
source = 'host uptime';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (finite(openedAt)) {
|
|
89
|
+
try {
|
|
90
|
+
// On reuse this refreshes hostPid/updatedAt while keeping the epoch; on
|
|
91
|
+
// re-derive it writes the new epoch. Either way it happens once, here.
|
|
92
|
+
write(stateFile, { openedAt, hostPid, updatedAt: at });
|
|
93
|
+
} catch { /* best effort: never throw into the host */ }
|
|
94
|
+
}
|
|
95
|
+
trace('presence clock from ' + source);
|
|
96
|
+
return openedAt;
|
|
97
|
+
}
|