дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 09:11:10 +02:00
GitHub Copilot now runs over `copilot --headless --no-auto-update --stdio` (the protocol the Copilot SDK speaks) behind the in-process ACP shim, like the Claude Code and Codex drivers. It exposes the full model catalog with per-model efforts, the 200K / 1M context tier per session (also switched mid-session) and per-tier token pricing in the model picker, using Copilot's own defaults for model, effort and context tier. When the headless protocol fails for a reason other than sign-in or a missing executable (catalog discovery, probe, session create/resume, or a protocol error before the first prompt streams), that Copilot executable (path, mtime, size) falls back to `copilot --acp` for the rest of the session; reloading agents clears it. Registry installs with `args = ["--acp"]` and no `driver` move to the native driver; an explicit `driver = "acp"` stays on ACP. Verified with Copilot CLI 1.0.112: probe reports the native protocol and its sign-in method; a CLI that rejects `--headless` falls back to ACP v1, and back to native once the executable changes. ide-agent tests (282) and clippy, agents and locale vitest (831), typecheck, lint, format and knip pass; bindings unchanged. Co-authored-by: dengliu <[email protected]>
575 рядки
22 KiB
TypeScript
575 рядки
22 KiB
TypeScript
/** Pure composer helpers: `@` / `/` completion, attachments, history recall, settings. */
|
||
import type {
|
||
AgentCommand,
|
||
AgentConfigOption,
|
||
AgentCost,
|
||
AgentEntry,
|
||
AgentImage,
|
||
AgentLimit,
|
||
AgentPrompt,
|
||
AgentRetry,
|
||
AgentUsage,
|
||
} from "@/bindings";
|
||
import { tx } from "@/platform/i18n";
|
||
|
||
export interface FileRef {
|
||
/** Absolute path (in the task's directory). */
|
||
path: string;
|
||
/** As written after `@`; the file name when `attached`. */
|
||
rel: string;
|
||
/** Sent without an `@` mention: a file from outside the project, shown as a chip. */
|
||
attached?: boolean;
|
||
}
|
||
|
||
export interface ComposerDraft {
|
||
text: string;
|
||
files: FileRef[];
|
||
images: AgentImage[];
|
||
}
|
||
|
||
export const emptyDraft = (): ComposerDraft => ({
|
||
text: "",
|
||
files: [],
|
||
images: [],
|
||
});
|
||
|
||
export type MessageToken = { kind: "text" | "file" | "command"; value: string };
|
||
|
||
/**
|
||
* A message's text split into plain runs, `@file` references and `/command` skills. A
|
||
* command is a `/word` at the start or after whitespace; a reference likewise after `@`.
|
||
* Punctuation that ends either belongs to the text.
|
||
*/
|
||
export function messageTokens(text: string): MessageToken[] {
|
||
const out: MessageToken[] = [];
|
||
let last = 0;
|
||
// Full-width punctuation ends one too, as Chinese text runs on without a space after it.
|
||
for (const match of text.matchAll(/(^|\s)([@/][^\s@,。;:!?、()【】《》「」『』]+)/g)) {
|
||
// Punctuation after it ends the sentence, not the path: "see @a.ts, then /review."
|
||
const token = match[2]!.replace(/^(.+?)[,.;:!?)\]}>'",。;:!?、)】》」』]+$/, "$1");
|
||
const start = match.index! + match[1]!.length;
|
||
const command = /^\/[A-Za-z][\w:.-]*$/.test(token);
|
||
if (token.startsWith("/") && !command) continue;
|
||
if (start > last) out.push({ kind: "text", value: text.slice(last, start) });
|
||
out.push({ kind: command ? "command" : "file", value: token });
|
||
last = start + token.length;
|
||
}
|
||
if (last < text.length) out.push({ kind: "text", value: text.slice(last) });
|
||
return out;
|
||
}
|
||
|
||
export type Completion =
|
||
| { kind: "file"; query: string; from: number; to: number }
|
||
| { kind: "command"; query: string; from: number; to: number };
|
||
|
||
/** The `@file` or `/command` being typed at `caret`, if any; both may follow other text. */
|
||
export function completionAt(text: string, caret: number): Completion | null {
|
||
const before = text.slice(0, caret);
|
||
const word = /(^|\s)([@/])([^\s@]*)$/.exec(before);
|
||
if (!word) return null;
|
||
const from = caret - word[3]!.length - 1;
|
||
return {
|
||
kind: word[2] === "/" ? "command" : "file",
|
||
query: word[3]!,
|
||
from,
|
||
to: caret,
|
||
};
|
||
}
|
||
|
||
/** Replaces the completion with `insert` plus a space; returns the text and the caret after it. */
|
||
export function applyCompletion(text: string, c: Completion, insert: string): { text: string; caret: number } {
|
||
const after = text.slice(c.to);
|
||
const glue = after.startsWith(" ") ? "" : " ";
|
||
const next = text.slice(0, c.from) + insert + glue + after;
|
||
return { text: next, caret: c.from + insert.length + 1 };
|
||
}
|
||
|
||
/**
|
||
* Commands matching `query`: prefix matches first (a plugin's "plugin:name" also by its
|
||
* name), then substrings, then names holding its letters in order ("trig" → "triage").
|
||
*/
|
||
export function matchCommands(commands: readonly AgentCommand[], query: string): AgentCommand[] {
|
||
const q = query.toLowerCase();
|
||
const rank = (name: string) => {
|
||
const n = name.toLowerCase();
|
||
if (n.startsWith(q) || n.slice(n.lastIndexOf(":") + 1).startsWith(q)) return 0;
|
||
if (n.includes(q)) return 1;
|
||
return inOrder(n, q) ? 2 : -1;
|
||
};
|
||
return commands
|
||
.map((command) => ({ command, rank: rank(command.name) }))
|
||
.filter((m) => m.rank >= 0)
|
||
.sort((a, b) => Number(a.command.source === "skill") - Number(b.command.source === "skill") || a.rank - b.rank)
|
||
.map((m) => m.command);
|
||
}
|
||
|
||
function inOrder(text: string, query: string): boolean {
|
||
let i = 0;
|
||
for (const ch of text) if (ch === query[i]) i++;
|
||
return i >= query.length;
|
||
}
|
||
|
||
/** Whether an `@` query is a typed-out path (`../x`, `./x`, `/x`) rather than a project file search. */
|
||
export const isPathQuery = (query: string) => /^(\.\.?(\/|$)|\/)/.test(query);
|
||
|
||
const isDrive = (part: string | undefined) => !!part && /^[A-Za-z]:$/.test(part);
|
||
|
||
/** `rel` (as typed after `@`) resolved against `root`, `.` and `..` folded lexically. */
|
||
export function resolveTyped(root: string, rel: string): string {
|
||
const out: string[] = [];
|
||
const path = rel.startsWith("/") ? rel : `${root.replace(/\\/g, "/")}/${rel}`;
|
||
for (const part of path.split("/")) {
|
||
if (part === "..") {
|
||
// Never fold away a Windows drive (`C:`).
|
||
if (out.length > 1 || !isDrive(out[0])) out.pop();
|
||
} else if (part && part !== ".") out.push(part);
|
||
}
|
||
return isDrive(out[0]) ? out.join("/") : `/${out.join("/")}`;
|
||
}
|
||
|
||
interface IndexMatch {
|
||
path: string;
|
||
relPath: string;
|
||
score: number;
|
||
/** Matched characters of `relPath`. */
|
||
indices?: number[];
|
||
}
|
||
|
||
/**
|
||
* Index file and folder matches as one list, best first (files first on a tie); folders'
|
||
* `rel` loses the trailing `/` the index gives them.
|
||
*/
|
||
export function mergeMatches(
|
||
files: readonly IndexMatch[],
|
||
dirs: readonly IndexMatch[],
|
||
limit: number,
|
||
): {
|
||
path: string;
|
||
rel: string;
|
||
dir: boolean;
|
||
score: number;
|
||
indices: number[];
|
||
}[] {
|
||
return [
|
||
...files.map((f) => ({
|
||
path: f.path,
|
||
rel: f.relPath,
|
||
dir: false,
|
||
score: f.score,
|
||
indices: f.indices ?? [],
|
||
})),
|
||
...dirs.map((d) => ({
|
||
path: d.path,
|
||
rel: d.relPath.replace(/\/$/, ""),
|
||
dir: true,
|
||
score: d.score,
|
||
indices: d.indices ?? [],
|
||
})),
|
||
]
|
||
.sort((a, b) => b.score - a.score || Number(a.dir) - Number(b.dir))
|
||
.slice(0, limit);
|
||
}
|
||
|
||
export interface Mention {
|
||
/** As written after `@`; a folder keeps its trailing `/`. */
|
||
rel: string;
|
||
dir: boolean;
|
||
/** 1-based lines, when the mention names a range. */
|
||
lines?: { from: number; to: number };
|
||
}
|
||
|
||
/** `@src/a.rs:10-20` → its path and lines; `null` for an empty `@`. */
|
||
export function parseMention(token: string): Mention | null {
|
||
const m = /^@(.+?)(?::(\d+)(?:-(\d+))?)?$/.exec(token);
|
||
if (!m) return null;
|
||
const rel = m[1]!;
|
||
const from = m[2] ? Number(m[2]) : undefined;
|
||
const lines = from === undefined ? undefined : { from, to: m[3] ? Math.max(from, Number(m[3])) : from };
|
||
return { rel, dir: rel.endsWith("/"), ...(lines && { lines }) };
|
||
}
|
||
|
||
/** "10" or "10–20". */
|
||
export const linesLabel = (lines: { from: number; to: number }) =>
|
||
lines.from === lines.to ? String(lines.from) : `${lines.from}–${lines.to}`;
|
||
|
||
/** Lines of `text` that start with `>`: a quoted reply or selection, drawn as a block. */
|
||
export const isQuoteLine = (line: string) => /^>( |$)/.test(line);
|
||
|
||
export interface Fence {
|
||
/** Line indexes (0-based) of the opening and the closing fence. */
|
||
open: number;
|
||
close: number;
|
||
/** After the opening fence: a language, or `terminal <title>`. */
|
||
info: string;
|
||
}
|
||
|
||
/** The closed ``` blocks among `lines`. */
|
||
export function fencedBlocks(lines: readonly string[]): Fence[] {
|
||
const out: Fence[] = [];
|
||
for (let i = 0; i < lines.length; i++) {
|
||
const open = /^(`{3,})([^`]*)$/.exec(lines[i]!);
|
||
if (!open) continue;
|
||
const ticks = open[1]!.length;
|
||
const close = lines.findIndex((l, j) => j > i && new RegExp(`^\`{${ticks},}\\s*$`).test(l));
|
||
if (close < 0) break;
|
||
out.push({ open: i, close, info: open[2]!.trim() });
|
||
i = close;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** `text` as a ``` block on its own lines, fenced longer than any run of backticks in it. */
|
||
export function fenced(text: string, info: string): string {
|
||
const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map((m) => m[0].length));
|
||
const fence = "`".repeat(longest + 1);
|
||
return `${fence}${info}\n${text.replace(/\r\n?/g, "\n").replace(/\s+$/, "")}\n${fence}`;
|
||
}
|
||
|
||
export type FenceKind = "terminal" | "problems" | "trace" | "text" | "code";
|
||
|
||
/**
|
||
* A block's kind and label: `terminal zsh` → a terminal named zsh, `problems`, `trace` (an
|
||
* error's stack), `text` (a long paste); anything else is code in that language (`ts`).
|
||
*/
|
||
export function fenceLabel(info: string): { kind: FenceKind; label: string; language: string | null } {
|
||
const [first = "", ...rest] = info.split(/\s+/);
|
||
if (first === "terminal" || first === "problems" || first === "trace" || first === "text")
|
||
return { kind: first, label: rest.join(" "), language: null };
|
||
return { kind: "code", label: info, language: first || null };
|
||
}
|
||
|
||
/** An error's stack trace or a crash: pasted as a block, its project lines as references. */
|
||
export function looksLikeTrace(text: string): boolean {
|
||
if (!text.trim().includes("\n")) return false;
|
||
return [
|
||
/^\s+at\s+\S/m, // JavaScript, Java, C#
|
||
/^Traceback \(most recent call last\)/m,
|
||
/^\s*File ".+", line \d+/m,
|
||
/panicked at /,
|
||
/^goroutine \d+ \[/m,
|
||
/^\s*\d+: .+\n\s+at \S+:\d+/m, // Rust backtrace
|
||
/^(?:Uncaught |Unhandled )?[\w.$]*(?:Error|Exception)\b.*\n\s+(?:at|File|in) /m,
|
||
].some((re) => re.test(text));
|
||
}
|
||
|
||
/** Long pasted text goes in as a block rather than filling the box. */
|
||
export const LONG_PASTE_LINES = 30;
|
||
|
||
/**
|
||
* `path:line` places in output (`src/a.ts:12`, `/abs/a.go:34:5`, `(a.js:3:9)`,
|
||
* `File "a.py", line 7`), each once, at most `limit`, dependency paths left out.
|
||
*/
|
||
export function placesInText(text: string, limit = 8): { path: string; line: number }[] {
|
||
const out: { path: string; line: number }[] = [];
|
||
const seen = new Set<string>();
|
||
const add = (raw: string, line: string) => {
|
||
const path = raw.replace(/^file:\/\//, "");
|
||
if (/(^|[\\/])(node_modules|site-packages|\.cargo|\.rustup|go[\\/]pkg[\\/]mod)[\\/]/.test(path)) return;
|
||
const key = `${path}:${line}`;
|
||
if (seen.has(key) || out.length >= limit) return;
|
||
seen.add(key);
|
||
out.push({ path, line: Number(line) });
|
||
};
|
||
for (const m of text.matchAll(/File "([^"]+)", line (\d+)/g)) add(m[1]!, m[2]!);
|
||
for (const m of text.matchAll(/(?:file:\/\/)?((?:[A-Za-z]:)?[\w.@+\-\\/]*[\w-]\.[A-Za-z0-9]{1,8}):(\d+)(?::\d+)?/g))
|
||
add(m[1]!, m[2]!);
|
||
return out;
|
||
}
|
||
|
||
/**
|
||
* Pasted absolute paths, one per line (`/abs/a.rs`, `/abs/a.rs:10-20`, `/abs/a.rs:10:5`,
|
||
* quoted, or `file://` URLs); `null` when any line is something else.
|
||
*/
|
||
export function pastedPaths(text: string): { path: string; lines?: { from: number; to: number } }[] | null {
|
||
const rows = text
|
||
.split(/\r?\n/)
|
||
.map((l) => l.trim())
|
||
.filter(Boolean);
|
||
if (!rows.length) return null;
|
||
const out: { path: string; lines?: { from: number; to: number } }[] = [];
|
||
for (let row of rows) {
|
||
row = row.replace(/^(["'])(.*)\1$/, "$2");
|
||
if (row.startsWith("file://")) {
|
||
try {
|
||
row = decodeURIComponent(new URL(row).pathname).replace(/^\/([A-Za-z]:)/, "$1");
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
const m = /^((?:\/|[A-Za-z]:[\\/]).*?)(?::(\d+)(?:(?:-(\d+))|(?::\d+))?)?$/.exec(row);
|
||
if (!m) return null;
|
||
const from = m[2] ? Number(m[2]) : undefined;
|
||
out.push({
|
||
path: m[1]!.replace(/[\\/]+$/, "") || m[1]!,
|
||
...(from !== undefined && { lines: { from, to: m[3] ? Math.max(from, Number(m[3])) : from } }),
|
||
});
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** `@rel` with a line range suffix when given ("@src/a.rs:10-20"). */
|
||
export function mentionOf(rel: string, lines?: { from: number; to: number }): string {
|
||
if (!lines) return `@${rel}`;
|
||
return lines.from === lines.to ? `@${rel}:${lines.from}` : `@${rel}:${lines.from}-${lines.to}`;
|
||
}
|
||
|
||
/** Whether `text` still holds the `@rel` mention, with or without a line range. */
|
||
export const isMentioned = (text: string, rel: string) =>
|
||
new RegExp(`@${escapeRe(rel)}(?![\\w./-])|@${escapeRe(rel)}:`).test(text);
|
||
|
||
/** The file in the focused editor and the lines selected in it, for IDE context. */
|
||
export interface IdeContext {
|
||
path: string;
|
||
rel: string;
|
||
/** 1-based lines of a non-empty selection. */
|
||
lines?: { from: number; to: number };
|
||
}
|
||
|
||
/**
|
||
* `draft` with the editor's current file added (as an attachment), or its selection as a
|
||
* line-range mention after the text; unchanged when the draft already references the file.
|
||
*/
|
||
export function withIdeContext(draft: ComposerDraft, context: IdeContext | null): ComposerDraft {
|
||
if (
|
||
!context ||
|
||
isMentioned(draft.text, context.rel) ||
|
||
draft.files.some((f) => f.path === context.path && f.attached)
|
||
)
|
||
return draft;
|
||
if (!context.lines)
|
||
return { ...draft, files: [...draft.files, { path: context.path, rel: context.rel, attached: true }] };
|
||
const mention = mentionOf(context.rel, context.lines);
|
||
const text = draft.text.trim();
|
||
return {
|
||
...draft,
|
||
text: text ? `${text}\n\n${mention}` : mention,
|
||
files: [...draft.files, { path: context.path, rel: context.rel }],
|
||
};
|
||
}
|
||
|
||
/** The prompt to send: attached files, files still mentioned in the text (each once), and the images. */
|
||
export function toPrompt(draft: ComposerDraft): AgentPrompt {
|
||
const seen = new Set<string>();
|
||
const files = draft.files.filter((f) => {
|
||
if (seen.has(f.path) || !(f.attached || isMentioned(draft.text, f.rel))) return false;
|
||
seen.add(f.path);
|
||
return true;
|
||
});
|
||
return {
|
||
text: draft.text.trim(),
|
||
files: files.map((f) => f.path),
|
||
images: draft.images,
|
||
};
|
||
}
|
||
|
||
export const canSend = (d: ComposerDraft) => !!d.text.trim() || d.images.length > 0 || d.files.some((f) => f.attached);
|
||
|
||
/**
|
||
* ↑ / ↓ through sent messages (newest first). `index` −1 is the unsent draft. Returns the
|
||
* new index, or `null` when the key should move the caret instead.
|
||
*/
|
||
export function recall(history: readonly string[], index: number, dir: -1 | 1): number | null {
|
||
const next = index + (dir < 0 ? 1 : -1);
|
||
if (next < -1 || next >= history.length) return null;
|
||
return next;
|
||
}
|
||
|
||
/** Whether ↑ / ↓ recalls history: the caret is on the first / last line. */
|
||
export function atEdgeLine(text: string, caret: number, dir: -1 | 1): boolean {
|
||
return dir < 0 ? !text.slice(0, caret).includes("\n") : !text.slice(caret).includes("\n");
|
||
}
|
||
|
||
export const isContextOption = (id: string) => /^(context_tier|contextTier)$/.test(id);
|
||
|
||
/** Whether an option's available values and default belong to the selected model rather than the provider. */
|
||
export const isPerModelOption = (o: AgentConfigOption) =>
|
||
o.category === "thought_level" || o.category === "context_tier" || isContextOption(o.id);
|
||
|
||
/** Formats a per-1M-token credit rate cleanly (`200`, `1000`, `0`, `12.5`). */
|
||
export function formatCreditRate(rate: number | null | undefined): string {
|
||
if (rate == null || !Number.isFinite(rate)) return "0";
|
||
if (rate === 0) return "0";
|
||
if (rate < 0.01) return rate.toExponential(2);
|
||
return Number(rate.toFixed(4)).toString();
|
||
}
|
||
|
||
const matchesCategory = (o: AgentConfigOption, category: string) =>
|
||
o.category === category ||
|
||
(category === "model_config" &&
|
||
(o.category === "model_config" || o.category === "context_tier" || o.id === "fast" || isContextOption(o.id)));
|
||
|
||
/** Cursor / ACP model parameters (`fast`, `contextTier`…), separate from the model id itself. */
|
||
export function modelConfigOptions(config: readonly AgentConfigOption[]): AgentConfigOption[] {
|
||
return config.filter(
|
||
(o) => o.category === "model_config" || o.category === "context_tier" || o.id === "fast" || isContextOption(o.id),
|
||
);
|
||
}
|
||
|
||
/** The settings shown in the composer: model, mode, collaboration mode, permissions, approvals, effort, fast. */
|
||
export function mainOptions(config: readonly AgentConfigOption[]): AgentConfigOption[] {
|
||
const order = ["model", "mode", "collaboration_mode", "permissions", "approval", "thought_level", "model_config"];
|
||
return order.flatMap((c) => {
|
||
const matched = config.filter((o) => matchesCategory(o, c));
|
||
return c === "model_config" ? matched : matched.slice(0, 1);
|
||
});
|
||
}
|
||
|
||
/** Cursor defaults to Fast; prefer standard Composer unless the user chose otherwise. */
|
||
export function cursorModelDefaults(
|
||
providerId: string | undefined,
|
||
config: readonly AgentConfigOption[],
|
||
): Record<string, string> {
|
||
if (providerId !== "cursor") return {};
|
||
const fast = config.find((o) => o.id === "fast" || o.category === "model_config");
|
||
if (fast?.values.some((v) => v.value === "false")) return { [fast.id]: "false" };
|
||
return {};
|
||
}
|
||
|
||
export const modeOption = (config: readonly AgentConfigOption[]) => config.find((o) => o.category === "mode");
|
||
|
||
/**
|
||
* An icon per permission mode, by what it lets the agent do (mode ids differ per agent:
|
||
* Claude `acceptEdits`, Gemini `auto_edit`, Codex `full-access`…). Unknown modes ask.
|
||
*/
|
||
export function modeIcon(mode: string): string {
|
||
const m =
|
||
mode
|
||
.toLowerCase()
|
||
.split(/[#/]/)
|
||
.at(-1)
|
||
?.replace(/[^a-z]/g, "") ?? "";
|
||
if (m.includes("plan") || m === "architect") return "todo";
|
||
if (m.includes("bypass") || m === "yolo" || m.includes("fullaccess") || m === "dangerous") return "unlock";
|
||
if (m.includes("readonly") || m === "ask" || m === "chat") return "eye";
|
||
if (m.includes("edit") || m === "code") return "edit";
|
||
if (m === "auto" || m === "agent" || m.includes("autopilot")) return "run";
|
||
return "lock";
|
||
}
|
||
|
||
/** The settings that approve everything without asking (a bypass mode, or approvals), by option id. */
|
||
export function bypassDefaults(config: readonly AgentConfigOption[]): Record<string, string> {
|
||
const out: Record<string, string> = {};
|
||
const mode = modeOption(config);
|
||
const unlock = mode?.values.find((v) => modeIcon(v.value) === "unlock");
|
||
if (mode && unlock) out[mode.id] = unlock.value;
|
||
const permissions = config.find((o) => o.category === "permissions");
|
||
const allowAll = permissions?.values.find((v) => /^(on|true)$/i.test(v.value));
|
||
if (permissions && allowAll) out[permissions.id] = allowAll.value;
|
||
const approval = config.find((o) => o.category === "approval");
|
||
if (approval?.values.some((v) => v.value === "bypass")) out[approval.id] = "bypass";
|
||
return out;
|
||
}
|
||
|
||
/** Shift+Tab: the mode after the current one. */
|
||
export function nextValue(option: AgentConfigOption, current = option.current): string | null {
|
||
if (!option.values.length) return null;
|
||
const i = option.values.findIndex((v) => v.value === current);
|
||
return option.values[(i + 1) % option.values.length]!.value;
|
||
}
|
||
|
||
/** A pending API retry: "3/10" (or "3" when the agent gives no limit) and the seconds left. */
|
||
export function retryParts(r: AgentRetry, now: number): { attempt: string; wait: number } {
|
||
return {
|
||
attempt: r.maxRetries != null ? `${r.attempt}/${r.maxRetries}` : String(r.attempt),
|
||
wait: r.retryAtMs == null ? 0 : Math.max(0, Math.ceil((r.retryAtMs - now) / 1000)),
|
||
};
|
||
}
|
||
|
||
/** "167k/1M (17%)" of the context window and a tooltip with the exact counts. */
|
||
export function usageLabel(u: AgentUsage): {
|
||
short: string;
|
||
percent: number;
|
||
detail: string;
|
||
} {
|
||
const percent = Math.min(100, Math.round((u.used / u.size) * 100));
|
||
return {
|
||
short: `${tokens(u.used)}/${tokens(u.size)} (${percent}%)`,
|
||
percent,
|
||
detail: tx`${tokens(u.used)} / ${tokens(u.size)} tokens`,
|
||
};
|
||
}
|
||
|
||
/** The usage-limit windows agents report, by the name they give them; others show that name. */
|
||
const LIMIT_WINDOWS: Record<string, { short: string; name: string }> = {
|
||
five_hour: { short: "5h", name: "5-hour limit" },
|
||
seven_day: { short: "7d", name: "Weekly limit" },
|
||
seven_day_opus: { short: "7d Opus", name: "Weekly Opus limit" },
|
||
seven_day_sonnet: { short: "7d Sonnet", name: "Weekly Sonnet limit" },
|
||
};
|
||
|
||
/** "5h 19%" for a usage-limit window, and a tooltip saying when it resets. */
|
||
export function limitLabel(l: AgentLimit, now: number): { short: string; percent: number; detail: string } {
|
||
const known = LIMIT_WINDOWS[l.window];
|
||
const percent = Math.min(100, Math.round(l.usedPercent ?? 0));
|
||
const name = known ? tx(known.name) : l.window;
|
||
const used = tx`${name}: ${percent}% used`;
|
||
if (l.resetsMs == null)
|
||
return {
|
||
short: `${known?.short ?? l.window} ${percent}%`,
|
||
percent,
|
||
detail: used,
|
||
};
|
||
const reset = untilReset(Math.max(0, l.resetsMs - now));
|
||
return {
|
||
short: `${known?.short ?? l.window} ${percent}%`,
|
||
percent,
|
||
detail: tx`${used}, resets in ${reset}`,
|
||
};
|
||
}
|
||
|
||
/** `45m`, `2h 51m`, `5d 3h`. */
|
||
function untilReset(ms: number): string {
|
||
const m = Math.round(ms / 60_000);
|
||
if (m < 60) return `${m}m`;
|
||
const h = Math.floor(m / 60);
|
||
if (h < 24) return `${h}h ${String(m % 60).padStart(2, "0")}m`;
|
||
return `${Math.floor(h / 24)}d ${h % 24}h`;
|
||
}
|
||
|
||
/** "$0.42": what the session has cost so far. */
|
||
export function costLabel(c: AgentCost): string {
|
||
try {
|
||
return new Intl.NumberFormat("en-US", {
|
||
style: "currency",
|
||
currency: c.currency,
|
||
}).format(c.amount ?? 0);
|
||
} catch {
|
||
// Not an ISO 4217 code.
|
||
return `${(c.amount ?? 0).toFixed(2)} ${c.currency}`;
|
||
}
|
||
}
|
||
|
||
/** `850`, `83.1k`, `1M`. */
|
||
function tokens(n: number): string {
|
||
if (n >= 1_000_000) return `${+(n / 1_000_000).toFixed(1)}M`;
|
||
if (n >= 1000) return `${+(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k`;
|
||
return `${Math.round(n)}`;
|
||
}
|
||
|
||
/** Time the agent spent on the task's turns; a running one counts up to `now` (`null` when idle). */
|
||
export function workTime(entries: readonly AgentEntry[], now: number | null): number {
|
||
const users = entries.filter((e): e is Extract<AgentEntry, { type: "user" }> => e.type === "user");
|
||
let total = 0;
|
||
users.forEach((e, i) => {
|
||
if (e.sentMs == null) return;
|
||
const end = e.doneMs ?? (i === users.length - 1 ? now : null);
|
||
if (end != null && end > e.sentMs) total += end - e.sentMs;
|
||
});
|
||
return total;
|
||
}
|
||
|
||
/** `data:image/png;base64,AAA` → an image attachment. */
|
||
export function imageFromDataUrl(url: string, name?: string): AgentImage | null {
|
||
const m = /^data:([^;,]+);base64,(.*)$/s.exec(url);
|
||
if (!m || !m[1]!.startsWith("image/")) return null;
|
||
return { mimeType: m[1]!, data: m[2]!, name: name ?? null };
|
||
}
|
||
|
||
export const IMAGE_EXTENSIONS = /\.(png|jpe?g|gif|webp)$/i;
|
||
/** Larger images are refused (agents reject them anyway). */
|
||
export const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
||
|
||
function escapeRe(s: string) {
|
||
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||
}
|