import { spawn } from "node:child_process";
import { ChangelogEntry, EncryptedEnvelopeV1, FieldEnvelope, FieldFormat, FieldSensitivity, GeneratedDataKey, IntegrationConfigResult, IntegrationInstall, RegistryEntry, ScopeInfo, SecretAggregate, SecretCategory, SecretMetadata, SecretScope } from "@alfe/types";

//#region ../agent-api-client/dist/index.d.ts

//# sourceMappingURL=tool-error-capture.d.ts.map
//#endregion
//#region src/transport.d.ts
/**
 * Shared HTTP transport for the Agent API client — request core, retry
 * policy, error formatting, and the `ApiBase` class the domain method
 * groups under `./domains/` build on.
 */
interface AgentApiClientConfig {
  apiKey: string;
  apiUrl: string;
}
/**
 * Encode each path segment but keep the `/` separators — `encodeURIComponent`
 * would escape the slashes too, breaking greedy proxy routes.
 */

declare class AgentApiTransport {
  private readonly apiKey;
  private readonly apiUrl;
  constructor(config: AgentApiClientConfig);
  /**
   * Binary sibling of `request<T>()`. `request()` forces
   * `Content-Type: application/json` and parses a `{ data: T }` envelope,
   * neither of which fits a raw-audio flow (voice TTS/STT), so those go
   * through this instead. Auth (Bearer), the request budget, and the single
   * retry policy on transient 5xx / network errors is kept in sync with
   * `request()`. Safe read methods retry once by default; mutation methods do
   * not, because a response can be lost after a handler or provider call has
   * already succeeded.
   */
  rawRequest(path: string, init: {
    method: string;
    headers: Headers;
    body?: BodyInit | Uint8Array;
  }, extra?: {
    retry?: boolean;
  }): Promise<Response>;
  /**
   * @param extra.timeoutMs Per-request abort timeout (default REQUEST_TIMEOUT_MS).
   *   Long endpoints (image generation) pass a larger value so the gateway's
   *   own timeout wins with a readable status instead of a client-side abort.
   * @param extra.retry Whether to retry once on transient failures. Safe reads
   *   (GET/HEAD/OPTIONS) default to true; mutations default to false. Set true
   *   only when the endpoint's server-side contract is explicitly idempotent.
   * @param extra.signal Optional caller cancellation combined with the client's
   *   own timeout budget. Aborting either signal cancels the request.
   */
  request<T>(path: string, options?: RequestInit, extra?: {
    timeoutMs?: number;
    retry?: boolean;
    signal?: AbortSignal;
  }): Promise<T>;
}
/**
 * Base class for the domain method groups. Holds the shared transport;
 * `AgentApiClient` assembles the groups onto one class via `applyMixins`
 * (prototype copy), so methods keep their original `this`-on-the-client
 * call shape.
 */
declare class ApiBase {
  protected readonly transport: AgentApiTransport;
  constructor(transport: AgentApiTransport);
}
//# sourceMappingURL=transport.d.ts.map
//#endregion
//#region src/domains/workspace.d.ts
/** Response of GET /agent/workspace (services/agents). */
interface AgentWorkspaceInfo {
  templateKey?: string;
  defaultModel?: string;
  installedFrom?: {
    templateKey: string;
    authorTenantId: string;
    version: number;
  };
  runtime?: string;
  teams?: {
    teamId: string;
    name: string;
    description?: string;
    parentTeamId?: string;
  }[];
  projects?: {
    projectId: string;
    name: string;
    description?: string;
    status: string;
    parentProjectId?: string;
  }[];
  teamIds?: string[];
  projectIds?: string[];
}
declare class WorkspaceApi extends ApiBase {
  /**
   * GET /agent/workspace — workspace config for the authenticated agent
   * (template assignment, default model, org roster).
   */
  getWorkspace(): Promise<AgentWorkspaceInfo>;
  /**
   * GET /templates/{key}/files — persona/workspace file contents for a
   * template the agent has access to. Pass `version` to pin to the version
   * the agent was installed from (omit → the endpoint resolves `latest`).
   */
  getTemplateFiles(templateKey: string, opts?: {
    version?: number;
  }): Promise<{
    files: Record<string, string>;
  }>;
}
//# sourceMappingURL=workspace.d.ts.map
//#endregion
//#region src/domains/sync.d.ts
interface SyncAgentInfo {
  agentId: string;
  tenantId: string;
  displayName: string;
  s3Prefix: string;
  status: "stale" | "syncing" | "synced";
  fileCount?: number;
  totalSize?: number;
  lastSync?: string;
}
interface SyncManifestEntry {
  hash: string;
  size: number;
  modified: string;
  etag?: string;
  storageClass?: string;
  compressed?: boolean;
}
interface SyncManifest {
  version: 1;
  agentId: string;
  lastSync: string;
  files: Record<string, SyncManifestEntry>;
}
interface SyncPresignedUrl {
  path: string;
  url: string;
  expiresAt: string;
}
interface SyncConfirmedUpload {
  filePath: string;
  hash: string;
  size: number;
  storageClass: "STANDARD" | "GLACIER_IR";
  syncedAt: string;
}
interface SyncReconstructFile {
  path: string;
  size: number;
  url: string;
  storageClass?: string;
  compressed?: boolean;
}
interface SyncReconstructBundle {
  agentId: string;
  mode: "full" | "active" | "memory";
  fileCount: number;
  totalSize: number;
  files: SyncReconstructFile[];
  expiresAt: string;
}
interface SyncAgentStats {
  agentId: string;
  standardBytes: number;
  glacierBytes: number;
  fileCount: number;
  lastSyncAt: string | null;
}
interface SyncFileEntry {
  filePath: string;
  size: number;
  modified: string;
  contentHash: string;
  storageClass?: string;
  compressed?: boolean;
}
interface SyncSessionEntry {
  sessionId: string;
  size: number;
  lastModified: string;
  storageClass?: string;
  isArchived: boolean;
}
interface SyncSessionContent {
  sessionId: string;
  content: string;
  compressed: boolean;
}
interface SharedFileEntry {
  filePath: string;
  fileName: string;
  size: number;
  contentType?: string;
}
declare class SyncApi extends ApiBase {
  syncRegister(args?: {
    displayName?: string;
  }): Promise<{
    agent: SyncAgentInfo;
  }>;
  syncGetManifest(): Promise<SyncManifest>;
  syncPresign(args: {
    files: {
      path: string;
      operation: "put" | "get";
      contentType?: string;
    }[];
  }): Promise<{
    urls: SyncPresignedUrl[];
  }>;
  syncConfirmUpload(args: {
    filePath: string;
    hash: string;
    size: number;
    storageClass?: "STANDARD" | "GLACIER_IR";
  }): Promise<SyncConfirmedUpload>;
  syncReconstruct(args: {
    mode: "full" | "active" | "memory";
  }): Promise<SyncReconstructBundle>;
  syncGetStats(): Promise<SyncAgentStats>;
  syncListFiles(args?: {
    prefix?: string;
  }): Promise<{
    files: SyncFileEntry[];
  }>;
  syncListSessions(): Promise<{
    sessions: SyncSessionEntry[];
  }>;
  syncGetSession(sessionId: string): Promise<SyncSessionContent>;
  syncDeleteFile(filePath: string): Promise<{
    removed: boolean;
  }>;
  sharedListFiles(args: {
    scope: "org" | "team" | "project";
    scopeId: string;
    limit?: number;
    cursor?: string;
  }): Promise<{
    files: SharedFileEntry[];
    nextCursor: string | null;
  }>;
  sharedDownloadUrl(args: {
    scope: "org" | "team" | "project";
    scopeId: string;
    filePath: string;
  }): Promise<{
    downloadUrl: string;
    expiresIn: number;
  }>;
}
//# sourceMappingURL=sync.d.ts.map
//#endregion
//#region src/domains/knowledge.d.ts
type KnowledgeScopeType = "org" | "team" | "project";
interface KnowledgeScope {
  scopeType: KnowledgeScopeType;
  scopeId: string;
  name: string;
}
interface KnowledgeSearchHit {
  id: string;
  text: string;
  /** Normalized relevance in (0,1]; higher = closer. */
  score: number;
  scopeType: KnowledgeScopeType;
  scopeId: string;
  /**
   * Provenance of the hit. All live results are `"doc"`; `"fact"` only ever
   * appears for legacy vectors indexed before the facts primitive was removed
   * (the search index stays tolerant of them). Treat every hit as a doc.
   */
  source: "doc" | "fact";
  /** The canonical file under shared/<scope>/ (present on doc hits). */
  filePath?: string;
  /** Legacy-only: the id of a pre-removal fact vector. */
  factId?: string;
}
interface KnowledgeSearchResult {
  results: KnowledgeSearchHit[];
  /** True when fan-out breadth was capped (more member scopes than the cap). */
  truncatedScopes: boolean;
}
interface KnowledgeProfileLink {
  label: string;
  url: string;
}
interface KnowledgeProfile {
  scopeType: KnowledgeScopeType;
  scopeId: string;
  about: string | null;
  description: string | null;
  links: KnowledgeProfileLink[];
  updatedAt: string | null;
  updatedBy: string | null;
}
type ChangeRequestResourceType = "doc" | "profile";
type ChangeRequestOperation = "create" | "update" | "delete";
type ChangeRequestStatus = "open" | "approved" | "rejected" | "withdrawn" | "superseded";
type ChangeRequestActorKind = "human" | "agent";
/** Public projection of a change request (mirrors `PublicChangeRequest` in services/org). */
interface KnowledgeChangeRequest {
  changeRequestId: string;
  scopeType: KnowledgeScopeType;
  scopeId: string;
  resourceType: ChangeRequestResourceType;
  operation: ChangeRequestOperation;
  targetPath: string | null;
  baseVersionId: string | null;
  proposedContentType: string | null;
  status: ChangeRequestStatus;
  proposerId: string;
  proposerKind: ChangeRequestActorKind;
  rationale: string;
  reviewerId: string | null;
  reviewerKind: ChangeRequestActorKind | null;
  reviewedAt: string | null;
  reviewNote: string | null;
  appliedRef: string | null;
  createdAt: string;
  updatedAt: string;
}
/** Per-type proposal payload for `proposeScopeChange`. */
interface ProposeScopeChangeInput {
  resourceType: ChangeRequestResourceType;
  operation: ChangeRequestOperation;
  /** Why the change is proposed — shown to the reviewer. */
  rationale: string;
  /** doc: the path the proposal applies to (e.g. designs/data-center.md). */
  targetPath?: string;
  /** doc create/update: the staged body to upload (markdown or other text). */
  content?: string;
  /** doc create/update: content type of the staged body (default text/markdown). */
  contentType?: string;
  /** profile: the proposed value ({ about, description, links }). */
  proposedValue?: unknown;
}
interface KnowledgeDoc {
  filePath: string;
  fileName: string;
  contentType?: string;
  size: number;
  uploadedBy?: string;
  createdAt: string;
  updatedAt: string;
}
declare class KnowledgeApi extends ApiBase {
  /**
   * Semantic search across the agent's member scopes. Fan-out is gated
   * server-side by `listScopes` set-inclusion (fail-closed). Pass
   * `scopeType` + `scopeId` to narrow to one scope; a non-member scope
   * yields empty results (never a cross-scope leak).
   */
  knowledgeSearch(query: string, opts?: {
    limit?: number;
    scopeType?: KnowledgeScopeType;
    scopeId?: string;
  }): Promise<KnowledgeSearchResult>;
  /** Enumerate the scopes (org + teams + projects) this agent belongs to. */
  listScopes(): Promise<{
    scopes: KnowledgeScope[];
  }>;
  /** Read a scope's structured knowledge profile (after membership check). */
  getScopeProfile(scopeType: KnowledgeScopeType, scopeId: string): Promise<KnowledgeProfile>;
  /**
   * Open a change request against a scope's knowledge resource. For a doc
   * create/update, `services/org` returns a presigned staging PUT; this method
   * uploads the proposed `content` to it (echoing the same Content-Type that
   * was signed), mirroring `writeScopeDoc`. The staged body is applied to the
   * canonical doc — attributed to this agent — only when a reviewer approves.
   */
  proposeScopeChange(scopeType: KnowledgeScopeType, scopeId: string, input: ProposeScopeChangeInput): Promise<KnowledgeChangeRequest>;
  /**
   * List the agent's OWN change requests in a scope (filtered server-side to
   * this agent as proposer). Pass `status` to narrow to open / approved / etc.
   */
  listScopeChangeRequests(scopeType: KnowledgeScopeType, scopeId: string, opts?: {
    status?: ChangeRequestStatus;
    limit?: number;
    cursor?: string;
  }): Promise<{
    changeRequests: KnowledgeChangeRequest[];
    nextCursor: string | null;
  }>;
  /** List a scope's docs (the org-files corpus; mirrored to shared/<scope>/). */
  listScopeDocs(scopeType: KnowledgeScopeType, scopeId: string, opts?: {
    limit?: number;
    cursor?: string;
  }): Promise<{
    files: KnowledgeDoc[];
    nextCursor: string | null;
  }>;
  /**
   * Read the full text of a scope doc. Resolves a presigned download URL
   * from `services/org`, then fetches the bytes directly from S3 (the one
   * legitimate raw fetch in a plugin — same pattern as sync).
   */
  readScopeDoc(scopeType: KnowledgeScopeType, scopeId: string, filePath: string, opts?: {
    maxBytes?: number;
  }): Promise<{
    filePath: string;
    text: string;
  }>;
  /**
   * Write (create or overwrite) a scope doc. Two-step presigned upload:
   * `services/org` returns a signed URL plus `requiredHeaders` (author /
   * authorKind / message as `x-amz-meta-*`) that MUST be sent verbatim on
   * the PUT, alongside the same `Content-Type` that was signed. Author and
   * authorKind are server-set from the agent token — never trusted here.
   */
  writeScopeDoc(scopeType: KnowledgeScopeType, scopeId: string, filePath: string, content: string, opts?: {
    contentType?: string;
    message?: string;
  }): Promise<{
    filePath: string;
  }>;
}
//# sourceMappingURL=knowledge.d.ts.map
//#endregion
//#region src/domains/mobile.d.ts
/** Response of GET /mobile/numbers for an agent (services/mobile). */
interface MobileNumberInfo {
  phoneNumber: string;
  countryCode: string;
  monthlyPrice?: number;
  status: string;
  errorMessage?: string;
}
/** One purchasable number from GET /mobile/numbers/search. */
interface MobileAvailableNumber {
  number: string;
  friendlyName: string;
  locality: string;
  region: string;
  country: string;
}
/** Approved WhatsApp content template from GET /mobile/whatsapp/templates. */
interface WhatsAppTemplate {
  contentSid: string;
  name: string;
  language: string;
  body: string;
  variables: Record<string, string>;
  category?: string;
}
declare class MobileApi extends ApiBase {
  getMobileNumber(): Promise<MobileNumberInfo>;
  searchMobileNumbers(args?: {
    country?: string;
    query?: string;
  }): Promise<{
    numbers: MobileAvailableNumber[];
    monthlyPrice: number;
  }>;
  assignMobileNumber(args: {
    phoneNumber: string;
    countryCode: string;
  }): Promise<{
    phoneNumber: string;
    countryCode: string;
    status: "pending";
  }>;
  releaseMobileNumber(): Promise<{
    released: true;
  }>;
  sendSms(args: {
    to: string;
    body: string;
  }): Promise<{
    sent: true;
    sid: string;
  }>;
  startOutboundCall(args: {
    to: string;
  }): Promise<{
    callSid: string;
    status: string;
  }>;
  getWhatsAppSession(to: string): Promise<{
    active: boolean;
    expiresAt?: string;
  }>;
  sendWhatsAppMessage(args: {
    to: string;
    body: string;
  }): Promise<{
    sent: true;
    sid: string;
  }>;
  sendWhatsAppTemplate(args: {
    to: string;
    contentSid: string;
    contentVariables: Record<string, string>;
    bodyPreview?: string;
  }): Promise<{
    sent: true;
    sid: string;
  }>;
  listWhatsAppTemplates(): Promise<{
    templates: WhatsAppTemplate[];
  }>;
}
//# sourceMappingURL=mobile.d.ts.map
//#endregion
//#region src/domains/remote.d.ts
interface RemoteSessionInfo {
  sessionId: string;
  agentId: string;
  surface: "browser" | "terminal";
  status: "agent_driving" | "awaiting_human" | "human_in_control" | "resuming" | "completed" | "expired" | "failed";
  url?: string;
  instructions?: string;
  requestedAt?: string;
}
declare class RemoteApi extends ApiBase {
  requestBrowserTakeover(args: {
    instructions: string;
    url?: string;
    conversationId?: string;
  }): Promise<{
    sessionId: string;
    status: string;
  }>;
  getRemoteSession(sessionId: string): Promise<RemoteSessionInfo>;
  completeRemoteSession(sessionId: string): Promise<{
    ok: boolean;
  }>;
}
//# sourceMappingURL=remote.d.ts.map
//#endregion
//#region src/domains/self.d.ts
/** Voice settings — core agent config. Mirrors `VoiceConfig` in `@alfe/types`. */
interface AgentVoiceConfig {
  /** ElevenLabs voice ID; platform default when unset. */
  voiceId?: string;
  ttsModel?: string;
  enabled?: boolean;
}
/**
 * The agent's own public identity, as returned by `updateSelf`, `generateAvatar`,
 * `presignAvatar`'s finalize (`finalizeAvatar`). This is the public agent
 * projection; only the identity-relevant fields are typed here — the response
 * carries the full public agent record.
 */
