@laraveladmin/dsh-stay-awake 0.2.14 → 0.3.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.
@@ -167,6 +167,50 @@
167
167
  `unreachable`、`!enabled` 这类语义禁用保留。
168
168
  - 自动化:81 项单测/接线测试全绿(纯前端改动,无新增用例)。
169
169
 
170
+ ## 0.3.0 断网自动重试(2026-12-03)
171
+
172
+ ### 实现依据(读的是当前安装的 DSH 源码,不是猜的)
173
+
174
+ - `dsh-api-session-controller/src/index.ts`:`prompt()` 对 `content.length === 0` 构造
175
+ `source.kind = 'retry'` 的用户消息;`commands.ts` 的空内容分支要求
176
+ `continuation.stateOf(session).ending !== null`、`mode === 'queue'`、inbox 无待处理人类消息,
177
+ 否则抛 `session/agent-busy`。这就是界面「重试」按钮的后端语义。
178
+ - `dsh-api-session-controller/src/continuation.ts`:可续跑投影的三个条件(人类输入被接纳、
179
+ `assistant/attempt` 未产出成功消息、`turn/end` 错误码属于
180
+ `RATE_LIMIT/SERVER/TIMEOUT/TRANSPORT/EMPTY_RESPONSE/STREAM_CLOSED`)。本插件 `lib/resume.js`
181
+ 按同样条件从 `session/event` 本地折叠,不依赖投影服务。
182
+ - `dsh-llm-retry`:DSH 自带 5 次退避重试覆盖 `TRANSPORT/TIMEOUT`;本功能接手「5 次仍失败」之后。
183
+
184
+ ### 本轮验证过的
185
+
186
+ - 真机 TCP 探测:`probeTcp({ host: 'api.deepseek.com', port: 443 })` 返回 `true`(19ms);
187
+ 不存在的域名与本地关闭端口均返回 `false`,说明成功/失败两条路径都真的跑通。
188
+ - 自动化测试 81 → **109 项全绿**,新增 28 项覆盖:失败判定状态机(成功轮、`aborted`/`blocked`/
189
+ `interrupted`/`max-tokens`、非网络错误码、无人类输入)、retry 消息计入「已接纳」、每故障 3 次上限、
190
+ 用户消息重置预算、60 分钟窗口过期、拒绝后清除、`probeTcp` 三种结果、调度器(探测通过才重试、
191
+ 探测失败不重试、拒绝态、开关关闭不探测、关闭清队列)、提问/审批提醒(两个 waterfall 事件各响一次且
192
+ `next()` 照常继续、声音开关关闭时不响)、三种试听音效(成功/失败/提醒的 `kind` 回包,未知 kind 400)、
193
+ macOS/Windows/Linux 三平台提醒音命令映射与自定义文件覆盖。
194
+ - 配置校验:默认值(开、`TRANSPORT/TIMEOUT`、`api.deepseek.com:443`、15s、60min、3 次)与非法值
195
+ 钳制/回退均有测试;`state.json` 新增 `autoResume` 的读写测试。
196
+ - 宿主协议 3:回包 `autoResume` / `resume` 字段与 `set-auto-resume` 动作有测试;客户端字典
197
+ 简中/繁中/英文各 54 键、键集合一致、无空值、英文无 CJK 残留;全部文件 `node --check` 通过。
198
+ - 提醒音依据的是宿主 Event 合同(`user-questions/request`、`approval/request` 均为 waterfall),
199
+ 监听器旁路调用 `next()`,由接线测试证明不吞请求。
200
+ - 繁体中文通过 `ctx.locale.addLanguage({ id: 'zh-Hant', label: '繁體中文', fallback: 'zh' })` 贡献;
201
+ 该接口在 DSH 客户端 locale 服务合同里存在(`addLanguage`:回退目标必须已注册、链必须终结于英文)。
202
+
203
+ ### 未验证(需真机与真实故障)
204
+
205
+ | 项 | 原因 | 何时可验 |
206
+ |---|---|---|
207
+ | AC-21 合盖断网 → 唤醒恢复后自动续跑 | 需要真实合盖断网 + 宿主重启加载新代码;本会话无法模拟(也无法在本进程内重启宿主) | 用户重启 DSH 后合盖实测;观察对话中出现 retry 消息、弹层显示「已自动重试」 |
208
+ | AC-22 网络长期不恢复 | 同上 | 断开 Wi-Fi 后观察「等待网络恢复…」 |
209
+ | AC-24 连续 3 次失败后停止 | 需要稳定的失败环境 | 断网状态下等三次调度 |
210
+ | `sessionController.prompt` 从插件调用 | 只在真实宿主里才有该服务;已在源码层面确认服务合同与空内容分支,但未真机调用 | 用户实测 AC-21 时一并验证 |
211
+ | 提问/审批提醒音实际听感 | 需要宿主重启加载新代码并真实触发一次 `ask_user_question` 或审批;本进程内无法重启宿主 | 用户重启后提问一次即可确认 |
212
+ | 繁体中文在 DSH 语言列表中出现并可选中 | `addLanguage` 注册成功后由 DSH 的「语言」设置行渲染,本会话无浏览器控制权 | 重启后在 设置 → 语言 中查看「繁體中文」 |
213
+
170
214
  ## 未验证(明确记录,不代替验证)
