dsh-caffeinate 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,47 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0] - 2026-11-11
4
+
5
+ First public release.
6
+
7
+ > Version note: earlier iterations used internal sequence numbers (the sections below). The public series restarts here at 0.1.0; internal numbers are not carried over.
8
+
9
+
10
+ 本项目遵循 [Keep a Changelog](https://keepachangelog.com/) 与 [语义化版本](https://semver.org/)。
11
+
12
+ ## [Unreleased]
13
+
14
+ ## [1.0.0] - 2026-11-10
15
+
16
+ 首个公开版本。
17
+
18
+ ### Added
19
+
20
+ - Host 侧守护:插件加载后 `spawn` 一个 `/usr/bin/caffeinate` 子进程,参数按设置拼装,
21
+ 末尾固定追加 `-w <Host PID>`;默认组合为 `-i -s -m -w <pid>`。
22
+ - 断言绑定宿主进程生命周期:宿主退出或崩溃后由 `caffeinate(8)` 的 `-w` 语义释放断言;
23
+ 插件卸载时额外 `clearInterval` + 对子进程 `SIGTERM`。
24
+ - 6 个 Schemastery 配置键:`enabled`、`mode`(`always` / `running-only`)、
25
+ `preventIdleSystemSleep`、`preventSystemSleepOnAC`、`preventDiskSleep`、`preventDisplaySleep`。
26
+ - 每 15 秒一次 `reconcile()`:`always` 模式补拉子进程,`running-only` 模式按是否存在
27
+ `status === 'running'` 的 agent 决定起停;定时器 `unref()`,不阻塞宿主退出。
28
+ - 斜杠指令 `/keepawake`(别名 `/caffeinate`):`on` / `display` / `nodisplay` / `running` / `off`
29
+ 即时切换,其余输入落到状态报告;报告包含子进程 PID、绑定的 Host PID、已运行秒数、
30
+ 当前启动参数,以及 `pmset -g assertions` 过滤后的片段。
31
+ - `examples/com.user.caffeinate.plist`:可选的系统级 LaunchAgent 示例,插件不安装也不依赖它。
32
+
33
+ ### Changed
34
+
35
+ - 公开包名统一为 `dsh-caffeinate`:`package.json` 的 `name`、`index.js` 的 `name` 导出、
36
+ `cordis.patch.yml` 的 `insert.name` 与 `id`、以及指令输出的插件标识全部逐字一致。
37
+ - 依赖 `@deepseek-ai/schemastery` 由 DSH 自带:原先 `package.json` 里根本没声明,现补为
38
+ `peerDependencies`(`>=3.0.0-0`)。仓库本来就不带 `node_modules`。
39
+ - 补齐开源元数据:`license`、`author`、`keywords`、`repository`、`homepage`、`bugs`、
40
+ `publishConfig`、`files`。
41
+ - 新增 `README.en.md`、`LICENSE`、`CHANGELOG.md`、`.gitignore`、`assets/icon-180.png`、
42
+ CI(语法 + 脱敏两道)与 `scripts/sanitize-check.mjs`。
43
+
44
+ ### Notes
45
+
46
+ - 仅 macOS:非 `darwin` 平台不启动子进程,`lastError` 记录「不支持的操作系统平台」。
47
+ - 配置在 `apply()` 时读取一次,代码不监听设置变更;修改设置后何时生效取决于宿主是否重载插件。
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 veritaswiki
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.en.md ADDED
@@ -0,0 +1,164 @@
1
+ # dsh-caffeinate — keep the Mac awake while DSH runs
2
+
3
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
4
+ [![Node 20](https://img.shields.io/badge/node-20-blue.svg)](./.github/workflows/ci.yml)
5
+ [![macOS only](https://img.shields.io/badge/platform-macOS-lightgrey.svg)](#known-limitations)
6
+
7
+ <!-- npm badge: add https://img.shields.io/npm/v/dsh-caffeinate once the package is published -->
8
+
9
+ > A host-side DSH plugin: it spawns the `caffeinate` that ships with macOS and binds the assertion to the DSH main process with `-w`. When the host goes away, the assertion goes away. The display still sleeps as usual.
10
+
11
+ ## What it does
12
+
13
+ 1. **Spawns one `caffeinate` child** — on plugin load it runs `spawn("/usr/bin/caffeinate", args)` with `stdio: "ignore"`, `detached: false`, then `unref()`, so it never holds the host open.
14
+ 2. **Arguments come from settings, with `-w <host pid>` always appended** — the default build is `/usr/bin/caffeinate -i -s -m -w <pid>`; no `-d` unless display sleep prevention is enabled.
15
+ 3. **The assertion is bound to the host process** — `-w` in `caffeinate(8)` means "wait for the process with the specified pid to exit; once it exits, the assertion is also released". A DSH exit or kill therefore does not leave an orphaned `caffeinate` holding the machine awake.
16
+ 4. **Re-checks every 15 seconds** — `setInterval(reconcile, 15000)`: in `always` mode a missing child is restarted; in `running-only` mode the child is started and stopped based on whether any agent is running.
17
+ 5. **Slash commands read and switch live** — `/keepawake` (alias `/caffeinate`) reports state, child PID, the host PID it is bound to, uptime in seconds, the exact spawn arguments, and a filtered excerpt of `pmset -g assertions`; it also switches modes.
18
+ 6. **Cleanup on unmount** — the `ctx.effect` disposer calls `clearInterval` and sends `SIGTERM` to the child.
19
+
20
+ ## How it works
21
+
22
+ ### Argument assembly (`buildCaffeinateArgs`)
23
+
24
+ | Config key | Default | Flag | Meaning (per `caffeinate(8)`) |
25
+ | --- | --- | --- | --- |
26
+ | `preventIdleSystemSleep` | `true` | `-i` | prevent system idle sleep |
27
+ | `preventSystemSleepOnAC` | `true` | `-s` | prevent system sleep; valid only on AC power |
28
+ | `preventDiskSleep` | `true` | `-m` | prevent disk idle sleep |
29
+ | `preventDisplaySleep` | `false` | `-d` | prevent display sleep |
30
+ | all four off | — | fallback `-i` | if the flag list is empty, `-i` is added |
31
+ | always appended | — | `-w <pid>` | watch the host process, `process.pid` |
32
+
33
+ With the defaults the real command line is:
34
+
35
+ ```text
36
+ /usr/bin/caffeinate -i -s -m -w <DSH main process PID>
37
+ ```
38
+
39
+ **Whose pid is watched**: `buildCaffeinateArgs(state, process.pid)` — the DSH host process that loaded the plugin, not `caffeinate` itself and not anything it forks.
40
+
41
+ ### Lifecycle
42
+
43
+ | Moment | Behavior |
44
+ | --- | --- |
45
+ | Plugin load | `apply()` calls `reconcile()` once |
46
+ | Every 15 s | `setInterval` calls `reconcile()` again; the timer is `unref()`ed |
47
+ | Plugin unload | `clearInterval` + `kill("SIGTERM")` on the child |
48
+ | Host process gone | `caffeinate -w` releases the assertion and exits on its own |
49
+ | Child exits or fails to start | `exit` / `error` handlers clear `state.child`; the next `reconcile()` restarts it, errors land in `state.lastError` |
50
+
51
+ ### The three `reconcile()` outcomes
52
+
53
+ - `enabled === false` → stop the child;
54
+ - `mode === "always"` → start a child if there is none;
55
+ - `mode === "running-only"` → start only if some agent has `status === "running"`, otherwise stop.
56
+
57
+ That check reads the host's `agents` service and scans its `values()` for `status`.
58
+
59
+ ## Install
60
+
61
+ This plugin is a DSH (Cordis) bundle. Two ways in.
62
+
63
+ ### Option A: let the agent use `plugin_manager`
64
+
65
+ Ask the agent inside DSH to install `dsh-caffeinate`; it calls `plugin_manager`:
66
+
67
+ - `action: "install_bundle"`, with `target` set to an install spec:
68
+ - local clone: `file:/abs/path/to/dsh-caffeinate`
69
+ - the GitHub repo: `github:veritaswiki/dsh-caffeinate`
70
+ - or the npm name `dsh-caffeinate` (only once published to the registry)
71
+ - then `action: "set_bundle"` to enable it.
72
+
73
+ > Release status: the name is fixed as `dsh-caffeinate`, but the package is **not published to npm yet**, so `npm` search will not find it. Until it is, use the `github:` or `file:` spec above.
74
+
75
+ ### Option B: mount it into a profile by hand
76
+
77
+ 1. Put the repo anywhere (referred to below as `/abs/path/to/dsh-caffeinate`).
78
+ 2. Edit the profile's `package.json` (`~/.dsh/profiles/<profile>/package.json`):
79
+ - add `"dsh-caffeinate": "link:/abs/path/to/dsh-caffeinate"` to `dependencies`
80
+ - add `"dsh-caffeinate"` to the `dsh.profile.bundles` array
81
+ 3. Install dependencies in the profile directory (DSH also does this on next start).
82
+
83
+ ### About the dependency
84
+
85
+ `index.js` needs `@deepseek-ai/schemastery` for host-side config validation. **DSH ships that package**, so a normal install needs nothing extra; `package.json` declares it under `peerDependencies` (`>=3.0.0-0`) only to state the relationship. This repo ships no `node_modules`.
86
+
87
+ ## Configuration
88
+
89
+ Settings live in the plugin's standard form (Schemastery `Config`):
90
+
91
+ | Key | Type | Default | Notes |
92
+ | --- | --- | --- | --- |
93
+ | `enabled` | boolean | `true` | master switch |
94
+ | `mode` | `"always"` \| `"running-only"` | `"always"` | `always` = stay awake the whole time DSH is open; `running-only` = only while an agent is executing |
95
+ | `preventIdleSystemSleep` | boolean | `true` | maps to `-i` |
96
+ | `preventSystemSleepOnAC` | boolean | `true` | maps to `-s` |
97
+ | `preventDiskSleep` | boolean | `true` | maps to `-m` |
98
+ | `preventDisplaySleep` | boolean | `false` | maps to `-d`; off by default so the display still sleeps and locks |
99
+
100
+ Invalid values (`normalizeConfig`): booleans are `true` unless explicitly `false`; `mode` is `"always"` unless explicitly `"running-only"`; `preventDisplaySleep` goes through `Boolean()`, so anything not truthy becomes `false`.
101
+
102
+ Config is read once at `apply()` time; there is no config-change listener in the code.
103
+
104
+ ## Slash commands
105
+
106
+ `/keepawake` and `/caffeinate` register the same logic. Subcommand behavior:
107
+
108
+ | Input | In-memory change | Restarts the child |
109
+ | --- | --- | --- |
110
+ | `/keepawake status` (or empty, or any unrecognized word) | none | no, report only |
111
+ | `/keepawake on` / `start` | `enabled=true`, `mode=always`, display policy reset to the configured `preventDisplaySleep` | yes (stop then start; PID and uptime reset) |
112
+ | `/keepawake display` / `screen` | `enabled=true`, `mode=always`, `preventDisplaySleep=true` | yes |
113
+ | `/keepawake nodisplay` / `headless` | `enabled=true`, `mode=always`, `preventDisplaySleep=false` | yes |
114
+ | `/keepawake running` / `auto` | `enabled=true`, `mode=running-only` | no, left to `reconcile()` |
115
+ | `/keepawake off` / `stop` | `enabled=false` | yes (stop) |
116
+
117
+ Note that `status` is not a branch of its own: there is no `status` check in the code, so it lands on the same report-only default path as an unknown word.
118
+
119
+ Every invocation returns the same report: state, current `mode`, the exact spawn arguments, display policy, the last error if any, and the `pmset -g assertions` lines matching `PreventUserIdleSystemSleep`, `PreventSystemSleep`, `PreventUserIdleDisplaySleep`, `caffeinate` or `powerd` (4-second timeout, first 600 characters as a fallback, and a plain "not supported" line on non-macOS).
120
+
121
+ ## Known limitations
122
+
123
+ - **macOS only.** On any platform other than `darwin` nothing is spawned and `state.lastError` records an unsupported-platform message; the `pmset` part of the report says so too.
124
+ - **Requires `/usr/bin/caffeinate`** (bundled with macOS). The plugin does not check for it or advise on install; a failed `spawn` only shows up in `lastError`.
125
+ - **`-w` watches the host main process pid.** Processes DSH forks are outside the binding: their absence cannot keep `caffeinate` alive and their presence cannot extend it — when the main process goes, this layer of assertion ends.
126
+ - **`running-only` depends on the host exposing an `agents` service** with `status === "running"`. When that service is unavailable the check is always false, so this mode never starts `caffeinate` (it fails toward not holding the machine awake).
127
+ - **15-second polling**: start/stop in `running-only` can lag by up to 15 seconds; it is not event driven.
128
+ - **Command changes are not persisted**: `/keepawake` only mutates in-memory state. A plugin reload returns to the configured values.
129
+ - **`/keepawake display` and `/keepawake nodisplay` force `mode` to `always`**: "display stays on" and "only while an agent runs" cannot currently be combined.
130
+ - **`/keepawake on` does not force the display to stay on** — it restores the display policy from config, so if `preventDisplaySleep` is `false` the display still sleeps.
131
+ - **`-s` is only effective on AC power**; that is `caffeinate`'s own semantics, and the plugin does not inspect power state.
132
+ - **Assertions are not merged**: if the machine also runs a system-level `caffeinate` (for example the resident LaunchAgent in `examples/com.user.caffeinate.plist`), both layers hold assertions at once and `/keepawake off` only turns off the plugin's layer.
133
+ - **No unit tests**: the gate is `node --check` plus the sanitization scan; `scripts/sanitize-check.mjs` checks text, not behavior.
134
+
135
+ ## Relation to other implementations
136
+
137
+ The same problem has another implementation: `bearice/dsh-keep-awake` (npm name `dsh-keep-awake`). It takes the cross-platform route and offers a visual, bilingual settings page; this package is macOS-only and puts its control surface in slash commands. This package is named `dsh-caffeinate` rather than `dsh-keep-awake` because the latter name is already taken on npm.
138
+
139
+ The tradeoff is stated plainly: calling the system's own `caffeinate` and delegating lifetime to `-w` buys near-zero platform code plus a scriptable, reversible command surface; it costs macOS-only support and no separate panel (settings live in the plugin's standard config form). Use that one if you need multiple platforms; use this one if you only need a Mac to keep working with the lid open.
140
+
141
+ ## Development and checks
142
+
143
+ ```bash
144
+ node --check index.js
145
+ node scripts/sanitize-check.mjs
146
+ ```
147
+
148
+ `scripts/sanitize-check.mjs` is the sanitization gate: absolute home paths, private package scopes, loopback addresses, internal address ranges, and key/token prefixes are all rejected, and any hit exits with code 1. CI (`.github/workflows/ci.yml`) runs exactly these two steps on Node 20 and does not publish to npm.
149
+
150
+ ## Files
151
+
152
+ | File | Purpose |
153
+ | --- | --- |
154
+ | `package.json` | bundle manifest: `dsh.bundle.patch` points at `cordis.patch.yml` |
155
+ | `cordis.patch.yml` | inserts one loader entry (`insert.name` must equal the package name) |
156
+ | `index.js` | all host-side logic: config, `caffeinate` start/stop, `reconcile`, both slash commands |
157
+ | `locale/zh.json`, `locale/en.json` | plugin manager title and description |
158
+ | `icon.svg` | icon source |
159
+ | `assets/icon-180.png` | 180x180 bitmap for consumers that need a raster icon |
160
+ | `examples/com.user.caffeinate.plist` | optional system-level LaunchAgent example; the plugin does not install, read or depend on it |
161
+
162
+ ## License
163
+
164
+ MIT © 2026 veritaswiki
package/README.md CHANGED
@@ -1,3 +1,164 @@
1
- # Temporary Holding Version
1
+ # dsh-caffeinate — DSH 运行期间不让 Mac 睡过去
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
4
+ [![Node 20](https://img.shields.io/badge/node-20-blue.svg)](./.github/workflows/ci.yml)
5
+ [![macOS only](https://img.shields.io/badge/platform-macOS-lightgrey.svg)](#已知限制)
6
+
7
+ <!-- npm 徽章:`dsh-caffeinate` 发布后再补 https://img.shields.io/npm/v/dsh-caffeinate -->
8
+
9
+ > 一个 Host 侧 DSH 插件:拉一个 macOS 自带的 `caffeinate` 子进程,用 `-w` 把防休眠断言绑到 DSH 主进程上。宿主没了,断言跟着没;屏幕该息屏还是息屏。
10
+
11
+ ## 它做什么
12
+
13
+ 1. **拉起一个 `caffeinate` 子进程** —— 插件加载时 `spawn("/usr/bin/caffeinate", args)`,`stdio: "ignore"`、`detached: false`,随后 `unref()`,不拖住宿主退出。
14
+ 2. **参数由设置决定,末尾固定 `-w <Host PID>`** —— 默认拼出来是 `/usr/bin/caffeinate -i -s -m -w <pid>`;不勾「阻止显示器休眠」就不带 `-d`。
15
+ 3. **断言绑在宿主进程上** —— `-w` 的语义来自 `caffeinate(8)`:「等待指定 pid 的进程退出,进程退出后断言一并释放」。所以 DSH 正常退出或被杀掉之后,不会留下一个继续压着系统的孤儿 `caffeinate`。
16
+ 4. **每 15 秒自检一次** —— `setInterval(reconcile, 15000)`:`always` 模式下子进程没了就重拉;`running-only` 模式下按「有没有正在执行的 agent」决定起停。
17
+ 5. **斜杠指令随时看随时切** —— `/keepawake`(别名 `/caffeinate`)能报当前状态、子进程 PID、绑定的宿主 PID、已运行秒数、实际启动参数,并附一段 `pmset -g assertions` 的过滤结果;也能直接切模式。
18
+ 6. **卸载清理** —— `ctx.effect` 的清理函数里 `clearInterval` 并对子进程发 `SIGTERM`。
19
+
20
+ ## 它怎么做
21
+
22
+ ### 参数拼装(`buildCaffeinateArgs`)
23
+
24
+ | 配置键 | 默认 | 拼进去的参数 | 含义(依 `caffeinate(8)`) |
25
+ | --- | --- | --- | --- |
26
+ | `preventIdleSystemSleep` | `true` | `-i` | 阻止系统空闲休眠 |
27
+ | `preventSystemSleepOnAC` | `true` | `-s` | 阻止整机睡眠;这条断言只在交流电下有效 |
28
+ | `preventDiskSleep` | `true` | `-m` | 阻止磁盘空闲休眠 |
29
+ | `preventDisplaySleep` | `false` | `-d` | 阻止显示器休眠 |
30
+ | 四个全关时 | — | 兜底 `-i` | 代码里 flags 为空会补一个 `-i` |
31
+ | 固定尾部 | — | `-w <pid>` | 监视宿主进程,`process.pid` |
32
+
33
+ 默认全开(`-d` 除外)时,实际命令行是:
34
+
35
+ ```text
36
+ /usr/bin/caffeinate -i -s -m -w <DSH 主进程 PID>
37
+ ```
38
+
39
+ **绑的是谁的 pid**:`buildCaffeinateArgs(state, process.pid)` —— 即运行插件的那个 DSH 宿主进程,不是 `caffeinate` 自己的 pid,也不是它 fork 出去的任何子进程。
40
+
41
+ ### 生命周期
42
+
43
+ | 时机 | 行为 |
44
+ | --- | --- |
45
+ | 插件加载 | `apply()` 里先跑一次 `reconcile()` |
46
+ | 每 15 秒 | `setInterval` 再跑一次 `reconcile()`,定时器 `unref()` |
47
+ | 插件卸载 | `clearInterval` + 对子进程 `kill("SIGTERM")` |
48
+ | 宿主进程消失 | 由 `caffeinate -w` 自行释放断言并退出 |
49
+ | 子进程自己退出 / 起不来 | `exit` / `error` 回调把 `state.child` 清空,下一次 `reconcile()` 重拉;错误记进 `state.lastError` |
50
+
51
+ ### `reconcile()` 的三种结果
52
+
53
+ - `enabled === false` → 停掉子进程;
54
+ - `mode === "always"` → 没有子进程就起一个;
55
+ - `mode === "running-only"` → 有 `status === "running"` 的 agent 才起,否则停。
56
+
57
+ 判断方式是从宿主取 `agents` 服务,遍历其 `values()` 看 `status`。
58
+
59
+ ## 安装
60
+
61
+ 本插件是 DSH(Cordis)bundle。两种装法。
62
+
63
+ ### 方式 A:让 Agent 用 `plugin_manager` 安装
64
+
65
+ 在 DSH 里对 Agent 说「装 `dsh-caffeinate`」,它会调 `plugin_manager`:
66
+
67
+ - `action: "install_bundle"`,`target` 填安装 spec:
68
+ - 已 clone 到本地:`file:/abs/path/to/dsh-caffeinate`
69
+ - GitHub 上的仓库:`github:veritaswiki/dsh-caffeinate`
70
+ - 或直接填 npm 包名 `dsh-caffeinate`(需已发布到 registry)
71
+ - 装完 `action: "set_bundle"` 启用。
72
+
73
+ > 首发状态:包名已定为 `dsh-caffeinate`,但**还没有发布到 npm registry**,所以现在在 npm 上搜不到。发布前请用上面的 `github:` 或 `file:` spec。
74
+
75
+ ### 方式 B:手动挂到 profile
76
+
77
+ 1. 把仓库放在任意目录(下面记作 `/abs/path/to/dsh-caffeinate`)。
78
+ 2. 编辑 profile 的 `package.json`(`~/.dsh/profiles/<profile>/package.json`):
79
+ - `dependencies` 里加 `"dsh-caffeinate": "link:/abs/path/to/dsh-caffeinate"`
80
+ - `dsh.profile.bundles` 数组里加 `"dsh-caffeinate"`
81
+ 3. 在 profile 目录安装依赖(DSH 下次启动时也会自行安装)。
82
+
83
+ ### 依赖说明
84
+
85
+ `index.js` 需要 `@deepseek-ai/schemastery`(Host 侧配置校验)。**DSH 自带这个包**,正常安装不需要另装;`package.json` 里它是 `peerDependencies`(`>=3.0.0-0`),只用来把依赖关系写明。本仓库不带 `node_modules`。
86
+
87
+ ## 配置
88
+
89
+ 配置项在插件的标准设置表单里(Schemastery `Config`):
90
+
91
+ | 键 | 类型 | 默认值 | 说明 |
92
+ | --- | --- | --- | --- |
93
+ | `enabled` | boolean | `true` | 是否启用守护 |
94
+ | `mode` | `"always"` \| `"running-only"` | `"always"` | `always` = DSH 打开期间一直防休眠;`running-only` = 只有 agent 在执行时才防休眠 |
95
+ | `preventIdleSystemSleep` | boolean | `true` | 对应 `-i` |
96
+ | `preventSystemSleepOnAC` | boolean | `true` | 对应 `-s` |
97
+ | `preventDiskSleep` | boolean | `true` | 对应 `-m` |
98
+ | `preventDisplaySleep` | boolean | `false` | 对应 `-d`;默认关闭,屏幕照常息屏锁屏 |
99
+
100
+ 非法值的行为(`normalizeConfig`):布尔项除显式 `false` 外都按 `true`;`mode` 除显式 `"running-only"` 外都按 `"always"`;`preventDisplaySleep` 走 `Boolean()`,非真值即 `false`。
101
+
102
+ 配置在 `apply()` 时读一次即定型,代码里没有监听配置变更的分支。
103
+
104
+ ## 斜杠指令
105
+
106
+ `/keepawake` 与 `/caffeinate` 注册的是同一套逻辑,子命令行为如下:
107
+
108
+ | 输入 | 内存状态变化 | 是否重启子进程 |
109
+ | --- | --- | --- |
110
+ | `/keepawake status`(或空、或任何未识别的词) | 无 | 否,只报告 |
111
+ | `/keepawake on` / `start` | `enabled=true`、`mode=always`、屏幕策略回到配置里的 `preventDisplaySleep` 值 | 是(先停再起,PID 与运行时长归零) |
112
+ | `/keepawake display` / `screen` | `enabled=true`、`mode=always`、`preventDisplaySleep=true` | 是 |
113
+ | `/keepawake nodisplay` / `headless` | `enabled=true`、`mode=always`、`preventDisplaySleep=false` | 是 |
114
+ | `/keepawake running` / `auto` | `enabled=true`、`mode=running-only` | 否,交给 `reconcile()` 决定 |
115
+ | `/keepawake off` / `stop` | `enabled=false` | 是(停) |
116
+
117
+ 注意 `status` 不是独立分支:代码里没有 `status` 判断,它和不认识的词一样落到「只报告」这条默认路径上。
118
+
119
+ 每次执行完都会返回同一份报告:守护状态、当前 `mode`、实际启动参数、屏幕策略、最近异常(若有),以及 `pmset -g assertions` 里匹配 `PreventUserIdleSystemSleep`、`PreventSystemSleep`、`PreventUserIdleDisplaySleep`、`caffeinate`、`powerd` 的行(`pmset` 超时 4 秒,取不到就截前 600 字符,非 macOS 直接说明不支持)。
120
+
121
+ ## 已知限制
122
+
123
+ - **仅 macOS**。非 `darwin` 平台不会 `spawn`,`state.lastError` 记下「不支持的操作系统平台」,指令报告里能看到;`pmset` 那一段也会说明平台不支持。
124
+ - **需要 `/usr/bin/caffeinate` 存在**(macOS 自带)。插件不检查路径、不做安装提示;`spawn` 失败只会进 `lastError`。
125
+ - **`-w` 绑的是宿主主进程 pid**。DSH fork 出去的进程不在绑定范围内:它们不在时不会让 `caffeinate` 续命,它们还在时也不会让 `caffeinate` 多活——主进程一走,这一层断言就结束。
126
+ - **`running-only` 依赖宿主暴露 `agents` 服务**,且 agent 的 `status` 为 `"running"`。取不到该服务时判断恒为「没有正在执行的 agent」,结果是这个模式下不会拉起 `caffeinate`(宁可不防,也不乱防)。
127
+ - **15 秒轮询**:`running-only` 的起停最多有 15 秒延迟,不是事件驱动的即时反应。
128
+ - **指令改动不落盘**:`/keepawake` 只改内存里的状态,不写配置。重载插件后回到配置文件里的值。
129
+ - **`/keepawake display`、`/keepawake nodisplay` 会把 `mode` 强制成 `always`**:想同时保持「屏幕常亮 + 仅任务执行时防休眠」当前做不到,得二选一。
130
+ - **`/keepawake on` 不会强制开屏幕常亮**,它把屏幕策略恢复成配置里的值——如果配置里 `preventDisplaySleep` 是 `false`,它就是关的。
131
+ - **`-s` 只在交流电下有效**,这是 `caffeinate` 自身语义,插件不额外判断电源状态。
132
+ - **不改断言的叠加关系**:若机器上另有系统级 `caffeinate`(例如 `examples/com.user.caffeinate.plist` 那种常驻 LaunchAgent),两层断言会同时存在,`/keepawake off` 只关插件这一层。
133
+ - **没有单元测试**:门禁是 `node --check` 加脱敏扫描,`scripts/sanitize-check.mjs` 不覆盖行为。
134
+
135
+ ## 与其它实现的关系
136
+
137
+ 同一个问题还有一份实现:`bearice/dsh-keep-awake`(npm 包名 `dsh-keep-awake`)。它走跨平台路线,并提供可视化的双语设置页;本包只做 macOS,交互面放在斜杠指令上。本包之所以叫 `dsh-caffeinate` 而不是 `dsh-keep-awake`,是因为后者在 npm 上已被占用。
138
+
139
+ 取舍写在明面上:直接用系统自带的 `caffeinate`、把生命周期交给 `-w`,换来的是几乎为零的平台层代码和一个可脚本化、可回滚的命令面;代价是只能在 macOS 上跑,屏幕上也没有独立面板(配置在插件标准设置表单里)。需要跨平台就用那一份,只需要 Mac 上安静地不合盖,用这份就够。
140
+
141
+ ## 开发与检查
142
+
143
+ ```bash
144
+ node --check index.js
145
+ node scripts/sanitize-check.mjs
146
+ ```
147
+
148
+ `scripts/sanitize-check.mjs` 是脱敏门禁:本机绝对路径、私有包前缀、回环地址、内网地址段、密钥与令牌前缀一律不许出现,命中即退出码 1。CI(`.github/workflows/ci.yml`)在 Node 20 上只跑这两步,不发布 npm。
149
+
150
+ ## 文件
151
+
152
+ | 文件 | 作用 |
153
+ | --- | --- |
154
+ | `package.json` | bundle 清单:`dsh.bundle.patch` 指回 `cordis.patch.yml` |
155
+ | `cordis.patch.yml` | 插入一行 Loader 条目(`insert.name` 必须等于包名) |
156
+ | `index.js` | Host 侧全部逻辑:配置、`caffeinate` 起停、`reconcile`、两个斜杠指令 |
157
+ | `locale/zh.json`、`locale/en.json` | 插件管理页的标题与描述 |
158
+ | `icon.svg` | 插件图标(源码) |
159
+ | `assets/icon-180.png` | 180×180 位图,供需要位图图标的场合使用 |
160
+ | `examples/com.user.caffeinate.plist` | 可选的系统级 LaunchAgent 示例;插件不安装、不读取、不依赖它 |
161
+
162
+ ## License
163
+
164
+ MIT © 2026 veritaswiki
Binary file
@@ -0,0 +1,18 @@
1
+ # dsh-caffeinate — 防休眠守护
2
+ #
3
+ # 由 DSH Loader 读取并把本插件插入为一行 Loader 条目。
4
+ # 注意:insert.name 必须与 package.json 的 name 完全一致,Loader 按包名解析模块。
5
+ #
6
+ # 运行时行为:在 DSH 运行期间调用 macOS 自带的 /usr/bin/caffeinate,
7
+ # 末尾固定加 -w <Host PID>,把断言绑到宿主进程生命周期上;
8
+ # 宿主退出或崩溃后 caffeinate 自行释放断言并退出(caffeinate(8) 的 -w 语义)。
9
+ - insert:
10
+ - id: dsh-caffeinate
11
+ name: 'dsh-caffeinate'
12
+ config:
13
+ enabled: true
14
+ mode: always
15
+ preventIdleSystemSleep: true
16
+ preventSystemSleepOnAC: true
17
+ preventDiskSleep: true
18
+ preventDisplaySleep: false
package/icon.svg ADDED
@@ -0,0 +1,28 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" fill="none">
2
+ <defs>
3
+ <linearGradient id="kaBg" x1="6" y1="6" x2="58" y2="58" gradientUnits="userSpaceOnUse">
4
+ <stop offset="0%" stop-color="#0F172A"/>
5
+ <stop offset="55%" stop-color="#1E293B"/>
6
+ <stop offset="100%" stop-color="#334155"/>
7
+ </linearGradient>
8
+ <linearGradient id="kaCup" x1="16" y1="26" x2="46" y2="50" gradientUnits="userSpaceOnUse">
9
+ <stop offset="0%" stop-color="#FBBF24"/>
10
+ <stop offset="100%" stop-color="#EA580C"/>
11
+ </linearGradient>
12
+ <linearGradient id="kaSteam" x1="22" y1="12" x2="38" y2="24" gradientUnits="userSpaceOnUse">
13
+ <stop offset="0%" stop-color="#38BDF8"/>
14
+ <stop offset="100%" stop-color="#FDE047"/>
15
+ </linearGradient>
16
+ </defs>
17
+ <rect x="4" y="4" width="56" height="56" rx="14" fill="url(#kaBg)" stroke="#F59E0B" stroke-width="2"/>
18
+ <!-- steam waves -->
19
+ <path d="M23 22C23 19 26 18 26 15C26 13 24 12 24 12" stroke="url(#kaSteam)" stroke-width="2.2" stroke-linecap="round"/>
20
+ <path d="M31 21C31 18 34 17 34 14C34 12 32 11 32 11" stroke="url(#kaSteam)" stroke-width="2.2" stroke-linecap="round"/>
21
+ <path d="M39 22C39 19 42 18 42 15C42 13 40 12 40 12" stroke="url(#kaSteam)" stroke-width="2.2" stroke-linecap="round"/>
22
+ <!-- coffee cup body -->
23
+ <path d="M17 27H43V38C43 44.6274 37.6274 50 31 50H29C22.3726 50 17 44.6274 17 38V27Z" fill="url(#kaCup)" stroke="#FEF08A" stroke-width="1.5" stroke-linejoin="round"/>
24
+ <!-- cup handle -->
25
+ <path d="M43 30H46.5C49.5376 30 52 32.4624 52 35.5C52 38.5376 49.5376 41 46.5 41H43" stroke="#FBBF24" stroke-width="2.5" stroke-linecap="round"/>
26
+ <!-- lightning bolt inside cup -->
27
+ <path d="M31.5 31L26.5 38H31L29.5 45L35.5 37H31L31.5 31Z" fill="#0F172A"/>
28
+ </svg>
package/index.js ADDED
@@ -0,0 +1,251 @@
1
+ import { spawn, execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import z from "@deepseek-ai/schemastery";
4
+
5
+ const execFileAsync = promisify(execFile);
6
+
7
+ export const name = "dsh-caffeinate";
8
+ export const inject = [];
9
+
10
+ export const Config = z.object({
11
+ enabled: z.boolean().default(true).description("是否启用 DSH 防休眠守护"),
12
+ mode: z
13
+ .union(["always", "running-only"])
14
+ .default("always")
15
+ .description("守护模式:always(DSH 打开期间始终防休眠)或 running-only(仅当有 Agent 会话正在执行时防休眠)"),
16
+ preventIdleSystemSleep: z
17
+ .boolean()
18
+ .default(true)
19
+ .description("阻止系统空闲休眠(caffeinate -i):允许屏幕正常息屏省电,但保持 CPU 与网络不断开"),
20
+ preventSystemSleepOnAC: z
21
+ .boolean()
22
+ .default(true)
23
+ .description("连接电源适配器时阻止整机睡眠(caffeinate -s)"),
24
+ preventDiskSleep: z
25
+ .boolean()
26
+ .default(true)
27
+ .description("阻止磁盘空闲休眠(caffeinate -m)"),
28
+ preventDisplaySleep: z
29
+ .boolean()
30
+ .default(false)
31
+ .description("阻止显示器息屏(caffeinate -d):默认关闭以便正常锁屏省电;需要屏幕常亮时可开启"),
32
+ });
33
+
34
+ function normalizeConfig(raw = {}) {
35
+ const cfg = typeof raw === "object" && raw !== null ? raw : {};
36
+ return {
37
+ enabled: cfg.enabled !== false,
38
+ mode: cfg.mode === "running-only" ? "running-only" : "always",
39
+ preventIdleSystemSleep: cfg.preventIdleSystemSleep !== false,
40
+ preventSystemSleepOnAC: cfg.preventSystemSleepOnAC !== false,
41
+ preventDiskSleep: cfg.preventDiskSleep !== false,
42
+ preventDisplaySleep: Boolean(cfg.preventDisplaySleep),
43
+ };
44
+ }
45
+
46
+ function buildCaffeinateArgs(state, hostPid) {
47
+ const flags = [];
48
+ if (state.preventIdleSystemSleep) flags.push("-i");
49
+ if (state.preventSystemSleepOnAC) flags.push("-s");
50
+ if (state.preventDiskSleep) flags.push("-m");
51
+ if (state.preventDisplaySleep) flags.push("-d");
52
+ if (flags.length === 0) flags.push("-i");
53
+ flags.push("-w", String(hostPid));
54
+ return flags;
55
+ }
56
+
57
+ async function queryPmsetAssertions() {
58
+ if (process.platform !== "darwin") {
59
+ return "当前平台非 macOS,不支持 pmset 查询。";
60
+ }
61
+ try {
62
+ const { stdout } = await execFileAsync("/usr/bin/pmset", ["-g", "assertions"], {
63
+ timeout: 4000,
64
+ });
65
+ const lines = stdout
66
+ .split("\n")
67
+ .filter((line) =>
68
+ /PreventUserIdleSystemSleep|PreventSystemSleep|PreventUserIdleDisplaySleep|caffeinate|powerd/i.test(
69
+ line,
70
+ ),
71
+ )
72
+ .map((line) => line.trim());
73
+ return lines.length > 0 ? lines.join("\n") : stdout.slice(0, 600);
74
+ } catch (err) {
75
+ return `无法读取 pmset assertions:${err instanceof Error ? err.message : String(err)}`;
76
+ }
77
+ }
78
+
79
+ export function apply(ctx, rawConfig) {
80
+ const config = normalizeConfig(rawConfig);
81
+ const state = {
82
+ ...config,
83
+ child: null,
84
+ startedAt: null,
85
+ lastArgs: [],
86
+ lastError: null,
87
+ };
88
+
89
+ function stopCaffeinate() {
90
+ const proc = state.child;
91
+ state.child = null;
92
+ state.startedAt = null;
93
+ if (proc && !proc.killed) {
94
+ try {
95
+ proc.kill("SIGTERM");
96
+ } catch {}
97
+ }
98
+ }
99
+
100
+ function startCaffeinate() {
101
+ if (process.platform !== "darwin") {
102
+ state.lastError = `不支持的操作系统平台: ${process.platform}`;
103
+ return false;
104
+ }
105
+ stopCaffeinate();
106
+ const args = buildCaffeinateArgs(state, process.pid);
107
+ try {
108
+ const proc = spawn("/usr/bin/caffeinate", args, {
109
+ stdio: "ignore",
110
+ detached: false,
111
+ });
112
+ proc.on("error", (err) => {
113
+ state.lastError = err instanceof Error ? err.message : String(err);
114
+ if (state.child === proc) {
115
+ state.child = null;
116
+ state.startedAt = null;
117
+ }
118
+ });
119
+ proc.on("exit", () => {
120
+ if (state.child === proc) {
121
+ state.child = null;
122
+ state.startedAt = null;
123
+ }
124
+ });
125
+ proc.unref();
126
+ state.child = proc;
127
+ state.startedAt = new Date();
128
+ state.lastArgs = args;
129
+ state.lastError = null;
130
+ return true;
131
+ } catch (err) {
132
+ state.lastError = err instanceof Error ? err.message : String(err);
133
+ return false;
134
+ }
135
+ }
136
+
137
+ function hasRunningAgent() {
138
+ try {
139
+ const agents = ctx.get?.("agents");
140
+ if (!agents || typeof agents.values !== "function") return false;
141
+ for (const agent of agents.values()) {
142
+ if (agent?.status === "running") return true;
143
+ }
144
+ } catch {}
145
+ return false;
146
+ }
147
+
148
+ function reconcile() {
149
+ if (!state.enabled) {
150
+ stopCaffeinate();
151
+ return;
152
+ }
153
+ if (state.mode === "always") {
154
+ if (!state.child) startCaffeinate();
155
+ return;
156
+ }
157
+ // running-only mode
158
+ if (hasRunningAgent()) {
159
+ if (!state.child) startCaffeinate();
160
+ } else {
161
+ stopCaffeinate();
162
+ }
163
+ }
164
+
165
+ // Initial activation
166
+ reconcile();
167
+
168
+ // Periodic health & running-only check every 15s
169
+ const timer = setInterval(() => {
170
+ reconcile();
171
+ }, 15_000);
172
+ if (typeof timer.unref === "function") timer.unref();
173
+
174
+ ctx.effect(() => () => {
175
+ clearInterval(timer);
176
+ stopCaffeinate();
177
+ });
178
+
179
+ async function handleCommand({ args }) {
180
+ const sub = String(args ?? "")
181
+ .trim()
182
+ .toLowerCase();
183
+
184
+ if (sub === "on" || sub === "start") {
185
+ state.enabled = true;
186
+ state.mode = "always";
187
+ state.preventDisplaySleep = config.preventDisplaySleep;
188
+ startCaffeinate();
189
+ } else if (sub === "display" || sub === "screen") {
190
+ state.enabled = true;
191
+ state.mode = "always";
192
+ state.preventDisplaySleep = true;
193
+ startCaffeinate();
194
+ } else if (sub === "nodisplay" || sub === "headless") {
195
+ state.enabled = true;
196
+ state.mode = "always";
197
+ state.preventDisplaySleep = false;
198
+ startCaffeinate();
199
+ } else if (sub === "running" || sub === "auto") {
200
+ state.enabled = true;
201
+ state.mode = "running-only";
202
+ reconcile();
203
+ } else if (sub === "off" || sub === "stop") {
204
+ state.enabled = false;
205
+ stopCaffeinate();
206
+ }
207
+
208
+ const assertions = await queryPmsetAssertions();
209
+ const isRunning = Boolean(state.child && state.child.pid);
210
+ const uptimeSec = state.startedAt
211
+ ? Math.max(0, Math.round((Date.now() - state.startedAt.getTime()) / 1000))
212
+ : 0;
213
+
214
+ return {
215
+ kind: "success",
216
+ text: [
217
+ `☕ **DSH 防休眠守护 (dsh-caffeinate)**`,
218
+ `- 守护状态:${isRunning ? `🟢 运行中 (caffeinate PID: \`${state.child.pid}\`, 绑定 DSH Host PID: \`${process.pid}\`, 已持续 ${uptimeSec}s)` : state.enabled ? "🟡 待命(running-only 模式下暂无运行中会话)" : "⚪ 已关闭"}`,
219
+ `- 当前模式:\`${state.mode}\`(${state.mode === "always" ? "DSH 运行期间始终防休眠" : "仅当有 Agent 任务运行时防休眠"})`,
220
+ `- 启动参数:\`/usr/bin/caffeinate ${state.lastArgs.join(" ")}\``,
221
+ `- 屏幕策略:${state.preventDisplaySleep ? "🔆 保持屏幕常亮 (-d)" : "🌙 允许屏幕正常息屏省电,仅阻止系统/CPU/网络/磁盘休眠 (-i -s -m)"}`,
222
+ state.lastError ? `- 最近异常:${state.lastError}` : "",
223
+ ``,
224
+ `### 系统当前防休眠断言 (\`pmset -g assertions\`)`,
225
+ "```text",
226
+ assertions,
227
+ "```",
228
+ ``,
229
+ `**可用指令**:\`/keepawake status\` · \`/keepawake on\`(允许息屏防系统休眠)· \`/keepawake display\`(连屏幕也保持常亮)· \`/keepawake running\`(仅任务运行时防休眠)· \`/keepawake off\`(关闭插件内防休眠)`,
230
+ ]
231
+ .filter((line) => line !== "")
232
+ .join("\n"),
233
+ };
234
+ }
235
+
236
+ ctx.inject(["commands"], (cmdCtx) => {
237
+ const definition = {
238
+ description:
239
+ "查看或控制 DSH 防休眠守护(Keep Awake):通过 macOS caffeinate 绑定主进程防止系统/网络/磁盘休眠",
240
+ input: {
241
+ hint: "[status | on | display | nodisplay | running | off]",
242
+ attachments: false,
243
+ },
244
+ handler: handleCommand,
245
+ };
246
+ cmdCtx.commands.register({ name: "keepawake", ...definition });
247
+ cmdCtx.commands.register({ name: "caffeinate", ...definition });
248
+ });
249
+ }
250
+
251
+ export default { name, inject, apply, Config };
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Caffeinate · Sleep Guard",
4
+ "description": "Runs macOS caffeinate while DeepSeek Harness is running and binds the assertion to the host process with -w: the display may still lock and sleep, while system, CPU and disk idle sleep are held off during long tasks. Includes the /keepawake command."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "防休眠守护 · Caffeinate",
4
+ "description": "在 DSH 运行期间调用 macOS 自带的 caffeinate,并用 -w 把断言绑定到宿主进程:允许显示器正常息屏锁屏,但阻止系统、CPU 与磁盘空闲休眠,防止长任务与编队执行被打断。可用 /keepawake 查看与切换。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "dsh-caffeinate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Keep the Mac awake while DeepSeek Harness runs: a macOS caffeinate child process bound to the host pid with -w, plus the /keepawake command family.",
6
+ "license": "MIT",
7
+ "author": {
8
+ "name": "veritaswiki",
9
+ "url": "https://github.com/veritaswiki"
10
+ },
11
+ "keywords": [
12
+ "dsh-plugin",
13
+ "deepseek-harness",
14
+ "dsh",
15
+ "cordis",
16
+ "caffeinate",
17
+ "keep-awake",
18
+ "macos",
19
+ "sleep-prevention"
20
+ ],
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/veritaswiki/dsh-caffeinate.git"
24
+ },
25
+ "homepage": "https://github.com/veritaswiki/dsh-caffeinate#readme",
26
+ "bugs": {
27
+ "url": "https://github.com/veritaswiki/dsh-caffeinate/issues"
28
+ },
29
+ "icon": "./icon.svg",
30
+ "exports": {
31
+ ".": "./index.js",
32
+ "./locale/*.json": "./locale/*.json",
33
+ "./icon": "./icon.svg"
34
+ },
35
+ "files": [
36
+ "index.js",
37
+ "cordis.patch.yml",
38
+ "locale/*.json",
39
+ "icon.svg",
40
+ "assets/icon-180.png",
41
+ "README.md",
42
+ "README.en.md",
43
+ "CHANGELOG.md",
44
+ "LICENSE"
45
+ ],
46
+ "publishConfig": {
47
+ "access": "public",
48
+ "provenance": true
49
+ },
50
+ "peerDependencies": {
51
+ "@deepseek-ai/schemastery": ">=3.0.0-0"
52
+ },
53
+ "scripts": {
54
+ "check": "node --check index.js",
55
+ "sanitize": "node scripts/sanitize-check.mjs"
56
+ },
57
+ "dsh": {
58
+ "bundle": {
59
+ "patch": "./cordis.patch.yml"
60
+ }
61
+ }
62
+ }