-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Extract shared bridge core helpers #3432
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Hmbown
wants to merge
2
commits into
main
Choose a base branch
from
feature/bridge-core-consolidation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+672
−895
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| { | ||
| "name": "@codewhale/bridge-core", | ||
| "version": "0.1.0", | ||
| "private": true, | ||
| "type": "module", | ||
| "description": "Shared pure helpers for CodeWhale chat bridges.", | ||
| "main": "src/lib.mjs", | ||
| "scripts": { | ||
| "check": "node --check src/lib.mjs", | ||
| "test": "node --test test/*.test.mjs" | ||
| }, | ||
| "engines": { | ||
| "node": ">=18" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,330 @@ | ||||||||||||||||||
| import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises"; | ||||||||||||||||||
| import path from "node:path"; | ||||||||||||||||||
|
|
||||||||||||||||||
| const DEFAULT_ACTION_TTL_MS = 24 * 60 * 60 * 1000; | ||||||||||||||||||
|
|
||||||||||||||||||
| async function chmodBestEffort(filePath, mode) { | ||||||||||||||||||
| try { | ||||||||||||||||||
| await chmod(filePath, mode); | ||||||||||||||||||
| } catch (error) { | ||||||||||||||||||
| if (process.platform !== "win32") throw error; | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export class ThreadStore { | ||||||||||||||||||
| static async open(filePath, options = {}) { | ||||||||||||||||||
| const store = new ThreadStore(filePath, options); | ||||||||||||||||||
| await store.load(); | ||||||||||||||||||
| return store; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| constructor(filePath, options = {}) { | ||||||||||||||||||
| this.filePath = filePath; | ||||||||||||||||||
| this.options = { | ||||||||||||||||||
| messageLimit: options.messageLimit || 0, | ||||||||||||||||||
| actions: options.actions === true, | ||||||||||||||||||
| actionLimit: options.actionLimit || 200, | ||||||||||||||||||
| actionTtlMs: options.actionTtlMs || DEFAULT_ACTION_TTL_MS, | ||||||||||||||||||
| privateMode: options.privateMode === true | ||||||||||||||||||
| }; | ||||||||||||||||||
| this.data = { chats: {} }; | ||||||||||||||||||
| this.ensureShape(); | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| ensureShape() { | ||||||||||||||||||
| if (!this.data || typeof this.data !== "object") this.data = {}; | ||||||||||||||||||
| if (!this.data.chats || typeof this.data.chats !== "object") this.data.chats = {}; | ||||||||||||||||||
| if (this.options.messageLimit > 0 && !Array.isArray(this.data.messages)) { | ||||||||||||||||||
| this.data.messages = []; | ||||||||||||||||||
| } | ||||||||||||||||||
| if (this.options.actions && (!this.data.actions || typeof this.data.actions !== "object")) { | ||||||||||||||||||
| this.data.actions = {}; | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| async load() { | ||||||||||||||||||
| try { | ||||||||||||||||||
| const raw = await readFile(this.filePath, "utf8"); | ||||||||||||||||||
| this.data = JSON.parse(raw); | ||||||||||||||||||
| this.ensureShape(); | ||||||||||||||||||
| } catch (error) { | ||||||||||||||||||
| if (error.code !== "ENOENT") throw error; | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| async recordMessage(messageKey) { | ||||||||||||||||||
| if (!messageKey || this.options.messageLimit <= 0) return false; | ||||||||||||||||||
| this.ensureShape(); | ||||||||||||||||||
| if (this.data.messages.includes(messageKey)) return true; | ||||||||||||||||||
| this.data.messages.push(messageKey); | ||||||||||||||||||
| this.data.messages = this.data.messages.slice(-this.options.messageLimit); | ||||||||||||||||||
| await this.save(); | ||||||||||||||||||
| return false; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| async getChat(chatId) { | ||||||||||||||||||
| return this.data.chats[chatId] || null; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| listChats() { | ||||||||||||||||||
| return Object.entries(this.data.chats || {}); | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| async setChat(chatId, state) { | ||||||||||||||||||
| this.data.chats[chatId] = state; | ||||||||||||||||||
| await this.save(); | ||||||||||||||||||
| return state; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| async patchChat(chatId, patch) { | ||||||||||||||||||
| const current = this.data.chats[chatId] || {}; | ||||||||||||||||||
| this.data.chats[chatId] = { ...current, ...patch }; | ||||||||||||||||||
| await this.save(); | ||||||||||||||||||
| return this.data.chats[chatId]; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| async putAction(action) { | ||||||||||||||||||
| if (!this.options.actions) return ""; | ||||||||||||||||||
| this.ensureShape(); | ||||||||||||||||||
| const token = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; | ||||||||||||||||||
| this.data.actions[token] = { | ||||||||||||||||||
| ...action, | ||||||||||||||||||
| createdAt: new Date().toISOString() | ||||||||||||||||||
| }; | ||||||||||||||||||
| this.pruneActions(); | ||||||||||||||||||
| await this.save(); | ||||||||||||||||||
| return token; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| async getAction(token) { | ||||||||||||||||||
| if (!token || !this.options.actions) return null; | ||||||||||||||||||
| this.ensureShape(); | ||||||||||||||||||
| return this.data.actions[token] || null; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| async takeAction(token) { | ||||||||||||||||||
| const action = await this.getAction(token); | ||||||||||||||||||
| if (action) { | ||||||||||||||||||
| delete this.data.actions[token]; | ||||||||||||||||||
| await this.save(); | ||||||||||||||||||
| } | ||||||||||||||||||
| return action; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| pruneActions() { | ||||||||||||||||||
| if (!this.options.actions) return; | ||||||||||||||||||
| const cutoff = Date.now() - this.options.actionTtlMs; | ||||||||||||||||||
| const fresh = Object.entries(this.data.actions || {}).filter(([, action]) => { | ||||||||||||||||||
| const time = Date.parse(action.createdAt || ""); | ||||||||||||||||||
| return Number.isFinite(time) && time >= cutoff; | ||||||||||||||||||
| }); | ||||||||||||||||||
| this.data.actions = Object.fromEntries(fresh.slice(-this.options.actionLimit)); | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| async save() { | ||||||||||||||||||
| const dir = path.dirname(this.filePath); | ||||||||||||||||||
| await mkdir(dir, { recursive: true, mode: 0o700 }); | ||||||||||||||||||
| if (this.options.privateMode) await chmodBestEffort(dir, 0o700); | ||||||||||||||||||
| const tmp = `${this.filePath}.tmp`; | ||||||||||||||||||
| await writeFile(tmp, `${JSON.stringify(this.data, null, 2)}\n`, { mode: 0o600 }); | ||||||||||||||||||
| if (this.options.privateMode) await chmodBestEffort(tmp, 0o600); | ||||||||||||||||||
| await rename(tmp, this.filePath); | ||||||||||||||||||
| if (this.options.privateMode) await chmodBestEffort(this.filePath, 0o600); | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function envFirst(env, ...names) { | ||||||||||||||||||
| for (const name of names) { | ||||||||||||||||||
| const value = env?.[name]; | ||||||||||||||||||
| if (value != null && String(value).trim()) return String(value).trim(); | ||||||||||||||||||
| } | ||||||||||||||||||
| return ""; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function parseList(raw) { | ||||||||||||||||||
| return String(raw || "") | ||||||||||||||||||
| .split(",") | ||||||||||||||||||
| .map((item) => item.trim()) | ||||||||||||||||||
| .filter(Boolean); | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function parseBool(raw, fallback = false) { | ||||||||||||||||||
| if (raw == null || raw === "") return fallback; | ||||||||||||||||||
| return ["1", "true", "yes", "on"].includes(String(raw).trim().toLowerCase()); | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function parseEnvText(raw) { | ||||||||||||||||||
| const env = {}; | ||||||||||||||||||
| for (const line of String(raw || "").split(/\r?\n/)) { | ||||||||||||||||||
| const trimmed = line.trim(); | ||||||||||||||||||
| if (!trimmed || trimmed.startsWith("#")) continue; | ||||||||||||||||||
| const normalized = trimmed.startsWith("export ") ? trimmed.slice(7).trim() : trimmed; | ||||||||||||||||||
| const index = normalized.indexOf("="); | ||||||||||||||||||
| if (index <= 0) continue; | ||||||||||||||||||
| const key = normalized.slice(0, index).trim(); | ||||||||||||||||||
| let value = normalized.slice(index + 1).trim(); | ||||||||||||||||||
| if ( | ||||||||||||||||||
| (value.startsWith('"') && value.endsWith('"')) || | ||||||||||||||||||
| (value.startsWith("'") && value.endsWith("'")) | ||||||||||||||||||
| ) { | ||||||||||||||||||
| value = value.slice(1, -1); | ||||||||||||||||||
| } | ||||||||||||||||||
| env[key] = value; | ||||||||||||||||||
| } | ||||||||||||||||||
| return env; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function cleanEnvValue(value) { | ||||||||||||||||||
| return String(value ?? "").trim(); | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function isPlaceholderValue(value) { | ||||||||||||||||||
| const normalized = cleanEnvValue(value).toLowerCase(); | ||||||||||||||||||
| return ( | ||||||||||||||||||
| !normalized || | ||||||||||||||||||
| normalized.includes("replace-with") || | ||||||||||||||||||
| normalized.includes("xxxxxxxx") || | ||||||||||||||||||
| normalized === "changeme" | ||||||||||||||||||
| ); | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function parseTextContent(content, keys = ["text", "content"]) { | ||||||||||||||||||
| if (typeof content !== "string") return ""; | ||||||||||||||||||
| try { | ||||||||||||||||||
| const parsed = JSON.parse(content); | ||||||||||||||||||
| for (const key of keys) { | ||||||||||||||||||
| if (typeof parsed?.[key] === "string") return parsed[key]; | ||||||||||||||||||
| } | ||||||||||||||||||
| } catch { | ||||||||||||||||||
| return content; | ||||||||||||||||||
| } | ||||||||||||||||||
| return content; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function stripGroupPrefix(text, { chatType, requirePrefix, prefix, directChatTypes = [] }) { | ||||||||||||||||||
| const trimmed = String(text || "").trim(); | ||||||||||||||||||
| if (!trimmed) return { accepted: false, text: "" }; | ||||||||||||||||||
| if (!requirePrefix || directChatTypes.includes(chatType)) { | ||||||||||||||||||
| return { accepted: true, text: trimmed }; | ||||||||||||||||||
| } | ||||||||||||||||||
| const marker = prefix || "/ds"; | ||||||||||||||||||
| if (trimmed === marker) return { accepted: true, text: "/help" }; | ||||||||||||||||||
| if (trimmed.startsWith(`${marker} `)) { | ||||||||||||||||||
| return { accepted: true, text: trimmed.slice(marker.length).trim() }; | ||||||||||||||||||
| } | ||||||||||||||||||
| return { accepted: false, text: "" }; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function parseCommand(text, options = {}) { | ||||||||||||||||||
| const trimmed = String(text || "").trim(); | ||||||||||||||||||
| if (!trimmed.startsWith("/")) return { name: "prompt", args: trimmed }; | ||||||||||||||||||
| const [head, ...rest] = trimmed.split(/\s+/); | ||||||||||||||||||
| const rawName = head.slice(1); | ||||||||||||||||||
| const name = (options.stripBotMention ? rawName.split("@")[0] : rawName).toLowerCase(); | ||||||||||||||||||
| return { | ||||||||||||||||||
| name, | ||||||||||||||||||
| args: rest.join(" ").trim() | ||||||||||||||||||
| }; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function parseApprovalDecisionArgs(args) { | ||||||||||||||||||
| const parts = String(args || "") | ||||||||||||||||||
| .split(/\s+/) | ||||||||||||||||||
| .filter(Boolean); | ||||||||||||||||||
| return { | ||||||||||||||||||
| approvalId: parts[0] || "", | ||||||||||||||||||
| remember: parts.slice(1).includes("remember") | ||||||||||||||||||
| }; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function commandAction(command, options = {}) { | ||||||||||||||||||
| const allowMenu = options.allowMenu === true; | ||||||||||||||||||
| const allowStart = options.allowStart === true; | ||||||||||||||||||
| switch (command.name) { | ||||||||||||||||||
| case "start": | ||||||||||||||||||
| if (allowStart) return { kind: "help" }; | ||||||||||||||||||
| break; | ||||||||||||||||||
| case "help": | ||||||||||||||||||
| return { kind: "help" }; | ||||||||||||||||||
| case "menu": | ||||||||||||||||||
| if (allowMenu) return { kind: "menu" }; | ||||||||||||||||||
| break; | ||||||||||||||||||
| case "status": | ||||||||||||||||||
| return { kind: "status" }; | ||||||||||||||||||
| case "threads": | ||||||||||||||||||
| return { kind: "threads" }; | ||||||||||||||||||
| case "new": | ||||||||||||||||||
| return { kind: "new_thread" }; | ||||||||||||||||||
| case "resume": | ||||||||||||||||||
| return { kind: "resume", threadId: command.args }; | ||||||||||||||||||
| case "interrupt": | ||||||||||||||||||
| return { kind: "interrupt" }; | ||||||||||||||||||
| case "compact": | ||||||||||||||||||
| return { kind: "compact" }; | ||||||||||||||||||
| case "model": | ||||||||||||||||||
| return { kind: "set_model", modelName: command.args }; | ||||||||||||||||||
| case "allow": | ||||||||||||||||||
| return { kind: "approval", decision: "allow", ...parseApprovalDecisionArgs(command.args) }; | ||||||||||||||||||
| case "deny": | ||||||||||||||||||
| return { kind: "approval", decision: "deny", ...parseApprovalDecisionArgs(command.args) }; | ||||||||||||||||||
| case "prompt": | ||||||||||||||||||
| return { kind: "prompt", prompt: command.args }; | ||||||||||||||||||
| default: | ||||||||||||||||||
| break; | ||||||||||||||||||
| } | ||||||||||||||||||
| return { | ||||||||||||||||||
| kind: "prompt", | ||||||||||||||||||
| prompt: `/${command.name}${command.args ? ` ${command.args}` : ""}` | ||||||||||||||||||
| }; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function preservedChatStateFields(state = {}, fields = ["model"]) { | ||||||||||||||||||
| const preserved = {}; | ||||||||||||||||||
| for (const field of fields) { | ||||||||||||||||||
| if (Object.prototype.hasOwnProperty.call(state || {}, field)) { | ||||||||||||||||||
| preserved[field] = state[field] || null; | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
| return preserved; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function splitMessage(text, maxChars = 3500) { | ||||||||||||||||||
| const value = String(text || ""); | ||||||||||||||||||
| const chars = Array.from(value); | ||||||||||||||||||
| if (chars.length <= maxChars) return value ? [value] : []; | ||||||||||||||||||
| const chunks = []; | ||||||||||||||||||
| let cursor = 0; | ||||||||||||||||||
| while (cursor < chars.length) { | ||||||||||||||||||
| chunks.push(chars.slice(cursor, cursor + maxChars).join("")); | ||||||||||||||||||
| cursor += maxChars; | ||||||||||||||||||
| } | ||||||||||||||||||
| return chunks; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function compactRuntimeError(status, body) { | ||||||||||||||||||
| const message = | ||||||||||||||||||
| body?.error?.message || | ||||||||||||||||||
| body?.message || | ||||||||||||||||||
| (typeof body === "string" ? body : JSON.stringify(body)); | ||||||||||||||||||
| return `Runtime API request failed (${status}): ${message}`; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function latestRunningTurn(detail) { | ||||||||||||||||||
| const turns = Array.isArray(detail?.turns) ? detail.turns : []; | ||||||||||||||||||
| for (let index = turns.length - 1; index >= 0; index -= 1) { | ||||||||||||||||||
| const turn = turns[index]; | ||||||||||||||||||
| if (["queued", "in_progress"].includes(turn?.status)) return turn; | ||||||||||||||||||
| } | ||||||||||||||||||
| return null; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| export function activeTurnBlock(detail, state = {}) { | ||||||||||||||||||
| const runningTurn = latestRunningTurn(detail); | ||||||||||||||||||
| if (!runningTurn) return null; | ||||||||||||||||||
| return { | ||||||||||||||||||
| turnId: runningTurn.id || state.activeTurnId || "", | ||||||||||||||||||
| message: `Thread already has active turn ${ | ||||||||||||||||||
| runningTurn.id || state.activeTurnId || "(unknown)" | ||||||||||||||||||
| }. Wait for it to finish or send /interrupt.` | ||||||||||||||||||
|
Comment on lines
+325
to
+328
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If
Suggested change
|
||||||||||||||||||
| }; | ||||||||||||||||||
| } | ||||||||||||||||||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In
parseEnvText, if the value is a single quote or double quote character (e.g.,"or'), the current logic will strip it to an empty string becausestartsWithandendsWithboth match the same single character. Adding a length check ensures that only valid quoted strings (with at least an opening and a closing quote) are stripped.