171
215
 
172
216
  | ID / 项 | 原因 | 何时可验 |
package/index.js CHANGED
@@ -12,14 +12,17 @@
12
12
  * the machine awake forever.
13
13
  */
14
14
 
15
+ import { randomUUID } from 'node:crypto'
15
16
  import { readFileSync } from 'node:fs'
16
17
 
17
18
  import { createActivity } from './lib/activity.js'
19
+ import { createAutoResume } from './lib/auto-resume.js'
18
20
  import { applyState, normalizeConfig } from './lib/config.js'
19
21
  import { createController } from './lib/controller.js'
20
22
  import { createLog } from './lib/log.js'
21
23
  import { backendName, verifyCommand } from './lib/platform.js'
22
24
  import { createPower } from './lib/power.js'
25
+ import { createResumeTracker } from './lib/resume.js'
23
26
  import { createStatusHandler } from './lib/server.js'
24
27
  import { createSound } from './lib/sound.js'
25
28
  import { defaultStatePath, loadState, saveState } from './lib/state.js'
@@ -65,7 +68,12 @@ export function start(ctx, rawConfig, deps = {}) {
65
68
 
66
69
  const persist = () => {
67
70
  if (deps.statePath === false) return
68
- const result = saveState(statePath, { enabled: config.enabled, scope: config.scope, sound: config.sound })
71
+ const result = saveState(statePath, {
72
+ enabled: config.enabled,
73
+ scope: config.scope,
74
+ sound: config.sound,
75
+ autoResume: config.autoResume,
76
+ })
69
77
  if (!result.ok) log.warn(`stay-awake: could not persist settings: ${result.error}`)
70
78
  }
71
79
 
@@ -106,6 +114,62 @@ export function start(ctx, rawConfig, deps = {}) {
106
114
  }
107
115
  }
108
116
 
