AkurAI Build
Menu

popagent

public

Latest change dc4b371554df3a78c40c29085ead1db3de7e24f8 - Add model routing policy, companyStatus tool, Markdown channel output, compact Runtime settings by AkurAI Build

export const MAX_AGENT_INSTRUCTIONS_CHARACTERS = 32_000;
export const DEFAULT_WORKSPACE_ID = "default";
export const AGENT_IDS = [
  "orchistrator",
  "researcher",
  "implementer",
  "reviewer",
  "build-maintainer",
  "build-release-manager",
  "community-steward",
] as const;
export type AgentId = (typeof AGENT_IDS)[number];

export type ChatMessage = {
  id: string;
  role: string;
  parts: unknown[];
  metadata?: Record<string, unknown>;
  [key: string]: unknown;
};
export type AgentToolActivity = {
  id: string;
  name: string;
  args: Record<string, unknown>;
  result?: unknown;
  error?: string;
  status: "running" | "complete" | "error";
};
export type AgentActivity = {
  turnId: string;
  runId: string;
  agentId: string;
  agentName: string;
  iteration: number;
  maxIterations: number | null;
  isFinal: boolean;
  finishReason: string;
  text: string;
  tools: string[];
  toolCalls?: AgentToolActivity[];
};

export type AgentWorkspace = {
  id: string;
  name: string;
  repositoryPath: string;
  createdAt: string;
  updatedAt: string;
};

export type DocumentationFolder = {
  path: string;
  name: string;
  updatedAt: string;
};

export type DocumentationPageSummary = {
  path: string;
  title: string;
  revision: string;
  size: number;
  updatedAt: string;
};
export type DocumentationPage = DocumentationPageSummary & { content: string };
export type DocumentationSearchResult = {
  workspaceId: string;
  workspaceName: string;
  path: string;
  title: string;
  heading?: string;
  excerpt: string;
  score: number;
};
export type DocumentationIndexStatus = {
  workspaceId: string;
  files: number;
  chunks: number;
  indexedAt: string | null;
  model: string;
  dimension: number;
  running: boolean;
};
export type DocumentationListResponse = {
  folders: DocumentationFolder[];
  pages: DocumentationPageSummary[];
};
export type DocumentationSearchResponse = { results: DocumentationSearchResult[] };

export type SessionSummary = {
  id: string;
  title: string;
  model: string;
  workspaceId: string;
  revision: number;
  archivedAt: string | null;
  createdAt: string;
  updatedAt: string;
};