interface AgentSelf {
  agentId: string;
  tenantId: string;
  name: string;
  avatarUrl?: string;
  voiceConfig?: AgentVoiceConfig;
  status: string;
}
/** Result of `presignAvatar` — the agent PUTs bytes to `uploadUrl`, then finalizes with `s3Key`. */
interface AgentAvatarPresign {
  /** Presigned PUT URL to upload the image bytes to. */
  uploadUrl: string;
  /** Object key — echoed back to `finalizeAvatar`. */
  s3Key: string;
  /** Stable public URL the avatar will be served from once finalized. */
  publicUrl: string;
  /** ISO expiry of the presigned PUT URL. */
  expiresAt: string;
}
/** A voice in the platform catalogue (ElevenLabs), from `listVoices`. */
interface AgentVoice {
  id: string;
  name: string;
  previewUrl: string;
  description: string;
  labels: Record<string, string>;
  category: string;
}
declare class SelfApi extends ApiBase {
  /** Update the agent's own name and/or voice config. Returns the updated agent. */
  updateSelf(update: {
    name?: string;
    voiceConfig?: AgentVoiceConfig;
  }): Promise<AgentSelf>;
  /**
   * Generate the agent's own avatar from a text prompt. The image is generated,
   * stored, and set on the agent server-side; returns the updated agent.
   *
   * ASYNC (same reason as `generateImage`): avatar gen runs `gpt-image-1`
   * (30–60s) which exceeds the API Gateway 30s ceiling, so this enqueues a job
   * (`POST /agent/avatar/generate` → `jobId`) then polls (`GET /agent/avatar/{jobId}`)
   * until the avatar is set. Signature unchanged — the plugin is unaffected.
   */
  generateAvatar(args: {
    prompt: string;
  }): Promise<AgentSelf>;
  /**
   * Get a presigned PUT URL to upload a new avatar image. Upload the bytes to
   * `uploadUrl`, then call `finalizeAvatar(s3Key)` to set it on the agent.
   */
  presignAvatar(args: {
    mimeType: string;
    size: number;
  }): Promise<AgentAvatarPresign>;
  /**
   * Finalize an avatar upload — validates ownership + size, then sets the
   * agent's `avatarUrl` server-side. Returns the updated agent.
   */
  finalizeAvatar(s3Key: string): Promise<AgentSelf>;
  /** List the platform voice catalogue (ElevenLabs) so the agent can pick its own voice. */
  listVoices(): Promise<{
    voices: AgentVoice[];
  }>;
}
//# sourceMappingURL=self.d.ts.map
//#endregion
//#region src/domains/voice.d.ts
/** The ElevenLabs models with a pricing row — the TTS endpoint rejects any other value. */
type VoiceTtsModel = "eleven_turbo_v2_5" | "eleven_multilingual_v2";
interface VoiceTtsArgs {
  /** Text to synthesize (1–5000 chars — the endpoint enforces this). */
  text: string;
  /** ElevenLabs voice id; platform default when unset. */
  voiceId?: string;
  /** TTS model; `eleven_turbo_v2_5` (lower latency) when unset. */
  model?: VoiceTtsModel;
}
/** Raw synthesized audio plus its PCM framing (from the response headers). */
interface VoiceTtsResult {
  /** Raw little-endian PCM samples — no container. Wrap in WAV to make a playable file. */
  audio: Buffer;
  /** Samples per second (e.g. 24000). */
  sampleRate: number;
  /** Channel count (mono = 1). */
  channels: number;
  /** Bits per sample (e.g. 16). */
  bitDepth: number;
}
interface VoiceSttArgs {
  /** Raw linear16 (16-bit little-endian) mono PCM samples — no WAV/container header. */
  audio: Uint8Array;
  /** Sample rate of `audio` in Hz (8000–48000). */
  sampleRate: number;
}
interface VoiceSttResult {
  text: string;
  /** Deepgram confidence in (0,1]. */
  confidence: number;
}
declare class VoiceApi extends ApiBase {
  /**
   * Text-to-speech. Returns raw PCM audio bytes plus their framing — the
   * voice service defaults to 24 kHz / mono / 16-bit. Wrap in a WAV container
   * to produce a playable file. Metered per character against the tenant
   * credit pool server-side; TTS completes regardless of metering outcome.
   */
  tts(args: VoiceTtsArgs): Promise<VoiceTtsResult>;
  /**
   * Speech-to-text. Accepts raw linear16 (16-bit LE) mono PCM — NOT a WAV or
   * other container (the endpoint transcribes with a fixed linear16 encoding,
   * so a container header would be transcribed as noise). Strip any WAV header
   * and pass `sampleRate` from it before calling. Metered by transcribed
   * duration against the tenant credit pool server-side.
   */
  stt(args: VoiceSttArgs): Promise<VoiceSttResult>;
}
//# sourceMappingURL=voice.d.ts.map
//#endregion
//#region src/domains/identity.d.ts
type IdentityStatus = "anonymous" | "partial" | "identified" | "verified";
interface IdentityDirectoryEntry {
  identityId: string;
  status: IdentityStatus;
  displayName: string;
  name?: string;
  avatarUrl?: string;
  lastSeenAt: string;
  lastSeenProvider?: string;
  messageable: boolean;
}
declare class IdentityApi extends ApiBase {
  /**
   * Returns the calling agent's own identity context — `{ agentId, tenantId }`
   * decoded server-side from the agent API token. Used by the
   * `@alfe.ai/openclaw-identity` plugin to bootstrap context when the
   * OpenClaw daemon doesn't plumb `ctx.agentId` through to plugin hooks.
   * Plugins should cache this for the daemon's lifetime (single-agent-per-
   * process invariant). One HTTP round-trip per process activate; not for
   * per-call use.
   */
  whoami(): Promise<{
    agentId: string;
    tenantId: string;
  }>;
  resolveIdentity(args: {
    provider: string;
    platformId: string;
    kind?: "user" | "agent" | "service" | "bot" | "workspace";
    displayName?: string;
  }): Promise<{
    identityId: string | null;
    status: string;
    created?: boolean;
    reason?: string;
    /**
     * Flattened auriclabs permission strings for the resolved identity
     * (scope-prefixed where applicable). Empty array on miss / org service
     * outage — the runtime gate fails closed in that case.
     */
    permissions: string[];
  }>;
  searchIdentities(args?: {
    q?: string;
    status?: string;
    limit?: number;
  }): Promise<{
    identities: unknown[];
  }>;
  listIdentities(args?: {
    status?: IdentityStatus;
    limit?: number;
    cursor?: string;
  }): Promise<{
    identities: IdentityDirectoryEntry[];
    cursor: string | null;
  }>;
  getIdentityContext(identityId: string): Promise<{
    context: unknown;
  }>;
  mergeIdentities(survivorId: string, args: {
    mergedId: string;
  }): Promise<{
    ok: boolean;
    error?: string;
  }>;
  unmergeIdentity(identityId: string): Promise<{
    ok: boolean;
    error?: string;
  }>;
  addIdentityNote(identityId: string, args: {
    content: string;
    category?: string;
  }): Promise<{
    noteId: string | null;
  }>;
  tagIdentity(identityId: string, args: {
    tag: string;
    action: "add" | "remove";
  }): Promise<{
    ok: boolean;
  }>;
  getIdentityChangelog(identityId: string, args?: {
    limit?: number;
    cursor?: string;
  }): Promise<{
    entries: unknown[];
    cursor: string | null;
  }>;
  rollbackIdentity(identityId: string, args: {
    targetVersion: number;
  }): Promise<{
    ok: boolean;
    entry?: unknown;
  }>;
  requestIdentityVerification(args: {
    claimedIdentityId: string;
    requestingIdentityId: string;
    requestingProvider: string;
    requestingPlatformId: string;
    preferredChannel?: "mobile" | "email";
    /**
     * Phase 2: agent-supplied contact endpoint. When provided, the top-level
     * `preferredChannel` is ignored — the contact's channel wins.
     */
    contact?: {
      channel: "email" | "mobile";
      value: string;
    };
  }): Promise<{
    verificationId: string;
    channel: string;
    deliveredTo: string;
    expiresAt: string;
    availableChannels: {
      channel: string;
      deliveredTo: string;
    }[];
  } | {
    error: string;
  }>;
  confirmIdentityVerification(args: {
    claimedIdentityId: string;
    verificationId: string;
    phrase: string;
  }): Promise<{
    verified: boolean;
    identityId?: string;
    /** Phase 2: how the confirm resolved — Scenario A vs B. */
    action?: "merged" | "contact_verified" | "already_confirmed";
    error?: string;
  }>;
  /**
   * Update display-shape fields on an Identity. Body excludes `email` /
   * `phone` / `title` / `company` / `metadata` per Section D4 — contacts go
   * via the verify flow, title/company live on OrgMembership, metadata is
   * not agent-writable.
   */
  updateIdentity(identityId: string, args: {
    name?: string;
    avatarUrl?: string;
    timezone?: string;
    locale?: string;
  }): Promise<{
    ok: boolean;
  }>;
  /**
   * Phase 2 (Section H): server-side verification of a Google Chat sender via
   * the agent's existing Google OAuth credentials. Returns the resolved
   * identity (created or matched via Scenario-B email enrichment).
   */
  resolveGoogleChatSender(args: {
    senderUserId: string;
    spaceId?: string;
  }): Promise<{
    identityId: string | null;
    status: string;
  }>;
}
//# sourceMappingURL=identity.d.ts.map
//#endregion
//#region src/domains/search.d.ts
/**
 * The broad-news providers behind the metered `services/news` Lambda. The
 * server validates this with a zod enum; a value outside the union is an
 * unpriceable product, so keep the literal union in lockstep with the service.
 */
