| 1 | import { chmod, mkdir, open, readFile, rename, rm } from "node:fs/promises"; |
| 2 | import path from "node:path"; |
| 3 | import { randomBytes } from "node:crypto"; |
| 4 | import { setTimeout as delay } from "node:timers/promises"; |
| 5 | |
| 6 | const DEFAULT_ACTION_TTL_MS = 24 * 60 * 60 * 1000; |
| 7 | |
| 8 | export const THREAD_NOT_OWNED_MESSAGE = "This chat can only use threads it started. Send /new to start a new thread."; |
| 9 | |
| 10 | function normalizeCursorValue(value, fallback = 0) { |
| 11 | const number = Number(value); |
| 12 | if (Number.isFinite(number) && number >= 0) return Math.floor(number); |
| 13 | const fallbackNumber = Number(fallback); |
| 14 | if (Number.isFinite(fallbackNumber) && fallbackNumber >= 0) return Math.floor(fallbackNumber); |
| 15 | return 0; |
| 16 | } |
| 17 | |
| 18 | async function chmodBestEffort(filePath, mode) { |
| 19 | try { |
| 20 | await chmod(filePath, mode); |
| 21 | } catch (error) { |
| 22 | if (process.platform !== "win32") throw error; |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * Replace `filePath` so a crash leaves either the old bytes or the new ones: |
| 28 | * a unique temporary name (two processes sharing a state dir never write the |
| 29 | * same temp file), fsync before the rename, and a best-effort directory fsync |
| 30 | * after it so the rename itself survives power loss where the OS allows. |
| 31 | */ |
| 32 | export async function writeFileDurable(filePath, contents, { mode = 0o600 } = {}) { |
| 33 | const dir = path.dirname(filePath); |
| 34 | const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`); |
| 35 | let handle = null; |
| 36 | try { |
| 37 | handle = await open(tmp, "wx", mode); |
| 38 | await handle.writeFile(contents); |
| 39 | await handle.sync(); |
| 40 | await handle.close(); |
| 41 | handle = null; |
| 42 | for (let attempt = 0; ; attempt++) { |
| 43 | try { |
| 44 | await rename(tmp, filePath); |
| 45 | break; |
| 46 | } catch (error) { |
| 47 | // Windows readers/other writers can temporarily deny replacement. |
| 48 | // Never unlink the old record to make the rename succeed. |
| 49 | if (process.platform !== "win32" || !["EPERM", "EACCES", "EBUSY"].includes(error.code) || attempt >= 10) throw error; |
| 50 | await delay(50 * (attempt + 1)); |
| 51 | } |
| 52 | } |
| 53 | } catch (error) { |
| 54 | await handle?.close().catch(() => {}); |
| 55 | await rm(tmp, { force: true }).catch(() => {}); |
| 56 | throw error; |
| 57 | } |
| 58 | let dirHandle = null; |
| 59 | try { |
| 60 | dirHandle = await open(dir, "r"); |
| 61 | await dirHandle.sync(); |
| 62 | } catch { |
| 63 | // Windows and some filesystems cannot fsync a directory. |
| 64 | } finally { |
| 65 | await dirHandle?.close().catch(() => {}); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | export class ThreadStore { |
| 70 | static async open(filePath, options = {}) { |
| 71 | const store = new this(filePath, options); |
| 72 | await store.load(); |
| 73 | return store; |
| 74 | } |
| 75 | |
| 76 | constructor(filePath, options = {}) { |
| 77 | this.filePath = filePath; |
| 78 | this.options = { |
| 79 | messageLimit: options.messageLimit || 0, |
| 80 | actions: options.actions === true, |
| 81 | actionLimit: options.actionLimit || 200, |
| 82 | actionTtlMs: options.actionTtlMs || DEFAULT_ACTION_TTL_MS, |
| 83 | privateMode: options.privateMode === true, |
| 84 | ownerLimit: options.ownerLimit || options.actionLimit || 200, |
| 85 | legacyOwnerScope: typeof options.legacyOwnerScope === "function" ? options.legacyOwnerScope : () => "" |
| 86 | }; |
| 87 | this.data = { chats: {} }; |
| 88 | this.saveDirty = false; |
| 89 | this.savePending = null; |
| 90 | this.handlingMessages = new Map(); |
| 91 | this.ensureShape(); |
| 92 | } |
| 93 | |
| 94 | ensureShape() { |
| 95 | if (!this.data || typeof this.data !== "object") this.data = {}; |
| 96 | if (!this.data.chats || typeof this.data.chats !== "object") this.data.chats = {}; |
| 97 | if (!Array.isArray(this.data.threadOwners)) this.data.threadOwners = []; |
| 98 | if (this.options.messageLimit > 0 && !Array.isArray(this.data.messages)) { |
| 99 | this.data.messages = []; |
| 100 | } |
| 101 | if (this.options.messageLimit > 0 && (!this.data.inflight || typeof this.data.inflight !== "object" || Array.isArray(this.data.inflight))) { |
| 102 | this.data.inflight = {}; |
| 103 | } |
| 104 | if (this.options.actions && (!this.data.actions || typeof this.data.actions !== "object")) { |
| 105 | this.data.actions = {}; |
| 106 | } |
| 107 | if (this.data.cursors && typeof this.data.cursors !== "object") { |
| 108 | this.data.cursors = {}; |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | async load() { |
| 113 | try { |
| 114 | const raw = await readFile(this.filePath, "utf8"); |
| 115 | const parsed = JSON.parse(raw); |
| 116 | const unmigrated = !parsed || typeof parsed !== "object" || !Array.isArray(parsed.threadOwners); |
| 117 | this.data = parsed; |
| 118 | this.ensureShape(); |
| 119 | if (unmigrated) this.data.threadOwners = this.legacyThreadOwners(); |
| 120 | } catch (error) { |
| 121 | if (error.code !== "ENOENT") throw error; |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | /** |
| 126 | * Claim one inbound message before acting on it. "new": handle it now (it |
| 127 | * is recorded as in flight first, durably). "done": a finished duplicate. |
| 128 | * "interrupted": an earlier process claimed it and stopped before |
| 129 | * completeMessage. The caller reports the unknown outcome and completes |
| 130 | * the claim after the report succeeds. |
| 131 | */ |
| 132 | async claimMessage(messageKey) { |
| 133 | if (!messageKey || this.options.messageLimit <= 0) return "new"; |
| 134 | this.ensureShape(); |
| 135 | const inflight = this.data.inflight; |
| 136 | if (Object.hasOwn(inflight, messageKey)) return "interrupted"; |
| 137 | if (this.data.messages.includes(messageKey)) return "done"; |
| 138 | if (Object.keys(inflight).length >= this.options.messageLimit) { |
| 139 | throw new Error("Too many unfinished bridge messages. Reconcile their outcomes before accepting more."); |
| 140 | } |
| 141 | this.data.inflight = { ...inflight, [messageKey]: new Date().toISOString() }; |
| 142 | await this.save(); |
| 143 | return "new"; |
| 144 | } |
| 145 | |
| 146 | /** Mark a claimed message handled after its action or interruption report finishes. */ |
| 147 | async completeMessage(messageKey) { |
| 148 | if (!messageKey || !this.data.inflight || !Object.hasOwn(this.data.inflight, messageKey)) return; |
| 149 | delete this.data.inflight[messageKey]; |
| 150 | if (!this.data.messages.includes(messageKey)) { |
| 151 | this.data.messages.push(messageKey); |
| 152 | this.data.messages = this.data.messages.slice(-this.options.messageLimit); |
| 153 | } |
| 154 | await this.save(); |
| 155 | } |
| 156 | |
| 157 | async handleMessageOnce(messageKey, handle, reportInterrupted) { |
| 158 | if (!messageKey || this.options.messageLimit <= 0) return handle(); |
| 159 | if (this.handlingMessages.has(messageKey)) return this.handlingMessages.get(messageKey); |
| 160 | const pending = Promise.resolve().then(async () => { |
| 161 | const claim = await this.claimMessage(messageKey); |
| 162 | if (claim === "done") return; |
| 163 | if (claim === "interrupted") await reportInterrupted(); |
| 164 | else await handle(); |
| 165 | await this.completeMessage(messageKey); |
| 166 | }).finally(() => this.handlingMessages.delete(messageKey)); |
| 167 | this.handlingMessages.set(messageKey, pending); |
| 168 | return pending; |
| 169 | } |
| 170 | |
| 171 | async recordMessage(messageKey, chatId = null, patch = null) { |
| 172 | if (patch && !chatId) throw new Error("Durable admission requires a chat binding"); |
| 173 | if (!messageKey || this.options.messageLimit <= 0) { |
| 174 | if (patch) throw new Error("Durable admission requires message retention"); |
| 175 | return false; |
| 176 | } |
| 177 | this.ensureShape(); |
| 178 | if (this.data.messages.includes(messageKey)) return true; |
| 179 | this.data.messages.push(messageKey); |
| 180 | this.data.messages = this.data.messages.slice(-this.options.messageLimit); |
| 181 | if (chatId && patch) this.data.chats[chatId] = { ...this.data.chats[chatId], ...patch }; |
| 182 | await this.save(); |
| 183 | return false; |
| 184 | } |
| 185 | |
| 186 | getCursor(name, fallback = 0) { |
| 187 | if (!name) return normalizeCursorValue(fallback); |
| 188 | this.ensureShape(); |
| 189 | return normalizeCursorValue(this.data.cursors?.[name], fallback); |
| 190 | } |
| 191 | |
| 192 | async setCursor(name, value) { |
| 193 | if (!name) return normalizeCursorValue(value); |
| 194 | this.ensureShape(); |
| 195 | if (!this.data.cursors || typeof this.data.cursors !== "object") { |
| 196 | this.data.cursors = {}; |
| 197 | } |
| 198 | const cursor = normalizeCursorValue(value); |
| 199 | if (this.data.cursors[name] === cursor) return cursor; |
| 200 | this.data.cursors[name] = cursor; |
| 201 | await this.save(); |
| 202 | return cursor; |
| 203 | } |
| 204 | |
| 205 | async getChat(chatId) { |
| 206 | return this.data.chats[chatId] || null; |
| 207 | } |
| 208 | |
| 209 | listChats() { |
| 210 | return Object.entries(this.data.chats || {}); |
| 211 | } |
| 212 | |
| 213 | async setChat(chatId, state) { |
| 214 | this.data.chats[chatId] = state; |
| 215 | await this.save(); |
| 216 | return state; |
| 217 | } |
| 218 | |
| 219 | async patchChat(chatId, patch) { |
| 220 | const current = this.data.chats[chatId] || {}; |
| 221 | this.data.chats[chatId] = { ...current, ...patch }; |
| 222 | await this.save(); |
| 223 | return this.data.chats[chatId]; |
| 224 | } |
| 225 | |
| 226 | legacyThreadOwners() { |
| 227 | const chatsByThread = new Map(); |
| 228 | const reference = (threadId, chatId) => { |
| 229 | if (!chatsByThread.has(threadId)) chatsByThread.set(threadId, new Set()); |
| 230 | chatsByThread.get(threadId).add(chatId); |
| 231 | }; |
| 232 | const candidates = []; |
| 233 | for (const [chatId, state] of Object.entries(this.data.chats || {})) { |
| 234 | if (!state || typeof state !== "object") continue; |
| 235 | const own = []; |
| 236 | for (const entry of Array.isArray(state.threadBindings) ? state.threadBindings : []) { |
| 237 | if (!entry?.threadId || !entry.actorId) continue; |
| 238 | reference(entry.threadId, chatId); |
| 239 | own.push({ threadId: entry.threadId, chatId, scope: String(entry.actorId) }); |
| 240 | } |
| 241 | if (state.threadId) { |
| 242 | reference(state.threadId, chatId); |
| 243 | const scope = this.options.legacyOwnerScope(chatId, state); |
| 244 | if (typeof scope === "string") own.push({ threadId: state.threadId, chatId, scope, legacy: true }); |
| 245 | } |
| 246 | candidates.push(...own.slice(-this.options.ownerLimit)); |
| 247 | } |
| 248 | const seen = new Set(); |
| 249 | return candidates.filter((entry) => { |
| 250 | const key = JSON.stringify([entry.threadId, entry.chatId, entry.scope]); |
| 251 | if (seen.has(key) || chatsByThread.get(entry.threadId).size !== 1) return false; |
| 252 | seen.add(key); |
| 253 | return true; |
| 254 | }); |
| 255 | } |
| 256 | |
| 257 | ownsThread(chatId, threadId, scope = "") { |
| 258 | if (!chatId || !threadId) return false; |
| 259 | return this.data.threadOwners.some((entry) => entry.legacy !== true && entry.threadId === threadId && entry.chatId === chatId && entry.scope === scope); |
| 260 | } |
| 261 | |
| 262 | ownershipPending(chatId, threadId, scope = "") { |
| 263 | if (!chatId || !threadId || this.ownsThread(chatId, threadId, scope)) return false; |
| 264 | return this.data.threadOwners.some((entry) => entry.legacy === true && entry.threadId === threadId && entry.chatId === chatId && entry.scope === scope); |
| 265 | } |
| 266 | |
| 267 | legacyOwnerCount() { |
| 268 | return this.data.threadOwners.filter((entry) => entry.legacy === true).length; |
| 269 | } |
| 270 | |
| 271 | async verifyLegacyOwners(runtimeJson, accept, { concurrency = 8 } = {}) { |
| 272 | const ids = [...new Set(this.data.threadOwners.filter((entry) => entry.legacy === true).map((entry) => entry.threadId))]; |
| 273 | const verdicts = new Map(); |
| 274 | for (let index = 0; index < ids.length; index += concurrency) { |
| 275 | await Promise.all(ids.slice(index, index + concurrency).map(async (threadId) => { |
| 276 | try { |
| 277 | const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(threadId)}`); |
| 278 | verdicts.set(threadId, accept(detail?.thread ?? detail) === true); |
| 279 | } catch (error) { |
| 280 | if (error?.status === 404) verdicts.set(threadId, false); |
| 281 | } |
| 282 | })); |
| 283 | } |
| 284 | if (verdicts.size) { |
| 285 | this.data.threadOwners = this.data.threadOwners.flatMap((entry) => { |
| 286 | if (entry.legacy !== true || !verdicts.has(entry.threadId)) return [entry]; |
| 287 | if (!verdicts.get(entry.threadId)) return []; |
| 288 | const { legacy, ...confirmed } = entry; |
| 289 | return [confirmed]; |
| 290 | }); |
| 291 | await this.save(); |
| 292 | } |
| 293 | return this.legacyOwnerCount(); |
| 294 | } |
| 295 | |
| 296 | requireOwnedThread(chatId, threadId, scope = "") { |
| 297 | if (!this.ownsThread(chatId, threadId, scope)) throw new ThreadOwnershipError(THREAD_NOT_OWNED_MESSAGE); |
| 298 | } |
| 299 | |
| 300 | ownedThreadIds(chatId, scope = "") { |
| 301 | if (!chatId) return []; |
| 302 | return this.data.threadOwners |
| 303 | .filter((entry) => entry.legacy !== true && entry.chatId === chatId && entry.scope === scope) |
| 304 | .map((entry) => entry.threadId) |
| 305 | .reverse(); |
| 306 | } |
| 307 | |
| 308 | async recordThreadOwner(chatId, threadId, scope = "") { |
| 309 | if (!chatId || !threadId) throw new ThreadOwnershipError(THREAD_NOT_OWNED_MESSAGE); |
| 310 | const held = this.data.threadOwners.find((entry) => entry.threadId === threadId); |
| 311 | if (held) { |
| 312 | if (held.chatId === chatId && held.scope === scope) return; |
| 313 | throw new ThreadOwnershipError(THREAD_NOT_OWNED_MESSAGE); |
| 314 | } |
| 315 | const owners = [...this.data.threadOwners, { threadId, chatId, scope }]; |
| 316 | const mine = owners.filter((entry) => entry.chatId === chatId); |
| 317 | const evicted = new Set(mine.slice(0, Math.max(0, mine.length - this.options.ownerLimit))); |
| 318 | this.data.threadOwners = owners.filter((entry) => !evicted.has(entry)); |
| 319 | await this.save(); |
| 320 | } |
| 321 | |
| 322 | async finishObservedTurn(chatId, threadId, turnId) { |
| 323 | const current = this.data.chats[chatId]; |
| 324 | if (turnId && current?.threadId === threadId && current.activeTurnId === turnId) { |
| 325 | await this.patchChat(chatId, { activeTurnId: null, updatedAt: new Date().toISOString() }); |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | /** |
| 330 | * Record only a turn accepted by Runtime, before its events are delivered. |
| 331 | * A later sender cannot overwrite that turn's origin. Records use the chat's |
| 332 | * existing lifecycle and action retention bound; retired records fail closed. |
| 333 | * This does not authenticate the platform SDK or pin replacement credentials. |
| 334 | */ |
| 335 | async recordTurnOrigin(chatId, threadId, turnId, actorId) { |
| 336 | const current = this.data.chats[chatId]; |
| 337 | if (!current || current.threadId !== threadId || !turnId || !actorId) { |
| 338 | throw new ApprovalOwnershipError("accepted turn needs its current chat, thread and initiating human"); |
| 339 | } |
| 340 | const origins = Array.isArray(current.turnOrigins) ? current.turnOrigins : []; |
| 341 | const existing = origins.find((origin) => origin.threadId === threadId && origin.turnId === turnId); |
| 342 | if (existing) { |
| 343 | if (existing.actorId !== actorId) throw new ApprovalOwnershipError("turn origin cannot change"); |
| 344 | return existing; |
| 345 | } |
| 346 | const origin = { threadId, turnId, actorId }; |
| 347 | // patchChat mutates synchronously before saving, preserving concurrent turns. |
| 348 | await this.patchChat(chatId, { |
| 349 | turnOrigins: [...origins.filter((entry) => entry.threadId === threadId), origin].slice(-this.options.actionLimit) |
| 350 | }); |
| 351 | return origin; |
| 352 | } |
| 353 | |
| 354 | turnOrigin(chatId, threadId, turnId) { |
| 355 | const state = this.data.chats[chatId]; |
| 356 | if (!state || state.threadId !== threadId || !turnId) return null; |
| 357 | return (Array.isArray(state.turnOrigins) ? state.turnOrigins : []) |
| 358 | .find((origin) => origin.threadId === threadId && origin.turnId === turnId && origin.actorId) || null; |
| 359 | } |
| 360 | |
| 361 | async putAction(action, owner) { |
| 362 | if (!this.options.actions) return ""; |
| 363 | this.ensureShape(); |
| 364 | const binding = actionOwner(owner); |
| 365 | if (!binding.chatId) throw new ApprovalOwnershipError("button action needs its receiving chat"); |
| 366 | if (action.kind === "approval" && |
| 367 | (!binding.threadId || !binding.turnId || !binding.actorId || |
| 368 | this.turnOrigin(binding.chatId, binding.threadId, binding.turnId)?.actorId !== binding.actorId)) { |
| 369 | throw new ApprovalOwnershipError("approval button needs the accepted turn and initiating human"); |
| 370 | } |
| 371 | const token = randomBytes(16).toString("hex"); |
| 372 | this.data.actions[token] = { |
| 373 | ...action, |
| 374 | owner: binding, |
| 375 | createdAt: new Date().toISOString() |
| 376 | }; |
| 377 | this.pruneActions(); |
| 378 | await this.save(); |
| 379 | return token; |
| 380 | } |
| 381 | |
| 382 | async getAction(token, owner = null) { |
| 383 | if (!token || !this.options.actions) return null; |
| 384 | this.ensureShape(); |
| 385 | this.pruneActions(); |
| 386 | const action = this.data.actions[token] || null; |
| 387 | if (!action) return null; |
| 388 | // Legacy unbound buttons cannot prove which chat received authority. |
| 389 | if (!action.owner || !sameOwner(action.owner, owner)) return null; |
| 390 | if (action.kind === "approval" && |
| 391 | (!action.owner.threadId || !action.owner.turnId || !action.owner.actorId || |
| 392 | this.turnOrigin(action.owner.chatId, action.owner.threadId, action.owner.turnId)?.actorId !== action.owner.actorId)) return null; |
| 393 | return action; |
| 394 | } |
| 395 | |
| 396 | async takeAction(token, owner = null) { |
| 397 | const action = await this.getAction(token, owner); |
| 398 | if (action) { |
| 399 | delete this.data.actions[token]; |
| 400 | await this.save(); |
| 401 | } |
| 402 | return action; |
| 403 | } |
| 404 | |
| 405 | pruneActions() { |
| 406 | if (!this.options.actions) return; |
| 407 | const cutoff = Date.now() - this.options.actionTtlMs; |
| 408 | const fresh = Object.entries(this.data.actions || {}).filter(([, action]) => { |
| 409 | const time = Date.parse(action.createdAt || ""); |
| 410 | return Number.isFinite(time) && time >= cutoff; |
| 411 | }); |
| 412 | this.data.actions = Object.fromEntries(fresh.slice(-this.options.actionLimit)); |
| 413 | } |
| 414 | |
| 415 | async save() { |
| 416 | // Batch bursts of small updates: saves issued while a write is in flight |
| 417 | // coalesce into a single follow-up write. The returned promise resolves |
| 418 | // only after this mutation is durable on disk (temp file + rename). |
| 419 | this.saveDirty = true; |
| 420 | if (!this.savePending) { |
| 421 | this.savePending = this.flushSaves(); |
| 422 | } |
| 423 | return this.savePending; |
| 424 | } |
| 425 | |
| 426 | async flushSaves() { |
| 427 | try { |
| 428 | while (this.saveDirty) { |
| 429 | this.saveDirty = false; |
| 430 | await this.writeSnapshot(); |
| 431 | } |
| 432 | } finally { |
| 433 | this.savePending = null; |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | async writeSnapshot() { |
| 438 | const dir = path.dirname(this.filePath); |
| 439 | await mkdir(dir, { recursive: true, mode: 0o700 }); |
| 440 | if (this.options.privateMode) await chmodBestEffort(dir, 0o700); |
| 441 | await writeFileDurable(this.filePath, `${JSON.stringify(this.data, null, 2)}\n`, { mode: 0o600 }); |
| 442 | if (this.options.privateMode) await chmodBestEffort(this.filePath, 0o600); |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | function actionOwner(owner) { |
| 447 | return { |
| 448 | chatId: String(owner?.chatId ?? ""), |
| 449 | ...(owner?.threadId ? { threadId: String(owner.threadId) } : {}), |
| 450 | ...(owner?.turnId ? { turnId: String(owner.turnId) } : {}), |
| 451 | ...(owner?.actorId ? { actorId: String(owner.actorId) } : {}) |
| 452 | }; |
| 453 | } |
| 454 | |
| 455 | function sameOwner(stored, owner) { |
| 456 | if (!owner) return false; |
| 457 | const wanted = actionOwner(owner); |
| 458 | if (!stored.chatId || stored.chatId !== wanted.chatId) return false; |
| 459 | return (!stored.threadId || stored.threadId === wanted.threadId) && |
| 460 | (!stored.actorId || stored.actorId === wanted.actorId) && |
| 461 | (!stored.turnId || !wanted.turnId || stored.turnId === wanted.turnId); |
| 462 | } |
| 463 | |
| 464 | export class ApprovalOwnershipError extends Error { |
| 465 | constructor(message) { |
| 466 | super(message); |
| 467 | this.name = "ApprovalOwnershipError"; |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | export class ThreadOwnershipError extends Error { |
| 472 | constructor(message = THREAD_NOT_OWNED_MESSAGE) { |
| 473 | super(message); |
| 474 | this.name = "ThreadOwnershipError"; |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | export async function settleLegacyOwners(store, runtimeJson, accept, { retryMs = 30_000, timeoutMs = 15_000, onSettled = null } = {}) { |
| 479 | const bounded = (route) => runtimeJson(route, { signal: AbortSignal.timeout(timeoutMs) }); |
| 480 | const run = async (retried) => { |
| 481 | const pendingBefore = new Set( |
| 482 | (store.data?.threadOwners || []).filter((entry) => entry.legacy === true).map((entry) => entry.threadId) |
| 483 | ); |
| 484 | const remaining = await store.verifyLegacyOwners(bounded, accept).catch(() => store.legacyOwnerCount()); |
| 485 | if (retried && typeof onSettled === "function" && pendingBefore.size) { |
| 486 | const stillPending = new Set( |
| 487 | (store.data?.threadOwners || []).filter((entry) => entry.legacy === true).map((entry) => entry.threadId) |
| 488 | ); |
| 489 | const settled = new Set([...pendingBefore].filter((id) => !stillPending.has(id))); |
| 490 | if (settled.size) { |
| 491 | await Promise.resolve(onSettled(settled)).catch((error) => { |
| 492 | console.error("failed after settling legacy thread owners", error); |
| 493 | }); |
| 494 | } |
| 495 | } |
| 496 | if (remaining > 0) setTimeout(() => void run(true), retryMs).unref(); |
| 497 | }; |
| 498 | await run(false); |
| 499 | } |
| 500 | |
| 501 | export function createdByBridge(thread, { systemPrompt, workspace }) { |
| 502 | return thread?.system_prompt === systemPrompt && String(thread?.workspace ?? "") === workspace; |
| 503 | } |
| 504 | |
| 505 | export async function listOwnedThreads(store, runtimeJson, chatId, scope = "", limit = 8) { |
| 506 | const ids = store.ownedThreadIds(chatId, scope); |
| 507 | if (!ids.length) return []; |
| 508 | const query = new URLSearchParams({ limit: String(limit), include_archived: "true", thread_ids: ids.join(",") }); |
| 509 | const rows = await runtimeJson(`/v1/threads/summary?${query}`); |
| 510 | return (Array.isArray(rows) ? rows : []).filter((thread) => store.ownsThread(chatId, thread?.id, scope)).slice(0, limit); |
| 511 | } |
| 512 | |
| 513 | /** |
| 514 | * Runtime owns pending approvals and their turn ids. The existing chat store |
| 515 | * owns the immutable human who initiated that accepted turn. Admission to a |
| 516 | * group, a newer sender or a legacy unbound button does not grant this authority. |
| 517 | */ |
| 518 | export async function decideApproval(runtimeJson, { store, chatId, actorId, approvalId, decision, remember = false, turnId = null, ownsThread = null }) { |
| 519 | if (decision !== "allow" && decision !== "deny") throw new ApprovalOwnershipError("decision must be allow or deny"); |
| 520 | const state = await store.getChat(chatId); |
| 521 | const threadId = state?.threadId; |
| 522 | if (!threadId) throw new ApprovalOwnershipError("this chat has no Runtime thread yet"); |
| 523 | if (typeof ownsThread === "function" && !ownsThread(threadId)) throw new ThreadOwnershipError(THREAD_NOT_OWNED_MESSAGE); |
| 524 | if (!actorId) throw new ApprovalOwnershipError("missing initiating human"); |
| 525 | if (!approvalId) throw new ApprovalOwnershipError("missing approval id"); |
| 526 | const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(threadId)}`); |
| 527 | const pending = detail?.pending_approvals ?? detail?.thread?.pending_approvals ?? []; |
| 528 | const approval = pending.find((entry) => (entry?.id ?? entry?.approval_id) === approvalId); |
| 529 | const pendingTurnId = approval?.turn_id; |
| 530 | if (!pendingTurnId || (turnId && pendingTurnId !== turnId) || |
| 531 | store.turnOrigin(chatId, threadId, pendingTurnId)?.actorId !== actorId) { |
| 532 | throw new ApprovalOwnershipError("approval needs its accepted turn's initiating human in this chat"); |
| 533 | } |
| 534 | await runtimeJson(`/v1/approvals/${encodeURIComponent(approvalId)}`, { |
| 535 | method: "POST", |
| 536 | body: { decision, remember: remember === true } |
| 537 | }); |
| 538 | } |
| 539 | |
| 540 | /** |
| 541 | * Settle a stored approval button: look it up for this owner, deliver the |
| 542 | * decision, and consume the token only once the Runtime accepted it. A failed |
| 543 | * POST leaves the button usable. |
| 544 | */ |
| 545 | export async function settleStoredApproval(store, token, owner, deliver) { |
| 546 | const stored = await store.getAction(token, owner); |
| 547 | if (!stored || stored.kind !== "approval") return null; |
| 548 | await deliver(stored); |
| 549 | await store.takeAction(token, owner); |
| 550 | return stored; |
| 551 | } |
| 552 | |
| 553 | export function envFirst(env, ...names) { |
| 554 | for (const name of names) { |
| 555 | const value = env?.[name]; |
| 556 | if (value != null && String(value).trim()) return String(value).trim(); |
| 557 | } |
| 558 | return ""; |
| 559 | } |
| 560 | |
| 561 | export function parseList(raw) { |
| 562 | return String(raw || "") |
| 563 | .split(",") |
| 564 | .map((item) => item.trim()) |
| 565 | .filter(Boolean); |
| 566 | } |
| 567 | |
| 568 | export function parseBool(raw, fallback = false) { |
| 569 | if (raw == null || raw === "") return fallback; |
| 570 | return ["1", "true", "yes", "on"].includes(String(raw).trim().toLowerCase()); |
| 571 | } |
| 572 | |
| 573 | export function parseEnvText(raw) { |
| 574 | const env = {}; |
| 575 | for (const line of String(raw || "").split(/\r?\n/)) { |
| 576 | const trimmed = line.trim(); |
| 577 | if (!trimmed || trimmed.startsWith("#")) continue; |
| 578 | const normalized = trimmed.startsWith("export ") ? trimmed.slice(7).trim() : trimmed; |
| 579 | const index = normalized.indexOf("="); |
| 580 | if (index <= 0) continue; |
| 581 | const key = normalized.slice(0, index).trim(); |
| 582 | let value = normalized.slice(index + 1).trim(); |
| 583 | if ( |
| 584 | value.length >= 2 && |
| 585 | ((value.startsWith('"') && value.endsWith('"')) || |
| 586 | (value.startsWith("'") && value.endsWith("'"))) |
| 587 | ) { |
| 588 | value = value.slice(1, -1); |
| 589 | } |
| 590 | env[key] = value; |
| 591 | } |
| 592 | return env; |
| 593 | } |
| 594 | |
| 595 | export function cleanEnvValue(value) { |
| 596 | return String(value ?? "").trim(); |
| 597 | } |
| 598 | |
| 599 | export function isPlaceholderValue(value) { |
| 600 | const normalized = cleanEnvValue(value).toLowerCase(); |
| 601 | return ( |
| 602 | !normalized || |
| 603 | normalized.includes("replace-with") || |
| 604 | normalized.includes("xxxxxxxx") || |
| 605 | normalized === "changeme" |
| 606 | ); |
| 607 | } |
| 608 | |
| 609 | export function parseTextContent(content, keys = ["text", "content"]) { |
| 610 | if (typeof content !== "string") return ""; |
| 611 | try { |
| 612 | const parsed = JSON.parse(content); |
| 613 | let firstString = null; |
| 614 | for (const key of keys) { |
| 615 | if (typeof parsed?.[key] === "string") { |
| 616 | if (parsed[key].trim()) return parsed[key]; |
| 617 | if (firstString === null) firstString = parsed[key]; |
| 618 | } |
| 619 | } |
| 620 | if (firstString !== null) return firstString; |
| 621 | } catch { |
| 622 | return content; |
| 623 | } |
| 624 | return content; |
| 625 | } |
| 626 | |
| 627 | export function stripGroupPrefix(text, { chatType, requirePrefix, prefix, directChatTypes = [] }) { |
| 628 | const trimmed = String(text || "").trim(); |
| 629 | if (!trimmed) return { accepted: false, text: "" }; |
| 630 | if (!requirePrefix || directChatTypes.includes(chatType)) { |
| 631 | return { accepted: true, text: trimmed }; |
| 632 | } |
| 633 | const marker = prefix || "/ds"; |
| 634 | if (trimmed === marker) return { accepted: true, text: "/help" }; |
| 635 | if (trimmed.startsWith(marker) && /\s/u.test(trimmed.charAt(marker.length))) { |
| 636 | return { accepted: true, text: trimmed.slice(marker.length).trim() }; |
| 637 | } |
| 638 | return { accepted: false, text: "" }; |
| 639 | } |
| 640 | |
| 641 | export function parseCommand(text, options = {}) { |
| 642 | const trimmed = String(text || "").trim(); |
| 643 | if (!trimmed.startsWith("/")) return { name: "prompt", args: trimmed }; |
| 644 | const [head, ...rest] = trimmed.split(/\s+/); |
| 645 | const rawName = head.slice(1); |
| 646 | const name = (options.stripBotMention ? rawName.split("@")[0] : rawName).toLowerCase(); |
| 647 | return { |
| 648 | name, |
| 649 | args: name === "prompt" ? trimmed.slice(head.length).trimStart() : rest.join(" ") |
| 650 | }; |
| 651 | } |
| 652 | |
| 653 | export function parseApprovalDecisionArgs(args) { |
| 654 | const parts = String(args || "") |
| 655 | .split(/\s+/) |
| 656 | .filter(Boolean); |
| 657 | return { |
| 658 | approvalId: parts[0] || "", |
| 659 | remember: parts.slice(1).includes("remember") |
| 660 | }; |
| 661 | } |
| 662 | |
| 663 | export function commandAction(command, options = {}) { |
| 664 | const allowMenu = options.allowMenu === true; |
| 665 | const allowStart = options.allowStart === true; |
| 666 | switch (command.name) { |
| 667 | case "start": |
| 668 | if (allowStart) return { kind: "help" }; |
| 669 | break; |
| 670 | case "help": |
| 671 | return { kind: "help" }; |
| 672 | case "menu": |
| 673 | if (allowMenu) return { kind: "menu" }; |
| 674 | break; |
| 675 | case "status": |
| 676 | return { kind: "status" }; |
| 677 | case "threads": |
| 678 | return { kind: "threads" }; |
| 679 | case "new": |
| 680 | return { kind: "new_thread" }; |
| 681 | case "resume": |
| 682 | return { kind: "resume", threadId: command.args }; |
| 683 | case "interrupt": |
| 684 | return { kind: "interrupt" }; |
| 685 | case "compact": |
| 686 | return { kind: "compact" }; |
| 687 | case "model": |
| 688 | return { kind: "set_model", modelName: command.args }; |
| 689 | case "allow": |
| 690 | return { kind: "approval", decision: "allow", ...parseApprovalDecisionArgs(command.args) }; |
| 691 | case "deny": |
| 692 | return { kind: "approval", decision: "deny", ...parseApprovalDecisionArgs(command.args) }; |
| 693 | case "prompt": |
| 694 | return { kind: "prompt", prompt: command.args }; |
| 695 | default: |
| 696 | break; |
| 697 | } |
| 698 | return { |
| 699 | kind: "prompt", |
| 700 | prompt: `/${command.name}${command.args ? ` ${command.args}` : ""}` |
| 701 | }; |
| 702 | } |
| 703 | |
| 704 | export function preservedChatStateFields(state = {}, fields = ["model", "authorizedIdentity"]) { |
| 705 | const preserved = {}; |
| 706 | for (const field of fields) { |
| 707 | if (Object.prototype.hasOwnProperty.call(state || {}, field)) { |
| 708 | preserved[field] = state[field] || null; |
| 709 | } |
| 710 | } |
| 711 | return preserved; |
| 712 | } |
| 713 | |
| 714 | export function splitMessage(text, maxChars = 3500, maxBytes = 0) { |
| 715 | const value = String(text || ""); |
| 716 | const limit = Math.max(1, Math.floor(Number(maxChars) || 3500)); |
| 717 | // Materialize code points once; all chunking below works on index ranges |
| 718 | // instead of re-running Array.from over the shrinking remainder. |
| 719 | const chars = Array.from(value); |
| 720 | const byteLimit = Math.floor(Number(maxBytes) || 0); |
| 721 | let chunks; |
| 722 | if (chars.length <= limit && (byteLimit <= 0 || Buffer.byteLength(value, "utf8") <= byteLimit)) { |
| 723 | chunks = value ? [value] : []; |
| 724 | } else { |
| 725 | chunks = []; |
| 726 | let offset = 0; |
| 727 | let openFence = null; |
| 728 | while (offset < chars.length) { |
| 729 | const next = takeRenderedSplitMessageChunk(chars, offset, limit, openFence, byteLimit); |
| 730 | chunks.push(next.chunk); |
| 731 | offset = next.offset; |
| 732 | openFence = next.openFence; |
| 733 | } |
| 734 | } |
| 735 | if (byteLimit <= 0) return chunks; |
| 736 | // Transport caps such as WeCom's 4096-byte message limit are measured in |
| 737 | // UTF-8 bytes, not characters: a 3500-character CJK reply is ~10.5 KB and |
| 738 | // gets silently truncated. Split any oversized chunk on code-point bounds. |
| 739 | return chunks.flatMap((chunk) => splitChunkByBytes(chunk, byteLimit)); |
| 740 | } |
| 741 | |
| 742 | export function splitAtCodePoint(text, maxChars) { |
| 743 | const value = String(text || ""); |
| 744 | let cut = Math.min(value.length, Math.max(1, Math.floor(maxChars))); |
| 745 | const code = value.charCodeAt(cut - 1); |
| 746 | if (cut < value.length && cut > 1 && code >= 0xd800 && code <= 0xdbff) cut -= 1; |
| 747 | return [value.slice(0, cut), value.slice(cut)]; |
| 748 | } |
| 749 | |
| 750 | function splitChunkByBytes(chunk, maxBytes) { |
| 751 | const out = []; |
| 752 | let buf = ""; |
| 753 | let size = 0; |
| 754 | for (const ch of String(chunk || "")) { |
| 755 | const b = Buffer.byteLength(ch, "utf8"); |
| 756 | if (size + b > maxBytes && buf) { |
| 757 | out.push(buf); |
| 758 | buf = ""; |
| 759 | size = 0; |
| 760 | } |
| 761 | buf += ch; |
| 762 | size += b; |
| 763 | } |
| 764 | if (buf) out.push(buf); |
| 765 | return out; |
| 766 | } |
| 767 | |
| 768 | function codeFenceContinuation(fence, maxChars, maxBytes) { |
| 769 | if (fence === null) return ""; |
| 770 | const prefix = `${fence.marker}${fence.info}\n`; |
| 771 | const closingLength = fence.marker.length + 1; |
| 772 | if (charLength(prefix) + closingLength >= maxChars) return ""; |
| 773 | if (maxBytes > 0 && Buffer.byteLength(prefix, "utf8") + closingLength + 4 > maxBytes) return ""; |
| 774 | return prefix; |
| 775 | } |
| 776 | |
| 777 | function takeRenderedSplitMessageChunk(chars, offset, maxChars, openFence, maxBytes = 0) { |
| 778 | const prefix = codeFenceContinuation(openFence, maxChars, maxBytes); |
| 779 | const prefixLength = charLength(prefix); |
| 780 | let payloadLimit = Math.max(1, maxChars - prefixLength); |
| 781 | |
| 782 | while (true) { |
| 783 | let splitAt = splitMessageChunkEnd(chars, offset, payloadLimit); |
| 784 | let payload = chars.slice(offset, splitAt).join(""); |
| 785 | if (openFence === null && splitAt < chars.length) { |
| 786 | if (/^\s*`{3,}[^\r\n`]*\r?\n\s*$/.test(payload)) { |
| 787 | splitAt = Math.min(offset + payloadLimit, chars.length); |
| 788 | payload = chars.slice(offset, splitAt).join(""); |
| 789 | } else { |
| 790 | const trailingFence = /\n`{3,}[^\r\n`]*\r?\n\s*$/.exec(payload); |
| 791 | if (trailingFence && updateCodeFenceState(null, payload.slice(0, trailingFence.index + 1)) === null) { |
| 792 | splitAt = offset + charLength(payload.slice(0, trailingFence.index + 1)); |
| 793 | payload = chars.slice(offset, splitAt).join(""); |
| 794 | } |
| 795 | } |
| 796 | } |
| 797 | const body = `${prefix}${payload}`; |
| 798 | const nextOpenFence = updateCodeFenceState(openFence, payload); |
| 799 | const suffix = splitAt < chars.length && codeFenceContinuation(nextOpenFence, maxChars, maxBytes) |
| 800 | ? `${body.endsWith("\n") ? "" : "\n"}${nextOpenFence.marker}` |
| 801 | : ""; |
| 802 | const overflow = prefixLength + (splitAt - offset) + suffix.length - maxChars; |
| 803 | const byteOverflow = maxBytes > 0 ? Buffer.byteLength(`${body}${suffix}`, "utf8") - maxBytes : 0; |
| 804 | if ((overflow <= 0 && byteOverflow <= 0) || payloadLimit === 1) { |
| 805 | return { chunk: `${body}${suffix}`, offset: splitAt, openFence: nextOpenFence }; |
| 806 | } |
| 807 | payloadLimit = Math.max(1, payloadLimit - Math.max(overflow, Math.ceil(byteOverflow / 4))); |
| 808 | } |
| 809 | } |
| 810 | |
| 811 | function splitMessageChunkEnd(chars, offset, maxChars) { |
| 812 | if (chars.length - offset <= maxChars) return chars.length; |
| 813 | return offset + preferredSplitIndex(chars, offset, maxChars); |
| 814 | } |
| 815 | |
| 816 | function preferredSplitIndex(chars, offset, maxChars) { |
| 817 | const limit = Math.min(chars.length - offset, maxChars); |
| 818 | for (let i = limit - 1; i > 0; i -= 1) { |
| 819 | if (chars[offset + i] === "\n") return i + 1; |
| 820 | } |
| 821 | for (let i = limit - 1; i > 0; i -= 1) { |
| 822 | if (/\s/u.test(chars[offset + i])) return i + 1; |
| 823 | } |
| 824 | return limit; |
| 825 | } |
| 826 | |
| 827 | function charLength(text) { |
| 828 | let length = 0; |
| 829 | for (const _ of text) length += 1; |
| 830 | return length; |
| 831 | } |
| 832 | |
| 833 | function updateCodeFenceState(openFence, text) { |
| 834 | let current = openFence; |
| 835 | for (const [, marker, rest] of text.matchAll(/^(`{3,})([^\r\n`]*)\r?$/gm)) { |
| 836 | if (current === null) { |
| 837 | current = { marker, info: rest.trim() }; |
| 838 | } else if (marker.length >= current.marker.length && !rest.trim()) { |
| 839 | current = null; |
| 840 | } |
| 841 | } |
| 842 | return current; |
| 843 | } |
| 844 | |
| 845 | export async function readJsonSafe(response, { jsonOnly = false } = {}) { |
| 846 | const limit = response.ok ? 8 * 1024 * 1024 : 4096; |
| 847 | const oversized = () => { |
| 848 | if (response.ok) throw new Error("Runtime response exceeds the size limit"); |
| 849 | return jsonOnly ? null : "Runtime error body exceeds the size limit"; |
| 850 | }; |
| 851 | if (Number(response.headers.get("content-length")) > limit) { |
| 852 | await response.body?.cancel().catch(() => {}); |
| 853 | return oversized(); |
| 854 | } |
| 855 | const decoder = new TextDecoder(); |
| 856 | let size = 0; |
| 857 | let text = ""; |
| 858 | if (response.body) { |
| 859 | for await (const chunk of response.body) { |
| 860 | size += chunk.byteLength; |
| 861 | if (size > limit) return oversized(); |
| 862 | text += decoder.decode(chunk, { stream: true }); |
| 863 | } |
| 864 | text += decoder.decode(); |
| 865 | } |
| 866 | if (!text) return jsonOnly ? null : {}; |
| 867 | try { |
| 868 | return JSON.parse(text); |
| 869 | } catch { |
| 870 | return jsonOnly ? null : text; |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | const MAX_EVENT_BYTES = 2 * 1024 * 1024; |
| 875 | |
| 876 | export async function* readSse(response) { |
| 877 | const decoder = new TextDecoder("utf-8", { fatal: true }); |
| 878 | let line = Buffer.allocUnsafe(1024); |
| 879 | let length = 0, frameBytes = 0, afterCr = false; |
| 880 | let event = "", data = "", sawData = false; |
| 881 | |
| 882 | for await (const chunk of response.body) { |
| 883 | for (const byte of chunk) { |
| 884 | const pairedLf = afterCr && byte === 10; |
| 885 | afterCr = byte === 13; |
| 886 | if (pairedLf && frameBytes === 0) continue; |
| 887 | if (++frameBytes > MAX_EVENT_BYTES) throw new Error("Runtime event frame exceeds the size limit"); |
| 888 | if (pairedLf) continue; |
| 889 | if (byte !== 10 && byte !== 13) { |
| 890 | if (length === line.length) { |
| 891 | const larger = Buffer.allocUnsafe(Math.min(MAX_EVENT_BYTES, line.length * 2)); |
| 892 | line.copy(larger); |
| 893 | line = larger; |
| 894 | } |
| 895 | line[length++] = byte; |
| 896 | continue; |
| 897 | } |
| 898 | if (length === 0) { |
| 899 | if (sawData || event) yield { event, data }; |
| 900 | event = ""; |
| 901 | data = ""; |
| 902 | sawData = false; |
| 903 | frameBytes = 0; |
| 904 | continue; |
| 905 | } |
| 906 | const field = decoder.decode(line.subarray(0, length)); |
| 907 | length = 0; |
| 908 | const colon = field.indexOf(":"); |
| 909 | const name = colon < 0 ? field : field.slice(0, colon); |
| 910 | const value = colon < 0 ? "" : field.slice(colon + (field[colon + 1] === " " ? 2 : 1)); |
| 911 | if (name === "event") event = value; |
| 912 | if (name === "data") { |
| 913 | data += (sawData ? "\n" : "") + value; |
| 914 | sawData = true; |
| 915 | } |
| 916 | } |
| 917 | } |
| 918 | if (frameBytes) throw new Error("Runtime event stream ended inside a frame"); |
| 919 | } |
| 920 | |
| 921 | export async function* readThreadEvents(response, threadId) { |
| 922 | if (!threadId) throw new Error("Missing expected Runtime thread identity"); |
| 923 | for await (const { data } of readSse(response)) { |
| 924 | if (!data) continue; |
| 925 | const record = JSON.parse(data); |
| 926 | if (record?.thread_id !== threadId || typeof record.event !== "string" || !record.event) { |
| 927 | throw new Error("Invalid Runtime event or thread identity"); |
| 928 | } |
| 929 | if (record.event === "stream.end") { |
| 930 | yield record; |
| 931 | return; |
| 932 | } |
| 933 | if (!Number.isSafeInteger(record.seq) || record.seq < 0) throw new Error("Invalid Runtime event sequence"); |
| 934 | yield record; |
| 935 | } |
| 936 | throw new Error("Runtime event stream ended before a terminal event"); |
| 937 | } |
| 938 | |
| 939 | export function createRuntimeClient({ runtimeUrl, runtimeToken, runtimeRequestTimeoutMs }) { |
| 940 | function authHeaders() { |
| 941 | return { authorization: `Bearer ${runtimeToken}` }; |
| 942 | } |
| 943 | |
| 944 | async function runtimeJson(route, options = {}) { |
| 945 | const response = await fetch(`${runtimeUrl}${route}`, { |
| 946 | method: options.method || "GET", |
| 947 | headers: { |
| 948 | ...(options.auth === false ? {} : authHeaders()), |
| 949 | ...(options.body ? { "content-type": "application/json" } : {}) |
| 950 | }, |
| 951 | body: options.body ? JSON.stringify(options.body) : undefined, |
| 952 | signal: options.signal || (runtimeRequestTimeoutMs ? AbortSignal.timeout(runtimeRequestTimeoutMs) : undefined) |
| 953 | }); |
| 954 | const body = await readJsonSafe(response); |
| 955 | if (!response.ok) { |
| 956 | const error = new Error(compactRuntimeError(response.status, body)); |
| 957 | error.status = response.status; |
| 958 | throw error; |
| 959 | } |
| 960 | return body; |
| 961 | } |
| 962 | |
| 963 | return { runtimeJson, authHeaders }; |
| 964 | } |
| 965 | |
| 966 | export function compactRuntimeError(status, body) { |
| 967 | const message = |
| 968 | body?.error?.message || |
| 969 | body?.message || |
| 970 | (typeof body === "string" ? body : JSON.stringify(body)); |
| 971 | return `Runtime API request failed (${status}): ${message}`; |
| 972 | } |
| 973 | |
| 974 | export function questionText(request) { |
| 975 | const questions = Array.isArray(request?.questions) ? request.questions : []; |
| 976 | const lines = ["需要你回答 / Codewhale is asking"]; |
| 977 | for (const [index, question] of questions.entries()) { |
| 978 | const prefix = questions.length > 1 ? `${index + 1}. ` : ""; |
| 979 | lines.push(`${prefix}${question.header ? `${question.header}: ` : ""}${question.question || ""}`); |
| 980 | for (const [optionIndex, option] of (question.options || []).entries()) { |
| 981 | const description = String(option.description || "").trim(); |
| 982 | lines.push(` ${optionIndex + 1}) ${option.label}${option.description ? ` - ${description.length > 120 ? `${description.slice(0, 119)}…` : description}` : ""}`); |
| 983 | } |
| 984 | } |
| 985 | lines.push(questions.length > 1 |
| 986 | ? "每行回答一个问题,可回复选项编号或文字。/ Answer one question per line, by option number or in words." |
| 987 | : "回复选项编号或文字。/ Reply with an option number or in words."); |
| 988 | return lines.join("\n"); |
| 989 | } |
| 990 | |
| 991 | export function parseQuestionAnswers(request, text) { |
| 992 | const questions = Array.isArray(request?.questions) ? request.questions : []; |
| 993 | if (!questions.length) return null; |
| 994 | const replies = questions.length > 1 |
| 995 | ? String(text || "").split(/\n+/).map((line) => line.trim()).filter(Boolean) |
| 996 | : [String(text || "").trim()]; |
| 997 | if (replies.length !== questions.length || replies.some((reply) => !reply)) return null; |
| 998 | const answers = []; |
| 999 | for (const [index, question] of questions.entries()) { |
| 1000 | const reply = replies[index]; |
| 1001 | const options = question.options || []; |
| 1002 | const byLabel = (label) => label |
| 1003 | ? options.filter((option) => option.label.toLowerCase() === label.toLowerCase()) |
| 1004 | : []; |
| 1005 | const picks = question.multi_select ? reply.split(/[\s,,、]+/u).filter(Boolean) : [reply]; |
| 1006 | let chosen = picks.every((pick) => /^\d+$/.test(pick) && Number(pick) >= 1 && Number(pick) <= options.length) |
| 1007 | ? picks.map((pick) => options[Number(pick) - 1]) |
| 1008 | : byLabel(reply); |
| 1009 | if (!chosen.length && question.multi_select) { |
| 1010 | const named = reply.split(/[,,、]/u).map((label) => byLabel(label.trim())); |
| 1011 | if (named.length > 1 && named.every((matches) => matches.length)) chosen = named.flat(); |
| 1012 | } |
| 1013 | if (chosen.length) { |
| 1014 | for (const option of chosen) answers.push({ id: question.id, label: option.label, value: option.label }); |
| 1015 | } else if (question.allow_free_text || !options.length) { |
| 1016 | answers.push({ id: question.id, label: "Other", value: reply }); |
| 1017 | } else { |
| 1018 | return null; |
| 1019 | } |
| 1020 | } |
| 1021 | return answers; |
| 1022 | } |
| 1023 | |
| 1024 | export async function admitTurn({ runtimeJson, pending, capabilities, persistPending, ensureThread }) { |
| 1025 | if (!pending?.request || (pending.operationKey && pending.request.operation_key !== pending.operationKey)) { |
| 1026 | throw new Error("Invalid retained turn admission"); |
| 1027 | } |
| 1028 | if (pending.operationKey && (capabilities?.turn_operation_idempotency !== true || capabilities?.turn_operation_lookup !== true)) { |
| 1029 | return { pending, turn: null, uncertain: true }; |
| 1030 | } |
| 1031 | if (!pending.threadId) { |
| 1032 | const threadId = await ensureThread(pending.threadRequest); |
| 1033 | if (!threadId) throw new Error("Turn admission requires a durable thread binding"); |
| 1034 | pending = { ...pending, threadId }; |
| 1035 | await persistPending(pending); |
| 1036 | } |
| 1037 | if (pending.sinceSeq === null) { |
| 1038 | const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(pending.threadId)}`); |
| 1039 | if (latestRunningTurn(detail)) return { pending, turn: null, blocked: true }; |
| 1040 | pending = { ...pending, sinceSeq: Number(detail.latest_seq || 0) }; |
| 1041 | await persistPending(pending); |
| 1042 | } |
| 1043 | let turn; |
| 1044 | if (pending.submitted) { |
| 1045 | if (!pending.operationKey || capabilities?.turn_operation_idempotency !== true || capabilities?.turn_operation_lookup !== true) { |
| 1046 | return { pending, turn: null, uncertain: true }; |
| 1047 | } |
| 1048 | try { |
| 1049 | turn = await runtimeJson(`/v1/threads/${encodeURIComponent(pending.threadId)}/turn-operations/${encodeURIComponent(pending.operationKey)}`); |
| 1050 | } catch (error) { |
| 1051 | if (error.status !== 404) throw error; |
| 1052 | const detail = await runtimeJson(`/v1/threads/${encodeURIComponent(pending.threadId)}`); |
| 1053 | if (latestRunningTurn(detail)) return { pending, turn: null, blocked: true }; |
| 1054 | } |
| 1055 | } |
| 1056 | if (!turn) { |
| 1057 | pending = { ...pending, submitted: true }; |
| 1058 | await persistPending(pending); |
| 1059 | const result = await runtimeJson(`/v1/threads/${encodeURIComponent(pending.threadId)}/turns`, { |
| 1060 | method: "POST", body: pending.request |
| 1061 | }); |
| 1062 | turn = result?.turn; |
| 1063 | } |
| 1064 | if (!turn?.id || turn.thread_id !== pending.threadId) throw new Error("Invalid Engine admission receipt"); |
| 1065 | return { pending, turn }; |
| 1066 | } |
| 1067 | |
| 1068 | export function latestRunningTurn(detail) { |
| 1069 | const turns = Array.isArray(detail?.turns) ? detail.turns : []; |
| 1070 | for (let index = turns.length - 1; index >= 0; index -= 1) { |
| 1071 | const turn = turns[index]; |
| 1072 | if (["queued", "in_progress"].includes(turn?.status)) return turn; |
| 1073 | } |
| 1074 | return null; |
| 1075 | } |
| 1076 | |
| 1077 | export function activeTurnBlock(detail, state = {}) { |
| 1078 | const runningTurn = latestRunningTurn(detail); |
| 1079 | if (!runningTurn) return null; |
| 1080 | const activeTurnId = state?.activeTurnId || ""; |
| 1081 | return { |
| 1082 | turnId: runningTurn.id || activeTurnId, |
| 1083 | message: `Thread already has active turn ${ |
| 1084 | runningTurn.id || activeTurnId || "(unknown)" |
| 1085 | }. Wait for it to finish or send /interrupt.` |
| 1086 | }; |
| 1087 | } |
| 1088 | |
| 1089 | export function turnTerminalStatus(record) { |
| 1090 | if (record.event === "turn.completed") return record.payload?.turn?.status || "completed"; |
| 1091 | if (record.event !== "turn.lifecycle") return null; |
| 1092 | const status = record.payload?.turn?.status || record.payload?.status; |
| 1093 | return ["failed", "canceled", "interrupted"].includes(status) ? status : null; |
| 1094 | } |
| 1095 | |
| 1096 | export function turnOutcomeText({ status, text, error }) { |
| 1097 | if (status === "completed") return text.trim() || "Turn completed."; |
| 1098 | return `Turn ${status}.${error ? `\n${error}` : ""}`; |
| 1099 | } |
| 1100 | |
| 1101 | export async function observeTurn({ |
| 1102 | fetchEvents, |
| 1103 | threadId, |
| 1104 | turnId, |
| 1105 | sinceSeq, |
| 1106 | responseText = "", |
| 1107 | timeoutMs, |
| 1108 | saveCursor, |
| 1109 | onDelta = (text) => text, |
| 1110 | onApproval = async () => {}, |
| 1111 | onTerminal, |
| 1112 | onTimeout = async () => {} |
| 1113 | }) { |
| 1114 | const controller = new AbortController(); |
| 1115 | const timeout = setTimeout(() => controller.abort(), timeoutMs); |
| 1116 | let text = responseText; |
| 1117 | let latestSeq = Number(sinceSeq || 0); |
| 1118 | try { |
| 1119 | const response = await fetchEvents(latestSeq, controller.signal); |
| 1120 | if (!response.ok) throw new Error(compactRuntimeError(response.status, await readJsonSafe(response))); |
| 1121 | for await (const record of readThreadEvents(response, threadId)) { |
| 1122 | if (record.event === "stream.end") return false; |
| 1123 | latestSeq = Math.max(latestSeq, Number(record.seq || 0)); |
| 1124 | if (turnId && record.turn_id === turnId) { |
| 1125 | if (record.event === "item.delta" && record.payload?.kind === "agent_message") { |
| 1126 | text = await onDelta(text + (record.payload.delta || "")); |
| 1127 | } |
| 1128 | if (record.event === "approval.required") await onApproval(record.payload || {}); |
| 1129 | const status = turnTerminalStatus(record); |
| 1130 | if (status) { |
| 1131 | const error = record.payload?.turn?.error || record.payload?.error || ""; |
| 1132 | await onTerminal({ status, text, error }); |
| 1133 | await saveCursor({ lastSeq: latestSeq, responseText: "" }); |
| 1134 | return true; |
| 1135 | } |
| 1136 | } |
| 1137 | await saveCursor({ lastSeq: latestSeq, responseText: text }); |
| 1138 | } |
| 1139 | return false; |
| 1140 | } catch (error) { |
| 1141 | if (error.name !== "AbortError") throw error; |
| 1142 | await onTimeout(text); |
| 1143 | return false; |
| 1144 | } finally { |
| 1145 | clearTimeout(timeout); |
| 1146 | } |
| 1147 | } |
| 1148 |