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
193 changes: 193 additions & 0 deletions packages/core/src/opendirector/agent/command_help.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import difflib
from uuid import UUID

from pydantic import JsonValue

from opendirector.domain.creation.commands import COMMAND_MODELS
from opendirector.domain.creation.contract_messages import contract_text, kebab
from opendirector.domain.projects import ProjectError

EXCLUDED = {'project.create', 'project.trash', 'project.restore', 'asset.import', 'job.checkpoint',
'canvas.applyEdit', 'canvas.publishMedia', 'timeline.publishRender'}

COMMANDS = {name: model for name, model in COMMAND_MODELS.items()
if name not in EXCLUDED}
for command_name, command_model in COMMANDS.items():
assert command_model.__doc__ and command_model.__doc__.strip(), f'Missing command metadata: {command_name}'


def command_help(schema: dict, path: str, project_id: UUID) -> dict:
definitions = schema.get('$defs', {})

def resolve(node: dict) -> dict:
if '$ref' in node:
return {**definitions[node['$ref'].rsplit('/', 1)[1]], **node}
return node

def branches(node: dict) -> dict:
mapping = node.get('discriminator', {}).get('mapping')
if mapping:
return {key: {'$ref': value} for key, value in mapping.items()}
choices = node.get('anyOf', node.get('oneOf', []))
return {str(index): choice for index, choice in enumerate(choices)}

def summary(node: dict, target: str) -> dict:
node = resolve(node)
details = {key: node[key] for key in (
'type', 'format', 'const', 'enum', 'default', 'description', 'minimum', 'maximum',
'exclusiveMinimum', 'exclusiveMaximum', 'minLength', 'maxLength',
'minItems', 'maxItems', 'pattern',
) if key in node}
choices = branches(node)
if choices:
details.setdefault('type', 'union')
details['branches'] = {}
for key, choice in choices.items():
branch = resolve(choice)
details['branches'][key] = {
'path': f'{target}@{key}',
'description': branch.get('description', branch.get('title', branch.get('type', key))),
**{name: branch[name] for name in ('type', 'required', 'const', 'enum') if name in branch},
}
if target:
details['path'] = target
return details

def minimal_value(node: dict, branch: str | None = None) -> JsonValue:
node = resolve(node)
if 'examples' in node:
return node['examples'][0]
if 'const' in node:
return node['const']
if 'enum' in node:
return node['enum'][0]
choices = branches(node)
if choices:
return minimal_value(choices.get(branch, next(iter(choices.values()))))
kind = node.get('type')
if kind == 'object':
return {key: minimal_value(node['properties'][key], 'timeline' if key == 'document' else None) for key in node.get('required', [])}
if kind == 'array':
return [minimal_value(node['items']) for _ in range(node.get('minItems', 0))]
if kind == 'string':
if node.get('format') == 'uuid':
return str(project_id)
if node.get('pattern') == '^sha256:[0-9a-f]{64}$':
return 'sha256:' + '0' * 64
if node.get('pattern') == '^[0-9a-f]{64}$':
return '0' * 64
return 'x' * max(1, node.get('minLength', 0))
if kind in {'integer', 'number'}:
return node.get('minimum', node.get('exclusiveMinimum', -1) + 1)
if kind == 'boolean':
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('@'):
choices = branches(node)
selector = next((key for key in sorted(choices, key=len, reverse=True)
if remaining[1:] == key or remaining[1:].startswith((key + '.', key + '@'))), None)
child = choices.get(selector) if selector is not None else None
remaining = remaining[len(selector) + 1:] if selector is not None else ''
else:
boundary = min((remaining.find(mark) for mark in ('.', '@') if mark in remaining), default=len(remaining))
field = remaining[:boundary]
child = node.get('items') if field == '[]' else node.get('properties', {}).get(field)
remaining = remaining[boundary:]
if child is None:
raise invalid_path(level, node, path)
level = path[:len(path) - len(remaining)]
node = child
if remaining.startswith('.'):
remaining = remaining[1:]

node = resolve(node)
prefix = f'{path}.' if path else ''
result = {'path': path, **summary(node, path)}
if 'description' in node:
result['description'] = node['description']
if 'properties' in node:
result['required'] = node.get('required', [])
result['fields'] = {key: summary(value, prefix + key) for key, value in node['properties'].items()}
if not path:
payload = resolve(node['properties']['payload'])
command = node['properties']['type']['const']
fields = result['fields']
fields.pop('type')
fields['payload']['required'] = payload.get('required', [])
fields['payload']['fields'] = {
key: summary(value, f'payload.{key}') for key, value in payload.get('properties', {}).items()
}
example = {'type': command, 'payload': minimal_value(payload)}
if command == 'canvas.createGeneration':
spec = example['payload']['spec']
item = example['payload']['item']
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)
versions = sample.required_versions()
if versions:
owned = next((getattr(parsed_payload, field, None) for field in ('spec', 'reference', 'document')
if getattr(parsed_payload, field, None) is not None), None)
revision = getattr(parsed_payload, 'expectedSpecRevision', getattr(owned, 'revision', 1))
example['expectedVersions'] = [
{'objectType': kind, 'id': str(identity), 'revision': revision}
for kind, identity in dict.fromkeys(versions)
]
if command == 'asset.delete':
example['expectedPreview'] = '0' * 64
return {
'command': command,
'description': node['description'],
'example': example,
'fields': fields,
}
if 'items' in node:
result['items'] = summary(node['items'], prefix + '[]')
return result
Loading
Loading