type NewsProvider = "apitube" | "newsdata";
/** One normalized article. `sentiment` is provider-shaped (APITube supplies it). */
interface NewsArticle {
  title: string;
  url: string;
  source: string;
  publishedAt: string;
  snippet: string;
  sentiment?: unknown;
}
/** Provider-agnostic result — the server normalizes every adapter to this. */
interface NewsResult {
  articles: NewsArticle[];
  provider: string;
}
declare class SearchApi extends ApiBase {
  searchWeb(params: {
    query: string;
    count?: number;
    offset?: number;
    country?: string;
    freshness?: string;
  }, options?: {
    signal?: AbortSignal;
  }): Promise<unknown>;
  searchImages(params: {
    query: string;
    count?: number;
  }, options?: {
    signal?: AbortSignal;
  }): Promise<unknown>;
  searchNews(params: {
    query: string;
    count?: number;
    offset?: number;
    freshness?: string;
  }, options?: {
    signal?: AbortSignal;
  }): Promise<unknown>;
  /** Search news across the selected provider's corpus. → POST /agent/news/search */
  newsSearch(params: {
    query: string;
    provider?: NewsProvider;
    source?: string;
    from?: string;
    to?: string;
    language?: string;
    category?: string;
    limit?: number;
  }): Promise<NewsResult>;
  /** Top headlines for the selected provider. → POST /agent/news/headlines */
  newsHeadlines(params?: {
    provider?: NewsProvider;
    category?: string;
    source?: string;
    language?: string;
    limit?: number;
  }): Promise<NewsResult>;
}
//# sourceMappingURL=search.d.ts.map
//#endregion
//#region src/domains/webhooks.d.ts
interface AgentWebhook {
  webhookId: string;
  tenantId: string;
  agentId: string;
  name: string;
  provider: string;
  active: boolean;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
}
interface CreatedAgentWebhook extends AgentWebhook {
  url: string;
  signingSecret: string;
}
interface AgentWebhookDelivery {
  deliveryId: string;
  webhookId: string;
  status: string;
  attempts: number;
  createdAt: string;
  deliveredAt?: string;
}
declare class WebhooksApi extends ApiBase {
  createWebhook(args: {
    name: string;
    provider?: "generic" | "github" | "stripe" | "slack";
  }): Promise<CreatedAgentWebhook>;
  listWebhooks(): Promise<AgentWebhook[]>;
  deleteWebhook(webhookId: string): Promise<{
    webhookId: string;
    active: false;
  }>;
  rotateWebhookSecret(webhookId: string): Promise<{
    webhookId: string;
    signingSecret: string;
  }>;
  listWebhookDeliveries(webhookId: string): Promise<AgentWebhookDelivery[]>;
}
//# sourceMappingURL=webhooks.d.ts.map
//#endregion
//#region src/domains/chat.d.ts
declare class ChatApi extends ApiBase {
  ensureDirectConversation(identityId: string): Promise<{
    conversationId: string;
    identityId: string;
    tenantId: string;
    userId: string;
    displayName: string;
    created: boolean;
  }>;
  presignAttachments(files: {
    filename: string;
    mimeType: string;
    size: number;
  }[]): Promise<{
    attachments: {
      id: string;
      uploadUrl: string;
      uploadHeaders: Record<string, string>;
      downloadUrl: string;
      s3Key: string;
      expiresAt: string;
    }[];
  }>;
  recordActivity(data: {
    userId?: string;
    channel: string;
    role: "user" | "assistant";
  }): Promise<{
    recorded: boolean;
  }>;
}
//# sourceMappingURL=chat.d.ts.map
//#endregion
//#region src/domains/connect-credentials.d.ts
declare class ConnectCredentialsApi extends ApiBase {
  /**
   * Returns every connected Google account for the agent. Multi-account by
   * design — the openclaw-google plugin requires the LLM to pass `email`
   * explicitly to `google_run_command` so an account is always selected
   * deliberately.
   *
   * 2026-05-14 (connections-redesign PR 1): the legacy flat shape (`email`,
   * `refreshToken`, `accessToken`, etc., populated from the default account)
   * is gone. Iterate over `accounts`.
   */
  getGoogleCredentials(): Promise<{
    accounts: {
      email: string;
      refreshToken: string;
      clientId: string;
      clientSecret: string;
      displayName?: string;
      connectedAt?: string;
    }[];
  }>;
  disconnectGoogleAccount(email: string): Promise<{
    accounts: {
      email: string;
      displayName?: string;
      connectedAt?: string;
    }[];
  }>;
  getGoogleChatCredentials(): Promise<{
    email: string;
    refreshToken: string;
    clientId: string;
    clientSecret: string;
    displayName?: string;
  }>;
  /**
   * Fetch decrypted credentials for ONE specific connection by its
   * stable connectionId (connection-scoped, vs the provider-scoped
   * `get<Provider>Credentials` helpers). Used by the daemon to resolve
   * a Custom Connection-driven integration's credentials from the
   * exact connection it was installed from — every custom connection
   * shares the `custom` provider id, so provider-scoping is ambiguous.
   *
   * For custom connections `accessToken` is the JSON-encoded secret
   * bundle (the daemon un-bundles it); non-secret fields are on
   * `providerMetadata`. The endpoint enforces that the connection is in
   * the calling agent's effective scope (403 otherwise).
   */
  getConnectionCredentials(connectionId: string): Promise<{
    provider: string;
    connectionId: string;
    accountIdentifier?: string;
    accessToken?: string;
    providerMetadata?: Record<string, unknown>;
    [key: string]: unknown;
  }>;
  /**
   * @deprecated Returns a single primary credential blob (legacy "pick-the-
   * default-connection" shape). Use `getGithubAccounts()` for the multi-
   * account shape required by Pattern A — explicit selector args on every
   * tool. Retained because the `@alfe.ai/github-mcp` proxy is the
   * only consumer that knows about Pattern A; legacy env-interpolation
   * callers will keep hitting `/credentials` until they move to the proxy.
   */
  getGithubCredentials(): Promise<{
    login: string;
    accessToken: string;
  }>;
  /**
   * Pattern A: multi-account credential fetch for GitHub.
   *
   * Returns every agent-scoped GitHub connection. The caller is expected
   * to require a `login` selector on every credential-touching tool and
   * look up the matching account at dispatch time.
   *
   * GitHub OAuth tokens have no expiry (`tokenLifecycle: "no_expiry"`),
   * so there is intentionally no `refreshGithubAccountToken` method — if
   * a token is revoked the user must re-run the OAuth flow.
   *
   * Returned `accounts[i].login` is the GitHub username — the stable
   * cross-session identifier the LLM should pass.
   */
  getGithubAccounts(): Promise<{
    accounts: {
      connectionId: string;
      accountIdentifier: string;
      displayName: string | null;
      connectedAt: string;
      accessToken: string;
      login: string;
      scopes: string;
    }[];
  }>;
  /**
   * @deprecated Returns a single primary credential blob (legacy "pick-the-
   * default-connection" shape). Use `getXeroAccounts()` for the multi-
   * account shape required by Pattern A — explicit selector args on every
   * tool. This method will be removed once all consumers migrate.
   */
  getXeroCredentials(): Promise<{
    accessToken: string;
    accessTokenExpiresAt: string;
    xeroTenantId: string;
  }>;
  /**
   * Pattern A: multi-account credential fetch for Xero. Returns every
   * agent-scoped Xero connection. The caller is expected to require a
   * selector arg (e.g. `xeroTenantId`) on every credential-touching tool
   * and look up the matching account by that selector at dispatch time.
   *
   * `xeroTenantId` is the model-facing organisation selector. The separate
   * `accountIdentifier` is the Connect persistence key used for refresh and
   * may be an email; never substitute one for the other.
   */
  getXeroAccounts(): Promise<{
    accounts: {
      connectionId: string;
      accountIdentifier: string;
      displayName: string | null;
      connectedAt: string;
      accessToken: string;
      accessTokenExpiresAt: string;
      xeroTenantId: string;
    }[];
  }>;
  refreshXeroToken(): Promise<{
    accessToken: string;
    expiresAt: string;
  }>;
  /**
   * Refresh a specific Xero Connection by its exact `accountIdentifier` from
   * `getXeroAccounts()`. Do not substitute `xeroTenantId`: current Xero OAuth
   * rows may use the account email as their persistence key even when a sole
   * organisation tenant ID is available in provider metadata.
   */
  refreshXeroAccountToken(accountIdentifier: string): Promise<{
    accessToken: string;
    accessTokenExpiresAt: string;
    expiresAt: string;
  }>;
  /**
   * @deprecated Returns a single primary credential blob (legacy "pick-the-
   * default-connection" shape). Use `getNotionAccounts()` for the multi-
   * account shape required by Pattern A.
   */
  getNotionCredentials(): Promise<{
    accessToken: string;
    workspaceId: string;
    workspaceName: string;
  }>;
  /**
   * Pattern A: multi-account credential fetch for Notion. Returns every
   * agent-scoped Notion connection. The caller is expected to require a
   * selector arg (e.g. `workspaceId`) on every credential-touching tool.
   *
   * Returned `accounts[i].accountIdentifier` is the Notion workspaceId.
   */
  getNotionAccounts(): Promise<{
    accounts: {
      connectionId: string;
      accountIdentifier: string;
      displayName: string | null;
      connectedAt: string;
      accessToken: string;
      workspaceId: string;
      workspaceName: string;
    }[];
  }>;
  /**
   * @deprecated Returns a single primary Atlassian Connection's credentials
   * (one OAuth user, one cloudId) — the legacy "pick-the-default-connection"
   * shape. Atlassian is multi-site by nature (each OAuth user may have
   * access to multiple Cloud sites), so Pattern A plugins MUST use
   * `getAtlassianAccounts()` to discover the full set and dispatch via
   * the `cloudId` selector arg.
   */
  getAtlassianCredentials(): Promise<{
    accessToken: string;
    refreshToken: string;
    accessTokenExpiresAt: string;
    cloudId: string;
    siteName: string;
    siteUrl: string;
    email: string;
    enabledProducts: string[];
    clientId: string;
    clientSecret: string;
  }>;
  refreshAtlassianToken(): Promise<{
    accessToken: string;
    expiresAt: string;
  }>;
  /**
   * Pattern A: multi-account / multi-site credential fetch for Atlassian.
   *
   * Returns every agent-scoped Atlassian Connection. Each Connection is
   * one OAuth user with a single access token and N accessible Cloud
   * sites (`availableSites`). The caller is expected to:
   *
   *   1. Flatten (connection × cloudId) into one MCP child per site.
   *   2. Require a `cloudId` selector on every credential-touching tool.
   *   3. Use the access token bound to the Connection that owns the
   *      requested `cloudId` (Atlassian shares one access token across
   *      all sites accessible to the OAuth user).
   *
   * Per-account token refresh uses `refreshAtlassianAccountToken(email)`
   * — refreshing one Connection rotates its single access token, which
   * then applies to every cloudId for that Connection.
   *
   * Returned `accounts[i].accountIdentifier` is the OAuth user's email
   * — the stable cross-session identifier for refresh purposes. The LLM
   * never sees this directly: it picks a site via the `cloudId` arg
   * instead.
   */
  getAtlassianAccounts(): Promise<{
    accounts: {
      connectionId: string;
      accountIdentifier: string;
      displayName: string | null;
      connectedAt: string;
      accessToken: string;
      accessTokenExpiresAt: string;
      clientId: string;
      clientSecret: string;
      cloudId: string;
      siteName: string;
      siteUrl: string;
      availableSites: {
        id: string;
        url: string;
        name: string;
        scopes?: string[];
        avatarUrl?: string;
      }[];
    }[];
  }>;
  /**
   * Pattern A: refresh a specific Atlassian Connection by `accountIdentifier`
   * (the OAuth user's email).
   *
   * Atlassian rotates refresh tokens (`rotatesRefreshToken: true`); the
   * server-side per-account refresh endpoint handles rotation and
   * persistence. Refreshing one Connection updates its single access
   * token, which applies to every accessible Cloud site (cloudId) for
   * that OAuth user.
   *
   * Returns the new access token + expiry. The proxy is responsible for
   * fanning the new token out to every child server it spawned for
   * cloudIds owned by this Connection.
   */
  refreshAtlassianAccountToken(accountIdentifier: string): Promise<{
    accessToken: string;
    accessTokenExpiresAt: string;
    expiresAt: string;
  }>;
  /**
   * @deprecated Returns a single primary credential blob (legacy "pick-the-
   * default-connection" shape). Use `getMYOBAccounts()` for the multi-
   * account shape required by Pattern A.
   */
  getMYOBCredentials(): Promise<{
    accessToken: string;
    accessTokenExpiresAt: string;
    myobBusinessId: string;
    clientId: string;
  }>;
  /**
   * Pattern A: multi-account credential fetch for MYOB. Returns every
   * agent-scoped MYOB connection. The caller is expected to require a
   * selector arg (e.g. `myobBusinessId` / `accountIdentifier`) on every
   * credential-touching tool.
   *
   * Returned `accounts[i].accountIdentifier` is the MYOB businessId.
   */
  getMYOBAccounts(): Promise<{
    accounts: {
      connectionId: string;
      accountIdentifier: string;
      displayName: string | null;
      connectedAt: string;
      accessToken: string;
      accessTokenExpiresAt: string;
      myobBusinessId: string;
      clientId: string;
    }[];
  }>;
  refreshMYOBToken(): Promise<{
    accessToken: string;
    expiresAt: string;
  }>;
  /**
   * Pattern A: refresh one MYOB Connection by its stable
   * `accountIdentifier` (the MYOB business id returned by
   * `getMYOBAccounts()`).
   *
   * MYOB refresh tokens belong to individual Connection rows. A
   * multi-business client must use this method instead of refreshing the
   * primary Connection and copying that access token into every cached
   * business client.
   */
  refreshMYOBAccountToken(accountIdentifier: string): Promise<{
    accessToken: string;
    accessTokenExpiresAt: string;
    expiresAt: string;
  }>;
  /**
   * @deprecated Returns a single primary credential blob. Use
   * `getSalesforceAccounts()` for the multi-account shape required by
   * Pattern A.
   */
  getSalesforceCredentials(): Promise<{
    accessToken: string;
    accessTokenExpiresAt: string;
    instanceUrl: string;
    orgId: string;
  }>;
  /**
   * Pattern A: multi-account credential fetch for Salesforce. Returns every
   * agent-scoped Salesforce connection. One OAuth grant maps to one org, so
   * `accounts[i].accountIdentifier` (and `orgId`) is the Salesforce org id —
   * the selector every credential-touching tool requires.
   */
  getSalesforceAccounts(): Promise<{
    accounts: {
      connectionId: string;
      accountIdentifier: string;
      displayName: string | null;
      connectedAt: string;
      accessToken: string;
      accessTokenExpiresAt: string;
      instanceUrl: string;
      orgId: string;
    }[];
  }>;
  /**
   * Refresh the access token for a specific Salesforce org. Salesforce
   * tokens aren't interchangeable across orgs, so the connection is targeted
   * by `accountIdentifier` (the org id) — mirrors `refreshXeroAccountToken`.
   */
  refreshSalesforceAccountToken(orgId: string): Promise<{
    accessToken: string;
    accessTokenExpiresAt: string;
    expiresAt: string;
  }>;
  /**
   * Pattern A: multi-account credential fetch for Microsoft 365.
   *
   * Returns every agent-scoped Microsoft connection. The caller is expected
   * to require an `email` selector on every credential-touching tool and
   * look up the matching account at dispatch time.
   *
   * Returned `accounts[i].accountIdentifier` is the user's primary email
   * (or the tid claim as fallback) — the stable cross-session identifier
   * the LLM should pass.
   *
   * Per-account token refresh is exposed via `refreshMicrosoftAccountToken`,
   * NOT `refreshXeroAccountToken` — Microsoft refresh tokens are not
   * interchangeable across (tenant, user) pairs.
   */
  getMicrosoftAccounts(): Promise<{
    accounts: {
      connectionId: string;
      accountIdentifier: string;
      displayName: string | null;
      connectedAt: string;
      accessToken: string;
      accessTokenExpiresAt: string;
      email: string;
      microsoftTenantId: string;
      workspaceDomain: string;
    }[];
  }>;
  /**
   * Pattern A: refresh a specific Microsoft 365 connection by its
   * `accountIdentifier`. For Microsoft, `accountIdentifier` is the user's
   * email when the Graph profile fetch succeeded at connect time, and the
   * Azure tenant id (`tid` claim) as fallback. Callers should pass the
   * value returned by `getMicrosoftAccounts()` rather than synthesising
   * an email locally.
   *
   * Microsoft refresh tokens are bound to a specific (tenant, user) pair —
   * they are NOT interchangeable across accounts, so per-account refresh
   * is mandatory. The generic /accounts/{accountIdentifier}/refresh
   * endpoint walks the agent's full visible scope chain to find a matching
   * connection (works for inherited team/project Microsoft connections).
   */
  refreshMicrosoftAccountToken(accountIdentifier: string): Promise<{
    accessToken: string;
    accessTokenExpiresAt: string;
    expiresAt: string;
  }>;
  /**
   * Disconnects one connected Microsoft 365 account for the agent, by its
   * `accountIdentifier`. Hits the generic per-account disconnect route
   * (`DELETE /agent/connect/microsoft/accounts/{accountIdentifier}`), which
   * resolves across the agent's full effective scope chain and deletes the
   * matching Connection row. Returns the remaining accounts.
   *
   * IMPORTANT: pass the `accountIdentifier` from `getMicrosoftAccounts()`, NOT
   * a synthesised email. For Microsoft, `accountIdentifier` is the user's email
   * only when the Graph profile fetch succeeded at connect time; it falls back
   * to the Azure tenant id (`tid` claim) otherwise. The backend matches on
   * `accountIdentifier` exactly, so passing an email would 404 on those
   * fallback-identifier accounts. (This is why the param is not named `email`,
   * unlike `disconnectGoogleAccount` where the identifier is always the email.)
   */
  disconnectMicrosoftAccount(accountIdentifier: string): Promise<{
    accounts: {
      accountIdentifier: string;
      displayName?: string;
      connectedAt?: string;
    }[];
  }>;
  /**
   * Resolve the primary cTrader Connection's credentials for the calling
   * agent. Unlike most providers, the cTrader Open API needs app-level auth
   * (`clientId` + `clientSecret`) AND account auth (`accessToken` +
   * `accountId`) on the socket, so `@alfe.ai/ctrader-mcp` self-fetches the
   * full set here at startup (the atlassian/google pattern). `clientId` /
   * `clientSecret` are the SST-sourced global app credentials the connect
   * endpoint injects — they are never persisted on the connection. `host` is
   * the resolved TLS endpoint (`live.ctraderapi.com` / `demo.ctraderapi.com`)
   * derived from the selected account's live/demo flag.
   */
  getCTraderCredentials(): Promise<{
    accessToken: string;
    refreshToken: string;
    accountId: string;
    host: string;
    clientId: string;
    clientSecret: string;
  }>;
  /**
   * Pattern A: multi-account credential fetch for cTrader.
   *
   * Unlike atlassian/salesforce (one Connection row per account/site), a
   * cTrader is MULTI-grant per agent: an agent may connect several distinct
   * cTrader logins, each its own Connection row keyed on `accountIdentifier =
   * ctid:<userId>` (Phase 1). This aggregates the *trading accounts* across
   * ALL of those Connection rows — each row contributes its `availableAccounts`
   * flattened, and every account carries ITS OWN grant's `accessToken` (the
   * token that authenticates that account against the cTrader Open API). One
   * OAuth grant still covers all accounts under that single login on one shared
   * token; only the `ctidTraderAccountId` and the protobuf socket `host` (live
   * vs demo) differ within a grant. Across grants the tokens differ, so the
   * token is now PER-ACCOUNT rather than hoisted to the top level.
   *
   * `host` per account is derived from the account's `isLive` flag
   * (`live.ctraderapi.com` / `demo.ctraderapi.com`) — the same mapping the
   * connect provider applies server-side when an account is auto-selected.
   *
   * `clientId` / `clientSecret` are the SST-sourced GLOBAL app credentials the
   * connect endpoint injects — identical across every Connection row (one
   * cTrader app), never persisted on a connection. We take them from the first
   * row that carries them.
   *
   * Accounts are deduped on `ctidTraderAccountId` first-wins: Spotware ids are
   * globally unique across logins, so a duplicate can only appear if the same
   * account somehow surfaced under two grants — first-wins keeps it
   * deterministic.
   *
   * `accounts` may be empty (no cTrader Connection at all), in which case we
   * return empty creds rather than throwing.
   */
  getCTraderAccounts(): Promise<{
    accounts: {
      ctidTraderAccountId: string;
      host: string;
      isLive: boolean;
      brokerName?: string;
      accountNumber?: string;
      accessToken: string;
      /**
       * The stable per-grant Connection key (`ctid:<userId>`) this account
       * belongs to. Every trading account under one cTrader login shares one
       * grant (one OAuth token), so this is the identifier the MCP server
       * passes to `refreshCTraderAccount()` to rotate the token for the whole
       * grant on a `CH_ACCESS_TOKEN_INVALID` expiry. Empty string when the
       * server did not supply one (legacy rows) — such an account can still
       * trade with its current token but cannot self-refresh.
       */
      accountIdentifier: string;
    }[];
    clientId: string;
    clientSecret: string;
  }>;
  /**
   * Pattern A: refresh a specific cTrader grant by its stable
   * `accountIdentifier` (`ctid:<userId>` from `getCTraderAccounts()`).
   *
   * cTrader access tokens live ~30 days; the `getCTraderAccounts()` /
   * credentials reads serve the STORED token without refreshing, so refresh is
   * the consumer's job. `@alfe.ai/ctrader-mcp` calls this when the cTrader Open
   * API rejects an account-auth with `CH_ACCESS_TOKEN_INVALID`, then re-runs
   * the socket handshake with the returned `accessToken`.
   *
   * Refreshing one grant rotates the single OAuth token that covers EVERY
   * trading account under that login. cTrader's refresh token itself does not
   * expire but may rotate on refresh (`rotatesRefreshToken: true`); connect
   * persists the rotated refresh token server-side, so the caller only needs
   * the new `accessToken`. Mirrors `refreshXeroAccountToken`.
   */
  refreshCTraderAccount(accountIdentifier: string): Promise<{
    accessToken: string;
    accessTokenExpiresAt: string;
    expiresAt: string;
  }>;
  /**
   * @deprecated Returns a single primary credential blob. Use
   * `getShopifyAccounts()` for the multi-account shape required by Pattern A
   * (`@alfe.ai/shopify-mcp` keys per-shop on the myshopify domain).
   */
  getShopifyCredentials(): Promise<{
    accessToken: string;
    shopDomain: string;
    shopGid: string;
    shopName: string;
    apiVersion: string;
  }>;
  /**
   * Pattern A: multi-account credential fetch for Shopify. Returns every
   * agent-scoped Shopify Connection. One OAuth grant maps to one store, so the
   * stable per-call selector is the store's myshopify domain (`shopDomain`),
   * NOT `accountIdentifier` — the connect provider keys `accountIdentifier` on
   * the immutable shop GID (falling back to the domain), so `shopDomain` is the
   * value the LLM passes and the plugin routes on.
   *
   * Each entry is shaped by the connect provider's `buildCredentialsResponse`:
   * `{ accessToken, shopDomain, shopGid, shopName, apiVersion }` — offline
   * Shopify tokens never expire, so there is NO token / expiry field and no
   * refresh method (unlike Salesforce). The GraphQL Admin API authenticates
   * purely on `X-Shopify-Access-Token`; no client credentials are on the wire.
   */
  getShopifyAccounts(): Promise<{
    accounts: {
      connectionId: string;
      accountIdentifier: string;
      displayName: string | null;
      connectedAt: string;
      accessToken: string;
      shopDomain: string;
      shopGid: string;
      shopName: string;
      apiVersion: string;
    }[];
  }>;
  /**
   * Pattern A: provider-parameterized multi-account credential fetch for the
   * social connectors (Bluesky, and the approval-gated backlog: X, Meta,
   * Threads, LinkedIn, Pinterest, TikTok, Reddit, YouTube).
   *
   * Unlike the bespoke `getGithubAccounts()` / `getXeroAccounts()` shapes,
   * this returns a UNIFORM normalized account shape so `@alfe.ai/social-mcp`'s
   * shared driver can require a single `account` selector on every
   * credential-touching tool regardless of platform. The backend
   * `api-agents/{provider}/accounts` route is already provider-generic; this
   * is the client-side normalization the plan (`do-we-need-any-moonlit-toucan`
   * Phase 0, step 5) calls for.
   *
   * `accountIdentifier` is the stable per-account selector the LLM should
   * pass back (for Bluesky: the account DID). `accessToken` carries whatever
   * the provider's `buildCredentialsResponse` bundles (for Bluesky: the JSON
   * session bundle — the driver parses the `accessJwt` out of it, or reads the
   * top-level `accessJwt` from `providerMetadata`-adjacent fields). Everything
   * else the driver needs for routing (handle, pdsHost, did, …) is on
   * `providerMetadata`.
   *
   * Token refresh is delegated to connect (never done in-plugin) via the
   * per-account route `POST /agent/connect/{provider}/accounts/{accountIdentifier}/refresh`
   * — call `refreshSocialAccount(provider, accountIdentifier)`. (The non-account
   * `POST /agent/connect/{provider}/refresh` route refreshes the provider's
   * PRIMARY connection, which is wrong under multi-account Pattern A.)
   */
  getSocialAccounts(provider: string): Promise<{
    provider: string;
    accounts: {
      connectionId: string;
      accountIdentifier: string;
      displayName: string | null;
      accessToken: string;
      providerMetadata: Record<string, unknown>;
      connectedAt: string;
    }[];
  }>;
  /**
   * Pattern A: refresh a specific social Connection by its stable
   * `accountIdentifier` (for Bluesky: the account DID) via the
   * provider-generic per-account refresh route. The counterpart to
   * `getSocialAccounts(provider)`; `@alfe.ai/social-mcp` calls this on a
   * 401/ExpiredToken from the platform PDS/API, then re-fetches accounts to
   * pick up the rotated bundle.
   *
   * Refresh itself is ALWAYS delegated to connect — the plugin never calls
   * the platform's own refresh XRPC (e.g. `com.atproto.server.refreshSession`)
   * because connect owns the encrypted refresh token + rotation persistence
   * (Bluesky rotates the refreshJwt; a missed rotation kills the connection
   * after one refresh). The returned `accessToken` is whatever the provider's
   * `refreshToken` hook re-bundled (for Bluesky: the JSON session bundle with
   * the fresh `accessJwt`) — callers typically ignore it and re-fetch via
   * `getSocialAccounts` for a consistent shape.
   */
  refreshSocialAccount(provider: string, accountIdentifier: string): Promise<{
    accountIdentifier: string;
    accessToken: string;
    accessTokenExpiresAt: string;
    expiresAt: string;
  }>;
}
//# sourceMappingURL=connect-credentials.d.ts.map
//#endregion
//#region src/domains/database.d.ts
declare class DatabaseApi extends ApiBase {
  registerDatabaseCredentials(): Promise<{
    connectionString: string;
    username: string;
    password: string;
    databases: string[];
  }>;
  reportDatabaseAudit(entry: {
    database: string;
    collection: string;
    operation: string;
    summary?: string;
  }): Promise<void>;
}
//# sourceMappingURL=database.d.ts.map
//#endregion
//#region src/domains/images.d.ts
declare class ImagesApi extends ApiBase {
  /**
   * Generate an image from a text prompt and get back a STABLE, public URL
   * (served from the agent-assets CDN — it does not expire). Embed the returned
   * `imageUrl` in a reply as markdown to show it to the user.
   *
   * ASYNC: `gpt-image-1` routinely runs 30–60s, which exceeds the API Gateway
   * 30s ceiling, so this enqueues a job (`POST /agent/images/generate` →
   * `jobId`) then polls (`GET /agent/images/{jobId}`) until it completes. The
   * worker's real failure message (e.g. an unsupported `size`) surfaces via the
   * job's `error` field.
   */
  generateImage(args: {
    prompt: string;
    model?: string;
    size?: string;
    quality?: string;
  }): Promise<{
    imageUrl: string;
    model: string;
  }>;
}
//# sourceMappingURL=images.d.ts.map
//#endregion
//#region src/domains/integrations.d.ts
declare class IntegrationsApi extends ApiBase {
  listIntegrations(): Promise<IntegrationInstall[]>;
  getIntegrationConfig(integrationId: string): Promise<IntegrationConfigResult>;
  updateIntegrationConfig(integrationId: string, config: Record<string, unknown>): Promise<void>;
  installIntegration(integrationId: string, options?: {
    version?: string;
    config?: Record<string, unknown>;
  }): Promise<IntegrationInstall>;
  removeIntegration(integrationId: string): Promise<IntegrationInstall>;
  getOAuthUrl(provider: string, scopes?: string[], options?: {
    shop?: string;
  }): Promise<{
    url: string;
    provider: string;
    expiresIn: number;
  }>;
  getOAuthStatus(provider: string): Promise<{
    provider: string;
    connected: boolean;
    config?: Record<string, string>;
  }>;
  getRegistry(): Promise<{
    integrations: RegistryEntry[];
  }>;
}
//# sourceMappingURL=integrations.d.ts.map
//#endregion
//#region src/domains/memory.d.ts
declare class MemoryApi extends ApiBase {
  memorySearch(query: string, opts?: {
    limit?: number;
    topic?: string;
    subtopic?: string;
    tag?: string;
    includeKnowledge?: boolean;
  }): Promise<{
    facts: {
      subject: string;
      predicate: string;
      object: string;
      since: string;
      confidence: number;
    }[];
    memories: {
      id: string;
      text: string;
      topic: string;
      subtopic: string;
      tag: string;
      importance: number;
      timestamp: number;
      score: number;
    }[];
  }>;
  memoryStore(text: string, opts?: {
    topic?: string;
    subtopic?: string;
    tag?: string;
    importance?: number;
  }): Promise<{
    memoryId: string;
  }>;
  memoryIngest(sessionKey: string, messages: {
    role: string;
    content: string;
    index: number;
    timestamp?: string;
  }[], metadata?: {
    channelId?: string;
    userId?: string;
    userName?: string;
  }, ingestEpoch?: number): Promise<{
    queued: boolean;
    messageCount: number;
  }>;
  memoryLoadContext(tier?: number, topicHint?: string): Promise<{
    tier: number;
    facts: {
      subject: string;
      predicate: string;
      object: string;
      since: string;
    }[];
    memories: {
      text: string;
      topic: string;
      subtopic: string;
      score: number;
    }[];
    tokenEstimate: number;
    formatted: string;
  }>;
  memoryLookupEntity(subject: string): Promise<{
    subject: string;
    triples: {
      tripleId: string;
      predicate: string;
      object: string;
      validFrom: string;
      validTo?: string;
      confidence: number;
    }[];
  }>;
  memoryNavigate(): Promise<{
    topics: {
      name: string;
      tripleCount: number;
      subtopics: string[];
    }[];
    cursor: string | null;
  }>;
  memoryDelete(memoryId: string): Promise<{
    deleted: boolean;
  }>;
  memoryStats(): Promise<{
    vectorCount: number;
    tripleCount: number;
    storageEstimateBytes: number;
    lastIngestionAt?: string;
  }>;
  memoryLearn(args: {
    text: string;
    source?: string;
    sourceType?: "file" | "url" | "inline";
    metadata?: {
      sessionId?: string;
      channelId?: string;
      userName?: string;
    };
  }): Promise<{
    memoriesStored: number;
    triplesStored: number;
    chunks: number;
    source?: string;
  }>;
  memoryBootstrapStatus(): Promise<{
    synced: boolean;
    syncedAt?: string;
    sessionsBackfillSynced?: boolean;
    sessionsBackfillSyncedAt?: string;
  }>;
  memoryBootstrapStatusMark(scope?: "files" | "sessions"): Promise<{
    synced: true;
    syncedAt: string;
  }>;
}
//# sourceMappingURL=memory.d.ts.map
//#endregion
//#region src/domains/secrets.d.ts
declare class SecretsApi extends ApiBase {
  /**
   * Mint a fresh AES-256 data key for a specific (secret, field) pair. The
   * encryption context is rebuilt server-side from `auth.tenantId` + the body
   * fields including `fieldKey`; the agent cannot forge context for a scope
   * or field it doesn't own. Legacy single-envelope secrets are migrated to
   * `field#value` rows by the data migration, so call with `fieldKey: "value"`
   * to reach them.
   */
  generateSecretDataKey(args: {
    scope: SecretScope;
    scopeId: string;
    secretId: string;
    fieldKey: string;
  }): Promise<GeneratedDataKey>;
  /**
   * Unwrap a wrapped data key so the agent can decrypt the envelope locally.
   * `fieldKey` MUST match the value supplied when the data key was generated
   * (it's bound into KMS encryption context); mismatch fails with
   * `InvalidCiphertextException`.
   */
  decryptSecretDataKey(args: {
    scope: SecretScope;
    scopeId: string;
    secretId: string;
    fieldKey: string;
    dataKeyCiphertext: string;
  }): Promise<{
    plaintextKey: string;
  }>;
  /**
   * Create a new secret with one or more fields. Encrypted fields must arrive
   * pre-sealed (the agent has already obtained per-field data keys via
   * `generateSecretDataKey({ ..., fieldKey })` and AES-encrypted locally).
   * Plaintext fields ship the value inline.
   */
  createSecret(args: {
    scope: SecretScope;
    scopeId: string;
    secretId: string;
    secretName: string;
    category?: SecretCategory;
    description?: string;
    tags?: string[];
    fields: {
      key: string;
      format?: FieldFormat;
      sensitivity: FieldSensitivity;
      value?: string;
      envelope?: EncryptedEnvelopeV1;
    }[];
    reason?: string;
  }): Promise<SecretAggregate>;
  /** Fetch the secret aggregate plus per-field encrypted envelopes. */
  getSecret(args: {
    scope: SecretScope;
    scopeId: string;
    secretId: string;
  }): Promise<{
    aggregate: SecretAggregate;
    envelopes: FieldEnvelope[];
  }>;
  /** Fetch one field. Plaintext: value inline. Encrypted: envelope. */
  getSecretField(args: {
    scope: SecretScope;
    scopeId: string;
    secretId: string;
    fieldKey: string;
  }): Promise<{
    key: string;
    sensitivity: FieldSensitivity;
    format?: FieldFormat;
    value?: string;
    envelope?: EncryptedEnvelopeV1;
    rotatedAt?: string;
    createdAt: string;
    updatedAt: string;
  }>;
  /** Add OR rotate one field. */
  setSecretField(args: {
    scope: SecretScope;
    scopeId: string;
    secretId: string;
    fieldKey: string;
    sensitivity: FieldSensitivity;
    format?: FieldFormat;
    value?: string;
    envelope?: EncryptedEnvelopeV1;
    reason?: string;
  }): Promise<{
    fieldKey: string;
    rotated: boolean;
  }>;
  /** Remove one field. */
  removeSecretField(args: {
    scope: SecretScope;
    scopeId: string;
    secretId: string;
    fieldKey: string;
  }): Promise<void>;
  /** Update secret-level metadata (name/description/tags/category). */
  updateSecretMetadata(args: {
    scope: SecretScope;
    scopeId: string;
    secretId: string;
    secretName?: string;
    description?: string;
    tags?: string[];
    category?: SecretCategory;
    reason?: string;
  }): Promise<SecretAggregate>;
  /** List metadata for secrets in a scope. Optional filters route through the byFacet GSI. */
  listSecrets(args: {
    scope: SecretScope;
    scopeId: string;
    category?: SecretCategory;
    tag?: string;
    fieldKey?: string;
  }): Promise<SecretMetadata[]>;
  /** Bounded changelog read — metadata-only audit entries. */
  getSecretHistory(args: {
    scope: SecretScope;
    scopeId: string;
    secretId: string;
    limit?: number;
    cursor?: string;
  }): Promise<{
    entries: ChangelogEntry[];
    nextCursor?: string;
  }>;
  /** Delete a secret (and all its field rows + tag rows + changelog rows). */
  deleteSecret(args: {
    scope: SecretScope;
    scopeId: string;
    secretId: string;
  }): Promise<void>;
  /** Enumerate scopes (org/team/project/agent) this agent can access. */
  listSecretScopes(): Promise<ScopeInfo[]>;
}
//# sourceMappingURL=secrets.d.ts.map
//#endregion
//#region src/domains/teams.d.ts
declare class TeamsApi extends ApiBase {
  getTeamsCredentials(): Promise<{
    agentId: string;
    tenantId: string;
    azureAppId: string;
    azureBotId: string;
    azureClientSecret: string;
    botDisplayName?: string;
    teamsTenantId?: string;
    serviceUrl?: string;
  }>;
  sendTeamsMessage(data: {
    conversationId: string;
    text?: string;
    adaptiveCard?: Record<string, unknown>;
  }): Promise<{
    ok: boolean;
    activityId: string;
  }>;
  listTeamsChannels(): Promise<{
    channels: {
      id: string;
      name: string;
      description?: string;
    }[];
  }>;
}
//# sourceMappingURL=teams.d.ts.map

