Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

fix(cli): normalize native file outputs

IgnoreMeBut50a0b4a623ec
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index fd3151a1..9f1b4a2b 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -27,6 +27,7 @@ import {
} from '../paths';
import {
conversationLayout,
+ chatAttachmentDirForConversation,
conversationMessageFile,
conversationMessageReadFile,
listProjectIds,
@@ -52,6 +53,11 @@ import {
} from '../util/record_sync_fields';
import { limitNameDisplayText } from '../util/name-limit';
import { versionChatMediaLocalUrlsInText } from '../util/chat-media-url';
+import { isPathAllowed } from '../util/path-sandbox';
+import {
+ persistedCodexOutputCitationPaths,
+ sanitizePersistedCodexFileCitations,
+} from './local_agents/public-output';
const log = createLogger('chats');
// A boot-time stale-state sweep may run twice: once before the first window
@@ -163,10 +169,83 @@ export interface Conversation {
* canonical type is `GroupMessage` from `group_chat/visibility`. */
export type MessageRecord = GroupMessage;
-function _messageForDisplay(message: MessageRecord): MessageRecord {
+interface MessageDisplayContext {
+ citationWorkingDir?: string;
+ allowedCitationRoots: string[];
+}
+
+async function _messageDisplayContext(
+ userId: string,
+ cid: string,
+ projectIdHint?: string | null,
+): Promise<MessageDisplayContext> {
+ const layout = conversationLayout(userId, cid, projectIdHint);
+ const state = await readState(userId, cid, layout.projectId);
+ const allowedCitationRoots = [
+ state.coding_project_dir,
+ ...(state.tool_extra_roots || []),
+ chatAttachmentDirForConversation(userId, cid, layout.projectId),
+ ].filter((root): root is string => typeof root === 'string' && path.isAbsolute(root));
+
+ let workspaceRoot: string | undefined;
+ try {
+ const userWorkspace = await import('./user_workspace');
+ workspaceRoot = userWorkspace.getWorkspacePath(userId, layout.projectId || undefined);
+ if (path.isAbsolute(workspaceRoot)) allowedCitationRoots.push(workspaceRoot);
+ } catch (err) {
+ log.warn(`resolve workspace for legacy Codex output cid=${maskId(cid)}: ${(err as Error).message}`);
+ }
+
+ return {
+ citationWorkingDir: state.coding_project_dir && path.isAbsolute(state.coding_project_dir)
+ ? state.coding_project_dir
+ : workspaceRoot,
+ allowedCitationRoots,
+ };
+}
+
+function _isAuthorizedLegacyOutputFile(candidate: string, allowedRoots: readonly string[]): boolean {
+ if (!path.isAbsolute(candidate) || !isPathAllowed(candidate, allowedRoots)) return false;
+ try { return fs.statSync(candidate).isFile(); }
+ catch { return false; }
+}
+
+function _messageForDisplay(message: MessageRecord, context: MessageDisplayContext): MessageRecord {
if (message.from === 'user') return message;
- const text = versionChatMediaLocalUrlsInText(message.text);
- return text === message.text ? message : { ...message, text };
+ const storedProduced = Array.isArray(message.produced)
+ ? message.produced.filter((item): item is string => typeof item === 'string' && !!item.trim())
+ : [];
+ const produced = [...storedProduced];
+ const producedKeys = new Set(produced.map((item) => path.resolve(item)));
+ const citedOutputs: string[] = [];
+ for (const candidate of persistedCodexOutputCitationPaths(
+ message.text,
+ context.citationWorkingDir,
+ )) {
+ const resolved = path.resolve(candidate);
+ if (!producedKeys.has(resolved)) {
+ if (!_isAuthorizedLegacyOutputFile(resolved, context.allowedCitationRoots)) continue;
+ produced.push(resolved);
+ producedKeys.add(resolved);
+ }
+ citedOutputs.push(resolved);
+ }
+ // A native output citation is an exact publication declaration. Historical
+ // rows predate a separate `published` field, so project only the cited files
+ // into the renderer footer while retaining the complete list as sanitizer
+ // backing. Without a trusted citation, preserve the stored footer verbatim.
+ const displayProduced = citedOutputs.length ? citedOutputs : storedProduced;
+ const text = versionChatMediaLocalUrlsInText(
+ sanitizePersistedCodexFileCitations(message.text, produced, context.citationWorkingDir),
+ );
+ const producedUnchanged = displayProduced.length === storedProduced.length
+ && displayProduced.every((item, index) => item === storedProduced[index]);
+ if (text === message.text && producedUnchanged) return message;
+ return {
+ ...message,
+ text,
+ ...(displayProduced.length ? { produced: displayProduced } : {}),
+ };
}
// ── CRUD ─────────────────────────────────────────────────────────────────
@@ -2025,7 +2104,8 @@ export async function getMessagesPage(
if (page.nextCursor === null) break;
cursor = page.nextCursor;
}
- return { history: history.map(_messageForDisplay), nextCursor };
+ const displayContext = await _messageDisplayContext(userId, cid, projectIdHint);
+ return { history: history.map((message) => _messageForDisplay(message, displayContext)), nextCursor };
}
/** Load from the fixed-size page containing a search hit through the newest
@@ -2053,8 +2133,9 @@ export async function getMessagesPageAtIndex(
const visible = page.records
.map((message, offset) => ({ message, index: pageStart + offset }))
.filter(({ message }) => !message.deleted_at);
+ const displayContext = await _messageDisplayContext(userId, cid, projectIdHint);
return {
- history: visible.map(({ message }) => _messageForDisplay(message)),
+ history: visible.map(({ message }) => _messageForDisplay(message, displayContext)),
// Keep the source JSONL indexes aligned with `history`. The renderer uses
// this as the final navigation identity for old records that predate
// stable message ids/timestamps; filtering a tombstone must not shift the
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 22b2ebf6..8e66cede 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -135,7 +135,10 @@ import {
createPhasedTextState,
resolvedPhasedText,
} from '../local_agents/text-phase';
-import { sanitizeLocalAgentPublicOutput } from '../local_agents/public-output';
+import {
+ CodexFileCitationStreamFilter,
+ normalizeLocalAgentPublicOutput,
+} from '../local_agents/public-output';
import {
buildCliConversationContext,
buildCliDurableInstructions,
@@ -4470,6 +4473,7 @@ async function runActorTurn(
},
});
for (const p of cliOut.produced || []) await onFileWritten(p);
+ if (cliOut.published?.length) onOutputsPublished(cliOut.published);
finalText = cliOut.text;
streamingText = cliOut.text;
cliCommanderHandoff = cliOut.commanderHandoff || null;
@@ -7513,6 +7517,7 @@ async function _runCliAgentTurn(opts: {
error?: string;
aborted?: boolean;
produced?: string[];
+ published?: string[];
commanderHandoff?: import('../local_agents/bridge').CommanderHandoffRequest;
failureKind?: GroupMessageFailureKind;
failureCode?: string;
@@ -7628,6 +7633,9 @@ async function _runCliAgentTurn(opts: {
const textState = createPhasedTextState();
const bufferPublicOutput = runtime.cli === 'hermes';
+ const codexStreamFilter = runtime.cli === 'codex'
+ ? new CodexFileCitationStreamFilter()
+ : null;
let resultText = '';
let aborted = false;
let backendSessionId: string | undefined;
@@ -7676,6 +7684,7 @@ async function _runCliAgentTurn(opts: {
if (typeof (e as any).text === 'string') {
const text = (e as any).text as string;
const phased = appendPhasedText(textState, text, (e as any).phase);
+ const streamText = codexStreamFilter ? codexStreamFilter.push(text) : text;
// Slash-command turns: buffer text-delta in `textState` instead
// of streaming to the bubble. The success-return path below
// either swaps the body for "已发送命令 …" (CLI returned
@@ -7692,11 +7701,13 @@ async function _runCliAgentTurn(opts: {
to: 'final_answer',
});
}
- opts.onProcess({
- type: 'delta',
- text,
- ...(phased.phase ? { phase: phased.phase } : {}),
- });
+ if (streamText) {
+ opts.onProcess({
+ type: 'delta',
+ text: streamText,
+ ...(phased.phase ? { phase: phased.phase } : {}),
+ });
+ }
}
}
break;
@@ -7810,6 +7821,10 @@ async function _runCliAgentTurn(opts: {
opts.onProcess({ type: 'event', event: { stream: 'cli', data: e as unknown as Record<string, unknown> } });
break;
case 'done':
+ if (codexStreamFilter && !slashCommandName) {
+ const streamTail = codexStreamFilter.flush();
+ if (streamTail) opts.onProcess({ type: 'delta', text: streamTail });
+ }
if ((e as any).resumeRejected === true) resumeRejected = true;
if (runtime.cli === 'claude') {
const reportedModel = (e as any).usage?.model;
@@ -7935,18 +7950,26 @@ async function _runCliAgentTurn(opts: {
failureCode: result.cliError || 'missing_cli',
};
}
- const publicText = () => appendCliGeneratedMediaMarkdown(
- sanitizeLocalAgentPublicOutput({
- cli: runtime.cli as LocalCliType,
- text: resolvedPhasedText(textState, resultText),
- userTask: publicTaskBody,
- }),
+ const publicOutput = normalizeLocalAgentPublicOutput({
+ cli: runtime.cli as LocalCliType,
+ text: resolvedPhasedText(textState, resultText),
+ userTask: publicTaskBody,
+ workingDir: opts.workingDir,
+ producedPaths: Array.from(produced),
+ });
+ const publicText = appendCliGeneratedMediaMarkdown(
+ publicOutput.text,
inlineGeneratedImages,
opts.cid,
inlineRemoteMedia.values(),
);
if (result.status === 'cancelled') {
- return { text: publicText(), aborted: true, produced: Array.from(produced) };
+ return {
+ text: publicText,
+ aborted: true,
+ produced: Array.from(produced),
+ published: publicOutput.publishedPaths,
+ };
}
if (result.status === 'failed' || result.status === 'timeout') {
const vars = { name: opts.agent.name || runtime.cli, cli: runtime.cli };
@@ -7966,9 +7989,10 @@ async function _runCliAgentTurn(opts: {
? t('cli_agent.upgrade_required_detail', vars)
: t('cli_agent.run_failed_detail', vars);
return {
- text: publicText(),
+ text: publicText,
error: detail,
produced: Array.from(produced),
+ published: publicOutput.publishedPaths,
failureKind: runtimeFailure === 'upgrade_required' ? 'dependency' : 'runtime',
failureCode: result.status === 'timeout'
? 'cli_timeout'
@@ -7977,17 +8001,19 @@ async function _runCliAgentTurn(opts: {
: 'cli_failed',
};
}
- const finalText = publicText();
+ const finalText = publicText;
if (slashCommandName && _looksLikeNoOutput(finalText)) {
return {
text: t('cli_agent.slash_no_output', { cmd: slashCommandName }),
produced: Array.from(produced),
+ published: publicOutput.publishedPaths,
...(result.commanderHandoff ? { commanderHandoff: result.commanderHandoff } : {}),
};
}
return {
text: finalText,
produced: Array.from(produced),
+ published: publicOutput.publishedPaths,
historySyncEligible: !contextPlan.passthrough,
...(result.commanderHandoff ? { commanderHandoff: result.commanderHandoff } : {}),
};
diff --git a/src/main/features/local_agents/backends/openclaw.ts b/src/main/features/local_agents/backends/openclaw.ts
index db4a2e02..fc2e0c13 100644
--- a/src/main/features/local_agents/backends/openclaw.ts
+++ b/src/main/features/local_agents/backends/openclaw.ts
@@ -33,6 +33,7 @@
*/
import * as crypto from 'node:crypto';
+import { fileURLToPath } from 'node:url';
import { createLogger } from '../../../logger.js';
import { logErrorSummary } from '../../../util/log-redact.js';
import {
@@ -124,6 +125,7 @@ export const openclawBackend: LocalBackend = {
const parsed = parseOpenclawReply(fullStderr);
const replyText = parsed?.text || '';
const media = parsed?.media || [];
+ const files = parsed?.files || [];
const sid = parsed?.sessionId || sessionId;
if (replyText) {
@@ -139,12 +141,24 @@ export const openclawBackend: LocalBackend = {
items: media.map(uri => ({ uri })),
});
}
+ if (files.length) {
+ // OpenClaw's structured attachment envelope can point at arbitrary
+ // documents (PDF/Office/etc.), not only previewable image/video
+ // media. Keep those paths on the generic produced-file channel; the
+ // group-chat boundary validates cwd ownership and existence before
+ // exposing them in the deliverable footer.
+ opts.onEvent({
+ type: 'file-change',
+ source: 'openclaw_attachment',
+ paths: files,
+ });
+ }
const usage = parsed?.usage;
- if (code === 0 && (replyText || media.length)) {
+ if (code === 0 && (replyText || media.length || files.length)) {
return finish('completed', { output: replyText, sessionId: sid, ...(usage ? { usage } : {}) });
}
- if (code === 0 && !replyText && !media.length) {
+ if (code === 0 && !replyText && !media.length && !files.length) {
// Exit clean but no parseable reply → treat as failed so
// the user sees an error bubble instead of an empty turn.
return finish('failed', {
@@ -206,7 +220,7 @@ function hasOpenclawTimeoutArg(args: string[] | undefined): boolean {
*/
export function parseOpenclawReply(stderrText: string):
| null
- | { text: string; media: string[]; sessionId?: string; error?: string; usage?: Record<string, number | string> } {
+ | { text: string; media: string[]; files: string[]; sessionId?: string; error?: string; usage?: Record<string, number | string> } {
if (!stderrText) return null;
const clean = stripAnsi(stderrText);
@@ -230,17 +244,28 @@ export function parseOpenclawReply(stderrText: string):
.map(p => (p && typeof p.text === 'string') ? p.text : '')
.filter(s => s.length)
.join('\n');
- const media = Array.from(new Set((obj.payloads as any[]).flatMap((payload): string[] => {
+ const mediaCandidates = (obj.payloads as any[]).flatMap((payload): string[] => {
+ if (!payload || typeof payload !== 'object') return [];
+ return [payload.media, payload.mediaUrl, payload.mediaUrls]
+ .flatMap(openclawStringValues)
+ .map(value => value.trim())
+ .filter(Boolean);
+ });
+ const explicitFileCandidates = (obj.payloads as any[]).flatMap((payload): string[] => {
if (!payload || typeof payload !== 'object') return [];
- const candidates = [
- typeof payload.mediaUrl === 'string' ? payload.mediaUrl : '',
- ...(Array.isArray(payload.mediaUrls) ? payload.mediaUrls : []),
- ];
- return candidates
- .filter((value): value is string => typeof value === 'string')
+ return [payload.path, payload.filePath]
+ .flatMap(openclawStringValues)
.map(value => value.trim())
.filter(Boolean);
- })));
+ });
+ const media: string[] = [];
+ const files: string[] = [];
+ for (const candidate of mediaCandidates) {
+ const localPath = openclawLocalAttachmentPath(candidate);
+ if (localPath) files.push(localPath);
+ else media.push(candidate);
+ }
+ files.push(...explicitFileCandidates);
const sessionId = obj.meta?.agentMeta?.sessionId
|| obj.meta?.sessionId
|| undefined;
@@ -248,15 +273,42 @@ export function parseOpenclawReply(stderrText: string):
obj.meta?.agentMeta?.usage || obj.meta?.usage,
obj.meta?.agentMeta?.model || obj.meta?.agentMeta?.provider,
);
- return { text, media, sessionId, ...(usage ? { usage } : {}) };
+ return {
+ text,
+ media: Array.from(new Set(media)),
+ files: Array.from(new Set(files)),
+ sessionId,
+ ...(usage ? { usage } : {}),
+ };
}
if (obj && typeof obj === 'object' && typeof obj.error === 'string') {
- return { text: '', media: [], error: String(obj.error) };
+ return { text: '', media: [], files: [], error: String(obj.error) };
}
}
return null;
}
+function openclawStringValues(value: unknown): string[] {
+ if (typeof value === 'string') return [value];
+ if (!Array.isArray(value)) return [];
+ return value.filter((item): item is string => typeof item === 'string');
+}
+
+function openclawLocalAttachmentPath(value: string): string | null {
+ const candidate = value.trim();
+ if (!candidate) return null;
+ if (/^file:/iu.test(candidate)) {
+ try { return fileURLToPath(candidate); } catch { return candidate; }
+ }
+ if (/^(?:https?:|data:)/iu.test(candidate)) return null;
+ // Treat another URI scheme as media rather than resolving it relative to
+ // cwd. Exclude Windows drive paths (`C:\...`) from the scheme check.
+ if (/^[A-Za-z][A-Za-z\d+.-]*:/u.test(candidate) && !/^[A-Za-z]:[\\/]/u.test(candidate)) {
+ return null;
+ }
+ return candidate;
+}
+
/** Normalize openclaw's `meta.agentMeta.usage` block (or a fallback at
* `meta.usage`) into our shared usage shape. openclaw passes through
* whatever the upstream provider returned (Anthropic / OpenAI / etc.),
diff --git a/src/main/features/local_agents/public-output.ts b/src/main/features/local_agents/public-output.ts
index 372f23f8..e567b90e 100644
--- a/src/main/features/local_agents/public-output.ts
+++ b/src/main/features/local_agents/public-output.ts
@@ -1,12 +1,20 @@
/**
* Public-output boundary for local CLI agents.
*
- * External runtimes remain free to emit their native output. Hermes
- * installations in the wild can emit a KSTAR work record alongside the public
- * result. Parse that known wire shape only at the Orkas presentation boundary,
- * leaving the CLI prompt and raw runtime behavior unchanged.
+ * External runtimes remain free to emit their native output. Normalize known
+ * native wire shapes only at the Orkas presentation boundary, leaving the CLI
+ * prompt and raw runtime behavior unchanged:
+ *
+ * - Hermes installations in the wild can emit a KSTAR work record alongside
+ * the public result.
+ * - Codex emits `:codex-file-citation{...}` directives for files it considers
+ * final outputs. Those directives are transport metadata, not user-facing
+ * prose; Orkas turns them into an explicit produced-file selection after
+ * verifying the path was already registered by this turn.
*/
+import * as path from 'node:path';
+
import type { LocalCliType } from './registry.js';
type KstarSectionId = 'K' | 'S' | 'T' | 'A' | 'EXPECTED' | 'R' | 'DELTA' | 'AAR';
@@ -114,14 +122,279 @@ function extractHermesKstarResult(text: string): { matched: boolean; result: str
return { matched: true, result };
}
-export function sanitizeLocalAgentPublicOutput(args: {
+interface CodexFileCitation {
+ path: string;
+ purpose: string;
+}
+
+interface ParsedCodexFileCitationLine {
+ citation: CodexFileCitation;
+ /** Text to keep when the directive is consumed. Empty for a standalone directive. */
+ replacement: string;
+}
+
+const CODEX_FILE_CITATION_PREFIX = ':codex-file-citation{';
+const CODEX_FILE_CITATION_LINE_RE = /^\s*:codex-file-citation\{([\s\S]*)\}\s*$/u;
+const CODEX_FILE_CITATION_ATTR_RE = /([A-Za-z_][\w-]*)\s*=\s*"((?:\\.|[^"\\])*)"/gy;
+
+function decodeCodexAttribute(value: string): string {
+ // Codex currently escapes only quote and backslash in directive attributes.
+ // Preserve unknown escape sequences so a Windows path such as `C:\tmp`
+ // does not silently lose characters if an older runtime emits it verbatim.
+ return value.replace(/\\(["\\])/g, '$1');
+}
+
+function parseCodexFileCitationLine(line: string): CodexFileCitation | null {
+ const match = CODEX_FILE_CITATION_LINE_RE.exec(line);
+ if (!match) return null;
+ const body = match[1];
+ const attributes = new Map<string, string>();
+ let offset = 0;
+ while (offset < body.length) {
+ while (/\s/u.test(body[offset] || '')) offset += 1;
+ if (offset >= body.length) break;
+ CODEX_FILE_CITATION_ATTR_RE.lastIndex = offset;
+ const attribute = CODEX_FILE_CITATION_ATTR_RE.exec(body);
+ if (!attribute || attribute.index !== offset) return null;
+ attributes.set(attribute[1], decodeCodexAttribute(attribute[2]));
+ offset = CODEX_FILE_CITATION_ATTR_RE.lastIndex;
+ }
+ const citationPath = String(attributes.get('path') || '').trim();
+ const purpose = String(attributes.get('purpose') || '').trim();
+ return citationPath && purpose ? { path: citationPath, purpose } : null;
+}
+
+function codexCitationPathIdentity(rawPath: string): string {
+ let value = String(rawPath || '').trim();
+ if (value.startsWith('<') && value.endsWith('>')) value = value.slice(1, -1).trim();
+ try { value = decodeURI(value); } catch { /* preserve malformed legacy text */ }
+ return value.replace(/\\/g, '/');
+}
+
+/**
+ * Besides the current standalone wire shape, some older Codex builds emitted
+ * the directive immediately after a Markdown link to the same file. Keep that
+ * link as prose, but consume the adjacent transport suffix. Requiring an exact
+ * path match keeps ordinary inline examples untouched.
+ */
+function parseCodexFileCitationPresentationLine(line: string): ParsedCodexFileCitationLine | null {
+ const standalone = parseCodexFileCitationLine(line);
+ if (standalone) return { citation: standalone, replacement: '' };
+
+ const markerIndex = line.lastIndexOf(CODEX_FILE_CITATION_PREFIX);
+ if (markerIndex <= 0) return null;
+ const citation = parseCodexFileCitationLine(line.slice(markerIndex));
+ if (!citation) return null;
+ const leading = line.slice(0, markerIndex);
+ const link = /\[[^\]\n]+\]\(([^)\n]+)\)\s*$/u.exec(leading);
+ if (!link) return null;
+ if (codexCitationPathIdentity(link[1]) !== codexCitationPathIdentity(citation.path)) return null;
+ return { citation, replacement: leading.trimEnd() };
+}
+
+function markdownFenceToken(line: string): string {
+ const match = /^ {0,3}(`{3,}|~{3,})/u.exec(line);
+ return match?.[1] || '';
+}
+
+function isClosingMarkdownFence(token: string, openFence: string): boolean {
+ return !!token
+ && token[0] === openFence[0]
+ && token.length >= openFence.length;
+}
+
+function resolveCitationPath(rawPath: string, workingDir?: string): string | null {
+ if (path.isAbsolute(rawPath)) return path.normalize(rawPath);
+ if (!workingDir) return null;
+ return path.resolve(workingDir, rawPath);
+}
+
+function normalizeCodexFileCitations(args: {
+ text: string;
+ producedPaths?: readonly string[];
+ workingDir?: string;
+ removeUnmatched: boolean;
+}): { text: string; publishedPaths: string[] } {
+ const text = String(args.text || '');
+ if (!text.includes(CODEX_FILE_CITATION_PREFIX)) {
+ return { text, publishedPaths: [] };
+ }
+
+ const produced = new Map<string, string>();
+ for (const rawPath of args.producedPaths || []) {
+ if (typeof rawPath !== 'string' || !rawPath.trim()) continue;
+ const resolved = path.resolve(rawPath);
+ produced.set(resolved, resolved);
+ }
+
+ const published = new Set<string>();
+ const kept: string[] = [];
+ let openFence = '';
+ let removed = false;
+ for (const line of text.replace(/\r/g, '').split('\n')) {
+ const fence = markdownFenceToken(line);
+ if (fence) {
+ if (!openFence) openFence = fence;
+ else if (isClosingMarkdownFence(fence, openFence)) openFence = '';
+ kept.push(line);
+ continue;
+ }
+ if (openFence) {
+ kept.push(line);
+ continue;
+ }
+
+ const parsed = parseCodexFileCitationPresentationLine(line);
+ if (!parsed) {
+ kept.push(line);
+ continue;
+ }
+ const citation = parsed.citation;
+ const resolved = resolveCitationPath(citation.path, args.workingDir);
+ const registered = resolved ? produced.get(path.resolve(resolved)) : undefined;
+ if (citation.purpose === 'output' && registered) published.add(registered);
+ if (registered || args.removeUnmatched) {
+ removed = true;
+ if (parsed.replacement) kept.push(parsed.replacement);
+ continue;
+ }
+ kept.push(line);
+ }
+
+ const normalizedText = removed
+ ? kept.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd()
+ : text;
+ return { text: normalizedText, publishedPaths: Array.from(published) };
+}
+
+export interface LocalAgentPublicOutput {
+ text: string;
+ /** Exact current-turn produced files selected by native output metadata. */
+ publishedPaths: string[];
+}
+
+export function normalizeLocalAgentPublicOutput(args: {
cli: LocalCliType;
text: string;
userTask?: string;
-}): string {
+ workingDir?: string;
+ producedPaths?: readonly string[];
+}): LocalAgentPublicOutput {
const text = String(args.text || '');
- if (args.cli !== 'hermes' || !text.trim()) return text;
- if (hasExplicitKstarRequest(String(args.userTask || ''))) return text;
+ if (args.cli === 'codex') {
+ return normalizeCodexFileCitations({
+ text,
+ workingDir: args.workingDir,
+ producedPaths: args.producedPaths,
+ removeUnmatched: true,
+ });
+ }
+ if (args.cli !== 'hermes' || !text.trim()) return { text, publishedPaths: [] };
+ if (hasExplicitKstarRequest(String(args.userTask || ''))) return { text, publishedPaths: [] };
const extracted = extractHermesKstarResult(text);
- return extracted.matched ? extracted.result : text;
+ return {
+ text: extracted.matched ? extracted.result : text,
+ publishedPaths: [],
+ };
+}
+
+export function sanitizeLocalAgentPublicOutput(args: {
+ cli: LocalCliType;
+ text: string;
+ userTask?: string;
+}): string {
+ return normalizeLocalAgentPublicOutput(args).text;
+}
+
+/**
+ * Read-only compatibility projection for messages persisted by builds that
+ * displayed Codex's native directive. Only citations already backed by that
+ * message's structured `produced` list are removed; unmatched prose remains
+ * intact and the canonical JSONL is never rewritten.
+ */
+export function sanitizePersistedCodexFileCitations(
+ text: string,
+ producedPaths?: readonly string[],
+ workingDir?: string,
+): string {
+ return normalizeCodexFileCitations({
+ text,
+ producedPaths,
+ workingDir,
+ removeUnmatched: false,
+ }).text;
+}
+
+/**
+ * Extract only recognized `purpose="output"` paths from persisted Codex
+ * transport metadata. The caller remains responsible for checking existence
+ * and conversation-scoped path authorization before treating them as files.
+ */
+export function persistedCodexOutputCitationPaths(
+ text: string,
+ workingDir?: string,
+): string[] {
+ const source = String(text || '');
+ if (!source.includes(CODEX_FILE_CITATION_PREFIX)) return [];
+
+ const found = new Set<string>();
+ let openFence = '';
+ for (const line of source.replace(/\r/g, '').split('\n')) {
+ const fence = markdownFenceToken(line);
+ if (fence) {
+ if (!openFence) openFence = fence;
+ else if (isClosingMarkdownFence(fence, openFence)) openFence = '';
+ continue;
+ }
+ if (openFence) continue;
+ const parsed = parseCodexFileCitationPresentationLine(line);
+ if (!parsed || parsed.citation.purpose !== 'output') continue;
+ const resolved = resolveCitationPath(parsed.citation.path, workingDir);
+ if (resolved) found.add(path.resolve(resolved));
+ }
+ return Array.from(found);
+}
+
+/**
+ * Streaming filter used by the Codex adapter boundary. It buffers at most one
+ * incomplete line, so a directive split across arbitrary protocol deltas is
+ * never briefly painted as chat prose. Fenced examples remain visible.
+ */
+export class CodexFileCitationStreamFilter {
+ private buffer = '';
+
+ private openFence = '';
+
+ push(chunk: string): string {
+ this.buffer += String(chunk || '').replace(/\r/g, '');
+ let output = '';
+ let newline = this.buffer.indexOf('\n');
+ while (newline >= 0) {
+ const line = this.buffer.slice(0, newline);
+ this.buffer = this.buffer.slice(newline + 1);
+ output += this.filterCompleteLine(line, '\n');
+ newline = this.buffer.indexOf('\n');
+ }
+ return output;
+ }
+
+ flush(): string {
+ const line = this.buffer;
+ this.buffer = '';
+ return this.filterCompleteLine(line, '');
+ }
+
+ private filterCompleteLine(line: string, ending: string): string {
+ const fence = markdownFenceToken(line);
+ if (fence) {
+ if (!this.openFence) this.openFence = fence;
+ else if (isClosingMarkdownFence(fence, this.openFence)) this.openFence = '';
+ return `${line}${ending}`;
+ }
+ if (!this.openFence) {
+ const parsed = parseCodexFileCitationPresentationLine(line);
+ if (parsed) return `${parsed.replacement}${parsed.replacement ? ending : ''}`;
+ }
+ return `${line}${ending}`;
+ }
}
diff --git a/test/main/features/chats.test.ts b/test/main/features/chats.test.ts
index adb1a0fc..ac7dfa29 100644
--- a/test/main/features/chats.test.ts
+++ b/test/main/features/chats.test.ts
@@ -143,6 +143,87 @@ describe('chats › message history tombstones', () => {
expect(fs.readFileSync(historyFile, 'utf8')).toContain(`[poster](${sandboxUrl})`);
});
+ it('projects authorized legacy Codex output directives into produced-file footers', async () => {
+ const chats = await loadChats();
+ const conv = await chats.createConversation(TEST_UID, { title: 'legacy Codex output' });
+ const historyFile = path.join(
+ tmpDir, TEST_UID, 'cloud', 'chats', `${conv.conversation_id}.jsonl`);
+ const deckPath = path.join(tmpDir, 'workspace', 'analysis.pptx');
+ const recoveredDeckPath = path.join(tmpDir, 'workspace', 'recovered.pptx');
+ const supportingPath = path.join(tmpDir, 'workspace', 'supporting.md');
+ const outsidePath = path.join(tmpDir, 'outside', 'private.pdf');
+ fs.mkdirSync(path.dirname(deckPath), { recursive: true });
+ fs.mkdirSync(path.dirname(outsidePath), { recursive: true });
+ fs.writeFileSync(deckPath, 'deck');
+ fs.writeFileSync(recoveredDeckPath, 'recovered deck');
+ fs.writeFileSync(supportingPath, 'supporting notes');
+ fs.writeFileSync(outsidePath, 'private');
+ const groupState = await import('../../../src/main/features/group_chat/state');
+ await groupState.setCodingProjectDir(
+ TEST_UID,
+ conv.conversation_id,
+ path.dirname(deckPath),
+ { explicit: true },
+ );
+ const backedDirective = `:codex-file-citation{path="${deckPath}" purpose="output"}`;
+ const recoveredDirective = `:codex-file-citation{path="${recoveredDeckPath}" purpose="output"}`;
+ const outsideDirective = `:codex-file-citation{path="${outsidePath}" purpose="output"}`;
+ const recoveredLink = `[recovered.pptx](${recoveredDeckPath})`;
+ const rows = [
+ {
+ id: 'm1', ts: '2026-07-10T10:00:00Z', from: 'codex-agent', to: ['user'],
+ text: `演示文稿已经完成。\n\n${backedDirective}`,
+ produced: [supportingPath, deckPath],
+ },
+ {
+ id: 'm2', ts: '2026-07-10T10:01:00Z', from: 'codex-agent', to: ['user'],
+ text: outsideDirective,
+ produced: [deckPath],
+ },
+ {
+ id: 'm3', ts: '2026-07-10T10:02:00Z', from: 'user', to: ['codex-agent'],
+ text: backedDirective,
+ produced: [deckPath],
+ },
+ {
+ id: 'm4', ts: '2026-07-10T10:03:00Z', from: 'codex-agent', to: ['user'],
+ text: `已恢复旧输出。\n\n${recoveredDirective}`,
+ },
+ {
+ id: 'm5', ts: '2026-07-10T10:04:00Z', from: 'codex-agent', to: ['user'],
+ text: `${recoveredLink}${recoveredDirective}`,
+ },
+ ];
+ fs.writeFileSync(historyFile, `${rows.map((row) => JSON.stringify(row)).join('\n')}\n`);
+
+ const page = await chats.getMessagesPage(TEST_UID, conv.conversation_id, 10);
+
+ expect(page.history[0].text).toBe('演示文稿已经完成。');
+ expect(page.history[0].produced).toEqual([deckPath]);
+ expect(page.history[1].text).toBe(outsideDirective);
+ expect(page.history[1].produced).toEqual([deckPath]);
+ expect(page.history[2].text).toBe(backedDirective);
+ expect(page.history[3].text).toBe('已恢复旧输出。');
+ expect(page.history[3].produced).toEqual([recoveredDeckPath]);
+ expect(page.history[4].text).toBe(recoveredLink);
+ expect(page.history[4].produced).toEqual([recoveredDeckPath]);
+
+ const indexed = await chats.getMessagesPageAtIndex(
+ TEST_UID,
+ conv.conversation_id,
+ 3,
+ 10,
+ );
+ expect(indexed.history[3].text).toBe('已恢复旧输出。');
+ expect(indexed.history[3].produced).toEqual([recoveredDeckPath]);
+
+ const persisted = fs.readFileSync(historyFile, 'utf8').trim()
+ .split('\n').map((line) => JSON.parse(line));
+ expect(persisted[0].text).toContain(backedDirective);
+ expect(persisted[3].text).toContain(recoveredDirective);
+ expect(persisted[3].produced).toBeUndefined();
+ });
+
it('fills each page with visible messages while skipping deleted rows', async () => {
const chats = await loadChats();
const conv = await chats.createConversation(TEST_UID, { title: 'history' });
diff --git a/test/main/features/group_chat/bus.test.ts b/test/main/features/group_chat/bus.test.ts
index 24bb44f7..6d11a466 100644
--- a/test/main/features/group_chat/bus.test.ts
+++ b/test/main/features/group_chat/bus.test.ts
@@ -2746,6 +2746,59 @@ describe('group_chat bus › enqueue routing + persistence', () => {
expect(attachments.listPendingAttachments(TEST_UID, cid)).toEqual([]);
});
+ it('converts a Codex file citation into the exact produced-file footer selection', async () => {
+ const paths = await import('../../../../src/main/paths');
+ const agentFile = path.join(paths.agentDir(TEST_UID, AGENT_ID), 'agent.json');
+ const spec = JSON.parse(fs.readFileSync(agentFile, 'utf8'));
+ spec.runtime = { kind: 'cli', cli: 'codex' };
+ fs.writeFileSync(agentFile, JSON.stringify(spec));
+
+ const projectDir = path.join(tmpDir, 'workspace');
+ const agents = await import('../../../../src/main/features/agents');
+ await agents.setAgentCliProjectDir(TEST_UID, AGENT_ID, projectDir);
+ const deckPath = path.join(projectDir, 'AI会议助手竞品分析.pptx');
+ const supportingPath = path.join(projectDir, 'analysis-notes.md');
+ fs.writeFileSync(deckPath, 'presentation bytes');
+ fs.writeFileSync(supportingPath, 'supporting notes');
+
+ cliRunMock.nextEvents.push({
+ type: 'file-change',
+ source: 'codex',
+ paths: [deckPath, supportingPath],
+ });
+ cliRunMock.nextResult = {
+ runId: 'codex-file-citation',
+ status: 'completed',
+ output: [
+ '演示文稿已经完成。',
+ '',
+ `:codex-file-citation{path="${deckPath}" purpose="output"}`,
+ ].join('\n'),
+ };
+
+ const cid = 'cid-codex-file-citation';
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ await bus.enqueue({
+ uid: TEST_UID,
+ cid,
+ fromActorId: 'user',
+ text: `@${AGENT_NAME} create the presentation`,
+ forceTo: [AGENT_ID],
+ });
+ await waitForQuiescent(TEST_UID, cid);
+
+ const mainFile = path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`);
+ const rows = fs.readFileSync(mainFile, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ const reply = rows.find(row => row.from === AGENT_ID);
+ expect(reply?.text).toBe('演示文稿已经完成。');
+ // Renderer consumes `produced` for the clickable list under the bubble.
+ // The native citation explicitly selects the deck, while the supporting
+ // file remains owned by the conversation without being presented as final.
+ expect(reply?.produced).toEqual([deckPath]);
+ expect(bus._cidStateForTest(TEST_UID, cid)?.producedPaths.has(deckPath)).toBe(true);
+ expect(bus._cidStateForTest(TEST_UID, cid)?.producedPaths.has(supportingPath)).toBe(true);
+ });
+
it('previews materialized CLI images and videos once and retains remote fallback media', async () => {
const paths = await import('../../../../src/main/paths');
const layout = await import('../../../../src/main/util/project-layout');
diff --git a/test/main/features/local_agents/openclaw_parser.test.ts b/test/main/features/local_agents/openclaw_parser.test.ts
index 45f90f27..1f0b8299 100644
--- a/test/main/features/local_agents/openclaw_parser.test.ts
+++ b/test/main/features/local_agents/openclaw_parser.test.ts
@@ -1,4 +1,6 @@
import { describe, it, expect } from 'vitest';
+import * as path from 'node:path';
+import { pathToFileURL } from 'node:url';
import { buildOpenclawArgs, parseOpenclawReply } from '../../../../src/main/features/local_agents/backends/openclaw';
describe('local_agents/backends/openclaw › parseOpenclawReply', () => {
@@ -56,6 +58,34 @@ describe('local_agents/backends/openclaw › parseOpenclawReply', () => {
});
});
+ it('separates structured local attachments from remote preview media', () => {
+ const reportPath = path.resolve('tmp-openclaw', 'report.pdf');
+ const sheetPath = path.resolve('tmp-openclaw', 'metrics.xlsx');
+ const notesPath = path.resolve('tmp-openclaw', 'notes.docx');
+ const stderr = JSON.stringify({
+ payloads: [
+ {
+ text: 'Artifacts ready.',
+ path: reportPath,
+ filePath: sheetPath,
+ media: [
+ 'https://cdn.example/preview.png',
+ pathToFileURL(notesPath).toString(),
+ ],
+ },
+ { path: reportPath },
+ ],
+ meta: { agentMeta: { sessionId: 'attachment-session' } },
+ });
+
+ expect(parseOpenclawReply(stderr)).toMatchObject({
+ text: 'Artifacts ready.',
+ media: ['https://cdn.example/preview.png'],
+ files: [notesPath, reportPath, sheetPath],
+ sessionId: 'attachment-session',
+ });
+ });
+
it('strips ANSI color escapes before parsing', () => {
// Real openclaw injects ANSI on log prefixes; the JSON envelope
// doesn't usually have them, but the function must not break if
diff --git a/test/main/features/local_agents/public-output.test.ts b/test/main/features/local_agents/public-output.test.ts
index e680fa26..0dd81bc0 100644
--- a/test/main/features/local_agents/public-output.test.ts
+++ b/test/main/features/local_agents/public-output.test.ts
@@ -1,6 +1,13 @@
import { describe, expect, it } from 'vitest';
+import * as path from 'node:path';
-import { sanitizeLocalAgentPublicOutput } from '../../../../src/main/features/local_agents/public-output';
+import {
+ CodexFileCitationStreamFilter,
+ normalizeLocalAgentPublicOutput,
+ persistedCodexOutputCitationPaths,
+ sanitizeLocalAgentPublicOutput,
+ sanitizePersistedCodexFileCitations,
+} from '../../../../src/main/features/local_agents/public-output';
describe('local_agents/public-output', () => {
it('publishes only the result from a real Hermes KSTAR scaffold', () => {
@@ -222,4 +229,148 @@ describe('local_agents/public-output', () => {
userTask: 'Repeat this diagnostic.',
})).toBe(raw);
});
+
+ describe('Codex file citations', () => {
+ const workingDir = path.resolve('tmp-public-output-workspace');
+ const deckPath = path.join(workingDir, 'assets', 'AI会议助手竞品分析.pptx');
+
+ it('turns the native output directive into an exact published-file selection', () => {
+ const raw = [
+ '演示文稿已经完成。',
+ '',
+ `:codex-file-citation{path="${deckPath}" purpose="output"}`,
+ ].join('\n');
+
+ expect(normalizeLocalAgentPublicOutput({
+ cli: 'codex',
+ text: raw,
+ workingDir,
+ producedPaths: [deckPath, path.join(workingDir, 'supporting-notes.md')],
+ })).toEqual({
+ text: '演示文稿已经完成。',
+ publishedPaths: [deckPath],
+ });
+ });
+
+ it('supports relative paths, attribute order, and multiple deduplicated outputs', () => {
+ const spreadsheetPath = path.join(workingDir, 'results', 'metrics.xlsx');
+ const raw = [
+ ':codex-file-citation{purpose="output" path="assets/AI会议助手竞品分析.pptx"}',
+ ':codex-file-citation{path="results/metrics.xlsx" purpose="output"}',
+ ':codex-file-citation{path="results/metrics.xlsx" purpose="output"}',
+ ].join('\n');
+
+ expect(normalizeLocalAgentPublicOutput({
+ cli: 'codex',
+ text: raw,
+ workingDir,
+ producedPaths: [deckPath, spreadsheetPath],
+ })).toEqual({
+ text: '',
+ publishedPaths: [deckPath, spreadsheetPath],
+ });
+ });
+
+ it('removes transport metadata but cannot publish a path not registered by the turn', () => {
+ const outsidePath = path.resolve('private', 'unregistered.pdf');
+ expect(normalizeLocalAgentPublicOutput({
+ cli: 'codex',
+ text: `Done.\n${`:codex-file-citation{path="${outsidePath}" purpose="output"}`}`,
+ workingDir,
+ producedPaths: [deckPath],
+ })).toEqual({
+ text: 'Done.',
+ publishedPaths: [],
+ });
+ });
+
+ it('preserves fenced, quoted, inline, and malformed examples', () => {
+ const raw = [
+ 'Example:',
+ '```text',
+ `:codex-file-citation{path="${deckPath}" purpose="output"}`,
+ '```',
+ `> :codex-file-citation{path="${deckPath}" purpose="output"}`,
+ `Inline :codex-file-citation{path="${deckPath}" purpose="output"}`,
+ ':codex-file-citation{path="unterminated purpose="output"}',
+ ].join('\n');
+
+ expect(normalizeLocalAgentPublicOutput({
+ cli: 'codex',
+ text: raw,
+ workingDir,
+ producedPaths: [deckPath],
+ })).toEqual({ text: raw, publishedPaths: [] });
+ });
+
+ it('does not interpret a Codex directive emitted by another CLI adapter', () => {
+ const raw = `:codex-file-citation{path="${deckPath}" purpose="output"}`;
+ expect(normalizeLocalAgentPublicOutput({
+ cli: 'claude',
+ text: raw,
+ workingDir,
+ producedPaths: [deckPath],
+ })).toEqual({ text: raw, publishedPaths: [] });
+ });
+
+ it('projects legacy persisted output only when its structured file list backs the citation', () => {
+ const raw = `Ready.\n:codex-file-citation{path="${deckPath}" purpose="output"}`;
+ expect(sanitizePersistedCodexFileCitations(raw, [deckPath])).toBe('Ready.');
+ expect(sanitizePersistedCodexFileCitations(raw, [])).toBe(raw);
+ });
+
+ it('extracts legacy output candidates without consuming fenced examples', () => {
+ const raw = [
+ `:codex-file-citation{path="assets/AI会议助手竞品分析.pptx" purpose="output"}`,
+ '```text',
+ ':codex-file-citation{path="private/inside-example.pdf" purpose="output"}',
+ '```',
+ ':codex-file-citation{path="assets/notes.md" purpose="input"}',
+ ].join('\n');
+
+ expect(persistedCodexOutputCitationPaths(raw, workingDir)).toEqual([deckPath]);
+ });
+
+ it('consumes the legacy suffix adjacent to a Markdown link for the same file', () => {
+ const directive = `:codex-file-citation{path="${deckPath}" name="deck" purpose="output"}`;
+ const link = `新版文件:[AI会议助手竞品分析.pptx](${deckPath})`;
+ const raw = `${link}${directive}`;
+
+ expect(persistedCodexOutputCitationPaths(raw)).toEqual([deckPath]);
+ expect(sanitizePersistedCodexFileCitations(raw, [deckPath])).toBe(link);
+
+ const mismatched = `${link}:codex-file-citation{path="${path.join(workingDir, 'other.pptx')}" purpose="output"}`;
+ expect(persistedCodexOutputCitationPaths(mismatched)).toEqual([]);
+ expect(sanitizePersistedCodexFileCitations(mismatched, [deckPath])).toBe(mismatched);
+ });
+
+ it('never streams a split directive and keeps fenced examples visible', () => {
+ const filter = new CodexFileCitationStreamFilter();
+ const chunks = [
+ filter.push('完成。\n:codex-file-'),
+ filter.push(`citation{path="${deckPath}" purpose="out`),
+ filter.push('put"}\n下一行'),
+ filter.flush(),
+ ];
+ expect(chunks.join('')).toBe('完成。\n下一行');
+
+ const inline = new CodexFileCitationStreamFilter();
+ const link = `[deck](${deckPath})`;
+ expect([
+ inline.push(`${link}:codex-file-citation{path="${deckPath}" purpose="output"}\n`),
+ inline.flush(),
+ ].join('')).toBe(`${link}\n`);
+
+ const fenced = new CodexFileCitationStreamFilter();
+ expect([
+ fenced.push(`\`\`\`text\n:codex-file-citation{path="${deckPath}" purpose="output"}\n`),
+ fenced.push('\`\`\`'),
+ fenced.flush(),
+ ].join('')).toBe([
+ '```text',
+ `:codex-file-citation{path="${deckPath}" purpose="output"}`,
+ '```',
+ ].join('\n'));
+ });
+ });
});