117
+ // ---- automatic retry of a turn that died with the network ----
118
+ const resumeTracker = createResumeTracker({
119
+ codes: config.autoResumeCodes,
120
+ maxAttempts: config.autoResumeMaxAttempts,
121
+ windowMs: config.autoResumeWindowMinutes * 60_000,
122
+ now: clockNow,
123
+ })
124
+
125
+ /**
126
+ * Press DSH's own retry door: an empty prompt becomes a `retry`-source user
127
+ * message and re-runs the failed step, exactly like the Retry button. The
128
+ * host refuses it with `session/agent-busy` when the turn is no longer
129
+ * retryable, so a stale decision fails closed.
130
+ */
131
+ async function retryTurn(sessionId) {
132
+ const sessionController = ctx.get('sessionController')
133
+ if (sessionController === undefined || sessionController === null
134
+ || typeof sessionController.prompt !== 'function') {
135
+ return { ok: false, reason: 'session-controller-unavailable' }
136
+ }
137
+ try {
138
+ await sessionController.prompt({
139
+ requestId: randomUUID(),
140
+ sessionId,
141
+ mode: 'queue',
142
+ content: [],
143
+ }, AbortSignal.timeout(20_000))
144
+ return { ok: true }
145
+ } catch (error) {
146
+ return { ok: false, reason: describe(error) }
147
+ }
148
+ }
149
+
150
+ const autoResume = createAutoResume({
151
+ tracker: resumeTracker,
152
+ config,
153
+ log,
154
+ retry: retryTurn,
155
+ now: clockNow,
156
+ })
157
+
158
+ // ---- "your turn": the agent is waiting for an answer or an approval ----
159
+ /**
160
+ * These two are waterfall events, so the listener asks for a sound and then
161
+ * hands the request back untouched. Ringing is best effort: a missing player
162
+ * or a closed sound switch must never affect the question itself.
163
+ */
164
+ const ringQuestion = () => {
165
+ try {
166
+ if (!config.enabled || !config.sound || config.soundOnQuestion !== true) return
167
+ sound.play('question')
168
+ } catch (error) {
169
+ log.warn(`stay-awake: question sound failed: ${describe(error)}`)
170
+ }
171
+ }
172
+
109
173
  const sync = () => {
110
174
  const working = activity.hasWork(config)
111
175
  if (working && !wasWorking) {
@@ -149,6 +213,11 @@ export function start(ctx, rawConfig, deps = {}) {
149
213
  sync()
150
214
  }),
151
215
  ctx.on('session/event', (session, event) => {
216
+ // Subagent sessions are not resumed automatically: their parent owns
217
+ // the failure and retrying a child out of band would fork the work.
218
+ if (session?.header?.parentSession === undefined && session?.header?.origin !== 'subagent') {
219
+ resumeTracker.observe(session.id, event)
220
+ }
152
221
  if (event?.type === 'user/message') {
153
222
  pendingUserSound = true
154
223
  return
@@ -178,6 +247,30 @@ export function start(ctx, rawConfig, deps = {}) {
178
247
  }
179
248
  }, 'stay-awake: activity sources')
180
249
 
250
+ ctx.effect(() => {
251
+ const listen = (name) => {
252
+ try {
253
+ return ctx.on(name, (_payload, next) => {
254
+ ringQuestion()
255
+ return typeof next === 'function' ? next() : undefined
256
+ })
257
+ } catch (error) {
258
+ log.warn(`stay-awake: could not subscribe to ${name}: ${describe(error)}`)
259
+ return () => {}
260
+ }
261
+ }
262
+ const disposers = [listen('user-questions/request'), listen('approval/request')]
263
+ return () => {
264
+ for (const dispose of disposers) {
265
+ try {
266
+ dispose()
267
+ } catch {
268
+ // Unloading is best effort.
269
+ }
270
+ }
271
+ }
272
+ }, 'stay-awake: question sound')
273
+
181
274
  const jobs = ctx.get('jobs')
182
275
  if (jobs !== undefined && jobs !== null && config.includeBackgroundJobs) {
183
276
  ctx.effect(() => {
@@ -237,6 +330,18 @@ export function start(ctx, rawConfig, deps = {}) {
237
330
  sync()
238
331
  }
239
332
 
333
+ // The runner schedules its own probes (default every 15 s) and only acts when
334
+ // the tracker says a turn is retryable; the tick itself is cheap.
335
+ ctx.effect(() => {
336
+ const timer = setInterval(() => {
337
+ Promise.resolve(autoResume.tick()).catch((error) => {
338
+ log.warn(`stay-awake: auto-resume tick failed: ${describe(error)}`)
339
+ })
340
+ }, 5_000)
341
+ if (typeof timer.unref === 'function') timer.unref()
342
+ return () => clearInterval(timer)
343
+ }, 'stay-awake: auto-resume')
344
+
240
345
  if (config.reconcileSeconds > 0) {
241
346
  ctx.effect(() => {
242
347
  const timer = setInterval(reconcile, config.reconcileSeconds * 1000)
@@ -255,6 +360,7 @@ export function start(ctx, rawConfig, deps = {}) {
255
360
  version: VERSION,
256
361
  backend,
257
362
  verify: verifyCommand(platform),
363
+ autoResume,
258
364
  onChange: persist,
259
365
  })
260
366
  scope.effect(() => {
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The automatic retry runner.
3
+ *
4
+ * One detached tick loop (wired in `index.js`) asks the tracker whether a turn
5
+ * is retryable, waits until the probe says the network is actually back, then
6
+ * presses DSH's own retry door once. Nothing here talks to the model: the retry
7
+ * is an empty `retry`-source user message, exactly like the Retry button.
8
+ */
9
+
10
+ import { probeTcp } from './probe.js'
11
+
12
+ /**
13
+ * @param {object} options
14
+ * @param {ReturnType<import('./resume.js').createResumeTracker>} options.tracker
15
+ * @param {Record<string, any>} options.config live normalized config (mutated by the popover)
16
+ * @param {{ warn: (message: string) => void, info?: (message: string) => void }} options.log
17
+ * @param {(options: { host: string, port: number, timeoutMs: number }) => Promise<boolean>} [options.probe]
18
+ * @param {(sessionId: string) => Promise<{ ok: true } | { ok: false, reason: string }>} options.retry
19
+ * @param {() => number} [options.now]
20
+ */
21
+ export function createAutoResume({ tracker, config, log, probe = probeTcp, retry, now = Date.now }) {
22
+ let inFlight = false
23
+ let lastProbeAt = 0
24
+ /** @type {'idle' | 'waiting' | 'retrying' | 'failed'} */
25
+ let state = 'idle'
26
+ let failure = null
27
+
28
+ function view() {
29
+ return {
30
+ enabled: config.autoResume === true,
31
+ state: config.autoResume === true ? state : 'idle',
32
+ failure: state === 'failed' ? failure : null,
33
+ retries: tracker.stats().sent,
34
+ lastSentAt: tracker.stats().lastSentAt,
35
+ probeHost: config.autoResumeProbeHost,
36
+ probePort: config.autoResumeProbePort,
37
+ }
38
+ }
39
+
40
+ function setEnabled(enabled) {
41
+ if (enabled !== true) {
42
+ state = 'idle'
43
+ failure = null
44
+ tracker.clear()
45
+ }
46
+ }
47
+
48
+ async function tick() {
49
+ if (config.autoResume !== true) {
50
+ state = 'idle'
51
+ return
52
+ }
53
+ if (tracker.pending().length === 0) {
54
+ if (state !== 'retrying') state = 'idle'
55
+ return
56
+ }
57
+ state = 'waiting'
58
+ if (inFlight) return
59
+ const at = now()
60
+ if (at - lastProbeAt < config.autoResumeProbeIntervalMs) return
61
+ lastProbeAt = at
62
+ inFlight = true
63
+ try {
64
+ const reachable = await probe({
65
+ host: config.autoResumeProbeHost,
66
+ port: config.autoResumeProbePort,
67
+ timeoutMs: 4_000,
68
+ })
69
+ if (!reachable) return
70
+ // Re-read after the probe: the user may have taken over meanwhile.
71
+ const [next] = tracker.pending()
72
+ if (next === undefined) return
73
+ tracker.recordSend(next.sessionId)
74
+ state = 'retrying'
75
+ const result = await retry(next.sessionId)
76
+ if (result?.ok === true) {
77
+ state = 'idle'
78
+ log.info?.(`stay-awake: retried session ${next.sessionId} after the network came back`)
79
+ } else {
80
+ failure = result?.reason ?? 'retry failed'
81
+ tracker.recordRejected(next.sessionId, failure)
82
+ state = 'failed'
83
+ log.warn(`stay-awake: automatic retry was rejected for ${next.sessionId}: ${failure}`)
84
+ }
85
+ } catch (error) {
86
+ failure = error instanceof Error ? error.message : String(error)
87
+ state = 'failed'
88
+ log.warn(`stay-awake: automatic retry failed: ${failure}`)
89
+ } finally {
90
+ inFlight = false
91
+ }
92
+ }
93
+
94
+ return { tick, view, setEnabled }
95
+ }
package/lib/config.js CHANGED
@@ -24,7 +24,18 @@ export const DEFAULTS = Object.freeze({
24
24
  soundOnlyUserTasks: true,
25
25
  successSound: '',
26
26
  errorSound: '',
27
+ questionSound: '',
28
+ soundOnQuestion: true,
27
29
  soundVolume: 1,
30
+ // "Retry the turn that died with the network": on by default, but it only
31
+ // fires for a lost connection, never for a user abort or an approval wait.
32
+ autoResume: true,
33
+ autoResumeCodes: Object.freeze(['TRANSPORT', 'TIMEOUT']),
34
+ autoResumeProbeHost: 'api.deepseek.com',
35
+ autoResumeProbePort: 443,
36
+ autoResumeProbeIntervalMs: 15_000,
37
+ autoResumeWindowMinutes: 60,
38
+ autoResumeMaxAttempts: 3,
28
39
  })
29
40
 
30
41
  const SCOPES = new Set(['system', 'display'])
@@ -40,6 +51,7 @@ export function applyState(config, state) {
40
51
  if (typeof state?.enabled === 'boolean') next.enabled = state.enabled
41
52
  if (SCOPES.has(state?.scope)) next.scope = state.scope
42
53
  if (typeof state?.sound === 'boolean') next.sound = state.sound
54
+ if (typeof state?.autoResume === 'boolean') next.autoResume = state.autoResume
43
55
  return next
44
56
  }
45
57
 
@@ -62,6 +74,14 @@ function asOptionalPath(value) {
62
74
  return typeof value === 'string' ? value.trim() : ''
63
75
  }
64
76
 
77
+ function asCodes(value, fallback) {
78
+ if (!Array.isArray(value)) return [...fallback]
79
+ const codes = value
80
+ .filter((entry) => typeof entry === 'string' && entry.trim() !== '')
81
+ .map((entry) => entry.trim().toUpperCase())
82
+ return codes.length > 0 ? codes : [...fallback]
83
+ }
84
+
65
85
  /**
66
86
  * @param {Record<string, unknown> | undefined} raw
67
87
  * @returns {{ config: typeof DEFAULTS, warnings: string[] }}
@@ -86,11 +106,26 @@ export function normalizeConfig(raw) {
86
106
  soundOnlyUserTasks: asBoolean(input.soundOnlyUserTasks, DEFAULTS.soundOnlyUserTasks),
87
107
  successSound: asOptionalPath(input.successSound),
88
108
  errorSound: asOptionalPath(input.errorSound),
109
+ questionSound: asOptionalPath(input.questionSound),
110
+ soundOnQuestion: asBoolean(input.soundOnQuestion, DEFAULTS.soundOnQuestion),
89
111
  soundVolume: asNumber(input.soundVolume, DEFAULTS.soundVolume, { min: 0, max: 3 }),
112
+ autoResume: asBoolean(input.autoResume, DEFAULTS.autoResume),
113
+ autoResumeCodes: asCodes(input.autoResumeCodes, DEFAULTS.autoResumeCodes),
114
+ autoResumeProbeHost: asPath(input.autoResumeProbeHost, DEFAULTS.autoResumeProbeHost),
115
+ autoResumeProbePort: asNumber(input.autoResumeProbePort, DEFAULTS.autoResumeProbePort, { min: 1, max: 65_535 }),
116
+ autoResumeProbeIntervalMs: asNumber(input.autoResumeProbeIntervalMs, DEFAULTS.autoResumeProbeIntervalMs, { min: 1_000, max: 300_000 }),
117
+ autoResumeWindowMinutes: asNumber(input.autoResumeWindowMinutes, DEFAULTS.autoResumeWindowMinutes, { min: 1, max: 24 * 60 }),
118
+ autoResumeMaxAttempts: asNumber(input.autoResumeMaxAttempts, DEFAULTS.autoResumeMaxAttempts, { min: 1, max: 10 }),
90
119
  }
91
120
 
92
121
  for (const key of Object.keys(config)) {
93
122
  if (input[key] === undefined) continue
123
+ if (Array.isArray(config[key])) {
124
+ if (!Array.isArray(input[key]) || input[key].join('\u0000') !== config[key].join('\u0000')) {
125
+ warnings.push(`config: "${key}" has an invalid value (${JSON.stringify(input[key])}); using ${JSON.stringify(config[key])}`)
126
+ }
127
+ continue
128
+ }
94
129
  if (config[key] !== input[key]) {
95
130
  warnings.push(`config: "${key}" has an invalid value (${JSON.stringify(input[key])}); using ${JSON.stringify(config[key])}`)
96
131
  }
package/lib/probe.js ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Reachability probe used before an automatic retry.
3
+ *
4
+ * A TCP handshake is the cheapest question that actually answers "can this
5
+ * machine reach the provider again": it sends no request, no headers and no
6
+ * prompt data, and it fails fast while the Wi-Fi is still coming up. DNS alone
7
+ * would pass on a cached answer, and an HTTP request would look like traffic
8
+ * the user never asked for.
9
+ */
10
+
11
+ import { createConnection } from 'node:net'
12
+
13
+ /**
14
+ * @param {object} options
15
+ * @param {string} options.host
16
+ * @param {number} options.port
17
+ * @param {number} [options.timeoutMs]
18
+ * @param {typeof createConnection} [options.createConnection] test seam
19
+ * @returns {Promise<boolean>} true when the TCP handshake completed
20
+ */
21
+ export function probeTcp({ host, port, timeoutMs = 4_000, createConnection: connect = createConnection }) {
22
+ return new Promise((resolve) => {
23
+ let settled = false
24
+ /** @type {import('node:net').Socket | undefined} */
25
+ let socket
26
+
27
+ const finish = (reachable) => {
28
+ if (settled) return
29
+ settled = true
30
+ try {
31
+ socket?.destroy()
32
+ } catch {
33
+ // A socket already torn down by the failure itself is not an error.
34
+ }
35
+ resolve(reachable)
36
+ }
37
+
38
+ try {
39
+ socket = connect({ host, port })
40
+ } catch {
41
+ resolve(false)
42
+ return
43
+ }
44
+
45
+ socket.once('connect', () => finish(true))
46
+ socket.once('timeout', () => finish(false))
47
+ socket.once('error', () => finish(false))
48
+ if (typeof socket.setTimeout === 'function') socket.setTimeout(timeoutMs)
49
+ })
50
+ }
package/lib/resume.js ADDED
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Eligibility tracking for "retry the turn that died with the network".
3
+ *
4
+ * DSH already owns the retry itself: `sessionController.prompt` with empty
5
+ * content appends a `retry`-source user message and re-runs the failed step,
6
+ * gated by the `conversationContinuation` projection — a turn is retryable only
7
+ * when it started from admitted input, contained a failed model attempt, and
8
+ * ended with one of the recoverable failure codes.
9
+ *
10
+ * This module mirrors those three facts from the session event feed so the
11
+ * plugin can tell *when* the door is open, without depending on the projection
12
+ * service. It tracks, per ordinary session:
13
+ *
14
+ * - `admitted`: a real user message or an earlier retry (empty content) was
15
+ * admitted in this turn;
16
+ * - `failedAttempt`: an `assistant/attempt` never produced a committed
17
+ * assistant message (a successful message or the next step clears it);
18
+ * - `ending`: the `turn/end` sequence that closed a recoverable failure.
19
+ */
20
+
21
+ /** Failure codes that a lost connection produces; the popover can widen this. */
22
+ export const NETWORK_CODES = Object.freeze(['TRANSPORT', 'TIMEOUT'])
23
+
24
+ const EMPTY = Object.freeze({
25
+ admitted: false,
26
+ failedAttempt: false,
27
+ ending: null,
28
+ attempts: 0,
29
+ eligibleAt: 0,
30
+ })
31
+
32
+ /**
33
+ * @param {object} options
34
+ * @param {readonly string[]} [options.codes] failure codes that count as network loss
35
+ * @param {number} [options.maxAttempts] automatic retries allowed per episode
36
+ * @param {number} [options.windowMs] how long a failure stays eligible
37
+ * @param {() => number} [options.now]
38
+ */
39
+ export function createResumeTracker({ codes = NETWORK_CODES, maxAttempts = 3, windowMs = 60 * 60_000, now = Date.now } = {}) {
40
+ const wanted = new Set(codes.map((code) => String(code).toUpperCase()))
41
+ /** @type {Map<string, typeof EMPTY & { admitted: boolean, failedAttempt: boolean, ending: number | null }>} */
42
+ const sessions = new Map()
43
+ let sent = 0
44
+ let lastSentAt = 0
45
+ let lastResult = null
46
+
47
+ function stateOf(sessionId) {
48
+ let state = sessions.get(sessionId)
49
+ if (state === undefined) {
50
+ state = { ...EMPTY }
51
+ sessions.set(sessionId, state)
52
+ }
53
+ return state
54
+ }
55
+
56
+ /**
57
+ * Fold one `session/event` into the eligibility state. Unknown event types
58
+ * are ignored on purpose: this is a projection, not a log.
59
+ * @param {string} sessionId
60
+ * @param {any} event
61
+ */
62
+ function observe(sessionId, event) {
63
+ if (typeof sessionId !== 'string' || sessionId === '') return
64
+ if (event === null || typeof event !== 'object') return
65
+ const state = stateOf(sessionId)
66
+ switch (event.type) {
67
+ case 'turn/start':
68
+ state.admitted = false
69
+ state.failedAttempt = false
70
+ state.ending = null
71
+ return
72
+ case 'step/start':
73
+ case 'assistant/message':
74
+ if (state.failedAttempt) state.failedAttempt = false
75
+ return
76
+ case 'user/message': {
77
+ const data = event.data ?? {}
78
+ const source = data.source ?? {}
79
+ const content = Array.isArray(data.content) ? data.content : []
80
+ const human = source.kind === 'user' && content.length > 0
81
+ const retry = source.kind === 'retry' && content.length === 0
82
+ if (event.surfaceOp !== 'append' || (!human && !retry)) return
83
+ // A real message starts a new episode; a retry message is our own.
84
+ if (human) {
85
+ state.attempts = 0
86
+ state.ending = null
87
+ }
88
+ state.admitted = true
89
+ return
90
+ }
91
+ case 'assistant/attempt':
92
+ state.failedAttempt = true
93
+ return
94
+ case 'turn/end': {
95
+ const reason = event.data?.reason ?? {}
96
+ const code = reason.error?.code
97
+ if (reason.kind === 'error' && typeof code === 'string' && wanted.has(code.toUpperCase())
98
+ && state.admitted && state.failedAttempt) {
99
+ state.ending = typeof event.seq === 'number' ? event.seq : 0
100
+ state.eligibleAt = now()
101
+ } else {
102
+ state.ending = null
103
+ if (reason.kind === 'completed') state.attempts = 0
104
+ }
105
+ state.failedAttempt = false
106
+ return
107
+ }
108
+ default:
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Sessions whose last turn can be retried right now: a recoverable failure,
114
+ * within the window, with attempts left. Oldest first.
115
+ */
116
+ function pending(at = now()) {
117
+ const list = []
118
+ for (const [sessionId, state] of sessions) {
119
+ if (state.ending === null) continue
120
+ if (state.attempts >= maxAttempts) continue
121
+ if (at - state.eligibleAt > windowMs) continue
122
+ list.push({ sessionId, eligibleAt: state.eligibleAt, attempts: state.attempts })
123
+ }
124
+ return list.sort((a, b) => a.eligibleAt - b.eligibleAt)
125
+ }
126
+
127
+ /** Count one automatic retry and close the current window so it cannot repeat. */
128
+ function recordSend(sessionId, at = now()) {
129
+ const state = stateOf(sessionId)
130
+ state.attempts += 1
131
+ state.ending = null
132
+ state.eligibleAt = 0
133
+ sent += 1
134
+ lastSentAt = at
135
+ lastResult = 'sent'
136
+ }
137
+
138
+ /** The attempt was rejected (session busy, user took over): stop offering it. */
139
+ function recordRejected(sessionId, reason) {
140
+ const state = stateOf(sessionId)
141
+ state.ending = null
142
+ state.eligibleAt = 0
143
+ lastResult = 'failed'
144
+ lastFailure = reason ?? null
145
+ }
146
+
147
+ function forget(sessionId) {
148
+ sessions.delete(sessionId)
149
+ }
150
+
151
+ function clear() {
152
+ sessions.clear()
153
+ }
154
+
155
+ let lastFailure = null
156
+
157
+ return {
158
+ observe,
159
+ pending,
160
+ recordSend,
161
+ recordRejected,
162
+ forget,
163
+ clear,
164
+ stateOf,
165
+ stats: () => ({ sent, lastSentAt, lastResult, lastFailure }),
166
+ get maxAttempts() {
167
+ return maxAttempts
168
+ },
169
+ get windowMs() {
170
+ return windowMs
171
+ },
172
+ }
173
+ }
package/lib/server.js CHANGED
@@ -2,13 +2,14 @@
2
2
 
3
3
  const MAX_BODY_BYTES = 4096
4
4
  const SCOPES = new Set(['system', 'display'])
5
+ const SOUND_KINDS = new Set(['success', 'error', 'question'])
5
6
 
6
- export function createStatusHandler({ controller, activity, sound, config, platform, version, backend, verify, onChange }) {
7
+ export function createStatusHandler({ controller, activity, sound, config, platform, version, backend, verify, autoResume, onChange }) {
7
8
  return async function handle(request) {
8
9
  try {
9
10
  if (request.method === 'GET') {
10
11
  if (typeof controller.refresh === 'function') controller.refresh()
11
- return json(payload({ controller, activity, config, platform, version, backend, verify }))
12
+ return json(payload({ controller, activity, config, platform, version, backend, verify, autoResume }))
12
13
  }
13
14
  if (request.method !== 'POST') {
14
15
  return new Response(null, { status: 405, headers: { allow: 'GET, POST' } })
@@ -27,7 +28,7 @@ export function createStatusHandler({ controller, activity, sound, config, platf
27
28
  }
28
29
  if (body === null || typeof body !== 'object') return json({ error: 'invalid-body' }, 400)
29
30
 
30
- const base = () => payload({ controller, activity, config, platform, version, backend, verify })
31
+ const base = () => payload({ controller, activity, config, platform, version, backend, verify, autoResume })
31
32
 
32
33
  switch (body.action) {
33
34
  case 'hold':
@@ -51,15 +52,24 @@ export function createStatusHandler({ controller, activity, sound, config, platf
51
52
  config.sound = body.enabled
52
53
  notify(onChange)
53
54
  break
54
- case 'test-sound':
55
+ case 'set-auto-resume':
56
+ if (typeof body.enabled !== 'boolean') return json({ error: 'invalid-body' }, 400)
57
+ config.autoResume = body.enabled
58
+ autoResume?.setEnabled?.(body.enabled)
59
+ notify(onChange)
60
+ break
61
+ case 'test-sound': {
55
62
  // The click is a request to hear the sound, so bypass the throttle and
56
63
  // tell the caller whether a player was actually spawned: the button
57
64
  // used to report the same "saved" note as a switch, which read as a
58
- // failed test.
65
+ // failed test. `kind` lets the panel audition each of the three cues.
66
+ const kind = body.kind === undefined ? 'success' : body.kind
67
+ if (!SOUND_KINDS.has(kind)) return json({ error: 'invalid-body' }, 400)
59
68
  return json({
60
69
  ...base(),
61
- testSound: sound?.play('success', { force: true }) === true ? 'played' : 'unavailable',
70
+ testSound: sound?.play(kind, { force: true }) === true ? 'played' : 'unavailable',
62
71
  })
72
+ }
63
73
  default:
64
74
  return json({ error: 'invalid-action' }, 400)
65
75
  }
@@ -80,10 +90,12 @@ function notify(onChange) {
80
90
  }
81
91
  }
82
92
 
83
- function payload({ controller, activity, config, platform, version, backend, verify }) {
93
+ function payload({ controller, activity, config, platform, version, backend, verify, autoResume }) {
84
94
  return {
85
95
  ok: true,
86
- protocol: 2,
96
+ // 3 adds the auto-resume switch and status; a client that sees 2 knows the
97
+ // host half is an older build and says so instead of sending dead actions.
98
+ protocol: 3,
87
99
  version,
88
100
  platform,
89
101
  backend,
@@ -93,6 +105,8 @@ function payload({ controller, activity, config, platform, version, backend, ver
93
105
  maxHoldHours: config.maxHoldHours,
94
106
  sound: config.sound,
95
107
  soundMinSeconds: config.soundMinSeconds,
108
+ autoResume: config.autoResume === true,
109
+ resume: autoResume?.view?.() ?? null,
96
110
  counts: activity.counts(config),
97
111
  ...controller.status(),
98
112
  }