Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

12.0 KB
Raw Blame
import { isPersistentSandboxMode, type SandboxMode } from '@lobechat/builtin-tool-cloud-sandbox';

import type { UnansweredUserTurn } from './unansweredUserTurns';
import { formatUnansweredUserTurns } from './unansweredUserTurns';

export interface ConversationHistoryEntry {
  content: string;
  role: 'assistant' | 'user';
}

/**
 * Builds the system context injected before every user prompt for cloud Claude Code runs.
 *
 * This context is cloud-sandbox-specific: it describes the workspace layout,
 * lists the GitHub repos that were pre-cloned, and tells CC how to handle
 * repos that may not have been cloned successfully.
 *
 * It is NOT the agent's systemRole (which lives in agentConfig.systemRole and
 * is a user-facing persona definition). This is pure infra context for CC.
 *
 * Returned string is passed as the first text block in the --input-json array
 * via sandboxRunner β†’ spawnHeteroSandbox. If nothing meaningful to inject,
 * returns undefined so no extra block is added.
 */
/**
 * Where the run keeps its files. Absent or `ephemeral` renders the original
 * wording byte for byte; `drive` describes the folder on the user's drive and
 * `persistent` the environment directory the execution plane starts the run in
 * β€” by its place on the drive, never by an absolute path, which is the
 * plane's to choose.
 */
export interface CloudHeteroSandboxPlacement {
  /** Chosen subdirectory of the workspace, relative to its root. */
  cwd?: string;
  mode?: SandboxMode;
}

