Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

2.5 KB
Raw Blame
import { copyFile, link, lstat, mkdir, readFile, readdir, symlink } from 'node:fs/promises';
import { join } from 'node:path';

export async function optionalText(path: string): Promise<string | null> {
  try {
    return await readFile(path, 'utf8');
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
    throw error;
  }
}

/** Reference host-owned configuration assets while keeping session state in its own home. */
export async function linkHomeAsset(source: string, destination: string): Promise<void> {
  try {
    await lstat(destination);
    return;
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
  }
  try {
    await lstat(source);
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
    throw error;
  }
  const directory = (await lstat(source)).isDirectory();
  try {
    await symlink(source, destination, directory ? 'junction' : 'file');
  } catch (error) {
    if (
      process.platform !== 'win32' ||
      directory ||
      (error as NodeJS.ErrnoException).code !== 'EPERM'
    )
      throw error;
    await linkFileWithoutSymlink(source, destination);
  }
}

/**
 * Windows lets an account make a file symlink only with Developer Mode on or
 * as an administrator. A hard link stands in for it on the same volume; on
 * another, the file is copied, and the copy does not follow later edits.
 */
async function linkFileWithoutSymlink(source: string, destination: string): Promise<void> {
  try {
    await link(source, destination);
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error;
    await copyFile(source, destination);
    console.warn(
      `Copied ${source} to ${destination}: Windows refused a symlink, and a hard link cannot cross volumes. Edits to ${source} reach the agent only after ${destination} is deleted.`
    );
  }
}

/**
 * Link the host's skills one by one, leaving out `switch`: the session is given
 * Console's copy of that skill, and a stale one beside it would contradict it.
 */
export async function linkSkills(source: string, destination: string): Promise<void> {
  let entries: string[];
  try {
    entries = await readdir(source);
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
    throw error;
  }
  await mkdir(destination, { recursive: true });
  for (const entry of entries) {
    if (entry === 'switch') continue;
    await linkHomeAsset(join(source, entry), join(destination, entry));
  }
}