Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

17.3 KB
Raw Blame
// "While you were away" (batch 3): what agents need from you, finished and failed since you last
// looked. Pure helpers, so the page and the node tests share them; the API calls are at the bottom.

export type AwayKind = 'question' | 'approval' | 'delegation' | 'routine_run' | 'watch' | 'stopped' | 'connection';
export type AwaySection = 'waiting' | 'finished' | 'failed';
export type ApprovalDecision = 'allow_once' | 'always_allow' | 'deny';

export interface AwayLink {
  thread_id: string | null;
  channel_id: string | null;
  direct_kwant_id: string | null;
  /** 22i (Lin, #700): set only when the item's thread belongs to another bot; open the thread under it. */
  thread_kwant_id?: string | null;
}

export interface AwayItem {
  kind: AwayKind;
  id: string;
  kwant_id: string;
  kwant_name: string;
  title: string;
  summary: string;
  status: string;
  timestamp: string;
  link: AwayLink;
  /** Questions only. */
  choices?: string[];
  /** Approvals only, from servers that send them: the tool and the card's details. */
  tool_name?: string;
  details?: Record<string, unknown>;
  /** Approvals only: set when the payment floor asked, also on servers that send no details. */
  payment_reason?: string;
  /**
   * 0.9.5 part B, approvals only: the card's own question built from what the call names, e.g.
   * `Approve “Spring sale: 15% off”?`. Absent when the call names nothing; `title` is always sent.
   */
  question?: string;
  /** 0.9.0 P1, watch items only: the watched mission and the first task that needs the person. */
  mission_id?: string | null;
  task_id?: string | null;
  /** 0.9.5, stopped items only: the chat notice that carries Retry or Continue, what resumes the work
   * (null: Retry in the chat resends the person's message), and the browser step it waits on. */
  message_id?: string | null;
  retry?: { type: 'continue' } | { type: 'approval'; approval_id: string } | null;
  human_step_id?: string | null;
  /** 0.9.5, connection items only (Inbox): a sign-in only the person can redo, and its fix button. */
  connection?: string;
  /** "sign_in" or "reconnect" (an app to connect again); older servers may leave it out. */
  cause?: string;
  fix?: { label: string; opens?: string } | null;
  /** 22i (Lin's server part): what resolves the item. Older servers leave it out; `askAction` infers it. */
  action?: 'retry' | 'continue' | 'ask_again' | 'answer' | 'decide' | 'browser' | null;
  /** 22i (Lin, #700): whether "Done, clear it" may close it. Older servers leave it out (the strip infers). */
  dismissable?: boolean;
}

/**
 * 31y: an approval answered on its chat card (or found lapsed) leaves the "Needs you" strip and its sidebar row in
 * the same update that drops the card, as an ask cleared from the strip does (22i). Its waiting item carries the
 * ticket's own id (server away.rs `item`), so that id is what clears; it leaves the set once the server's list
 * no longer has it. Any other ask in that chat stays.
 */
export const clearAnswered = (cleared: ReadonlySet<string>, ticketId: string): ReadonlySet<string> =>
  cleared.has(ticketId) ? cleared : new Set(cleared).add(ticketId);

export interface AwayCounts {
  waiting: number;
  finished: number;
  failed: number;
  total: number;
}

export interface AwayResponse {
  since: string;
  last_seen: string | null;
  now: string;
  stuck_after_minutes: number;
  waiting: AwayItem[];
  finished: AwayItem[];
  failed: AwayItem[];
  unseen: AwayCounts;
}

export const AWAY_SECTIONS: { key: AwaySection; label: string; empty: string }[] = [
  { key: 'waiting', label: 'Waiting on you', empty: 'No questions or approvals waiting.' },
  { key: 'failed', label: 'Failed or stuck', empty: 'Nothing failed or stuck.' },
  { key: 'finished', label: 'Finished', empty: 'Nothing finished since you last looked.' },
];

/** H5: how each section is sorted, said after its count on desktop. */
export const AWAY_SORT_HINT: Record<AwaySection, string> = {
  waiting: 'oldest first',
  failed: 'oldest first',
  finished: 'not read first, then newest',
};

/**
 * H5 order inside a section: waiting and failed oldest first (the longest wait on top); finished
 * not read (newer than `lastSeen`) first, then newest first.
 */
export function sortAwaySection(key: AwaySection, items: AwayItem[], lastSeen?: string | null): AwayItem[] {
  const t = (i: AwayItem) => Date.parse(i.timestamp) || 0;
  if (key !== 'finished') return [...items].sort((a, b) => t(a) - t(b));
  const seen = lastSeen ? Date.parse(lastSeen) || 0 : 0;
  const unread = (i: AwayItem) => (t(i) > seen ? 0 : 1);
  return [...items].sort((a, b) => unread(a) - unread(b) || t(b) - t(a));
}

