@linxin666/dsh-client-ui-task-board-team 0.0.0-stage → 0.4.14

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 (74) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +66 -2
  4. package/README.zh.md +67 -0
  5. package/cordis.patch.yml +14 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +1490 -0
  8. package/lib/index.js +2968 -0
  9. package/lib/types/client/PluginSettingsCard.d.ts +255 -0
  10. package/lib/types/client/RangeBubble.d.ts +46 -0
  11. package/lib/types/client/SegmentGroup.d.ts +28 -0
  12. package/lib/types/client/index.d.ts +58 -0
  13. package/lib/types/client/locales.d.ts +90 -0
  14. package/lib/types/client/optional-service.d.ts +22 -0
  15. package/lib/types/client/settings-form.d.ts +235 -0
  16. package/lib/types/client/team/extension.d.ts +29 -0
  17. package/lib/types/client/team/sections.d.ts +38 -0
  18. package/lib/types/client/team/settings.d.ts +67 -0
  19. package/lib/types/client/team/summary.d.ts +34 -0
  20. package/lib/types/core/contract.d.ts +269 -0
  21. package/lib/types/core/hub-protocol.d.ts +175 -0
  22. package/lib/types/core/identity.d.ts +96 -0
  23. package/lib/types/core/mirror.d.ts +51 -0
  24. package/lib/types/core/question-report.d.ts +84 -0
  25. package/lib/types/core/settlement.d.ts +49 -0
  26. package/lib/types/core/task-record.d.ts +59 -0
  27. package/lib/types/core/timers.d.ts +20 -0
  28. package/lib/types/host/bindings.d.ts +92 -0
  29. package/lib/types/host/channel.d.ts +44 -0
  30. package/lib/types/host/credentials.d.ts +63 -0
  31. package/lib/types/host/extension.d.ts +57 -0
  32. package/lib/types/host/hub-client.d.ts +157 -0
  33. package/lib/types/host/questions.d.ts +105 -0
  34. package/lib/types/host/service.d.ts +209 -0
  35. package/lib/types/host/setup.d.ts +152 -0
  36. package/lib/types/host/tools.d.ts +19 -0
  37. package/lib/types/host/waterfall.d.ts +39 -0
  38. package/lib/types/index.d.ts +152 -0
  39. package/locale/en.json +6 -0
  40. package/locale/zh.json +6 -0
  41. package/package.json +84 -3
  42. package/src/client/PluginSettingsCard.tsx +838 -0
  43. package/src/client/RangeBubble.tsx +164 -0
  44. package/src/client/SegmentGroup.tsx +93 -0
  45. package/src/client/css-modules.d.ts +5 -0
  46. package/src/client/index.ts +139 -0
  47. package/src/client/locales.ts +168 -0
  48. package/src/client/optional-service.ts +30 -0
  49. package/src/client/settings-card.module.css +821 -0
  50. package/src/client/settings-form.ts +510 -0
  51. package/src/client/team/extension.ts +185 -0
  52. package/src/client/team/sections.tsx +159 -0
  53. package/src/client/team/settings.tsx +348 -0
  54. package/src/client/team/summary.ts +156 -0
  55. package/src/client/team/team.module.css +193 -0
  56. package/src/core/contract.ts +326 -0
  57. package/src/core/hub-protocol.ts +217 -0
  58. package/src/core/identity.ts +193 -0
  59. package/src/core/mirror.ts +88 -0
  60. package/src/core/question-report.ts +144 -0
  61. package/src/core/settlement.ts +84 -0
  62. package/src/core/task-record.ts +65 -0
  63. package/src/core/timers.ts +34 -0
  64. package/src/host/bindings.ts +211 -0
  65. package/src/host/channel.ts +97 -0
  66. package/src/host/credentials.ts +147 -0
  67. package/src/host/extension.ts +197 -0
  68. package/src/host/hub-client.ts +287 -0
  69. package/src/host/questions.ts +275 -0
  70. package/src/host/service.ts +1421 -0
  71. package/src/host/setup.ts +259 -0
  72. package/src/host/tools.ts +70 -0
  73. package/src/host/waterfall.ts +51 -0
  74. package/src/index.ts +452 -0
