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.0 KB
Raw Blame
import { z } from 'zod';
import { DELIVERABLE_ERRORS_PER_EVENT, type HookSpoolEntry } from './hook-spool.js';
import { normalizePlatformSource } from './platform-source.js';
import { formatHostForUrl } from './worker-url.js';

export const REMOTE_SPOOL_PROTOCOL_VERSION = 1;
export const REMOTE_SPOOL_TIMEOUT_MS = 1000;
export const REMOTE_SPOOL_REQUEST_TIMEOUT_MS = 10_000;
export const REMOTE_SPOOL_MAX_ENTRIES = 16;

const commonPayload = z.object({
  contentSessionId: z.string().min(1).max(512),
  platformSource: z.string().min(1).max(128),
  cwd: z.string().max(32768).optional(),
}).passthrough();
const observationPayload = commonPayload.extend({
  toolName: z.string().min(1).max(512),
  toolInput: z.unknown().optional(),
  toolResponse: z.unknown().optional(),
  toolUseId: z.string().max(2048).optional(),
  agentId: z.string().max(128).optional(),
  agentType: z.string().max(128).optional(),
});
const timestamp = z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER);
const workStateTelemetryPayload = z.object({
  contentSessionId: z.string().min(1).max(512),
  platformSource: z.string().min(1).max(128),
  eventId: z.string().min(1).max(2048),
  agentId: z.string().max(128).optional(),
  agentRole: z.enum(['main', 'subagent', 'unknown']).optional(),
});
const entrySchema = z.discriminatedUnion('kind', [
  z.object({ kind: z.literal('observation'), payload: observationPayload, enqueuedAtEpochMs: timestamp }),
  z.object({ kind: z.literal('file_edit'), payload: observationPayload, enqueuedAtEpochMs: timestamp }),
  z.object({ kind: z.literal('summarize'), payload: commonPayload.extend({
    lastAssistantMessage: z.string(),
    observedModel: z.string().max(1024).optional(),
    observedBilling: z.string().max(1024).optional(),
  }), enqueuedAtEpochMs: timestamp }),
  z.object({ kind: z.literal('session_end'), payload: commonPayload, enqueuedAtEpochMs: timestamp }),
  z.object({ kind: z.literal('subagent_stop'), payload: commonPayload.extend({
    agentId: z.string().min(1).max(128),
    agentType: z.string().max(128).optional(),
  }), enqueuedAtEpochMs: timestamp }),
  z.object({ kind: z.literal('advisor_calls'), payload: commonPayload.extend({
    transcriptPath: z.string().max(32768).optional(),
    calls: z.array(z.object({
      toolUseId: z.string().min(1).max(2048),
      advice: z.string(),
      advisorModel: z.string().nullable().optional(),
      occurredAtEpoch: timestamp,
      lastUserMessage: z.string().nullable().optional(),
      transcriptByteOffset: z.number().int().nonnegative().nullable().optional(),
    }).passthrough()).min(1).max(128),
  }), enqueuedAtEpochMs: timestamp }),
  z.strictObject({ kind: z.literal('remote_deliverables'), payload: z.strictObject({
    contentSessionId: z.string().min(1).max(512),
    platformSource: z.string().min(1).max(128),
    files: z.array(z.strictObject({
      name: z.string().min(1).max(255).refine(name => name.trim().length > 0).regex(/^[^/\\:\x00-\x1f\x7f<>]+$/u),
      version: z.string().regex(/^[a-f0-9]{64}$/),
      occurredAtEpoch: timestamp.int().positive(),
    })).min(1).max(50),
  }), enqueuedAtEpochMs: timestamp }),
  z.object({ kind: z.literal('deliverables'), payload: commonPayload.extend({
    cwd: z.string().min(1).max(32768),
    project: z.string().min(1).max(512),
    agentId: z.string().max(128).optional(),
    // One Stop copies at most DELIVERABLES_PER_STOP files (src/cli/deliverables-capture.ts); 128 leaves room for that bound to grow.
    files: z.array(z.object({
      sourcePath: z.string().min(1).max(32768),
      bucketPath: z.string().min(1).max(32768),
      title: z.string().max(512),
      kind: z.string().min(1).max(64),
      bytes: z.number().int().nonnegative(),
      sha256: z.string().regex(/^[a-f0-9]{64}$/),
      declared: z.boolean(),
      list: z.string().max(512).nullable().optional(),
      field: z.string().max(512).nullable().optional(),
      toolUseId: z.string().max(2048).nullable().optional(),
      occurredAtEpoch: timestamp,
    }).passthrough()).min(1).max(128),
    errors: z.array(z.object({ sourcePath: z.string().max(32768), error: z.string().max(2048) }).passthrough()).max(DELIVERABLE_ERRORS_PER_EVENT).optional(),
  }), enqueuedAtEpochMs: timestamp }),
  z.object({ kind: z.literal('work_state_telemetry'), payload: z.discriminatedUnion('kind', [
    workStateTelemetryPayload.extend({
      kind: z.literal('instruction'),
      state: z.enum(['returned', 'disabled', 'excluded', 'missing', 'unknown']),
    }).strict(),
    workStateTelemetryPayload.extend({
      kind: z.literal('mcp'),
      tool: z.enum(['read', 'write']),
      outcome: z.enum(['ok', 'error', 'excluded', 'disabled', 'unknown']),
    }).strict(),
  ]), enqueuedAtEpochMs: timestamp }),
]);

export const remoteSpoolEnvelopeSchema = z.object({
  protocolVersion: z.literal(REMOTE_SPOOL_PROTOCOL_VERSION),
  entry: entrySchema,
}).strict();

export function normalizeRemoteSpoolEntry(entry: HookSpoolEntry): HookSpoolEntry {
  return { ...entry, payload: { ...entry.payload,
    platformSource: normalizePlatformSource(entry.payload.platformSource) } } as HookSpoolEntry;
}

export function remoteHookSpoolToken(value: unknown): string {
  if (typeof value !== 'string') return '';
  const token = value.trim();
  return token.length <= 1024 && /^[\x20-\x7e]+$/.test(token) ? token : '';
}

export function usesRemoteHookSpool(host: string | undefined, transport: string = 'auto', workerUrl = ''): boolean {
  transport = transport.trim().toLowerCase();
  if (transport === 'http') return true;
  if (transport === 'filesystem') return false;
  if (workerUrl.trim()) return true;
  if (!host) return false;
  let normalized = host.toLowerCase().replace(/^\[|\]$/g, '');
  try { normalized = new URL(`http://${formatHostForUrl(host)}`).hostname.replace(/^\[|\]$/g, ''); } catch {}
  return !(normalized === 'localhost' || normalized.endsWith('.localhost')
    || normalized === '0.0.0.0' || normalized === '::' || normalized === '::1'
    || /^127\.\d+\.\d+\.\d+$/.test(normalized)
    || /^::ffff:127\.\d+\.\d+\.\d+$/.test(normalized)
    || /^::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(normalized));
}