feat: create task-center project tasks from native DSH conversations

This commit is contained in:
阿白叔 committed 2026-10-30 14:42:50 +08:00
1 parent e9b77186dc
commit ef40f339cd
23 files changed
+773 -31

No files matched your search

+2 -2
View File
@@ -42,11 +42,11 @@ def launch_environment(data_root: Path) -> dict[str, str]:
return env
def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='', automation=None) -> dict:
def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='', automation=None, creation=None) -> dict:
data_root.mkdir(parents=True, exist_ok=True)
value = snapshot.safe_dict() | {'revision': uuid4().hex,
'events': [str(e)[:300] for e in events][-20:], 'action_result': str(action_result)[:300],
'task_name': str(task_name)[:128], 'automation': automation or {}}
'task_name': str(task_name)[:128], 'automation': automation or {}, 'creation': creation or {}}
temporary = data_root / ('context-' + uuid4().hex + '.tmp')
temporary.write_text(json.dumps(value, ensure_ascii=False), encoding='utf8')
destination = data_root / 'task-context.json'
+91
View File
@@ -0,0 +1,91 @@
"""Validate chat task specifications and create confirmed projects atomically."""
from __future__ import annotations
from hashlib import sha256
import json
from pathlib import Path
import re
from ..trial_task_center.errors import TaskCenterError
from ..trial_task_center.rule_validation import validate_mapping_pairs
def validate_creation_spec(raw):
allowed = {'name', 'note', 'project_directory', 'rules', 'copy_part_number_to_value'}
if not isinstance(raw, dict) or set(raw) - allowed:
raise TaskCenterError('assistant_task_fields', '任务草稿包含不支持的字段。')
def text(value, limit, required=False):
if not isinstance(value, str) or len(value) > limit or (required and not value.strip()) or '\x00' in value:
raise TaskCenterError('assistant_task_text', '任务名称、备注或规则文本无效。')
return value.strip()
value = {'name': text(raw.get('name'), 120, True), 'note': text(raw.get('note', ''), 2000),
'project_directory': text(raw.get('project_directory', ''), 2000), 'rules': [],
'copy_part_number_to_value': raw.get('copy_part_number_to_value', False)}
if not isinstance(value['copy_part_number_to_value'], bool):
raise TaskCenterError('assistant_task_value_option', 'Value 策略必须为明确的开关。')
rules = raw.get('rules', [])
if not isinstance(rules, list) or len(rules) > 30:
raise TaskCenterError('assistant_task_rules', '一次最多创建 30 条替换规则。')
for row in rules:
if not isinstance(row, dict) or set(row) - {'old_part_number', 'new_part_number', 'target_cell', 'custom_value', 'sync_nc'}:
raise TaskCenterError('assistant_task_rule_fields', '替换规则字段无效。')
normalized = {'old_part_number': text(row.get('old_part_number'), 128, True),
'new_part_number': text(row.get('new_part_number'), 128, True),
'target_cell': text(row.get('target_cell', ''), 128),
'sync_nc': row.get('sync_nc', True)}
if 'custom_value' in row:
normalized['custom_value'] = text(row['custom_value'], 500)
if not isinstance(normalized['sync_nc'], bool):
raise TaskCenterError('assistant_task_rule_option', 'NC 策略必须为明确的开关。')
value['rules'].append(normalized)
if value['rules']:
validate_mapping_pairs((row['old_part_number'], row['new_part_number']) for row in value['rules'])
return value
def create_confirmed_tasks(service, request_id, raw, root, selected_paths):
from ..trial_task_center.project_tasks import create_project_tasks
from ..trial_task_center.batch_rules import mutate_batch_rules
from ..trial_task_center.models import TaskStatus
if not isinstance(request_id, str) or not re.fullmatch(r'[a-f0-9]{32}', request_id):
raise TaskCenterError('assistant_request_id', '任务创建请求标识无效。')
# The service accepts only the same public specification as the model tool.
spec = validate_creation_spec(raw)
root = Path(root).resolve()
selected_paths = tuple(sorted({Path(path).resolve() for path in selected_paths}, key=lambda p: str(p).casefold()))
if not selected_paths or len(selected_paths) > 100:
raise TaskCenterError('assistant_project_selection', '请确认 1 至 100 个工程。')
digest = sha256(json.dumps({'spec': spec, 'root': str(root), 'paths': list(map(str, selected_paths))},
sort_keys=True, ensure_ascii=False).encode()).hexdigest()
store = service._store
with store.transaction():
previous = store.assistant_creation_receipt(request_id)
if previous is not None:
if previous['request_hash'] != digest:
raise TaskCenterError('assistant_request_conflict', '同一创建请求不能改用其他参数或工程。')
return previous['result'] | {'replayed': True}
active = {project.path.resolve(): task.task_id for task in store.list_tasks()
if task.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED} for project in store.list_projects(task.task_id)}
existing_ids = list(dict.fromkeys(active[path] for path in selected_paths if path in active))
created = create_project_tasks(store, root, selected_paths=selected_paths, excluded_roots=(service._logging.root,))
names = {task.name.casefold() for task in store.list_tasks()}
tasks = []
for task in created:
names.discard(task.name.casefold())
base_name = spec['name'] if len(created) == 1 else spec['name'] + ' · ' + task.name
name, suffix = base_name, 2
while name.casefold() in names:
name = f'{base_name} ({suffix})'; suffix += 1
names.add(name.casefold())
store.update_task(task.task_id, name=name, note=spec['note'])
tasks.append(store.set_copy_part_number_to_value(task.task_id, spec['copy_part_number_to_value']))
if tasks:
for rule in spec['rules']:
mutate_batch_rules(service, tasks[0].task_id, 'add', **rule,
enabled=True, custom_value_enabled='custom_value' in rule)
result = {'status': 'created' if tasks else 'existing', 'created_count': len(tasks),
'existing_count': len(existing_ids), 'task_ids': [task.task_id for task in tasks] or existing_ids,
'existing_task_ids': existing_ids, 'rules_count': len(spec['rules']), 'cad_execution_started': False,
'tasks': [{'task_id': task.task_id, 'name': task.name, 'status': task.status.value} for task in tasks]}
store.record_assistant_creation(request_id, digest, result)
return result