//#endregion
//#region src/index.d.ts
interface AgentApiClient extends SyncApi, IntegrationsApi, WorkspaceApi, ConnectCredentialsApi, TeamsApi, ChatApi, SecretsApi, IdentityApi, MemoryApi, SearchApi, KnowledgeApi, DatabaseApi, MobileApi, RemoteApi, SelfApi, VoiceApi, ImagesApi, WebhooksApi {}
declare class AgentApiClient extends ApiBase {
  constructor(config: AgentApiClientConfig);
}
//# sourceMappingURL=index.d.ts.map

//#endregion
//#endregion
//#region ../chat/dist/index.d.ts
//#region src/types.d.ts
/**
 * Types for the @alfe.ai/chat package.
 */
/** Configuration for the ChatServiceClient. */
interface ChatServiceClientOptions {
  /** Chat service WebSocket URL (e.g. wss://chat.dev.alfe.ai/ws) */
  wsUrl: string;
  /** Agent API key for Bearer auth */
  apiKey: string;
  /** Called when the chat service sends an RPC request */
  onRequest: (request: RpcRequest) => void | Promise<void>;
  /** Called when connection state changes */
  onConnectionChange?: (connected: boolean) => void;
  /** Optional logger (defaults to console) */
  logger?: Logger;
}
/** An RPC request from the chat service. */
interface RpcRequest {
  type: 'req';
  id: string;
  method: string;
  params: Record<string, unknown>;
}
/** Minimal logger interface — no dependency on any logging library. */
interface Logger {
  info(msg: string, ...args: unknown[]): void;
  warn(msg: string, ...args: unknown[]): void;
  error(msg: string, ...args: unknown[]): void;
  debug(msg: string, ...args: unknown[]): void;
}
//#endregion
//#region src/client.d.ts
declare class ChatServiceClient {
  private readonly options;
  private ws;
  private stopped;
  private connected;
  private connectionGeneration;
  private retryCount;
  private retryTimer;
  private heartbeatTimer;
  private isAlive;
  private readonly log;
  private pendingRequests;
  private requestCounter;
  private messageQueue;
  private queuedBytes;
  constructor(options: ChatServiceClientOptions);
  get isConnected(): boolean;
  /** Start connecting to the chat service. */
  start(): void;
  /** Stop the client and close the connection. */
  stop(): void;
  /** Send a raw JSON message to the chat service. Queues if disconnected. */
  send(msg: unknown): void;
  /** Send an RPC response back to the chat service. */
  sendResponse(id: string, ok: boolean, payload?: unknown): void;
  /** Send a streaming event to the chat service (e.g. chat deltas). */
  sendEvent(event: string, payload: unknown): void;
  /** Send a fire-and-forget notification to the chat service. */
  notify(event: string, payload: Record<string, unknown>): void;
  /**
   * Send an RPC request to the chat service and wait for a response.
   * Used by agent-to-agent tools to invoke server-side logic.
   */
  sendRequest(method: string, params: Record<string, unknown>, timeoutMs?: number): Promise<Record<string, unknown>>;
  private flushMessageQueue;
  private enqueueMessage;
  private flushPendingRequests;
  private rejectPendingRequest;
  private doConnect;
  private isCurrentSocket;
  private setConnected;
  private notifyConnectionChange;
  private handleMessage;
  private scheduleReconnect;
  /**
   * Detect a silently-dropped connection. Each tick: if no inbound liveness
   * (pong/ping/message) was seen since the last tick, force-close so the
   * `close` handler reconnects; otherwise send a fresh ping and arm the next.
   */
  private startHeartbeat;
  private clearHeartbeat;
}
//#endregion
//#region src/config.d.ts
/**
 * Chat config resolver — reads API key from ~/.alfe/config.toml
 * and derives the chat service URL from the token prefix.
 *
 * Resolution priority: explicit overrides → config file → env vars.
 */
