Skip to content
Merged
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
6 changes: 3 additions & 3 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def __init__(self, projects):
def path(self, project_id: UUID, session: str | None = None) -> Path:
with self.projects.local.transaction() as db:
self.projects._recover()
directory, _, _ = self.projects._load(db, project_id)
directory, _ = self.projects._find(db, project_id)
if session:
self.projects._lease(db, project_id, directory, session, browser_only=True)
return directory
Expand All @@ -162,7 +162,7 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft |
finish_mono, finish_at = (_monotonic(), _utc_now()) if finish is not None else (None, None)
with self.projects.local.transaction() as db:
self.projects._recover()
directory, _, _ = self.projects._load(db, project_id)
directory, _ = self.projects._find(db, project_id)
if session:
self.projects._lease(db, project_id, directory, session, browser_only=True)
folder = child(directory, 'agent-runs')
Expand Down Expand Up @@ -383,7 +383,7 @@ def conversation_of(self, project_id: UUID, turn_id: UUID) -> str:
def activate(self, project_id: UUID, conversation_id: UUID, session: str, *, create=False) -> dict:
with self.projects.local.transaction() as db:
self.projects._recover()
directory, _, _ = self.projects._load(db, project_id)
directory, _ = self.projects._find(db, project_id)
self.projects._lease(db, project_id, directory, session, browser_only=True)
folder = child(directory, 'agent-runs')
folder.mkdir(exist_ok=True)
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 @@ -100,6 +100,10 @@ English summary: a Job created by an Agent `generation.submit` records `agentRun

Windows 上的 Codex 启动显式设置 `windows.sandbox="elevated"`,避免隔离启动忽略用户配置后,`workspace-write` 降为只读并拦截 Shell。保留沙箱约束,不绕过审批或沙箱。PowerShell 使用 `Get-Command opendirector` 发现 CLI,POSIX Shell 使用 `command -v opendirector`。

OpenDirector 独立启动 Codex CLI 时不继承 Codex 桌面版的注册运行时标记。否则,即使模型能回复,独立 CLI 启动 PowerShell 时仍可能被注册运行时拒绝。此处理只作用于 Codex 子进程,仍使用 Windows 沙箱。

When launching the standalone Codex CLI, OpenDirector drops Desktop's registered-runtime markers from that child process. A model reply can succeed even when the inherited markers prevent PowerShell from starting. The Windows sandbox remains in use.

On Windows, Codex explicitly sets `windows.sandbox="elevated"` so ignoring user configuration does not downgrade `workspace-write` to read-only and block Shell execution. Sandbox restrictions remain enabled. Discover the CLI with `Get-Command opendirector` in PowerShell or `command -v opendirector` in POSIX shells.

CLI 通过环境变量中的本轮本地 Socket 地址连接业务网关,不使用连接令牌或凭据文件。网关继续校验工程范围、轮次生命周期及业务输入。
Expand Down
7 changes: 7 additions & 0 deletions docs/development/lessons.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,13 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u
- **Four-view cropping:** A frozen face-emphasis prompt proves the setting reached the provider, while visual compliance still requires reviewing the generated image. Put the crop before appearance guidance and scope it to the first two columns. Specify a separate scale and headroom for the full back view. Check both a text-only subject and a reference with a less obvious neck.
- **Reference medium:** Explicit photography wording corrected a photograph but turned an illustrated reference into a live-action portrait. Treat the layout as composition only and use medium-neutral framing language. Verify style changes against a photo and an illustration.

## History replay can block unrelated canvas reads

- **Trigger:** Opening a canvas with hundreds of full-snapshot commits sends media, conversation, and update requests concurrently.
- **Evidence:** Media and assistant requests returned storage-lock timeouts on a Windows project with over 800 commits. All the referenced files were present, and reading the committed head resolved the failing media requests.
- **Check:** Read current media from the committed head and replay immutable history outside the catalog lock. Before publishing, recheck the head and rerun command validation if it changed. The asset and storage tests cover original bytes and a concurrent head change during replay.
- **Rename follow-up:** [PR #544](https://github.com/ThinkFlowLab/OpenDirector/pull/544) reproduced receipt and change-feed reads reporting corruption when a concurrent rename moved a valid commit directory. Resolve the project again after a failed replay and retry when its location or manifest changed. Keep the integrity error when the basis stayed the same.

## An upstream response and a consumer finishing it are separate facts

- **Trigger:** Forwarding streamed model responses through the loopback gateway.
Expand Down
13 changes: 9 additions & 4 deletions packages/core/src/opendirector/agent/native.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,13 @@ def executable(runtime: str) -> str | None:
_CODEX_ISOLATION: dict[tuple[str, ...], tuple[str, ...]] = {}


def codex_environment() -> dict[str, str]:
env = dict(os.environ)
def codex_environment(base: dict[str, str] | None = None) -> dict[str, str]:
env = dict(os.environ if base is None else base)
if sys.platform == 'win32':
# This is an independent CLI launch, not a registered Desktop Core child.
# Inheriting the registration selects a runner that cannot start this CLI's shell.
env.pop('CODEX_WINDOWS_REGISTERED_CORE', None)
env.pop('CODEX_WINDOWS_SANDBOX_PACKAGE_FAMILY', None)
if sys.platform == 'win32' and not (env.get('HTTPS_PROXY') or env.get('ALL_PROXY')):
# A Windows system proxy need not be exported to the CLI process.
if proxy := getproxies().get('https'):
Expand Down Expand Up @@ -94,8 +99,8 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None
if bundled:
runtime = 'opencode'
env = cli_transport.environment(work, socket, bridge_env)
if runtime == 'codex' and (proxy := codex_environment().get('HTTPS_PROXY')):
env['HTTPS_PROXY'] = proxy
if runtime == 'codex':
env = codex_environment(env)
if runtime == 'opencode':
config = {'autoupdate': False, 'default_agent': 'opendirector',
'agent': {'opendirector': {'mode': 'primary', 'prompt': SYSTEM}},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,15 +209,13 @@ def open_media(self, project_id, asset_id, *, snapshot=None):
"""
with self.projects.local.transaction() as db:
self.projects._recover()
if snapshot is not None and snapshot.project.id != UUID(str(project_id)):
raise ProjectError('素材读取快照不属于当前工程。', 409)
path, manifest = self.projects._find(db, project_id)
if snapshot is None:
# A head whose chain was already proven needs no replay per read.
path, manifest = self.projects._find(db, project_id)
record, validated = self.projects._current_record(db, project_id, path, manifest)
snapshot = (record if validated else self.projects._load(db, project_id)[2][0]).snapshot
else:
if snapshot.project.id != UUID(str(project_id)):
raise ProjectError('素材读取快照不属于当前工程。', 409)
path, _ = self.projects._find(db, project_id)
try:
asset = self._asset(snapshot, asset_id)
except ContractError:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,8 @@ def used(kind, obj, ids=None, *, exclude_self=False):
# Read independent tool ledgers once, retaining their deletion protection.
asset_keys = {str(key): key for key in statuses}
with self.projects.local.transaction() as db:
path, _, _ = self.projects._load(db, snapshot.project.id)
self.projects._recover()
path, _ = self.projects._find(db, snapshot.project.id)
folder = gateway().child(path, 'tool-tasks')
if folder.exists():
for entry in folder.glob('*.json'):
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/opendirector/domain/image_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ def image_outputs(config, profile):
('16:9', '2720x1536'), ('9:16', '1536x2720'), ('3:2', '2496x1664'),
('2:3', '1664x2496'), ('21:9', '3136x1344'), ('9:21', '1344x3136'),
]]
if profile == 'vllm-omni-minimax-h3-image':
return [dict(aspectRatio=ratio, size=size) for ratio, size in [
('1:1', '1024x1024'), ('3:2', '1536x1024'), ('2:3', '1024x1536'),
('4:3', '1600x1200'), ('3:4', '1200x1600'),
('16:9', '1920x1080'), ('9:16', '1080x1920'), ('21:9', '2240x960'),
]]
if config.get('protocol') == 'volcengine':
# This adapter only declares the existing automatic 2K request. Do not
# promise a ratio without an explicit output contract for that service.
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/opendirector/domain/input_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ def _adapter_rules(config):
rules.update(profile='minimax-h3-image', maxImages=16,
imageBytes=64 * 1024 * 1024, requestBytes=64 * 1024 * 1024)
return rules
if (kind == 'image' and config.get('protocol') == 'openai'
and config.get('connectionType') == 'self_hosted'
and model.rsplit('/', 1)[-1].lower() == 'minimax-h3-image'):
rules.update(profile='vllm-omni-minimax-h3-image')
return rules
if is_moss_image(config):
rules.update(profile='moss-image', allowedKinds=['text'], maxImages=0,
maxPromptCharacters=MOSS_IMAGE_PROMPT_CHARACTERS)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
and by a bounded background warm, never by trusting a bare timestamp.
"""
import threading
from contextlib import contextmanager
from hashlib import sha256

from opendirector.domain.projects import ProjectError
Expand Down Expand Up @@ -310,6 +311,27 @@ def _read_manifest(self, project_id):
self._recover()
return self._find(db, project_id)

@contextmanager
def _write_basis(self, project_id):
while True:
path, manifest = self._read_manifest(project_id)
self._await_warm(project_id, manifest.head)
signature = _head_signature(path, manifest.head, self._verify_record_bytes)
try:
records = self._history(path, manifest)
except (OSError, ProjectError):
if (path, manifest) != self._read_manifest(project_id):
continue
raise
with self.local.transaction() as db:
self._recover()
if (path, manifest) != self._find(db, project_id):
continue
if signature is None or signature != _head_signature(path, manifest.head, self._verify_record_bytes):
raise ProjectError('工程提交身份不一致,原文件已保留。', 409, code='storage_unavailable')
yield db, path, manifest, records
return

def records(self, project_id):
"""Private commit records for read-only scans; callers must not mutate them.

Expand All @@ -318,7 +340,18 @@ def records(self, project_id):
megabytes for long histories, so they read the shared records directly.
"""
path, manifest = self._read_manifest(project_id)
return tuple(self._history(path, manifest))
return tuple(self._read_history(project_id, path, manifest))

def _read_history(self, project_id, path, manifest):
while True:
try:
return self._history(path, manifest)
except (OSError, ProjectError):
# The immutable files can move together when a project is renamed.
current = self._read_manifest(project_id)
if current == (path, manifest):
raise
path, manifest = current

def history(self, project_id):
records = self.records(project_id)
Expand All @@ -328,22 +361,19 @@ def history(self, project_id):

def history_index(self, project_id):
"""Small detached event metadata; toolbar queries need no snapshots."""
path, manifest = self._read_manifest(project_id)
records = self._history(path, manifest)
records = self.records(project_id)
return records[0].snapshot.undoClearedThrough, tuple(dict(
commandId=r.command.commandId, type=r.command.type,
cursor=r.event.cursor, source=r.event.source,
targetCommandId=getattr(r.command.payload, 'targetCommandId', None),
) for r in records if r.event is not None)

def receipt(self, project_id, command_id):
with self.local.transaction() as db:
self._recover()
records = self._load(db, project_id)[2]
found = next((record.receipt for record in records if str(record.command.commandId) == str(command_id)), None)
if found is None:
raise ProjectError('没有该命令的已提交回执。', 404)
return found.model_copy(deep=True)
records = self.records(project_id)
found = next((record.receipt for record in records if str(record.command.commandId) == str(command_id)), None)
if found is None:
raise ProjectError('没有该命令的已提交回执。', 404)
return found.model_copy(deep=True)

def changes(self, project_id, *, after=0, limit=100):
if type(after) is not int or after < 0 or type(limit) is not int or not 1 <= limit <= 200:
Expand All @@ -362,15 +392,13 @@ def changes(self, project_id, *, after=0, limit=100):
cursor = head.snapshot.eventCursor
if after > cursor:
raise ProjectError('变更游标超出当前工程,请重新读取快照。', 409)
if after == cursor:
if not validated:
# A head served by the fast path has not proven its ancestry
# yet; the outbox is derived from the chain, so validate it
# before claiming there are no events.
self._history(path, manifest)
return dict(events=[], nextCursor=after, currentCursor=cursor, hasMore=False)
records = self._history(path, manifest)
events = [record.event for record in reversed(records) if record.event and record.event.cursor > after][:limit]
events = [event.model_copy(deep=True) for event in events]
return dict(events=events, nextCursor=events[-1].cursor if events else after,
currentCursor=cursor, hasMore=bool(events and events[-1].cursor < cursor))
if after == cursor and validated:
return dict(events=[], nextCursor=after, currentCursor=cursor, hasMore=False)
records = self._read_history(project_id, path, manifest)
cursor = records[0].snapshot.eventCursor
if after > cursor:
raise ProjectError('变更游标超出当前工程,请重新读取快照。', 409)
events = [record.event for record in reversed(records) if record.event and record.event.cursor > after][:limit]
events = [event.model_copy(deep=True) for event in events]
return dict(events=events, nextCursor=events[-1].cursor if events else after,
currentCursor=cursor, hasMore=bool(events and events[-1].cursor < cursor))
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,14 @@ def _replay(records, command):
def replay(self, command):
"""Resolve an already committed command before reading upload handles."""
self._await_current_warm(command.projectId)
with self.local.transaction() as db:
self._recover()
return self._replay(self._load(db, command.projectId)[2], command)
return self._replay(self.records(command.projectId), command)

def commit(self, command: Command,
apply: Callable[[ProjectSnapshot], ProjectSnapshot] | Callable[[ProjectSnapshot, tuple[CommitRecord, ...]], ProjectSnapshot], *,
session=None, source='ui', files=(), deletes=(), with_history=False):
if source not in {'ui', 'agent', 'background', 'external'}:
raise ProjectError('无效的命令来源。')
self._await_current_warm(command.projectId)
with self.local.transaction() as db:
self._recover()
path, manifest, records = self._load(db, command.projectId)
with self._write_basis(command.projectId) as (db, path, manifest, records):
replay = self._replay(records, command)
if replay:
return replay
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,10 @@ def lock(self, project_id, handle):

def _scope(self, db, project_id, session, trusted=False):
self.projects._recover()
path, _, records = self.projects._load(db, project_id)
path, manifest = self.projects._find(db, project_id)
if not trusted:
self.projects._lease(db, project_id, path, session)
return records[0].snapshot
return self.projects._current(db, project_id, path, manifest).snapshot

def _owner(self, folder, project_id, handle, session):
try:
Expand Down
Loading
Loading