@@ -0,0 +1,1421 @@
1
+ /**
2
+ * The provider's hub synchronization: registration, heartbeat, claiming, leases
3
+ * and write-back.
4
+ *
5
+ * The division of authority runs through every method here. The hub decides
6
+ * which issues exist, who owns them and what collaboration status they carry;
7
+ * this Host decides whether it may take one, how it runs it locally and what the
8
+ * run produced. A claim is the only moment the two meet: the hub hands over a
9
+ * lease and an attempt id, this Host materializes the issue as a board card and
10
+ * reports back when that card's execution settles.
11
+ *
12
+ * Reconnection is the interesting path, so it is written as one: the attempt
13
+ * credentials live on the card's own payload, and a re-claim presents them. A
14
+ * hub that recognizes them re-establishes the lease and creates nothing new, and
15
+ * this Host in turn never creates a second card for an issue it already mirrors
16
+ * and never starts a second execution for an attempt it already ran.
17
+ *
18
+ * @module dsh-task-board-team/host/service
19
+ */
20
+ import {
21
+ type HubAgentDefinition,
22
+ type HubClaim,
23
+ type HubComment,
24
+ type HubIssue,
25
+ type HubIssueStatus,
26
+ HOST_CLIENT_VERSION,
27
+ LEASE_RENEW_INTERVAL_MS,
28
+ HEARTBEAT_INTERVAL_MS,
29
+ RECONNECT_BASE_MS,
30
+ RECONNECT_MAX_MS,
31
+ SWEEP_INTERVAL_MS,
32
+ readServerFrame,
33
+ type HubServerFrame,
34
+ } from '../core/hub-protocol.ts'
35
+ import type { TaskBoardExtensionHost, TaskBoardCapabilities, TaskBoardLinkedTask } from '../core/contract.ts'
36
+ import {
37
+ TEAM_EXTENSION_ID,
38
+ findLinkedTask,
39
+ readTaskIssueLink,
40
+ readTeamIssueLink,
41
+ toPayload,
42
+ type TeamIssueLink,
43
+ } from '../core/identity.ts'
44
+ import { buildMirrorDraft, type MirrorAgent } from '../core/mirror.ts'
45
+ import { buildSettleRequest, type SettleRequestBody } from '../core/settlement.ts'
46
+ import type { TaskRecord } from '../core/task-record.ts'
47
+ import type { HostTimerFace } from '../core/timers.ts'
48
+ import type { BoundAgent, TeamAgentBinding } from './bindings.ts'
49
+ import { HubError, type HubClient } from './hub-client.ts'
50
+ import { QuestionRouter, type PendingQuestionView } from './questions.ts'
51
+ import type { SocketHandlers, SocketLike } from './channel.ts'
52
+
53
+ /** Live settings of one mount, read at use time. */
54
+ export interface TeamRuntimeSettings {
55
+ /** Whether this extension is switched on. */
56
+ enabled: boolean
57
+ /** Hostname this Host registers under. */
58
+ hostname: string
59
+ /** Configured member bindings. */
60
+ bindings: readonly TeamAgentBinding[]
61
+ /** Workspace this mount runs its cards in; empty falls back to the member's team. */
62
+ workspaceId?: string
63
+ /** Optional local fallback wait for a claimed question, in minutes; 0 means none. */
64
+ questionWaitMinutes?: number
65
+ }
66
+
67
+ /** One comment, as the browser renders it. */
68
+ export interface TeamCommentView {
69
+ id: string
70
+ author: string
71
+ content: string
72
+ createdAt: number
73
+ }
74
+
75
+ /** One activity entry, as the browser renders it. */
76
+ export interface TeamActivityView {
77
+ id: string
78
+ type: string
79
+ text: string
80
+ createdAt: number
81
+ }
82
+
83
+ /** The collaboration half of one mirrored card. */
84
+ export interface TeamCardView {
85
+ issueId: string
86
+ issueNumber?: number
87
+ hubStatus?: HubIssueStatus
88
+ assignee?: string
89
+ reviewer?: string
90
+ /** Member id behind `assignee`, when the hub named one. */
91
+ assigneeMemberId?: string
92
+ /** Member id behind `reviewer`, when the hub named one. */
93
+ reviewerMemberId?: string
94
+ agentName?: string
95
+ comments: TeamCommentView[]
96
+ activity: TeamActivityView[]
97
+ lastError?: string
98
+ }
99
+
100
+ /** How the row's connection to the hub currently stands. */
101
+ export type TeamConnectionState = 'idle' | 'connecting' | 'online' | 'reconnecting' | 'error'
102
+
103
+ /** The summary this extension publishes into the board snapshot. */
104
+ export interface TeamExtensionSummary {
105
+ connection: {
106
+ state: TeamConnectionState
107
+ hostId?: string
108
+ lastHeartbeatAt?: number
109
+ reconnects: number
110
+ lastError?: string
111
+ }
112
+ capabilities: TaskBoardCapabilities
113
+ agents: Array<{ memberId: string; name: string; preset?: string; hubAgentId?: string }>
114
+ problems: string[]
115
+ /**
116
+ * Whether this board pins a draft preset, model and effort when it creates a
117
+ * card.
118
+ *
119
+ * `unknown` until the first mirror card proves it either way: the verdict comes
120
+ * from reading the created card back, because a board revision without the
121
+ * draft targets drops them silently.
122
+ */
123
+ presetPin: 'unknown' | 'supported' | 'missing'
124
+ cards: Record<string, TeamCardView>
125
+ pendingQuestions: PendingQuestionView[]
126
+ /**
127
+ * Non-secret configuration, added by the mounting row rather than by the
128
+ * service: the settings block renders the configured hub, team and bindings
129
+ * from the same document it reads everything else from.
130
+ */
131
+ configuration?: {
132
+ hubUrl?: string
133
+ teamId?: string
134
+ hostname?: string
135
+ tokenConfigured?: boolean
136
+ /** Optional local fallback wait for a claimed question, in minutes; 0 means none. */
137
+ questionWaitMinutes?: number
138
+ }
139
+ }
140
+
141
+ /** The problem line published when the board serves no draft preset. */
142
+ export const DRAFT_PIN_PROBLEM = 'this board revision cannot pin an agent preset, model or reasoning effort on a new card, so a claimed issue becomes a mirror card that is left for a human to start'
143
+
144
+ /** The problem line published while this Host has no workspace to run a card in. */
145
+ export const WORKSPACE_PROBLEM = 'no run workspace is bound to this Host, so no team issue is claimed: a mirror card without a workspace cannot be started, and the hub would keep its issue running'
146
+
147
+ /** Longest comment or activity text one summary carries. */
148
+ const VIEW_TEXT_LIMIT = 2_000
149
+ /** Most comments and activity entries one summary carries per card. */
150
+ const VIEW_ENTRY_LIMIT = 20
151
+
152
+ export interface TeamSyncServiceOptions {
153
+ /** The board's capability face. */
154
+ host: TaskBoardExtensionHost
155
+ /** Hub REST client. */
156
+ hub: HubClient
157
+ /** Live settings. */
158
+ settings: () => TeamRuntimeSettings
159
+ /** Resolve the bound members out of the dsh-agents ledger. */
160
+ resolveAgents: () => Promise<{ agents: BoundAgent[]; problems: string[] }>
161
+ /** Open the team channel; undefined means this deployment cannot. */
162
+ connect: (sinceSeq: number, handlers: SocketHandlers) => Promise<SocketLike | undefined>
163
+ /** Which optional capabilities the board really serves. */
164
+ capabilities: TaskBoardCapabilities
165
+ /** Ask the board to run one card; absent means this Host cannot start executions. */
166
+ requestRun?: (taskId: string) => void
167
+ timers: HostTimerFace
168
+ now: () => number
169
+ uuid: () => string
170
+ log?: (message: string, detail?: unknown) => void
171
+ }
172
+
173
+ function clip(text: string): string {
174
+ const trimmed = text.trim()
175
+ return trimmed.length <= VIEW_TEXT_LIMIT ? trimmed : trimmed.slice(0, VIEW_TEXT_LIMIT - 3) + '...'
176
+ }
177
+
178
+ /** The synchronization service of one mounted extension. */
179
+ export class TeamSyncService {
180
+ readonly #options: TeamSyncServiceOptions
181
+ readonly #questions: QuestionRouter
182
+ readonly #leases = new Map<string, () => void>()
183
+ readonly #cards = new Map<string, TeamCardView>()
184
+ /** Hub agent records by their hub id, learned at registration. */
185
+ readonly #hubAgents = new Map<string, BoundAgent>()
186
+ #agents: BoundAgent[] = []
187
+ #problems: string[] = []
188
+ #hostId: string | undefined
189
+ #seq = 0
190
+ #socket: SocketLike | undefined
191
+ #stopHeartbeat: (() => void) | undefined
192
+ #stopReconnect: (() => void) | undefined
193
+ #started = false
194
+ #connection: TeamConnectionState = 'idle'
195
+ #lastError: string | undefined
196
+ #lastHeartbeatAt: number | undefined
197
+ #reconnects = 0
198
+ #reconnectAttempt = 0
199
+ #starting: Promise<void> | undefined
200
+ #presetPin: 'unknown' | 'supported' | 'missing' = 'unknown'
201
+ /** Instant of the last sweep, so a burst of events coalesces into one pass. */
202
+ #lastSweepAt: number | undefined
203
+ /** A sweep scheduled for the next cadence boundary, while one is pending. */
204
+ #pendingSweep: (() => void) | undefined
205
+ /** Issues with a claim in flight: one claim per issue at a time, whoever asks. */
206
+ readonly #claiming = new Set<string>()
207
+ /** Agent names the hub reported another Host already owns, by name. */
208
+ readonly #agentConflicts = new Map<string, string>()
209
+ /** Issues whose owed settlement the current pass already retried. */
210
+ readonly #settledThisPass = new Set<string>()
211
+
212
+ constructor(options: TeamSyncServiceOptions) {
213
+ this.#options = options
214
+ this.#questions = new QuestionRouter({
215
+ hub: options.hub,
216
+ host: options.host,
217
+ linked: () => this.#linked(),
218
+ timers: options.timers,
219
+ now: options.now,
220
+ uuid: options.uuid,
221
+ onChange: () => { this.#publish() },
222
+ fallbackWaitMs: () => {
223
+ const minutes = options.settings().questionWaitMinutes ?? 0
224
+ return minutes > 0 ? minutes * 60_000 : undefined
225
+ },
226
+ ...(options.log === undefined ? {} : { log: options.log }),
227
+ })
228
+ }
229
+
230
+ /** Republish the summary, e.g. after a configuration write changed what it shows. */
231
+ publishNow(): void {
232
+ this.#publish()
233
+ }
234
+
235
+ /** The question router this service routes the Host waterfall through. */
236
+ get questions(): QuestionRouter {
237
+ return this.#questions
238
+ }
239
+
240
+ /** Start registration, heartbeat, the channel and the first claim sweep. */
241
+ async start(): Promise<void> {
242
+ if (this.#started) return
243
+ this.#started = true
244
+ this.#starting = this.#bootstrap()
245
+ await this.#starting
246
+ }
247
+
248
+ /**
249
+ * Resolve once this mount finished registering, or immediately when it has not
250
+ * started at all.
251
+ *
252
+ * A sweep requested before registration completes must wait for the host id
253
+ * instead of silently claiming nothing, which is what a caller racing the
254
+ * bootstrap would otherwise get.
255
+ * @returns a promise resolved when the bootstrap settles.
256
+ */
257
+ async whenStarted(): Promise<void> {
258
+ await this.#starting
259
+ }
260
+
261
+ /** Release every timer, the socket and every pending question claim. */
262
+ stop(): void {
263
+ this.#started = false
264
+ this.#stopHeartbeat?.()
265
+ this.#stopHeartbeat = undefined
266
+ this.#stopReconnect?.()
267
+ this.#stopReconnect = undefined
268
+ this.#pendingSweep?.()
269
+ this.#pendingSweep = undefined
270
+ this.#socket?.close()
271
+ this.#socket = undefined
272
+ for (const cancel of this.#leases.values()) cancel()
273
+ this.#leases.clear()
274
+ this.#questions.dispose()
275
+ this.#connection = 'idle'
276
+ }
277
+
278
+ /** The summary the browser renders, built fresh from the live state. */
279
+ summary(): TeamExtensionSummary {
280
+ const cards: Record<string, TeamCardView> = {}
281
+ for (const [taskId, view] of this.#cards) cards[taskId] = { ...view }
282
+ for (const entry of this.#linked()) {
283
+ const link = readTaskIssueLink(entry.task)
284
+ if (link === undefined) continue
285
+ const existing = cards[entry.task.id]
286
+ cards[entry.task.id] = {
287
+ issueId: link.issueId,
288
+ ...(link.issueNumber === undefined ? {} : { issueNumber: link.issueNumber }),
289
+ ...(link.hubStatus === undefined ? {} : { hubStatus: link.hubStatus }),
290
+ ...(link.assignee === undefined ? {} : { assignee: link.assignee }),
291
+ ...(link.reviewer === undefined ? {} : { reviewer: link.reviewer }),
292
+ comments: existing?.comments ?? [],
293
+ activity: existing?.activity ?? [],
294
+ ...(link.lastError === undefined ? {} : { lastError: link.lastError }),
295
+ ...(existing?.agentName === undefined ? {} : { agentName: existing.agentName }),
296
+ }
297
+ }
298
+ const agents = this.#agents.map(agent => {
299
+ const hubAgentId = this.#hubAgentIdOf(agent.memberId)
300
+ return {
301
+ memberId: agent.memberId,
302
+ name: agent.name,
303
+ ...(agent.preset === undefined ? {} : { preset: agent.preset }),
304
+ ...(hubAgentId === undefined ? {} : { hubAgentId }),
305
+ }
306
+ })
307
+ return {
308
+ connection: {
309
+ state: this.#connection,
310
+ ...(this.#hostId === undefined ? {} : { hostId: this.#hostId }),
311
+ ...(this.#lastHeartbeatAt === undefined ? {} : { lastHeartbeatAt: this.#lastHeartbeatAt }),
312
+ reconnects: this.#reconnects,
313
+ ...(this.#lastError === undefined ? {} : { lastError: this.#lastError }),
314
+ },
315
+ capabilities: this.#options.capabilities,
316
+ agents,
317
+ problems: [...this.#problems, ...this.#conflictProblems()],
318
+ presetPin: this.#presetPin,
319
+ cards,
320
+ pendingQuestions: [...this.#questions.pending()],
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Report one settled execution back to the hub.
326
+ * @param event - the board's settlement notification.
327
+ */
328
+ async handleExecutionSettled(event: {
329
+ taskId: string
330
+ executionId: string
331
+ outcome: 'succeeded' | 'failed' | 'cancelled'
332
+ error?: string
333
+ }): Promise<void> {
334
+ const task = this.#options.host.tasks.get(event.taskId)
335
+ if (task === undefined) return
336
+ const link = readTaskIssueLink(task)
337
+ if (link === undefined) return
338
+ this.#releaseLease(task.id)
339
+ const attemptId = link.attemptId
340
+ if (attemptId === undefined) {
341
+ // Every write-back names the attempt that ran, so the hub can refuse a late
342
+ // one from an earlier round (protocol section 5, review R2). A card that
343
+ // carries no attempt cannot report an outcome at all, and sending one
344
+ // anyway would let it land under whatever attempt the hub holds now.
345
+ this.#recordError(task.id, new Error(
346
+ 'this card carries no execution attempt, so its outcome cannot be attributed and was not written back',
347
+ ))
348
+ return
349
+ }
350
+ const body = buildSettleRequest({
351
+ task,
352
+ executionId: event.executionId,
353
+ outcome: event.outcome,
354
+ ...(event.error === undefined ? {} : { error: event.error }),
355
+ attemptId,
356
+ })
357
+ // The write-back is recorded on the card BEFORE it is sent, so a refusal this
358
+ // Host may retry keeps what the run produced instead of dropping it.
359
+ this.#writeLink(task.id, { pendingSettle: body })
360
+ await this.#writeSettlement(task.id, link.issueId, body)
361
+ this.#publish()
362
+ }
363
+
364
+ /**
365
+ * Send one recorded settlement and, once the hub takes it, release everything
366
+ * the hub now owns.
367
+ *
368
+ * The attempt and its lease belong to a finished run: settling is the last
369
+ * thing this Host does with them, so a later claim of the same issue is fresh
370
+ * instead of a reconnect that would ask the hub to re-establish a dead attempt.
371
+ * @param taskId - the card the settlement belongs to.
372
+ * @param issueId - the issue it settles.
373
+ * @param body - the settlement body, as the card recorded it.
374
+ */
375
+ async #writeSettlement(taskId: string, issueId: string, body: SettleRequestBody): Promise<void> {
376
+ const attemptId = body.execution_attempt_id
377
+ if (attemptId === undefined) {
378
+ this.#writeLink(taskId, { pendingSettle: undefined })
379
+ this.#recordError(taskId, new Error('a settlement without an execution attempt is never sent to the hub'))
380
+ return
381
+ }
382
+ try {
383
+ const settled = await this.#options.hub.settle(issueId, body)
384
+ this.#writeLink(taskId, {
385
+ pendingSettle: undefined,
386
+ attemptId: undefined,
387
+ leaseToken: undefined,
388
+ hubStatus: readStatus(settled.status),
389
+ })
390
+ } catch (error) {
391
+ if (!isSettlementFinal(error)) {
392
+ // Every refusal that may pass (a network failure, a timeout, a 5xx, a rate
393
+ // limit) leaves the outcome on the card for the next sweep or reconnect to
394
+ // place, and the hub's own gates still decide whether it lands.
395
+ this.#recordError(taskId, error)
396
+ return
397
+ }
398
+ // A final refusal can never be accepted again: the attempt it names is gone
399
+ // or the hub forbids it outright, so a retry would only spend this Host's
400
+ // request budget. The card forgets the write-back.
401
+ const card = this.#options.host.tasks.get(taskId)
402
+ const current = card === undefined ? undefined : readTaskIssueLink(card)
403
+ if (current?.attemptId !== undefined && current.attemptId !== attemptId) {
404
+ // The card has since moved to a newer attempt (a rework or a retry minted
405
+ // one): this settlement belongs to the round that replaced it, so nothing
406
+ // of the current run may be released and the operator sees no error for a
407
+ // result the next run is about to report anyway.
408
+ this.#writeLink(taskId, { pendingSettle: undefined })
409
+ this.#options.log?.('dropped the settlement of a replaced attempt for ' + issueId, error)
410
+ return
411
+ }
412
+ this.#writeLink(taskId, { pendingSettle: undefined, attemptId: undefined, leaseToken: undefined })
413
+ this.#recordError(taskId, new Error(
414
+ 'the hub refused this settlement for good (' + describe(error) + '); it was dropped instead of retried, '
415
+ + 'so start the card again to report a new outcome',
416
+ ))
417
+ }
418
+ }
419
+
420
+ /**
421
+ * Retry every settlement the hub has not accepted yet.
422
+ *
423
+ * A refusal is not permission to decide the outcome locally: the retry presents
424
+ * the same body and the hub's own gates still decide whether it lands. A
425
+ * settlement an expired attempt made impossible was already dropped by
426
+ * {@link TeamSyncService.#writeSettlement}, so only a retryable refusal is
427
+ * carried into this pass.
428
+ */
429
+ async #retryPendingSettlements(): Promise<void> {
430
+ for (const entry of this.#linked()) {
431
+ const link = readTeamIssueLink(entry.payload)
432
+ const pending = link?.pendingSettle
433
+ if (link === undefined || pending === undefined) continue
434
+ this.#settledThisPass.add(link.issueId)
435
+ await this.#writeSettlement(entry.task.id, link.issueId, pending)
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Claim every issue the hub offers this Host, for the agents bound to it.
441
+ * @returns how many issues this pass turned into a new card.
442
+ */
443
+ async sweep(): Promise<number> {
444
+ if (!this.#started) return 0
445
+ await this.whenStarted()
446
+ return await this.#runSweep()
447
+ }
448
+
449
+ /**
450
+ * Ask for a sweep, coalesced to at most one pass per cadence window.
451
+ *
452
+ * A burst of channel events (a reviewer rejecting, a status moving, an issue
453
+ * appearing) asks for the same work, and the hub counts Host requests per
454
+ * minute (protocol amendment A4 point 6), so the asks collapse into one pass:
455
+ * the current window's pass or the single pass scheduled at its boundary.
456
+ */
457
+ requestSweep(): void {
458
+ if (!this.#started) return
459
+ if (this.#pendingSweep !== undefined) return
460
+ const now = this.#options.now()
461
+ const last = this.#lastSweepAt
462
+ if (last === undefined || now - last >= SWEEP_INTERVAL_MS) {
463
+ void this.#runSweep()
464
+ return
465
+ }
466
+ this.#pendingSweep = this.#options.timers.timeout(() => {
467
+ this.#pendingSweep = undefined
468
+ void this.#runSweep()
469
+ }, SWEEP_INTERVAL_MS - (now - last))
470
+ }
471
+
472
+ /**
473
+ * One claim sweep over what the hub currently offers this Host.
474
+ * @returns how many issues this pass turned into a new card.
475
+ */
476
+ async #runSweep(): Promise<number> {
477
+ if (this.#hostId === undefined) return 0
478
+ this.#lastSweepAt = this.#options.now()
479
+ // A pass first finishes what the last one could not hand over: a settlement
480
+ // the hub refused is retried once, before any new work is claimed.
481
+ this.#settledThisPass.clear()
482
+ await this.#retryPendingSettlements()
483
+ // A card the board cannot start is worse than no card: the claim moves the
484
+ // issue to `running` on the hub, this Host keeps renewing the lease, and
485
+ // nothing ever settles it. The board resolves a card's workspace from the
486
+ // card itself and refuses the run when there is none, so a mount with no
487
+ // workspace for any bound member asks for nothing and says why.
488
+ if (this.#agents.length > 0 && !this.#agents.some(agent => this.#workspaceFor(agent) !== '')) {
489
+ this.#raiseProblem(WORKSPACE_PROBLEM)
490
+ this.#publish()
491
+ return 0
492
+ }
493
+ this.#dropProblem(WORKSPACE_PROBLEM)
494
+ let issues: readonly HubIssue[]
495
+ try {
496
+ issues = await this.#options.hub.listClaimableIssues(this.#hostId)
497
+ } catch (error) {
498
+ this.#lastError = describe(error)
499
+ this.#publish()
500
+ return 0
501
+ }
502
+ let claimed = 0
503
+ for (const issue of issues) {
504
+ // Only an agent bound to THIS machine may be executed here. The hub's own
505
+ // filter is the first gate; this is the second, and it is the one that
506
+ // keeps a wrongly listed issue from being run on the wrong machine.
507
+ const agent = this.#agentFor(issue)
508
+ if (agent === undefined) continue
509
+ // A member with no workspace to run in is skipped for the reason the whole
510
+ // pass above is skipped: its card would be created here and never start.
511
+ if (this.#workspaceFor(agent) === '') continue
512
+ try {
513
+ if (await this.#claimIssue(issue, agent)) claimed += 1
514
+ } catch (error) {
515
+ this.#lastError = describe(error)
516
+ this.#options.log?.('claim failed for ' + issue.id, error)
517
+ }
518
+ }
519
+ this.#publish()
520
+ return claimed
521
+ }
522
+
523
+ /** The agents whose hub records were synchronized at registration. */
524
+ boundAgents(): readonly BoundAgent[] {
525
+ return this.#agents
526
+ }
527
+
528
+ async #bootstrap(): Promise<void> {
529
+ const resolved = await this.#options.resolveAgents()
530
+ // A member whose definition pins no preset is not registered (protocol
531
+ // amendment A4 point 1): running it would silently fall back to the
532
+ // deployment default, which is exactly what this provider must not do.
533
+ const runnable = resolved.agents.filter(agent => agent.preset !== undefined && agent.preset !== '')
534
+ const skipped = resolved.agents
535
+ .filter(agent => agent.preset === undefined || agent.preset === '')
536
+ .map(agent => agent.name + ' is not registered: its dsh-agents definition pins no agent preset, so this Host '
537
+ + 'would have to run it under the deployment default')
538
+ this.#agents = runnable
539
+ this.#problems = [...resolved.problems, ...skipped]
540
+ if (this.#agents.length === 0) {
541
+ this.#problems = [...this.#problems, 'no dsh-agents member is bound to this Host, so no issue is claimed']
542
+ this.#publish()
543
+ return
544
+ }
545
+ await this.#register()
546
+ if (this.#hostId === undefined) {
547
+ this.#publish()
548
+ return
549
+ }
550
+ this.#startHeartbeat()
551
+ await this.#openChannel()
552
+ await this.#runSweep()
553
+ }
554
+
555
+ async #register(): Promise<void> {
556
+ this.#connection = 'connecting'
557
+ const definitions: HubAgentDefinition[] = this.#agents.map(agent => ({
558
+ name: agent.name,
559
+ preset_id: agent.preset ?? '',
560
+ ...(agent.model === undefined ? {} : { model: agent.model }),
561
+ ...(agent.reasoningEffort === undefined ? {} : { reasoning_effort: agent.reasoningEffort }),
562
+ }))
563
+ try {
564
+ const registered = await this.#options.hub.register({
565
+ hostname: this.#options.settings().hostname,
566
+ client_version: HOST_CLIENT_VERSION,
567
+ agents: definitions,
568
+ })
569
+ this.#hostId = registered.host_id
570
+ this.#connection = 'online'
571
+ this.#lastError = undefined
572
+ this.#hubAgents.clear()
573
+ for (const record of readAgentRecords(registered)) {
574
+ const local = this.#agents.find(agent => agent.name === record.name)
575
+ if (local !== undefined) this.#hubAgents.set(record.id, local)
576
+ }
577
+ // A name another Host already owns is skipped by the hub and reported back
578
+ // (section 5): the member stays unregistered here, claims nothing, and the
579
+ // operator reads why in the summary instead of meeting a card that never
580
+ // runs.
581
+ this.#agentConflicts.clear()
582
+ for (const conflict of readAgentConflicts(registered)) {
583
+ this.#agentConflicts.set(conflict.name, conflict.reason)
584
+ }
585
+ } catch (error) {
586
+ this.#hostId = undefined
587
+ this.#connection = 'error'
588
+ this.#lastError = describe(error)
589
+ this.#options.log?.('host registration failed', error)
590
+ }
591
+ this.#publish()
592
+ }
593
+
594
+ #startHeartbeat(): void {
595
+ this.#stopHeartbeat?.()
596
+ const beat = (): void => {
597
+ const hostId = this.#hostId
598
+ if (hostId === undefined) return
599
+ void this.#options.hub.heartbeat(hostId).then(() => {
600
+ this.#lastHeartbeatAt = this.#options.now()
601
+ if (this.#connection === 'reconnecting') this.#connection = 'online'
602
+ this.#publish()
603
+ }).catch((error: unknown) => {
604
+ this.#lastError = describe(error)
605
+ this.#options.log?.('heartbeat failed', error)
606
+ this.#publish()
607
+ })
608
+ }
609
+ this.#stopHeartbeat = this.#options.timers.interval(beat, HEARTBEAT_INTERVAL_MS)
610
+ beat()
611
+ }
612
+
613
+ async #openChannel(): Promise<void> {
614
+ this.#stopReconnect?.()
615
+ this.#stopReconnect = undefined
616
+ let socket: SocketLike | undefined
617
+ try {
618
+ socket = await this.#options.connect(this.#seq, {
619
+ message: data => { this.#onFrame(data) },
620
+ closed: reason => { this.#onClosed(reason) },
621
+ })
622
+ } catch (error) {
623
+ this.#options.log?.('team channel could not open', error)
624
+ socket = undefined
625
+ }
626
+ if (socket === undefined) {
627
+ this.#lastError = 'the team channel is unavailable; reconnecting'
628
+ this.#scheduleReconnect()
629
+ this.#publish()
630
+ return
631
+ }
632
+ this.#socket = socket
633
+ this.#connection = 'online'
634
+ this.#reconnectAttempt = 0
635
+ this.#publish()
636
+ }
637
+
638
+ #scheduleReconnect(): void {
639
+ this.#stopReconnect?.()
640
+ this.#connection = 'reconnecting'
641
+ this.#reconnects += 1
642
+ const delay = Math.min(RECONNECT_BASE_MS * 2 ** this.#reconnectAttempt, RECONNECT_MAX_MS)
643
+ this.#reconnectAttempt += 1
644
+ this.#stopReconnect = this.#options.timers.timeout(() => {
645
+ this.#stopReconnect = undefined
646
+ // Re-register first: a hub that restarted has forgotten this Host, and a
647
+ // channel opened before registration would push events for an unknown host.
648
+ void this.#register().then(async () => {
649
+ await this.#openChannel()
650
+ await this.#runSweep()
651
+ }).catch((error: unknown) => {
652
+ this.#options.log?.('reconnect failed', error)
653
+ this.#scheduleReconnect()
654
+ })
655
+ }, delay)
656
+ }
657
+
658
+ #onClosed(reason?: string): void {
659
+ if (!this.#started) return
660
+ this.#socket = undefined
661
+ if (reason !== undefined && reason !== '') this.#lastError = reason
662
+ this.#publish()
663
+ this.#scheduleReconnect()
664
+ }
665
+
666
+ #onFrame(data: string): void {
667
+ let parsed: unknown
668
+ try {
669
+ parsed = JSON.parse(data)
670
+ } catch {
671
+ return
672
+ }
673
+ const frame = readServerFrame(parsed)
674
+ if (frame === undefined) return
675
+ if (frame.t === 'pong') return
676
+ if (frame.t === 'resync_required') {
677
+ // The channel could not replay what this Host missed, so the only honest
678
+ // recovery is a fresh claim sweep: it re-establishes every issue the hub
679
+ // still offers and leaves the rest on the hub.
680
+ this.#seq = 0
681
+ this.requestSweep()
682
+ return
683
+ }
684
+ this.#onEvent(frame)
685
+ }
686
+
687
+ #onEvent(frame: Extract<HubServerFrame, { t: 'event' }>): void {
688
+ // Sequence numbers only move forward; a replayed frame already applied is
689
+ // dropped instead of being applied twice.
690
+ if (frame.seq <= this.#seq && this.#seq !== 0) return
691
+ this.#seq = frame.seq
692
+ const payload = frame.payload
693
+ switch (frame.event) {
694
+ case 'question.answered':
695
+ this.#questions.answered(payload)
696
+ return
697
+ case 'question.expired':
698
+ this.#questions.expired(payload)
699
+ return
700
+ case 'question.withdrawn':
701
+ this.#questions.withdrawn(payload)
702
+ return
703
+ case 'comment.created':
704
+ this.#recordComment(payload)
705
+ return
706
+ case 'comment.mentioned':
707
+ void this.#deliverMention(payload)
708
+ return
709
+ case 'issue.rework':
710
+ void this.#rework(payload)
711
+ return
712
+ case 'issue.status_changed':
713
+ this.#recordStatus(payload)
714
+ return
715
+ case 'issue.created':
716
+ case 'issue.updated':
717
+ this.requestSweep()
718
+ return
719
+ default:
720
+ return
721
+ }
722
+ }
723
+
724
+ /**
725
+ * Claim one issue for one bound agent out of a sweep.
726
+ * @returns whether this call created a card.
727
+ */
728
+ async #claimIssue(issue: HubIssue, agent: BoundAgent): Promise<boolean> {
729
+ return await this.#claimExclusively(issue.id, () => this.#claimOnce({ issueId: issue.id, issue, agent }))
730
+ }
731
+
732
+ /**
733
+ * Run one claim while no other claim for the same issue is in flight.
734
+ *
735
+ * Protocol amendment A4 point 5 makes claims on one issue strictly single
736
+ * flight, and both paths that claim — a sweep and an `issue.rework` event, which
737
+ * the hub sends back to back with `issue.updated` — enter here: the second
738
+ * caller finds the issue already being claimed and has nothing to do, instead of
739
+ * racing a claim the hub would refuse and recording that refusal as a failure.
740
+ * @param issueId - the issue being claimed.
741
+ * @param claim - the claim to run while the issue is held.
742
+ * @returns whatever the claim answered; false when one is already in flight.
743
+ */
744
+ async #claimExclusively(issueId: string, claim: () => Promise<boolean>): Promise<boolean> {
745
+ if (this.#claiming.has(issueId)) return false
746
+ this.#claiming.add(issueId)
747
+ try {
748
+ return await claim()
749
+ } finally {
750
+ this.#claiming.delete(issueId)
751
+ }
752
+ }
753
+
754
+ /**
755
+ * Claim one issue and act on what the claim grants.
756
+ *
757
+ * The card is the one this Host already mirrors, when it mirrors one: a claim
758
+ * never creates a second card for one issue. A card whose run finished but
759
+ * whose outcome the hub has not accepted is never claimed at all: the claim
760
+ * would mint an attempt nothing here executes, and the retry of the old body
761
+ * would then be refused against that attempt, losing what the run produced.
762
+ * Only a pending rework may claim such a card, because the reviewer's
763
+ * rejection IS the newer round.
764
+ *
765
+ * What runs afterwards follows from the claim itself — a pending rework always
766
+ * runs, a reconnect runs nothing, and a card with nothing running here is
767
+ * started again (a human retry moved the issue back to `assigned`, and nothing
768
+ * else would ever start that card).
769
+ * @param input - the issue, the agent it belongs to, and any rework the caller knows.
770
+ * @returns whether this call created a card.
771
+ */
772
+ async #claimOnce(input: {
773
+ issueId: string
774
+ /** The issue a sweep listed; absent when the caller only knows it by id. */
775
+ issue?: HubIssue
776
+ /** The agent to claim for; needed only when the issue has no card here yet. */
777
+ agent?: BoundAgent
778
+ /** Rework instructions the caller already knows; a sweep reads them off the issue. */
779
+ rework?: string
780
+ }): Promise<boolean> {
781
+ const existing = findLinkedTask(this.#linked(), input.issueId)
782
+ const previous = existing === undefined ? undefined : readTaskIssueLink(existing)
783
+ const agent = input.agent
784
+ const issue = input.issue
785
+ // A caller that knows neither a mirrored card nor the issue behind one has
786
+ // nothing the claim could act on, so nothing is asked of the hub.
787
+ if (existing === undefined && (agent === undefined || issue === undefined)) return false
788
+ const instructions = input.rework
789
+ ?? (typeof issue?.rework_instructions === 'string' ? issue.rework_instructions.trim() : '')
790
+ // A run whose outcome the hub never accepted is finished here and must not be
791
+ // re-claimed: that claim would hand this Host a new attempt with nothing to
792
+ // execute, keep its lease alive, and make the next retry of the old body
793
+ // answer 412 against the new attempt, losing the result for good. The pass
794
+ // retries the write-back first (once, not twice), so a hub that is ready again
795
+ // moves the issue instead of this Host taking an attempt it cannot run.
796
+ if (existing !== undefined && previous?.pendingSettle !== undefined && instructions === '') {
797
+ if (!this.#settledThisPass.has(input.issueId)) {
798
+ this.#settledThisPass.add(input.issueId)
799
+ await this.#writeSettlement(existing.id, input.issueId, previous.pendingSettle)
800
+ }
801
+ if (this.#pendingSettleOf(existing.id) !== undefined) return false
802
+ }
803
+ const claim = await this.#claimFromHub(input.issueId, existing, previous)
804
+ if (claim === undefined) return false
805
+
806
+ if (existing !== undefined) {
807
+ // A hub that recognizes the attempt re-establishes the same lease, and this
808
+ // Host mirrors the credentials without starting anything of its own: a
809
+ // second execution for one attempt is exactly the duplicate this path
810
+ // prevents, and a rework the issue still carries belongs to the run that is
811
+ // already consuming it.
812
+ this.#writeLink(existing.id, {
813
+ attemptId: claim.execution_attempt_id,
814
+ leaseToken: claim.lease_token,
815
+ leaseExpiresAt: claim.lease_expires_at,
816
+ hubStatus: 'running',
817
+ })
818
+ this.#ensureLease(existing, input.issueId, claim.lease_token)
819
+ // A settlement left by an earlier round belongs to an attempt the hub has
820
+ // replaced: it can never land again, and keeping it would make the next
821
+ // retry answer 412 against credentials the card no longer uses.
822
+ if (previous?.pendingSettle !== undefined
823
+ && previous.pendingSettle.execution_attempt_id !== claim.execution_attempt_id) {
824
+ this.#writeLink(existing.id, { pendingSettle: undefined })
825
+ }
826
+ if (this.#localExecutionRunning(existing)) return false
827
+ // A pending rework IS the one thing that has to run, and only after the
828
+ // claim above succeeded.
829
+ if (instructions !== '') {
830
+ this.#applyRework(existing.id, instructions)
831
+ return false
832
+ }
833
+ // Nothing runs here and nothing waits to be written back: a human retry
834
+ // moved the issue back to `assigned` while this card sat finished, and
835
+ // this is the one entry that starts it again.
836
+ this.#requestRun(existing.id)
837
+ return false
838
+ }
839
+
840
+ // The guard above keeps these two defined on this path.
841
+ if (agent === undefined || issue === undefined) return false
842
+ const workspaceId = this.#workspaceFor(agent)
843
+ const mirror: MirrorAgent = {
844
+ agentId: this.#hubAgentIdOf(agent.memberId) ?? agent.memberId,
845
+ memberId: agent.memberId,
846
+ name: agent.name,
847
+ ...(agent.preset === undefined ? {} : { preset: agent.preset }),
848
+ ...(agent.model === undefined ? {} : { model: agent.model }),
849
+ ...(agent.reasoningEffort === undefined ? {} : { reasoningEffort: agent.reasoningEffort }),
850
+ // The card carries the workspace this Host resolved for the member, not only
851
+ // the one the team pins: the claim above already refused to run without one.
852
+ ...(workspaceId === '' ? {} : { workspaceId }),
853
+ }
854
+ const draft = buildMirrorDraft(issue, mirror)
855
+ const payload = toPayload({
856
+ issueId: issue.id,
857
+ issueNumber: issue.issue_number,
858
+ attemptId: claim.execution_attempt_id,
859
+ leaseToken: claim.lease_token,
860
+ leaseExpiresAt: claim.lease_expires_at,
861
+ agentId: mirror.agentId,
862
+ agentMemberId: agent.memberId,
863
+ ...(agent.preset === undefined ? {} : { preset: agent.preset }),
864
+ hubStatus: 'running',
865
+ })
866
+ let task: TaskRecord
867
+ try {
868
+ task = this.#options.host.tasks.create(draft, { payload })
869
+ } catch (error) {
870
+ this.#options.log?.('mirror card refused for ' + issue.id, error)
871
+ this.#lastError = describe(error)
872
+ return false
873
+ }
874
+ this.#cards.set(task.id, {
875
+ issueId: issue.id,
876
+ issueNumber: issue.issue_number,
877
+ hubStatus: 'running',
878
+ agentName: agent.name,
879
+ comments: [],
880
+ activity: [],
881
+ })
882
+ this.#ensureLease(task, issue.id, claim.lease_token)
883
+ // The card is read back before anything runs: a board revision that cannot
884
+ // pin the draft targets drops them silently, and a card that fell back to the
885
+ // deployment's default preset must NOT be started as if it were the member's
886
+ // own run. Such a card is left for a human, visibly.
887
+ if (!this.#verifyDraftPin(task.id, agent)) {
888
+ this.#recordError(task.id, new Error(
889
+ 'this board revision cannot pin an agent preset on a new card, so the mirror card was created without '
890
+ + agent.name + "'s own preset and was not started; start it by hand once the board supports draft targets",
891
+ ))
892
+ return true
893
+ }
894
+ this.#requestRun(task.id)
895
+ return true
896
+ }
897
+
898
+ /**
899
+ * The settlement one card still owes the hub, read back from the card itself.
900
+ * @param taskId - the card to read.
901
+ * @returns the pending settlement, or undefined when the hub took it.
902
+ */
903
+ #pendingSettleOf(taskId: string): SettleRequestBody | undefined {
904
+ const task = this.#options.host.tasks.get(taskId)
905
+ if (task === undefined) return undefined
906
+ return readTaskIssueLink(task)?.pendingSettle
907
+ }
908
+
909
+ /**
910
+ * Ask the hub for one issue, presenting this Host's previous attempt only on a
911
+ * reconnect.
912
+ *
913
+ * A reconnect is the one moment the old credentials are still true: the run is
914
+ * executing here and this Host still holds the lease, so the hub re-establishes
915
+ * that attempt instead of minting a new one (protocol section 5). Every other
916
+ * claim is fresh and the hub mints the attempt id itself, so presenting one it
917
+ * never granted would only ask it to adopt this Host's guess.
918
+ * @param issueId - the issue to claim.
919
+ * @param task - the card that mirrors it, when it has one.
920
+ * @param link - that card's stored linkage.
921
+ * @returns the lease the hub granted, or undefined when another attempt holds the issue.
922
+ */
923
+ async #claimFromHub(
924
+ issueId: string,
925
+ task: TaskRecord | undefined,
926
+ link: TeamIssueLink | undefined,
927
+ ): Promise<HubClaim | undefined> {
928
+ try {
929
+ return await this.#options.hub.claim(issueId, this.#reconnectCredentials(task, link))
930
+ } catch (error) {
931
+ // The loser of a claim race is not a failure: the hub already granted this
932
+ // issue to an attempt that is executing it, so this caller has nothing to
933
+ // do and must not put a false error on the operator's screen.
934
+ if (isClaimHeldElsewhere(error)) return undefined
935
+ throw error
936
+ }
937
+ }
938
+
939
+ /**
940
+ * The credentials one claim presents, which is non-empty only on a reconnect.
941
+ * @param task - the card that mirrors the issue, when it has one.
942
+ * @param link - that card's stored linkage.
943
+ * @returns the attempt and lease to present, or nothing for a fresh claim.
944
+ */
945
+ #reconnectCredentials(task: TaskRecord | undefined, link: TeamIssueLink | undefined): {
946
+ execution_attempt_id?: string
947
+ lease_token?: string
948
+ } {
949
+ if (task === undefined || link === undefined) return {}
950
+ if (link.attemptId === undefined || link.leaseToken === undefined) return {}
951
+ if (!this.#localExecutionRunning(task)) return {}
952
+ return { execution_attempt_id: link.attemptId, lease_token: link.leaseToken }
953
+ }
954
+
955
+ /**
956
+ * Whether this Host still runs one of the card's executions.
957
+ *
958
+ * The board closes an execution by stamping its end instant, so an execution
959
+ * with no end is what "running here" means: the card's column can read
960
+ * `running` for a declaration a human made, and that starts nothing.
961
+ * @param task - the card to read.
962
+ * @returns whether one of its executions is still open.
963
+ */
964
+ #localExecutionRunning(task: TaskRecord): boolean {
965
+ return task.executions.some(execution => execution.endedAt === undefined)
966
+ }
967
+
968
+ /**
969
+ * Check that the created card really carries the member's execution targets.
970
+ * @param taskId - the card just created.
971
+ * @param agent - the member it was created for.
972
+ * @returns whether the board kept the pinned preset (no preset means nothing to check).
973
+ */
974
+ #verifyDraftPin(taskId: string, agent: BoundAgent): boolean {
975
+ if (agent.preset === undefined || agent.preset === '') {
976
+ this.#presetPin = 'supported'
977
+ return true
978
+ }
979
+ const created = this.#options.host.tasks.get(taskId)
980
+ if (created !== undefined && created.mode === agent.preset) {
981
+ this.#presetPin = 'supported'
982
+ return true
983
+ }
984
+ this.#presetPin = 'missing'
985
+ this.#raiseProblem(DRAFT_PIN_PROBLEM)
986
+ return false
987
+ }
988
+
989
+ /**
990
+ * Post one agent comment on the issue a card mirrors.
991
+ *
992
+ * The agent identity is the hub record this Host registered for the member the
993
+ * card was claimed for: the hub only accepts agent comments from the token
994
+ * holder that owns that agent, so the id comes from the payload instead of
995
+ * from whatever the model named.
996
+ * @param input - the card or issue to comment on, and the markdown body.
997
+ * @returns the stored comment's id.
998
+ */
999
+ async postComment(input: { taskId?: string; issueId?: string; text: string }): Promise<{ issueId: string; commentId: string }> {
1000
+ const linked = this.#linked()
1001
+ const task = input.taskId === undefined
1002
+ ? (input.issueId === undefined ? undefined : findLinkedTask(linked, input.issueId))
1003
+ : this.#options.host.tasks.get(input.taskId)
1004
+ if (task === undefined) throw new Error('no team card matches this comment')
1005
+ const link = readTaskIssueLink(task)
1006
+ if (link === undefined) throw new Error('that card does not mirror a team issue')
1007
+ const agentId = link.agentId ?? this.#hubAgentIdOf(link.agentMemberId ?? '')
1008
+ if (agentId === undefined) throw new Error('no hub agent record is bound to that card yet')
1009
+ const comment = await this.#options.hub.createComment(link.issueId, {
1010
+ content: input.text,
1011
+ author_type: 'agent',
1012
+ author_agent_id: agentId,
1013
+ })
1014
+ this.#recordComment({ comment })
1015
+ return { issueId: link.issueId, commentId: comment.id }
1016
+ }
1017
+
1018
+ #requestRun(taskId: string): void {
1019
+ const run = this.#options.requestRun
1020
+ if (run === undefined) {
1021
+ this.#recordError(taskId, new Error('this board revision serves no way to start an execution; open the card and run it from the board'))
1022
+ return
1023
+ }
1024
+ try {
1025
+ run(taskId)
1026
+ } catch (error) {
1027
+ this.#recordError(taskId, error)
1028
+ }
1029
+ }
1030
+
1031
+ #ensureLease(task: TaskRecord, issueId: string, leaseToken: string): void {
1032
+ this.#releaseLease(task.id)
1033
+ const renew = (): void => {
1034
+ void this.#options.hub.renewLease(issueId, leaseToken).then(renewed => {
1035
+ this.#writeLink(task.id, { leaseExpiresAt: renewed.lease_expires_at })
1036
+ }).catch((error: unknown) => {
1037
+ // LEASE_EXPIRED is the one refusal that means the lease is gone: keeping
1038
+ // the timer would renew a lease the hub no longer has.
1039
+ if (error instanceof HubError && error.code === 'LEASE_EXPIRED') {
1040
+ this.#releaseLease(task.id)
1041
+ this.#recordError(task.id, error)
1042
+ return
1043
+ }
1044
+ this.#options.log?.('lease renewal failed for ' + issueId, error)
1045
+ })
1046
+ }
1047
+ this.#leases.set(task.id, this.#options.timers.interval(renew, LEASE_RENEW_INTERVAL_MS))
1048
+ renew()
1049
+ }
1050
+
1051
+ #releaseLease(taskId: string): void {
1052
+ const cancel = this.#leases.get(taskId)
1053
+ if (cancel === undefined) return
1054
+ cancel()
1055
+ this.#leases.delete(taskId)
1056
+ }
1057
+
1058
+ async #deliverMention(payload: Record<string, unknown>): Promise<void> {
1059
+ const issueId = typeof payload.issue_id === 'string' ? payload.issue_id : undefined
1060
+ const content = typeof payload.content === 'string' ? payload.content : ''
1061
+ if (issueId === undefined || content.trim() === '') return
1062
+ const author = typeof payload.author === 'string' && payload.author !== '' ? payload.author : 'a team member'
1063
+ const task = findLinkedTask(this.#linked(), issueId)
1064
+ if (task === undefined) return
1065
+ this.#pushActivity(task.id, issueId, 'comment.mentioned', clip(author + ': ' + content))
1066
+ const sessions = this.#options.host.sessions
1067
+ const deliver = sessions?.followUp
1068
+ if (sessions === undefined || deliver === undefined) {
1069
+ // Visible degradation: the mention is kept on the card's activity stream,
1070
+ // and the settings section says this board cannot deliver it into the
1071
+ // session instead of the message disappearing silently.
1072
+ this.#recordError(task.id, new Error('this board revision serves no follow-up delivery, so a mention could not reach the session'))
1073
+ return
1074
+ }
1075
+ try {
1076
+ await deliver.call(sessions, task.id, clip(author + ' mentioned this task: ' + content))
1077
+ } catch (error) {
1078
+ this.#recordError(task.id, error)
1079
+ }
1080
+ }
1081
+
1082
+ async #rework(payload: Record<string, unknown>): Promise<void> {
1083
+ const issueId = typeof payload.issue_id === 'string' ? payload.issue_id : undefined
1084
+ if (issueId === undefined) return
1085
+ const instructions = typeof payload.instructions === 'string' ? payload.instructions.trim() : ''
1086
+ const task = findLinkedTask(this.#linked(), issueId)
1087
+ if (task === undefined) {
1088
+ this.#options.log?.('rework requested for an issue this Host does not mirror: ' + issueId)
1089
+ return
1090
+ }
1091
+ if (instructions === '') {
1092
+ // A rejection without instructions is a malformed signal: claiming the
1093
+ // issue for it would take work this Host cannot redo.
1094
+ this.#recordError(task.id, new Error('the rework request carried no instructions, so nothing was re-run'))
1095
+ return
1096
+ }
1097
+ // The claim goes through the SAME per-issue lock a sweep uses (protocol
1098
+ // amendment A4 point 5). The hub sends `issue.updated` and `issue.rework` back
1099
+ // to back, so the sweep and this event otherwise claim one issue twice: the
1100
+ // hub grants it to one of them and the loser records a race the operator
1101
+ // would read as a failure. A rework claim is fresh, so the hub mints the new
1102
+ // attempt id itself and nothing here presents a dead one.
1103
+ try {
1104
+ await this.#claimExclusively(issueId, () => this.#claimOnce({ issueId, rework: instructions }))
1105
+ } catch (error) {
1106
+ // Claim failed: nothing runs. The instructions are not applied and the
1107
+ // card is untouched, because a rework the hub did not authorize must not
1108
+ // start an execution.
1109
+ this.#recordError(task.id, error)
1110
+ return
1111
+ }
1112
+ this.#publish()
1113
+ }
1114
+
1115
+ /**
1116
+ * Apply review instructions to one already-mirrored card through the board's
1117
+ * rework capability, or report the gap.
1118
+ * @param taskId - the card the reviewer sent back.
1119
+ * @param instructions - what the reviewer asked for.
1120
+ */
1121
+ #applyRework(taskId: string, instructions: string): void {
1122
+ const rework = this.#options.host.tasks.rework
1123
+ if (rework === undefined) {
1124
+ this.#recordError(taskId, new Error('this board revision serves no rework, so the review instructions could not be applied'))
1125
+ return
1126
+ }
1127
+ try {
1128
+ rework.call(this.#options.host.tasks, taskId, instructions, 'team-hub')
1129
+ } catch (error) {
1130
+ this.#recordError(taskId, error)
1131
+ }
1132
+ }
1133
+
1134
+ #recordComment(payload: Record<string, unknown>): void {
1135
+ const comment = payload.comment
1136
+ if (typeof comment !== 'object' || comment === null) return
1137
+ const row = comment as HubComment
1138
+ if (typeof row.issue_id !== 'string') return
1139
+ const task = findLinkedTask(this.#linked(), row.issue_id)
1140
+ if (task === undefined) return
1141
+ const view = this.#view(task.id, row.issue_id)
1142
+ const author = this.#authorLabel(row)
1143
+ const entry: TeamCommentView = {
1144
+ id: typeof row.id === 'string' ? row.id : this.#options.uuid(),
1145
+ author,
1146
+ content: clip(typeof row.content === 'string' ? row.content : ''),
1147
+ createdAt: typeof row.created_at === 'number' ? row.created_at : this.#options.now(),
1148
+ }
1149
+ view.comments = [...view.comments, entry].slice(-VIEW_ENTRY_LIMIT)
1150
+ this.#pushActivity(task.id, row.issue_id, 'comment.created', entry.content)
1151
+ this.#publish()
1152
+ }
1153
+
1154
+ /**
1155
+ * Render one comment author the way a reader recognizes them.
1156
+ *
1157
+ * An agent author resolves to the member name this Host registered, and a human
1158
+ * author to the display name the card already knows; a name this Host cannot
1159
+ * resolve reads as "team member" rather than as a raw `mem_...` identifier,
1160
+ * which tells a reader nothing about who is speaking.
1161
+ * @param comment - the comment row the hub served.
1162
+ * @returns the label the detail section renders.
1163
+ */
1164
+ #authorLabel(comment: HubComment): string {
1165
+ const agentId = typeof comment.author_agent_id === 'string' ? comment.author_agent_id : undefined
1166
+ if (agentId !== undefined) {
1167
+ const agent = this.#hubAgents.get(agentId)
1168
+ if (agent !== undefined) return agent.name
1169
+ return 'team agent'
1170
+ }
1171
+ const memberId = typeof comment.author_member_id === 'string' ? comment.author_member_id : undefined
1172
+ if (memberId !== undefined) {
1173
+ for (const view of this.#cards.values()) {
1174
+ if (view.reviewerMemberId === memberId && view.reviewer !== undefined) return view.reviewer
1175
+ if (view.assigneeMemberId === memberId && view.assignee !== undefined) return view.assignee
1176
+ }
1177
+ }
1178
+ return 'team member'
1179
+ }
1180
+
1181
+ #recordStatus(payload: Record<string, unknown>): void {
1182
+ const issueId = typeof payload.issue_id === 'string' ? payload.issue_id : undefined
1183
+ const status = readStatus(payload.new_status)
1184
+ if (issueId === undefined || status === undefined) return
1185
+ const task = findLinkedTask(this.#linked(), issueId)
1186
+ if (task === undefined) return
1187
+ const view = this.#view(task.id, issueId)
1188
+ view.hubStatus = status
1189
+ this.#pushActivity(task.id, issueId, 'issue.status_changed', status)
1190
+ this.#writeLink(task.id, { hubStatus: status })
1191
+ // A lease that lapsed puts the issue back in the pool the hub offers this
1192
+ // Host; the sweep turns that into a renewed claim, never a second card. A
1193
+ // terminal status releases the lease on this side.
1194
+ if (status === 'assigned' || status === 'waiting_host') this.requestSweep()
1195
+ if (status === 'done' || status === 'canceled' || status === 'failed') this.#releaseLease(task.id)
1196
+ this.#publish()
1197
+ }
1198
+
1199
+ #pushActivity(taskId: string, issueId: string, type: string, text: string): void {
1200
+ const view = this.#view(taskId, issueId)
1201
+ view.activity = [...view.activity, {
1202
+ id: this.#options.uuid(),
1203
+ type,
1204
+ text: clip(text),
1205
+ createdAt: this.#options.now(),
1206
+ }].slice(-VIEW_ENTRY_LIMIT)
1207
+ }
1208
+
1209
+ #view(taskId: string, issueId: string): TeamCardView {
1210
+ const existing = this.#cards.get(taskId)
1211
+ if (existing !== undefined) {
1212
+ existing.issueId = issueId
1213
+ return existing
1214
+ }
1215
+ const created: TeamCardView = { issueId, comments: [], activity: [] }
1216
+ this.#cards.set(taskId, created)
1217
+ return created
1218
+ }
1219
+
1220
+ #recordError(taskId: string, error: unknown): void {
1221
+ const message = describe(error)
1222
+ this.#lastError = message
1223
+ const view = this.#cards.get(taskId)
1224
+ if (view !== undefined) view.lastError = message
1225
+ if (this.#options.host.tasks.get(taskId) !== undefined) this.#writeLink(taskId, { lastError: message })
1226
+ this.#options.log?.(message)
1227
+ this.#publish()
1228
+ }
1229
+
1230
+ #writeLink(taskId: string, patch: Partial<TeamIssueLink>): void {
1231
+ const task = this.#options.host.tasks.get(taskId)
1232
+ if (task === undefined) return
1233
+ const current = readTaskIssueLink(task)
1234
+ if (current === undefined) return
1235
+ const merged: TeamIssueLink = { ...current, ...patch }
1236
+ const payload = toPayload(merged)
1237
+ // A member this patch sets to undefined is one the card has to FORGET (the
1238
+ // attempt of a settled run, a settlement the hub has taken). `toPayload`
1239
+ // drops absent members to keep a merge from storing them, so the deletions
1240
+ // are put back here: the board's own merge removes an explicit undefined.
1241
+ for (const key of Object.keys(patch) as Array<keyof TeamIssueLink>) {
1242
+ if (patch[key] === undefined) payload[key] = undefined
1243
+ }
1244
+ try {
1245
+ this.#options.host.integration.write(taskId, payload)
1246
+ } catch (error) {
1247
+ this.#options.log?.('integration write failed for ' + taskId, error)
1248
+ return
1249
+ }
1250
+ const view = this.#cards.get(taskId)
1251
+ if (view !== undefined && merged.hubStatus !== undefined) view.hubStatus = merged.hubStatus
1252
+ }
1253
+
1254
+ #linked(): readonly TaskBoardLinkedTask[] {
1255
+ try {
1256
+ return this.#options.host.tasks.linked()
1257
+ } catch {
1258
+ return []
1259
+ }
1260
+ }
1261
+
1262
+ /**
1263
+ * The workspace a mirror card claimed for one member runs in.
1264
+ *
1265
+ * The mount's own setting wins, then the workspace the member's dsh-agents team
1266
+ * pins. An empty answer means the board could not start a card created for this
1267
+ * member, which is the state a claim must never enter.
1268
+ * @param agent - the member the issue would be claimed for.
1269
+ * @returns the workspace id, or an empty string when neither source names one.
1270
+ */
1271
+ #workspaceFor(agent: BoundAgent): string {
1272
+ const configured = (this.#options.settings().workspaceId ?? '').trim()
1273
+ if (configured !== '') return configured
1274
+ return (agent.workspaceId ?? '').trim()
1275
+ }
1276
+
1277
+ #agentFor(issue: HubIssue): BoundAgent | undefined {
1278
+ const hubAgentId = issue.assignee_agent_id
1279
+ if (hubAgentId === undefined) return undefined
1280
+ // Only a hub agent record this Host learned at registration may be executed
1281
+ // here: an id it cannot resolve is either another machine's agent or one the
1282
+ // hub refused in `conflicts`, and neither may run on this machine.
1283
+ return this.#hubAgents.get(hubAgentId)
1284
+ }
1285
+
1286
+ #hubAgentIdOf(memberId: string): string | undefined {
1287
+ for (const [hubId, agent] of this.#hubAgents) {
1288
+ if (agent.memberId === memberId) return hubId
1289
+ }
1290
+ return undefined
1291
+ }
1292
+
1293
+ /**
1294
+ * The problems the hub's registration answer leaves behind, one per clash.
1295
+ * @returns the visible lines the settings section renders.
1296
+ */
1297
+ #conflictProblems(): string[] {
1298
+ return [...this.#agentConflicts].map(([name, reason]) => name + ' is not registered: ' + reason)
1299
+ }
1300
+
1301
+ /**
1302
+ * Add one operator-visible problem line, once.
1303
+ *
1304
+ * A sweep repeats every few seconds, so appending the same line each pass would
1305
+ * bury every other problem under copies of itself.
1306
+ * @param line - the line to publish while its cause holds.
1307
+ */
1308
+ #raiseProblem(line: string): void {
1309
+ if (this.#problems.includes(line)) return
1310
+ this.#problems = [...this.#problems, line]
1311
+ }
1312
+
1313
+ /**
1314
+ * Drop one problem line whose cause is gone.
1315
+ * @param line - the line to stop publishing.
1316
+ */
1317
+ #dropProblem(line: string): void {
1318
+ if (!this.#problems.includes(line)) return
1319
+ this.#problems = this.#problems.filter(problem => problem !== line)
1320
+ }
1321
+
1322
+ #publish(): void {
1323
+ try {
1324
+ this.#options.host.publish(this.summary() as unknown as Record<string, unknown>)
1325
+ } catch (error) {
1326
+ this.#options.log?.('summary publish failed', error)
1327
+ }
1328
+ }
1329
+ }
1330
+
1331
+ /** Read one status string into the collaboration vocabulary. */
1332
+ function readStatus(raw: unknown): HubIssueStatus | undefined {
1333
+ switch (raw) {
1334
+ case 'todo':
1335
+ case 'assigned':
1336
+ case 'waiting_host':
1337
+ case 'running':
1338
+ case 'in_review':
1339
+ case 'done':
1340
+ case 'canceled':
1341
+ case 'failed':
1342
+ return raw
1343
+ default:
1344
+ return undefined
1345
+ }
1346
+ }
1347
+
1348
+ /** Read the agent records one registration answered with. */
1349
+ function readAgentRecords(registered: unknown): Array<{ id: string; name: string }> {
1350
+ if (typeof registered !== 'object' || registered === null) return []
1351
+ const agents = (registered as { agents?: unknown }).agents
1352
+ if (!Array.isArray(agents)) return []
1353
+ const records: Array<{ id: string; name: string }> = []
1354
+ for (const entry of agents) {
1355
+ if (typeof entry !== 'object' || entry === null) continue
1356
+ const record = entry as Record<string, unknown>
1357
+ if (typeof record.id === 'string' && typeof record.name === 'string') {
1358
+ records.push({ id: record.id, name: record.name })
1359
+ }
1360
+ }
1361
+ return records
1362
+ }
1363
+
1364
+ /** Read the agent names one registration answer reported as already owned elsewhere. */
1365
+ function readAgentConflicts(answer: unknown): Array<{ name: string; reason: string }> {
1366
+ if (typeof answer !== 'object' || answer === null) return []
1367
+ const conflicts = (answer as { conflicts?: unknown }).conflicts
1368
+ if (!Array.isArray(conflicts)) return []
1369
+ const rows: Array<{ name: string; reason: string }> = []
1370
+ for (const entry of conflicts) {
1371
+ if (typeof entry !== 'object' || entry === null) continue
1372
+ const row = entry as Record<string, unknown>
1373
+ if (typeof row.name !== 'string' || row.name === '') continue
1374
+ rows.push({ name: row.name, reason: typeof row.reason === 'string' ? row.reason : 'the hub reported a conflict' })
1375
+ }
1376
+ return rows
1377
+ }
1378
+
1379
+ /**
1380
+ * Whether one settlement refusal means the hub will never accept that body.
1381
+ *
1382
+ * Two families are final. `412 LEASE_EXPIRED` says the issue no longer carries the
1383
+ * attempt the write-back presents — a rework, a retry or another attempt replaced
1384
+ * it — so the same body can never match again. Every other deterministic 4xx says
1385
+ * the request itself is refused, which a later identical request does not change;
1386
+ * `408` and `429` are the two that mean "not now" rather than "not ever", so those
1387
+ * stay retryable along with transport failures and 5xx.
1388
+ * @param error - the refusal the settlement answered with.
1389
+ * @returns whether this settlement can never land.
1390
+ */
1391
+ function isSettlementFinal(error: unknown): boolean {
1392
+ if (!(error instanceof HubError)) return false
1393
+ if (error.code === 'LEASE_EXPIRED') return true
1394
+ if (error.status < 400 || error.status >= 500) return false
1395
+ // 401 means this Host's token is unknown or revoked, which the operator fixes
1396
+ // by pasting the right one; a 4xx without the hub's error envelope came from
1397
+ // something in front of the hub (a CDN or firewall), not from its gates.
1398
+ if (error.status === 401 || error.code === 'HTTP_' + String(error.status)) return false
1399
+ return error.status !== 408 && error.status !== 429
1400
+ }
1401
+
1402
+ /**
1403
+ * Whether one claim refusal means another attempt is already executing the issue.
1404
+ *
1405
+ * Two callers claiming the same issue is a race the hub resolves, not a fault:
1406
+ * the loser is told the lease belongs to another attempt (409 `LEASE_HELD_BY_OTHER`,
1407
+ * or the bare 409 of a claim that just lost). Recording that as a failure would
1408
+ * put a false error on a card that is running exactly as it should.
1409
+ * @param error - the refusal the claim answered with.
1410
+ * @returns whether this refusal is a lost race.
1411
+ */
1412
+ function isClaimHeldElsewhere(error: unknown): boolean {
1413
+ return error instanceof HubError && (error.status === 409 || error.code === 'LEASE_HELD_BY_OTHER')
1414
+ }
1415
+
1416
+ /** One error as the summary and the log carry it. */
1417
+ function describe(error: unknown): string {
1418
+ if (error instanceof HubError) return error.code + ': ' + error.message
1419
+ if (error instanceof Error) return error.message
1420
+ return String(error)
1421
+ }