export type Session<Message = ChatMessage> = SessionSummary & { messages: Message[] };
export const AGENT_TOOL_NAMES = [
  "getTime",
  "retainMemory",
  "recallMemory",
  "reflectMemory",
  "editMemory",
  "useBrowserSecret",
  "bifrostNavigator",
  "webSearch",
  "searchDocumentation",
  "companyStatus",
  "repoBrief",
  "codeContext",
  "symbolContext",
  "changeImpact",
  "akuraiRepoList",
  "akuraiRepoAdd",
  "akuraiRepoHost",
  "akuraiRepoSync",
  "akuraiRelease",
  "akuraiRepoRename",
  "akuraiRepoRemove",
  "akuraiRepoVisibility",
  "akuraiRepoBranches",
  "akuraiRepoTree",
  "akuraiRepoBlob",
  "akuraiRunQueue",
  "akuraiRuns",
  "akuraiRunShow",
  "akuraiRunCancel",
  "akuraiRunWait",
  "akuraiRunLogs",
  "akuraiRunRetry",
  "akuraiRunPromote",
  "akuraiDeliveryMetrics",
  "akuraiWorkers",
  "akuraiPipelineValidate",
  "akuraiIssueList",
  "akuraiIssueCreate",
  "akuraiIssueUpdate",
  "akuraiIssueComment",
  "akuraiCacheStats",
  "akuraiCachePrune",
  "akuraiWorkerDrain",
  "akuraiAuditEvents",
] as const;
export type AgentToolName = (typeof AGENT_TOOL_NAMES)[number];
export type AgentWorkspaceAccess = "read-write" | "read-only" | "none";
export type AgentBrowserAccess = "interactive" | "read-only" | "none";
export const BUILD_AGENT_IDS = ["build-maintainer", "build-release-manager", "community-steward"] as const;
export type BuildAgentId = (typeof BUILD_AGENT_IDS)[number];
export const BUILD_AGENT_TOOL_ALLOWLISTS = {
  "build-maintainer": [
    "akuraiRepoList", "akuraiRepoAdd", "akuraiRepoHost", "akuraiRepoSync", "akuraiRepoRename",
    "akuraiRepoRemove", "akuraiRepoVisibility", "akuraiRepoBranches", "akuraiRepoTree", "akuraiRepoBlob",
    "akuraiRunQueue", "akuraiRuns", "akuraiRunShow", "akuraiRunCancel", "akuraiRunWait", "akuraiRunLogs",
    "akuraiRunRetry", "akuraiDeliveryMetrics", "akuraiWorkers", "akuraiPipelineValidate",
    "akuraiIssueList", "akuraiIssueCreate", "akuraiIssueUpdate", "akuraiIssueComment",
    "akuraiCacheStats", "akuraiCachePrune", "akuraiWorkerDrain", "akuraiAuditEvents",
  ],
  "build-release-manager": [
    "akuraiRepoList", "akuraiRepoBranches", "akuraiRepoTree", "akuraiRepoBlob",
    "akuraiRuns", "akuraiRunShow", "akuraiRunWait", "akuraiRunLogs", "akuraiDeliveryMetrics",
    "akuraiRelease", "akuraiRunPromote",
  ],
  "community-steward": [
    "akuraiRepoList", "akuraiRepoBranches", "akuraiRepoTree", "akuraiRepoBlob",
    "akuraiIssueList", "akuraiIssueCreate", "akuraiIssueUpdate", "akuraiIssueComment",
  ],
} as const satisfies Record<BuildAgentId, readonly AgentToolName[]>;

export type AgentSettings = {
  id: string;
  name: string;
  description: string;
  instructions: string;
  model: string | null;
  workspaceAccess: AgentWorkspaceAccess;
  browserAccess: AgentBrowserAccess;
  delegationEnabled: boolean;
  tools: AgentToolName[];
  sourceUrls: string[];
  createdAt: string;
  updatedAt: string;
};

export type CompanyMember = {
  id: string;
  name: string;
  title: string;
  email: string;
  avatarUrl: string;
};

export type CompanyDepartment = {
  id: string;
  name: string;
  members: CompanyMember[];
};

export type AgentSettingsInput = Pick<
  AgentSettings,
  | "name"
  | "description"
  | "instructions"
  | "model"
  | "workspaceAccess"
  | "browserAccess"
  | "delegationEnabled"
  | "tools"
>;

export type AgentSecret = {
  name: string;
  allowedOrigin: string | null;
  createdAt: string;
  updatedAt: string;
};

export type AgentSecretInput = {
  name: string;
  value: string;
  allowedOrigin: string;
};

export type AgentSecretUpdateInput = {
  value?: string;
  allowedOrigin?: string;
};

export type AgentSecretListResponse = { secrets: AgentSecret[] };

export type AgentSkill = {
  id: string;
  agentId: string;
  name: string;
  description: string;
  instructions: string;
  references: Record<string, string>;
  sourceUrls: string[];
  enabled: boolean;
  userInvocable: boolean;
  evolutionManaged: boolean;
  createdAt: string;
  updatedAt: string;
};

export type AgentSkillInput = Pick<
  AgentSkill,
  "name" | "description" | "instructions" | "references" | "enabled" | "userInvocable"
>;

export type ChannelDispatchMode = "every-message" | "mentions";
export type ChannelToolDisplay = "compact" | "timeline";

