Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -759,7 +759,7 @@ async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None
project_id = chain.project_id
message = plan['message']
turn_id = UUID(message['id'])
text, status, error = '', 'complete', None
text, status, error, error_code = '', 'complete', None, None
activities: list[dict] = []
edited_documents: dict[str, int] = {}
positions: dict[str, int] = {}
Expand Down Expand Up @@ -857,6 +857,7 @@ async def renew_session() -> None:
except Exception as failure:
# Persist partial output even when an integration fails unexpectedly.
status = 'interrupted'
error_code = failure.code if isinstance(failure, ProjectError) else 'operation_rejected'
if isinstance(failure, ProjectError):
error = localized_error_for_language(
plan.get('accept_language'), chinese=str(failure),
Expand All @@ -877,7 +878,9 @@ async def renew_session() -> None:
'model': plan['model'], 'modelIsCliDefault': plan.get('model_is_cli_default', False),
'runtime': message['runtime'], 'thinking': plan['thinking'], 'tools': activities,
'sources': list(sources.values()),
**({'plan': steps} if steps is not None else {})}, conversation_id=chain.conversation_id,
**({'plan': steps} if steps is not None else {}),
**({'error': error, 'errorCode': error_code} if error else {})},
conversation_id=chain.conversation_id,
finish_turn_id=turn_id, edited_documents=edited_documents)
except Exception:
logger.exception(f'agent.turn.unfinished project_id={project_id} turn_id={turn_id}')
Expand Down
6 changes: 6 additions & 0 deletions apps/api/src/opendirector_api/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
'keyframe_needs_reference': 'Keyframes also need at least one ordinary reference image or video.',
'keyframe_time': 'Each keyframe needs its own time, earlier than the end of the video and at least 1/24 second from the others.',
'keyframe_image': 'A keyframe must be a PNG, JPEG or WebP image within the size limit.',
'agent_cli_login': 'The Agent CLI is not signed in, or its credential was rejected. Sign in with that CLI, or choose another runtime in the Agent panel.',
'agent_cli_exit': 'The Agent CLI exited before this turn finished. Check its sign-in and configuration; this turn\'s trace keeps its output.',
'agent_cli_output_invalid': 'The Agent CLI produced no usable output. Check its sign-in and configuration; this turn\'s trace keeps its output.',
'higgsfield_model': 'Choose MAGI-2 with the official Higgsfield Open API address.',
'higgsfield_key': 'Enter your Higgsfield Open KEY_ID:KEY_SECRET.',
'higgsfield_output': 'MAGI-2 supports 1080p and whole-second durations from 4 to 30 seconds.',
Expand Down Expand Up @@ -282,6 +285,9 @@ def localized_error_for_language(
if generic and status in {413, 502, 504}:
return ENGLISH_BY_STATUS[status]
specific = None if code == "operation_rejected" else ENGLISH_BY_CODE.get(code)
if code.startswith('agent_cli_'):
detail = chinese.split('CLI 输出:', 1)[-1].strip() if 'CLI 输出:' in chinese else ''
return specific + (' CLI output: ' + detail if detail else '')
if code == 'voice_provider_error':
from opendirector.domain.voices import VOICE_MESSAGES
detail = chinese.removeprefix(VOICE_MESSAGES[code]).strip()
Expand Down
4 changes: 4 additions & 0 deletions docs/architecture/agent-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ Default 的模型网关在 `agent-runs/<turn-id>.model.jsonl` 记录实际转发

停止或流连接断开时,适配层终止进程组,Gateway 关闭新调用入口并等待已接受操作结束;API 保存部分回复并释放运行占用。业务操作以各自回执确认,远端生成任务仍通过任务取消命令处理。

原生 CLI 的 stdout 不保证每行都是事件:它会在事件之间输出警告、横幅、纯文本错误或结构化日志。事件按各运行时自己的类型集合与必需字段识别,其余行按诊断记入本轮轨迹(截断到 2000 字符,并替换本轮任务令牌与 provider 密钥),本轮继续;失败信息里保留它的首行,按 200 字符截断;只有整轮没有任何可读事件才判为失败。失败的一轮在助手消息上同时保存解释文字和稳定的 `errorCode`:`agent_cli_login` 表示命令行凭据被拒绝,`agent_cli_exit` 表示进程退出并附带它自己的首行输出,`agent_cli_output_invalid` 表示只有不可读输出而没有事件。界面按当前显示语言重新渲染该代码,事后切换语言仍是同一句解释;原始输出留在轨迹与错误文本里供排查。

English summary: a native CLI line is not guaranteed to be an event. Events are recognized by each runtime's own type set and required fields; other lines are kept as diagnostics in the turn's trace, truncated to 2000 characters with the turn token and provider key redacted, and the turn continues; only a turn whose output holds no readable event fails. A failed turn stores both an explanatory text and a stable `errorCode` (`agent_cli_login` for a rejected CLI credential, `agent_cli_exit` for a process that exited, carrying its own first output line, and `agent_cli_output_invalid` for unreadable output only), so reopening the project still explains the failure. The UI renders that code in the language currently shown, and the raw output stays in the trace.

## Agent 来源追溯

Agent 的 `generation.submit` 接受任务时,把本轮标识和工具调用标识写入 Job 自身:
Expand Down
129 changes: 112 additions & 17 deletions packages/core/src/opendirector/agent/native.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,22 +159,90 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None
return args, env


def native_line(line: bytes) -> tuple[dict | None, str | None]:
text = line.decode('utf-8', errors='replace').strip()
if not text:
return None, None
try:
raw = json.loads(text)
except ValueError:
return None, text
return (raw, None) if isinstance(raw, dict) else (None, text)


def redacted(text: str, config, token: str = '') -> str:
if token:
text = text.replace(token, '[redacted]')
secret = (config or {}).get('apiKey')
return text.replace(secret, '[redacted]') if secret else text


def limited(text: str, config, token: str = '', limit: int = 200) -> str:
return redacted(text, config, token)[:limit]


def cli_detail(lines: list[str], config, token: str = '') -> str:
return f' CLI 输出:{limited(lines[0], config, token)}' if lines else ''


EVENT_TYPES = {
'opencode': {'step_start', 'step_finish', 'tool_use', 'text', 'reasoning',
'error', 'diagnostic', 'session'},
'codex': {'thread.started', 'turn.started', 'turn.completed', 'turn.failed',
'item.started', 'item.updated', 'item.completed', 'error'},
'claude': {'system', 'assistant', 'user', 'result', 'stream_event', 'error'},
'pi': {'session', 'agent_start', 'agent_end', 'turn_start', 'turn_end',
'message_start', 'message_update', 'message_end', 'tool_execution_start',
'tool_execution_update', 'tool_execution_end', 'compaction_start',
'compaction_end', 'auto_retry_start', 'auto_retry_end'},
'antigravity': {'init', 'step_update', 'result', 'error'},
}


def event_like(runtime: str, raw: dict) -> bool:
kind = raw.get('event') if runtime == 'antigravity' else raw.get('type')
if not isinstance(kind, str):
return False
kinds = EVENT_TYPES.get(runtime)
if kinds is None:
return True
if kind not in kinds:
return False
if runtime == 'codex' and kind.startswith('item.'):
return isinstance(raw.get('item'), dict)
if runtime == 'claude' and kind == 'assistant':
return isinstance((raw.get('message') or {}).get('content'), list)
if runtime == 'opencode' and kind == 'text':
return isinstance(raw.get('part'), dict)
if runtime == 'pi' and kind.startswith('message_'):
return isinstance(raw.get('message'), dict)
if runtime == 'antigravity' and kind == 'step_update':
return isinstance(raw.get('step_update'), dict)
if runtime == 'antigravity' and kind == 'result':
return isinstance(raw.get('result'), dict)
return True


def text_events(runtime: str, raw: dict) -> list[dict]:
kind = raw.get('type')
if runtime == 'claude' and raw.get('error') == 'authentication_failed':
raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401)
if runtime == 'codex' and raw['type'] == 'error':
raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401,
code='agent_cli_login')
if runtime == 'codex' and kind == 'error':
# Codex also emits this event while reconnecting. Wait for turn.failed or process exit.
return []
if raw['type'] in {'error', 'turn.failed'} or raw['type'] == 'result' and raw.get('is_error'):
if kind in {'error', 'turn.failed'} or kind == 'result' and raw.get('is_error'):
raise ProjectError(f'{runtime} 运行失败,请检查登录、模型或原生轨迹。', 502)
if runtime == 'opencode' and raw['type'] == 'text':
return [{'type': 'delta', 'text': raw['part']['text']}]
if runtime == 'codex' and raw['type'] == 'item.completed' and raw['item']['type'] == 'agent_message':
return [{'type': 'delta', 'text': raw['item']['text']}]
if runtime == 'opencode' and kind == 'text':
return [{'type': 'delta', 'text': (raw.get('part') or {}).get('text', '')}]
if runtime == 'codex' and kind == 'item.completed' and (raw.get('item') or {}).get('type') == 'agent_message':
return [{'type': 'delta', 'text': (raw.get('item') or {}).get('text', '')}]
if runtime == 'codex' and (sources := search_sources(raw)):
return [{'type': 'sources', 'sources': sources}]
if runtime == 'claude' and raw['type'] == 'assistant':
return [{'type': 'delta', 'text': part['text']} for part in raw['message']['content'] if part['type'] == 'text']
if runtime == 'claude' and kind == 'assistant':
return [{'type': 'delta', 'text': part['text']}
for part in (raw.get('message') or {}).get('content') or []
if isinstance(part, dict) and part.get('type') == 'text']
return []


