pi-web-ui 0.114.3 → 0.116.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.
Files changed (224) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/bin/pi-web-ui.mjs +90 -8
  3. package/dist/gh-comment-781.md +5 -0
  4. package/dist/server/agent-service-daemon.js +522 -32
  5. package/dist/server/agent-service.js +954 -402
  6. package/dist/server/canvas/canvas-dispatch.js +13 -1
  7. package/dist/server/client-state.js +42 -2
  8. package/dist/server/communicate-tool.js +2 -0
  9. package/dist/server/conversation-communication.js +14 -0
  10. package/dist/server/conversation-identity.js +27 -0
  11. package/dist/server/device-center/approval-summary.js +31 -0
  12. package/dist/server/device-center/bot-catalog.js +21 -7
  13. package/dist/server/device-center/bot-execution.js +100 -9
  14. package/dist/server/device-center/bot-presets.js +46 -0
  15. package/dist/server/device-center/collab-service.js +362 -13
  16. package/dist/server/device-center/collab-tool.js +824 -13
  17. package/dist/server/device-center/connector.js +359 -23
  18. package/dist/server/device-center/desktop-page.js +22 -16
  19. package/dist/server/device-center/device-integration.js +595 -0
  20. package/dist/server/device-center/execution-guides.js +32 -0
  21. package/dist/server/device-center/execution-instructions.js +20 -0
  22. package/dist/server/device-center/execution-settings.js +213 -0
  23. package/dist/server/device-center/execution-system-prompt.js +38 -0
  24. package/dist/server/device-center/execution-workspace.js +20 -0
  25. package/dist/server/device-center/executor.js +392 -40
  26. package/dist/server/device-center/file-sync-paths.js +171 -0
  27. package/dist/server/device-center/file-sync.js +186 -96
  28. package/dist/server/device-center/group-context-delta.js +37 -0
  29. package/dist/server/device-center/group-context-message.js +210 -0
  30. package/dist/server/device-center/group-context.js +179 -0
  31. package/dist/server/device-center/group-events.js +136 -0
  32. package/dist/server/device-center/group-plan-guard.js +138 -0
  33. package/dist/server/device-center/hub-conversations.js +233 -0
  34. package/dist/server/device-center/hub-deliveries.js +277 -0
  35. package/dist/server/device-center/hub-integration.js +451 -0
  36. package/dist/server/device-center/hub-locks.js +320 -0
  37. package/dist/server/device-center/hub-page.js +13 -33
  38. package/dist/server/device-center/hub-webhooks.js +165 -0
  39. package/dist/server/device-center/hub.js +2379 -107
  40. package/dist/server/device-center/human-interaction.js +232 -0
  41. package/dist/server/device-center/integration-errors.js +25 -0
  42. package/dist/server/device-center/local-hub.js +20 -1
  43. package/dist/server/device-center/local-page.js +17 -0
  44. package/dist/server/device-center/local.js +430 -41
  45. package/dist/server/device-center/main.js +11 -1
  46. package/dist/server/device-center/partition-log.js +293 -0
  47. package/dist/server/device-center/path-portal.js +11 -3
  48. package/dist/server/device-center/relay.js +364 -35
  49. package/dist/server/device-center/report-metadata.js +66 -0
  50. package/dist/server/device-center/report-upload.js +63 -0
  51. package/dist/server/device-center/runtime.js +598 -41
  52. package/dist/server/device-center/smoke-preview.js +3 -0
  53. package/dist/server/device-center/store.js +203 -41
  54. package/dist/server/device-center/task-context-budget.js +161 -0
  55. package/dist/server/device-center/task-journal.js +385 -0
  56. package/dist/server/device-center/task-plan.js +33 -0
  57. package/dist/server/device-center/task-progress.js +141 -0
  58. package/dist/server/device-center/task-recovery.js +452 -0
  59. package/dist/server/device-center/task-report-outbox.js +216 -0
  60. package/dist/server/device-center/task-report.js +384 -0
  61. package/dist/server/device-center/task-scheduler.js +445 -0
  62. package/dist/server/device-center/task-state.js +333 -0
  63. package/dist/server/device-center/transfer-stream.js +1006 -0
  64. package/dist/server/device-center/transfers.js +841 -8
  65. package/dist/server/dispatch-domain-handlers.js +35 -6
  66. package/dist/server/dsh/dsh-agent-service.js +6 -0
  67. package/dist/server/durable/durable-capabilities.js +11 -0
  68. package/dist/server/engine-probe.js +112 -1
  69. package/dist/server/global-loader.js +119 -19
  70. package/dist/server/goal-service.js +10 -5
  71. package/dist/server/index.js +222 -29
  72. package/dist/server/managed.js +2 -0
  73. package/dist/server/markers/builtins/services.js +123 -0
  74. package/dist/server/markers/builtins/todo.js +189 -0
  75. package/dist/server/markers-list-tool.js +34 -0
  76. package/dist/server/message-deletion.js +40 -0
  77. package/dist/server/message-window.js +9 -0
  78. package/dist/server/model-admin.js +48 -6
  79. package/dist/server/model-enrich.js +10 -1
  80. package/dist/server/orchestrator.js +109 -0
  81. package/dist/server/patch-executable-lookup.js +396 -0
  82. package/dist/server/payload-limits.js +2 -0
  83. package/dist/server/plugin-llm.js +100 -9
  84. package/dist/server/plugins.js +65 -7
  85. package/dist/server/preset-fields.js +24 -0
  86. package/dist/server/preset-share.js +2 -0
  87. package/dist/server/prompt-base-store.js +85 -0
  88. package/dist/server/prompt-composer.js +44 -2
  89. package/dist/server/protocol-version.js +1 -1
  90. package/dist/server/protocol.js +2 -2
  91. package/dist/server/reasoning-registry.js +207 -0
  92. package/dist/server/remote-ssh-service.js +22 -9
  93. package/dist/server/resolve-global-sdk.js +2 -0
  94. package/dist/server/session-search.js +1 -1
  95. package/dist/server/settings-service.js +90 -39
  96. package/dist/server/skill-content-filler.js +29 -8
  97. package/dist/server/skill-tool.js +12 -3
  98. package/dist/server/startup-banner.js +35 -0
  99. package/dist/server/subagent-helpers.js +4 -1
  100. package/dist/server/subagents.js +52 -37
  101. package/dist/server/system-prompt-soul.js +41 -0
  102. package/dist/server/tool-host-factories.js +1 -0
  103. package/dist/server/tool-manager.js +17 -9
  104. package/dist/server/unauthorized-page.js +319 -0
  105. package/dist/server/univer-service.js +448 -0
  106. package/dist/server/universal/drivers/dsh-driver.js +379 -0
  107. package/dist/server/universal/universal-session.js +5 -0
  108. package/dist/server/webui-context.js +25 -5
  109. package/dist/test-artifact.md +9 -0
  110. package/dist/test-preview-modal.md +11 -0
  111. package/dist/test-report.html +20 -0
  112. package/docs/README.md +94 -0
  113. package/docs/architecture-plugins.md +946 -0
  114. package/docs/device-center.md +106 -12
  115. package/docs/dsh-engine.md +10 -10
  116. package/extensions/webui.ts +43 -1
  117. package/package.json +2 -1
  118. package/themes/aetheris.css +5 -0
  119. package/themes/ayu-light.css +6 -0
  120. package/themes/bases/flow-base.css +68 -68
  121. package/themes/catppuccin-latte.css +6 -0
  122. package/themes/catppuccin.css +6 -0
  123. package/themes/claude-code-dark.css +5 -0
  124. package/themes/codex.css +6 -0
  125. package/themes/cyberpunk.css +6 -0
  126. package/themes/dark-teal.css +6 -1
  127. package/themes/dazzle.css +6 -0
  128. package/themes/everforest-light.css +6 -0
  129. package/themes/flow-light.css +8 -1
  130. package/themes/flow.css +6 -1
  131. package/themes/geist.css +6 -0
  132. package/themes/gruvbox-light.css +6 -0
  133. package/themes/kanagawa-lotus.css +6 -0
  134. package/themes/md-preview.css +6 -0
  135. package/themes/mist.css +6 -0
  136. package/themes/nord.css +6 -0
  137. package/themes/one-dark.css +6 -0
  138. package/themes/paper.css +6 -0
  139. package/themes/rose-pine-dawn.css +6 -0
  140. package/themes/sakura.css +6 -0
  141. package/themes/solarized-light.css +6 -0
  142. package/themes/tokyo-night.css +6 -0
  143. package/themes/translucent.css +6 -0
  144. package/themes/transparent.css +6 -0
  145. package/themes/vs-code-dark.css +5 -0
  146. package/themes/wallpaper-flow.css +5 -1
  147. package/themes/wallpaper-obsidian.css +6 -0
  148. package/themes/white.css +6 -0
  149. package/themes/zhujian-dark.css +6 -1
  150. package/themes/zhujian.css +6 -1
  151. package/themes/zhupi-dark.css +6 -1
  152. package/themes/zhupi.css +6 -1
  153. package/web/dist/.build-assets.json +1 -1
  154. package/web/dist/assets/BgTasksModal-BDoOpj-F.js +1 -0
  155. package/web/dist/assets/BgTasksModal-C0i3O1FT.js +1 -0
  156. package/web/dist/assets/{CanvasStudio-BSg9ghPV.js → CanvasStudio-B8thymBN.js} +3 -3
  157. package/web/dist/assets/{CanvasStudio-DxW7C3Sz.js → CanvasStudio-zSxyIx1R.js} +3 -3
  158. package/web/dist/assets/DeviceCenter-DfAHKcid.js +3 -0
  159. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +3 -0
  160. package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +1 -0
  161. package/web/dist/assets/DeviceGroups-CI14_SRb.js +1 -0
  162. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +1 -0
  163. package/web/dist/assets/Dropdown-C4LIhshN.js +1 -0
  164. package/web/dist/assets/FilePreview-BgGongmv.js +2 -0
  165. package/web/dist/assets/FilePreview-D4NrhF-U.js +2 -0
  166. package/web/dist/assets/GlobalSearchModal-BWgU8yPd.js +1 -0
  167. package/web/dist/assets/GlobalSearchModal-F7fNimKk.js +1 -0
  168. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +17 -0
  169. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +17 -0
  170. package/web/dist/assets/HintTip-c6d0TJoh.js +1 -0
  171. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +2 -0
  172. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +2 -0
  173. package/web/dist/assets/PiSetupModal-BmMrrgB9.js +1 -0
  174. package/web/dist/assets/ProviderOAuthControls-BGSBIKD7.js +1 -0
  175. package/web/dist/assets/SCMPanel-B8_EDxNr.js +2 -0
  176. package/web/dist/assets/SCMPanel-BU58qk3T.js +2 -0
  177. package/web/dist/assets/SettingsModal-CMUybq3J.js +32 -0
  178. package/web/dist/assets/SettingsModal-OBmGTh-5.js +32 -0
  179. package/web/dist/assets/TerminalPanel-0CYvD72B.js +3 -0
  180. package/web/dist/assets/TerminalPanel-DDavKvFr.js +3 -0
  181. package/web/dist/assets/TuiOverlayModal-BsA-QTvN.js +1 -0
  182. package/web/dist/assets/TuiOverlayModal-DzoVQBuG.js +1 -0
  183. package/web/dist/assets/app-globals-CZxzGvIo.js +123 -0
  184. package/web/dist/assets/canvas-client-CUnXlQYX.js +1 -0
  185. package/web/dist/assets/{desktop-7EvUHhKQ.js → desktop-aAKpvKJV.js} +1 -1
  186. package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
  187. package/web/dist/assets/index-C6DwztqE.css +1 -0
  188. package/web/dist/assets/index-CuN802Sj.js +93 -0
  189. package/web/dist/assets/index-EH5Fw9fa.js +93 -0
  190. package/web/dist/assets/plugin-host-BRWib9DF.js +1 -0
  191. package/web/dist/assets/remote-ssh-client-CfYSMEZg.js +1 -0
  192. package/web/dist/assets/theme-D2l_mLNo.js +1 -0
  193. package/web/dist/index.html +10 -9
  194. package/web/dist/sw.js +1 -1
  195. package/web/dist/assets/BgTasksModal-BvnUHjFe.js +0 -1
  196. package/web/dist/assets/BgTasksModal-DSC8ncW3.js +0 -1
  197. package/web/dist/assets/DeviceCenter-Bmgr-Bwm.js +0 -3
  198. package/web/dist/assets/DeviceCenter-Cl9MBXaH.js +0 -3
  199. package/web/dist/assets/DeviceGroups-aeLD2msl.js +0 -1
  200. package/web/dist/assets/Dropdown-D1Jl35dw.js +0 -1
  201. package/web/dist/assets/FilePreview-6CqoDF_P.js +0 -2
  202. package/web/dist/assets/FilePreview-CJa27G_Q.js +0 -2
  203. package/web/dist/assets/GlobalSearchModal-CJX35rZL.js +0 -1
  204. package/web/dist/assets/GlobalSearchModal-CMW0xz0P.js +0 -1
  205. package/web/dist/assets/GroupConversation-Cq4daBFb.js +0 -1
  206. package/web/dist/assets/GroupConversation-DoELa83U.js +0 -1
  207. package/web/dist/assets/ModelConfigModal-Bp7tfKYh.js +0 -2
  208. package/web/dist/assets/PiSetupModal-DD8srwBJ.js +0 -1
  209. package/web/dist/assets/ProviderOAuthControls-C6tfXb88.js +0 -1
  210. package/web/dist/assets/SCMPanel-CghgsyBN.js +0 -2
  211. package/web/dist/assets/SCMPanel-D8-8aqwC.js +0 -2
  212. package/web/dist/assets/SettingsModal-BbBe2rYo.js +0 -20
  213. package/web/dist/assets/SettingsModal-qETiVPKj.js +0 -20
  214. package/web/dist/assets/TerminalPanel-Da-Xs4Wk.js +0 -3
  215. package/web/dist/assets/TerminalPanel-DnS4tFQO.js +0 -3
  216. package/web/dist/assets/TuiOverlayModal-CGyGkKYl.js +0 -1
  217. package/web/dist/assets/TuiOverlayModal-CpBKjG6x.js +0 -1
  218. package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
  219. package/web/dist/assets/fi-NyN-ZrgD.js +0 -325
  220. package/web/dist/assets/index-DK3F5ZJo.js +0 -85
  221. package/web/dist/assets/index-DQMii2he.js +0 -85
  222. package/web/dist/assets/index-vwBnwzkr.css +0 -1
  223. package/web/dist/assets/plugin-host-BCnX3P8U.js +0 -1
  224. package/web/dist/assets/theme-D2DMH6tH.js +0 -1
