dsh-marker 0.0.0-stage → 0.1.2
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/README.md +44 -2
- package/client.js +609 -0
- package/cordis.patch.yml +5 -0
- package/docs/DETAIL.md +45 -0
- package/icon.svg +8 -0
- package/index.js +204 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +59 -4
- package/src/bridge.js +494 -0
- package/src/discovery.js +428 -0
- package/src/endpoint.js +166 -0
- package/src/focus.js +204 -0
- package/src/locator.js +317 -0
- package/src/mentions.js +120 -0
- package/src/paths.js +52 -0
- package/src/presentation.js +255 -0
- package/src/protocol.js +610 -0
- package/src/queue.js +278 -0
- package/src/sessions.js +240 -0
- package/src/store.js +267 -0
- package/src/tools.js +392 -0
package/src/queue.js
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pending mention deliveries.
|
|
3
|
+
*
|
|
4
|
+
* An annotation carries `routing.sessionId` when the user picked a target in
|
|
5
|
+
* the overlay. The Host cannot write that Session's composer — drafts live in
|
|
6
|
+
* the browser — so the delivery is queued here, durably, and the Web Client
|
|
7
|
+
* appends it the next time that Session is open. Nothing is sent, no turn is
|
|
8
|
+
* started: the user decides when the message leaves.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-marker/queue
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { readFile, rename, writeFile } from 'node:fs/promises'
|
|
14
|
+
import { join } from 'node:path'
|
|
15
|
+
|
|
16
|
+
import { QUEUE_ACK_PATH, QUEUE_PATH } from './protocol.js'
|
|
17
|
+
|
|
18
|
+
/** A queue is a hand-off, not a backlog: an unsent pile helps nobody. */
|
|
19
|
+
const MAX_ENTRIES = 50
|
|
20
|
+
|
|
21
|
+
/** Acknowledged ids are the whole request; anything larger is not our client. */
|
|
22
|
+
const MAX_BODY_BYTES = 4_096
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @typedef {object} QueuedMention
|
|
26
|
+
* @property {string} id Annotation id, also the entry identity.
|
|
27
|
+
* @property {string} sessionId Target Session.
|
|
28
|
+
* @property {string} mention Canonical mention text to append to the draft.
|
|
29
|
+
* @property {string} label Chip label the mention carries.
|
|
30
|
+
* @property {number} createdAt Unix epoch milliseconds.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {object} options
|
|
35
|
+
* @param {string} options.dir Directory holding the annotations log.
|
|
36
|
+
* @param {{ warn?: (...args: any[]) => void }} [options.logger]
|
|
37
|
+
* @param {string} [options.file]
|
|
38
|
+
*/
|
|
39
|
+
export function createMentionQueue({ dir, logger, file = 'pending-mentions.json' }) {
|
|
40
|
+
const path = join(dir, file)
|
|
41
|
+
/** @type {QueuedMention[]} */
|
|
42
|
+
let entries = []
|
|
43
|
+
let writing = null
|
|
44
|
+
|
|
45
|
+
async function load() {
|
|
46
|
+
try {
|
|
47
|
+
const raw = await readFile(path, 'utf8')
|
|
48
|
+
const parsed = JSON.parse(raw)
|
|
49
|
+
entries = (Array.isArray(parsed) ? parsed : []).filter(isEntry).slice(-MAX_ENTRIES)
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (error?.code !== 'ENOENT') logger?.warn?.(`annotations: pending queue unreadable (${messageOf(error)})`)
|
|
52
|
+
entries = []
|
|
53
|
+
}
|
|
54
|
+
return entries.length
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Queue one delivery. Re-enqueuing an id replaces its entry, so a replayed
|
|
59
|
+
* offline submission cannot pile up duplicates.
|
|
60
|
+
* @param {{ id: string, sessionId: string, mention: string, label?: string }} input
|
|
61
|
+
* @returns {Promise<void>}
|
|
62
|
+
*/
|
|
63
|
+
async function enqueue(input) {
|
|
64
|
+
if (!isUsable({ ...input, createdAt: Date.now() })) return
|
|
65
|
+
const entry = {
|
|
66
|
+
id: String(input.id),
|
|
67
|
+
sessionId: String(input.sessionId),
|
|
68
|
+
mention: String(input.mention),
|
|
69
|
+
label: typeof input.label === 'string' ? input.label : '',
|
|
70
|
+
createdAt: Date.now(),
|
|
71
|
+
}
|
|
72
|
+
entries = entries.filter((item) => item.id !== entry.id)
|
|
73
|
+
entries.push(entry)
|
|
74
|
+
if (entries.length > MAX_ENTRIES) entries = entries.slice(-MAX_ENTRIES)
|
|
75
|
+
await save()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Entries waiting for one Session, oldest first.
|
|
80
|
+
* @param {string} sessionId
|
|
81
|
+
* @returns {QueuedMention[]}
|
|
82
|
+
*/
|
|
83
|
+
function list(sessionId) {
|
|
84
|
+
return entries.filter((entry) => entry.sessionId === sessionId)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** @returns {QueuedMention[]} */
|
|
88
|
+
function all() {
|
|
89
|
+
return [...entries]
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Drop acknowledged entries.
|
|
94
|
+
* @param {readonly string[]} ids
|
|
95
|
+
* @returns {Promise<number>} how many were actually queued
|
|
96
|
+
*/
|
|
97
|
+
async function ack(ids) {
|
|
98
|
+
const wanted = new Set(ids.map(String))
|
|
99
|
+
const before = entries.length
|
|
100
|
+
entries = entries.filter((entry) => !wanted.has(entry.id))
|
|
101
|
+
const removed = before - entries.length
|
|
102
|
+
if (removed > 0) await save()
|
|
103
|
+
return removed
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Drop entries whose annotation no longer exists, without a client round trip. */
|
|
107
|
+
async function prune(exists) {
|
|
108
|
+
const before = entries.length
|
|
109
|
+
entries = entries.filter((entry) => exists(entry.id))
|
|
110
|
+
if (before !== entries.length) await save()
|
|
111
|
+
return before - entries.length
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function save() {
|
|
115
|
+
// Serialize writes: two overlapping renames would interleave.
|
|
116
|
+
writing = (writing ?? Promise.resolve()).then(async () => {
|
|
117
|
+
const temp = `${path}.tmp`
|
|
118
|
+
await writeFile(temp, `${JSON.stringify(entries, null, 2)}\n`, 'utf8')
|
|
119
|
+
await rename(temp, path)
|
|
120
|
+
})
|
|
121
|
+
return writing
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return { load, enqueue, list, all, ack, prune, flush: () => writing ?? Promise.resolve(), path }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Serve the queue to the Web Client that owns the target composers.
|
|
129
|
+
*
|
|
130
|
+
* The bridge token cannot gate this: the page is a different trust anchor from
|
|
131
|
+
* the extension, and handing it the extension's token would be worse than the
|
|
132
|
+
* route. What gates it is the browser's own same-origin header — the Client is
|
|
133
|
+
* the page this Host serves, and a cross-site request cannot claim otherwise.
|
|
134
|
+
*
|
|
135
|
+
* @param {any} webServer
|
|
136
|
+
* @param {object} options
|
|
137
|
+
* @param {ReturnType<typeof createMentionQueue>} options.queue
|
|
138
|
+
* @param {string} [options.path]
|
|
139
|
+
* @param {string} [options.ackPath]
|
|
140
|
+
* @returns {() => void} disposer
|
|
141
|
+
*/
|
|
142
|
+
export function registerQueueRoutes(webServer, { queue, path = QUEUE_PATH, ackPath = QUEUE_ACK_PATH }) {
|
|
143
|
+
const baseHeaders = {
|
|
144
|
+
'content-type': 'application/json; charset=utf-8',
|
|
145
|
+
'cache-control': 'no-store',
|
|
146
|
+
vary: 'sec-fetch-site',
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const disposeRead = webServer.register({
|
|
150
|
+
kind: 'exact',
|
|
151
|
+
path,
|
|
152
|
+
auth: 'anonymous',
|
|
153
|
+
handler: (request, response) => {
|
|
154
|
+
/** @param {number} status @param {any} payload */
|
|
155
|
+
const send = (status, payload) => {
|
|
156
|
+
response.writeHead(status, baseHeaders)
|
|
157
|
+
response.end(request.method === 'HEAD' ? undefined : JSON.stringify(payload))
|
|
158
|
+
}
|
|
159
|
+
if (!sameOrigin(request)) {
|
|
160
|
+
send(403, { ok: false, error: 'origin' })
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
164
|
+
send(405, { ok: false, error: 'method' })
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
const url = new URL(request.url ?? path, 'http://127.0.0.1')
|
|
168
|
+
const sessionId = url.searchParams.get('session') ?? ''
|
|
169
|
+
if (sessionId === '') {
|
|
170
|
+
send(400, { ok: false, error: 'session' })
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
send(200, { ok: true, items: queue.list(sessionId).map(toWire) })
|
|
174
|
+
},
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
const disposeAck = webServer.register({
|
|
178
|
+
kind: 'exact',
|
|
179
|
+
path: ackPath,
|
|
180
|
+
auth: 'anonymous',
|
|
181
|
+
handler: (request, response) => {
|
|
182
|
+
/** @param {number} status @param {any} payload */
|
|
183
|
+
const send = (status, payload) => {
|
|
184
|
+
response.writeHead(status, baseHeaders)
|
|
185
|
+
response.end(JSON.stringify(payload))
|
|
186
|
+
}
|
|
187
|
+
if (!sameOrigin(request)) {
|
|
188
|
+
send(403, { ok: false, error: 'origin' })
|
|
189
|
+
return
|
|
190
|
+
}
|
|
191
|
+
if (request.method !== 'POST') {
|
|
192
|
+
send(405, { ok: false, error: 'method' })
|
|
193
|
+
return
|
|
194
|
+
}
|
|
195
|
+
readJson(request)
|
|
196
|
+
.then(async (body) => {
|
|
197
|
+
const ids = Array.isArray(body?.ids) ? body.ids.filter((id) => typeof id === 'string') : []
|
|
198
|
+
if (ids.length === 0) {
|
|
199
|
+
send(400, { ok: false, error: 'ids' })
|
|
200
|
+
return
|
|
201
|
+
}
|
|
202
|
+
send(200, { ok: true, removed: await queue.ack(ids) })
|
|
203
|
+
})
|
|
204
|
+
.catch((error) => {
|
|
205
|
+
send(400, { ok: false, error: 'body', message: messageOf(error) })
|
|
206
|
+
})
|
|
207
|
+
},
|
|
208
|
+
})
|
|
209
|
+
|
|
210
|
+
return () => {
|
|
211
|
+
disposeRead()
|
|
212
|
+
disposeAck()
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* The GUI is served by this Host, so the browser marks its own requests
|
|
218
|
+
* `same-origin`. A request without the header is not the page (and a page that
|
|
219
|
+
* omits it cannot use this route at all — an honest 403 beats a guess).
|
|
220
|
+
* @param {any} request
|
|
221
|
+
*/
|
|
222
|
+
function sameOrigin(request) {
|
|
223
|
+
return request.headers?.['sec-fetch-site'] === 'same-origin'
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** @param {any} request */
|
|
227
|
+
function readJson(request) {
|
|
228
|
+
return new Promise((resolve, reject) => {
|
|
229
|
+
let size = 0
|
|
230
|
+
const chunks = []
|
|
231
|
+
request.on('data', (chunk) => {
|
|
232
|
+
size += chunk.length
|
|
233
|
+
if (size > MAX_BODY_BYTES) {
|
|
234
|
+
reject(new Error('body too large'))
|
|
235
|
+
request.destroy()
|
|
236
|
+
return
|
|
237
|
+
}
|
|
238
|
+
chunks.push(chunk)
|
|
239
|
+
})
|
|
240
|
+
request.on('end', () => {
|
|
241
|
+
try {
|
|
242
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
|
|
243
|
+
} catch (error) {
|
|
244
|
+
reject(error)
|
|
245
|
+
}
|
|
246
|
+
})
|
|
247
|
+
request.on('error', reject)
|
|
248
|
+
})
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** @param {QueuedMention} entry */
|
|
252
|
+
function toWire(entry) {
|
|
253
|
+
return { id: entry.id, mention: entry.mention, label: entry.label, createdAt: entry.createdAt }
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** @param {unknown} value */
|
|
257
|
+
function isEntry(value) {
|
|
258
|
+
return isUsable(value) && typeof value.label === 'string' && typeof value.createdAt === 'number'
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** @param {any} value */
|
|
262
|
+
function isUsable(value) {
|
|
263
|
+
return (
|
|
264
|
+
value !== null &&
|
|
265
|
+
typeof value === 'object' &&
|
|
266
|
+
typeof value.id === 'string' &&
|
|
267
|
+
value.id !== '' &&
|
|
268
|
+
typeof value.sessionId === 'string' &&
|
|
269
|
+
value.sessionId !== '' &&
|
|
270
|
+
typeof value.mention === 'string' &&
|
|
271
|
+
value.mention !== ''
|
|
272
|
+
)
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** @param {unknown} error */
|
|
276
|
+
function messageOf(error) {
|
|
277
|
+
return error instanceof Error ? error.message : String(error)
|
|
278
|
+
}
|
package/src/sessions.js
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session catalog for the overlay's target picker.
|
|
3
|
+
*
|
|
4
|
+
* The picker answers one question — "which conversation does this annotation
|
|
5
|
+
* belong to?" — so the catalog is a flat list ordered by last activity, with
|
|
6
|
+
* the workspace carried as a detail line rather than a grouping level. Every
|
|
7
|
+
* Session the Host knows is a candidate, including ones the browser has never
|
|
8
|
+
* shown; there is no per-Session state here, only reads.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-marker/sessions
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { LIMITS, SESSIONS_PATH } from './protocol.js'
|
|
14
|
+
|
|
15
|
+
/** Session titles are optional: an empty catalog row still lists. */
|
|
16
|
+
const TITLE_TIMEOUT_MS = 4_000
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @typedef {object} SessionCatalogItem
|
|
20
|
+
* @property {string} id Session identity used by the reference mention.
|
|
21
|
+
* @property {string} title Latest log-backed title, or an empty string.
|
|
22
|
+
* @property {number} updatedAt Last activity in Unix epoch milliseconds.
|
|
23
|
+
* @property {boolean} running Whether a turn is in flight right now.
|
|
24
|
+
* @property {boolean} blank Whether the Session has no conversation yet.
|
|
25
|
+
* @property {boolean} agentAvailable Whether a live Agent currently owns it.
|
|
26
|
+
* @property {string | null} cwd Working directory the Host recorded.
|
|
27
|
+
* @property {{ id: string, title: string, path: string } | null} workspace Owning workspace, when one claims the Session.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {object} options
|
|
32
|
+
* @param {(name: string) => any} options.get Cordis service lookup for the mounting context.
|
|
33
|
+
* @param {{ warn?: (...args: any[]) => void }} [options.logger]
|
|
34
|
+
*/
|
|
35
|
+
export function createSessionCatalog({ get, logger }) {
|
|
36
|
+
/**
|
|
37
|
+
* @param {object} [options]
|
|
38
|
+
* @param {string} [options.query] Case-insensitive substring over title, id, cwd and workspace.
|
|
39
|
+
* @param {number} [options.limit]
|
|
40
|
+
* @param {boolean} [options.includeSubagents] Subagent Sessions are noise for a human picker; opt in to list them.
|
|
41
|
+
* @param {AbortSignal} [options.signal]
|
|
42
|
+
*/
|
|
43
|
+
async function list(options = {}) {
|
|
44
|
+
const controller = get('sessionController')
|
|
45
|
+
if (controller === undefined) throw new Error('the session controller is not mounted in this profile')
|
|
46
|
+
|
|
47
|
+
const limit = clamp(options.limit ?? 20, 1, LIMITS.sessionsLimit)
|
|
48
|
+
const signal = options.signal ?? AbortSignal.timeout(8_000)
|
|
49
|
+
const value = await controller.list({}, signal)
|
|
50
|
+
const summaries = (Array.isArray(value?.items) ? value.items : []).filter(
|
|
51
|
+
(row) => options.includeSubagents === true || row?.origin !== 'subagent',
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
const titles = await readTitles(
|
|
55
|
+
summaries.map((row) => row.sessionId),
|
|
56
|
+
signal,
|
|
57
|
+
)
|
|
58
|
+
const workspaces = workspaceIndex()
|
|
59
|
+
const needle = (options.query ?? '').trim().toLowerCase()
|
|
60
|
+
|
|
61
|
+
const items = summaries
|
|
62
|
+
.map((row) => describe(row, titles.get(row.sessionId), workspaces.get(row.sessionId)))
|
|
63
|
+
.filter((item) => needle === '' || matches(item, needle))
|
|
64
|
+
.sort((left, right) => right.updatedAt - left.updatedAt)
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
items: items.slice(0, limit),
|
|
68
|
+
/** Rows after filtering, before the limit. */
|
|
69
|
+
total: items.length,
|
|
70
|
+
truncated: items.length > limit,
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Titles live in a separate fold; a failure here must not hide the catalog.
|
|
76
|
+
* @param {string[]} ids
|
|
77
|
+
* @param {AbortSignal} outer
|
|
78
|
+
* @returns {Promise<Map<string, string>>}
|
|
79
|
+
*/
|
|
80
|
+
async function readTitles(ids, outer) {
|
|
81
|
+
const titles = new Map()
|
|
82
|
+
const query = get('sessionQuery')
|
|
83
|
+
if (query === undefined || ids.length === 0) return titles
|
|
84
|
+
|
|
85
|
+
const budget = AbortSignal.timeout(TITLE_TIMEOUT_MS)
|
|
86
|
+
try {
|
|
87
|
+
const results = await query.readTitleSnapshots(ids, AbortSignal.any([outer, budget]))
|
|
88
|
+
for (const [index, result] of (Array.isArray(results) ? results : []).entries()) {
|
|
89
|
+
// `{sessionId, status, value: {session, title?: SessionTitleSnapshot}}`;
|
|
90
|
+
// a rejected row carries only a reason and must not drop the others.
|
|
91
|
+
const title = result?.value?.title?.title ?? result?.title
|
|
92
|
+
if (typeof title !== 'string' || title === '') continue
|
|
93
|
+
const id = typeof result?.sessionId === 'string' ? result.sessionId : ids[index]
|
|
94
|
+
if (typeof id === 'string') titles.set(id, title)
|
|
95
|
+
}
|
|
96
|
+
} catch (error) {
|
|
97
|
+
logger?.warn?.(`annotations: session titles unavailable (${messageOf(error)})`)
|
|
98
|
+
}
|
|
99
|
+
return titles
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @returns {Map<string, { id: string, title: string, path: string }>} */
|
|
103
|
+
function workspaceIndex() {
|
|
104
|
+
const index = new Map()
|
|
105
|
+
const registry = get('workspaceRegistry')
|
|
106
|
+
if (registry === undefined) return index
|
|
107
|
+
try {
|
|
108
|
+
for (const workspace of registry.list()) {
|
|
109
|
+
const info = { id: workspace.id, title: workspace.title, path: workspace.path }
|
|
110
|
+
for (const sessionId of workspace.sessionIds ?? []) index.set(sessionId, info)
|
|
111
|
+
}
|
|
112
|
+
} catch (error) {
|
|
113
|
+
logger?.warn?.(`annotations: workspace index unavailable (${messageOf(error)})`)
|
|
114
|
+
}
|
|
115
|
+
return index
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return { list }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Serve the catalog over the Host webserver.
|
|
123
|
+
*
|
|
124
|
+
* The bridge token is the only gate: the overlay runs on an arbitrary http(s)
|
|
125
|
+
* page, so no cookie or Origin assumption can hold.
|
|
126
|
+
*
|
|
127
|
+
* @param {any} webServer
|
|
128
|
+
* @param {object} options
|
|
129
|
+
* @param {ReturnType<typeof createSessionCatalog>} options.catalog
|
|
130
|
+
* @param {string} options.token
|
|
131
|
+
* @param {(presented: unknown, expected: string) => boolean} options.matchesToken
|
|
132
|
+
* @param {() => string | undefined} [options.preferred] Session the Client is showing, when it said so
|
|
133
|
+
* @param {string} [options.path]
|
|
134
|
+
* @returns {() => void} disposer
|
|
135
|
+
*/
|
|
136
|
+
export function registerSessionsRoute(webServer, { catalog, token, matchesToken, preferred, path = SESSIONS_PATH }) {
|
|
137
|
+
return webServer.register({
|
|
138
|
+
kind: 'exact',
|
|
139
|
+
path,
|
|
140
|
+
auth: 'anonymous',
|
|
141
|
+
handler: (request, response) => {
|
|
142
|
+
const headers = {
|
|
143
|
+
'content-type': 'application/json; charset=utf-8',
|
|
144
|
+
'cache-control': 'no-store',
|
|
145
|
+
'access-control-allow-origin': '*',
|
|
146
|
+
'access-control-allow-headers': 'authorization, content-type, x-anno-token',
|
|
147
|
+
'access-control-allow-methods': 'GET, OPTIONS',
|
|
148
|
+
}
|
|
149
|
+
/** @param {number} status */
|
|
150
|
+
const send = (status, payload) => {
|
|
151
|
+
const body = JSON.stringify(payload)
|
|
152
|
+
response.writeHead(status, headers)
|
|
153
|
+
response.end(request.method === 'HEAD' ? undefined : body)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (request.method === 'OPTIONS') {
|
|
157
|
+
response.writeHead(204, headers)
|
|
158
|
+
response.end()
|
|
159
|
+
return
|
|
160
|
+
}
|
|
161
|
+
if (!matchesToken(presentedToken(request), token)) {
|
|
162
|
+
send(401, { ok: false, error: 'token' })
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const url = new URL(request.url ?? path, 'http://127.0.0.1')
|
|
167
|
+
const limit = Number.parseInt(url.searchParams.get('limit') ?? '', 10)
|
|
168
|
+
catalog
|
|
169
|
+
.list({
|
|
170
|
+
query: url.searchParams.get('q') ?? '',
|
|
171
|
+
...(Number.isFinite(limit) ? { limit } : {}),
|
|
172
|
+
includeSubagents: url.searchParams.get('subagents') === '1',
|
|
173
|
+
})
|
|
174
|
+
.then((value) => {
|
|
175
|
+
send(200, { ok: true, ...value, defaultSessionId: defaultId(value.items, preferred?.()) })
|
|
176
|
+
})
|
|
177
|
+
.catch((error) => {
|
|
178
|
+
send(500, { ok: false, error: 'catalog', message: messageOf(error) })
|
|
179
|
+
})
|
|
180
|
+
},
|
|
181
|
+
})
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* The row the picker starts on: the Session the Client is showing while the
|
|
186
|
+
* catalog still lists it, otherwise the most recently active one. A hint that
|
|
187
|
+
* points at a deleted or filtered-out Session is not a choice, so it loses.
|
|
188
|
+
* @param {readonly { id: string }[]} items
|
|
189
|
+
* @param {string | undefined} preferredId
|
|
190
|
+
* @returns {string | null}
|
|
191
|
+
*/
|
|
192
|
+
export function defaultId(items, preferredId) {
|
|
193
|
+
if (preferredId !== undefined && items.some((item) => item.id === preferredId)) return preferredId
|
|
194
|
+
return items[0]?.id ?? null
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Accept the token from the query string, a bearer header, or the dedicated header. */
|
|
198
|
+
function presentedToken(request) {
|
|
199
|
+
const header = request.headers?.authorization
|
|
200
|
+
if (typeof header === 'string' && header.toLowerCase().startsWith('bearer ')) return header.slice(7).trim()
|
|
201
|
+
const custom = request.headers?.['x-anno-token']
|
|
202
|
+
if (typeof custom === 'string' && custom !== '') return custom
|
|
203
|
+
try {
|
|
204
|
+
return new URL(request.url ?? '/', 'http://127.0.0.1').searchParams.get('token') ?? ''
|
|
205
|
+
} catch {
|
|
206
|
+
return ''
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** @param {any} row @param {string | undefined} title @param {{ id: string, title: string, path: string } | undefined} workspace */
|
|
211
|
+
function describe(row, title, workspace) {
|
|
212
|
+
return {
|
|
213
|
+
id: row.sessionId,
|
|
214
|
+
title: typeof title === 'string' ? title : '',
|
|
215
|
+
updatedAt: typeof row.updatedAt === 'number' ? row.updatedAt : 0,
|
|
216
|
+
running: row.running === true,
|
|
217
|
+
blank: row.blank === true,
|
|
218
|
+
agentAvailable: row.agentAvailable === true,
|
|
219
|
+
cwd: typeof row.cwd === 'string' ? row.cwd : null,
|
|
220
|
+
workspace: workspace ?? null,
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** @param {SessionCatalogItem} item @param {string} needle */
|
|
225
|
+
function matches(item, needle) {
|
|
226
|
+
return [item.title, item.id, item.cwd ?? '', item.workspace?.title ?? '', item.workspace?.path ?? ''].some((value) =>
|
|
227
|
+
value.toLowerCase().includes(needle),
|
|
228
|
+
)
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** @param {number} value @param {number} low @param {number} high */
|
|
232
|
+
function clamp(value, low, high) {
|
|
233
|
+
const number = Number.isFinite(value) ? Math.trunc(value) : low
|
|
234
|
+
return Math.min(Math.max(number, low), high)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** @param {unknown} error */
|
|
238
|
+
function messageOf(error) {
|
|
239
|
+
return error instanceof Error ? error.message : String(error)
|
|
240
|
+
}
|