Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

15.4 KB
Raw Blame
// Context Link — lets two agent nodes on the canvas read each other's context on demand.
//
// Connecting two agent nodes means "these two may READ each other." No messages flow. The
// renderer pushes the current link map to main (context-link:set-links); main builds one link
// document per node (linked nodes' titles, transcript paths learned from hooks, cwds, tmux
// session names) and answers reads over the hook server's /context-link/ route. A POSIX-sh shim
// (context.sh) is the client; a globally-installed Claude skill (plus instruction blocks for the
// agents that have no skill system) tells the agent how + when to call it. The local shim is built
// with the shared-Codex thread resolver before its node-id gate; the SSH installer keeps the
// machine-neutral body because this machine's ownership-record path is meaningless on the host.
//
// The reading and parsing happen HERE, on the desktop, not in the CLI. That is what lets an SSH
// project's remote agent use the feature at all: its transcripts live on the host, reachable over
// the project's ControlMaster (injected as `deps`), and its terminal is captured by a PtyManager
// that already knows the difference. The link documents are also still written to
// <userData>/context-links/ as a debugging aid.
import fs from 'fs'
import path from 'path'
import { platform } from './platform'
import { syncWindowsShLauncher, writeManagedHookFileAtomic } from './agents/hooks/install-helper'
import { IPC } from '../shared/ipc'
import type { ContextLinkInfo, ContextLinkMap } from '../shared/types'
import { type PtyManager } from './pty-manager'
import { findInLoginPath } from './exec-path'
import { isSafeOpencodeSessionId, remoteOpencodeExportCommand, runOpencodeExportAt } from './opencode-export'
import { TMUX_SOCKET } from './tmux-naming'
import {
  buildContextShimScript,
  buildLinkDoc,
  resolveLinkTranscript,
  transcriptPathOf,
  type LinkDoc,
  type LinkDocEntry
} from './context-link-core'
import { codexThreadIdentityRoot } from './codex-identity-proxy'
import {
  CONTEXT_LINK_VERBS,
  renderContextLink,
  type ContextLinkFetch,
  type ContextLinkVerb
} from './context-link-render'
import { hookServer } from './agents/hook-server'
import {
  locateAntigravity,
  locateClaude,
  locateCodex,
  locateGemini,
  locateGrok
} from './handoff/locate'
import { cursorTranscriptText, locateCursorChat } from './cursor-chat'

export { setNodeTranscript } from './context-link-core'

let dir = ''
export function contextLinkDir(): string {
  if (!dir) dir = path.join(platform().userDataDir, 'context-links')
  return dir
}
function cliShimPath(): string {
  return path.join(contextLinkDir(), 'context.sh')
}
/** The context-link shim the get-linked-context skill points at (written by `initContextLink`).
 *  The skill itself is installed by the consent lifecycle (`core/agent-integrations.ts`). */
export function contextLinkShimPath(): string {
  return cliShimPath()
}

function writeCliFiles(): void {
  const d = contextLinkDir()
  fs.mkdirSync(d, { recursive: true })
  // Temp + rename, never a truncating write: agents execute this file (see canvas-control.ts).
  writeManagedHookFileAtomic(cliShimPath(), buildContextShimScript(codexThreadIdentityRoot()), undefined, 0o755)
  // Windows: `context.cmd` beside it for PowerShell-run agents (see canvas-control.ts).
  syncWindowsShLauncher(d, 'context.sh')
  // Sweep the retired Electron-as-Node CLI off upgraders' disks: the shim no longer execs it,
  // and it would sit there pointing at a binary path that moves with every app update.
  try {
    fs.rmSync(path.join(d, 'context-cli.mjs'), { force: true })
  } catch {
    /* fail open */
  }
}

let pty: PtyManager | undefined
let deps: ContextLinkDeps = {}

/**
 * The shell-specific reach the reads need. Everything here is about ONE question — is this node
 * on a remote host, and if so how do I reach it — which `src/core` must not answer for itself
 * (SshProjectManager and the ControlMaster wiring are desktop-only). The Server Edition passes
 * nothing and gets the local-only behavior it had before.
 */