//#endregion
//#region src/stream-mapper.d.ts
/**
 * Claude Code `--output-format stream-json` → Alfe chat-activity mapper.
 *
 * This is the load-bearing core of the bridge. It consumes the newline-delimited
 * JSON events emitted by `claude -p ... --output-format stream-json
 * --include-partial-messages` and translates them into the SAME wire shapes the
 * `@alfe.ai/openclaw-chat` plugin emits, so the chat service / adapter / UI
 * treat a Claude Code turn identically to an OpenClaw turn.
 *
 * Ground truth: a real captured turn (thinking + Read tool + text + result) at
 * `src/__fixtures__/turn-read-tool.stream.jsonl`. The mapper test runs against
 * that fixture (TEST-FIRST).
 *
 * Event model (verified against the fixture + Claude Code stream-json docs):
 *   - `{type:'system', subtype:'init', session_id}` — carries the claude
 *     session id we persist for `--resume`.
 *   - `{type:'stream_event', event:{type:'content_block_delta', delta:{
 *        type:'thinking_delta', thinking}}}` — a thinking chunk.
 *   - `{type:'stream_event', event:{type:'content_block_delta', delta:{
 *        type:'text_delta', text}}}` — a visible-text chunk (accumulate → the
 *        CUMULATIVE snapshot the adapter length-slices).
 *   - `{type:'assistant', message:{content:[{type:'tool_use', id, name,
 *        input}]}}` — a tool CALL. The non-streaming `assistant` message has the
 *        COMPLETE id/name/input (the streaming `content_block_start` has empty
 *        input, filled by `input_json_delta`), so we correlate off THIS.
 *   - `{type:'user', message:{content:[{type:'tool_result', tool_use_id,
 *        content, is_error?}]}}` — a tool RESULT. `tool_use_id === tool_use.id`.
 *   - `{type:'result', is_error, result, duration_ms}` — the turn end.
 *
 * The mapper is a PURE reducer over one event: it takes the running state and an
 * event, mutates the state, and returns the list of `MapperEmission`s to send.
 * It performs NO IO — the host does the sending / persisting. `progressText` /
 * the 250ms mid-tool throttle from openclaw-chat is inert here: Claude Code has
 * no mid-tool progress analog, so we deliberately don't implement it.
 */
