@max10240/opencode-plugin-infinite-loop 0.0.0-stage → 1.0.35
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/README.md +84 -2
- package/README.zh-CN.md +76 -0
- package/dist/index.js +3 -0
- package/dist/src/controller.js +379 -0
- package/dist/src/duration.js +100 -0
- package/dist/src/index.js +277 -0
- package/dist/src/options.js +98 -0
- package/dist/src/rpc.js +118 -0
- package/dist/src/tracker.js +360 -0
- package/dist/src/tui.js +1320 -0
- package/dist/tui.js +9 -0
- package/package.json +67 -4
package/README.md
CHANGED
|
@@ -1,3 +1,85 @@
|
|
|
1
|
-
#
|
|
1
|
+
# opencode-plugin-infinite-loop
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Keep a session working. When the session you activate it for goes idle, the plugin waits a short
|
|
4
|
+
quiet window and then sends a nudge message, so the agent keeps going until the configured time
|
|
5
|
+
window ends. A cooldown paces reminders from the last nudge, not from the check that noticed it.
|
|
6
|
+
|
|
7
|
+
## How it works
|
|
8
|
+
|
|
9
|
+
- Activate per session from the TUI; other conversations are never affected.
|
|
10
|
+
- Every idle boundary first checks live background work: background shells, subagents, and image
|
|
11
|
+
or video jobs. No nudge is sent while any of them is still running.
|
|
12
|
+
- The live directory is event-driven: session history and shell/execution events keep it current,
|
|
13
|
+
so the hot path never scans the session database.
|
|
14
|
+
- With no background work the plugin opens a quiet window (3s default). Any new input in that
|
|
15
|
+
window — your typing, cross-session messages, steering — cancels the nudge.
|
|
16
|
+
- Each successful nudge sets a cooldown. The next attempt is scheduled at
|
|
17
|
+
`max(now + quiet, lastNudge + cooldown)`. If the session went idle three minutes ago and the
|
|
18
|
+
cooldown is five minutes, the plugin waits two more minutes, then checks busy/background again
|
|
19
|
+
before sending.
|
|
20
|
+
- Abnormal endings keep the loop going: a failed turn, or a system interruption (shutdown,
|
|
21
|
+
superseded, inactivity), is picked up from the execution event stream and the loop retries.
|
|
22
|
+
- Only a manual user interruption pauses the loop. It resumes with the next turn that completes
|
|
23
|
+
normally. An explicit stop (panel `ctrl+d` twice, `/` RPC stop, or `ctrl+shift+d` stop all) ends the task.
|
|
24
|
+
- Tasks live in memory only: there is no history, and a server restart clears them.
|
|
25
|
+
- The runtime is shared across projects in one OpenCode process, so the all-projects panel can
|
|
26
|
+
see and stop every active loop.
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
|
|
30
|
+
- `/infinite-loop 2h` starts a two-hour window for the current session.
|
|
31
|
+
- `/infinite-loop 90m cooldown=10m` starts with a per-run cooldown override.
|
|
32
|
+
- `/infinite-loop` (or `ctrl+shift+i`) opens the panel: clickable presets (15m, 1h, 2h, 3h, 8h, 1d),
|
|
33
|
+
custom duration (`90m`, `1h30m`, `2d12h`, bare numbers are hours), custom cooldown (`5m`, `1h`, `0`,
|
|
34
|
+
bare numbers are minutes), live status, and `ctrl+d` twice to stop.
|
|
35
|
+
- `/infinite-loops` (or `ctrl+shift+o`) opens the all-projects panel. Inside any panel,
|
|
36
|
+
`ctrl+a` switches between this session and all projects.
|
|
37
|
+
- All-projects panel: `↑/↓` select, `ctrl+d` twice to stop the selected loop, `ctrl+shift+d` stop all
|
|
38
|
+
(with confirmation), `ctrl+r` refresh, `f1` help, `esc` close.
|
|
39
|
+
- Printable characters always belong to the duration and cooldown inputs; panel actions are Ctrl
|
|
40
|
+
combinations, so they behave the same regardless of focus.
|
|
41
|
+
- Bounds: 5 minutes to 7 days by default; cooldown 0 to 30 days. Out-of-range input is rejected
|
|
42
|
+
with the closest valid range shown.
|
|
43
|
+
- `f1` opens keyboard help; `esc` closes help first, then the panel.
|
|
44
|
+
|
|
45
|
+
## Options
|
|
46
|
+
|
|
47
|
+
```jsonc
|
|
48
|
+
{
|
|
49
|
+
"infiniteLoop": {
|
|
50
|
+
"message": "Keep working without asking any questions. Do not stop until you have finished everything you need to do.",
|
|
51
|
+
"delayMs": 3000,
|
|
52
|
+
"recheckMs": 2000,
|
|
53
|
+
"cooldownMs": 300000,
|
|
54
|
+
"defaultDurationMs": 3600000,
|
|
55
|
+
"minDurationMs": 300000,
|
|
56
|
+
"maxDurationMs": 604800000,
|
|
57
|
+
"presets": ["15m", "1h", "2h", "3h", "8h", "1d"],
|
|
58
|
+
"keybind": "ctrl+shift+i",
|
|
59
|
+
"overviewKeybind": "ctrl+shift+o"
|
|
60
|
+
},
|
|
61
|
+
"features": { "infiniteLoop": false }
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
- `message`: the text sent on every nudge.
|
|
66
|
+
- `delayMs`: the quiet window after idle (100–600000).
|
|
67
|
+
- `recheckMs`: how often background work is re-evaluated (100–600000).
|
|
68
|
+
- `cooldownMs`: minimum time between successful nudges (0–30 days); `0` disables the cooldown.
|
|
69
|
+
- `defaultDurationMs`: used when the custom duration input is empty.
|
|
70
|
+
- `minDurationMs` / `maxDurationMs`: accepted custom duration range.
|
|
71
|
+
- `presets`: panel shortcuts; invalid entries are rejected at load.
|
|
72
|
+
- `keybind` / `overviewKeybind`: global shortcuts, or `false` to disable the binding (slash
|
|
73
|
+
commands still work).
|
|
74
|
+
- `features.infiniteLoop: false` (or `enabled: false`) turns the plugin off on both the server
|
|
75
|
+
and TUI side.
|
|
76
|
+
|
|
77
|
+
## Notes
|
|
78
|
+
|
|
79
|
+
- Uses the experimental `experimental.idle` session hook; requires OpenCode 2.3 or newer. On older
|
|
80
|
+
versions the plugin disables itself.
|
|
81
|
+
- The idle hook does not run after a failed or interrupted turn. The loop recovers from the
|
|
82
|
+
durable execution events and a post-send recheck.
|
|
83
|
+
- A manual interruption of the task session or any of its subagents pauses the whole task family.
|
|
84
|
+
- Background image/video work is also treated as busy, even though the plugin's live gate is
|
|
85
|
+
primarily built around Bash and subagents.
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# opencode-plugin-infinite-loop
|
|
2
|
+
|
|
3
|
+
让会话持续工作。为你激活它的会话在空闲时等待一个短暂的安静窗口,然后发送一条 nudge
|
|
4
|
+
消息,让 agent 持续推进,直到配置的时间窗结束。冷却按“上一次成功 nudge”计算,而不是按
|
|
5
|
+
“这次检查”计算。
|
|
6
|
+
|
|
7
|
+
## 工作方式
|
|
8
|
+
|
|
9
|
+
- 通过 TUI 按会话激活,不影响其他对话。
|
|
10
|
+
- 每次空闲边界先检查实时后台任务:后台 Bash、子 Agent、图像/视频任务。运行期间不发送
|
|
11
|
+
nudge。
|
|
12
|
+
- 实时目录由事件维护:会话树、执行状态和 shell 事件增量更新,热路径不扫描会话数据库。
|
|
13
|
+
- 没有后台任务时打开安静窗口(默认 3 秒)。窗口内出现任何新输入——你打字、跨会话消息、
|
|
14
|
+
steering——都会取消本次 nudge。
|
|
15
|
+
- 每次成功 nudge 后进入冷却。下一次尝试时间 =
|
|
16
|
+
`max(现在 + 安静窗口, 上次 nudge + 冷却)`。例如上次 nudge 在 3 分钟前、冷却为 5 分钟,
|
|
17
|
+
就只再等 2 分钟;到点后重新检查 busy/后台,再决定是否发送。
|
|
18
|
+
- 异常结束不会中断循环:turn 失败或系统级中断(shutdown、superseded、inactivity)会从
|
|
19
|
+
执行事件流捕获并重试。
|
|
20
|
+
- 只有**你手动打断**才暂停循环,并在你下一个正常完成的 turn 后自动恢复。显式停止
|
|
21
|
+
(面板 `ctrl+d` 连按两次、RPC stop、`ctrl+shift+d` 停止全部)才真正终止任务。
|
|
22
|
+
- 任务只存在于内存:没有历史记录,服务重启后任务消失。
|
|
23
|
+
- 同一个 OpenCode 进程内所有项目共享 runtime,所以“所有项目”面板能看到并停止全部 Loop。
|
|
24
|
+
|
|
25
|
+
## 用法
|
|
26
|
+
|
|
27
|
+
- `/infinite-loop 2h` 为当前会话启动 2 小时的时间窗。
|
|
28
|
+
- `/infinite-loop 90m cooldown=10m` 按本次任务覆盖冷却。
|
|
29
|
+
- `/infinite-loop`(或 `ctrl+shift+i`)打开面板:可点击的预设档位(15m、1h、2h、3h、8h、1d)、
|
|
30
|
+
自定义时长(`90m`、`1h30m`、`2d12h`,纯数字按小时)、自定义冷却(`5m`、`1h`、`0`,
|
|
31
|
+
纯数字按分钟)、实时状态,`ctrl+d` 连按两次停止。
|
|
32
|
+
- `/infinite-loops`(或 `ctrl+shift+o`)打开“所有项目”面板。任意面板内 `ctrl+a` 可在
|
|
33
|
+
“当前会话”和“所有项目”之间切换。
|
|
34
|
+
- 所有项目面板:`↑/↓` 选择,`ctrl+d` 连按两次停止选中 Loop,`ctrl+shift+d` 停止全部(二次确认),
|
|
35
|
+
`ctrl+r` 刷新,`f1` 帮助,`esc` 关闭。
|
|
36
|
+
- 可打印字符始终输入到时长和冷却输入框;面板动作统一使用 Ctrl 组合键,不依赖焦点。
|
|
37
|
+
- 边界:默认时间窗 5 分钟到 7 天;冷却 0 到 30 天。超界输入会被拒绝并提示合法范围。
|
|
38
|
+
- `f1` 打开键位帮助;`esc` 先关帮助,再关面板。
|
|
39
|
+
|
|
40
|
+
## 配置
|
|
41
|
+
|
|
42
|
+
```jsonc
|
|
43
|
+
{
|
|
44
|
+
"infiniteLoop": {
|
|
45
|
+
"message": "Keep working without asking any questions. Do not stop until you have finished everything you need to do.",
|
|
46
|
+
"delayMs": 3000,
|
|
47
|
+
"recheckMs": 2000,
|
|
48
|
+
"cooldownMs": 300000,
|
|
49
|
+
"defaultDurationMs": 3600000,
|
|
50
|
+
"minDurationMs": 300000,
|
|
51
|
+
"maxDurationMs": 604800000,
|
|
52
|
+
"presets": ["15m", "1h", "2h", "3h", "8h", "1d"],
|
|
53
|
+
"keybind": "ctrl+shift+i",
|
|
54
|
+
"overviewKeybind": "ctrl+shift+o"
|
|
55
|
+
},
|
|
56
|
+
"features": { "infiniteLoop": false }
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
- `message`:每次 nudge 发送的文本。
|
|
61
|
+
- `delayMs`:空闲后的安静窗口(100–600000)。
|
|
62
|
+
- `recheckMs`:复查后台任务的间隔(100–600000)。
|
|
63
|
+
- `cooldownMs`:两次成功 nudge 之间的最小间隔(0–30 天);`0` 表示关闭冷却。
|
|
64
|
+
- `defaultDurationMs`:自定义输入为空时使用的默认时长。
|
|
65
|
+
- `minDurationMs` / `maxDurationMs`:自定义时长允许的范围。
|
|
66
|
+
- `presets`:面板快捷档位;加载时校验,非法项会被拒绝。
|
|
67
|
+
- `keybind` / `overviewKeybind`:全局快捷键,设为 `false` 关闭键位绑定(slash 命令仍可用)。
|
|
68
|
+
- `features.infiniteLoop: false`(或 `enabled: false`)在 server 与 TUI 两侧同时关闭本插件。
|
|
69
|
+
|
|
70
|
+
## 说明
|
|
71
|
+
|
|
72
|
+
- 使用实验性的 `experimental.idle` 会话 hook,需要 OpenCode 2.3 或更新版本。旧版本上插件
|
|
73
|
+
自行禁用。
|
|
74
|
+
- turn 失败或系统级中断不会触发该 hook,循环通过执行事件流和发送后的复查自愈。
|
|
75
|
+
- 手动打断任务会话或它的任意子 Agent,会暂停整个任务家族。
|
|
76
|
+
- 图像/视频后台任务也视为忙;实时门禁的核心是 Bash 和 Subagent。
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
/** Node and Bun fire a later timer immediately, so long waits are split into chunks. */
|
|
2
|
+
const MAX_TIMER_MS = 2_147_000_000;
|
|
3
|
+
/**
|
|
4
|
+
* Owns the infinite-loop state for one OpenCode process. Pure with respect to time and effects:
|
|
5
|
+
* timers, busy lookups, and nudges are injected, which keeps the loop testable without a server.
|
|
6
|
+
*
|
|
7
|
+
* Loop flow per session:
|
|
8
|
+
* - `onIdle` runs at the idle boundary. Any background work rechecks until it quiets.
|
|
9
|
+
* - With no background work, `fireAt = max(now + delayMs, lastSentAt + cooldownMs)`.
|
|
10
|
+
* A cooldown is measured from the last successful nudge, not from the check that noticed it.
|
|
11
|
+
* - At `fireAt` the session is checked again; any new input, stop, or new task invalidates the
|
|
12
|
+
* attempt through the task generation counter.
|
|
13
|
+
* - The nudge is sent only after a final busy/background check. The cycle repeats until the
|
|
14
|
+
* task's deadline.
|
|
15
|
+
*/
|
|
16
|
+
export class InfiniteLoopController {
|
|
17
|
+
options;
|
|
18
|
+
tasks = new Map();
|
|
19
|
+
outcomes = new Map();
|
|
20
|
+
/** Latest background list observed at each session's idle boundary, keyed by session ID. */
|
|
21
|
+
backgrounds = new Map();
|
|
22
|
+
constructor(options) {
|
|
23
|
+
this.options = options;
|
|
24
|
+
}
|
|
25
|
+
start(sessionID, durationMs, alreadyIdle, cooldownMs = this.options.cooldownMs) {
|
|
26
|
+
const now = this.options.now();
|
|
27
|
+
const previous = this.tasks.get(sessionID);
|
|
28
|
+
if (previous)
|
|
29
|
+
this.clearTimer(previous);
|
|
30
|
+
const task = {
|
|
31
|
+
sessionID,
|
|
32
|
+
startedAt: now,
|
|
33
|
+
deadline: now + Math.max(1, Math.round(durationMs)),
|
|
34
|
+
cooldownMs: Math.max(0, Math.round(cooldownMs)),
|
|
35
|
+
sentCount: 0,
|
|
36
|
+
generation: (previous?.generation ?? 0) + 1,
|
|
37
|
+
phase: "waiting",
|
|
38
|
+
};
|
|
39
|
+
this.tasks.set(sessionID, task);
|
|
40
|
+
this.outcomes.delete(sessionID);
|
|
41
|
+
this.backgrounds.delete(sessionID);
|
|
42
|
+
if (alreadyIdle)
|
|
43
|
+
this.armFire(task);
|
|
44
|
+
else
|
|
45
|
+
this.arm(task, "deadline", task.deadline);
|
|
46
|
+
return this.emit(sessionID);
|
|
47
|
+
}
|
|
48
|
+
stop(sessionID) {
|
|
49
|
+
if (this.tasks.has(sessionID))
|
|
50
|
+
this.finish(sessionID, "stopped");
|
|
51
|
+
return this.emit(sessionID);
|
|
52
|
+
}
|
|
53
|
+
hasTask(sessionID) {
|
|
54
|
+
return this.tasks.has(sessionID);
|
|
55
|
+
}
|
|
56
|
+
activeStatuses() {
|
|
57
|
+
return [...this.tasks.keys()].map((sessionID) => ({ sessionID, status: this.status(sessionID) }));
|
|
58
|
+
}
|
|
59
|
+
status(sessionID) {
|
|
60
|
+
const task = this.tasks.get(sessionID);
|
|
61
|
+
if (!task) {
|
|
62
|
+
const outcome = this.outcomes.get(sessionID);
|
|
63
|
+
if (!outcome)
|
|
64
|
+
return { active: false };
|
|
65
|
+
return {
|
|
66
|
+
active: false,
|
|
67
|
+
...(outcome.sentCount === undefined ? {} : { sentCount: outcome.sentCount }),
|
|
68
|
+
...(outcome.lastSentAt === undefined ? {} : { lastSentAt: outcome.lastSentAt }),
|
|
69
|
+
outcome,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
active: true,
|
|
74
|
+
startedAt: task.startedAt,
|
|
75
|
+
deadline: task.deadline,
|
|
76
|
+
sentCount: task.sentCount,
|
|
77
|
+
...(task.lastSentAt === undefined ? {} : { lastSentAt: task.lastSentAt }),
|
|
78
|
+
...(task.lastInputAt === undefined ? {} : { lastInputAt: task.lastInputAt }),
|
|
79
|
+
cooldownMs: task.cooldownMs,
|
|
80
|
+
...(task.lastSentAt === undefined ? {} : { cooldownUntil: task.lastSentAt + task.cooldownMs }),
|
|
81
|
+
...(task.timerMode === "fire" && task.timerAt !== undefined ? { nextNudgeAt: task.timerAt } : {}),
|
|
82
|
+
phase: task.phase,
|
|
83
|
+
nudging: task.phase === "quiet" || task.phase === "checking",
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/** Runs when any session finishes model work and is about to go idle. */
|
|
87
|
+
onIdle(sessionID, background) {
|
|
88
|
+
this.backgrounds.set(sessionID, background);
|
|
89
|
+
const task = this.tasks.get(sessionID);
|
|
90
|
+
if (!task)
|
|
91
|
+
return;
|
|
92
|
+
// The idle boundary is authoritative: drop stale quiet windows and rechecks.
|
|
93
|
+
task.generation += 1;
|
|
94
|
+
this.clearTimer(task);
|
|
95
|
+
if (this.options.now() >= task.deadline) {
|
|
96
|
+
this.finish(sessionID, "expired");
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
task.phase = "waiting";
|
|
100
|
+
if (background.length > 0) {
|
|
101
|
+
this.arm(task, "recheck", Math.min(this.options.now() + this.options.recheckMs, task.deadline));
|
|
102
|
+
this.emit(sessionID);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
this.armFire(task);
|
|
106
|
+
}
|
|
107
|
+
/** Runs whenever a prompt enters a session; non-own input cancels the pending nudge. */
|
|
108
|
+
onPrompt(sessionID, own) {
|
|
109
|
+
if (own)
|
|
110
|
+
return;
|
|
111
|
+
this.onInput(sessionID);
|
|
112
|
+
}
|
|
113
|
+
/** Runs when a user or synthetic item is queued but not delivered yet. */
|
|
114
|
+
onInboxEnqueued(sessionID, own) {
|
|
115
|
+
if (own)
|
|
116
|
+
return;
|
|
117
|
+
this.onInput(sessionID);
|
|
118
|
+
}
|
|
119
|
+
/** A queued user message was cancelled before delivery; re-evaluate the idle session. */
|
|
120
|
+
onInputCancelled(sessionID) {
|
|
121
|
+
const task = this.tasks.get(sessionID);
|
|
122
|
+
if (!task)
|
|
123
|
+
return;
|
|
124
|
+
task.generation += 1;
|
|
125
|
+
this.clearTimer(task);
|
|
126
|
+
if (this.options.now() >= task.deadline) {
|
|
127
|
+
this.finish(sessionID, "expired");
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
task.phase = "waiting";
|
|
131
|
+
this.arm(task, "recheck", Math.min(this.options.now() + this.options.recheckMs, task.deadline));
|
|
132
|
+
this.emit(sessionID);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Runs when a task session's execution ends abnormally, published on the event stream as
|
|
136
|
+
* `session.execution.failed` or `session.execution.interrupted`. Failures and system
|
|
137
|
+
* interrupts (shutdown, superseded, inactivity) keep the loop going; a manual user
|
|
138
|
+
* interruption pauses until the next turn that completes normally.
|
|
139
|
+
*/
|
|
140
|
+
onAborted(sessionID, abort) {
|
|
141
|
+
const task = this.tasks.get(sessionID);
|
|
142
|
+
if (!task)
|
|
143
|
+
return;
|
|
144
|
+
task.generation += 1;
|
|
145
|
+
this.clearTimer(task);
|
|
146
|
+
if (abort.type === "interrupted" && abort.reason === "user") {
|
|
147
|
+
task.phase = "paused";
|
|
148
|
+
this.arm(task, "deadline", task.deadline);
|
|
149
|
+
this.emit(sessionID);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (this.options.now() >= task.deadline) {
|
|
153
|
+
this.finish(sessionID, "expired");
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
task.phase = "waiting";
|
|
157
|
+
this.arm(task, "recheck", Math.min(this.options.now() + this.options.recheckMs, task.deadline));
|
|
158
|
+
this.emit(sessionID);
|
|
159
|
+
}
|
|
160
|
+
dispose() {
|
|
161
|
+
for (const task of this.tasks.values())
|
|
162
|
+
this.clearTimer(task);
|
|
163
|
+
this.tasks.clear();
|
|
164
|
+
this.outcomes.clear();
|
|
165
|
+
this.backgrounds.clear();
|
|
166
|
+
}
|
|
167
|
+
onInput(sessionID) {
|
|
168
|
+
const task = this.tasks.get(sessionID);
|
|
169
|
+
if (!task)
|
|
170
|
+
return;
|
|
171
|
+
task.generation += 1;
|
|
172
|
+
task.lastInputAt = this.options.now();
|
|
173
|
+
this.clearTimer(task);
|
|
174
|
+
task.phase = "waiting";
|
|
175
|
+
// The session is now busy or has a queued user message. Only the deadline timer remains;
|
|
176
|
+
// the next idle boundary or abort event re-arms the loop.
|
|
177
|
+
this.arm(task, "deadline", task.deadline);
|
|
178
|
+
this.emit(sessionID);
|
|
179
|
+
}
|
|
180
|
+
armFire(task) {
|
|
181
|
+
const now = this.options.now();
|
|
182
|
+
const cooldownUntil = task.lastSentAt === undefined ? 0 : task.lastSentAt + task.cooldownMs;
|
|
183
|
+
const at = Math.max(now + this.options.delayMs, cooldownUntil);
|
|
184
|
+
if (at >= task.deadline) {
|
|
185
|
+
task.phase = "waiting";
|
|
186
|
+
this.arm(task, "deadline", task.deadline);
|
|
187
|
+
this.emit(task.sessionID);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
task.phase = "quiet";
|
|
191
|
+
this.arm(task, "fire", at);
|
|
192
|
+
this.emit(task.sessionID);
|
|
193
|
+
}
|
|
194
|
+
arm(task, mode, at) {
|
|
195
|
+
this.clearTimer(task);
|
|
196
|
+
const now = this.options.now();
|
|
197
|
+
const intended = Math.min(at, task.deadline);
|
|
198
|
+
task.timerMode = mode;
|
|
199
|
+
task.timerAt = intended;
|
|
200
|
+
const scheduled = Math.min(intended, now + MAX_TIMER_MS);
|
|
201
|
+
const delay = Math.max(0, scheduled - now);
|
|
202
|
+
const generation = task.generation;
|
|
203
|
+
task.timer = this.options.timers.setTimeout(() => {
|
|
204
|
+
if (this.tasks.get(task.sessionID) !== task || task.generation !== generation)
|
|
205
|
+
return;
|
|
206
|
+
task.timer = undefined;
|
|
207
|
+
const current = this.options.now();
|
|
208
|
+
if (current >= task.deadline) {
|
|
209
|
+
this.finish(task.sessionID, "expired");
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (current < intended) {
|
|
213
|
+
this.arm(task, mode, intended);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
if (mode === "fire")
|
|
217
|
+
void this.checkAndSend(task, generation);
|
|
218
|
+
else
|
|
219
|
+
void this.recheck(task, generation);
|
|
220
|
+
}, delay);
|
|
221
|
+
}
|
|
222
|
+
clearTimer(task) {
|
|
223
|
+
if (task.timer !== undefined) {
|
|
224
|
+
this.options.timers.clearTimeout(task.timer);
|
|
225
|
+
task.timer = undefined;
|
|
226
|
+
}
|
|
227
|
+
task.timerAt = undefined;
|
|
228
|
+
task.timerMode = undefined;
|
|
229
|
+
}
|
|
230
|
+
async recheck(task, generation) {
|
|
231
|
+
if (!this.current(task, generation))
|
|
232
|
+
return;
|
|
233
|
+
const now = this.options.now();
|
|
234
|
+
if (now >= task.deadline) {
|
|
235
|
+
this.finish(task.sessionID, "expired");
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
task.phase = "waiting";
|
|
239
|
+
if (await this.busy(task.sessionID)) {
|
|
240
|
+
if (this.current(task, generation))
|
|
241
|
+
this.arm(task, "recheck", Math.min(this.options.now() + this.options.recheckMs, task.deadline));
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (!this.current(task, generation))
|
|
245
|
+
return;
|
|
246
|
+
if (this.options.now() >= task.deadline) {
|
|
247
|
+
this.finish(task.sessionID, "expired");
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (await this.runningWork(task.sessionID)) {
|
|
251
|
+
if (this.current(task, generation))
|
|
252
|
+
this.arm(task, "recheck", Math.min(this.options.now() + this.options.recheckMs, task.deadline));
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
if (!this.current(task, generation))
|
|
256
|
+
return;
|
|
257
|
+
if (this.options.now() >= task.deadline) {
|
|
258
|
+
this.finish(task.sessionID, "expired");
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
this.armFire(task);
|
|
262
|
+
}
|
|
263
|
+
async checkAndSend(task, generation) {
|
|
264
|
+
if (!this.current(task, generation))
|
|
265
|
+
return;
|
|
266
|
+
if (this.options.now() >= task.deadline) {
|
|
267
|
+
this.finish(task.sessionID, "expired");
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
task.phase = "checking";
|
|
271
|
+
this.emit(task.sessionID);
|
|
272
|
+
if (await this.busy(task.sessionID)) {
|
|
273
|
+
if (this.current(task, generation))
|
|
274
|
+
this.arm(task, "recheck", Math.min(this.options.now() + this.options.recheckMs, task.deadline));
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
// A stop, expiry, or new input during the busy lookup cancels the send.
|
|
278
|
+
if (!this.current(task, generation))
|
|
279
|
+
return;
|
|
280
|
+
if (this.options.now() >= task.deadline) {
|
|
281
|
+
this.finish(task.sessionID, "expired");
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
if (await this.runningWork(task.sessionID)) {
|
|
285
|
+
if (this.current(task, generation))
|
|
286
|
+
this.arm(task, "recheck", Math.min(this.options.now() + this.options.recheckMs, task.deadline));
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
if (!this.current(task, generation))
|
|
290
|
+
return;
|
|
291
|
+
if (this.options.now() >= task.deadline) {
|
|
292
|
+
this.finish(task.sessionID, "expired");
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
try {
|
|
296
|
+
await this.options.send(task.sessionID);
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
this.options.onError(error, task.sessionID);
|
|
300
|
+
if (this.current(task, generation))
|
|
301
|
+
this.arm(task, "recheck", Math.min(this.options.now() + this.options.recheckMs, task.deadline));
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
if (!this.current(task, generation))
|
|
305
|
+
return;
|
|
306
|
+
task.sentCount += 1;
|
|
307
|
+
task.lastSentAt = this.options.now();
|
|
308
|
+
task.phase = "waiting";
|
|
309
|
+
this.emit(task.sessionID);
|
|
310
|
+
// The nudge turn may end interrupted or failed, which does not run the idle hook;
|
|
311
|
+
// poll so the loop recovers on its own.
|
|
312
|
+
this.arm(task, "recheck", Math.min(this.options.now() + this.options.recheckMs, task.deadline));
|
|
313
|
+
}
|
|
314
|
+
current(task, generation) {
|
|
315
|
+
return this.tasks.get(task.sessionID) === task && task.generation === generation;
|
|
316
|
+
}
|
|
317
|
+
async busy(sessionID) {
|
|
318
|
+
try {
|
|
319
|
+
return await this.options.isBusy(sessionID);
|
|
320
|
+
}
|
|
321
|
+
catch (error) {
|
|
322
|
+
this.options.onError(error, sessionID);
|
|
323
|
+
return true;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
/** True holds the nudge. Failures hold it rather than risking a send over unknown work. */
|
|
327
|
+
async runningWork(sessionID) {
|
|
328
|
+
if (this.options.hasRunningWork !== undefined) {
|
|
329
|
+
try {
|
|
330
|
+
return await this.options.hasRunningWork(sessionID);
|
|
331
|
+
}
|
|
332
|
+
catch (error) {
|
|
333
|
+
this.options.onError(error, sessionID);
|
|
334
|
+
return true;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
// Older host without a live check: fall back to the idle snapshot registry.
|
|
338
|
+
const known = this.backgrounds.get(sessionID) ?? [];
|
|
339
|
+
if (known.some((work) => work.sessionID === sessionID))
|
|
340
|
+
return true;
|
|
341
|
+
const owners = new Set(known.filter((work) => work.sessionID !== sessionID).map((work) => work.sessionID));
|
|
342
|
+
for (const owner of owners) {
|
|
343
|
+
if (await this.busy(owner))
|
|
344
|
+
return true;
|
|
345
|
+
if ((this.backgrounds.get(owner) ?? []).length > 0)
|
|
346
|
+
return true;
|
|
347
|
+
}
|
|
348
|
+
return false;
|
|
349
|
+
}
|
|
350
|
+
finish(sessionID, reason) {
|
|
351
|
+
const task = this.tasks.get(sessionID);
|
|
352
|
+
if (task)
|
|
353
|
+
this.clearTimer(task);
|
|
354
|
+
this.tasks.delete(sessionID);
|
|
355
|
+
this.backgrounds.delete(sessionID);
|
|
356
|
+
this.outcomes.set(sessionID, {
|
|
357
|
+
reason,
|
|
358
|
+
at: this.options.now(),
|
|
359
|
+
...(task && task.sentCount > 0 ? { sentCount: task.sentCount } : {}),
|
|
360
|
+
...(task?.lastSentAt === undefined ? {} : { lastSentAt: task.lastSentAt }),
|
|
361
|
+
});
|
|
362
|
+
this.emit(sessionID);
|
|
363
|
+
}
|
|
364
|
+
emit(sessionID) {
|
|
365
|
+
const status = this.status(sessionID);
|
|
366
|
+
this.options.onState?.(sessionID, status);
|
|
367
|
+
return status;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
/** A session is busy when its last execution start is newer than its last terminal transition. */
|
|
371
|
+
export function isSessionBusy(info) {
|
|
372
|
+
const busy = info?.time?.busy;
|
|
373
|
+
if (busy === undefined)
|
|
374
|
+
return false;
|
|
375
|
+
const idle = info?.time?.idle;
|
|
376
|
+
if (idle === undefined)
|
|
377
|
+
return true;
|
|
378
|
+
return busy > idle;
|
|
379
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
export const SECOND_MS = 1_000;
|
|
2
|
+
export const MINUTE_MS = 60_000;
|
|
3
|
+
export const HOUR_MS = 3_600_000;
|
|
4
|
+
export const DAY_MS = 86_400_000;
|
|
5
|
+
const UNIT_MS = { s: SECOND_MS, m: MINUTE_MS, h: HOUR_MS, d: DAY_MS };
|
|
6
|
+
const INVALID = (input) => `"${input}" is not a valid duration; use 90m, 2h, 1h30m, 1d, or a bare number of hours`;
|
|
7
|
+
/**
|
|
8
|
+
* Parses a duration: `<number><s|m|h|d>` with optional compound units such as `1h30m`.
|
|
9
|
+
* A bare number is treated as hours, matching the preset scale.
|
|
10
|
+
*/
|
|
11
|
+
export function parseDuration(input, bounds) {
|
|
12
|
+
return parseUnits(input, bounds, HOUR_MS, "hours");
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Parses a cooldown. Unlike a duration, a bare number is minutes (`5` = 5m) and
|
|
16
|
+
* zero is accepted when the lower bound allows it.
|
|
17
|
+
*/
|
|
18
|
+
export function parseCooldown(input, bounds) {
|
|
19
|
+
const text = input.trim().toLowerCase();
|
|
20
|
+
if (/^0+(?:\.0+)?$/.test(text)) {
|
|
21
|
+
if (bounds.minMs > 0)
|
|
22
|
+
return { ok: false, error: `Cooldown must be at least ${formatDuration(bounds.minMs)}` };
|
|
23
|
+
return { ok: true, ms: 0 };
|
|
24
|
+
}
|
|
25
|
+
return parseUnits(input, bounds, MINUTE_MS, "minutes");
|
|
26
|
+
}
|
|
27
|
+
function parseUnits(input, bounds, bareUnitMs, bareLabel) {
|
|
28
|
+
const text = input.trim().toLowerCase();
|
|
29
|
+
if (!text) {
|
|
30
|
+
return {
|
|
31
|
+
ok: false,
|
|
32
|
+
error: `Enter a duration like 90m, 2h, 1h30m, or a bare number of ${bareLabel}`,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
let ms = 0;
|
|
36
|
+
let index = 0;
|
|
37
|
+
while (index < text.length) {
|
|
38
|
+
const match = /^(\d+(?:\.\d+)?)\s*(s|m|h|d)?/.exec(text.slice(index));
|
|
39
|
+
if (!match)
|
|
40
|
+
return { ok: false, error: INVALID(input) };
|
|
41
|
+
const value = Number(match[1]);
|
|
42
|
+
if (!Number.isFinite(value) || value < 0)
|
|
43
|
+
return { ok: false, error: INVALID(input) };
|
|
44
|
+
if (value === 0 && index === 0 && text.length === match[0].length) {
|
|
45
|
+
if (bounds.minMs > 0)
|
|
46
|
+
return { ok: false, error: `Duration must be at least ${formatDuration(bounds.minMs)}` };
|
|
47
|
+
return { ok: true, ms: 0 };
|
|
48
|
+
}
|
|
49
|
+
if (value <= 0)
|
|
50
|
+
return { ok: false, error: INVALID(input) };
|
|
51
|
+
const unit = (match[2] ?? null);
|
|
52
|
+
ms += value * (unit === null ? bareUnitMs : UNIT_MS[unit]);
|
|
53
|
+
index += match[0].length;
|
|
54
|
+
}
|
|
55
|
+
const total = Math.round(ms);
|
|
56
|
+
if (total < bounds.minMs)
|
|
57
|
+
return { ok: false, error: `Duration must be at least ${formatDuration(bounds.minMs)}` };
|
|
58
|
+
if (total > bounds.maxMs)
|
|
59
|
+
return { ok: false, error: `Duration must be at most ${formatDuration(bounds.maxMs)}` };
|
|
60
|
+
return { ok: true, ms: total };
|
|
61
|
+
}
|
|
62
|
+
/** Formats a duration as a compact human string: `2d 12h`, `1h 30m`, `45m`, `30s`. */
|
|
63
|
+
export function formatDuration(ms) {
|
|
64
|
+
const total = Math.max(0, Math.round(ms));
|
|
65
|
+
if (total <= 0)
|
|
66
|
+
return "0s";
|
|
67
|
+
if (total < MINUTE_MS)
|
|
68
|
+
return `${Math.round(total / 1000)}s`;
|
|
69
|
+
const minutes = Math.round(total / MINUTE_MS);
|
|
70
|
+
const days = Math.floor(minutes / (24 * 60));
|
|
71
|
+
const hours = Math.floor((minutes % (24 * 60)) / 60);
|
|
72
|
+
const rest = minutes % 60;
|
|
73
|
+
const parts = [];
|
|
74
|
+
if (days > 0)
|
|
75
|
+
parts.push(`${days}d`);
|
|
76
|
+
if (hours > 0)
|
|
77
|
+
parts.push(`${hours}h`);
|
|
78
|
+
if (rest > 0 || parts.length === 0)
|
|
79
|
+
parts.push(`${rest}m`);
|
|
80
|
+
return parts.join(" ");
|
|
81
|
+
}
|
|
82
|
+
/** Parses a preset list, dropping entries that do not parse or fall outside the bounds. */
|
|
83
|
+
export function parsePresets(raw, bounds) {
|
|
84
|
+
if (!Array.isArray(raw))
|
|
85
|
+
return [];
|
|
86
|
+
const seen = new Set();
|
|
87
|
+
const presets = [];
|
|
88
|
+
for (const entry of raw) {
|
|
89
|
+
if (typeof entry !== "string")
|
|
90
|
+
continue;
|
|
91
|
+
const value = entry.trim();
|
|
92
|
+
if (!value || seen.has(value.toLowerCase()))
|
|
93
|
+
continue;
|
|
94
|
+
if (!parseDuration(value, bounds).ok)
|
|
95
|
+
continue;
|
|
96
|
+
seen.add(value.toLowerCase());
|
|
97
|
+
presets.push(value);
|
|
98
|
+
}
|
|
99
|
+
return presets;
|
|
100
|
+
}
|