/** "just now", "5 min ago", "3 h ago", "yesterday", "4 days ago", else the date. */
export function relativeTime(ts: string, now: number = Date.now()): string {
  const t = Date.parse(ts);
  if (Number.isNaN(t)) return '';
  const s = Math.max(0, Math.round((now - t) / 1000));
  if (s < 60) return 'just now';
  const m = Math.floor(s / 60);
  if (m < 60) return `${m} min ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h} h ago`;
  const d = Math.floor(h / 24);
  if (d === 1) return 'yesterday';
  if (d < 7) return `${d} days ago`;
  return new Date(t).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}

/** Page subtitle: the 7-day default window, or since the last visit. */
export function windowLabel(since: string, now: number = Date.now()): string {
  const t = Date.parse(since);
  if (Number.isNaN(t)) return '';
  if (now - t >= 7 * 86400_000 - 60_000) return 'From the last 7 days';
  return `Since you last looked, ${relativeTime(since, now)}`;
}

export type Tone = 'amber' | 'emerald' | 'rose' | 'sky' | 'zinc';

/** Short label and colour for an item's kind and status. */
export function itemLabel(item: Pick<AwayItem, 'kind' | 'status' | 'cause'>): { label: string; tone: Tone } {
  switch (item.kind) {
    case 'question':
      return { label: 'Question', tone: 'amber' };
    case 'approval':
      // Its turn stopped waiting, but the card is open and a late Allow resumes the work.
      return item.status === 'waiting' ? { label: 'Still open', tone: 'sky' } : { label: 'Needs approval', tone: 'amber' };
    case 'watch':
      return { label: 'Watch', tone: 'amber' };
    case 'stopped':
      // 0.9.5: a bot's work stopped and waits for the person; the title says why and what resumes it.
      return { label: 'Stopped', tone: 'amber' };
    case 'connection':
      // The chat line's cause: an app to connect again (Composio, no active account), else a sign-in.
      return item.cause === 'reconnect' ? { label: 'Connect again', tone: 'amber' } : { label: 'Sign in again', tone: 'amber' };
    case 'routine_run':
      return item.status === 'ok' ? { label: 'Routine ran', tone: 'emerald' } : { label: 'Routine failed', tone: 'rose' };
    case 'delegation':
      switch (item.status) {
        case 'completed':
          return { label: 'Handoff done', tone: 'emerald' };
        case 'stuck':
          return { label: 'Stuck', tone: 'amber' };
        case 'interrupted':
          return { label: 'Interrupted', tone: 'rose' };
        default:
          return { label: 'Handoff failed', tone: 'rose' };
      }
  }
  return { label: item.status, tone: 'zinc' };
}

/** A provider's own limit message ("You've hit your session limit · resets 3am"): never a result. The server
 * keeps these out of replies and summaries; this is the second guard on the card. */
const LIMIT_LINE = /\b(?:hit|reached|exceeded)\s+your\b[^.\n]{0,24}\blimit\b|\b(?:session|weekly|usage|opus)\s+limit\b|\blimit\b[^.\n]{0,12}\bresets?\b/i;
export const isLimitLine = (text: string | null | undefined): boolean => !!text && LIMIT_LINE.test(text);

/** The summary line a card shows: empty for a limit message, so the card shows its title alone. */
export const awaySummary = (item: Pick<AwayItem, 'summary' | 'title'>): string => (isLimitLine(item.summary) ? '' : item.summary);

/** Sidebar badge text: nothing at 0, "99+" past 99. */
export const badgeText = (n: number): string => (n <= 0 ? '' : n > 99 ? '99+' : String(n));

export const isAwayEmpty = (r: Pick<AwayResponse, AwaySection> | null): boolean =>
  !!r && r.waiting.length === 0 && r.finished.length === 0 && r.failed.length === 0;

/** Where clicking an item goes: exactly one of thread, channel or direct chat. */
export type AwayTarget = { thread: string; kwant: string } | { channel: string } | { direct: string };

export function awayTarget(item: Pick<AwayItem, 'kwant_id' | 'link'>): AwayTarget {
  const l = item.link;
  if (l.thread_id) return { thread: l.thread_id, kwant: l.thread_kwant_id || item.kwant_id };
  if (l.channel_id) return { channel: l.channel_id };
  return { direct: l.direct_kwant_id || item.kwant_id };
}

