Файли
openidea/src/features/agents/model.ts
T
Deng Liuтаdengliu 19aef36354 feat(agents): add Agent Memory settings and a per-session memory picker (#6826)
Adds Settings › Agents › Memory and a Session Memory picker (/memory, /memories, the composer + menu and the context meter link). They list each agent's own instruction files, path-scoped rules and auto-memory notes: AGENTS.md, CLAUDE.md and .claude/rules, .github/copilot-instructions.md and .github/instructions, .cursor/rules, GEMINI.md, and the Claude Code, Codex and Hermes auto-memory folders.

Per-file modes (Auto / Always / Off) and the auto-memory policy (Inherit / Read & Write / Read Only / Off) are stored in settings.toml at user or workspace scope and never edit tracked files. Workspace entries load only in trusted projects. Each driver receives the policy natively: Claude Code through --settings and --add-dir, Codex through its memories config and /memories, GitHub Copilot through excludedTools and the system message, and Hermes through config.yaml. A file set to Always is staged into other agents' sessions. Auto-memory notes can be promoted into the workspace AGENTS.md, and an idle session restarts when a memory policy changes.

Groups of the same agent are titled by scope, for example Claude Code (User) and Claude Code (Auto Memory).

Closes #6810

Co-authored-by: dengliu <[email protected]>
2026-11-29 22:38:20 +08:00

326 рядки
12 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
/** Pure helpers: task grouping, entry updates, labels. */
import type { AgentEntry, AgentStatus, AgentSubagentStatus, AgentTask, InterruptionReason } from "@/bindings";
import { isIconName } from "@/ui/icons";
export const SESSION_KIND = "agent-session";
export const HOME_KIND = "agent-home";
export const HOME_KEY = "agent:new";
export const TOOL_WINDOW = "agents";
/** MIME of a dragged agent task (a tree row or the docked conversation bar): the payload is the task id. */
export const TASK_DRAG = "application/x-openidea-agent-task";
/** MIME of a dragged custom agent task group header: the payload is the group id. */
export const GROUP_DRAG = "application/x-openidea-agent-group";
/** Settings › Agents › Agent Setup. */
export const REGISTRY_PAGE = "agents.list";
/** The Settings folder holding the agent pages. */
export const AGENTS_GROUP = "Agents";
/** Settings › Agents › MCP Connections. */
export const MCP_PAGE = "agents.mcpServers";
/** Settings › Agents › Skills: every CLI's SKILL.md folders and their modes. */
export const SKILLS_PAGE = "agents.skills";
/** Settings › Agents › Memory: instructions, path-scoped rules, and auto-memories across agents. */
export const MEMORY_PAGE = "agents.memory";
/** Settings › Agents › Command Rules. */
export const POLICY_PAGE = "agents.policy";
export const sessionKey = (task: string) => `agent:${task}`;
/** A task's Changes editor tab: its changed files and their diffs. */
export const CHANGES_KIND = "agent-changes";
export const changesKey = (task: string) => `agent-changes:${task}`;
/** Key of a conversation in the entries store: the task's own, or its subagent `subagent`'s. */
export const entriesKey = (task: string, subagent: string | null) => (subagent ? `${task}/${subagent}` : task);
export type SubagentEntry = Extract<AgentEntry, { type: "subagent" }>;
/** The card of subagent `id` in its parent's `entries`. */
export const findSubagent = (entries: AgentEntry[] | undefined, id: string) =>
entries?.find((e): e is SubagentEntry => e.type === "subagent" && e.id === id);
export const subagentWorking = (s: AgentSubagentStatus) => s === "running" || s === "needsInput";
/** "Explore", else what it was started for. */
export const subagentTitle = (e: SubagentEntry) => e.title ?? e.description ?? "Subagent";
export function subagentStatusLabel(s: AgentSubagentStatus): string {
switch (s) {
case "running":
return "Running";
case "needsInput":
return "Needs input";
case "done":
return "Done";
case "cancelled":
return "Stopped";
case "failed":
return "Failed";
}
}
/** Suggests an agent-file id for a display name (`"My Agent!"` → `"my-agent"`). */
export function slugifyId(name: string): string {
return name
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}
/** The agent a Hermes profile runs as: `hermes` for `default`, else `hermes-<slug>` (`hermes -p <name> acp`). */
export const hermesAgentId = (profile: string) => (profile === "default" ? "hermes" : `hermes-${slugifyId(profile)}`);
/** Providers whose logo is another provider's: legacy and ACP-adapter ids of the same agent. */
const ICON_ALIASES: Record<string, string> = {
"claude-acp": "claude",
"codex-acp": "codex",
"kimi-code": "kimi",
"opencode-v2": "opencode",
};
/** The agent's logo; custom agents get the generic agents icon, Hermes profiles Hermes'. */
export function providerIcon(provider: string): string {
const id = ICON_ALIASES[provider] ?? (provider.startsWith("hermes-") ? "hermes" : provider);
return isIconName(`agent-${id}`) ? `agent-${id}` : "toolwindow-agents";
}
export const isBusy = (s: AgentStatus) => s === "running" || s === "starting" || s === "needsInput";
export const isInterrupted = (t: Pick<AgentTask, "status" | "interrupted"> | null | undefined) =>
t?.status === "ready" && !!t.interrupted;
export const isWaitingForNetwork = (t: Pick<AgentTask, "status" | "retry"> | null | undefined) =>
!!t && isBusy(t.status) && t.retry?.deadlineMs != null;
export interface TaskGroup {
status: "needsInput" | "failed" | "limited" | "running" | "interrupted" | "ready" | "archived";
label: string;
tasks: AgentTask[];
}
/** Groups in attention order: what waits for the user comes first. */
const GROUPS: Array<[TaskGroup["status"], string, AgentStatus[]]> = [
["needsInput", "Needs Input", ["needsInput"]],
["failed", "Failed", ["failed"]],
["limited", "Usage Limit", ["limited"]],
["running", "Running", ["running", "starting"]],
["interrupted", "Interrupted", []],
["ready", "Ready to Review", ["ready"]],
["archived", "Archived", ["archived"]],
];
const GROUP_RANK = new Map<TaskGroup["status"], number>(GROUPS.map(([status], rank) => [status, rank]));
/** The group a status is shown in (`starting` runs). */
const groupStatus = (status: AgentStatus): TaskGroup["status"] =>
GROUPS.find(([, , members]) => members.includes(status))?.[0] ?? "ready";
/** The group a task is shown in (`ready` with `interrupted` goes to `interrupted`). */
export const taskGroupStatus = (task: Pick<AgentTask, "status" | "interrupted">): TaskGroup["status"] =>
isInterrupted(task) ? "interrupted" : groupStatus(task.status);
export const taskAttentionRank = (task: Pick<AgentTask, "status" | "interrupted">): number =>
GROUP_RANK.get(taskGroupStatus(task)) ?? GROUPS.length;
export function groupTasks(tasks: Iterable<AgentTask>): TaskGroup[] {
const sorted = [...tasks].sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
return GROUPS.map(([status, label]) => ({
status,
label,
tasks: sorted.filter((t) => taskGroupStatus(t) === status),
})).filter((g) => g.tasks.length > 0);
}
/** Whether `task` runs outside the project root (its own worktree, or an imported subfolder). */
export const hasTaskTerminal = (task: AgentTask, projectRoot?: string | null) =>
task.isolation === "worktree" || (!!projectRoot && task.cwd !== projectRoot);
/** `entries` with `entry` at `index` (appended when `index` is the length; gaps wait for a reload). */
export function upsertEntry(entries: AgentEntry[], index: number, entry: AgentEntry): AgentEntry[] | null {
if (index > entries.length) return null;
const next = entries.slice();
next[index] = entry;
return next;
}
/** `shown` with `text`, which follows its first `from` units, added; `null` when `shown` is too short to take it. */
function grown(shown: string, from: number, text: string): string | null {
if (shown.length < from) return null;
return shown.length >= from + text.length ? shown : shown + text.slice(shown.length - from);
}
/**
* `entries` with `text` appended to the message at `index` (or to the output of the tool call
* there), which read its first `from` UTF-16 units when the backend last sent it; `null` when
* the copy here can't take it (a gap, or another kind of entry), so the conversation is
* loaded again. A copy loaded while the text streamed may already hold some of it.
*/
export function appendEntry(entries: AgentEntry[], index: number, from: number, text: string): AgentEntry[] | null {
const entry = entries[index];
let next: AgentEntry;
if (entry?.type === "tool") {
const output = grown(entry.output ?? "", from, text);
if (output === null) return null;
if (output === entry.output) return entries;
next = { ...entry, output };
} else if (entry?.type === "agent" || entry?.type === "thought") {
const added = grown(entry.text, from, text);
if (added === null) return null;
if (added === entry.text) return entries;
next = { ...entry, text: added };
} else {
return null;
}
const copy = entries.slice();
copy[index] = next;
return copy;
}
/** "agent/fix-lexer" → "fix-lexer". */
export const branchLabel = (branch: string | null) => (branch ?? "").replace(/^agent\//, "");
export function statusLabel(s: AgentStatus): string {
switch (s) {
case "starting":
return "Starting";
case "running":
return "Running";
case "needsInput":
return "Needs input";
case "ready":
return "Ready";
case "failed":
return "Failed";
case "limited":
return "Usage limit";
case "archived":
return "Archived";
}
}
export function taskStatusLabel(task: Pick<AgentTask, "status" | "interrupted" | "retry">): string {
if (isWaitingForNetwork(task)) return "Waiting for network";
if (isInterrupted(task)) return "Interrupted";
return statusLabel(task.status);
}
export function interruptionBannerText(reason: InterruptionReason, wasWaitingForInput = false): string {
if (wasWaitingForInput) return "Interrupted while waiting for your approval.";
switch (reason) {
case "windowClose":
return "Interrupted when the project window closed.";
case "quit":
return "Interrupted when OpenIDEA quit.";
case "restart":
return "Interrupted when OpenIDEA restarted.";
case "backendUpgrade":
return "Interrupted when the OpenIDEA backend upgraded.";
case "backendStop":
return "Interrupted when the OpenIDEA backend stopped.";
case "unexpectedExit":
return "Interrupted when OpenIDEA exited unexpectedly.";
case "networkTimeout":
return "Paused after the network retry window expired.";
}
}
export function recoveryDividerLabel(reason: InterruptionReason): string {
switch (reason) {
case "windowClose":
return "Resumed after window close";
case "quit":
return "Resumed after OpenIDEA quit";
case "restart":
return "Resumed after OpenIDEA restart";
case "backendUpgrade":
return "Resumed after backend upgrade";
case "backendStop":
return "Resumed after backend stop";
case "unexpectedExit":
return "Resumed after unexpected exit";
case "networkTimeout":
return "Resumed after network drop";
}
}
/** Index of each turn-starting message in `entries`: its turn's number (messages steered into a running turn don't start one). */
export function turnNumbers(entries: AgentEntry[]): Map<number, number> {
const out = new Map<number, number>();
entries.forEach((e, i) => {
if (e.type === "user" && !e.steered) out.set(i, out.size);
});
return out;
}
export interface ReplyTurn {
turn: number;
prompt: Extract<AgentEntry, { type: "user" }>;
steered: boolean;
}
export interface ReplyTimes {
sentMs: number | null;
doneMs: number | null;
}
/** When the turn behind each agent reply was asked and finished, by entry index. */
export function replyTimes(entries: AgentEntry[]): Map<number, ReplyTimes> {
const out = new Map<number, ReplyTimes>();
let current: Extract<AgentEntry, { type: "user" }> | null = null;
entries.forEach((entry, i) => {
if (entry.type === "user" && !entry.steered) current = entry;
else if (entry.type === "agent" && current)
out.set(i, {
sentMs: current.sentMs ?? null,
doneMs: current.doneMs ?? null,
});
});
return out;
}
/** Only the last reply of a turn offers actions that change the conversation. */
export function replyTurns(entries: AgentEntry[]): Map<number, ReplyTurn> {
const out = new Map<number, ReplyTurn>();
let current: ReplyTurn | null = null;
let previous: number | null = null;
let turn = 0;
entries.forEach((entry, i) => {
if (entry.type === "user") {
if (!entry.steered) {
current = { turn: turn++, prompt: entry, steered: false };
previous = null;
} else if (current) current.steered = true;
} else if (entry.type === "agent" && entry.text.trim() && current) {
if (previous !== null) out.delete(previous);
out.set(i, current);
previous = i;
}
});
return out;
}
export function replyOperations(task: AgentTask, reply: ReplyTurn | undefined, turnCount: number) {
const idle = task.status !== "archived" && !isBusy(task.status) && !!reply;
const latest = reply?.turn === turnCount - 1;
const { fork = false, rollback = false } = task.capabilities ?? {};
return {
regenerate:
idle &&
latest &&
rollback &&
!reply.steered &&
!!reply.prompt.text.trim() &&
reply.prompt.attachments.length === (reply.prompt.images?.length ?? 0),
fork: idle && fork && (rollback || latest),
};
}
/** "3m", "2h", "5d" since `ms`. */
export function age(ms: number, now = Date.now()): string {
const s = Math.max(0, Math.round((now - ms) / 1000));
if (s < 60) return "now";
const m = Math.round(s / 60);
if (m < 60) return `${m}m`;
const h = Math.round(m / 60);
if (h < 24) return `${h}h`;
return `${Math.round(h / 24)}d`;
}