export type ChannelSettings = {
  enabled: boolean;
  channelName: string;
  dispatchMode: ChannelDispatchMode;
  contextMessages: number;
  streaming: boolean;
  toolDisplay: ChannelToolDisplay;
  updatedAt: string;
};

export type ChannelSettingsInput = Omit<ChannelSettings, "updatedAt">;

export type Channel = {
  id: string;
  name: string;
  createdAt: string;
  updatedAt: string;
};

export type ChannelAgentCommunication = {
  taskId: string;
  fromAgentId: string;
  toAgentId: string;
  toAgentName: string;
  replyToMessageId: string | null;
};


export type ChannelMessage = {
  id: string;
  channelId: string;
  workspaceId: string;
  authorId: string;
  authorName: string;
  content: string;
  taskId: string | null;
  task: AgentTask | null;
  agentCommunication: ChannelAgentCommunication | null;
  createdAt: string;
};

export type ChannelEvent = {
  id: string;
  channelId: string;
  type: "message" | "task" | "settings";
  messageId: string | null;
  taskId: string | null;
  taskStatus: AgentTaskStatus | null;
  createdAt: string;
};

export type ChannelPostResponse = { message: ChannelMessage; task: AgentTask | null };

export type BrowserScope = "thread" | "shared";

export type BrowserProvider = "agent-browser" | "bifrost-navigator";

export type BrowserSettings = {
  enabled: boolean;
  provider: BrowserProvider;
  scope: BrowserScope;
  viewportWidth: number;
  viewportHeight: number;
  timeoutMs: number;
  maxSessions: number;
  idleTimeoutMs: number;
  screencastEnabled: boolean;
  screenshotsEnabled: boolean;
  multiTabEnabled: boolean;
  formsEnabled: boolean;
  dialogsEnabled: boolean;
  dragEnabled: boolean;
  evaluateEnabled: boolean;
  recordingEnabled: boolean;
  recordingRetentionDays: number;
  recordingMaxFiles: number;
  allowHosts: string[];
  denyHosts: string[];
  updatedAt: string;
};

export type BrowserSettingsInput = Omit<BrowserSettings, "updatedAt">;

export type BrowserProviderHealth = {
  id: BrowserProvider;
  label: string;
  healthy: boolean;
  headless: boolean;
  detail: string;
};

export type BrowserHealth = {
  provider: string;
  healthy: boolean;
  headless: boolean;
  selected: BrowserProvider;
  providers: BrowserProviderHealth[];
  enabled: boolean;
  scope: BrowserScope;
  activeSessions: number;
  profileConfigured: boolean;
  screencastEnabled: boolean;
  recordingEnabled: boolean;
};

export type BrowserProfile = {
  id: string;
  name: string;
  enabled: boolean;
  createdAt: string;
  updatedAt: string;
};

export type BrowserSession = {
  id: string;
  threadId: string;
  access: "interactive" | "read-only";
  status: "active" | "closed" | "error";
  currentUrl: string | null;
  tabs: Array<{ id: string; url: string; title: string }>;
  activeTabIndex: number;
  createdAt: string;
  lastActivityAt: string;
};

export type MemoryActivationMode = "off" | "auto" | "5m" | "1hr" | "24hr";
export type MemoryAttachmentPolicy = "auto" | "all" | "none";

export type MemorySettings = {
  autoCompact: boolean;
  observationTokens: number;
  reflectionTokens: number;
  recentMessagePercent: number;
  asyncBuffering: boolean;
  bufferIntervalPercent: number;
  bufferOnIdle: boolean;
  observationBlockPercent: number;
  reflectionBufferPercent: number;
  reflectionBlockPercent: number;
  optimizeObserverContext: boolean;
  previousObserverTokens: number;
  retrievalEnabled: boolean;
  retrievalScope: "thread" | "resource";
  temporalMarkers: boolean;
  activateAfterIdle: MemoryActivationMode;
  activateOnProviderChange: boolean;
  shareTokenBudget: boolean;
  observeAttachments: MemoryAttachmentPolicy;
  observationInstruction: string;
  reflectionInstruction: string;
  internalRecall: boolean;
  internalRetention: boolean;
  updatedAt: string;
};

