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
2 changes: 2 additions & 0 deletions docs/development/lessons.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u

- **Color profile follow-up:** [PR #287's P3 review](https://github.com/ThinkFlowLab/OpenDirector/pull/287#pullrequestreview-5870014881) found that a correct full-size PNG did not prove correct thumbnails: the library JPEG and the asset/history WebP used separate encoders that both omitted ICC. Check every displayed rendition and the actual embedded profile, not only dimensions or successful decoding. Preserve RGB profiles through resizing, but do not attach a non-RGB source profile after converting its channels to RGB. / **颜色配置补充:** 同一素材的全尺寸 PNG 正确,并不能证明素材库 JPEG 和资产/版本历史 WebP 正确。逐条检查显示路径的实际 ICC;缩放保留 RGB 配置,转换通道后不能继续附带非 RGB 源配置。

- **Windows CLI follow-up:** In PR #323 validation, the Agent saved Unicode successfully, but PowerShell 5.1 shell readback failed when Python used the Windows code page. A saved-object comparison bypasses CLI stdout. Test write and readback in the actual Agent shell with Python UTF-8 mode disabled in the parent environment, and cover BOM-prefixed JSON files produced by PowerShell 5.1. / **Windows CLI 补充:** PR #323 验收中,Agent 正确保存了 Unicode,但 Python 使用 Windows 代码页时,PowerShell 5.1 中的读回失败。应在父进程关闭 Python UTF-8 模式,用真实 Agent Shell 验证写入和读回,并覆盖 PowerShell 5.1 生成的带 BOM JSON 文件。

## Baseline failures still need tracking

- **Trigger:** A relevant test fails and comparison shows that it also fails on the baseline.
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/opendirector/agent/cli_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def environment(work, socket, bridge_env=None):
cli_bin = work / '.opendirector-bin'
cli_bin.mkdir(exist_ok=True)
if os.name == 'nt':
(cli_bin / 'opendirector.cmd').write_text(f'@"{sys.executable}" -m opendirector.cli %*\n')
(cli_bin / 'opendirector.cmd').write_text(f'@"{sys.executable}" -X utf8 -m opendirector.cli %*\n')
else:
launcher = cli_bin / 'opendirector'
launcher.write_text('#!/bin/sh\nexec ' + shlex.join([sys.executable, '-m', 'opendirector.cli']) + ' "$@"\n')
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/opendirector/agent/native.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from uuid import UUID

from opendirector.agent.model_gateway import ModelGateway
from opendirector.agent import cli_transport, deepseek
from opendirector.agent import cli_transport, deepseek, windows_powershell
from opendirector.agent.cli_discovery import cli_executable
from opendirector.agent.context import RunContext
from opendirector.agent.citations import search_sources
Expand Down Expand Up @@ -239,6 +239,8 @@ async def stream(self, run: RunContext, gateway: ToolGateway):
config['modelId'] if config else runtime_model, model_url, catalog, bridge_env=bridge_env,
**({'native_directory': native_work} if runtime == 'opencode' else {}),
**({'input_modalities': config.get('inputModalities', ['text'])} if run.runtime == 'default' else {}))
if runtime == 'opencode':
await windows_powershell.configure_opencode(args[0], native_work, env, Path(temporary))
if thinking != 'auto' and runtime == 'codex':
args += ['-c', f'model_reasoning_effort={json.dumps(thinking)}']
elif thinking != 'auto' and runtime == 'claude':
Expand Down
116 changes: 116 additions & 0 deletions packages/core/src/opendirector/agent/windows_powershell.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
#!python -I
"""Run OpenCode's Windows PowerShell command with UTF-8 native pipelines."""

import asyncio
from contextlib import suppress
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys


_COMMAND_ENV = 'OPENDIRECTOR_POWERSHELL_COMMAND'
_BOOTSTRAP = r"""
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
$OutputEncoding = [Console]::OutputEncoding
. (& {
$source = [Environment]::GetEnvironmentVariable('OPENDIRECTOR_POWERSHELL_COMMAND')
[Environment]::SetEnvironmentVariable('OPENDIRECTOR_POWERSHELL_COMMAND', $null)
# A dot-sourced script can hide the last native command's failure. Check
# inside the script so the shell still exits 1 (or honors an explicit exit).
[scriptblock]::Create($source + [Environment]::NewLine + 'if (-not $?) { exit 1 }')
})
"""