export interface ContextLinkDeps {
  /** True when the node is a live session on an SSH project's remote host. */
  isRemoteNode?: (nodeId: string) => boolean
  /** Read (at most `maxBytes` of) a file on a remote node's host. null = unreadable. */
  readRemoteFile?: (nodeId: string, filePath: string, maxBytes: number) => Promise<string | null>
  /** Run one command on a remote node's host and return stdout. null = it failed. */
  runRemoteCommand?: (nodeId: string, command: string) => Promise<string | null>
}

// Remote transcripts are read from the END: a long-running session's file reaches tens of MB,
// and the whole thing would cross an ssh channel for a `summary` that shows 15 lines. A tail can
// start mid-line, which only costs that one line (it fails to parse and is dropped).
const REMOTE_TRANSCRIPT_MAX_BYTES = 2 * 1024 * 1024

// cursor's locator takes (id, cwd?), NOT the shared (id, accountId?), wrapped so an account id can
// never be read as a cwd. It locates strictly by the whole-UUID chat id.
const LINK_LOCATORS = {
  claude: locateClaude,
  codex: locateCodex,
  gemini: locateGemini,
  grok: locateGrok,
  antigravity: locateAntigravity,
  cursor: (sessionId: string) => locateCursorChat(sessionId)
}

/** Agents whose "transcript path" is not a text file: the path names a store the agent's own reader
 *  turns into transcript text. Everything else is read as utf-8. */
const TRANSCRIPT_TEXT_READERS: Record<string, (p: string) => Promise<string | null>> = {
  cursor: cursorTranscriptText
}

// The link documents, by node id — the same objects written to disk, kept in memory because they
// are what authorizes a read (a node may only ever name a link inside ITS OWN document).
let linkDocs = new Map<string, LinkDoc>()
let linkRevision = 0
// Only paths resolved for this exact identity may survive an intermediate publication.
// Include the hook path so a replaced/invalidated hook cannot reuse an older resolution.
let verifiedPaths = new Map<string, string>()
function transcriptIdentity(n: ContextLinkInfo): string {
  return JSON.stringify([n.id, n.agentId, n.sessionId, n.accountId, n.cwd,
    !!deps.isRemoteNode?.(n.id), transcriptPathOf(n.id)])
}

// Write one enriched link file per node id present in the map. Removed links should not
// linger, so we clear stale per-node files first. Async fs throughout — this runs on edge
// changes and scales with node/link count, and sync I/O here sits on the main event loop.
async function writeLinkFiles(map: ContextLinkMap, revision: number): Promise<void> {
  if (revision !== linkRevision) return
  const d = contextLinkDir()
  const bin = pty?.getTmuxBin() ?? null
  // Resolve each linked node's transcript once (hook-fed for claude, locator-by-sessionId
  // for codex/gemini), so buildLinkDoc stays pure and sync.
  const resolved = new Map<string, string>()
  const verified = new Map<string, string>()
  for (const links of Object.values(map)) {
    for (const n of links) {
      if (n.note != null || resolved.has(n.id)) continue
      const identity = transcriptIdentity(n)
      resolved.set(
        n.id,
        await resolveLinkTranscript(n, {
          hooked: transcriptPathOf,
          locators: LINK_LOCATORS,
          isRemote: deps.isRemoteNode
        })
      )
      if (identity === transcriptIdentity(n)) verified.set(identity, resolved.get(n.id)!)
      else resolved.set(n.id, '')
    }
  }
  if (revision !== linkRevision) return
  const docs = new Map<string, LinkDoc>()
  for (const [nodeId, links] of Object.entries(map)) {
    const doc = buildLinkDoc(nodeId, links, {
      transcriptOf: (id) => resolved.get(id) ?? '',
      tmuxBin: bin,
      tmuxSocket: TMUX_SOCKET
    })
    docs.set(nodeId, doc)
  }
  // Publish all enriched documents together; never expose a partially rebuilt map.
  verifiedPaths = verified
  linkDocs = docs
  try {
    for (const f of await fs.promises.readdir(d)) {
      if (f.endsWith('.json')) await fs.promises.rm(path.join(d, f), { force: true })
    }
  } catch {
    /* dir may not exist yet */
  }
  for (const [nodeId, doc] of docs) {
    try {
      await fs.promises.writeFile(path.join(d, `${nodeId}.json`), JSON.stringify(doc, null, 2))
    } catch (e) {
      console.warn('[context-link] write link file failed', e)
    }
  }
}

