A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): start named sessions with prompts (#546)
Sebastian Müller05aa747fec43
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex b6d35e421f..a8752bb4e3 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -2,6 +2,7 @@## [Unreleased]+- Added `/new` support for an optional stable session name and initial prompt.- Changed collapsed edit and IPython tool calls to show compact per-file line-change summaries while keeping full diffs available when expanded.- Changed session search to rank exact name and first-message matches before prefix, substring, and stricter transcript fuzzy matches.- Fixed daemon startup failing when an interrupted supervisor left an empty ownership directory.diff --git a/packages/coding-agent/src/core/new-session-command.ts b/packages/coding-agent/src/core/new-session-command.tsnew file mode 100644index 0000000000..92084b438e--- /dev/null+++ b/packages/coding-agent/src/core/new-session-command.ts@@ -0,0 +1,54 @@+export interface ParsedNewSessionCommand {+ name?: string;+ prompt?: string;+}++/** Parse /new's raw suffix while preserving the initial prompt verbatim. */+export function parseNewSessionCommand(rawArgs: string): ParsedNewSessionCommand {+ if (!rawArgs) return {};+ const args = consumeNewSeparator(rawArgs, "Expected whitespace after /new");+ if (!args.startsWith("-")) return { prompt: args };+ if (/^--(?:\s|$)/.test(args)) return { prompt: requireNewPrompt(args.slice(2)) };++ const option = args.match(/^\S+/)?.[0] ?? args;+ if (!/^--name(?:\s|$)/.test(args)) throw new Error(`Unknown /new option: ${option}`);+ let rest = consumeNewSeparator(args.slice(6), 'Missing value for /new option "--name"');+ if (/^--name(?:\s|$)/.test(rest)) throw new Error('Duplicate /new option: "--name"');+ if (!rest || rest.startsWith("-")) throw new Error('Missing value for /new option "--name"');++ let name: string;+ if (rest[0] === '"' || rest[0] === "'") {+ const quote = rest[0];+ const closingQuote = rest.indexOf(quote, 1);+ if (closingQuote === -1) throw new Error("Unterminated quote in /new --name");+ name = rest.slice(1, closingQuote);+ rest = rest.slice(closingQuote + 1);+ } else {+ const match = /^(\S+)([\s\S]*)$/.exec(rest)!;+ name = match[1];+ rest = match[2];+ }+ if (!name.trim()) throw new Error('/new option "--name" cannot be empty');+ if (!rest) return { name };+ rest = consumeNewSeparator(rest, 'Expected "--" before the /new prompt');+ if (/^--name(?:\s|$)/.test(rest)) throw new Error('Duplicate /new option: "--name"');+ if (!/^--(?:\s|$)/.test(rest)) {+ if (rest.startsWith("-")) throw new Error(`Unknown /new option: ${rest.match(/^\S+/)?.[0] ?? rest}`);+ throw new Error('Expected "--" before the /new prompt');+ }+ return { name, prompt: requireNewPrompt(rest.slice(2)) };+}++function consumeNewSeparator(value: string, error: string): string {+ let offset = /^[ \t]*/.exec(value)?.[0].length ?? 0;+ if (value.startsWith("\r\n", offset)) offset += 2;+ else if (value[offset] === "\n" || value[offset] === "\r") offset++;+ if (offset === 0) throw new Error(error);+ return value.slice(offset);+}++function requireNewPrompt(value: string): string {+ const prompt = consumeNewSeparator(value, 'Missing prompt after /new "--"');+ if (!prompt.trim()) throw new Error('Missing prompt after /new "--"');+ return prompt;+}diff --git a/packages/coding-agent/src/core/slash-commands.ts b/packages/coding-agent/src/core/slash-commands.tsindex bd21280f00..aedf0e18ad 100644--- a/packages/coding-agent/src/core/slash-commands.ts+++ b/packages/coding-agent/src/core/slash-commands.ts@@ -80,7 +80,12 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [argumentHint: "[list|login <name>|logout <name>]",takesArgument: true,},- { name: "new", description: "Start a new session" },+ {+ name: "new",+ description: "Start a new session, optionally named and/or with an initial prompt",+ argumentHint: '[--name "session name" --] [prompt]',+ takesArgument: true,+ },{name: "compact",description: "Compact the session context; optional instructions focus the summary",@@ -149,15 +154,10 @@ const BUILTIN_SLASH_COMMAND_ALIAS_TO_NAME = new Map();export function parseSlashCommand(text: string): ParsedSlashCommand | undefined {- if (!text.startsWith("/")) {- return undefined;- }- const spaceIndex = text.indexOf(" ");- const name = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);- if (!name) {- return undefined;- }- return { name, args: spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim() };+ if (!text.startsWith("/")) return undefined;+ const match = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(text);+ if (!match) return undefined;+ return { name: match[1], args: (match[2] ?? "").trim() };}export function resolveBuiltinSlashCommandName(name: string): string {@@ -169,6 +169,8 @@ export function isBuiltinSlashCommandName(name: string): boolean {}export function builtinSlashCommandTakesArgument(name: string): boolean {+ // /clear remains the no-argument compatibility alias even though /new accepts arguments.+ if (name === "clear") return false;return BUILTIN_SLASH_COMMAND_BY_NAME.get(resolveBuiltinSlashCommandName(name))?.takesArgument === true;}diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 6dc28f1c3a..2efaaa3c4b 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -105,6 +105,7 @@ import {HEARTBEAT_PROMPT_PREVIEW_LABEL,} from "../../core/messages.js";import { findExactModelReferenceMatch, resolveModelScopeFromModels } from "../../core/model-resolver.js";+import { parseNewSessionCommand } from "../../core/new-session-command.js";import { resolvePrimeAgentTracesBaseUrl } from "../../core/prime-inference-auth.js";import { resolvePrimeInferencePostLoginModelAction } from "../../core/prime-inference-model-selection.js";import { parseCommandArgs } from "../../core/prompt-templates.js";@@ -4500,9 +4501,27 @@ export class InteractiveMode {await this.handleMcpCommand(commandArgs);return;}- if (commandName === "new" && !commandArgs) {+ if (slashCommand?.name === "clear") {+ if (commandArgs) {+ this.editor.setText(text);+ this.showError("Usage: /clear");+ } else {+ this.editor.setText("");+ await this.handleClearCommand();+ }+ return;+ }+ if (slashCommand?.name === "new") {+ let options: ReturnType<typeof parseNewSessionCommand>;+ try {+ options = parseNewSessionCommand(text.slice(4));+ } catch (error) {+ this.editor.setText(text);+ this.showError(error instanceof Error ? error.message : String(error));+ return;+ }this.editor.setText("");- await this.handleClearCommand();+ await this.handleClearCommand(options);return;}if (commandName === "compact") {@@ -9648,19 +9667,40 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}${shorthis.ui.requestRender();}- private async handleClearCommand(): Promise<void> {+ private async handleClearCommand(options: { name?: string; prompt?: string } = {}): Promise<void> {this.stopWorkingLoader();+ const retainedImages = options.prompt ? this.getPromptStashImages(options.prompt) : [];+ const restorePrompt = () => {+ if (!options.prompt) return;+ for (const [id, image] of retainedImages) this.pastedImages.set(id, image);+ this.editor.setText(options.prompt);+ };+ let created = false;try {const result = await this.agentConnection.newSession();if (result.cancelled) {+ restorePrompt();return;}+ created = true;await this.renderCurrentSessionState();+ for (const [id, image] of retainedImages) this.pastedImages.set(id, image);this.chatContainer.addChild(new Spacer(1));this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ New session started")}`, 1, 1));this.ui.requestRender();+ const images = options.prompt ? this.collectImagesFor(options.prompt) : undefined;+ if (options.name) await this.agentConnection.setSessionName(options.name);+ if (options.prompt) {+ this.editor.addToHistory?.(options.prompt);+ await this.agentConnection.prompt(options.prompt, { images });+ }} catch (error: unknown) {- await this.handleFatalRuntimeError("Failed to create session", error);+ if (!created) {+ await this.handleFatalRuntimeError("Failed to create session", error);+ return;+ }+ restorePrompt();+ this.showError(error instanceof Error ? error.message : String(error));}}diff --git a/packages/coding-agent/test/interactive-mode-clear-command.test.ts b/packages/coding-agent/test/interactive-mode-clear-command.test.tsindex 7db0cde041..28aa590613 100644--- a/packages/coding-agent/test/interactive-mode-clear-command.test.ts+++ b/packages/coding-agent/test/interactive-mode-clear-command.test.ts@@ -7,7 +7,14 @@ type ClearCommandContext = {stopWorkingLoader: () => void;agentConnection: {newSession: () => Promise<{ cancelled: boolean }>;+ setSessionName?: (name: string) => Promise<void>;+ prompt?: (prompt: string, options?: { images?: unknown[] }) => Promise<void>;};+ editor?: { setText: (text: string) => void; addToHistory?: (text: string) => void };+ collectImagesFor?: (text: string) => unknown[] | undefined;+ getPromptStashImages?: (text: string) => readonly (readonly [number, unknown])[];+ pastedImages?: Map<number, unknown>;+ showError?: (message: string) => void;renderCurrentSessionState: () => Promise<void>;chatContainer: Container;ui: { requestRender: () => void };@@ -15,7 +22,7 @@ type ClearCommandContext = {};type InteractiveModePrototype = {- handleClearCommand(this: ClearCommandContext): Promise<void>;+ handleClearCommand(this: ClearCommandContext, options?: { name?: string; prompt?: string }): Promise<void>;};const interactiveModePrototype = InteractiveMode.prototype as unknown as InteractiveModePrototype;@@ -36,9 +43,19 @@ describe("InteractiveMode /clear", () => {const newSession = vi.fn(async () => ({ cancelled: false }));const renderCurrentSessionState = vi.fn(async () => {});const requestRender = vi.fn();+ const prompt = vi.fn(async () => {});+ const image = {};+ const pastedImages = new Map([[7, image]]);+ const setSessionName = vi.fn(async () => pastedImages.clear());+ const collectImagesFor = vi.fn(() => [...pastedImages.values()]);+ const addToHistory = vi.fn();const context: ClearCommandContext = {stopWorkingLoader: vi.fn(),- agentConnection: { newSession },+ agentConnection: { newSession, setSessionName, prompt },+ editor: { setText: vi.fn(), addToHistory },+ collectImagesFor,+ getPromptStashImages: vi.fn(() => [[7, image] as const]),+ pastedImages,renderCurrentSessionState,chatContainer: new Container(),ui: { requestRender },@@ -47,20 +64,31 @@ describe("InteractiveMode /clear", () => {}),};- await interactiveModePrototype.handleClearCommand.call(context);+ await interactiveModePrototype.handleClearCommand.call(context, {+ name: "stable",+ prompt: "-- exact\n text [image #7] ",+ });expect(context.stopWorkingLoader).toHaveBeenCalledWith();expect(newSession).toHaveBeenCalledWith();expect(renderCurrentSessionState).toHaveBeenCalledWith();+ expect(setSessionName).toHaveBeenCalledWith("stable");+ expect(addToHistory).toHaveBeenCalledWith("-- exact\n text [image #7] ");+ expect(prompt).toHaveBeenCalledWith("-- exact\n text [image #7] ", { images: [image] });+ expect(setSessionName.mock.invocationCallOrder[0]).toBeLessThan(prompt.mock.invocationCallOrder[0]);expect(requestRender).toHaveBeenCalledWith();expect(renderAll(context.chatContainer)).toContain("New session started");});it("does not rerender when the connection reports cancellation", async () => {const newSession = vi.fn(async () => ({ cancelled: true }));+ const setText = vi.fn();const context: ClearCommandContext = {stopWorkingLoader: vi.fn(),agentConnection: { newSession },+ editor: { setText },+ getPromptStashImages: vi.fn(() => []),+ pastedImages: new Map(),renderCurrentSessionState: vi.fn(async () => {}),chatContainer: new Container(),ui: { requestRender: vi.fn() },@@ -69,9 +97,10 @@ describe("InteractiveMode /clear", () => {}),};- await interactiveModePrototype.handleClearCommand.call(context);+ await interactiveModePrototype.handleClearCommand.call(context, { prompt: "keep me" });expect(newSession).toHaveBeenCalledWith();+ expect(setText).toHaveBeenCalledWith("keep me");expect(context.renderCurrentSessionState).not.toHaveBeenCalled();expect(context.ui.requestRender).not.toHaveBeenCalled();expect(context.chatContainer.children).toHaveLength(0);diff --git a/packages/coding-agent/test/slash-commands.test.ts b/packages/coding-agent/test/slash-commands.test.tsindex c15e14c5dd..421bc3b6bc 100644--- a/packages/coding-agent/test/slash-commands.test.ts+++ b/packages/coding-agent/test/slash-commands.test.ts@@ -1,4 +1,5 @@import { describe, expect, test } from "vitest";+import { parseNewSessionCommand } from "../src/core/new-session-command.js";import {BUILTIN_SLASH_COMMANDS,builtinSlashCommandTakesArgument,@@ -70,7 +71,7 @@ describe("built-in slash commands", () => {expect(builtinSlashCommandTakesArgument("thinking")).toBe(true);expect(builtinSlashCommandTakesArgument("heartbeat")).toBe(true);expect(builtinSlashCommandTakesArgument("mcp")).toBe(true);- expect(builtinSlashCommandTakesArgument("new")).toBe(false);+ expect(builtinSlashCommandTakesArgument("new")).toBe(true);expect(builtinSlashCommandTakesArgument("clear")).toBe(false);});});@@ -81,7 +82,8 @@ describe("slash command aliases", () => {expect(BUILTIN_SLASH_COMMANDS.find((command) => command.name === "usage")).toBeUndefined();expect(BUILTIN_SLASH_COMMANDS.find((command) => command.name === "rename")).toBeUndefined();expect(BUILTIN_SLASH_COMMANDS.find((command) => command.name === "new")).toMatchObject({- description: "Start a new session",+ description: "Start a new session, optionally named and/or with an initial prompt",+ argumentHint: '[--name "session name" --] [prompt]',aliases: ["clear"],});expect(BUILTIN_SLASH_COMMANDS.find((command) => command.name === "context")).toMatchObject({@@ -111,6 +113,7 @@ describe("slash command aliases", () => {const parsed = parseSlashCommand("/clear");expect(parsed).toEqual({ name: "clear", args: "" });+ expect(parseSlashCommand("/new\n multiline prompt")).toEqual({ name: "new", args: "multiline prompt" });expect(isBuiltinSlashCommandName("clear")).toBe(true);expect(resolveBuiltinSlashCommandName("clear")).toBe("new");expect(resolveSlashCommand(parsed!)).toEqual({@@ -119,6 +122,18 @@ describe("slash command aliases", () => {originalName: "clear",isAlias: true,});+ expect(parseNewSessionCommand(" write a\n multiline prompt ")).toEqual({+ prompt: "write a\n multiline prompt ",+ });+ expect(parseNewSessionCommand(" --name stable")).toEqual({ name: "stable" });+ expect(parseNewSessionCommand(' --name "stable name" -- \n --keep\nformat ')).toEqual({+ name: "stable name",+ prompt: " --keep\nformat ",+ });+ expect(() => parseNewSessionCommand(" --name")).toThrow("Missing value");+ expect(() => parseNewSessionCommand(' --name "one" --name "two"')).toThrow("Duplicate");+ expect(() => parseNewSessionCommand(" --other value")).toThrow("Unknown /new option");+ expect(() => parseNewSessionCommand(' --name "broken')).toThrow("Unterminated quote");});test("resolves /thinking to /effort through the alias path", () => {