export type MemorySettingsInput = Omit<MemorySettings, "updatedAt">;

export const MODEL_SOURCES = ["configured", "local", "openrouter-free"] as const;
export type ModelSource = typeof MODEL_SOURCES[number];
export const LOCAL_MODEL_ROUTE = "titan/ornith-1.0-9b-mtp-q4_k_m";
export const FREE_MODEL_ROUTE = "free-scout";

export function runtimeModelId(configuredModel: string, source: ModelSource): string {
  if (source === "local") return LOCAL_MODEL_ROUTE;
  if (source === "openrouter-free") return FREE_MODEL_ROUTE;
  return configuredModel;
}

/** Pseudo model id that resolves through the configured model routing policy. */
export const ROUTING_MODEL_ID = "policy/routing";
export const MODEL_ROUTING_STRATEGIES = ["fallback", "round-robin"] as const;
export type ModelRoutingStrategy = typeof MODEL_ROUTING_STRATEGIES[number];
export const REASONING_EFFORTS = ["default", "low", "medium", "high"] as const;
export type ReasoningEffort = typeof REASONING_EFFORTS[number];
export type ModelRoute = { model: string; reasoningEffort: ReasoningEffort };
export type ModelRouting = {
  enabled: boolean;
  strategy: ModelRoutingStrategy;
  /** How long a route stays out of rotation after a rate-limit or unknown-model failure. */
  cooldownMs: number;
  routes: ModelRoute[];
};
export const DEFAULT_MODEL_ROUTING: ModelRouting = { enabled: false, strategy: "fallback", cooldownMs: 900_000, routes: [] };

/** `model@effort` spec used on the wire; `resolveModel` strips the suffix and sends `reasoning_effort`. */
export function modelSpec(route: ModelRoute): string {
  return route.reasoningEffort === "default" ? route.model : `${route.model}@${route.reasoningEffort}`;
}
export function parseModelSpec(spec: string): ModelRoute {
  const match = /^(.*)@(low|medium|high)$/.exec(spec);
  return match ? { model: match[1]!, reasoningEffort: match[2] as ReasoningEffort } : { model: spec, reasoningEffort: "default" };
}

export type AgentRuntimeSettings = {
  defaultModel: string;
  modelSource: ModelSource;
  modelRouting: ModelRouting;
  supervisorMaxSteps: number;
  specialistMaxSteps: number;
  toolConcurrency: number;
  delegationContextMessages: number;
  delegationResultCharacters: number;
  maxProcessorRetries: number;
  finalResponseFeedback: string;
  delegationFailureFeedback: string;
  delegationResultTruncationMarker: string;
  taskConcurrency: number;
  taskPollIntervalMs: number;
  taskTimeoutMs: number;
  taskStaleAfterMs: number;
  updatedAt: string;
};

export type AgentRuntimeSettingsInput = Omit<AgentRuntimeSettings, "updatedAt">;

export type AutonomySettings = {
  enabled: boolean;
  reflectionIntervalMs: number;
  batchSize: number;
  maxAttempts: number;
  autoApplyStrategies: boolean;
  autoCreateSkills: boolean;
  autoRetainFacts: boolean;
  selfUpdateEnabled: boolean;
  selfUpdateCron: string;
  idleImprovementEnabled: boolean;
  idleDeploymentEnabled: boolean;
  idleWorkspaceIds: string[];
  updatedAt: string;
};

export type AutonomySettingsInput = Omit<AutonomySettings, "updatedAt">;

export type AutomationStatus = {
  state: "active" | "improving" | "paused";
  activeTask: AgentTask | null;
  selectedWorkspaceIds: string[];
};