@@ -0,0 +1,445 @@
1
+ import { executionRoot, executionRootsOverlap } from "./execution-workspace.js";
2
+ import { DeviceTaskError } from "./task-error.js";
3
+ import { DEFAULT_EXECUTION_SETTINGS, validateExecutionSettings, } from "./execution-settings.js";
4
+ export class DeviceTaskScheduler {
5
+ static MAX_ROOM_HISTORY = 256;
6
+ settings;
7
+ starvationThresholdMs;
8
+ maxSkipsBeforeStarvation;
9
+ onChange;
10
+ queue = [];
11
+ active = new Set();
12
+ roomDispatchHistory = new Map();
13
+ constructor(options) {
14
+ const validated = validateExecutionSettings(options?.initialSettings);
15
+ this.settings = validated.valid ? { ...validated.value } : { ...DEFAULT_EXECUTION_SETTINGS };
16
+ this.starvationThresholdMs = options?.starvationThresholdMs ?? this.settings.starvationThresholdMs ?? 8000;
17
+ this.maxSkipsBeforeStarvation = options?.maxSkipsBeforeStarvation ?? this.settings.maxSkipsBeforeStarvation ?? 3;
18
+ this.onChange = options?.onChange;
19
+ this.restoreState(options?.persistedState);
20
+ }
21
+ /** Fairness history is in-memory scheduling state; persist it so a restart cannot reset room fairness. */
22
+ snapshotState() {
23
+ return {
24
+ version: 1,
25
+ rooms: [...this.roomDispatchHistory].map(([roomId, history]) => ({
26
+ roomId,
27
+ lastDispatchedAt: history.lastDispatchedAt,
28
+ count: history.count,
29
+ })),
30
+ };
31
+ }
32
+ restoreState(value) {
33
+ if (!value || typeof value !== "object" || Array.isArray(value))
34
+ return;
35
+ const state = value;
36
+ if (state.version !== 1 || !Array.isArray(state.rooms))
37
+ return;
38
+ for (const entry of state.rooms.slice(0, DeviceTaskScheduler.MAX_ROOM_HISTORY)) {
39
+ if (!entry || typeof entry !== "object")
40
+ continue;
41
+ const { roomId, lastDispatchedAt, count } = entry;
42
+ if (typeof roomId !== "string" || !roomId || roomId.length > 128)
43
+ continue;
44
+ if (!Number.isSafeInteger(lastDispatchedAt) || lastDispatchedAt < 0)
45
+ continue;
46
+ if (!Number.isSafeInteger(count) || count < 0)
47
+ continue;
48
+ this.roomDispatchHistory.set(roomId, { lastDispatchedAt, count });
49
+ }
50
+ }
51
+ changed() {
52
+ try {
53
+ this.onChange?.();
54
+ }
55
+ catch {
56
+ /* persistence scheduling must never break dispatch */
57
+ }
58
+ }
59
+ getSettings() {
60
+ return { ...this.settings };
61
+ }
62
+ updateSettings(next) {
63
+ const validation = validateExecutionSettings(next);
64
+ if (!validation.valid) {
65
+ throw new Error(validation.error);
66
+ }
67
+ this.settings = { ...validation.value };
68
+ this.starvationThresholdMs = this.settings.starvationThresholdMs ?? 8000;
69
+ this.maxSkipsBeforeStarvation = this.settings.maxSkipsBeforeStarvation ?? 3;
70
+ this.drain();
71
+ return { ...this.settings };
72
+ }
73
+ getActiveCount() {
74
+ return this.active.size;
75
+ }
76
+ getWaitingCount() {
77
+ return this.queue.length;
78
+ }
79
+ getBlockedCount() {
80
+ return [...this.active].filter((a) => !!a.blocked).length;
81
+ }
82
+ isWorkspaceBlocked(botId, root) {
83
+ const targetRoot = executionRoot(root);
84
+ for (const owner of this.active) {
85
+ if (owner.blocked && this.checkConflict({ botId, root: targetRoot }, owner)) {
86
+ return true;
87
+ }
88
+ }
89
+ return false;
90
+ }
91
+ checkConflict(a, b) {
92
+ return a.botId === b.botId || executionRootsOverlap(a.root, b.root);
93
+ }
94
+ recordRoomDispatch(roomId) {
95
+ let history = this.roomDispatchHistory.get(roomId);
96
+ if (!history) {
97
+ // Bounded LRU eviction
98
+ if (this.roomDispatchHistory.size >= DeviceTaskScheduler.MAX_ROOM_HISTORY) {
99
+ let oldestKey;
100
+ let oldestTime = Infinity;
101
+ for (const [k, v] of this.roomDispatchHistory) {
102
+ if (v.lastDispatchedAt < oldestTime) {
103
+ oldestTime = v.lastDispatchedAt;
104
+ oldestKey = k;
105
+ }
106
+ }
107
+ if (oldestKey)
108
+ this.roomDispatchHistory.delete(oldestKey);
109
+ }
110
+ history = { lastDispatchedAt: 0, count: 0 };
111
+ }
112
+ history.lastDispatchedAt = Date.now();
113
+ history.count++;
114
+ this.roomDispatchHistory.set(roomId, history);
115
+ this.changed();
116
+ }
117
+ clearRoomHistory(roomId) {
118
+ if (this.roomDispatchHistory.delete(roomId))
119
+ this.changed();
120
+ }
121
+ enqueue(task, callbacks, signal) {
122
+ const canonicalRoot = executionRoot(task.root);
123
+ const candidate = { botId: task.botId, root: canonicalRoot };
124
+ // Check if active items have unconfirmed stop blocks
125
+ const blockedBlocker = [...this.active].find((owner) => owner.blocked && this.checkConflict(candidate, owner));
126
+ if (blockedBlocker) {
127
+ throw new DeviceTaskError("Task stop unconfirmed; workspace blocked until service restart");
128
+ }
129
+ // If queue is empty, slots available, and no conflict with active tasks,
130
+ // task can start immediately even if maxWaitingTasks is 0.
131
+ const canStartImmediately = this.queue.length === 0 &&
132
+ this.active.size < this.settings.maxActiveTasks &&
133
+ ![...this.active].some((owner) => this.checkConflict(candidate, owner));
134
+ if (canStartImmediately) {
135
+ try {
136
+ callbacks.start();
137
+ this.recordRoomDispatch(task.roomId);
138
+ }
139
+ catch (error) {
140
+ callbacks.reject(error);
141
+ }
142
+ return null;
143
+ }
144
+ // Needs to queue, check queue capacity
145
+ if (this.queue.length >= this.settings.maxWaitingTasks) {
146
+ throw new DeviceTaskError("Local task queue full");
147
+ }
148
+ const item = {
149
+ taskId: task.id,
150
+ attemptId: task.attemptId,
151
+ roomId: task.roomId,
152
+ botId: task.botId,
153
+ botRevision: task.botRevision,
154
+ root: canonicalRoot,
155
+ queuedAt: Date.now(),
156
+ skipCount: 0,
157
+ signal,
158
+ start: callbacks.start,
159
+ reject: callbacks.reject,
160
+ cancel: callbacks.cancel,
161
+ };
162
+ this.queue.push(item);
163
+ this.drain();
164
+ return item;
165
+ }
166
+ removeWaiting(item) {
167
+ const index = this.queue.indexOf(item);
168
+ if (index >= 0) {
169
+ this.queue.splice(index, 1);
170
+ this.drain();
171
+ return true;
172
+ }
173
+ return false;
174
+ }
175
+ cancelTask(taskId, attemptId) {
176
+ // 1. Check waiting queue
177
+ const waitingIndex = this.queue.findIndex((q) => q.taskId === taskId && (!attemptId || q.attemptId === attemptId));
178
+ if (waitingIndex >= 0) {
179
+ const [item] = this.queue.splice(waitingIndex, 1);
180
+ item.cancel();
181
+ this.drain();
182
+ return true;
183
+ }
184
+ // 2. Check active running tasks
185
+ const activeItem = [...this.active].find((a) => a.taskId === taskId && (!attemptId || a.attemptId === attemptId));
186
+ if (activeItem && activeItem.controller && !activeItem.controller.signal.aborted) {
187
+ activeItem.controller.abort(new DeviceTaskError("Task cancelled by user"));
188
+ return true;
189
+ }
190
+ return false;
191
+ }
192
+ registerActive(task, controller) {
193
+ const canonicalRoot = executionRoot(task.root);
194
+ // Guard against duplicate task ID
195
+ const duplicate = [...this.active].find((item) => item.taskId === task.id);
196
+ if (duplicate) {
197
+ throw new DeviceTaskError("Task is already running");
198
+ }
199
+ const candidate = { botId: task.botId, root: canonicalRoot };
200
+ // Guard against capacity breach
201
+ if (this.active.size >= this.settings.maxActiveTasks) {
202
+ throw new DeviceTaskError("Active task capacity exceeded");
203
+ }
204
+ // Guard against active conflict
205
+ const conflict = [...this.active].find((item) => this.checkConflict(candidate, item));
206
+ if (conflict) {
207
+ throw new DeviceTaskError(conflict.blocked
208
+ ? "Task stop unconfirmed; workspace blocked until service restart"
209
+ : "Active task workspace or bot conflict");
210
+ }
211
+ const item = {
212
+ taskId: task.id,
213
+ attemptId: task.attemptId,
214
+ roomId: task.roomId,
215
+ botId: task.botId,
216
+ botRevision: task.botRevision,
217
+ root: canonicalRoot,
218
+ startedAt: Date.now(),
219
+ controller,
220
+ };
221
+ this.active.add(item);
222
+ return item;
223
+ }
224
+ markBlocked(taskId, attemptId, error) {
225
+ for (const item of this.active) {
226
+ if (item.taskId === taskId && item.attemptId === attemptId) {
227
+ item.blocked = error;
228
+ }
229
+ }
230
+ }
231
+ releaseActive(item) {
232
+ this.active.delete(item);
233
+ this.drain();
234
+ }
235
+ drain() {
236
+ if (this.queue.length === 0)
237
+ return;
238
+ const now = Date.now();
239
+ // Reject tasks blocked by unconfirmed stops
240
+ const toReject = [];
241
+ for (let i = this.queue.length - 1; i >= 0; i--) {
242
+ const entry = this.queue[i];
243
+ const blocker = [...this.active].find((owner) => owner.blocked && this.checkConflict(entry, owner));
244
+ if (blocker) {
245
+ this.queue.splice(i, 1);
246
+ toReject.push({
247
+ entry,
248
+ error: new DeviceTaskError("Task stop unconfirmed; workspace blocked until service restart"),
249
+ });
250
+ }
251
+ }
252
+ for (const { entry, error } of toReject) {
253
+ entry.reject(error);
254
+ }
255
+ if (this.queue.length === 0)
256
+ return;
257
+ let availableSlots = this.settings.maxActiveTasks - this.active.size;
258
+ if (availableSlots <= 0)
259
+ return;
260
+ // Identify schedulable candidates
261
+ // A candidate can physically start if:
262
+ // 1. No active task conflicts with it.
263
+ // 2. No earlier queued task conflicts with it (strict FIFO for the same bot/workspace).
264
+ const schedulable = [];
265
+ for (let i = 0; i < this.queue.length; i++) {
266
+ const entry = this.queue[i];
267
+ const hasActiveConflict = [...this.active].some((owner) => this.checkConflict(entry, owner));
268
+ if (hasActiveConflict)
269
+ continue;
270
+ const hasPriorQueueConflict = this.queue.slice(0, i).some((prior) => this.checkConflict(entry, prior));
271
+ if (hasPriorQueueConflict)
272
+ continue;
273
+ const isStarved = now - entry.queuedAt >= this.starvationThresholdMs || entry.skipCount >= this.maxSkipsBeforeStarvation;
274
+ schedulable.push({ entry, isStarved });
275
+ }
276
+ if (schedulable.length === 0)
277
+ return;
278
+ // Sort schedulable candidates:
279
+ // 1. Starved tasks come first (anti-starvation guarantee, oldest starved first).
280
+ // 2. For non-starved tasks: Room fair share (fewer active tasks in room first, then room last dispatched).
281
+ // 3. FIFO within same priority.
282
+ schedulable.sort((a, b) => {
283
+ if (a.isStarved && !b.isStarved)
284
+ return -1;
285
+ if (!a.isStarved && b.isStarved)
286
+ return 1;
287
+ if (a.isStarved && b.isStarved) {
288
+ return a.entry.queuedAt - b.entry.queuedAt;
289
+ }
290
+ // Room active task count
291
+ const activeA = [...this.active].filter((item) => item.roomId === a.entry.roomId).length;
292
+ const activeB = [...this.active].filter((item) => item.roomId === b.entry.roomId).length;
293
+ if (activeA !== activeB)
294
+ return activeA - activeB;
295
+ // Room dispatch history
296
+ const histA = this.roomDispatchHistory.get(a.entry.roomId);
297
+ const histB = this.roomDispatchHistory.get(b.entry.roomId);
298
+ const countA = histA?.count ?? 0;
299
+ const countB = histB?.count ?? 0;
300
+ if (countA !== countB)
301
+ return countA - countB;
302
+ const lastA = histA?.lastDispatchedAt ?? 0;
303
+ const lastB = histB?.lastDispatchedAt ?? 0;
304
+ if (lastA !== lastB)
305
+ return lastA - lastB;
306
+ return a.entry.queuedAt - b.entry.queuedAt;
307
+ });
308
+ // Select up to availableSlots
309
+ const toDispatch = [];
310
+ for (const cand of schedulable) {
311
+ if (availableSlots <= 0)
312
+ break;
313
+ // Ensure candidates chosen in this batch do not conflict with each other
314
+ const conflictsWithSelected = toDispatch.some((selected) => this.checkConflict(cand.entry, selected));
315
+ if (conflictsWithSelected)
316
+ continue;
317
+ toDispatch.push(cand.entry);
318
+ availableSlots--;
319
+ }
320
+ // Update skip counts for schedulable candidates that were passed over
321
+ for (const cand of schedulable) {
322
+ if (!toDispatch.includes(cand.entry)) {
323
+ cand.entry.skipCount++;
324
+ }
325
+ }
326
+ // Dispatch selected entries with try/catch error isolation
327
+ for (const entry of toDispatch) {
328
+ const index = this.queue.indexOf(entry);
329
+ if (index >= 0) {
330
+ this.queue.splice(index, 1);
331
+ }
332
+ try {
333
+ entry.start();
334
+ this.recordRoomDispatch(entry.roomId);
335
+ }
336
+ catch (error) {
337
+ entry.reject(error);
338
+ this.drain();
339
+ }
340
+ }
341
+ }
342
+ analyzeBlockReason(entry, queueIndex) {
343
+ // Check workspace blocked by unconfirmed stop
344
+ const blockedBlocker = [...this.active].find((owner) => owner.blocked && this.checkConflict(entry, owner));
345
+ if (blockedBlocker) {
346
+ return {
347
+ reason: "workspace_blocked",
348
+ detail: "Workspace is locked due to an unconfirmed task stop",
349
+ };
350
+ }
351
+ // Check bot busy in active
352
+ const botActive = [...this.active].find((owner) => owner.botId === entry.botId);
353
+ if (botActive) {
354
+ return {
355
+ reason: "bot_busy",
356
+ detail: "Target bot is currently running another task",
357
+ };
358
+ }
359
+ // Check workspace conflict in active
360
+ const workspaceActive = [...this.active].find((owner) => executionRootsOverlap(entry.root, owner.root));
361
+ if (workspaceActive) {
362
+ return {
363
+ reason: "workspace_conflict",
364
+ detail: "Workspace is currently in use by an active task",
365
+ };
366
+ }
367
+ // Check prior queue item conflicts (FIFO constraint)
368
+ const priorBotQueue = this.queue.slice(0, queueIndex).find((prior) => prior.botId === entry.botId);
369
+ if (priorBotQueue) {
370
+ return {
371
+ reason: "bot_busy",
372
+ detail: "Target bot has an earlier queued task waiting",
373
+ };
374
+ }
375
+ const priorWorkspaceQueue = this.queue
376
+ .slice(0, queueIndex)
377
+ .find((prior) => executionRootsOverlap(entry.root, prior.root));
378
+ if (priorWorkspaceQueue) {
379
+ return {
380
+ reason: "workspace_conflict",
381
+ detail: "Workspace has an earlier queued task waiting",
382
+ };
383
+ }
384
+ // Check concurrency limit
385
+ if (this.active.size >= this.settings.maxActiveTasks) {
386
+ return {
387
+ reason: "max_concurrency_reached",
388
+ detail: "Device concurrent task limit reached",
389
+ };
390
+ }
391
+ // Otherwise waiting for room fairness round
392
+ return {
393
+ reason: "room_fairness_yield",
394
+ detail: "Waiting for fair scheduling turn across rooms",
395
+ };
396
+ }
397
+ getSnapshot() {
398
+ const running = [];
399
+ const blocked = [];
400
+ for (const item of this.active) {
401
+ if (item.blocked) {
402
+ const reason = item.blocked && item.blocked.stopUnconfirmed ? "unconfirmed_stop" : "workspace_blocked";
403
+ blocked.push({
404
+ taskId: item.taskId,
405
+ attemptId: item.attemptId,
406
+ roomId: item.roomId,
407
+ botId: item.botId,
408
+ reason,
409
+ });
410
+ }
411
+ else {
412
+ running.push({
413
+ taskId: item.taskId,
414
+ attemptId: item.attemptId,
415
+ roomId: item.roomId,
416
+ botId: item.botId,
417
+ startedAt: item.startedAt,
418
+ });
419
+ }
420
+ }
421
+ const waiting = this.queue.map((item, index) => {
422
+ const { reason, detail } = this.analyzeBlockReason(item, index);
423
+ return {
424
+ taskId: item.taskId,
425
+ attemptId: item.attemptId,
426
+ roomId: item.roomId,
427
+ botId: item.botId,
428
+ queuedAt: item.queuedAt,
429
+ queuePosition: index + 1,
430
+ blockReason: reason,
431
+ blockReasonDetail: detail,
432
+ cancelable: true,
433
+ };
434
+ });
435
+ return {
436
+ settings: this.getSettings(),
437
+ activeCount: this.active.size,
438
+ waitingCount: this.queue.length,
439
+ blockedCount: blocked.length,
440
+ running,
441
+ waiting,
442
+ blocked,
443
+ };
444
+ }
445
+ }