This commit is contained in:
zyp
2026-11-27 21:27:14 +08:00
parent b18c6efe92
commit 5f204764c9
12 changed files with 563 additions and 28 deletions
+90 -3
View File
@@ -114,6 +114,7 @@ class TurnRuntime:
catalog_read: bool = False
invoke_router: object = None
answer_mode: str = "analysis"
business_relation: str = "unspecified"
class RecordReferenceVerdict(BaseModel):
@@ -252,6 +253,12 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
PlanningModel(context.invoke_router, get_settings().work_assistant_planner_timeout_seconds))
context.decision_mode = route.mode
context.answer_mode = route.answer_mode
context.business_relation = route.business_relation
date_span = single_explicit_date_span(payload.message)
if route.intent == 'business' and date_span and explicit_date_bounds(date_span) is None:
return {"proposal": TurnProposal(intent='business', mode='clarify',
resolved_question=payload.message,
plan=Plan(response_kind='clarification', clarification=f'“{date_span}”不是有效的日期或起止范围,请确认正确日期。')).model_dump()}
if route.intent == "business" and not route.resources and route.capability_gap.strip():
return {"proposal": TurnProposal(intent="business", mode=route.mode,
resolved_question=payload.message,
@@ -276,7 +283,7 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
selected_resources=retrieve_descriptions(payload.message,payload.resources,context.previous_spec)
if route and route.intent == "business" and route.resources:
selected_resources = [r for r in payload.resources if r["id"] in route.resources]
from app.modules.work_assistant.semantic_router import resource_description, query_schema, PLANNING_INSTRUCTION, complete_explicit_summary, source_limitation, asks_identity
from app.modules.work_assistant.semantic_router import resource_description, query_schema, PLANNING_INSTRUCTION, complete_explicit_summary, source_limitation, asks_identity, capability_index
prompt_resources = [resource_description(r) for r in selected_resources]
previous = {key: value for key, value in context.previous_spec.items() if key in {"subject", "period", "question", "response_kind", "limitation", "pending_intent"}}
if context.previous_spec.get("primary_queries"):
@@ -290,7 +297,7 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
content = {
# Stable authorized metadata precedes changing context, allowing provider prefix-cache reuse.
"business_resources": prompt_resources,
"resource_index": [{"id": r["id"], "name": r.get("name", r["id"])} for r in payload.resources],
"resource_index": capability_index(payload.resources),
"meta_skills": [s for s in payload.allowed_skills if s in {
"current-user", "assistant-capabilities", "general-assistance", "system-navigation"}],
"today": payload.today, "calendar": calendar_context(payload.today),
@@ -363,6 +370,12 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
"constraints":error.get("ctx",{}), "message":error["msg"]}
for error in exc.errors()]
errors = []
if candidate.plan.response_kind == 'clarification' and not candidate.plan.clarification:
if route and route.capability_gap.strip():
candidate.plan.clarification = route.capability_gap
else:
errors.append({'location': ['plan', 'clarification'], 'type': 'missing_clarification',
'message': '需要澄清时必须给出具体问题,不能返回空白澄清。'})
meta = {"conversation":"general-assistance", "identity":"current-user", "capabilities":"assistant-capabilities", "navigation":"system-navigation"}
if candidate.intent in {"mutation", "restricted"}:
candidate.reply = ("我可以帮你查看相关记录和操作入口;当前助手不能直接修改或删除业务数据,请在对应业务页面操作。" if candidate.intent == "mutation" else "密码、接口密钥和令牌不在助手可读取的范围内。可以帮你查看不含敏感凭据的业务信息。")
@@ -452,6 +465,11 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
if definition is None:
errors.append({"location": location+["resource"], "type": "unauthorized_resource"})
continue
from .source_contracts import contract_errors, normalize_operation, bind_relation
normalize_operation(query, definition)
bind_relation(query, definition, route.business_relation if route else 'unspecified')
for issue in contract_errors(query, definition, route.business_relation if route else 'unspecified'):
errors.append({'location': location, **issue})
subject_filter = definition.get("subject_filter")
for conflict in definition.get('selection_conflicts', []):
if re.search(conflict['pattern'], payload.message):
@@ -603,6 +621,9 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
scope_notes = []
query_time_scopes = {}
patch = proposal.focus
from .scope_guard import request_only_first_person
if patch.subject_action == 'self' and request_only_first_person(payload.message):
patch.subject_action = 'inherit'
if re.search(r'第[零一二三四五六七八九十两0-9]+(?:位|个|条|项)', payload.message) and plan.resource_queries:
ordinal = _ordinal(payload.message)
if not payload.context_objects or ordinal is None or not 1<=ordinal<=len(payload.context_objects):
@@ -775,8 +796,14 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
query.resource = original['id']
subject_changed=patch.subject_action in {"self","visibility","clear","select","department"} or (
patch.subject_action=="named" and patch.subject_name!=previous.get("subject",{}).get("name"))
from .query_semantics import literal_filter_values, asks_application_status, followup_change
for query in plan.resource_queries:
definition=definitions.get(query.resource,{})
pure_change = followup_change(payload.message, relative_period, definition)
literal_filters = literal_filter_values(payload.message, definition)
query.filters.update(literal_filters)
proposal.cleared_context_fields = [key for key in proposal.cleared_context_fields
if key not in {f"{query.resource}:{field}" for field in literal_filters}]
temporal_keys = {key for key, spec in definition.get('filters', {}).items()
if spec.get('type') == 'date'}
temporal_keys.update(key for pair in definition.get('time_bindings', {}).values() for key in pair)
@@ -784,6 +811,16 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
old=[q for q in anchors if q.get("resource")==query.resource]
if proposal.mode!="followup" or len(old)!=1:
continue
if pure_change:
# The same population is counted/summed, or moved to another period.
# Preserve explicitly changed metric/date fields only; all other
# predicates come from the previous executed query, not defaults.
changed = temporal_keys if pure_change == 'time' else {'summary', 'group_by', 'sort_by', 'sort_direction'} if pure_change == 'metric' else {pure_change}
retained = {k: v for k, v in old[0].get('filters', {}).items()
if k in definition.get('filters', {}) and k not in changed}
query.filters = {**retained, **{k: v for k, v in query.filters.items() if k in changed}}
if query.filters.get('summary'):
query.operation = 'list'
qualifiers=set(definition.get("subject_context_filters",[])) | {definition.get("subject_filter"),definition.get("subject_id_filter"),definition.get("self_filter")}
# Short subject changes retain the previous business predicates.
# Models may regenerate a default status while switching the person.
@@ -805,6 +842,51 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
continue
if field not in query.filters and field in old[0].get("filters",{}):
query.filters[field]=old[0]["filters"][field]
for query in plan.resource_queries:
definition = definitions.get(query.resource, {})
from .source_contracts import bind_relation
if subject.get('mode') != 'visibility':
bind_relation(query, definition, context.business_relation)
if not definition.get('business_role', '').startswith('本人申请'):
continue
literals = literal_filter_values(payload.message, definition)
if 'status' in literals:
query.filters.pop('approval_state', None)
query.filters.pop('query_status', None)
if literals['status'] == '0' and definition.get('filters', {}).get('status', {}).get('values', {}).get('0') == '草稿':
query.filters.pop('submission_state', None)
old = [q for q in anchors if q.get('resource') == query.resource]
inherited_pending = continuing and len(old) == 1 and old[0].get('filters', {}).get('approval_state') == 'pending'
if not inherited_pending and not re.search(r'待审|正在审|还(?:在|没).{0,3}审|未审|审批中', payload.message):
query.filters.pop('approval_state', None)
if 'submission_state' in definition.get('filters', {}) and re.search(r'提交(?:了|的|过)|已提交', payload.message) and '草稿' not in payload.message:
query.filters['submission_state'] = 'submitted'
application_populations = {
(q.resource, q.scope, q.record_id, json.dumps({k: v for k, v in q.filters.items()
if k not in {'status', 'query_status', 'approval_state'}}, sort_keys=True))
for q in plan.resource_queries
if definitions.get(q.resource, {}).get('business_role', '').startswith('本人申请')
}
if asks_application_status(payload.message) and len(application_populations) == 1:
seen = set()
reads = []
focus_indices = []
for old_index, query in enumerate(plan.resource_queries):
definition = definitions.get(query.resource, {})
if definition.get('business_role', '').startswith('本人申请'):
for key in ('status', 'query_status', 'approval_state'):
query.filters.pop(key, None)
# Asking whether an application passed requires reading its
# actual state, not filtering to passed records first.
fingerprint = json.dumps(query.model_dump(exclude={'query_id'}), sort_keys=True)
if fingerprint in seen:
continue
seen.add(fingerprint)
if old_index in patch.focus_queries:
focus_indices.append(len(reads))
reads.append(query)
plan.resource_queries = reads
patch.focus_queries = focus_indices
# Catalog reads already carry the intended scope and predicates, including an exact count follow-up.
for index in (() if context.catalog_read else patch.focus_queries):
if index < 0 or index >= len(plan.resource_queries):
@@ -865,8 +947,13 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict:
if definition.get("self_filter"):
query.filters.pop(definition["self_filter"], None)
elif subject.get("mode") in {"self", "visibility"} and field:
# The actor changes here, not the requested business relationship.
# Preserve reviewed role predicates for self; visibility clears both.
role_fields = {key for binding in definition.get('query_contract', {}).get('relation_filters', {}).values()
for key in binding} if subject['mode'] == 'self' else set()
for key in definition.get("subject_context_filters", [field]):
query.filters.pop(key, None)
if key not in role_fields:
query.filters.pop(key, None)
if definition.get("subject_id_filter"):
query.filters.pop(definition["subject_id_filter"], None)
query.scope = "mine" if subject["mode"] == "self" else "accessible"