def system_powershell():
return Path(os.environ['SystemRoot']) / 'System32/WindowsPowerShell/v1.0/powershell.exe'


def _select_shell(configured, env):
# OpenCode checks its configured shell (or SHELL), then pwsh, then
# powershell. The remaining Git Bash/cmd fallbacks need no encoding setup.
path = env.get('PATH', '')
preferred = configured or env.get('SHELL')
if preferred and Path(preferred).stem.lower() not in {'nu', 'fish'}:
if Path(preferred).stem.lower() == 'bash':
# OpenCode resolves bare bash through Git for Windows before PATH.
return None
if executable := shutil.which(preferred, path=path):
return Path(executable)
if not shutil.which('pwsh', path=path):
if executable := shutil.which('powershell', path=path):
return Path(executable)
return None


async def configure_opencode(binary, cwd, env, directory):
if os.name != 'nt' or 'OPENCODE_CONFIG_CONTENT' not in env:
return
powershell = system_powershell()
if not powershell.is_file():
return

# Ask the same OpenCode binary to resolve its config before setting shell.
# This preserves explicit Git Bash/PowerShell 7 choices in user config.
try:
process = await asyncio.create_subprocess_exec(
binary, 'debug', 'config', '--pure', cwd=cwd, env=env,
stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW,
)
except OSError:
return
try:
raw, _ = await asyncio.wait_for(process.communicate(), 10)
except TimeoutError:
return
finally:
if process.returncode is None:
with suppress(ProcessLookupError):
process.kill()
await process.wait()

if process.returncode:
return
try:
config = json.loads(raw)
except ValueError:
return
selected = _select_shell(config.get('shell'), env)
if selected is None or selected.resolve() != powershell.resolve():
return

env['OPENCODE_CONFIG_CONTENT'] = json.dumps({
**json.loads(env['OPENCODE_CONFIG_CONTENT']),
'shell': str(make_launcher(directory)),
})


def make_launcher(directory):
from distlib.scripts import ScriptMaker

source = Path(__file__)
maker = ScriptMaker(str(source.parent), str(directory))
maker.force = True
launcher = Path(maker.make(source.name)[0])
# OpenCode uses the basename to select PowerShell arguments and parsing.
return launcher.replace(directory / 'powershell.exe')


def main():
args = sys.argv[1:]
env = dict(os.environ)
if len(args) >= 2 and args[-2].lower() in {'-command', '-c'} and args[-1] != '-':
env[_COMMAND_ENV] = args[-1]
args[-1] = _BOOTSTRAP
return subprocess.call(
[str(system_powershell()), *args], env=env, creationflags=subprocess.CREATE_NO_WINDOW,
stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr,
)


if __name__ == '__main__':
sys.exit(main())
6 changes: 5 additions & 1 deletion packages/core/src/opendirector/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,11 @@ def query(ctx: typer.Context, kind: str,


def read_file(path):
value = json.loads(sys.stdin.read() if str(path) == "-" else path.read_text(encoding="utf-8"))
if str(path) == "-":
source = sys.stdin.buffer.read().decode("utf-8-sig")
else:
source = path.read_text(encoding="utf-8-sig")
value = json.loads(source)
if not isinstance(value, dict):
raise ValueError("Expected a JSON object.")
return value
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ dependencies = [
"pydantic>=2.12,<3", "typer>=0.27.3,<0.28", "Pillow>=12,<14", "pillow-heif>=1.8.1,<2",
"fonttools==4.68.0", "fastapi>=0.115,<1", "uvicorn>=0.30,<1",
"starlette>=1.8,<2", "python-multipart>=0.0.33,<1",
"distlib>=0.4,<1; sys_platform == 'win32'",
]

[project.optional-dependencies]
Expand Down
Loading
Loading