export type EvolutionSignal = {
  id: string;
  sessionId: string | null;
  turnId: string | null;
  traceId: string | null;
  agentId: string;
  workspaceId: string | null;
  kind: "turn-success" | "turn-failure";
  summary: string;
  status: "pending" | "processing" | "applied" | "ignored" | "dead-letter";
  attempts: number;
  nextAttemptAt: string | null;
  processedAt: string | null;
  error: string | null;
  createdAt: string;
  updatedAt: string;
};

export type EvolutionRevision = {
  id: string;
  agentId: string;
  targetType: "overlay" | "skill" | "fact";
  targetKey: string;
  beforeContent: string | null;
  afterContent: string | null;
  rationale: string;
  evidenceIds: string[];
  status: "applied" | "reverted";
  revertsRevisionId: string | null;
  createdAt: string;
  appliedAt: string;
};

export type EvolutionSignalListResponse = { signals: EvolutionSignal[] };
export type EvolutionRevisionListResponse = { revisions: EvolutionRevision[] };

export type MemoryRecord = {
  id: string;
  resourceId: string;
  sessionId: string;
  kind: "fact" | "episode";
  key: string | null;
  content: string;
  importance: number;
  accessCount: number;
  createdAt: string;
  updatedAt: string;
  lastAccessedAt: string;
};

export type MemoryStatus = {
  facts: number;
  episodes: number;
  recalled: number;
  latestUpdatedAt: string | null;
};

export type AgentTaskSource = "user" | "self-update" | "build-maintenance";
export type AgentExecutionSource = "chat" | "task" | "schedule" | "self-update" | "build-maintenance";

export const AUTONOMY_WORKFLOW_PHASES = [
  "prepare",
  "research",
  "decide",
  "implement",
  "inspect-change",
  "verify",
  "review",
  "commit",
] as const;
export type AgentWorkflowPhaseId = typeof AUTONOMY_WORKFLOW_PHASES[number];
export type AgentWorkflowPhaseState = "waiting" | "active" | "complete" | "failed" | "cancelled" | "skipped";
export type AgentWorkflowState = "running" | "completed" | "failed" | "cancelled";
export type AgentWorkflowPhaseSummary = {
  id: AgentWorkflowPhaseId;
  label: string;
  state: AgentWorkflowPhaseState;
  evidence: string[];
};
export type AgentWorkflowSummary = {
  runId: string;
  correlationId: string;
  state: AgentWorkflowState;
  currentPhase: AgentWorkflowPhaseId | null;
  phases: AgentWorkflowPhaseSummary[];
};
export type AgentWorkflowPhaseDetail = AgentWorkflowPhaseSummary & {
  startedAt: string | null;
  completedAt: string | null;
  error: string | null;
};
export type AgentWorkflowDetail = Omit<AgentWorkflowSummary, "phases"> & {
  phases: AgentWorkflowPhaseDetail[];
};



export type AgentTaskErrorClass =
  | "timeout"
  | "provider"
  | "rate-limit"
  | "browser"
  | "database"
  | "infrastructure"
  | "cancelled"
  | "hook-denial"
  | "validation"
  | "permission"
  | "configuration"
  | "unknown"
  | "workflow"
  | "research"
  | "decision"
  | "implementation"
  | "inspection"
  | "verification"
  | "review"
  | "commit";

export type AgentTaskStatus = "queued" | "running" | "cancelling" | "completed" | "failed" | "cancelled" | "dead-letter";

export type AgentTask = {
  id: string;
  sessionId: string | null;
  scheduleId: string | null;
  source: AgentTaskSource;
  remediationForTaskId?: string | null;
  workspaceId: string;
  prompt: string;
  model: string;
  status: AgentTaskStatus;
  output: string | null;
  error: string | null;
  stepsCompleted: number;
  progress: string | null;
  activity?: AgentActivity[];
  workflow?: AgentWorkflowSummary;
  recoveryCount: number;
  attemptCount: number;
  maxAttempts: number;
  nextAttemptAt: string | null;
  lastErrorClass: AgentTaskErrorClass | null;
  deadLetteredAt: string | null;
  heartbeatAt?: string | null;
  createdAt: string;
  startedAt: string | null;
  completedAt: string | null;
};
export type AgentTaskProgress = Pick<AgentTask, "stepsCompleted" | "progress">
  & { activity?: AgentActivity; workflow?: AgentWorkflowDetail };