export function buildCloudHeteroContext(params: {
  repos: string[];
  /** Static systemContext from HeterogeneousProviderConfig.systemContext (agent-level). */
  agentSystemContext?: string;
  /**
   * Recent conversation turns to inject when resuming a session whose context
   * was cleared (sandbox recycled or context overflow).  Helps CC understand
   * what happened in prior turns even without a native session file.
   */
  conversationHistory?: ConversationHistoryEntry[];
  /** GitHub OAuth token injected as GITHUB_TOKEN env var in the sandbox. */
  githubToken?: string;
  sandbox?: CloudHeteroSandboxPlacement;
  /** User messages a resumed session may have missed (see `collectUnansweredUserTurns`). */
  unansweredUserTurns?: UnansweredUserTurn[];
}): string {
  const {
    repos,
    agentSystemContext,
    conversationHistory,
    githubToken,
    sandbox,
    unansweredUserTurns,
  } = params;
  const persistent = isPersistentSandboxMode(sandbox?.mode);

  const parts: string[] = [];

  // --- Agent-level static context (highest priority, goes first) ---
  if (agentSystemContext?.trim()) {
    parts.push(agentSystemContext.trim());
  }

  // --- Cloud workspace context ---
  // A persistent run is told what survives and what its neighbours are; the
  // push discipline stays, because a workspace on network storage is still not
  // where the source of truth for code lives.
  const placementLines: string[] = persistent
    ? [
        '## Cloud Workspace',
        sandbox?.mode === 'drive'
          ? sandbox.cwd
            ? `You are running inside a LobeHub cloud sandbox. Your working directory is \`${sandbox.cwd}\`, a folder on the user's **network drive**: files written there survive session expiry and are still there in your next session. The machine itself starts fresh every session, so installed packages do not carry over.`
            : "You are running inside a LobeHub cloud sandbox. Your working directory is the root of the user's **network drive**: files written there survive session expiry and are still there in your next session. The machine itself starts fresh every session, so installed packages do not carry over."
          : `You are running inside a LobeHub cloud sandbox. Your working directory is ${sandbox?.cwd ? `\`${sandbox.cwd}\`, ` : ''}an **environment directory** on the user's drive: its files and the packages its setup installed survive session expiry and are restored in your next session.`,
        'Other folders on the drive belong to other work β€” reachable with relative paths, but do not write into them unless the user asks.',
        'The workspace is network storage: fine for source files, results and notes, but slow for the thousands of small files a package install or a build writes.',
        // The persistent sandbox is for everyday work whose results should
        // stay; coding is what the temporary Cloud Sandbox is for.
        "This persistent sandbox is meant for everyday tasks, not coding: a repository's dependencies, virtual environments, caches and build output would take up a lot of the user's drive space. Keep those outside the working directory, and when the task is mainly programming on a codebase, suggest the user switch this conversation to the Cloud Sandbox, which is discarded after use.",
        '',
        '## Sandbox Persistence',
        'Files in your working directory persist across sessions; anything written outside it may not.',
        'The remote GitHub repository is still the source of truth for code:',
        '',
        '1. **Always commit and push** β€” after making changes, run `git add`, `git commit`, and `git push`.',
        '   Never leave code changes uncommitted at the end of a task.',
        '2. **Confirm push success** β€” verify with `git log --oneline origin/<branch>`',
        '   before reporting a task as complete.',
        '',
      ]
    : [
        '## Cloud Workspace',
        'You are running inside a LobeHub cloud sandbox. Your working directory is `/workspace`.',
        '',
        '## Sandbox Persistence β€” CRITICAL',
        'This sandbox is **ephemeral**: it will be destroyed after ~1 hour of inactivity.',
        '**Any file changes that are not pushed to a remote will be permanently lost.**',
        '',
        'Rules you MUST follow for every code change:',
        '',
        '1. **Always commit and push** β€” after making changes, run `git add`, `git commit`, and `git push`.',
        '   Never leave code changes uncommitted at the end of a task.',
        '2. **Confirm push success** β€” verify with `git log --oneline origin/<branch>`',
        '   before reporting a task as complete.',
        '3. **Never rely on local-only state** β€” treat every file in `/workspace` as temporary.',
        '   The source of truth is the remote GitHub repository.',
        '',
      ];
  const workspaceLines: string[] = [
    ...placementLines,
    '## Pushing to GitHub β€” Public vs Private Repos',
    '',
    'Before pushing, check whether the repo is public or private:',
    '```bash',
    'gh repo view <owner>/<repo> --json isPrivate --jq .isPrivate',
    '```',
    '',
    '**Private repo** β€” push directly to the origin remote:',
    '```bash',
    'git push origin <branch>',
    '```',
    '',
    '**Public repo** β€” you likely do not have write access. Fork first, then push:',
    '```bash',
    '# 1. Fork the repo to your account (idempotent β€” safe to run even if fork exists)',
    'gh repo fork <owner>/<repo> --clone=false',
    '# 2. Add the fork as a remote (idempotent β€” safe to re-run if remote already exists)',
    'GITHUB_USER=$(gh api user --jq .login)',
    'git remote set-url fork https://github.com/$GITHUB_USER/<repo>.git 2>/dev/null || git remote add fork https://github.com/$GITHUB_USER/<repo>.git',
    '# 3. Push to the fork',
    'git push fork <branch>',
    '# 4. Open a PR from the fork to the upstream repo',
    'gh pr create --repo <owner>/<repo> --head $GITHUB_USER:<branch> --title "..." --body "..."',
    '```',
    '',
    'If you are unsure whether you have push access, attempt `git push origin <branch>` first.',
    'If it fails with a 403 / permission denied error, fall back to the fork workflow above.',
    '',
    'If the user asks you to make code changes, the task is NOT complete until those changes',
    'are visible on GitHub (pushed to a branch or merged via PR).',
  ];

  if (githubToken) {
    workspaceLines.push(
      '',
      '## GitHub Authentication',
      'GitHub credentials are pre-injected into this sandbox:',
      '',
      '- `GITHUB_TOKEN` env var is set β€” git and `gh` CLI pick it up automatically',
      '- `gh` CLI is pre-authenticated β€” all `gh` commands work out of the box',
      '- `~/.creds/env` contains `GITHUB_ACCESS_TOKEN` (same format as `injectCredsToSandbox`)',
      '  β€” source it in sub-shells or scripts that need an explicit token:',
      '  ```bash',
      '  source ~/.creds/env',
      '  echo $GITHUB_ACCESS_TOKEN | gh auth login --hostname github.com --with-token',
      '  ```',
      '',
      'You can use `git push`, `git pull`, `gh pr create`, `gh issue list`, GitHub API calls, etc. directly.',
      '`gh` is the preferred tool for GitHub operations (PRs, issues, releases); use `git push` for pushing commits.',
      '',
      'If `git push` fails with an authentication error, recover with one of these approaches (in order of preference):',
      '1. `gh auth setup-git` β€” reconfigures git to use gh as credential helper, then retry `git push`',
      '2. `git push https://oauth2:[email protected]/<owner>/<repo>.git <branch>` β€” inline token fallback',
      '',
      'Use `gh pr view` or `gh pr list` to confirm that a PR was successfully created after pushing.',
    );
  }

  // Repos are cloned into the working directory, wherever that is: an absolute
  // path is only known for the ephemeral box.
  const repoRoot = persistent ? '.' : '/workspace';
  const repoRootLabel = persistent ? 'your working directory' : '`/workspace`';
  if (repos.length > 0) {
    workspaceLines.push(
      '',
      '## GitHub Repositories',
      `The following repositories were pre-cloned into ${repoRootLabel} before this conversation started:`,
      ...repos.map((repo) => {
        const dir = repoToLocalDir(repo);
        const url = toGithubUrl(repo);
        return `- \`${repoRoot}/${dir}\`  (${url})`;
      }),
      '',
      'You can start working in any of these directories immediately.',
      githubToken
        ? 'If a directory is missing (clone may have failed), you can recover it yourself using the available GITHUB_TOKEN.'
        : `If a directory is missing (clone may have failed), you can run \`git clone <url> ${repoRoot}/<dir>\` yourself to recover it.`,
    );
  } else {
    workspaceLines.push(
      '',
      'No GitHub repositories have been pre-cloned for this conversation.',
      githubToken
        ? 'If you need a repository, you can clone it yourself using the available GITHUB_TOKEN.'
        : `If you need a repository, ask the user to add it in the repo selector, or clone it yourself with \`git clone <url> ${repoRoot}/<dir>\`.`,
    );
  }

  parts.push(workspaceLines.join('\n'));

  // --- Previous conversation context (injected when session was reset) ---
  // Truncate per-message to avoid ballooning the system context:
  //   user turns    β†’ 1 KB (prompts are usually short)
  //   assistant turns β†’ 2 KB (responses may be longer but we want the gist)
  if (conversationHistory && conversationHistory.length > 0) {
    const USER_MAX = 1024;
    const ASST_MAX = 2048;
    const entries = conversationHistory.map((entry) => {
      const limit = entry.role === 'user' ? USER_MAX : ASST_MAX;
      const body =
        entry.content.length > limit
          ? `${entry.content.slice(0, limit)}… [truncated]`
          : entry.content;
      return `<${entry.role}>\n${body}\n</${entry.role}>`;
    });
    parts.push(`<previous_conversation>\n${entries.join('\n')}\n</previous_conversation>`);
  }

  const unanswered = formatUnansweredUserTurns(unansweredUserTurns);
  if (unanswered) parts.push(unanswered);

  return parts.join('\n\n');
}

// ---------------------------------------------------------------------------
// Helpers (mirrors sandboxRunner logic β€” kept local to avoid coupling)
// ---------------------------------------------------------------------------

function repoToLocalDir(repo: string): string {
  return (repo.split('/').findLast(Boolean) ?? repo).replace(/\.git$/, '');
}

function toGithubUrl(repo: string): string {
  if (repo.startsWith('http')) return repo.replace(/\.git$/, '');
  return `https://github.com/${repo}`;
}