/** Read a linked node's transcript bytes — from the remote host when it lives there, else from
 *  this machine's disk. null when there is no path yet or it could not be read. */
async function fetchTranscript(node: LinkDocEntry): Promise<string | null> {
  if (!node.transcriptPath) return null
  if (deps.isRemoteNode?.(node.id)) {
    // The path was jailed at ingest (isSafeRemoteTranscriptPath, where the hook payload arrives),
    // so what reaches here is already confined to the host's transcript roots.
    return deps.readRemoteFile
      ? await deps.readRemoteFile(node.id, node.transcriptPath, REMOTE_TRANSCRIPT_MAX_BYTES)
      : null
  }
  const read = node.agent ? TRANSCRIPT_TEXT_READERS[node.agent] : undefined
  if (read) return read(node.transcriptPath)
  try {
    return await fs.promises.readFile(node.transcriptPath, 'utf-8')
  } catch {
    return null
  }
}

// The id check and the export bounds live in `opencode-export.ts`, shared with the ⌘M chat view's
// reader. Re-exported so this module's callers are unchanged.
export { isSafeOpencodeSessionId } from './opencode-export'

// With no timeout a wedged CLI holds the linked agent's read open for good.
const OPENCODE_EXPORT_TIMEOUT_MS = 60_000

export async function opencodeExportAt(bin: string, sessionId: string): Promise<string | null> {
  const out = await runOpencodeExportAt(bin, sessionId, OPENCODE_EXPORT_TIMEOUT_MS)
  return out.ok ? out.stdout : null
}

async function fetchOpencodeExport(node: LinkDocEntry): Promise<string | null> {
  if (!node.sessionId || !isSafeOpencodeSessionId(node.sessionId)) return null
  if (deps.isRemoteNode?.(node.id)) {
    return deps.runRemoteCommand
      ? await deps.runRemoteCommand(node.id, remoteOpencodeExportCommand(shellQuote(node.sessionId)))
      : null
  }
  const bin = await findInLoginPath('opencode')
  return bin ? opencodeExportAt(bin, node.sessionId) : null
}

/** Single-quote for a POSIX shell. The session id reaches a remote command line, and it is
 *  ultimately provider-supplied data — never interpolate it raw. */