export type AgentSchedule = {
  id: string;
  sessionId: string | null;
  workspaceId: string;
  source: AgentTaskSource;
  name: string;
  prompt: string;
  model: string;
  maxAttempts: number;
  cron: string;
  timezone: string;
  enabled: boolean;
  nextRunAt: string | null;
  lastRunAt: string | null;
  latestTaskStatus?: AgentTaskStatus | null;
  latestHeartbeatAt?: string | null;
  createdAt: string;
  updatedAt: string;
};

export type HookRunStatus =
  | "passed"
  | "modified"
  | "denied"
  | "continued"
  | "failed-open"
  | "failed-closed";

export type HookAuditRun = {
  id: string;
  eventId: string;
  sessionId: string;
  turnId: string | null;
  toolCallId: string | null;
  eventName: string;
  handlerId: string;
  startedAt: string;
  completedAt: string;
  durationMs: number;
  status: HookRunStatus;
  reason: string | null;
  error: string | null;
};

export type ModelProfile = {
  label: string;
  role: "orchestrator" | "fast" | "local";
  summary: string;
  members: string[];
};

export type ModelCatalog = {
  models: string[];
  contextWindows: Record<string, number>;
  profiles: Record<string, ModelProfile>;
};

export type ModelCatalogResponse = ModelCatalog & { defaultModel: string };

export type ChannelListResponse = { channels: Channel[] };
export type ChannelMessageListResponse = { messages: ChannelMessage[]; nextCursor?: string | null };
export type WorkspaceListResponse = { workspaces: AgentWorkspace[] };
export type WorkspaceChatDeleteResponse = { deleted: number };
export type CompanyRosterResponse = { departments: CompanyDepartment[] };
export type AgentListResponse = { agents: AgentSettings[] };
export type AgentSkillListResponse = { skills: AgentSkill[] };
export type MemoryListResponse = { memories: MemoryRecord[] };
export type TaskListResponse = { tasks: AgentTask[] };
export type ScheduleListResponse = { schedules: AgentSchedule[] };
export type SessionListResponse = { sessions: SessionSummary[] };
export type HookRunListResponse = { runs: HookAuditRun[] };

export type ObservabilityTraceSummary = {
  traceId: string;
  name: string;
  entityName: string | null;
  status: "success" | "error" | "running";
  startedAt: string;
  endedAt: string | null;
  durationMs: number | null;
  tags: string[];
  metadata: Record<string, unknown>;
};

export type ObservabilityTraceSpan = ObservabilityTraceSummary & {
  spanId: string;
  parentSpanId: string | null;
  spanType: string;
  input: unknown;
  output: unknown;
  error: unknown;
};

export type ObservabilityOverviewResponse = {
  from: string;
  to: string;
  runs: number;
  errors: number;
  errorRate: number;
  p95LatencyMs: number | null;
  inputTokens: number;
  outputTokens: number;
  processRssBytes: number;
  processHeapUsedBytes: number;
};

export type ObservabilityTraceListResponse = {
  traces: ObservabilityTraceSummary[];
  page: number;
  perPage: number;
  total: number;
  hasMore: boolean;
};

export type ObservabilityTraceResponse = { traceId: string; spans: ObservabilityTraceSpan[] };

export type ObservabilityLog = {
  id: string | null;
  timestamp: string;
  level: "debug" | "info" | "warn" | "error" | "fatal";
  message: string;
  traceId: string | null;
  spanId: string | null;
  entityName: string | null;
  data: Record<string, unknown>;
};

export type ObservabilityLogListResponse = {
  logs: ObservabilityLog[];
  page: number;
  perPage: number;
  total: number;
  hasMore: boolean;
};

export type ObservabilityHealthResponse = {
  status: "ok" | "error";
  checkedAt: string;
  error?: string;
};