@linxin666/dsh-client-ui-task-board-team 0.0.0-stage → 0.4.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.i18n.yaml +6 -0
- package/README.md +66 -2
- package/README.zh.md +67 -0
- package/cordis.patch.yml +14 -0
- package/icon.svg +3 -0
- package/lib/client.js +1117 -0
- package/lib/index.js +2968 -0
- package/lib/types/client/index.d.ts +58 -0
- package/lib/types/client/locales.d.ts +83 -0
- package/lib/types/client/optional-service.d.ts +22 -0
- package/lib/types/client/team/extension.d.ts +29 -0
- package/lib/types/client/team/sections.d.ts +38 -0
- package/lib/types/client/team/settings.d.ts +41 -0
- package/lib/types/client/team/summary.d.ts +34 -0
- package/lib/types/core/contract.d.ts +269 -0
- package/lib/types/core/hub-protocol.d.ts +175 -0
- package/lib/types/core/identity.d.ts +96 -0
- package/lib/types/core/mirror.d.ts +51 -0
- package/lib/types/core/question-report.d.ts +84 -0
- package/lib/types/core/settlement.d.ts +49 -0
- package/lib/types/core/task-record.d.ts +59 -0
- package/lib/types/core/timers.d.ts +20 -0
- package/lib/types/host/bindings.d.ts +92 -0
- package/lib/types/host/channel.d.ts +44 -0
- package/lib/types/host/credentials.d.ts +63 -0
- package/lib/types/host/extension.d.ts +57 -0
- package/lib/types/host/hub-client.d.ts +157 -0
- package/lib/types/host/questions.d.ts +105 -0
- package/lib/types/host/service.d.ts +209 -0
- package/lib/types/host/setup.d.ts +152 -0
- package/lib/types/host/tools.d.ts +19 -0
- package/lib/types/host/waterfall.d.ts +39 -0
- package/lib/types/index.d.ts +152 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +83 -3
- package/src/client/css-modules.d.ts +5 -0
- package/src/client/index.ts +139 -0
- package/src/client/locales.ts +154 -0
- package/src/client/optional-service.ts +30 -0
- package/src/client/team/extension.ts +185 -0
- package/src/client/team/sections.tsx +159 -0
- package/src/client/team/settings.tsx +242 -0
- package/src/client/team/summary.ts +156 -0
- package/src/client/team/team.module.css +122 -0
- package/src/core/contract.ts +326 -0
- package/src/core/hub-protocol.ts +217 -0
- package/src/core/identity.ts +193 -0
- package/src/core/mirror.ts +88 -0
- package/src/core/question-report.ts +144 -0
- package/src/core/settlement.ts +84 -0
- package/src/core/task-record.ts +65 -0
- package/src/core/timers.ts +34 -0
- package/src/host/bindings.ts +211 -0
- package/src/host/channel.ts +97 -0
- package/src/host/credentials.ts +147 -0
- package/src/host/extension.ts +197 -0
- package/src/host/hub-client.ts +287 -0
- package/src/host/questions.ts +275 -0
- package/src/host/service.ts +1421 -0
- package/src/host/setup.ts +259 -0
- package/src/host/tools.ts +70 -0
- package/src/host/waterfall.ts +51 -0
- package/src/index.ts +452 -0
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Host's REST client for one team-hub.
|
|
3
|
+
*
|
|
4
|
+
* Every call carries the Host Token and the protocol version, resolves its base
|
|
5
|
+
* URL and team at call time (so a settings edit reaches the next call without a
|
|
6
|
+
* remount), and turns the hub's unified error envelope into one diagnosable
|
|
7
|
+
* error carrying its code. The transport is injected: a deployment uses the
|
|
8
|
+
* global fetch, and the test suite drives a fake hub through the same seam.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-task-board-team/host/hub-client
|
|
11
|
+
*/
|
|
12
|
+
import {
|
|
13
|
+
HUB_API_PREFIX,
|
|
14
|
+
HUB_PROTOCOL_HEADER,
|
|
15
|
+
HUB_PROTOCOL_VERSION,
|
|
16
|
+
type HubActivity,
|
|
17
|
+
type HubAgentDefinition,
|
|
18
|
+
type HubAgentRecord,
|
|
19
|
+
type HubClaim,
|
|
20
|
+
type HubComment,
|
|
21
|
+
type HubIssue,
|
|
22
|
+
type HubQuestion,
|
|
23
|
+
type HubQuestionAnswer,
|
|
24
|
+
} from '../core/hub-protocol.ts'
|
|
25
|
+
import type { QuestionReportBody } from '../core/question-report.ts'
|
|
26
|
+
import type { SettleRequestBody } from '../core/settlement.ts'
|
|
27
|
+
|
|
28
|
+
/** One response as this client reads it. */
|
|
29
|
+
export interface HubResponse {
|
|
30
|
+
ok: boolean
|
|
31
|
+
status: number
|
|
32
|
+
text(): Promise<string>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The transport one deployment hands the client. */
|
|
36
|
+
export type HubFetch = (
|
|
37
|
+
url: string,
|
|
38
|
+
init: { method: string; headers: Record<string, string>; body?: string },
|
|
39
|
+
) => Promise<HubResponse>
|
|
40
|
+
|
|
41
|
+
/** One refusal the hub answered with. */
|
|
42
|
+
export class HubError extends Error {
|
|
43
|
+
/** Machine-readable code from the unified error envelope. */
|
|
44
|
+
readonly code: string
|
|
45
|
+
/** HTTP status the hub answered with. */
|
|
46
|
+
readonly status: number
|
|
47
|
+
|
|
48
|
+
constructor(code: string, message: string, status: number) {
|
|
49
|
+
super(message)
|
|
50
|
+
this.name = 'HubError'
|
|
51
|
+
this.code = code
|
|
52
|
+
this.status = status
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Read the code out of the hub's unified error envelope. */
|
|
57
|
+
function readErrorCode(body: unknown, status: number): { code: string; message: string } {
|
|
58
|
+
if (typeof body === 'object' && body !== null) {
|
|
59
|
+
const error = (body as { error?: unknown }).error
|
|
60
|
+
if (typeof error === 'object' && error !== null) {
|
|
61
|
+
const envelope = error as { code?: unknown; message?: unknown }
|
|
62
|
+
return {
|
|
63
|
+
code: typeof envelope.code === 'string' ? envelope.code : 'HTTP_' + String(status),
|
|
64
|
+
message: typeof envelope.message === 'string' ? envelope.message : 'the hub refused the request',
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return { code: 'HTTP_' + String(status), message: 'the hub refused the request' }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface HubClientOptions {
|
|
72
|
+
/** Hub base URL, read per call. */
|
|
73
|
+
hubUrl: () => string
|
|
74
|
+
/** Team id, read per call. */
|
|
75
|
+
teamId: () => string
|
|
76
|
+
/** Host Token, resolved per call from the credential store. */
|
|
77
|
+
token: () => Promise<string | undefined>
|
|
78
|
+
/** Transport; the global fetch when absent. */
|
|
79
|
+
fetch?: HubFetch
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The REST surface one Host speaks to one team. */
|
|
83
|
+
export class HubClient {
|
|
84
|
+
readonly #options: HubClientOptions
|
|
85
|
+
|
|
86
|
+
constructor(options: HubClientOptions) {
|
|
87
|
+
this.#options = options
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Whether this deployment can reach a hub at all (a URL and a token exist). */
|
|
91
|
+
async configured(): Promise<boolean> {
|
|
92
|
+
return this.#base().ok
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Register this Host and synchronize its agent definitions.
|
|
97
|
+
*
|
|
98
|
+
* The body is snake_case end to end (protocol amendment A4 point 1): the hub
|
|
99
|
+
* stores exactly these keys, so a camelCase member is a field it never sees.
|
|
100
|
+
* @param body - hostname, client version and the local agent definitions.
|
|
101
|
+
* @returns the registered host id, status and the agent records the hub now holds.
|
|
102
|
+
*/
|
|
103
|
+
async register(body: {
|
|
104
|
+
hostname: string
|
|
105
|
+
client_version: string
|
|
106
|
+
agents: readonly HubAgentDefinition[]
|
|
107
|
+
}): Promise<{ host_id: string; status: string; agents?: readonly HubAgentRecord[] }> {
|
|
108
|
+
return await this.#call('POST', '/hosts/register', body) as {
|
|
109
|
+
host_id: string
|
|
110
|
+
status: string
|
|
111
|
+
agents?: readonly HubAgentRecord[]
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Send one heartbeat.
|
|
117
|
+
* @param hostId - the registered host id.
|
|
118
|
+
* @returns the hub's server time.
|
|
119
|
+
*/
|
|
120
|
+
async heartbeat(hostId: string): Promise<{ server_time?: number }> {
|
|
121
|
+
return await this.#call('POST', `/hosts/${encodeURIComponent(hostId)}/heartbeat`) as { server_time?: number }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* List the issues this Host may claim.
|
|
126
|
+
* @param hostId - the registered host id.
|
|
127
|
+
* @returns the claimable issues.
|
|
128
|
+
*/
|
|
129
|
+
async listClaimableIssues(hostId: string): Promise<readonly HubIssue[]> {
|
|
130
|
+
const query = '?assignee_host_id=' + encodeURIComponent(hostId) + '&status=' + encodeURIComponent('assigned,waiting_host')
|
|
131
|
+
const body = await this.#call('GET', '/issues' + query) as { issues?: unknown }
|
|
132
|
+
return Array.isArray(body.issues) ? body.issues as HubIssue[] : []
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Claim one issue, or re-establish the attempt already running locally.
|
|
137
|
+
* @param issueId - the issue to claim.
|
|
138
|
+
* @param credentials - the previous attempt credentials, when this is a reconnect.
|
|
139
|
+
* @returns the lease.
|
|
140
|
+
*/
|
|
141
|
+
async claim(issueId: string, credentials: { execution_attempt_id?: string; lease_token?: string } = {}): Promise<HubClaim> {
|
|
142
|
+
return await this.#call('POST', `/issues/${encodeURIComponent(issueId)}/claim`, credentials) as unknown as HubClaim
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Extend one lease.
|
|
147
|
+
* @param issueId - the claimed issue.
|
|
148
|
+
* @param leaseToken - the lease credential.
|
|
149
|
+
* @returns the new expiry.
|
|
150
|
+
*/
|
|
151
|
+
async renewLease(issueId: string, leaseToken: string): Promise<{ lease_expires_at: number }> {
|
|
152
|
+
return await this.#call('POST', `/issues/${encodeURIComponent(issueId)}/renew-lease`, { lease_token: leaseToken }) as { lease_expires_at: number }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Write one settlement back.
|
|
157
|
+
* @param issueId - the settled issue.
|
|
158
|
+
* @param body - outcome, summary and error.
|
|
159
|
+
* @returns the collaboration status the hub moved to.
|
|
160
|
+
*/
|
|
161
|
+
async settle(issueId: string, body: SettleRequestBody): Promise<{ ok: boolean; status: string }> {
|
|
162
|
+
return await this.#call('POST', `/issues/${encodeURIComponent(issueId)}/settle`, body) as { ok: boolean; status: string }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Report one decision question.
|
|
167
|
+
* @param issueId - the issue it belongs to.
|
|
168
|
+
* @param body - the question text, options and multi-select flag.
|
|
169
|
+
* @returns the stored question.
|
|
170
|
+
*/
|
|
171
|
+
async createQuestion(issueId: string, body: QuestionReportBody): Promise<HubQuestion> {
|
|
172
|
+
const response = await this.#call('POST', `/issues/${encodeURIComponent(issueId)}/questions`, body) as { question?: HubQuestion }
|
|
173
|
+
if (response.question === undefined) throw new HubError('INVALID_RESPONSE', 'the hub returned no question', 200)
|
|
174
|
+
return response.question
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Withdraw one pending question after the local asker gave up.
|
|
179
|
+
* @param questionId - the question to withdraw.
|
|
180
|
+
*/
|
|
181
|
+
async withdrawQuestion(questionId: string): Promise<void> {
|
|
182
|
+
await this.#call('POST', '/questions/' + encodeURIComponent(questionId) + '/withdraw')
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Post one agent comment.
|
|
187
|
+
* @param issueId - the issue to comment on.
|
|
188
|
+
* @param body - the content and the agent identity that wrote it.
|
|
189
|
+
* @returns the stored comment.
|
|
190
|
+
*/
|
|
191
|
+
async createComment(issueId: string, body: { content: string; author_type: 'agent'; author_agent_id: string }): Promise<HubComment> {
|
|
192
|
+
const response = await this.#call('POST', `/issues/${encodeURIComponent(issueId)}/comments`, body) as { comment?: HubComment }
|
|
193
|
+
if (response.comment === undefined) throw new HubError('INVALID_RESPONSE', 'the hub returned no comment', 200)
|
|
194
|
+
return response.comment
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Read one issue's comment thread.
|
|
199
|
+
* @param issueId - the issue to read.
|
|
200
|
+
* @returns the comments, oldest first.
|
|
201
|
+
*/
|
|
202
|
+
async comments(issueId: string): Promise<readonly HubComment[]> {
|
|
203
|
+
const body = await this.#call('GET', `/issues/${encodeURIComponent(issueId)}/comments`) as { comments?: unknown }
|
|
204
|
+
return Array.isArray(body.comments) ? body.comments as HubComment[] : []
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** The base URL and team, or the reason there is none. */
|
|
208
|
+
#base(): { ok: true; url: string } | { ok: false } {
|
|
209
|
+
const raw = this.#options.hubUrl().trim()
|
|
210
|
+
const team = this.#options.teamId().trim()
|
|
211
|
+
if (raw === '' || team === '') return { ok: false }
|
|
212
|
+
return { ok: true, url: raw.replace(/\/+$/, '') + HUB_API_PREFIX + '/teams/' + encodeURIComponent(team) }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async #call(method: string, path: string, body?: unknown): Promise<Record<string, unknown>> {
|
|
216
|
+
const base = this.#base()
|
|
217
|
+
if (!base.ok) throw new HubError('NOT_CONFIGURED', 'the team hub URL and team id are not configured', 0)
|
|
218
|
+
const token = await this.#options.token()
|
|
219
|
+
if (token === undefined || token === '') throw new HubError('UNAUTHORIZED', 'no Host Token is configured', 401)
|
|
220
|
+
const headers: Record<string, string> = {
|
|
221
|
+
authorization: 'Bearer ' + token,
|
|
222
|
+
[HUB_PROTOCOL_HEADER]: HUB_PROTOCOL_VERSION,
|
|
223
|
+
accept: 'application/json',
|
|
224
|
+
// The frozen samples declare it on every Host call, body or not
|
|
225
|
+
// (protocol amendment A4 point 9), so it is never conditional here.
|
|
226
|
+
'content-type': 'application/json',
|
|
227
|
+
}
|
|
228
|
+
const response = await this.#fetch()(
|
|
229
|
+
base.url + path,
|
|
230
|
+
{ method, headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }) },
|
|
231
|
+
)
|
|
232
|
+
const text = await response.text()
|
|
233
|
+
let parsed: unknown
|
|
234
|
+
try {
|
|
235
|
+
parsed = text === '' ? {} : JSON.parse(text)
|
|
236
|
+
} catch {
|
|
237
|
+
parsed = undefined
|
|
238
|
+
}
|
|
239
|
+
if (!response.ok) {
|
|
240
|
+
const { code, message } = readErrorCode(parsed, response.status)
|
|
241
|
+
throw new HubError(code, message, response.status)
|
|
242
|
+
}
|
|
243
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
244
|
+
throw new HubError('INVALID_RESPONSE', 'the hub returned a body this client cannot read', response.status)
|
|
245
|
+
}
|
|
246
|
+
return parsed as Record<string, unknown>
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
#fetch(): HubFetch {
|
|
250
|
+
const injected = this.#options.fetch
|
|
251
|
+
if (injected !== undefined) return injected
|
|
252
|
+
return async (url, init) => {
|
|
253
|
+
const response = await fetch(url, init)
|
|
254
|
+
return {
|
|
255
|
+
ok: response.ok,
|
|
256
|
+
status: response.status,
|
|
257
|
+
text: async () => await response.text(),
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** The activity entry one status change appends, as the browser renders it. */
|
|
264
|
+
export interface ActivityEntry {
|
|
265
|
+
id: string
|
|
266
|
+
type: string
|
|
267
|
+
text: string
|
|
268
|
+
createdAt: number
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Project one hub activity row into the shape the summary carries.
|
|
273
|
+
*
|
|
274
|
+
* The wire carries the payload as a JSON object (its `payload_json` column is a
|
|
275
|
+
* D1 storage form only), so the rendered text is this Host's own rendering of
|
|
276
|
+
* that object rather than a serialized column.
|
|
277
|
+
* @param activity - the row the hub broadcast or served.
|
|
278
|
+
* @returns the entry the browser renders.
|
|
279
|
+
*/
|
|
280
|
+
export function projectActivity(activity: HubActivity): ActivityEntry {
|
|
281
|
+
return {
|
|
282
|
+
id: activity.id,
|
|
283
|
+
type: activity.activity_type,
|
|
284
|
+
text: Object.keys(activity.payload).length === 0 ? activity.activity_type : JSON.stringify(activity.payload),
|
|
285
|
+
createdAt: activity.created_at,
|
|
286
|
+
}
|
|
287
|
+
}
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decision questions asked by a team card's session, routed through the hub.
|
|
3
|
+
*
|
|
4
|
+
* The Host's question waterfall is shared by every answerer on the machine, so
|
|
5
|
+
* this module claims exactly one case and delegates everything else: a request
|
|
6
|
+
* whose `agent.id` — the session id, since the event carries no session field —
|
|
7
|
+
* is the session of a card this extension mirrors. Every other conversation on
|
|
8
|
+
* the machine keeps its own answerer, and the local surface stays available for
|
|
9
|
+
* a claimed question because the claim holds the ask while the hub's reviewers
|
|
10
|
+
* answer it.
|
|
11
|
+
*
|
|
12
|
+
* Tool permission approvals are NOT part of this module and have no listener at
|
|
13
|
+
* all: `approval/request` belongs to the local machine's security domain
|
|
14
|
+
* (`team-hub/PROTOCOL.md` section 6), so this provider never puts one on the
|
|
15
|
+
* wire.
|
|
16
|
+
*
|
|
17
|
+
* @module dsh-task-board-team/host/questions
|
|
18
|
+
*/
|
|
19
|
+
import type { HubClient } from './hub-client.ts'
|
|
20
|
+
import { HubError } from './hub-client.ts'
|
|
21
|
+
import {
|
|
22
|
+
answerToHost,
|
|
23
|
+
buildQuestionReport,
|
|
24
|
+
isReportable,
|
|
25
|
+
unansweredAnswer,
|
|
26
|
+
type QuestionAnswer,
|
|
27
|
+
type QuestionItem,
|
|
28
|
+
type QuestionRequestShape,
|
|
29
|
+
} from '../core/question-report.ts'
|
|
30
|
+
import { findLinkedTask, findTaskBySession, readTaskIssueLink } from '../core/identity.ts'
|
|
31
|
+
import type { TaskBoardExtensionHost, TaskBoardLinkedTask } from '../core/contract.ts'
|
|
32
|
+
import type { HostTimerFace } from '../core/timers.ts'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Default local fallback wait, in milliseconds.
|
|
36
|
+
*
|
|
37
|
+
* Zero means "no local cap": the claim holds the ask until the hub settles it
|
|
38
|
+
* (answered, expired or withdrawn), which is what the acceptance loop needs — a
|
|
39
|
+
* member answering from a lock-screen push may take far longer than any fixed
|
|
40
|
+
* window. A deployment that wants the local surface back sooner turns the
|
|
41
|
+
* fallback on and names its own number of minutes.
|
|
42
|
+
*/
|
|
43
|
+
export const DEFAULT_QUESTION_WAIT_MS = 0
|
|
44
|
+
|
|
45
|
+
/** One question this Host reported and is still waiting on. */
|
|
46
|
+
export interface PendingQuestionView {
|
|
47
|
+
/** Local claim id. */
|
|
48
|
+
id: string
|
|
49
|
+
/** Card the asking session belongs to. */
|
|
50
|
+
taskId: string
|
|
51
|
+
/** Issue the question belongs to. */
|
|
52
|
+
issueId: string
|
|
53
|
+
/** The question text, as the browser renders it. */
|
|
54
|
+
question: string
|
|
55
|
+
/** Hub question id, once the hub stored it. */
|
|
56
|
+
hubQuestionId?: string
|
|
57
|
+
/** Instant the question was reported (ms epoch). */
|
|
58
|
+
askedAt: number
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface PendingQuestion extends PendingQuestionView {
|
|
62
|
+
item: QuestionItem
|
|
63
|
+
settle(answer: QuestionAnswer | undefined): void
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface QuestionRouterOptions {
|
|
67
|
+
hub: HubClient
|
|
68
|
+
host: TaskBoardExtensionHost
|
|
69
|
+
/** Every card this extension mirrors; read live so a deleted card is not answered. */
|
|
70
|
+
linked: () => readonly TaskBoardLinkedTask[]
|
|
71
|
+
timers: HostTimerFace
|
|
72
|
+
now: () => number
|
|
73
|
+
/** Mint the local claim id. */
|
|
74
|
+
uuid: () => string
|
|
75
|
+
/** Called whenever the pending set changes, so the summary can republish. */
|
|
76
|
+
onChange?: () => void
|
|
77
|
+
/**
|
|
78
|
+
* Local fallback wait for one claim, read per question.
|
|
79
|
+
*
|
|
80
|
+
* Absent or zero means the claim waits for the hub's own terminal state; a
|
|
81
|
+
* positive number withdraws the question after that long and hands the ask back
|
|
82
|
+
* to the next answerer.
|
|
83
|
+
*/
|
|
84
|
+
fallbackWaitMs?: () => number | undefined
|
|
85
|
+
log?: (message: string, detail?: unknown) => void
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The provider's claims on the Host's process-wide question waterfall.
|
|
90
|
+
*/
|
|
91
|
+
export class QuestionRouter {
|
|
92
|
+
readonly #options: QuestionRouterOptions
|
|
93
|
+
readonly #pending = new Map<string, PendingQuestion>()
|
|
94
|
+
|
|
95
|
+
constructor(options: QuestionRouterOptions) {
|
|
96
|
+
this.#options = options
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Every question this Host is still waiting on, oldest claim first. */
|
|
100
|
+
pending(): readonly PendingQuestionView[] {
|
|
101
|
+
return [...this.#pending.values()].map(entry => ({
|
|
102
|
+
id: entry.id,
|
|
103
|
+
taskId: entry.taskId,
|
|
104
|
+
issueId: entry.issueId,
|
|
105
|
+
question: entry.question,
|
|
106
|
+
...(entry.hubQuestionId === undefined ? {} : { hubQuestionId: entry.hubQuestionId }),
|
|
107
|
+
askedAt: entry.askedAt,
|
|
108
|
+
}))
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The waterfall body: claim one question that belongs to a team card, and
|
|
113
|
+
* delegate every other request to the next answerer.
|
|
114
|
+
* @param request - the pending question batch.
|
|
115
|
+
* @param next - the rest of the answerer chain.
|
|
116
|
+
* @returns the team's answer, or whatever the next answerer says.
|
|
117
|
+
*/
|
|
118
|
+
async request(request: QuestionRequestShape, next: () => Promise<QuestionAnswer>): Promise<QuestionAnswer> {
|
|
119
|
+
const sessionId = request.agent?.id
|
|
120
|
+
if (sessionId === undefined) return await next()
|
|
121
|
+
// The claim is scoped to a mirrored card's own session: a question asked in
|
|
122
|
+
// any other conversation on this machine is none of this provider's business.
|
|
123
|
+
const task = findTaskBySession(this.#options.linked(), sessionId)
|
|
124
|
+
if (task === undefined) return await next()
|
|
125
|
+
const link = readTaskIssueLink(task)
|
|
126
|
+
if (link === undefined) return await next()
|
|
127
|
+
const item = request.questions[0]
|
|
128
|
+
if (item === undefined || !isReportable(item)) return await next()
|
|
129
|
+
|
|
130
|
+
const id = this.#options.uuid()
|
|
131
|
+
let settle: (answer: QuestionAnswer | undefined) => void = () => undefined
|
|
132
|
+
const answer = new Promise<QuestionAnswer | undefined>(resolve => { settle = resolve })
|
|
133
|
+
let questionId: string
|
|
134
|
+
try {
|
|
135
|
+
const question = await this.#options.hub.createQuestion(link.issueId, buildQuestionReport(item))
|
|
136
|
+
questionId = question.id
|
|
137
|
+
} catch (error) {
|
|
138
|
+
// A hub that cannot take the question must not take the agent with it: the
|
|
139
|
+
// local surface answers, exactly as it did before this provider existed.
|
|
140
|
+
this.#options.log?.('question report failed', error)
|
|
141
|
+
return await next()
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const entry: PendingQuestion = {
|
|
145
|
+
id,
|
|
146
|
+
taskId: task.id,
|
|
147
|
+
issueId: link.issueId,
|
|
148
|
+
question: item.question,
|
|
149
|
+
hubQuestionId: questionId,
|
|
150
|
+
askedAt: this.#options.now(),
|
|
151
|
+
item,
|
|
152
|
+
settle,
|
|
153
|
+
}
|
|
154
|
+
this.#pending.set(id, entry)
|
|
155
|
+
this.#options.onChange?.()
|
|
156
|
+
|
|
157
|
+
const waitMs = this.#options.fallbackWaitMs?.()
|
|
158
|
+
const cancelWait = waitMs === undefined || waitMs <= 0
|
|
159
|
+
? (): void => {}
|
|
160
|
+
: this.#options.timers.timeout(() => { void this.#expireLocally(id) }, waitMs)
|
|
161
|
+
const abort = (): void => { void this.#withdraw(id) }
|
|
162
|
+
request.signal?.addEventListener('abort', abort, { once: true })
|
|
163
|
+
|
|
164
|
+
const settled = await answer
|
|
165
|
+
cancelWait()
|
|
166
|
+
request.signal?.removeEventListener('abort', abort)
|
|
167
|
+
return settled ?? await next()
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Settle one question with a team answer.
|
|
172
|
+
* @param payload - the hub's `question.answered` payload.
|
|
173
|
+
* @returns whether this Host was waiting on that question.
|
|
174
|
+
*/
|
|
175
|
+
answered(payload: Record<string, unknown>): boolean {
|
|
176
|
+
const questionId = typeof payload.question_id === 'string' ? payload.question_id : undefined
|
|
177
|
+
if (questionId === undefined) return false
|
|
178
|
+
const entry = this.#byHubId(questionId)
|
|
179
|
+
if (entry === undefined) return false
|
|
180
|
+
const answer = readAnswerPayload(payload.answer)
|
|
181
|
+
this.#settle(entry.id, answerToHost(entry.item, answer))
|
|
182
|
+
return true
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* End one question as unanswered, the way the hub's expiry does.
|
|
187
|
+
* @param payload - the hub's `question.expired` payload.
|
|
188
|
+
* @returns whether this Host was waiting on that question.
|
|
189
|
+
*/
|
|
190
|
+
expired(payload: Record<string, unknown>): boolean {
|
|
191
|
+
const questionId = typeof payload.question_id === 'string' ? payload.question_id : undefined
|
|
192
|
+
if (questionId === undefined) return false
|
|
193
|
+
const entry = this.#byHubId(questionId)
|
|
194
|
+
if (entry === undefined) return false
|
|
195
|
+
this.#settle(entry.id, unansweredAnswer())
|
|
196
|
+
return true
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Drop one question the hub reported withdrawn.
|
|
201
|
+
* @param payload - the hub's `question.withdrawn` payload.
|
|
202
|
+
* @returns whether this Host was waiting on that question.
|
|
203
|
+
*/
|
|
204
|
+
withdrawn(payload: Record<string, unknown>): boolean {
|
|
205
|
+
const questionId = typeof payload.question_id === 'string' ? payload.question_id : undefined
|
|
206
|
+
if (questionId === undefined) return false
|
|
207
|
+
const entry = this.#byHubId(questionId)
|
|
208
|
+
if (entry === undefined) return false
|
|
209
|
+
this.#settle(entry.id, unansweredAnswer())
|
|
210
|
+
return true
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Drop every claim, delegating each to the next answerer. */
|
|
214
|
+
dispose(): void {
|
|
215
|
+
for (const id of [...this.#pending.keys()]) this.#settle(id, undefined)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The local ask was cancelled: tell the hub, then let the next answerer take it.
|
|
220
|
+
*/
|
|
221
|
+
async #withdraw(id: string): Promise<void> {
|
|
222
|
+
const entry = this.#pending.get(id)
|
|
223
|
+
if (entry === undefined) return
|
|
224
|
+
if (entry.hubQuestionId !== undefined) {
|
|
225
|
+
try {
|
|
226
|
+
await this.#options.hub.withdrawQuestion(entry.hubQuestionId)
|
|
227
|
+
} catch (error) {
|
|
228
|
+
// A question the hub already closed needs no second close; a hub that
|
|
229
|
+
// is down costs the dismissal, not the agent's turn.
|
|
230
|
+
if (!(error instanceof HubError) || error.code !== 'QUESTION_NOT_PENDING') {
|
|
231
|
+
this.#options.log?.('question withdraw failed', error)
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
this.#settle(id, undefined)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** The local wait window ended: withdraw on the hub and return to the machine. */
|
|
239
|
+
async #expireLocally(id: string): Promise<void> {
|
|
240
|
+
await this.#withdraw(id)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
#byHubId(questionId: string): PendingQuestion | undefined {
|
|
244
|
+
for (const entry of this.#pending.values()) {
|
|
245
|
+
if (entry.hubQuestionId === questionId) return entry
|
|
246
|
+
}
|
|
247
|
+
return undefined
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
#settle(id: string, answer: QuestionAnswer | undefined): boolean {
|
|
251
|
+
const entry = this.#pending.get(id)
|
|
252
|
+
if (entry === undefined) return false
|
|
253
|
+
this.#pending.delete(id)
|
|
254
|
+
entry.settle(answer)
|
|
255
|
+
this.#options.onChange?.()
|
|
256
|
+
return true
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Read the hub's answer member into the shape the mapping needs.
|
|
262
|
+
*
|
|
263
|
+
* Protocol amendment A2 fixes this shape as `{ selected: string[], custom?: string }`
|
|
264
|
+
* (or null while a question is still unanswered), so a null answer reads as an
|
|
265
|
+
* empty selection instead of being mistaken for a custom-only reply.
|
|
266
|
+
*/
|
|
267
|
+
function readAnswerPayload(raw: unknown): { selected: readonly string[]; custom?: string } {
|
|
268
|
+
if (typeof raw !== 'object' || raw === null) return { selected: [] }
|
|
269
|
+
const answer = raw as Record<string, unknown>
|
|
270
|
+
const selected = Array.isArray(answer.selected)
|
|
271
|
+
? answer.selected.filter((value): value is string => typeof value === 'string')
|
|
272
|
+
: []
|
|
273
|
+
const custom = typeof answer.custom === 'string' ? answer.custom : undefined
|
|
274
|
+
return { selected, ...(custom === undefined ? {} : { custom }) }
|
|
275
|
+
}
|