function shellQuote(s: string): string {
  return `'${s.replace(/'/g, `'\\''`)}'`
}

const fetchers: ContextLinkFetch = {
  transcript: fetchTranscript,
  // captureSession already knows a remote node's tmux lives on the host, so this one call
  // covers both surfaces.
  terminal: async (node) => (pty ? await pty.captureSession(node.id) : ''),
  opencodeExport: fetchOpencodeExport
}

/**
 * Answer one /context-link/ request. AUTHORIZATION: the document is chosen by the REQUESTER's
 * node id and `pickLinkNode` (inside renderContextLink) will only ever return a node listed in
 * it — so a caller that holds the hook token still cannot read a node it was never linked to.
 * The token remains the outer boundary, exactly as it is for status hooks.
 */
export async function handleContextLinkRequest(req: {
  verb: string
  nodeId: string
  args: Record<string, string>
}): Promise<string> {
  if (!req.nodeId) return 'Not a nodeterm session — nothing to read.'
  if (!CONTEXT_LINK_VERBS.includes(req.verb as ContextLinkVerb)) {
    return 'Unknown command. Use: list | summary [--node X] [-n N] | transcript [--node X] | terminal [--node X]'
  }
  const doc = linkDocs.get(req.nodeId)
  if (!doc) {
    return 'No linked nodes. Draw a context-link edge from this node to another on the canvas.'
  }
  try {
    return await renderContextLink(doc, req.verb as ContextLinkVerb, req.args, fetchers)
  } catch (e) {
    console.warn('[context-link] read failed', e)
    return 'Could not read linked context.'
  }
}

// Serialize writes: writeLinkFiles is a multi-step async clear-then-write; two overlapping
// calls could interleave (B's clear runs before A's writes land) and leave a just-removed
// link file behind — which is a read-authorization leak, not just a perf nit.
let writeChain: Promise<void> = Promise.resolve()

/**
 * Replace the WHOLE link map (every project) and rewrite the per-node link files.
 *
 * The desktop reaches this over IPC, from the renderer that owns the canvas. The Server Edition
 * has no such renderer — it derives the map from persisted project files and calls this directly
 * (src/server/context-link.ts), which is why the map setter is a function and not only a handler.
 */
export function setContextLinks(map: ContextLinkMap): Promise<void> {
  const snapshot = structuredClone(map && typeof map === 'object' ? map : {})
  const revision = ++linkRevision
  // Authorization changes immediately, before transcript discovery or debug-file I/O. A slow
  // locator must neither hide a new edge from list nor retain a removed read permission.
  const retained = new Map<string, string>()
  const paths = new Map<string, string>()
  for (const links of Object.values(snapshot)) {
    for (const n of links) {
      if (n.note != null) continue
      // Dependency lookup can fail; leave discovery to report the failure asynchronously.
      try {
        const identity = transcriptIdentity(n)
        const prior = verifiedPaths.get(identity)
        if (prior) { retained.set(identity, prior); paths.set(n.id, prior) }
      } catch { /* no verified path */ }
    }
  }
  verifiedPaths = retained
  linkDocs = new Map(Object.entries(snapshot).map(([nodeId, links]) => [nodeId, buildLinkDoc(
    nodeId, links, { transcriptOf: (id) => paths.get(id) ?? '', tmuxBin: pty?.getTmuxBin() ?? null, tmuxSocket: TMUX_SOCKET }
  )]))
  const write = () => writeLinkFiles(snapshot, revision)
  writeChain = writeChain.then(write, write)
  return writeChain
}

/**
 * Boot Context Link: register the hook-server read handler and (re)write the shim under `dataDir`.
 *
 * Nothing here writes outside our own data dir. The discovery surface (the `get-linked-context`
 * skill in each consented agent's skills dir) is installed by the consent lifecycle
 * (`core/agent-integrations.ts`, issue #744) — the one place that decides what nodeterm may write
 * into user-owned agent configuration. `platformDeps` carries the shell's remote reach.
 */
export function initContextLink(ptyManager: PtyManager, platformDeps: ContextLinkDeps): void {
  pty = ptyManager
  deps = platformDeps
  // Re-derive from the platform this init runs under: a process that boots a second core (the
  // server e2e suites start several, each on its own dataDir) must not keep writing into the
  // FIRST one's directory — which is how a test's removed dataDir came back, `context.sh` and all.
  dir = ''
  linkRevision++
  linkDocs.clear()
  verifiedPaths.clear()
  hookServer.setContextLinkHandler(handleContextLinkRequest)
  try {
    const d = contextLinkDir()
    fs.mkdirSync(d, { recursive: true })
    for (const f of fs.readdirSync(d)) {
      if (f.endsWith('.json')) fs.rmSync(path.join(d, f), { force: true })
    }
    writeCliFiles()
  } catch (e) {
    console.error('[context-link] setup failed', e)
    return
  }
  platform().handle(IPC.contextLinkSetLinks, (map: ContextLinkMap) => setContextLinks(map))
  // `platform` is THIS core's: the renderer words the connect-time note for the machine whose shim
  // it names (a Windows core's non-claude agents run the `.cmd` launcher), never the viewer's.
  platform().handle(IPC.contextLinkInfo, () => ({ shimPath: cliShimPath(), platform: process.platform }))
}