interface ThinkingActivity {
  kind: 'thinking';
  text: string;
  delta?: boolean;
  ts?: number;
  seq?: number;
}
interface ToolActivity {
  kind: 'tool';
  toolCallId: string;
  name: string;
  status: 'running' | 'done' | 'failed';
  summary?: string;
  argsText?: string;
  resultText?: string;
  isError?: boolean;
  durationMs?: number;
  truncated?: {
    args?: boolean;
    result?: boolean;
  };
  ts?: number;
  seq?: number;
}
type ActivityEmission = {
  type: 'chat-activity';
  seq: number;
  ts: number;
  activity: ThinkingActivity;
} | {
  type: 'chat-activity';
  seq: number;
  ts: number;
  activity: ToolActivity;
};
/** A cumulative visible-text snapshot → a `chat` delta frame (B2). */
interface TextEmission {
  type: 'chat-delta';
  seq: number;
  ts: number;
  /** CUMULATIVE visible-so-far. Monotonically non-shrinking across the turn. */
  text: string;
}
/** The turn ended. `isError` routes the host to the C3 failure path. */
interface EndEmission {
  type: 'turn-end';
  seq: number;
  ts: number;
  isError: boolean;
  /** Final result text (present on success `result`); '' on error. */
  finalText: string;
  durationMs?: number;
  /** Error reason (present when `isError`). Goes under `payload.message` (C3). */
  errorMessage?: string;
}
type MapperEmission = ActivityEmission | TextEmission | EndEmission;
interface PendingTool {
  name: string;
  argsText?: string;
  argsTruncated?: boolean;
  startTs: number;
}
interface MapperState {
  /** Claude session id from the `init` event (persist for `--resume`). */
  claudeSessionId: string | null;
  /** Monotonic per-turn seq stamped on every emission (E1). */
  seq: number;
  /** CUMULATIVE visible text (B2 — never shrinks). */
  visibleText: string;
  /** tool_use.id → correlation record, joined on the later tool_result. */
  pendingTools: Map<string, PendingTool>;
  /** Whether the terminal `result` event has been seen. */
  ended: boolean;
}
declare function createMapperState(): MapperState;
/**
 * Map ONE stream-json event → zero or more emissions, mutating `state`.
 *
 * `nowMs` lets the host stamp real wall-clock timestamps (Claude Code events
 * don't all carry ms epochs); the fixture test injects a fixed clock.
 */
