@laraveladmin/dsh-stay-awake 0.2.13 → 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.
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
  }
package/lib/sound.js CHANGED
@@ -13,25 +13,38 @@ import { spawn as nodeSpawn } from 'node:child_process'
13
13
 
14
14
  const MAC_SUCCESS = '/System/Library/Sounds/Glass.aiff'
15
15
  const MAC_ERROR = '/System/Library/Sounds/Basso.aiff'
16
+ // A third voice for "the agent needs an answer": recognisably not "done" and
17
+ // not "failed", so a question never gets mistaken for the end of the work.
18
+ const MAC_QUESTION = '/System/Library/Sounds/Ping.aiff'
16
19
  const LINUX_SUCCESS = '/usr/share/sounds/freedesktop/stereo/complete.oga'
17
20
  const LINUX_ERROR = '/usr/share/sounds/freedesktop/stereo/dialog-error.oga'
21
+ const LINUX_QUESTION = '/usr/share/sounds/freedesktop/stereo/message.oga'
18
22
 
19
- /** @returns {{ command: string, args: string[] } | null} */
23
+ /**
24
+ * @param {object} options
25
+ * @param {string} options.platform
26
+ * @param {'success'|'error'|'question'} [options.kind]
27
+ * @param {object} [options.config]
28
+ * @returns {{ command: string, args: string[] } | null}
29
+ */
20
30
  export function buildSoundCommand({ platform, kind = 'success', config = {} }) {
21
31
  const isError = kind === 'error'
32
+ const isQuestion = kind === 'question'
22
33
  const volume = Number(config.soundVolume)
23
34
 
24
35
  if (platform === 'darwin') {
25
36
  const file = isError
26
37
  ? config.errorSound || MAC_ERROR
27
- : config.successSound || MAC_SUCCESS
38
+ : isQuestion
39
+ ? config.questionSound || MAC_QUESTION
40
+ : config.successSound || MAC_SUCCESS
28
41
  const args = [file]
29
42
  if (Number.isFinite(volume) && volume > 0 && volume !== 1) args.push('-v', String(volume))
30
43
  return { command: '/usr/bin/afplay', args }
31
44
  }
32
45
 
33
46
  if (platform === 'win32') {
34
- const sound = isError ? 'Hand' : 'Asterisk'
47
+ const sound = isError ? 'Hand' : isQuestion ? 'Question' : 'Asterisk'
35
48
  return {
36
49
  command: 'powershell.exe',
37
50
  args: ['-NoProfile', '-NonInteractive', '-Command', `[System.Media.SystemSounds]::${sound}.Play()`],
@@ -41,7 +54,9 @@ export function buildSoundCommand({ platform, kind = 'success', config = {} }) {
41
54
  if (platform === 'linux') {
42
55
  const file = isError
43
56
  ? config.errorSound || LINUX_ERROR
44
- : config.successSound || LINUX_SUCCESS
57
+ : isQuestion
58
+ ? config.questionSound || LINUX_QUESTION
59
+ : config.successSound || LINUX_SUCCESS
45
60
  const args = [file]
46
61
  if (Number.isFinite(volume) && volume > 0) args.push('--volume', String(Math.round(volume * 65536)))
47
62
  return { command: 'paplay', args }
package/lib/state.js CHANGED
@@ -27,11 +27,12 @@ export function sanitizeState(raw) {
27
27
  if (typeof raw.enabled === 'boolean') result.enabled = raw.enabled
28
28
  if (SCOPES.has(raw.scope)) result.scope = raw.scope
29
29
  if (typeof raw.sound === 'boolean') result.sound = raw.sound
30
+ if (typeof raw.autoResume === 'boolean') result.autoResume = raw.autoResume
30
31
  return result
31
32
  }
32
33
 
33
34
  /**
34
- * @returns {{ state: { enabled?: boolean, scope?: 'system'|'display' }, warning: string | null }}
35
+ * @returns {{ state: { enabled?: boolean, scope?: 'system'|'display', sound?: boolean, autoResume?: boolean }, warning: string | null }}
35
36
  */
36
37
  export function loadState(path) {
37
38
  let text
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Stay awake",
4
- "description": "Keeps this machine awake only while unattended work is still running — agent turns, background jobs and manual compaction — then releases automatically. The composer status bar shows whether it is holding; hover for active sources and hold duration."
4
+ "description": "Keeps this machine awake only while unattended work is still running — agent turns, background jobs and manual compaction — then releases automatically, retries the turn that died while offline once the network is back, and rings a distinct cue when the agent needs your answer or an approval. The composer status bar shows whether it is holding."
5
5
  }
6
6
  }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "守夜",
4
+ "description": "只在會話執行、背景工作或手動壓縮等「無人值守仍在繼續」的工作存在時保持系統不休眠,工作全部結束後自動釋放;斷網導致任務失敗時,網路恢復後自動重試那一輪;需要你回答或核准時也會響一聲提示音。輸入框下方狀態列顯示目前是否保持。"
5
+ }
6
+ }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "守夜",
4
- "description": "只在会话执行、后台任务或手动压缩等「无人值守仍在继续」的工作存在时保持系统不休眠,工作全部结束后自动释放。输入框下方状态栏显示当前是否保持,悬停可看活跃源与已持续时长。"
4
+ "description": "只在会话执行、后台任务或手动压缩等「无人值守仍在继续」的工作存在时保持系统不休眠,工作全部结束后自动释放;断网导致任务失败时,网络恢复后自动重试那一轮;需要你回答或审批时也会响一声提示音。输入框下方状态栏显示当前是否保持,悬停可看活跃源与已持续时长。"
5
5
  }
6
6
  }
package/market/index.json CHANGED
@@ -51,8 +51,8 @@
51
51
  },
52
52
  "versions": [
53
53
  {
54
- "version": "0.2.13",
55
- "publishTimestamp": 1796291435,
54
+ "version": "0.3.0",
55
+ "publishTimestamp": 1796301192,
56
56
  "source": {
57
57
  "type": "npm"
58
58
  },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@laraveladmin/dsh-stay-awake",
3
- "version": "0.2.13",
4
- "description": "DeepSeek Harness plugin that keeps the machine awake only while unattended work runs.",
3
+ "version": "0.3.0",
4
+ "description": "DeepSeek Harness plugin that keeps the machine awake only while unattended work runs, and retries the turn that died with the network once it is back.",
5
5
  "keywords": [
6
6
  "dsh-plugin",
7
7
  "deepseek-harness",