/**
 * 0.9.0 P1: a watch item comes as {at, mission_id, task_id, thread_id} with no `timestamp` or `link`
 * (p1-contract section 8). Give it the shape every card reads; other items pass through untouched.
 */
export function normalizeAwayItem(raw: AwayItem): AwayItem {
  if (raw.kind !== 'watch') return raw;
  const r = raw as AwayItem & { at?: unknown; thread_id?: unknown };
  const str = (v: unknown) => (typeof v === 'string' && v ? v : null);
  return {
    ...r,
    timestamp: str(r.timestamp) ?? str(r.at) ?? '',
    link: r.link ?? { thread_id: str(r.thread_id), channel_id: null, direct_kwant_id: str(r.kwant_id) },
    mission_id: str(r.mission_id),
    task_id: str(r.task_id),
  };
}

export function normalizeAway(r: AwayResponse): AwayResponse {
  const fix = (l: AwayItem[] | undefined) => (Array.isArray(l) ? l.map(normalizeAwayItem) : []);
  return { ...r, waiting: fix(r.waiting), finished: fix(r.finished), failed: fix(r.failed) };
}

/** Drops an acted-on item right away, before the refresh confirms it. */
export function withoutItem(r: AwayResponse, section: AwaySection, id: string): AwayResponse {
  const list = r[section].filter((i) => i.id !== id);
  if (list.length === r[section].length) return r;
  const dropped = section === 'waiting' ? 1 : 0;
  return {
    ...r,
    [section]: list,
    unseen: { ...r.unseen, waiting: Math.max(0, r.unseen.waiting - dropped), total: Math.max(0, r.unseen.total - dropped) },
  };
}

/** The message for a failed one-tap action; a 409 means the request lapsed meanwhile. */
export const actionErrorText = (status: number, fallback: string): string =>
  status === 409 || status === 404 ? 'This request expired' : fallback;

/** Outcome of a one-tap action; `info` is neither a success nor a failure (a card that expired). */
export interface AwayNotice {
  text: string;
  error: boolean;
  info?: boolean;
}

/**
 * The notice for a failed one-tap action. A card that expired before it was answered is not an error:
 * the server's own sentence ("This card expired: … Ask the bot again.") is shown as a plain notice.
 */