Expand Down Expand Up @@ -301,11 +369,24 @@ async def stream(self, run: RunContext, gateway: ToolGateway):
if run.runtime == 'default':
raise ProjectError(BUNDLED_INSTALL_ERROR, 503, code='agent_dependency_unavailable') from error
raise
stderr_tail = bytearray()
stderr_lines = []
stderr_bytes = 0
async def drain_stderr():
nonlocal stderr_bytes
pending = b''
while chunk := await process.stderr.read(4096):
stderr_tail.extend(chunk)
del stderr_tail[:-8192]
pending += chunk
while (edge := pending.find(b'\n')) >= 0:
line, pending = pending[:edge], pending[edge + 1:]
text = redacted(line.decode('utf-8', errors='replace'), config, token) + '\n'
stderr_lines.append(text)
stderr_bytes += len(text)
while stderr_bytes > 8192 and len(stderr_lines) > 1:
stderr_bytes -= len(stderr_lines.pop(0))
if len(pending) > 8192:
pending = b''
if pending:
stderr_lines.append(redacted(pending.decode('utf-8', errors='replace'), config, token))
stderr_task = asyncio.create_task(drain_stderr())
if runtime == 'antigravity':
instructions = '' if session_id else runtime_instructions(runtime) + '\n' + antigravity.APPENDIX + '\n'
Expand All @@ -318,14 +399,13 @@ async def drain_stderr():
process.stdin.close()
async def record_exit():
await stderr_task
diagnostic = stderr_tail.decode('utf-8', errors='replace').replace(token, '[redacted]')
if config and config.get('apiKey'):
diagnostic = diagnostic.replace(config['apiKey'], '[redacted]')
diagnostic = ''.join(stderr_lines)[-8192:]
await queue.put({'native': {'type': 'diagnostic', 'stderr': diagnostic,
'exitCode': process.returncode}})
async def output():
try:
reported_session = None
plain, parsed = [], False
if runtime == 'deepseek':
async def observe(raw):
await queue.put({'native': raw})
Expand All @@ -340,7 +420,16 @@ async def observe(raw):
deepseek_server, observe, session_id)
else:
while line := await process.stdout.readline():
raw = json.loads(line)
raw, text = native_line(line)
if raw is None or not event_like(runtime, raw):
if text is None and raw is None:
continue
text = text if text is not None else json.dumps(raw, ensure_ascii=False)
plain.append(text)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里退出原因只用第一条 plain,但每条普通日志都会把原文追加进列表。长回合里 trace 每条已经有限长,内存里的副本却会一直涨。建议只保存首条脱敏且限长的诊断摘要,其余继续按现有 trace 写出;补个多行诊断后仍能正确标记退出的回归即可。Dot,代表 @david6666666。

