Repository navigation
fix(agent): keep a CLI turn alive and store why it failed #568
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Zhangbo-cn
wants to merge
15
commits into
ThinkFlowLab:main
Choose a base branch
from
Zhangbo-cn:fix/agent-cli-plain-stdout
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+527
−23
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
e92a11b
fix(agent): keep the turn alive when a CLI prints plain stdout lines
Zhangbo-cn aad67c7
ci: retrigger the assistant browser lane
Zhangbo-cn 7966a15
Merge remote-tracking branch 'origin/main' into fix/agent-cli-plain-s…
Zhangbo-cn f61397c
[bugfix] agent: store why a turn failed, and say it in the language s…
2995a51
Merge remote-tracking branch 'origin/main' into fix/agent-cli-plain-s…
4dbefee
fix(agent): give every agent CLI code its own English text
ad0d54f
Merge remote-tracking branch 'origin/main' into fix/agent-cli-plain-s…
f3225e4
[fix] assistant: keep the failure line readable on the light sheet
2ee9345
[fix] agent: redact CLI diagnostics before trimming them
c262159
[bugfix] agent: recognize harness events by runtime contract
Zhangbo-cn 4eaea2c
Merge remote-tracking branch 'origin/main' into pr-568
Zhangbo-cn bfb1fbc
[ci] python: list the test modules main added without a shard
Zhangbo-cn 1c5c95e
Merge remote-tracking branch 'origin/main' into pr-568
Zhangbo-cn 7e72550
[bugfix] agent: keep only the first plain diagnostic for the exit reason
Zhangbo-cn 15981de
[bugfix] agent: keep malformed Claude assistant parts on the diagnost…
Zhangbo-cn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -159,22 +159,97 @@ 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(detail: str | None, config, token: str = '') -> str: | ||
| return f' CLI 输出:{limited(detail, config, token)}' if detail 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': | ||
| message = raw.get('message') | ||
| content = message.get('content') if isinstance(message, dict) else None | ||
| return isinstance(content, list) and all( | ||
| isinstance(part, dict) | ||
| and (part.get('type') != 'text' or isinstance(part.get('text'), str)) | ||
| for part in content) | ||
| 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': | ||
| message = raw.get('message') | ||
| content = message.get('content') if isinstance(message, dict) else None | ||
| return [{'type': 'delta', 'text': part['text']} for part in content or [] | ||
| if isinstance(part, dict) and part.get('type') == 'text' | ||
| and isinstance(part.get('text'), str)] | ||
| return [] | ||
|
|
||
|
|
||
|
|
@@ -301,11 +376,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' | ||
|
|
@@ -318,14 +406,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 = None, False | ||
| if runtime == 'deepseek': | ||
| async def observe(raw): | ||
| await queue.put({'native': raw}) | ||
|
|
@@ -340,7 +427,18 @@ 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) | ||
| diagnostic = limited(text, config, token, 2000) | ||
| if plain is None: | ||
| plain = diagnostic | ||
| await queue.put({'native': {'type': 'diagnostic', | ||
| 'stdout': diagnostic}}) | ||
| continue | ||
| parsed = True | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 这里 |
||
| previous_session = reported_session | ||
| if runtime == 'codex' and raw['type'] == 'thread.started': | ||
| reported_session = raw.get('thread_id') | ||
|
|
@@ -358,7 +456,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, | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这里先对
message调.get(),还没确认它是对象;异常形状的 stdout 仍可能在分类时直接结束这轮,而不是变成 diagnostic。建议先校验容器和后续要读取的字段类型,再把它交给事件 parser,并验证后续合法事件能继续输出。