Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
674 lines (618 loc) · 22.7 KB
/
Copy pathindex.ts
File metadata and controls
674 lines (618 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
import type { Plugin } from "@opencode-ai/plugin";
import type {
Context as PluginContextV2,
Plugin as PluginV2,
} from "@opencode/plugin/promise/plugin";
import {
existsSync,
mkdirSync,
readdirSync,
readFileSync,
writeFileSync,
unlinkSync,
} from "fs";
import { spawn, spawnSync } from "child_process";
const TMP_DIR = "/tmp/opencode-wakelock";
const SESSIONS_DIR = `${TMP_DIR}/sessions`;
const LOCK_PID_FILE = `${TMP_DIR}/lock.pid`;
const LEGACY_CAFFEINATE_PID_FILE = `${TMP_DIR}/caffeinate.pid`;
type SupportedPlatform = "darwin" | "linux";
type LogFn = (
level: "info" | "warn" | "debug",
message: string,
extra?: Record<string, unknown>,
) => Promise<void>;
// Extracts the sessionID a user-input event belongs to. v1 delivers the payload
// under `properties`, v2 under `data`, and `form.created` nests it under `form`.
function sessionIDOf(
event: { properties?: unknown; data?: unknown },
): string | undefined {
const payload = event.properties ?? event.data;
const p = payload as { sessionID?: string; form?: { sessionID?: string } };
return p?.sessionID ?? p?.form?.sessionID;
}
// Extracts the request id a user-input event belongs to. An "asked"/"created"
// event carries it as `id` (or `form.id`); a "replied"/"cancelled"/"rejected"
// event carries it as `requestID` (or `id`).
function requestIDOf(
event: { properties?: unknown; data?: unknown },
): string | undefined {
const p = (event.properties ?? event.data) as { id?: string; requestID?: string; form?: { id?: string } };
return p?.id ?? p?.requestID ?? p?.form?.id;
}
function detectPlatform(): SupportedPlatform | null {
if (process.platform === "darwin") return "darwin";
if (process.platform === "linux") return "linux";
return null;
}
interface InhibitorCommand {
command: string;
args: string[];
}
function getInhibitorCommand(platform: SupportedPlatform): InhibitorCommand {
// The inhibitor is shared across servers. Watch all entry owners, not
// just the server that spawned it, so a crash cannot orphan the lock or
// release another server's active sessions/background shells.
const watchdog = [
"sh",
"-c",
`while :; do
active=false
for entry in "$1"/*; do
pid=$(cat "$entry" 2>/dev/null) || continue
case "$pid" in ''|*[!0-9]*|0*) continue ;; esac
if kill -0 "$pid" 2>/dev/null; then
active=true
break
fi
done
"$active" || exit 0
sleep 1
done`,
"opencode-wakelock",
SESSIONS_DIR,
];
if (platform === "darwin") {
return { command: "caffeinate", args: ["-i", ...watchdog] };
}
return {
command: "systemd-inhibit",
args: [
"--what=sleep:idle",
"--who=opencode-wakelock",
"--why=OpenCode session is active",
...watchdog,
],
};
}
type CaffeinateProcess = {
pid: number;
// Absent only in PID files written by releases through 0.1.5.
startedAt?: string;
// caffeinate execs the supervised shell at the PID returned by spawn.
watchdog?: true;
};
function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function getProcessInfo(pid: number) {
// macOS can reuse a live PID, so start time is required for process identity.
const result = spawnSync(
"ps",
["-p", String(pid), "-o", "comm=", "-o", "ppid=", "-o", "lstart="],
{ encoding: "utf8" },
);
const match = result.stdout.trim().match(/^(\S+)\s+(\d+)\s+(.+)$/);
if (result.status !== 0 || !match) return;
return { command: match[1], parentPid: Number(match[2]), startedAt: match[3] };
}
function readCaffeinateProcess(): CaffeinateProcess | undefined {
const pidFile = existsSync(LOCK_PID_FILE)
? LOCK_PID_FILE
: LEGACY_CAFFEINATE_PID_FILE;
if (!existsSync(pidFile)) return;
const contents = readFileSync(pidFile, "utf8").trim();
try {
// Accept the PID-only format long enough to migrate existing installations.
const stored = JSON.parse(contents) as CaffeinateProcess | number;
if (typeof stored === "number")
return Number.isInteger(stored) && stored > 0 ? { pid: stored } : undefined;
if (stored && Number.isInteger(stored.pid) && stored.pid > 0) return stored;
} catch {
const pid = Number(contents);
if (Number.isInteger(pid) && pid > 0) return { pid };
}
}
function isCaffeinateProcess(stored: CaffeinateProcess): boolean {
const info = getProcessInfo(stored.pid);
if (!info) return false;
if (stored.watchdog) {
// The command may still be caffeinate while it is starting the shell.
return (info.command === "sh" || info.command === "caffeinate")
&& !!stored.startedAt && stored.startedAt === info.startedAt;
}
if (info.command !== "caffeinate") return false;
if (stored.startedAt) return stored.startedAt === info.startedAt;
// Migrate legacy PID-only files only when caffeinate is owned by OpenCode.
if (getProcessInfo(info.parentPid)?.command !== "opencode") return false;
writeFileSync(LOCK_PID_FILE, JSON.stringify({
pid: stored.pid,
startedAt: info.startedAt,
}));
try {
unlinkSync(LEGACY_CAFFEINATE_PID_FILE);
} catch {}
return true;
}
function ensureDirs() {
mkdirSync(SESSIONS_DIR, { recursive: true });
}
function getActiveSessions(): string[] {
if (!existsSync(SESSIONS_DIR)) return [];
const files = readdirSync(SESSIONS_DIR);
const active: string[] = [];
for (const sessionID of files) {
const filePath = `${SESSIONS_DIR}/${sessionID}`;
try {
const pid = parseInt(readFileSync(filePath, "utf8").trim(), 10);
if (isProcessAlive(pid)) active.push(sessionID);
else unlinkSync(filePath);
} catch {}
}
return active;
}
function isLockRunning(platform: SupportedPlatform): boolean {
if (platform === "darwin") {
try {
const stored = readCaffeinateProcess();
if (stored && isCaffeinateProcess(stored)) return true;
unlinkSync(LOCK_PID_FILE);
} catch {}
try {
unlinkSync(LEGACY_CAFFEINATE_PID_FILE);
} catch {}
return false;
}
if (!existsSync(LOCK_PID_FILE)) return false;
try {
const pid = parseInt(readFileSync(LOCK_PID_FILE, "utf8").trim(), 10);
if (isProcessAlive(pid)) return true;
unlinkSync(LOCK_PID_FILE);
return false;
} catch {
return false;
}
}
function startLock(platform: SupportedPlatform, log: LogFn): boolean {
const cmd = getInhibitorCommand(platform);
const reportFailure = (e: unknown) => {
const message = e instanceof Error ? e.message : String(e);
void log("warn", `Failed to start ${cmd.command}`, {
platform,
command: cmd.command,
error: message,
}).catch(() => {});
};
try {
const proc = spawn(cmd.command, cmd.args, { stdio: "ignore" });
proc.once("error", (e) => {
try {
const storedPid = platform === "darwin"
? readCaffeinateProcess()?.pid
: Number(readFileSync(LOCK_PID_FILE, "utf8").trim());
if (proc.pid !== undefined && storedPid === proc.pid) {
unlinkSync(LOCK_PID_FILE);
}
} catch {}
reportFailure(e);
});
if (proc.pid === undefined) return false;
try {
if (platform === "darwin") {
const info = getProcessInfo(proc.pid);
if (!info) {
// Do not leave an inhibitor running when it cannot be tracked safely.
proc.kill();
return false;
}
writeFileSync(LOCK_PID_FILE, JSON.stringify({
pid: proc.pid,
startedAt: info.startedAt,
watchdog: true,
}));
} else {
writeFileSync(LOCK_PID_FILE, String(proc.pid));
}
proc.unref();
return true;
} catch (e) {
proc.kill();
reportFailure(e);
return false;
}
} catch (e) {
reportFailure(e);
return false;
}
}
function stopLock(platform: SupportedPlatform) {
if (platform === "darwin") {
try {
const stored = readCaffeinateProcess();
// A stale PID file may point to an unrelated process after PID reuse.
if (stored && isCaffeinateProcess(stored))
process.kill(stored.pid, "SIGTERM");
} catch {}
try {
unlinkSync(LOCK_PID_FILE);
} catch {}
try {
unlinkSync(LEGACY_CAFFEINATE_PID_FILE);
} catch {}
return;
}
if (!existsSync(LOCK_PID_FILE)) return;
try {
const pid = parseInt(readFileSync(LOCK_PID_FILE, "utf8").trim(), 10);
process.kill(pid, "SIGTERM");
} catch {}
try {
unlinkSync(LOCK_PID_FILE);
} catch {}
}
function acquire(sessionID: string, platform: SupportedPlatform, log: LogFn): boolean {
ensureDirs();
writeFileSync(`${SESSIONS_DIR}/${sessionID}`, String(process.pid));
if (isLockRunning(platform)) return true;
return startLock(platform, log);
}
function release(sessionID: string, platform: SupportedPlatform) {
try {
unlinkSync(`${SESSIONS_DIR}/${sessionID}`);
} catch {}
const remaining = getActiveSessions();
if (remaining.length === 0) stopLock(platform);
}
function startupCleanup(platform: SupportedPlatform) {
ensureDirs();
const active = getActiveSessions();
if (active.length === 0) stopLock(platform);
}
const wakelockPlugin: Plugin = async ({ client }) => {
const platform = detectPlatform();
const log: LogFn = async (level, message, extra) => {
await client.app.log({
body: { level, service: "wakelock", message, extra },
});
};
await log("info", "Plugin initializing", {
platform: process.platform,
pid: process.pid,
});
if (platform === null) {
await log("info", "Plugin inactive (unsupported platform)");
return {};
}
startupCleanup(platform);
await log("info", "Startup cleanup complete", { platform });
// Sessions this instance considers active.
const activeSessions = new Set<string>();
// Per-session set of the request ids of prompts still awaiting the user. A
// session's lock entry is held back while this set is nonempty; it is
// re-acquired only once the last pending prompt for that session resolves, so
// overlapping prompts for one session do not re-acquire early. An "undefined"
// key stands in for a prompt that carried no request id.
const pendingPrompts = new Map<string, Set<string>>();
const clearPendingFor = (sessionID: string) => {
pendingPrompts.delete(sessionID);
};
// Event types that mean OpenCode is now blocked waiting for the user.
const WAIT_EVENTS = new Set([
"permission.asked",
"form.created",
"question.asked",
]);
// Event types that mean the user has answered or dismissed a prompt.
const RESUME_EVENTS = new Set([
"permission.replied",
"form.replied",
"form.cancelled",
"question.replied",
"question.rejected",
]);
// Hold back a session's lock entry so the system may sleep while the user is
// away. The entry is released only when the first pending prompt appears. When
// the wait event carries no sessionID (e.g. the question tool), fall back to
// holding back every active session, since the prompt blocks the running turn
// regardless of which session emitted it.
const suspendForInput = (sessionID: string | undefined, requestID: string | undefined) => {
const add = (id: string) => {
const set = pendingPrompts.get(id);
if (set) {
set.add(requestID ?? "undefined");
return;
}
pendingPrompts.set(id, new Set([requestID ?? "undefined"]));
release(id, platform);
};
if (sessionID) {
add(sessionID);
return;
}
for (const id of activeSessions) {
add(id);
}
};
// The user has answered (or dismissed) a prompt. Remove its request id and
// re-acquire the session's entry only when no prompt remains pending, and only
// if the session is still active, so a late reply does not resurrect a stale
// lock. A reply with no sessionID falls back to every pending session.
const resumeFromInput = (sessionID: string | undefined, requestID: string | undefined) => {
const key = requestID ?? "undefined";
const ids = sessionID ? [sessionID] : [...pendingPrompts.keys()];
for (const id of ids) {
const set = pendingPrompts.get(id);
if (!set) continue;
set.delete(key);
if (set.size > 0) continue;
pendingPrompts.delete(id);
if (!activeSessions.has(id)) continue;
const acquired = acquire(id, platform, log);
if (acquired) {
void log("info", "Re-acquired wakelock (user replied)", { sessionID: id });
}
}
};
return {
event: async ({ event }) => {
await log("debug", "Event received", { type: event.type });
if (event.type === "session.status" && event.properties.status.type === "busy") {
const { sessionID } = (event as any).properties;
activeSessions.add(sessionID);
clearPendingFor(sessionID);
if (acquire(sessionID, platform, log)) {
await log("info", "Acquired wakelock (session busy)", { sessionID });
}
}
if (event.type === "session.idle") {
const { sessionID } = (event as any).properties;
clearPendingFor(sessionID);
activeSessions.delete(sessionID);
release(sessionID, platform);
await log("info", "Released wakelock (session idle)", { sessionID });
}
if (event.type === "session.error") {
const { sessionID } = (event as any).properties;
if (sessionID) {
clearPendingFor(sessionID);
activeSessions.delete(sessionID);
release(sessionID, platform);
await log("info", "Released wakelock (session error)", { sessionID });
}
}
// OpenCode is blocked waiting for the user to answer (a permission prompt,
// the question tool, or a form). Release the session's lock entry so the
// system may sleep while the user is away.
const type = event.type as string;
if (WAIT_EVENTS.has(type)) {
suspendForInput(sessionIDOf(event), requestIDOf(event));
}
// The user has answered or cancelled. Re-acquire the session's entry.
if (RESUME_EVENTS.has(type)) {
resumeFromInput(sessionIDOf(event), requestIDOf(event));
}
},
};
};
// V2's event stream is server-wide. Several location-scoped plugin instances
// can own the same entry; unloading one must not release the others' locks.
const v2LockOwners = new Map<string, number>();
const wakelockPluginV2: PluginV2 = {
id: "opencode-wakelock",
async setup(ctx: PluginContextV2) {
const platform = detectPlatform();
if (platform === null) return;
startupCleanup(platform);
const log: LogFn = async (level, message, extra) => {
const details = extra ? ` ${JSON.stringify(extra)}` : "";
const line = `[opencode-wakelock] ${message}${details}`;
if (level === "warn") console.warn(line);
else if (level === "debug") console.debug(line);
else console.info(line);
};
const ownedLocks = new Set<string>();
const waitingSessions = new Map<string, object>();
// Per-session set of the request ids of prompts still awaiting the user. A
// session's lock entry is held back while this set is nonempty; it is
// re-acquired only once the last pending prompt for that session resolves. An
// "undefined" key stands in for a prompt that carried no request id.
const pendingPrompts = new Map<string, Set<string>>();
const clearPendingFor = (sessionID: string) => {
pendingPrompts.delete(sessionID);
};
// Sessions this instance still considers active. Guards re-acquisition after a
// session has gone terminal, so a late reply does not resurrect a stale lock.
const activeSessions = new Set<string>();
let stopped = false;
const acquireOwned = (key: string) => {
if (stopped) return;
if (!key.startsWith("shell-")) activeSessions.add(key);
if (!ownedLocks.has(key)) {
ownedLocks.add(key);
v2LockOwners.set(key, (v2LockOwners.get(key) ?? 0) + 1);
}
acquire(key, platform, log);
};
const releaseOwned = (key: string) => {
if (!ownedLocks.delete(key)) return;
const remaining = (v2LockOwners.get(key) ?? 1) - 1;
if (remaining > 0) {
v2LockOwners.set(key, remaining);
return;
}
v2LockOwners.delete(key);
release(key, platform);
};
// OpenCode is blocked waiting for the user to answer (a permission prompt, the
// question tool, or a form). Hold back the session's lock entry so the system
// may sleep while the user is away. The entry is released only when the first
// pending prompt appears.
const suspendForInput = (sessionID: string | undefined, requestID: string | undefined) => {
if (stopped) return;
const add = (id: string) => {
const set = pendingPrompts.get(id);
if (set) {
set.add(requestID ?? "undefined");
return;
}
pendingPrompts.set(id, new Set([requestID ?? "undefined"]));
releaseOwned(id);
};
if (sessionID) {
add(sessionID);
return;
}
for (const id of activeSessions) {
add(id);
}
};
// The user has answered (or dismissed) a prompt. Remove its request id and
// re-acquire the session's entry only when no prompt remains pending and the
// session is still active.
const resumeFromInput = (sessionID: string | undefined, requestID: string | undefined) => {
if (stopped) return;
const key = requestID ?? "undefined";
const ids = sessionID ? [sessionID] : [...pendingPrompts.keys()];
for (const id of ids) {
const set = pendingPrompts.get(id);
if (!set) continue;
set.delete(key);
if (set.size > 0) continue;
pendingPrompts.delete(id);
if (activeSessions.has(id)) acquireOwned(id);
}
};
const watchUntilIdle = (sessionID: string) => {
if (waitingSessions.has(sessionID)) return;
const token = {};
waitingSessions.set(sessionID, token);
void ctx.session.wait({ sessionID })
.catch(() => undefined)
.finally(() => {
// An older wait must not release a new execution's entry, or an
// entry now owned by a replacement plugin instance after cleanup.
if (waitingSessions.get(sessionID) !== token) return;
waitingSessions.delete(sessionID);
// session.wait() can complete on terminal paths that emit no public
// idle event, so clear the session's bookkeeping here; otherwise a
// late input reply could re-acquire a lock with no wait to release it.
activeSessions.delete(sessionID);
clearPendingFor(sessionID);
releaseOwned(sessionID);
});
};
// The context hook is the reliable point at which a v2 model dispatch is
// active. session.wait() follows it through every terminal path, including
// cases where the public lifecycle stream does not emit an idle event.
const contextHook = await ctx.session.hook("context", (request) => {
if (stopped) return;
acquireOwned(request.sessionID);
watchUntilIdle(request.sessionID);
});
const controller = new AbortController();
const watcher = (async () => {
try {
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
if (stopped) break;
switch (event.type) {
// Shell entries are independent of sessions. A tool can return
// early (or be moved to the background) while its shell runs on.
case "shell.created":
acquireOwned(`shell-${event.data.info.id}`);
break;
case "shell.exited":
case "shell.deleted":
releaseOwned(`shell-${event.data.id}`);
break;
case "session.status":
if (event.data.status.type === "busy") {
acquireOwned(event.data.sessionID);
watchUntilIdle(event.data.sessionID);
}
break;
case "session.idle":
case "session.execution.failed":
case "session.execution.interrupted":
waitingSessions.delete(event.data.sessionID);
clearPendingFor(event.data.sessionID);
activeSessions.delete(event.data.sessionID);
releaseOwned(event.data.sessionID);
break;
// OpenCode is blocked waiting for the user to answer (a permission
// prompt or a form). Release the session's lock entry so the system
// may sleep while the user is away.
case "permission.asked":
case "form.created": {
const sessionID = (event.data as { sessionID?: string; form?: { sessionID?: string } }).sessionID
?? (event.data as { form?: { sessionID?: string } }).form?.sessionID;
suspendForInput(sessionID, requestIDOf(event));
break;
}
// The user has answered or cancelled. Re-acquire the session's entry.
case "permission.replied":
case "form.replied":
case "form.cancelled":
resumeFromInput(
(event.data as { sessionID?: string; form?: { sessionID?: string } }).sessionID
?? (event.data as { form?: { sessionID?: string } }).form?.sessionID,
requestIDOf(event),
);
break;
}
// The question tool emits question.* events that are not in this SDK's
// event union yet, but block the turn the same way as a permission
// prompt or form. Handle them via a string cast, as the v1 path does.
const questionType = event.type as string;
if (questionType === "question.asked") {
const sessionID = (event.data as { sessionID?: string; form?: { sessionID?: string } }).sessionID
?? (event.data as { form?: { sessionID?: string } }).form?.sessionID;
suspendForInput(sessionID, requestIDOf(event));
}
if (questionType === "question.replied" || questionType === "question.rejected") {
resumeFromInput(
(event.data as { sessionID?: string; form?: { sessionID?: string } }).sessionID
?? (event.data as { form?: { sessionID?: string } }).form?.sessionID,
requestIDOf(event),
);
}
}
} catch (error) {
if (!controller.signal.aborted) {
await log("warn", "Event subscription stopped", {
error: error instanceof Error ? error.message : String(error),
});
}
}
})();
return async () => {
if (stopped) return;
stopped = true;
waitingSessions.clear();
pendingPrompts.clear();
activeSessions.clear();
controller.abort();
await watcher;
try {
await contextHook.dispose();
} finally {
for (const key of ownedLocks) releaseOwned(key);
}
};
},
};
export default { ...wakelockPluginV2, server: wakelockPlugin };