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
4 changes: 3 additions & 1 deletion apps/api/src/opendirector_api/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from opendirector.domain.url_import import url_import_message

from opendirector.domain.creation.commands import CommandReceipt
from opendirector.domain.creation.contract_messages import contract_message
from opendirector.domain.capabilities import Capability
from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message

Expand Down Expand Up @@ -199,7 +200,8 @@ def localized_error_for_language(
code: str = "operation_rejected",
required_capability: Capability | None = None,
) -> str:
specific = timeline_error_message(code, language) or url_import_message(code, language, chinese)
specific = (timeline_error_message(code, language) or url_import_message(code, language, chinese)
or contract_message(code, language, chinese))
if specific is not None:
return specific
if not wants_english_language(language):
Expand Down
7 changes: 7 additions & 0 deletions apps/api/src/opendirector_api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from fastapi.staticfiles import StaticFiles
from filelock import Timeout

from opendirector.domain.creation.contract_messages import CONTRACT_MESSAGES, contract_message
from opendirector.installation import data_root, web_root
from opendirector.wiring import configure_runtime
from opendirector.domain.projects import ProjectError, identifier
Expand Down Expand Up @@ -105,6 +106,12 @@ async def lifespan(app):
async def invalid_request(request, error):
# Validation errors must not echo request input containing credentials.
chinese = "请求字段无效,请检查必填项及字段格式。"
contract = next((item for item in error.errors() if item.get("type") in CONTRACT_MESSAGES), None)
if contract is not None:
fields = contract.get("ctx", {}).get("fields")
detail = (contract_message(contract["type"], request.headers.get("accept-language"), contract["msg"], fields)
if fields is not None else localized_error(request, chinese=contract["msg"], status=422, code=contract["type"]))
return JSONResponse({"detail": detail, "code": contract["type"]}, status_code=422)
return JSONResponse(
{
"detail": localized_error(
Expand Down
6 changes: 6 additions & 0 deletions docs/development/lessons.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,9 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u
- **Trigger:** Adding an external harness whose CLI runs shell commands in its own sandbox.
- **Lesson:** Antigravity CLI turns its terminal sandbox on by default in auto mode. With only permission rules passed, every `opendirector` command that reached the app failed with `Operation not permitted`: the macOS sandbox blocked the local socket outside the execution directory, and executables under `~/Documents`. `opendirector --help` still worked and the reply was a well-formed refusal, so a mocked CLI test and a successful turn status both passed while no project change was possible.
- **Check:** Accept a harness only after a real turn changes the project through `opendirector` and the result is read back. Pin the harness's sandbox and approval mode per run instead of inheriting the user's global settings, and let only `opendirector` leave the sandbox rather than every command.

## Rejected commands are parsed again when a project loads

- **Trigger:** Tightening a command model validator, such as requiring another `expectedVersions` entry at parse time.
- **Lesson:** [#645](https://github.com/ThinkFlowLab/OpenDirector/issues/645) needed `generation.submit` to require the origin node version. Commit records also store rejected commands and are parsed with the same models on load, so a submission rejected for that missing version would make the project unreadable if the parser required it.
- **Check:** Enforce new preconditions in `validate_command` against the project, and keep parse-time rules unchanged for recorded commands. Verify that a command rejected under the old rule still parses.
4 changes: 4 additions & 0 deletions docs/guides/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ opendirector --project PROJECT_UUID job wait --all --timeout 300

业务命令按对象分组,参数名使用短横线。复杂参数可使用 JSON 参数,或通过 `--file command.json` 读取含 `payload`、`expectedVersions` 和可选 `expectedPreview` 的对象。`--file -` 从标准输入读取。命令帮助包含从 Pydantic 业务契约派生的参数说明与示例。`--help-field PATH` 展开帮助中返回的结构化字段路径,例如 `opendirector canvas show --help-field payload.item@image.binding`。

`capabilities` 的 `expectedVersions`、命令帮助示例和服务端校验使用同一份版本规则;例如 `generation submit` 需要配置和来源节点两个版本。`generation submit` 的 `--expected-spec-revision` 会自动作为配置的 `expectedVersions`,来源节点版本仍须用 `--expected-version` 明确提供。缺少版本时一次列出全部缺失对象,错误码为 `version_required`,并给出可补充的 `--expected-version` 参数;只有已提供的版本已经变化时才返回 `revision_conflict`,并附上当前版本。`--help-field` 路径无效时返回最近的合法路径、当前层字段和可运行的示例。`canvas update` 只改位置时请使用 `canvas move`(`use_canvas_move`);同时改位置和其他字段时返回 `split_canvas_update`,按顺序给出 `canvas move` 和提交其余字段的 `canvas update` 两条命令,第 2 步使用第 1 步回执中的新版本;同时解锁时先解锁再移动。

`capabilities` lists `expectedVersions` from the same version rule as command help examples and server validation; for example, `generation submit` needs both the configuration and origin node versions. For `generation submit`, `--expected-spec-revision` also supplies the configuration entry in `expectedVersions`; the origin node version still needs an explicit `--expected-version`. A missing version is reported with every missing object at once, code `version_required`, and the `--expected-version` options to add. `revision_conflict` is returned only when a supplied version has changed, with the current revision. An invalid `--help-field` path returns the nearest valid path, the fields at that level and a runnable example. Use `canvas move` for position-only changes rather than `canvas update` (`use_canvas_move`). An update that changes the position together with other fields returns `split_canvas_update` with the `canvas move` and `canvas update` commands in the order to send them; step 2 uses the revision from the step 1 receipt, and an update that also unlocks the node unlocks first.

CLI 输出 JSON。修改回执附带对应的 assetId、itemId、specId 及其列表,视频节点创建回执同时返回包含当前版本的下一步提交命令。参数解析错误直接显示该子命令的完整用法。成功退出码为 0,拒绝或执行失败为 1,参数解析错误及等待任务超时为 2。生成接受回执会在 `next.commands` 返回一条覆盖本次全部任务的 `job wait` 命令,带入服务地址、工程和任务身份。建议按回执等待;等待窗口超时后可以再次执行同一命令。`job wait` 超时结束等待,任务继续由后台执行。

修改命令可在子命令前传 `--operation-id UUID`。相同身份及输入重试复用原回执,输入不同则拒绝。文件导入重放也核对登记文件的内容指纹。需要跨进程恢复暂存上传时,预先通过 `--session UUID` 保持相同会话身份。结果未知时先查询回执,再决定后续操作。
Expand Down
2 changes: 1 addition & 1 deletion docs/guides/openai-images.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ OpenDirector 把 OpenAI Images API 作为**可选**图像生成服务接入。
| 服务行为 | 类别 | 用户看到的提示 |
| --- | --- | --- |
| `401` / `invalid_api_key` | 鉴权失败 | 请在设置中检查 API Key |
| `429` / `rate_limit_exceeded` | 频率限制 | 核对调用频率及套餐额度 |
| `429` / `rate_limit_exceeded` | 频率限制 | 稍后再试;批量提交时降低并发或调用频率,并逐步拉长重试间隔 |
| `429` / `billing_hard_limit_reached` | 额度不足 | 核对账户余额和套餐额度 |
| `400` / `moderation_blocked` | 输入被拒 | 判定提示词或参考图片违反内容政策,请调整后再生成 |
| `5xx` | 服务暂时不可用 | 先核对已有任务,再处理当前步骤 |
Expand Down
7 changes: 5 additions & 2 deletions packages/core/src/opendirector/agent/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from opendirector.agent.tools import AgentTools, tools
from opendirector.domain.projects import ProjectError
from opendirector.domain.creation.commands import COMMAND_MODELS
from opendirector.domain.creation.contract_messages import CONTRACT_MESSAGES
from opendirector.domain.rule_facts import MAX_REFERENCES

REFERENCE_IDS = TypeAdapter(Annotated[list[UUID], Field(min_length=1, max_length=MAX_REFERENCES)])
Expand Down Expand Up @@ -130,15 +131,17 @@ async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue]
error = str(value['error'])
return ToolResult(value={**value, 'error': error} if error else value, error=error)
except ValidationError as failure:
messages = []
messages, codes = [], []
for issue in failure.errors(include_input=False, include_url=False):
location = issue['loc']
if location and location[0] in COMMAND_MODELS:
location = location[1:]
path = '.'.join(str(part) for part in location)
messages.append(f"{path or 'command'}: {issue['msg']}")
if issue['type'] in CONTRACT_MESSAGES:
codes.append(issue['type'])
error = '; '.join(messages)
return ToolResult(value={'error': error}, error=error)
return ToolResult(value={'error': error, **({'code': codes[0]} if codes else {})}, error=error)
except (ProjectError, ValueError, KeyError, OSError, UnicodeError) as failure:
details = {'error': str(failure)}
if isinstance(failure, ProjectError):
Expand Down
43 changes: 42 additions & 1 deletion packages/core/src/opendirector/agent/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from opendirector.domain.creation.assets import AssetDownloadFile, AssetProvenance
from opendirector.domain.creation.base import ObjectVersion
from opendirector.domain.creation.commands import Query, COMMAND_MODELS, parse_command
from opendirector.domain.creation.contract_messages import contract_text, kebab
from opendirector.domain.creation.models import ModelSnapshot
from opendirector.domain.projects import ProjectError
from opendirector.domain.rule_facts import MAX_REFERENCES
Expand Down Expand Up @@ -193,8 +194,45 @@ def minimal_value(node: dict, branch: str | None = None) -> JsonValue:
return False
return None

def field_paths(node: dict, prefix: str, depth: int = 0) -> list[str]:
node = resolve(node)
if depth > 6:
return []
found = []
children = [(f'{prefix}.{key}' if prefix else key, child) for key, child in node.get('properties', {}).items()]
if 'items' in node:
children.append((f'{prefix}.[]' if prefix else '[]', node['items']))
children += [(f'{prefix}@{key}', child) for key, child in branches(node).items()]
for target, child in children:
found.append(target)
found += field_paths(child, target, depth + 1)
return found

def invalid_path(level: str, node: dict, requested: str) -> ProjectError:
paths = field_paths(schema, '')
last = requested.replace('@', '.').rsplit('.', 1)[-1]
nearest = ''
for scope in ([value for value in paths if value.startswith(level)], paths) if level else (paths,):
same_name = sorted((value for value in scope if value.replace('@', '.').rsplit('.', 1)[-1] == last),
key=lambda value: (value.count('.') + value.count('@'), value))
nearest = same_name[0] if same_name else next(iter(difflib.get_close_matches(requested, scope, n=1, cutoff=0.5)), '')
if nearest:
break
nearest = nearest or level
available = [*resolve(node).get('properties', {}), *(f'@{key}' for key in branches(resolve(node)))]
command = resolve(schema).get('properties', {}).get('type', {}).get('const')
target = nearest or (f'{level}.{available[0]}' if level and available else available[0] if available else '')
example = '-'
if command and target:
namespace, action = command.split('.', 1)
example = (f'command_schema {{"type":"{command}","path":"{target}"}} | '
f'opendirector {kebab(namespace)} {kebab(action)} --help-field {target}')
return ProjectError(contract_text('help_field_invalid', requested=requested, nearest=nearest or '-', level=level or '$',
fields=', '.join(available) or '-', example=example), code='help_field_invalid')

node = schema
remaining = path
level = ''
while remaining:
node = resolve(node)
if remaining.startswith('@'):
Expand All @@ -209,7 +247,8 @@ def minimal_value(node: dict, branch: str | None = None) -> JsonValue:
child = node.get('items') if field == '[]' else node.get('properties', {}).get(field)
remaining = remaining[boundary:]
if child is None:
raise ProjectError('Invalid schema field path. Retry with only type for command overview, then use a field path returned by command_schema.')
raise invalid_path(level, node, path)
level = path[:len(path) - len(remaining)]
node = child
if remaining.startswith('.'):
remaining = remaining[1:]
Expand Down Expand Up @@ -238,6 +277,8 @@ def minimal_value(node: dict, branch: str | None = None) -> JsonValue:
spec['purpose'] = 'generation'
item['kind'] = spec['kind']
item['binding'] = {'role': 'generation', 'objectRef': {'id': spec['id']}}
if command == 'generation.submit':
example['payload']['originItemId'] = str(project_id)
model = COMMANDS[command]
parsed_payload = model.model_fields['payload'].annotation.model_validate(example['payload'])
sample = model.model_construct(type=command, payload=parsed_payload, projectId=project_id)
Expand Down
26 changes: 18 additions & 8 deletions packages/core/src/opendirector/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import json
import os
from pathlib import Path
import re
import socket
import shlex
import subprocess
Expand All @@ -37,6 +36,7 @@
ASSET_DOWNLOAD_ENGLISH, ASSET_REVISION_HEADER, AssetDownloadFile, AssetDownloadReceipt,
)
from opendirector.domain.creation.commands import COMMAND_MODELS, command_fingerprint, parse_command
from opendirector.domain.creation.contract_messages import CONTRACT_MESSAGES, contract_message, kebab
from opendirector.domain.projects import ProjectError
from opendirector.domain.timeline_errors import timeline_error, timeline_error_message
from opendirector.domain.url_import import url_import_error, url_import_message
Expand Down Expand Up @@ -73,10 +73,6 @@
groups: dict[str, typer.Typer] = {}


def kebab(name: str) -> str:
return re.sub(r"(?<!^)(?=[A-Z])", "-", name).replace("_", "-").lower()


def group(name: str) -> typer.Typer:
if name not in groups:
groups[name] = typer.Typer(no_args_is_help=True, help=GROUP_HELP[name])
Expand Down Expand Up @@ -1033,6 +1029,10 @@ def capabilities(compact: Annotated[bool, typer.Option("--compact", help="Only n
for field in branch.get("required", ())})}
if branches:
entry["branches"] = [branch.get("description", branch.get("title", "variant")) for branch in branches]
versions = [version["objectType"] for version in
command_help(model.model_json_schema(), "", UUID(int=0))["example"].get("expectedVersions", [])]
if versions:
entry["expectedVersions"] = versions
if not compact:
entry["fields"] = list(schema.get("properties", {}))
commands.append(entry)
Expand Down Expand Up @@ -1145,6 +1145,11 @@ def execute(ctx, file=None, expected_version=None, help_field=None, turn_referen
for value in expected_version or []:
object_type, identity, revision = value.split(":")
versions.append({"objectType": object_type, "id": str(UUID(identity)), "revision": int(revision)})
if kind == "generation.submit" and arguments.get("specId") and arguments.get("expectedSpecRevision") is not None:
spec = {"objectType": "generation_spec", "id": str(UUID(str(arguments["specId"]))),
"revision": int(arguments["expectedSpecRevision"])}
if not any(version["objectType"] == spec["objectType"] and str(version["id"]) == spec["id"] for version in versions):
versions.append(spec)
operation = ctx.obj.operation_id or uuid4()
if kind == "canvas.createGeneration" and turn_reference:
spec = arguments.get("spec")
Expand Down Expand Up @@ -1192,8 +1197,12 @@ def main():
typer.echo(error.ctx.get_help(), err=True)
raise SystemExit(error.exit_code)
except ValidationError as error:
emit({"error": [{"field": ".".join(str(part) for part in item["loc"]), "reason": item["msg"]}
for item in error.errors(include_input=False, include_url=False, include_context=False)]})
language = os.environ.get('OPENDIRECTOR_LANGUAGE', 'en-US')
emit({"error": [{"field": ".".join(str(part) for part in item["loc"]),
"reason": contract_message(item["type"], language, item["msg"],
item.get("ctx", {}).get("fields")) or item["msg"],
**({"code": item["type"]} if item["type"] in CONTRACT_MESSAGES else {})}
for item in error.errors(include_input=False, include_url=False)]})
raise SystemExit(1)
except (ProjectError, OSError, ValueError, httpx.HTTPError) as error:
value = {"error": str(error)}
Expand All @@ -1203,7 +1212,8 @@ def main():
translated = timeline_error_message(error.code, language)
if not language.lower().startswith('zh'):
translated = translated or ASSET_DOWNLOAD_ENGLISH.get(error.code)
value['error'] = translated or url_import_message(error.code, language, str(error)) or str(error)
value['error'] = (translated or url_import_message(error.code, language, str(error))
or contract_message(error.code, language, str(error)) or str(error))
emit(value)
raise SystemExit(1)

Expand Down
Loading
Loading