import type { SessionMessageAssistantTool, SessionMessageInfo } from "@opencode/client/promise" import type { IconName } from "@opencode/plugin/gui" import { Predicate, Schema } from "effect" import { artifactAddress, artifactLink } from "./artifact-link" import { bare, MAX_URL_LENGTH, pageKey } from "./history/page" import type { Visit } from "./history/visits" import { workspacePrefix } from "./remote-address" export type SessionLinkKind = "console" | "github" | "local" | "preview" export type SessionLink = { readonly url: string readonly key: string readonly kind: SessionLinkKind readonly title: string readonly detail: string readonly icon: string | undefined readonly fallbackIcon: IconName } export type SessionLinkTab = { readonly url: string readonly title: string readonly icon?: string } export type SessionLinkOptions = { readonly sessionKey?: string readonly sessionID?: string readonly serverUrl?: string readonly builtinServer?: boolean readonly limit?: number } const CachedSessionLink = Schema.Struct({ url: Schema.String, label: Schema.optionalKey(Schema.String), }) export type CachedSessionLink = typeof CachedSessionLink.Type const CachedSessionEntry = Schema.Struct({ session: Schema.String, /** Last message ID scanned into `links`, so incremental syncs skip earlier history. */ lastMessageID: Schema.optionalKey(Schema.String), /** Links newest-first. */ links: Schema.Array(CachedSessionLink), }) export const SessionLinksStore = Schema.Struct({ sessions: Schema.Array(CachedSessionEntry), }) export type SessionLinksStore = typeof SessionLinksStore.Type type ClassifiedLink = { readonly url: string readonly key: string readonly kind: SessionLinkKind readonly title: string readonly detail: string readonly origin?: string readonly fallbackIcon: IconName } type Candidate = ClassifiedLink & { label?: string tabTitle?: string tabIcon?: string } const DEFAULT_LIMIT = 8 const MAX_CACHED_SESSIONS = 50 const MAX_CACHED_LINKS = 20 /** When a session has no cached links yet, scan at most this many recent assistant messages. */ export const COLD_ASSISTANT_LIMIT = 10 const GENERIC_LABELS = [ "here", "link", "this link", "open", "view", "click here", "url", "page", "preview", ] const GITHUB_CHROME_PATHS = [ "login", "signup", "logout", "settings", "notifications", "session", "sessions", "new", "marketplace", "explore", "sponsors", "features", "pricing", "enterprise", "topics", "trending", "collections", "events", "about", "site", "security", "contact", "customer-stories", "readme", "search", ] const PREVIEW_SUFFIXES = [ ".trycloudflare.com", ".cfargotunnel.com", ".vercel.app", ".pages.dev", ".netlify.app", ".fly.dev", ".onrender.com", ".railway.app", ".workers.dev", ".ngrok-free.app", ".ngrok-free.dev", ".ngrok.io", ".ngrok.app", ".loca.lt", ".lhr.life", ] /** Normalizes a URL to the same deduplication key used by session links. */ export function sessionLinkKey(url: string, serverUrl?: string) { const artifact = serverUrl ? artifactLink(url, serverUrl) : undefined if (artifact) return artifact const key = pageKey(normalizeLocalHost(url)) return key ?? url } /** Classifies a URL into one of the supported session-link kinds, or undefined if it does not belong. */ export function classifySessionLink(raw: string, options: SessionLinkOptions = {}): ClassifiedLink | undefined { const cleaned = cleanRawURL(raw) if (!cleaned || cleaned.length > MAX_URL_LENGTH) return undefined const serverArtifact = options.serverUrl ? artifactLink(cleaned, options.serverUrl) : undefined const address = serverArtifact ?? cleaned if (address.startsWith("artifact://")) { const item = artifactAddress(address) if (!item) return undefined return { url: address, key: address, kind: "console", title: fileNameFromPath(item.path) || "Artifact", detail: address, fallbackIcon: "file-document", } } if (address.startsWith("workspace://")) { if (options.sessionID && !address.startsWith(workspacePrefix(options.sessionID))) return undefined return { url: address, key: address, kind: "local", title: fileNameFromPath(address.slice("workspace://".length)), detail: address, fallbackIcon: "file-document", } } if (address.startsWith("file://")) { if (!options.builtinServer) return undefined return { url: address, key: address, kind: "local", title: fileNameFromPath(address.slice("file://".length)), detail: address, fallbackIcon: "file-document", } } if (!URL.canParse(address)) return undefined const normalized = normalizeLocalHost(address) const parsed = new URL(normalized) if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.username || parsed.password) { return undefined } const key = pageKey(normalized) if (!key) return undefined const host = parsed.hostname.toLowerCase() const detail = bare(normalized) const consoleMatch = matchConsole(parsed, host, normalized, key, detail) if (consoleMatch) return consoleMatch const githubMatch = matchGitHub(parsed, host, normalized, key, detail) if (githubMatch) return githubMatch if (isLocalHost(host)) { return { url: normalized, key, kind: "local", title: "", detail, origin: parsed.origin, fallbackIcon: "globe", } } if (isPreviewHost(host)) { return { url: normalized, key, kind: "preview", title: "", detail, origin: parsed.origin, fallbackIcon: "globe", } } return undefined } /** Extracts markdown links and bare URLs from text, skipping fenced code blocks. */ export function extractTextLinks(text: string): Array<{ url: string; label?: string }> { if (!text) return [] const stripped = stripFencedCode(text) const results: Array<{ url: string; label?: string; index: number }> = [] const covered: Array<[number, number]> = [] const mdPattern = /\[([^\]\n]{1,200})\]\(((?:https?|artifact|workspace|file):\/\/[^\s<>)]+(?:\([^\s<>)]*\)[^\s<>)]*)*)\)/gi for (const match of stripped.matchAll(mdPattern)) { const start = match.index ?? 0 const end = start + match[0].length covered.push([start, end]) results.push({ url: match[2], label: cleanLabel(match[1], match[2]), index: start }) } const barePattern = /(?`"'\]\\]+)/gi for (const match of stripped.matchAll(barePattern)) { const start = match.index ?? 0 if (covered.some(([from, to]) => start >= from && start < to)) continue results.push({ url: match[1], index: start }) } return results .sort((a, b) => a.index - b.index) .map(({ url, label }) => (label ? { url, label } : { url })) } /** Returns the cached links for one session, newest-first. */ export function cachedSessionLinks(store: SessionLinksStore, sessionKey: string): readonly CachedSessionLink[] { return store.sessions.find((item) => item.session === sessionKey)?.links ?? [] } /** * Incrementally updates a session's cached links from its messages. When no cache exists for the session yet, only the * last `COLD_ASSISTANT_LIMIT` assistant messages (and surrounding user messages) are parsed. Returns undefined when * nothing changed. */ export function syncSessionLinks( store: SessionLinksStore, sessionKey: string, messages: readonly SessionMessageInfo[], options: SessionLinkOptions = {}, ): SessionLinksStore | undefined { if (messages.length === 0) return undefined const existing = store.sessions.find((item) => item.session === sessionKey) const lastIndex = existing?.lastMessageID ? messages.findIndex((message) => message.id === existing.lastMessageID) : -1 const slice = lastIndex >= 0 ? messages.slice(lastIndex) : coldMessageSlice(messages, COLD_ASSISTANT_LIMIT) const merged = new Map() const upsert = (raw: string, label?: string) => { const classified = classifySessionLink(raw, options) if (!classified) return const previous = merged.get(classified.key) if (previous) merged.delete(classified.key) const nextLabel = label || previous?.label merged.set(classified.key, nextLabel ? { url: classified.url, label: nextLabel } : { url: classified.url }) } // Seed with previously cached links (oldest-first so newer messages move repeated links to the front). if (existing) { for (const item of [...existing.links].reverse()) { upsert(item.url, item.label) } } for (const message of slice) { for (const link of extractMessageLinks(message)) upsert(link.url, link.label) } const nextLinks = [...merged.values()].reverse().slice(0, MAX_CACHED_LINKS) const nextLastMessageID = messages[messages.length - 1]?.id if ( existing && existing.lastMessageID === nextLastMessageID && cachedLinksEqual(existing.links, nextLinks) ) { return undefined } const entry = nextLastMessageID ? { session: sessionKey, lastMessageID: nextLastMessageID, links: nextLinks } : { session: sessionKey, links: nextLinks } return { sessions: [entry, ...store.sessions.filter((item) => item.session !== sessionKey)].slice(0, MAX_CACHED_SESSIONS), } } /** Resolves cached session links, open tabs, and session visits into display rows enriched from browser history. */ export function resolveSessionLinks( cached: readonly CachedSessionLink[], visits: readonly Visit[], tabs: readonly SessionLinkTab[] = [], options: SessionLinkOptions = {}, ): SessionLink[] { const candidates = new Map() const record = (raw: string, extra?: { label?: string; tabTitle?: string; tabIcon?: string }) => { const classified = classifySessionLink(raw, options) if (!classified) return const previous = candidates.get(classified.key) if (previous) candidates.delete(classified.key) candidates.set(classified.key, { ...classified, label: extra?.label || previous?.label, tabTitle: extra?.tabTitle || previous?.tabTitle, tabIcon: extra?.tabIcon || previous?.tabIcon, }) } // Cached links are newest-first; walk oldest-first so newer entries stay ahead. for (const item of [...cached].reverse()) { record(item.url, { label: item.label }) } // Session-scoped visits (artifacts and this session's workspace files) are stored newest-first, so walk oldest-first. for (const visit of [...visits].reverse()) { const belongs = (options.sessionKey && visit.session === options.sessionKey) || (options.sessionID && visit.url.startsWith(workspacePrefix(options.sessionID))) if (!belongs) continue record(visit.url, { tabTitle: visit.title, tabIcon: visit.icon }) } for (const tab of tabs) { record(tab.url, { tabTitle: tab.title, tabIcon: tab.icon }) } const visitByKey = new Map() const iconByOrigin = new Map() for (const visit of visits) { const key = sessionLinkKey(visit.url, options.serverUrl) if (!visitByKey.has(key)) visitByKey.set(key, visit) if (visit.icon && URL.canParse(visit.url)) { const origin = new URL(normalizeLocalHost(visit.url)).origin if (!iconByOrigin.has(origin)) iconByOrigin.set(origin, visit.icon) } } const limit = options.limit ?? DEFAULT_LIMIT const newestFirst = [...candidates.values()].reverse() const prioritized = [ ...newestFirst.filter((item) => item.kind === "github"), ...newestFirst.filter((item) => item.kind !== "github"), ] return prioritized .slice(0, limit) .map((item) => { const visit = visitByKey.get(item.key) const originIcon = (item.kind === "local" || item.kind === "preview") && item.origin ? iconByOrigin.get(item.origin) : undefined const title = pickTitle(item.detail, [visit?.title, item.tabTitle, item.label, item.title]) return { url: item.url, key: item.key, kind: item.kind, title, detail: item.detail, icon: visit?.icon ?? item.tabIcon ?? originIcon, fallbackIcon: item.fallbackIcon, } }) } /** Collects and enriches high-signal links from the session's messages, open tabs, and browser visits. */ export function sessionLinks( messages: readonly SessionMessageInfo[], visits: readonly Visit[], tabs: readonly SessionLinkTab[] = [], options: SessionLinkOptions = {}, ): SessionLink[] { const synced = syncSessionLinks({ sessions: [] }, options.sessionKey ?? "", messages, options) const cached = synced ? cachedSessionLinks(synced, options.sessionKey ?? "") : [] return resolveSessionLinks(cached, visits, tabs, options) } function coldMessageSlice(messages: readonly SessionMessageInfo[], assistantLimit: number) { let seen = 0 for (let index = messages.length - 1; index >= 0; index -= 1) { if (messages[index].type !== "assistant") continue seen += 1 if (seen < assistantLimit) continue // Include the user message immediately preceding the oldest assistant message in the window. const start = index > 0 && messages[index - 1].type === "user" ? index - 1 : index return messages.slice(start) } return messages } function extractMessageLinks(message: SessionMessageInfo): Array<{ url: string; label?: string }> { if (message.type === "user") return extractTextLinks(message.text) if (message.type !== "assistant") return [] return message.content.flatMap((part) => { if (part.type === "text") return extractTextLinks(part.text) if (part.type === "tool") return extractToolLinks(part) return [] }) } function cachedLinksEqual(a: readonly CachedSessionLink[], b: readonly CachedSessionLink[]) { return a.length === b.length && a.every((item, index) => item.url === b[index].url && item.label === b[index].label) } // Only tools that explicitly navigate or open a URL contribute via input.url; raw shell/read stdout is too noisy. function extractToolLinks(tool: SessionMessageAssistantTool): Array<{ url: string; label?: string }> { if (tool.state.status === "streaming" || tool.state.status === "error") return [] const inputUrl = tool.state.input.url return Predicate.isString(inputUrl) ? [{ url: inputUrl }] : [] } function matchConsole(parsed: URL, host: string, url: string, key: string, detail: string): ClassifiedLink | undefined { const segments = parsed.pathname.split("/").filter(Boolean) if ((host !== "opncd.ai" && !host.endsWith(".opncd.ai")) || segments.length === 0) return undefined return { url, key, kind: "console", title: "Artifact", detail, fallbackIcon: "file-document", } } function matchGitHub(parsed: URL, host: string, url: string, key: string, detail: string): ClassifiedLink | undefined { if (host !== "github.com" && host !== "www.github.com") return undefined const segments = parsed.pathname.split("/").filter(Boolean) if (segments.length < 2 || GITHUB_CHROME_PATHS.includes(segments[0].toLowerCase())) return undefined const repo = `${segments[0]}/${segments[1]}` const title = githubTitle(repo, segments) return { url, key, kind: "github", title, detail, fallbackIcon: "github", } } function githubTitle(repo: string, segments: readonly string[]) { const section = segments[2] const id = segments[3] if (section === "pull" && id && /^\d+$/.test(id)) return `PR #${id} · ${repo}` if (section === "issues" && id && /^\d+$/.test(id)) return `Issue #${id} · ${repo}` if (section === "discussions" && id && /^\d+$/.test(id)) return `Discussion #${id} · ${repo}` if (section === "actions" && id === "runs") return `Actions run · ${repo}` if (section === "actions") return `Actions · ${repo}` if (section === "commit" && id) return `Commit ${id.slice(0, 7)} · ${repo}` if (section === "releases" && id === "tag" && segments[4]) return `Release ${decodeURISafe(segments[4])} · ${repo}` if (section === "compare") return `Compare · ${repo}` if ((section === "blob" || section === "tree") && segments.length > 4) { return `${decodeURISafe(segments[segments.length - 1])} · ${repo}` } return repo } function isLocalHost(host: string) { if ( host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]" || host === "0.0.0.0" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".ts.net") ) { return true } return isTailscaleOrPrivateIPv4(host) } function isTailscaleOrPrivateIPv4(host: string) { const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host) if (!match) return false const a = Number(match[1]) const b = Number(match[2]) const c = Number(match[3]) const d = Number(match[4]) if (a > 255 || b > 255 || c > 255 || d > 255) return false // Tailscale CGNAT (100.64.0.0/10) if (a === 100 && b >= 64 && b <= 127) return true // Private LAN ranges if (a === 10) return true if (a === 192 && b === 168) return true return a === 172 && b >= 16 && b <= 31 } function isPreviewHost(host: string) { return PREVIEW_SUFFIXES.some((suffix) => host.endsWith(suffix) && host.length > suffix.length) } function normalizeLocalHost(url: string) { return url.replace(/^(https?:\/\/)0\.0\.0\.0(?=[:/?#]|$)/i, "$1localhost") } function stripFencedCode(text: string) { return text.replace(/^```[\s\S]*?^```\s*$/gm, "").replace(/^~~~[\s\S]*?^~~~\s*$/gm, "") } function cleanRawURL(raw: string) { let value = raw.trim() while (value.length > 0) { const last = value[value.length - 1] if (/[.,;:!?'"\]>\`]/.test(last)) { value = value.slice(0, -1) continue } if (last === ")") { const opens = (value.match(/\(/g) ?? []).length const closes = (value.match(/\)/g) ?? []).length if (closes > opens) { value = value.slice(0, -1) continue } } break } return value } function cleanLabel(label: string, url: string) { const trimmed = label.replace(/[`*_~]/g, "").trim() if (!trimmed || GENERIC_LABELS.includes(trimmed.toLowerCase())) return undefined const stripped = bare(trimmed).replace(/\/+$/, "") const target = bare(cleanRawURL(url)).replace(/\/+$/, "") if (stripped.toLowerCase() === target.toLowerCase()) return undefined return trimmed } function pickTitle(detail: string, candidates: readonly (string | undefined)[]) { const normalizedDetail = detail.replace(/\/+$/, "").toLowerCase() for (const candidate of candidates) { const trimmed = candidate?.trim() if (!trimmed) continue if (bare(trimmed).replace(/\/+$/, "").toLowerCase() === normalizedDetail) continue return trimmed } return "" } function fileNameFromPath(value: string) { const trimmed = value.replace(/[?#].*$/, "").replace(/\/+$/, "") const segment = trimmed.split("/").pop() return segment ? decodeURISafe(segment) : "" } function decodeURISafe(value: string) { try { return decodeURIComponent(value) } catch { return value } }