Skip to content

Agent Zero AI framework

Tighten Office document auto-handoff

Alessandro8a6d47b23fb7
diff --git a/plugins/_office/extensions/python/tool_execute_after/_20_document_response_affordance.py b/plugins/_office/extensions/python/tool_execute_after/_20_document_response_affordance.py
index 133ea4931..2634a6f24 100644
--- a/plugins/_office/extensions/python/tool_execute_after/_20_document_response_affordance.py
+++ b/plugins/_office/extensions/python/tool_execute_after/_20_document_response_affordance.py
@@ -11,6 +11,9 @@ from helpers.tool import Response
from plugins._office.helpers import document_affordance, wopi_store
+HANDOFF_CREATED_FLAG = "_office_document_handoff_created"
+
+
class DocumentResponseAffordance(Extension):
async def execute(
self,
@@ -18,12 +21,22 @@ class DocumentResponseAffordance(Extension):
response: Response | None = None,
**kwargs: Any,
):
- if tool_name != "response" or not self.agent or response is None:
+ if not self.agent or response is None:
+ return
+
+ if tool_name == "document_artifact":
+ if (response.additional or {}).get("file_id"):
+ self.agent.loop_data.params_persistent[HANDOFF_CREATED_FLAG] = True
+ return
+
+ if tool_name != "response":
return
tool = self.agent.loop_data.current_tool
if not tool:
return
+ if self.agent.loop_data.params_persistent.get(HANDOFF_CREATED_FLAG):
+ return
text = str(tool.args.get("text") or tool.args.get("message") or response.message or "").strip()
user_message = self.agent.last_user_message.content if self.agent.last_user_message else ""
@@ -51,6 +64,7 @@ class DocumentResponseAffordance(Extension):
content = json.dumps(payload, indent=2, ensure_ascii=False)
self.agent.hist_add_tool_result("document_artifact", content, **additional)
+ self.agent.loop_data.params_persistent[HANDOFF_CREATED_FLAG] = True
display_path = display_workspace_path(doc["path"])
note = document_affordance.format_created_response(doc["basename"], display_path)
diff --git a/plugins/_office/helpers/document_affordance.py b/plugins/_office/helpers/document_affordance.py
index e59751b83..79d928324 100644
--- a/plugins/_office/helpers/document_affordance.py
+++ b/plugins/_office/helpers/document_affordance.py
@@ -11,16 +11,20 @@ MIN_EXPLICIT_ARTIFACT_CHARS = 240
MIN_EXPLICIT_ARTIFACT_WORDS = 35
CREATE_TERMS = {
- "write",
- "draft",
+ "author",
+ "build",
"compose",
+ "convert",
"create",
+ "draft",
+ "format",
"generate",
+ "make",
"prepare",
"produce",
- "make",
- "build",
- "author",
+ "save",
+ "turn",
+ "write",
}
DOCUMENT_TERMS = {
@@ -65,6 +69,49 @@ PRESENTATION_TERMS = {
"slides",
}
+DELIVERABLE_TERMS = {
+ "brief",
+ "contract",
+ "cv",
+ "letter",
+ "manual",
+ "memo",
+ "policy",
+ "proposal",
+ "report",
+ "resume",
+ "spec",
+ "whitepaper",
+}
+
+EXPLICIT_FORMAT_TERMS = {
+ "docx",
+ "odt",
+ "ods",
+ "odp",
+ "pptx",
+ "xlsx",
+}
+
+HANDOFF_TERMS = {
+ "artifact",
+ "artifacts",
+ "canvas",
+ "downloadable",
+ "editable",
+ "in office",
+ "office canvas",
+ "open it",
+ "open in office",
+ "save it",
+ "save this",
+}
+
+FILE_HANDOFF_TERMS = {
+ "file",
+ "files",
+}
+
CHAT_ONLY_TERMS = {
"answer in chat",
"in chat",
@@ -107,10 +154,12 @@ def decide_response_artifact(user_message: Any, response_text: str) -> ArtifactD
if looks_like_tool_or_status_response(response_text):
return None
- kind, fmt, explicit_artifact = infer_kind_and_format(lowered_user)
- if not explicit_artifact and not has_document_creation_intent(lowered_user):
+ kind, fmt = infer_kind_and_format(lowered_user)
+ intent = artifact_intent(lowered_user, response_text)
+ if not intent:
return None
+ explicit_artifact = intent == "explicit_handoff"
if not is_substantial(response_text, explicit_artifact):
return None
@@ -120,7 +169,7 @@ def decide_response_artifact(user_message: Any, response_text: str) -> ArtifactD
fmt=fmt,
title=title,
content=response_text,
- reason="explicit" if explicit_artifact else "document_intent",
+ reason=intent,
)
@@ -151,17 +200,22 @@ def normalize_text(value: str) -> str:
return re.sub(r"\s+", " ", value.lower()).strip()
-def infer_kind_and_format(lowered_user: str) -> tuple[str, str, bool]:
- explicit = False
+def infer_kind_and_format(lowered_user: str) -> tuple[str, str]:
if has_any(lowered_user, PRESENTATION_TERMS):
- explicit = True
- return "presentation", "pptx", explicit
+ return "presentation", "pptx"
if has_any(lowered_user, SPREADSHEET_TERMS):
- explicit = True
- return "spreadsheet", "xlsx", explicit
- if has_any(lowered_user, DOCUMENT_TERMS):
- explicit = True
- return "document", "docx", explicit
+ return "spreadsheet", "xlsx"
+ return "document", "docx"
+
+
+def artifact_intent(lowered_user: str, response_text: str) -> str | None:
+ if not has_document_creation_intent(lowered_user):
+ return None
+ if has_explicit_handoff_signal(lowered_user):
+ return "explicit_handoff"
+ if has_any(lowered_user, DELIVERABLE_TERMS) and looks_like_standalone_artifact(response_text):
+ return "document_intent"
+ return None
def has_document_creation_intent(lowered_user: str) -> bool:
@@ -171,6 +225,28 @@ def has_document_creation_intent(lowered_user: str) -> bool:
)
+def has_explicit_handoff_signal(lowered_user: str) -> bool:
+ if has_any(lowered_user, EXPLICIT_FORMAT_TERMS | HANDOFF_TERMS):
+ return True
+ if has_any(lowered_user, FILE_HANDOFF_TERMS) and has_any(
+ lowered_user,
+ DOCUMENT_TERMS | SPREADSHEET_TERMS | PRESENTATION_TERMS,
+ ):
+ return True
+ if re.search(
+ r"\b(?:convert|format|save|turn)\b(?:\W+\w+){0,8}?\W+(?:as|to|into)\s+"
+ r"(?:a|an|the)?\s*(?:doc|document|spreadsheet|workbook|presentation|deck|slides|docx|xlsx|pptx)\b",
+ lowered_user,
+ ):
+ return True
+ return bool(re.search(
+ r"\b(?:write|draft|compose|create|generate|prepare|produce|make|build|author|format)\b"
+ r"(?:\s+(?:me|us|a|an|the|new|blank|editable|office|word|excel|powerpoint))*"
+ r"\s+(?:doc|document|spreadsheet|workbook|presentation|deck|slides)\b",
+ lowered_user,
+ ))
+
+
def has_any(text: str, terms: set[str]) -> bool:
return any(re.search(rf"\b{re.escape(term)}\b", text) for term in terms)
@@ -192,6 +268,27 @@ def looks_like_tool_or_status_response(text: str) -> bool:
return False
+def looks_like_standalone_artifact(text: str) -> bool:
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
+ if not lines or not title_from_response(text):
+ return False
+
+ heading_count = 0
+ formal_marker_count = 0
+ for line in lines[:40]:
+ normalized = normalize_text(line)
+ if re.match(r"^(#{1,4}\s+|\*\*.+\*\*$|[0-9]+[.)]\s+[A-Z])", line):
+ heading_count += 1
+ if re.match(
+ r"^(executive summary|summary|purpose|scope|background|introduction|"
+ r"recommendations?|conclusion|to:|from:|subject:|date:)\b",
+ normalized,
+ ):
+ formal_marker_count += 1
+
+ return heading_count >= 2 or formal_marker_count >= 2
+
+
def infer_title(user_text: str, response_text: str, kind: str) -> str:
response_title = title_from_response(response_text)
if response_title:
diff --git a/tests/test_office_document_affordance.py b/tests/test_office_document_affordance.py
new file mode 100644
index 000000000..2143c2212
--- /dev/null
+++ b/tests/test_office_document_affordance.py
@@ -0,0 +1,124 @@
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+if str(PROJECT_ROOT) not in sys.path:
+ sys.path.insert(0, str(PROJECT_ROOT))
+
+from plugins._office.helpers import document_affordance
+
+
+def substantial_text(prefix: str = "Here is the material.") -> str:
+ paragraph = (
+ "This section gives concrete context, constraints, tradeoffs, and next steps "
+ "so the artifact has enough substance to be useful in a real collaboration. "
+ )
+ return f"{prefix}\n\n" + paragraph * 8
+
+
+def standalone_report() -> str:
+ paragraph = (
+ "The team should align the operating model, clarify ownership, and preserve "
+ "a concise decision trail so execution remains calm, inspectable, and repeatable. "
+ )
+ return (
+ "# Retention Report\n\n"
+ "## Executive Summary\n"
+ f"{paragraph * 4}\n\n"
+ "## Recommendations\n"
+ f"{paragraph * 4}"
+ )
+
+
+def test_explicit_docx_request_creates_document_artifact():
+ decision = document_affordance.decide_response_artifact(
+ "Please create a DOCX report for the leadership review.",
+ substantial_text(),
+ )
+
+ assert decision is not None
+ assert decision.kind == "document"
+ assert decision.fmt == "docx"
+ assert decision.reason == "explicit_handoff"
+
+
+def test_explicit_spreadsheet_file_request_creates_spreadsheet_artifact():
+ decision = document_affordance.decide_response_artifact(
+ "Build an editable spreadsheet file for this budget.",
+ substantial_text(),
+ )
+
+ assert decision is not None
+ assert decision.kind == "spreadsheet"
+ assert decision.fmt == "xlsx"
+ assert decision.reason == "explicit_handoff"
+
+
+def test_convert_into_document_creates_document_artifact():
+ decision = document_affordance.decide_response_artifact(
+ "Convert this into a document.",
+ substantial_text(),
+ )
+
+ assert decision is not None
+ assert decision.kind == "document"
+ assert decision.reason == "explicit_handoff"
+
+
+def test_long_document_topic_does_not_create_artifact_without_handoff_signal():
+ decision = document_affordance.decide_response_artifact(
+ "Write a detailed explanation of the document handoff implementation.",
+ substantial_text(),
+ )
+
+ assert decision is None
+
+
+def test_long_policy_question_does_not_create_artifact_without_create_intent():
+ decision = document_affordance.decide_response_artifact(
+ "What should our remote-work policy say about async updates?",
+ substantial_text(),
+ )
+
+ assert decision is None
+
+
+def test_office_as_workplace_topic_is_not_a_handoff_signal():
+ decision = document_affordance.decide_response_artifact(
+ "Write a memo about office etiquette.",
+ substantial_text(),
+ )
+
+ assert decision is None
+
+
+def test_deliverable_request_needs_standalone_artifact_shape():
+ decision = document_affordance.decide_response_artifact(
+ "Draft a report about retention risks.",
+ substantial_text(),
+ )
+
+ assert decision is None
+
+
+def test_deliverable_request_with_artifact_shape_creates_document_artifact():
+ decision = document_affordance.decide_response_artifact(
+ "Draft a report about retention risks.",
+ standalone_report(),
+ )
+
+ assert decision is not None
+ assert decision.kind == "document"
+ assert decision.reason == "document_intent"
+
+
+def test_chat_only_instruction_blocks_even_explicit_file_request():
+ decision = document_affordance.decide_response_artifact(
+ "Create a DOCX report, but just answer in chat.",
+ standalone_report(),
+ )
+
+ assert decision is None