declare function mapStreamEvent(state: MapperState, raw: unknown, nowMs: number): MapperEmission[];
/**
 * Convenience: run the reducer over a whole array of parsed events (e.g. a
 * fixture). Returns the final state + all emissions in order. The host does NOT
 * use this at runtime (it maps line-by-line as they stream), but it's the
 * cleanest thing to assert against in a fixture test.
 */
declare function mapStreamEvents(events: unknown[], clock?: () => number): {
  state: MapperState;
  emissions: MapperEmission[];
};
/**
 * Terminalize the mapper's in-turn activity into persisted `ChatActivityRecord`
 * form (session store). Tools still pending at flush time (no tool_result seen)
 * are persisted as `interrupted`. Thinking deltas are concatenated into ONE
 * record. This mirrors openclaw-chat's per-turn accumulator flush.
 */
declare function collectTurnActivityRecords(emissions: MapperEmission[]): {
  kind: 'thinking' | 'tool';
  [k: string]: unknown;
}[];
//#endregion
//#region src/session-driver.d.ts
/**
 * `--input-format stream-json` does not keep a headless `claude -p` process
 * resident across turns on the pinned CLI (see header VERIFICATION). Until a
 * CLI ships a resident headless stdin channel, warm-streaming falls back to
 * per-turn spawn. Flip this (and implement a resident path) when that lands.
 */
declare const WARM_STREAMING_SUPPORTED = false;
/**
 * Restricted tool set for unattended bridged turns (Phase 2 tool-permission
 * posture). An inbound chat message could try to induce a destructive shell
 * command, and these turns run unattended on the user's machine. We therefore
 * pass an explicit allow-list of read/analysis/edit tools and DENY Bash by
 * default, and use `--permission-mode dontAsk` (NEVER `bypassPermissions` /
 * `--dangerously-skip-permissions`). See DEVELOPING.md → "Tool-permission
 * posture". Bash is intentionally absent — a bridged turn cannot run arbitrary
 * shell. Callers that want a wider set pass `allowedTools` explicitly.
 */
declare const DEFAULT_ALLOWED_TOOLS: readonly ["Read", "Grep", "Glob", "LS", "Edit", "Write", "WebFetch", "WebSearch", "Task", "TodoWrite"];
declare const CLAUDE_PERMISSION_MODES: readonly ["acceptEdits", "auto", "manual", "dontAsk", "plan"];
type ClaudePermissionMode = (typeof CLAUDE_PERMISSION_MODES)[number];
/**
 * Headless-safe permission posture supported by current Claude CLI releases.
 * Allow-listed tools run; any permission prompt the bridge cannot answer is
 * denied. `bypassPermissions` is deliberately not representable.
 */
declare const DEFAULT_PERMISSION_MODE: ClaudePermissionMode;
/** How a turn ended, surfaced to the host so it can settle / persist. */
interface DriverTurnResult {
  /** The claude session id observed on the `system:init` event (for --resume). */
  claudeSessionId: string | null;
  /** All emissions produced during the turn, in order (for activity persistence). */
  emissions: MapperEmission[];
  /** True if the terminal `result` event carried `is_error`, or the child failed. */
  isError: boolean;
  /** Final visible/result text (cumulative). '' on error. */
  finalText: string;
  /** Error reason when `isError` (goes under `payload.message` — C3). */
  errorMessage?: string;
  /** True if the turn was aborted via `abort()` (SIGINT). */
  aborted: boolean;
}
interface RunTurnParams {
  /** The user prompt for this turn. */
  prompt: string;
  /** Claude session id to `--resume`; null → start a fresh session. */
  claudeSessionId: string | null;
  /** Working directory (the agent workspace). */
  cwd: string;
  /** Path to the generated MCP config JSON. Omitted → no `--mcp-config`. */
  mcpConfigPath?: string;
  /** Persona + reply-style text appended to the system prompt. Omitted → none. */
  appendSystemPrompt?: string;
  /** Bare Claude model id for `--model` (subscription models only). Omitted → CLI default. */
  model?: string;
  /** Tool allow-list (defaults to DEFAULT_ALLOWED_TOOLS). */
  allowedTools?: readonly string[];
  /** Permission mode (defaults to DEFAULT_PERMISSION_MODE — never bypass). */
  permissionMode?: ClaudePermissionMode;
  /** Per-emission callback so the host can stream deltas/activity live. */
  onEmission: (emission: MapperEmission) => void;
  /** Wall-clock override for the mapper (tests). Defaults to Date.now. */
  now?: () => number;
}
/**
 * Hard cap on a single turn (E2). Deliberately BELOW the chat service's RPC
 * timeout (`AGENT_TIMEOUT_SEC=300` → 305s in daemon-server) so the host settles
 * a maxed-out turn *before* the caller rejects it — an equal cap races the
 * caller and can surface a spurious "stuck then error" flash. Inject-origin
 * turns have an even shorter caller timeout (~125s); those may over-run to this
 * cap, but the late settle is harmlessly no-op'd by the chat service.
 */
declare const TURN_TIMEOUT_MS = 300000;
/** Grace after SIGINT before SIGKILL + local settlement. Keeps E2 under 305s. */
declare const TERMINATION_GRACE_MS = 2000;
/**
 * Spawns and drives `claude` subprocesses. Tracks a SINGLE in-flight child, so
 * the host creates ONE driver PER TURN (`ClaudeCodeHost.makeDriver`) — a driver
 * shared across concurrent sessions would let the last spawn overwrite the
 * `child` slot and cross-abort / mis-probe the others.
 */
