Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(subagent): tag internal orchestration messages and filter from user-facing history

yushend392238be30c
diff --git a/apps/desktop/electron/ipc/hub.ts b/apps/desktop/electron/ipc/hub.ts
index b038efe81e..68dd5550a6 100644
--- a/apps/desktop/electron/ipc/hub.ts
+++ b/apps/desktop/electron/ipc/hub.ts
@@ -343,6 +343,9 @@ export function registerHubIpcHandlers(): void {
* Get message history for local chat with pagination.
* Returns raw AgentMessageItem[] so the renderer can render content blocks,
* tool results, thinking blocks, etc. — same format as the Gateway RPC.
+ *
+ * Reads from session storage (not in-memory state) so that internal
+ * orchestration messages are excluded by default.
*/
ipcMain.handle('localChat:getHistory', async (_event, agentId: string, options?: { offset?: number; limit?: number }) => {
const h = getHub()
@@ -353,7 +356,7 @@ export function registerHubIpcHandlers(): void {
try {
await agent.ensureInitialized()
- const allMessages = agent.getMessages()
+ const allMessages = agent.loadSessionMessages()
const total = allMessages.length
// Must match DEFAULT_MESSAGES_LIMIT from @multica/sdk/actions/rpc
const limit = options?.limit ?? 200
diff --git a/src/agent/async-agent.ts b/src/agent/async-agent.ts
index db22b843d0..e7aa7c2ee5 100644
--- a/src/agent/async-agent.ts
+++ b/src/agent/async-agent.ts
@@ -25,8 +25,11 @@ export class AsyncAgent {
});
this.sessionId = this.agent.sessionId;
- // Forward raw AgentEvent and MulticaEvent into the channel
+ // Forward raw AgentEvent and MulticaEvent into the channel.
+ // Suppress forwarding during internal runs to avoid leaking
+ // orchestration messages to the frontend/real-time stream.
this.agent.subscribeAll((event: AgentEvent | MulticaEvent) => {
+ if (this.agent.isInternalRun) return;
this.channel.send(event);
});
}
@@ -57,6 +60,29 @@ export class AsyncAgent {
});
}
+ /**
+ * Write an internal message to agent (non-blocking, serialized queue).
+ * Messages are persisted with `internal: true` and rolled back from
+ * in-memory state. Events are suppressed from the real-time stream.
+ */
+ writeInternal(content: string): void {
+ if (this._closed) throw new Error("Agent is closed");
+
+ this.queue = this.queue
+ .then(async () => {
+ if (this._closed) return;
+ const result = await this.agent.runInternal(content);
+ await this.agent.flushSession();
+ if (result.error) {
+ this.channel.send({ id: uuidv7(), content: `[error] ${result.error}` });
+ }
+ })
+ .catch((err) => {
+ const message = err instanceof Error ? err.message : String(err);
+ this.channel.send({ id: uuidv7(), content: `[error] ${message}` });
+ });
+ }
+
/** Continuously read channel stream (AgentEvent + error Messages) */
read(): AsyncIterable<ChannelItem> {
return this.channel;
@@ -226,12 +252,20 @@ export class AsyncAgent {
}
/**
- * Get all messages from the current session.
+ * Get all messages from the current session (in-memory state).
*/
getMessages(): AgentMessage[] {
return this.agent.getMessages();
}
+ /**
+ * Load messages from session storage with filtering.
+ * By default, internal messages are excluded.
+ */
+ loadSessionMessages(options?: { includeInternal?: boolean }): AgentMessage[] {
+ return this.agent.loadSessionMessages(options);
+ }
+
/**
* Get current provider and model information.
*/
diff --git a/src/agent/cli/commands/session.ts b/src/agent/cli/commands/session.ts
index e726cf6002..149143c732 100644
--- a/src/agent/cli/commands/session.ts
+++ b/src/agent/cli/commands/session.ts
@@ -22,7 +22,7 @@ ${cyan("Usage:")} multica session <command> [options]
${cyan("Commands:")}
${yellow("list")} List all sessions
- ${yellow("show")} <id> Show session details
+ ${yellow("show")} <id> Show session details (use --show-internal to include internal messages)
${yellow("delete")} <id> Delete a session
${yellow("help")} Show this help
@@ -122,7 +122,7 @@ function cmdList() {
console.log(`${dim("Resume with:")} multica --session <id>`);
}
-function cmdShow(sessionId: string | undefined) {
+function cmdShow(sessionId: string | undefined, showInternal = false) {
if (!sessionId) {
console.error("Error: Session ID is required");
console.error("Usage: multica session show <id>");
@@ -160,14 +160,25 @@ function cmdShow(sessionId: string | undefined) {
console.log(cyan("─".repeat(60)));
console.log("");
- // Parse and display messages
+ // Parse and display messages as SessionEntry objects
for (const line of lines) {
try {
- const msg = JSON.parse(line);
+ const entry = JSON.parse(line);
+
+ // Only display message entries
+ if (entry.type !== "message") continue;
+
+ // Skip internal messages unless --show-internal
+ if (entry.internal && !showInternal) continue;
+
+ const msg = entry.message;
+ if (!msg) continue;
+
const role = msg.role || "unknown";
const roleColor = role === "user" ? green : role === "assistant" ? cyan : dim;
+ const internalTag = entry.internal ? dim(" [internal]") : "";
- console.log(`${roleColor(`[${role}]`)}`);
+ console.log(`${roleColor(`[${role}]`)}${internalTag}`);
if (typeof msg.content === "string") {
// Truncate long content
@@ -238,6 +249,7 @@ function cmdDelete(sessionId: string | undefined) {
export async function sessionCommand(args: string[]): Promise<void> {
const command = (args[0] || "help") as Command;
const arg1 = args[1];
+ const showInternal = args.includes("--show-internal");
if (args.includes("--help") || args.includes("-h")) {
printHelp();
@@ -249,7 +261,7 @@ export async function sessionCommand(args: string[]): Promise<void> {
cmdList();
break;
case "show":
- cmdShow(arg1);
+ cmdShow(arg1, showInternal);
break;
case "delete":
cmdDelete(arg1);
diff --git a/src/agent/runner.ts b/src/agent/runner.ts
index 65fd528b9b..8955b04c82 100644
--- a/src/agent/runner.ts
+++ b/src/agent/runner.ts
@@ -84,6 +84,10 @@ export class Agent {
private readonly stderr: NodeJS.WritableStream;
private initialized = false;
+ // Internal run state
+ private _internalRun = false;
+ private _runMutex: Promise<void> = Promise.resolve();
+
// MulticaEvent subscribers (parallel to PiAgentCore's subscriber list)
// Typed as AgentEvent | MulticaEvent to match subscribeAll() callback signature
private multicaListeners: Array<(event: AgentEvent | MulticaEvent) => void> = [];
@@ -353,6 +357,48 @@ export class Agent {
}
async run(prompt: string): Promise<AgentRunResult> {
+ // Run-level mutex: prevents concurrent run/runInternal from mis-tagging messages
+ return this.withRunMutex(() => this._run(prompt));
+ }
+
+ /**
+ * Run a prompt as an internal turn.
+ * Messages are persisted with `internal: true` and rolled back from
+ * in-memory state after the turn completes, so they do not pollute
+ * the main conversation context.
+ */
+ async runInternal(prompt: string): Promise<AgentRunResult> {
+ return this.withRunMutex(async () => {
+ const messageCountBefore = this.agent.state.messages.length;
+ this._internalRun = true;
+ try {
+ const result = await this._run(prompt);
+ return result;
+ } finally {
+ this._internalRun = false;
+ // Roll back internal messages from in-memory state
+ const current = this.agent.state.messages;
+ if (current.length > messageCountBefore) {
+ this.agent.replaceMessages(current.slice(0, messageCountBefore));
+ }
+ }
+ });
+ }
+
+ private async withRunMutex<T>(fn: () => Promise<T>): Promise<T> {
+ // Chain on the mutex so only one run executes at a time
+ const prev = this._runMutex;
+ let resolve: () => void;
+ this._runMutex = new Promise<void>((r) => { resolve = r; });
+ await prev;
+ try {
+ return await fn();
+ } finally {
+ resolve!();
+ }
+ }
+
+ private async _run(prompt: string): Promise<AgentRunResult> {
await this.ensureInitialized();
this.output.state.lastAssistantText = "";
@@ -442,8 +488,10 @@ export class Agent {
private handleSessionEvent(event: AgentEvent) {
if (event.type === "message_end") {
const message = event.message as AgentMessage;
- this.session.saveMessage(message);
- if (message.role === "assistant") {
+ this.session.saveMessage(message, this._internalRun ? { internal: true } : undefined);
+ // Skip compaction during internal runs — internal messages will be
+ // rolled back from memory afterwards, so compacting now would be incorrect.
+ if (message.role === "assistant" && !this._internalRun) {
void this.maybeCompact();
}
}
@@ -510,6 +558,11 @@ export class Agent {
return this.agent.state.tools?.map(t => t.name) ?? [];
}
+ /** Whether the agent is currently executing an internal run */
+ get isInternalRun(): boolean {
+ return this._internalRun;
+ }
+
/** Ensure session messages are loaded from disk (idempotent) */
async ensureInitialized(): Promise<void> {
if (this.initialized) return;
@@ -521,11 +574,19 @@ export class Agent {
this.initialized = true;
}
- /** Get all messages from the current session */
+ /** Get all messages from the current session (in-memory state) */
getMessages(): AgentMessage[] {
return this.agent.state.messages.slice();
}
+ /**
+ * Load messages from session storage with filtering.
+ * By default, internal messages are excluded.
+ */
+ loadSessionMessages(options?: { includeInternal?: boolean }): AgentMessage[] {
+ return this.session.loadMessages(options);
+ }
+
/**
* Get all skills with their eligibility status.
* Returns empty array if skills are disabled.
diff --git a/src/agent/session/session-manager.ts b/src/agent/session/session-manager.ts
index eece48b1ff..6c3c49ae9d 100644
--- a/src/agent/session/session-manager.ts
+++ b/src/agent/session/session-manager.ts
@@ -167,11 +167,15 @@ export class SessionManager {
return repairSessionFileIfNeeded({ sessionFile: filePath, warn });
}
- loadMessages(): AgentMessage[] {
+ loadMessages(options?: { includeInternal?: boolean }): AgentMessage[] {
const entries = this.loadEntries();
let messages = entries
- .filter((entry) => entry.type === "message")
- .map((entry) => entry.message);
+ .filter((entry) => {
+ if (entry.type !== "message") return false;
+ if (!options?.includeInternal && entry.internal) return false;
+ return true;
+ })
+ .map((entry) => (entry as { type: "message"; message: AgentMessage }).message);
messages = sanitizeToolCallInputs(messages);
messages = sanitizeToolUseResultPairing(messages);
return messages;
@@ -203,11 +207,16 @@ export class SessionManager {
);
}
- saveMessage(message: AgentMessage) {
+ saveMessage(message: AgentMessage, options?: { internal?: boolean }) {
void this.enqueue(() =>
appendEntry(
this.sessionId,
- { type: "message", message, timestamp: Date.now() },
+ {
+ type: "message",
+ message,
+ timestamp: Date.now(),
+ ...(options?.internal ? { internal: true } : {}),
+ },
{ baseDir: this.baseDir },
),
);
diff --git a/src/agent/session/types.ts b/src/agent/session/types.ts
index 2d31190299..f347864962 100644
--- a/src/agent/session/types.ts
+++ b/src/agent/session/types.ts
@@ -11,7 +11,7 @@ export type SessionMeta = {
};
export type SessionEntry =
- | { type: "message"; message: AgentMessage; timestamp: number }
+ | { type: "message"; message: AgentMessage; timestamp: number; internal?: boolean }
| { type: "meta"; meta: SessionMeta; timestamp: number }
| {
type: "compaction";
diff --git a/src/agent/subagent/announce.ts b/src/agent/subagent/announce.ts
index ea541d5bfa..fff82b7e49 100644
--- a/src/agent/subagent/announce.ts
+++ b/src/agent/subagent/announce.ts
@@ -260,7 +260,7 @@ export function runCoalescedAnnounceFlow(
return false;
}
- parentAgent.write(message);
+ parentAgent.writeInternal(message);
return true;
} catch (err) {
console.error(`[SubagentAnnounce] Failed to coalesced-announce to parent:`, err);
@@ -308,7 +308,7 @@ export function runSubagentAnnounceFlow(params: SubagentAnnounceParams): boolean
return false;
}
- parentAgent.write(message);
+ parentAgent.writeInternal(message);
return true;
} catch (err) {
console.error(`[SubagentAnnounce] Failed to announce to parent:`, err);