export function actionFailureNotice(status: number, serverMessage: string, title: string): AwayNotice {
  if (status === 409 && /^This card expired\b/.test(serverMessage)) return { text: `${serverMessage} (“${title}”)`, error: false, info: true };
  return { text: `${actionErrorText(status, `Couldn't send it: ${serverMessage}`)}: “${title}”`, error: true };
}

export class AwayError extends Error {
  /** The server's machine-readable `code` (22i dismiss: `not_found`, `person_only`, `use_*`), when it sent one. */
  public code: string | null;
  /** `body`: the parsed JSON error body (22f: a 409 `needs_backup` floor refusal), when there was one. */
  constructor(public status: number, message: string, public body: unknown = null) {
    super(message);
    const c = body && typeof body === 'object' ? (body as { code?: unknown }).code : undefined;
    this.code = typeof c === 'string' && c ? c : null;
  }
}

/**
 * 22f: a production-floor refusal (409 with `status: "needs_backup"`, any `code`). The card is still waiting on the
 * server for a fresh backup, so it has not lapsed and must stay in the chat.
 */
export const isBackupRefusal = (err: unknown): err is AwayError =>
  err instanceof AwayError && err.status === 409 && !!err.body && typeof err.body === 'object' && (err.body as { status?: unknown }).status === 'needs_backup';

/** The notice for any failed one-tap action, given what was thrown. */
export function failureNotice(err: unknown, title: string): AwayNotice {
  if (isBackupRefusal(err)) {
    const why = err.message && !/^Request failed \(HTTP/.test(err.message) ? err.message : 'This step needs a backup from the last 10 minutes. Take one on the card, then Allow.';
    return { text: `${why} (“${title}”)`, error: true };
  }
  const status = err instanceof AwayError ? err.status : 0;
  return actionFailureNotice(status, err instanceof Error ? err.message : 'Something went wrong.', title);
}

/**
 * Resolve an approval from Away or the Inbox. The chat's copy of the card is dropped when it was answered or has
 * lapsed (409/404), but not on a backup refusal: that card is still waiting.
 */
export async function resolveFromList<T>(id: string, onResolved: ((id: string) => void) | undefined, run: () => Promise<T>): Promise<T> {
  try {
    const r = await run();
    onResolved?.(id);
    return r;
  } catch (err) {
    if (err instanceof AwayError && (err.status === 409 || err.status === 404) && !isBackupRefusal(err)) onResolved?.(id);
    throw err;
  }
}

async function call<T>(method: string, url: string, body?: unknown): Promise<T> {
  const res = await fetch(url, {
    method,
    headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  if (!res.ok) {
    let message = `Request failed (HTTP ${res.status}).`;
    let data: unknown = null;
    try {
      data = await res.json();
      const e = data && typeof data === 'object' ? (data as { error?: unknown }).error : undefined;
      if (typeof e === 'string' && e) message = e;
    } catch {
      // no JSON body
    }
    throw new AwayError(res.status, message, data);
  }
  return res.json();
}

const enc = encodeURIComponent;

/** 29p: the longest reason a Deny carries (the card's field stops at this too). */
export const DENY_REASON_MAX = 500;

/**
 * The body of `POST /api/approvals/:id/resolve`, for the chat card and the Inbox alike. `without_backup` only
 * with Allow once (22f); `reason` only with a Deny that has text (29p, trimmed, cut to 500). Every other answer
 * sends just `{ decision }`, as before.
 */
export function resolveBody(
  decision: ApprovalDecision,
  opts: { withoutBackup?: boolean; reason?: string } = {},
): { decision: ApprovalDecision; without_backup?: true; reason?: string } {
  if (opts.withoutBackup && decision === 'allow_once') return { decision, without_backup: true };
  const reason = decision === 'deny' && typeof opts.reason === 'string' ? opts.reason.trim().slice(0, DENY_REASON_MAX).trim() : '';
  return reason ? { decision, reason } : { decision };
}

export const awayApi = {
  get: (since?: string) => call<AwayResponse>('GET', `/api/away${since ? `?since=${enc(since)}` : ''}`).then(normalizeAway),
  seen: () => call<{ last_seen: string }>('POST', '/api/away/seen'),
  answer: (id: string, choice: number) => call<unknown>('POST', `/api/questions/${enc(id)}/answer`, { choice }),
  resolve: (id: string, decision: ApprovalDecision, withoutBackup = false, reason?: string) =>
    call<unknown>('POST', `/api/approvals/${enc(id)}/resolve`, resolveBody(decision, { withoutBackup, reason })),
  /** Approval records with this stored status, newest first (`answered_via` says where). */
  approvals: (status: string) => call<unknown>('GET', `/api/approvals?status=${enc(status)}`),
  /** 0.9.5: ask again for an approval that expired unanswered (starts a new turn; grants nothing). */
  retryApproval: (approvalId: string) => call<unknown>('POST', `/api/approvals/${enc(approvalId)}/retry`),
  /** 22i: Retry on a failed task or routine run that names its task (`missions` retry_task). */
  retryTask: (taskId: string) => call<unknown>('POST', `/api/tasks/${enc(taskId)}/retry`),
  /** 22i: "Done, clear it" (the person only, Lin #700): closes one item kwant can't close by itself. */
  dismiss: (id: string, kind: string) => call<unknown>('POST', `/api/waiting/${enc(id)}/dismiss`, { kind }),
};

/**
 * 0.9.5: the one action a stopped item offers in place. An expired approval is retried from the Inbox
 * itself; every other stop resumes in its chat (the notice there has Retry or Continue, a browser step
 * its Done), so the row opens the chat.
 */
export function stoppedAction(item: Pick<AwayItem, 'kind' | 'retry'>): { kind: 'retry_approval'; approvalId: string } | { kind: 'open_chat' } | null {
  if (item.kind !== 'stopped') return null;
  const r = item.retry;
  if (r && r.type === 'approval' && r.approval_id) return { kind: 'retry_approval', approvalId: r.approval_id };
  return { kind: 'open_chat' };
}

/** SSE events that can change what the page shows, so the badge re-counts. */
const AWAY_EVENTS = new Set([
  'question_updated', 'QuestionUpdated',
  'delegation_updated', 'DelegationUpdated',
  'routine_run', 'RoutineRun',
  'ApprovalRequired', 'ApprovalWithdrawn',
  // 22i: a stopped item closes when a later reply there ends, a browser step when it is done, and
  // any item when it is cleared; each refreshes Needs attention and the strip without a reload.
  'turn_ended', 'TurnEnded',
  'human_step_updated', 'HumanStepUpdated',
  'waiting_updated', 'WaitingUpdated', 'waiting_closed', 'WaitingClosed',
]);
export const affectsAway = (type: unknown): boolean => typeof type === 'string' && AWAY_EVENTS.has(type);