declare class SessionDriver {
  private child;
  private abortCurrent;
  private readonly bin;
  private readonly baseEnv;
  private readonly log;
  /** Injected spawn — tests replace this with a fake child. */
  private readonly spawnImpl;
  constructor(opts?: {
    claudeBin?: string;
    baseEnv?: NodeJS.ProcessEnv;
    logger?: Logger;
    /** Test seam: inject a fake `spawn`. */
    __spawn?: typeof spawn;
  });
  /** True while a `claude` child is running — backs the host's B4 drain probe. */
  get busy(): boolean;
  /**
   * Abort the in-flight turn by SIGINT-ing the child (B3). No-op if idle. The
   * child's exit drives `runTurn` to settle with `aborted: true`.
   */
  abort(): void;
  /**
   * Run ONE turn. Modes reconcile to the same per-turn spawn (see header
   * VERIFICATION) — `voice` is accepted for API symmetry and future warm mode.
   */
  runTurn(params: RunTurnParams, mode?: 'chat' | 'voice'): Promise<DriverTurnResult>;
  private buildArgs;
  private runPerTurn;
}
//#endregion
//#region src/host.d.ts
interface ClaudeCodeHostConfig {
  /** Chat service WS URL (e.g. wss://chat.dev.alfe.ai/ws). */
  wsUrl: string;
  /** Agent API key (Bearer auth for both chat WS and AgentApiClient). */
  apiKey: string;
  /** Base URL for the Alfe agent API (AgentApiClient). */
  apiUrl: string;
  /** Agent workspace dir (cwd for `claude`, source of persona files). */
  workspace: string;
  /** Path to the generated MCP config JSON (memory/voice/send + integrations). */
  mcpConfigPath?: string;
  /** Path to persist Alfe sessionId → claude session id. */
  claudeSessionsPath?: string;
  /**
   * Bare Claude model id for `claude -p --model` (e.g. `claude-opus-4-8` or the
   * `opus`/`sonnet`/`haiku` aliases). Sourced from the agent's `defaultModel`
   * via `ALFE_DEFAULT_MODEL`. Omitted → the operator's `claude` CLI default.
   * NEVER provider-qualified (`anthropic/…`) — that's an OpenClaw-only shape.
   */
  model?: string;
  logger?: Logger;
}
declare class ClaudeCodeHost {
  private readonly chat;
  /**
   * Factory for a per-turn `SessionDriver`. A driver tracks a single in-flight
   * `child`, so distinct sessions running concurrently (C4) each get their OWN
   * driver — a shared singleton would cross-abort and mis-probe (its one `child`
   * slot would be overwritten by whichever session spawned last).
   */
  private readonly makeDriver;
  private readonly api;
  private readonly log;
  private readonly cfg;
  private readonly queues;
  /** Alfe sessionId → claude session id map (mirrors ~/.alfe/claude-code/sessions.json). */
  private readonly claudeSessionIds;
  private claudeSessionsPath;
  /** RPC sessionKey → currently RUNNING request id (for chat.abort targeting). */
  private readonly runningTurns;
  /** idempotencyKey → settled request id, for E3 duplicate-RPC dedupe. */
  private readonly seenIdempotencyKeys;
  /** RPC sessionKey → resolved SessionDriver so chat.abort can SIGINT the child. */
  private activeDriverBySession;
  private claudeSessionSave;
  private stopping;
  private stopPromise;
  constructor(cfg: ClaudeCodeHostConfig, deps?: {
    /** Per-turn driver factory (test seam). Called once per turn. */
    makeDriver?: () => SessionDriver;
    chat?: ChatServiceClient;
    api?: AgentApiClient;
  });
  /** Start the chat WS. Non-blocking — the client reconnects internally. */
  start(): Promise<void>;
  /** Stop admission, abort owned children, and give active turns time to settle. */
  stop(): Promise<void>;
  /**
   * Inbound RPC dispatch. Invoked by the chat client's `onRequest` in
   * production; also the test seam (drive `agent`/`chat.abort`/… directly).
   */
  handleRequest(req: RpcRequest): Promise<void>;
  private handleAgent;
  private runAgentTurn;
  /**
   * Run a turn; on a `--resume` failure (stale/missing claude session id) start
   * fresh and prepend the last-N stored messages so the model keeps context.
   */
  private runWithResumeFallback;
  private forwardEmission;
  private handleChatAbort;
  private handleSessionsList;
  private handleSessionsGet;
  private buildSystemPrompt;
  private buildHistoryPreamble;
  private ensureSession;
  private loadClaudeSessionIds;
  private saveClaudeSessionIds;
  private rememberClaudeSessionId;
  private pruneIdempotency;
}
/** Strip the `agent:{agentId}:` prefix from a full server session key. */
declare function stripAgentPrefix(sessionKey: string): string;
//#endregion
//#region src/child-env.d.ts
/**
 * Child-process environment construction for spawned `claude` CLI processes.
 *
 * TWO non-negotiable invariants (Phase 2 plan, audit B2 + the hard
 * constraints):
 *
 * 1. **Scrub `ANTHROPIC_API_KEY` / `ANTHROPIC_BASE_URL` /
 *    `ANTHROPIC_AUTH_TOKEN`.** A self-hosted Mac very often has these set (for
 *    other tooling). If ANY of them reaches `claude`, the CLI silently switches
 *    from the user's Claude subscription (OAuth) to API-key/proxy auth — which
 *    is exactly what this whole runtime exists to avoid (no Agent SDK, no
 *    proxy, subscription only). The break is SILENT: the turn "works" but bills
 *    the wrong plane. So we strip them unconditionally from the child env.
 *
 * 2. **Set `ALFE_CLAUDE_BRIDGE=1`.** The Phase-1 CLI hooks
 *    (`alfe claude hook ...` in `packages/cli/src/commands/claude.ts`) check
 *    `process.env.ALFE_CLAUDE_BRIDGE` FIRST and no-op when set, so the host —
 *    not the interactive-session hooks — owns memory recall/capture for bridged
 *    turns. Omitting this double-captures every message. The env var NAME is a
 *    cross-phase contract; do not rename without updating the CLI.
 */
/** Anthropic env vars that force API-key / proxy auth and MUST be scrubbed. */
declare const SCRUBBED_ANTHROPIC_ENV_VARS: readonly ["ANTHROPIC_API_KEY", "ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN"];
/** Cross-phase contract marker (see header + packages/cli/src/commands/claude.ts). */
declare const BRIDGE_ENV_VAR = "ALFE_CLAUDE_BRIDGE";
/**
 * Build the env handed to a spawned `claude` child. Pure — takes the base env
 * explicitly so it unit-tests without touching `process.env`.
 *
 * - Every scrubbed Anthropic var is DELETED (not blanked) so `claude`'s
 *   env-detection treats it as absent.
 * - `ALFE_CLAUDE_BRIDGE=1` is set.
 * - Any caller-supplied `extra` entries are layered last (e.g. a per-turn
 *   marker) but can NEVER re-introduce a scrubbed var — the scrub runs after
 *   the merge as the final gate.
 */
declare function buildChildEnv(base: NodeJS.ProcessEnv, extra?: Record<string, string>): NodeJS.ProcessEnv;
//#endregion
//#region src/session/session-store.d.ts
type StoredMessageComponent = {
  type: 'link_button';
  id: string;
  label: string;
  url: string;
  target?: 'same-tab' | 'new-tab' | 'popup';
  style?: 'primary' | 'secondary' | 'danger';
} | {
  type: 'quick_reply';
  id: string;
  label: string;
  value: string;
  style?: 'primary' | 'secondary' | 'danger';
};
/**
 * Persisted reference to a message attachment. Deliberately stores NO URL —
 * the download URL is short-lived and re-signed on demand. Mirrors
 * openclaw-chat's `StoredAttachment`.
 */
interface StoredAttachment {
  attachmentId: string;
  type: 'image' | 'video' | 'audio' | 'document' | 'file';
  mimeType: string;
  filename: string;
  size?: number;
}
interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
  timestamp: number;
  senderId?: string;
  senderName?: string;
  components?: StoredMessageComponent[];
  attachments?: StoredAttachment[];
}
/**
 * Persisted form of a turn's agent activity (tool cards + thinking), so a
 * refresh can replay what the live `chat-activity` stream showed. Terminal by
 * construction: no `progressText`, no `running` status — a tool still running
 * at flush time persists as `interrupted`.
 */
type ChatActivityRecord = {
  kind: 'thinking';
  text: string;
  ts: number;
} | {
  kind: 'tool';
  toolCallId: string;
  name: string;
  status: 'done' | 'failed' | 'interrupted';
  summary?: string;
  argsText?: string;
  resultText?: string;
  isError?: boolean;
  durationMs?: number;
  truncated?: {
    args?: boolean;
    progress?: boolean;
    result?: boolean;
  };
  ts: number;
};
interface SessionData {
  sessionId: string;
  agentId: string;
  channel: string;
  tenantId?: string;
  userId?: string;
  createdAt: string;
  updatedAt: string;
  messages: ChatMessage[];
  /**
   * Activity records replayed on `sessions.get`. Unlike openclaw-chat (whose
   * PRIMARY source is OpenClaw's transcript), these records are the SOLE
   * history source here — there is no external transcript. Absent on
   * pre-persistence files.
   */
  activity?: ChatActivityRecord[];
}
interface SessionSummary {
  sessionId: string;
  agentId: string;
  channel: string;
  tenantId?: string;
  userId?: string;
  createdAt: string;
  lastMessageAt?: string;
  preview?: string;
  messageCount: number;
}
declare function getSession(sessionId: string): Promise<SessionData | null>;
declare function saveSession(session: SessionData): Promise<void>;
declare function createSession(sessionId: string, agentId: string, channel: string, tenantId?: string, userId?: string): Promise<SessionData>;
declare function addMessage(sessionId: string, role: 'user' | 'assistant', content: string, senderId?: string, senderName?: string, components?: StoredMessageComponent[], attachments?: StoredAttachment[]): Promise<void>;
/**
 * Append a turn's terminalized activity records. Called ONCE per turn (from the
 * dispatch `finally`) — never per-delta.
 */
declare function appendActivity(sessionId: string, entries: ChatActivityRecord[]): Promise<void>;
declare function listSessions(filters?: {
  agentId?: string;
  channel?: string;
  tenantId?: string;
  userId?: string;
}, limit?: number): Promise<SessionSummary[]>;
//#endregion
//#region src/host-config.d.ts
/**
 * Build the host config. Throws (→ non-zero exit from the CLI) when the chat
 * URL / api key can't resolve.
 */
declare function resolveHostConfig(): ClaudeCodeHostConfig;
//#endregion
export { type ActivityEmission, BRIDGE_ENV_VAR, CLAUDE_PERMISSION_MODES, type ChatActivityRecord, type ChatMessage, ClaudeCodeHost, type ClaudeCodeHostConfig, type ClaudePermissionMode, DEFAULT_ALLOWED_TOOLS, DEFAULT_PERMISSION_MODE, type DriverTurnResult, type EndEmission, type MapperEmission, type MapperState, type RunTurnParams, SCRUBBED_ANTHROPIC_ENV_VARS, type SessionData, SessionDriver, type SessionSummary, TERMINATION_GRACE_MS, TURN_TIMEOUT_MS, type TextEmission, type ThinkingActivity, type ToolActivity, WARM_STREAMING_SUPPORTED, addMessage, appendActivity, buildChildEnv, collectTurnActivityRecords, createMapperState, createSession, getSession, listSessions, mapStreamEvent, mapStreamEvents, resolveHostConfig, saveSession, stripAgentPrefix };