@narumitw/pi-caffeinate 0.1.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 narumiruna
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 ADDED
@@ -0,0 +1,75 @@
1
+ # pi-caffeinate
2
+
3
+ A public [pi](https://pi.dev) extension package that keeps your computer awake while the pi agent is processing a prompt.
4
+
5
+ The extension starts an OS sleep inhibitor on `agent_start` and releases it on `agent_end` or `session_shutdown`.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pi install npm:@narumitw/pi-caffeinate
11
+ ```
12
+
13
+ Try without installing:
14
+
15
+ ```bash
16
+ pi -e npm:@narumitw/pi-caffeinate
17
+ ```
18
+
19
+ Try this package locally from the repository root:
20
+
21
+ ```bash
22
+ pi -e ./extensions/pi-caffeinate
23
+ ```
24
+
25
+ ## Supported platforms
26
+
27
+ - macOS: uses `caffeinate -dimsu`
28
+ - Windows: uses PowerShell `SetThreadExecutionState`
29
+ - WSL: uses Windows `powershell.exe` with `SetThreadExecutionState`
30
+ - Linux: uses `systemd-inhibit` with `sleep infinity`
31
+ - Linux fallback: uses `caffeinate -dimsu` if available
32
+
33
+ If no supported inhibitor is available, the extension stays loaded and reports that caffeinate is unavailable.
34
+
35
+ ## Commands
36
+
37
+ ```text
38
+ /caffeinate-status
39
+ ```
40
+
41
+ Shows whether an inhibitor is active, unavailable, or disabled.
42
+
43
+ ```text
44
+ /caffeinate-stop
45
+ ```
46
+
47
+ Manually releases any active inhibitor for the current session.
48
+
49
+ ## Configuration
50
+
51
+ Disable the extension:
52
+
53
+ ```bash
54
+ PI_CAFFEINATE_DISABLED=1 pi
55
+ ```
56
+
57
+ Use a custom inhibitor command:
58
+
59
+ ```bash
60
+ PI_CAFFEINATE_COMMAND='systemd-inhibit --what=idle:sleep --why="pi running" --mode=block sleep infinity' pi
61
+ ```
62
+
63
+ The custom command is parsed with shell-like quoting and is run directly without a shell.
64
+
65
+ ## Package layout
66
+
67
+ ```txt
68
+ extensions/pi-caffeinate/
69
+ ├── src/
70
+ │ └── caffeinate.ts
71
+ ├── README.md
72
+ ├── LICENSE
73
+ ├── tsconfig.json
74
+ └── package.json
75
+ ```
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@narumitw/pi-caffeinate",
3
+ "version": "0.1.3",
4
+ "description": "Pi extension that keeps the computer awake while the agent is running.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "keywords": [
9
+ "pi-package",
10
+ "pi-extension",
11
+ "pi",
12
+ "caffeinate",
13
+ "awake",
14
+ "sleep"
15
+ ],
16
+ "files": [
17
+ "src",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "pi": {
22
+ "extensions": [
23
+ "./src/caffeinate.ts"
24
+ ]
25
+ },
26
+ "scripts": {
27
+ "check": "biome check . && npm run typecheck",
28
+ "format": "biome check --write .",
29
+ "typecheck": "tsc --noEmit"
30
+ },
31
+ "devDependencies": {
32
+ "@biomejs/biome": "2.4.14",
33
+ "@mariozechner/pi-coding-agent": "0.73.0",
34
+ "@types/node": "25.6.0",
35
+ "typescript": "6.0.3"
36
+ }
37
+ }
@@ -0,0 +1,318 @@
1
+ import { type ChildProcess, spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import pathModule from "node:path";
4
+ import process from "node:process";
5
+ import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
6
+
7
+ const STATUS_KEY = "caffeinate";
8
+ const DISABLED_VALUES = new Set(["1", "true", "yes", "on"]);
9
+
10
+ interface InhibitorCommand {
11
+ command: string;
12
+ args: string[];
13
+ description: string;
14
+ }
15
+
16
+ interface CaffeinateState {
17
+ process?: ChildProcess;
18
+ startedAt?: number;
19
+ command?: InhibitorCommand;
20
+ lastError?: string;
21
+ activeTurns: number;
22
+ available: boolean;
23
+ disabled: boolean;
24
+ }
25
+
26
+ const state: CaffeinateState = {
27
+ activeTurns: 0,
28
+ available: true,
29
+ disabled: isDisabled(),
30
+ };
31
+
32
+ export default function caffeinate(pi: ExtensionAPI) {
33
+ pi.on("session_start", (_event, ctx) => {
34
+ updateStatus(ctx);
35
+ });
36
+
37
+ pi.on("agent_start", (_event, ctx) => {
38
+ state.activeTurns += 1;
39
+ startInhibitor(ctx);
40
+ });
41
+
42
+ pi.on("agent_end", (_event, ctx) => {
43
+ state.activeTurns = Math.max(0, state.activeTurns - 1);
44
+ if (state.activeTurns === 0) stopInhibitor(ctx, "agent finished");
45
+ updateStatus(ctx);
46
+ });
47
+
48
+ pi.on("session_shutdown", (_event, ctx) => {
49
+ state.activeTurns = 0;
50
+ stopInhibitor(ctx, "session shutdown", { notify: false });
51
+ ctx.ui.setStatus(STATUS_KEY, undefined);
52
+ });
53
+
54
+ pi.registerCommand("caffeinate-status", {
55
+ description: "Show whether pi-caffeinate is currently keeping the computer awake",
56
+ handler: async (_args, ctx) => {
57
+ ctx.ui.notify(describeState(), state.process ? "info" : state.available ? "info" : "warning");
58
+ updateStatus(ctx);
59
+ },
60
+ });
61
+
62
+ pi.registerCommand("caffeinate-stop", {
63
+ description: "Release the active pi-caffeinate sleep inhibitor",
64
+ handler: async (_args, ctx) => {
65
+ state.activeTurns = 0;
66
+ stopInhibitor(ctx, "manual stop");
67
+ updateStatus(ctx);
68
+ },
69
+ });
70
+ }
71
+
72
+ function startInhibitor(ctx: ExtensionContext) {
73
+ if (state.disabled) {
74
+ updateStatus(ctx);
75
+ return;
76
+ }
77
+
78
+ if (state.process) {
79
+ updateStatus(ctx);
80
+ return;
81
+ }
82
+
83
+ const command = getInhibitorCommand();
84
+ if (!command) {
85
+ state.available = false;
86
+ state.lastError = `No supported sleep inhibitor found for ${process.platform}.`;
87
+ ctx.ui.notify(state.lastError, "warning");
88
+ updateStatus(ctx);
89
+ return;
90
+ }
91
+
92
+ try {
93
+ const child = spawn(command.command, command.args, {
94
+ detached: false,
95
+ stdio: ["ignore", "pipe", "pipe"],
96
+ });
97
+
98
+ state.process = child;
99
+ state.startedAt = Date.now();
100
+ state.command = command;
101
+ state.available = true;
102
+ state.lastError = undefined;
103
+
104
+ child.once("error", (error) => {
105
+ if (state.process === child) {
106
+ state.process = undefined;
107
+ state.startedAt = undefined;
108
+ }
109
+ state.available = false;
110
+ state.lastError = `${command.description} failed: ${error.message}`;
111
+ ctx.ui.notify(state.lastError, "warning");
112
+ updateStatus(ctx);
113
+ });
114
+
115
+ child.once("exit", (code, signal) => {
116
+ if (state.process !== child) return;
117
+ state.process = undefined;
118
+ state.startedAt = undefined;
119
+ state.lastError = `${command.description} exited unexpectedly (${formatExit(code, signal)}).`;
120
+ ctx.ui.notify(state.lastError, "warning");
121
+ updateStatus(ctx);
122
+ });
123
+
124
+ ctx.ui.notify(`Keeping computer awake with ${command.description}.`, "info");
125
+ updateStatus(ctx);
126
+ } catch (error) {
127
+ state.process = undefined;
128
+ state.startedAt = undefined;
129
+ state.available = false;
130
+ state.lastError = error instanceof Error ? error.message : String(error);
131
+ ctx.ui.notify(`Unable to start pi-caffeinate: ${state.lastError}`, "warning");
132
+ updateStatus(ctx);
133
+ }
134
+ }
135
+
136
+ function stopInhibitor(ctx: ExtensionContext, reason: string, options: { notify?: boolean } = {}) {
137
+ const child = state.process;
138
+ if (!child) return;
139
+
140
+ state.process = undefined;
141
+ state.startedAt = undefined;
142
+
143
+ child.removeAllListeners("exit");
144
+ child.removeAllListeners("error");
145
+
146
+ if (!child.killed) {
147
+ if (process.platform === "win32") {
148
+ child.kill();
149
+ } else {
150
+ child.kill("SIGTERM");
151
+ }
152
+ }
153
+
154
+ if (options.notify !== false) {
155
+ ctx.ui.notify(`Released pi-caffeinate (${reason}).`, "info");
156
+ }
157
+ }
158
+
159
+ function getInhibitorCommand(): InhibitorCommand | undefined {
160
+ const customCommand = process.env.PI_CAFFEINATE_COMMAND?.trim();
161
+ if (customCommand) {
162
+ const [command, ...args] = splitCommand(customCommand);
163
+ if (command) return { command, args, description: command };
164
+ }
165
+
166
+ if (process.platform === "darwin") {
167
+ return { command: "caffeinate", args: ["-dimsu"], description: "caffeinate" };
168
+ }
169
+
170
+ if (process.platform === "linux") {
171
+ if (isWsl() && commandExists("powershell.exe")) {
172
+ return windowsPowerInhibitorCommand("powershell.exe");
173
+ }
174
+
175
+ if (commandExists("systemd-inhibit")) {
176
+ return {
177
+ command: "systemd-inhibit",
178
+ args: [
179
+ "--what=idle:sleep",
180
+ "--who=pi-caffeinate",
181
+ "--why=Pi agent is running",
182
+ "--mode=block",
183
+ "sleep",
184
+ "infinity",
185
+ ],
186
+ description: "systemd-inhibit",
187
+ };
188
+ }
189
+
190
+ if (commandExists("caffeinate")) {
191
+ return { command: "caffeinate", args: ["-dimsu"], description: "caffeinate" };
192
+ }
193
+ }
194
+
195
+ if (process.platform === "win32") {
196
+ return windowsPowerInhibitorCommand("powershell.exe");
197
+ }
198
+
199
+ return undefined;
200
+ }
201
+
202
+ function commandExists(command: string) {
203
+ const path = process.env.PATH ?? "";
204
+ const extensions = process.platform === "win32" ? ["", ".exe", ".cmd", ".bat"] : [""];
205
+
206
+ for (const directory of path.split(process.platform === "win32" ? ";" : ":")) {
207
+ if (!directory) continue;
208
+ for (const extension of extensions) {
209
+ const candidate = pathModule.join(directory, `${command}${extension}`);
210
+ if (existsSync(candidate)) return true;
211
+ }
212
+ }
213
+
214
+ return false;
215
+ }
216
+
217
+ function splitCommand(input: string) {
218
+ const parts: string[] = [];
219
+ let current = "";
220
+ let quote: '"' | "'" | undefined;
221
+ let escaping = false;
222
+
223
+ for (const char of input) {
224
+ if (escaping) {
225
+ current += char;
226
+ escaping = false;
227
+ continue;
228
+ }
229
+
230
+ if (char === "\\") {
231
+ escaping = true;
232
+ continue;
233
+ }
234
+
235
+ if ((char === '"' || char === "'") && !quote) {
236
+ quote = char;
237
+ continue;
238
+ }
239
+
240
+ if (char === quote) {
241
+ quote = undefined;
242
+ continue;
243
+ }
244
+
245
+ if (/\s/.test(char) && !quote) {
246
+ if (current) {
247
+ parts.push(current);
248
+ current = "";
249
+ }
250
+ continue;
251
+ }
252
+
253
+ current += char;
254
+ }
255
+
256
+ if (current) parts.push(current);
257
+ return parts;
258
+ }
259
+
260
+ function windowsPowerInhibitorCommand(command: string): InhibitorCommand {
261
+ return {
262
+ command,
263
+ args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", windowsInhibitorScript()],
264
+ description: "PowerShell SetThreadExecutionState",
265
+ };
266
+ }
267
+
268
+ function windowsInhibitorScript() {
269
+ return `Add-Type -Namespace Native -Name Power -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint esFlags);'; while ($true) { [Native.Power]::SetThreadExecutionState(0x80000000 -bor 0x00000001 -bor 0x00000002) | Out-Null; Start-Sleep -Seconds 30 }`;
270
+ }
271
+
272
+ function isWsl() {
273
+ try {
274
+ return existsSync("/proc/sys/fs/binfmt_misc/WSLInterop");
275
+ } catch {
276
+ return false;
277
+ }
278
+ }
279
+
280
+ function updateStatus(ctx: ExtensionContext) {
281
+ if (state.disabled) {
282
+ ctx.ui.setStatus(STATUS_KEY, "caffeinate: disabled");
283
+ return;
284
+ }
285
+
286
+ if (state.process) {
287
+ ctx.ui.setStatus(STATUS_KEY, `caffeinate: on (${state.command?.description ?? "active"})`);
288
+ return;
289
+ }
290
+
291
+ if (!state.available) {
292
+ ctx.ui.setStatus(STATUS_KEY, "caffeinate: unavailable");
293
+ return;
294
+ }
295
+
296
+ ctx.ui.setStatus(STATUS_KEY, "caffeinate: idle");
297
+ }
298
+
299
+ function describeState() {
300
+ if (state.disabled) return "pi-caffeinate is disabled by PI_CAFFEINATE_DISABLED.";
301
+ if (state.process) {
302
+ const seconds = state.startedAt ? Math.round((Date.now() - state.startedAt) / 1000) : 0;
303
+ return `pi-caffeinate is active using ${state.command?.description ?? "an inhibitor"} for ${seconds}s.`;
304
+ }
305
+ if (!state.available)
306
+ return `pi-caffeinate is unavailable: ${state.lastError ?? "unknown reason"}`;
307
+ return "pi-caffeinate is idle and will keep the computer awake during the next agent run.";
308
+ }
309
+
310
+ function formatExit(code: number | null, signal: NodeJS.Signals | null) {
311
+ if (signal) return `signal ${signal}`;
312
+ return `code ${code ?? "unknown"}`;
313
+ }
314
+
315
+ function isDisabled() {
316
+ const value = process.env.PI_CAFFEINATE_DISABLED?.trim().toLowerCase();
317
+ return value ? DISABLED_VALUES.has(value) : false;
318
+ }