await queue.put({'native': {'type': 'diagnostic',
'stdout': limited(text, config, token, 2000)}})
continue
parsed = True

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里 parsed = True 实际只说明这一行可解析成 JSON 对象,不代表它有 Codex 事件所需的字段。遇到普通结构化日志时,下一段会直接读取 raw['type'],这轮还是可能提前退出。能先判断是不是可处理的事件,再把不匹配的日志走诊断,并断言后面的正常事件仍能到达吗?

previous_session = reported_session
if runtime == 'codex' and raw['type'] == 'thread.started':
reported_session = raw.get('thread_id')
Expand All @@ -358,7 +447,13 @@ async def observe(raw):
await queue.put({'native': raw})
if await process.wait():
await record_exit()
raise ProjectError(f'{runtime} 进程退出({process.returncode}),请检查 CLI 登录和配置。', 502)
raise ProjectError(f'{runtime} 进程退出({process.returncode}),请检查 CLI 登录和配置。'
f'{cli_detail(plain, config, token)}', 502, code='agent_cli_exit')
if not parsed and plain:
await record_exit()
raise ProjectError(f'{runtime} 未返回可识别的输出,请检查 CLI 登录和配置。'
f'{cli_detail(plain, config, token)}', 502,
code='agent_cli_output_invalid')
if reported_session:
run.save_native_session(reported_session, selection,
engine_directory=native_work,
Expand Down
5 changes: 4 additions & 1 deletion scripts/ci/python_shards.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"core": [
"tests/test_a2_repros.py",
"tests/test_app_settings.py",
"tests/test_ark_availability.py",
"tests/test_ark_plan_models.py",
"tests/test_asset_names.py",
"tests/test_atlascloud.py",
Expand Down Expand Up @@ -103,6 +104,7 @@
"tests/test_self_hosted_proxy.py",
"tests/test_self_hosted_queue.py",
"tests/test_structure_reference.py",
"tests/test_trace_job_queries.py",
"tests/test_vllm_omni_h3.py",
"tests/test_vllm_omni_image.py",
"tests/test_voice_library.py",
Expand Down Expand Up @@ -136,7 +138,8 @@
"tests/test_native_runtime.py",
"tests/test_native_sessions.py",
"tests/test_pi_runtime.py",
"tests/test_skill_snapshot.py"
"tests/test_skill_snapshot.py",
"tests/test_wait_outcome.py"
],
"media": [
"tests/test_canvas_text_cli_http.py",
Expand Down
2 changes: 2 additions & 0 deletions src/backend/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ export interface ChatMessage {
text: string;
content?: ReferenceContent | null;
status: "complete" | "streaming" | "stopped" | "interrupted";
error?: string;
errorCode?: string;
assets?: ChatAsset[];
model?: string | null;
modelIsCliDefault?: boolean;
Expand Down
5 changes: 3 additions & 2 deletions src/canvas/AssistantPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react";
import openDirectorLogo from "../assets/open_director_logo.png";
import { runtimeModels, type AssistantModelSelection, type ChatAsset, type ModelSelections } from "../backend/chat";
import { assistantModelSelection } from "./agentPreferences";
import { assistantFailureText } from "./assistantFailure";
import { creationClient } from "../backend/creationClient.ts";
import { fingerprint } from "../backend/generation.ts";
import type { BackendModels } from "../backend/models";
Expand Down Expand Up @@ -574,7 +575,7 @@ export function AssistantPanel({
? chat.thinkingNow
? t("assistant.activity.thinking")
: t("assistant.activity.replying")
: t("assistant.reply.empty"))
: assistantFailureText(message, t) || t("assistant.reply.empty"))
)}
</div>
{!collapsible && message.role === "assistant" && previous?.role === "user" &&
Expand Down Expand Up @@ -606,7 +607,7 @@ export function AssistantPanel({
)}
{message.role === "user" && !!message.assets?.length && <AttachmentStrip projectId={documentId} assets={message.assets.map(resolveAsset)} />}
{(message.status === "stopped" ||
message.status === "interrupted") && (
(message.status === "interrupted" && !message.error)) && (
<small className="cw-assistant-message-status">
{message.status === "stopped"
? t("assistant.panel.stopped")
Expand Down
5 changes: 4 additions & 1 deletion src/canvas/AssistantReply.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { activityProgress, replySections, toolCounts, toolDisplayStatus, toolLab
import type { ToolDisplayStatus } from "./assistantActivity.ts";
import { assistantToolText } from "./assistantToolText.ts";
import { assistantCitationFormatter } from "./assistantCitations.ts";
import { assistantFailureText } from "./assistantFailure";
import { defaultTranslate } from "./assistantTranslate.ts";
import { chatTurnTiming } from "./turnTiming.ts";
import { hidePartialSuggestionMarker, parseSuggestedReplies } from "./suggestedReplies.ts";
Expand Down Expand Up @@ -186,7 +187,9 @@ export const AssistantReply = memo(function AssistantReply({
{!message.text &&
!message.tools?.length &&
message.status !== "streaming" && (
<p className="cw-chat-progress">{t("assistant.reply.empty")}</p>
<p className={message.error ? "cw-chat-progress is-failed" : "cw-chat-progress"}>
{assistantFailureText(message, t) || t("assistant.reply.empty")}
</p>
)}
{!!message.text && message.status !== "streaming" && (
<div className="cw-chat-message-actions">
Expand Down
4 changes: 4 additions & 0 deletions src/canvas/assistant-experience.css
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@
color: var(--chat-muted);
font-size: 12px;
}

.cw-chat-progress.is-failed {
color: var(--chat-failure, #df9a9a);
}
.cw-chat-waiting { display: inline-flex; align-items: center; gap: 3px; }
.cw-chat-waiting i { width: 4px; height: 4px; border-radius: 50%; background: currentColor; animation: cw-chat-wait 1.2s ease-in-out infinite; }
.cw-chat-waiting i:nth-child(2) { animation-delay: 0.15s; }
Expand Down
2 changes: 2 additions & 0 deletions src/canvas/assistant-panel.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
--chat-surface: #242424;
--chat-text: #ededee;
--chat-muted: #858589;
--chat-failure: #df9a9a;
--chat-border: #ffffff14;
--chat-hover: #ffffff0a;
position: absolute;
Expand Down Expand Up @@ -763,6 +764,7 @@
--chat-surface: #eef0f4;
--chat-text: #30343c;
--chat-muted: #757b86;
--chat-failure: #9a4d36;
--chat-border: #dfe2e7;
--chat-hover: #e9edf3;
box-shadow: 0 12px 40px #30374420;
Expand Down
Loading
Loading