Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

6.2 KB
Raw Blame
import { CODEX_IMPORTED_TURN_PREFIX, CODEX_INJECTED_PREFIXES } from './codex-rollout.js';
import type { TranscriptFileActivity, TranscriptFileWrite } from './deliverables-transcript.js';
import { stripMemoryTags } from '../utils/tag-stripping.js';

/** Only links in the final answer count as offered output. The collector separately verifies file type, workspace and disk. */
function finalAnswerPaths(text: string): string[] {
  const paths: string[] = [];
  const visible = stripMemoryTags(text).replace(/(^|\n)(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:\n\2(?:\n|$)|$)/g, '\n');
  for (const match of visible.matchAll(/\[[^\]\n]+\]\(\s*(?:<([^>\n]+)>|([^\s)]+))\s*\)/g)) {
    const candidate = match[1] ?? match[2];
    const value = candidate.replace(/^sandbox:/, '');
    if (!/^(?:\/(?!\/)|[A-Za-z]:[\\/])/.test(value) || /[?#\u0000]/.test(value)) continue;
    try {
      const path = decodeURIComponent(value);
      if (!/[\r\n\u0000]/.test(path)) paths.push(path);
    } catch { /* A malformed destination cannot identify a local file. */ }
  }
  return paths;
}

/** Codex's apply_patch result names the files it actually changed. A transcript may wrap it in the tool's JSON envelope. */
function patchOutputPaths(output: unknown): string[] {
  if (typeof output !== 'string') return [];
  let text = output;
  if (text.trimStart().startsWith('{')) {
    try {
      const result = JSON.parse(text);
      if (result?.metadata?.exit_code !== 0 || typeof result.output !== 'string') return [];
      text = result.output;
    } catch { return []; }
  }
  const [status, ...changes] = text.trimEnd().split(/\r?\n/);
  if (status !== 'Success. Updated the following files:') return [];
  return changes.flatMap(line => {
    const changed = /^[AM] (.+)$/.exec(line);
    return changed ? [changed[1]] : [];
  });
}

/** Read the native rollout's user messages, paired patch results and final answer. Reasoning and shell commands provide no file evidence. */
export function extractCodexFileActivity(
  lines: string[], currentTurnOnly: boolean, privatePrompt: (value: string) => boolean, expectedTurnId?: string,
  hookAnswer?: { text: string; at: number },
): TranscriptFileActivity {
  const writes = new Map<string, TranscriptFileWrite>();
  const previous = new Map<string, TranscriptFileWrite>();
  const patchCalls = new Set<string>();
  let promptSeen = false;
  let privateTurn = false;
  let imported = false;
  let turnId: string | undefined;
  let forkThread: string | undefined;

  const nextTurn = () => {
    if (!currentTurnOnly && promptSeen && !privateTurn && !imported) {
      for (const [path, write] of writes) previous.set(path, write);
    }
    writes.clear();
    patchCalls.clear();
    promptSeen = false;
    privateTurn = false;
  };
  const add = (paths: string[], name: string, callId: string | null, at: number) => {
    if (!promptSeen || privateTurn || imported) return;
    for (const path of paths) writes.set(path, { path, toolName: name, toolUseId: callId, occurredAtEpoch: at });
  };

  for (const line of lines) {
    let record;
    try { record = JSON.parse(line); } catch { continue; }
    const item = record?.payload;
    if (!item || typeof item !== 'object') continue;
    if (record.type === 'session_meta' && item.forked_from_id && typeof item.id === 'string') forkThread = item.id;
    if (forkThread) {
      if (record.type === 'event_msg' && item.type === 'thread_settings_applied' && item.thread_id === forkThread) forkThread = undefined;
      continue;
    }
    if ((record.type === 'event_msg' && item.type === 'task_started') || record.type === 'turn_context') {
      if (typeof item.turn_id === 'string' && item.turn_id !== turnId) {
        nextTurn();
        turnId = item.turn_id;
        imported = item.turn_id.startsWith(CODEX_IMPORTED_TURN_PREFIX);
      }
      continue;
    }
    if (typeof item.turn_id === 'string' && item.turn_id.startsWith(CODEX_IMPORTED_TURN_PREFIX)) {
      imported = true;
      nextTurn();
    }
    if (imported || (expectedTurnId !== undefined && turnId !== expectedTurnId)) continue;
    const epoch = typeof record.timestamp === 'string' ? Date.parse(record.timestamp) : NaN;
    const at = Number.isFinite(epoch) ? epoch : 0;
    if (record.type === 'event_msg' && item.type === 'task_complete' && typeof item.last_agent_message === 'string') {
      add(finalAnswerPaths(item.last_agent_message), 'final_answer', null, at);
      continue;
    }
    if (record.type !== 'response_item') continue;
    if (item.type === 'message' && Array.isArray(item.content)) {
      if (item.role === 'user') {
        const inputs = item.content.flatMap((part: { type?: string; text?: string } | null) =>
          part?.type === 'input_text' && typeof part.text === 'string' && !CODEX_INJECTED_PREFIXES.some(prefix => part.text!.trimStart().startsWith(prefix))
            ? [part.text] : []);
        const text = inputs.join('\n').trim();
        if (text || item.content.some((part: { type?: string } | null) => part?.type === 'input_image')) {
          nextTurn();
          promptSeen = true;
          privateTurn = privatePrompt(text);
        }
      } else if (item.role === 'assistant' && item.phase === 'final_answer') {
        for (const part of item.content) if (part?.type === 'output_text' && typeof part.text === 'string') {
          add(finalAnswerPaths(part.text), 'final_answer', null, at);
        }
      }
      continue;
    }
    if (typeof item.call_id !== 'string') continue;
    if (item.type === 'custom_tool_call' || item.type === 'function_call') {
      patchCalls.delete(item.call_id);
      if (item.name === 'apply_patch' || item.name === 'functions.apply_patch') patchCalls.add(item.call_id);
    } else if ((item.type === 'custom_tool_call_output' || item.type === 'function_call_output') && patchCalls.delete(item.call_id)) {
      add(patchOutputPaths(item.output), 'apply_patch', item.call_id, at);
    }
  }
  if (expectedTurnId && turnId === expectedTurnId && hookAnswer) {
    // Prefer the native event timestamp when both the persisted answer and the Stop named the same file.
    add(finalAnswerPaths(hookAnswer.text).filter(path => !writes.has(path)), 'final_answer', null, hookAnswer.at);
  }
  for (const [path, write] of writes) previous.set(path, write);
  return { writes: [...previous.values()], workStateWrites: [], promptSeen, privateTurn };
}