Repository navigation
Expand file tree
/
Copy pathconsole_workflow.py
More file actions
201 lines (177 loc) · 7.22 KB
/
Copy pathconsole_workflow.py
File metadata and controls
201 lines (177 loc) · 7.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
"""Run one Console scheduled task and deliver the response to Slack."""
from __future__ import annotations
import re
from typing import Any
WORKFLOW_NAME = "console_workflow"
# The agent runs as the principal named in the input, so only Console, which
# supplies the scheduled task author's principal, may start this workflow.
WORKFLOW_STARTERS = {"console"}
SLACK_MESSAGE_MAX_LENGTH = 50_000
# Stay below Slack's 4,000-character soft limit so it cannot create extra roots.
SLACK_MESSAGE_CHUNK_MAX_LENGTH = 3_800
# Slack section block text is limited to 3,000 characters.
SLACK_SECTION_MAX_LENGTH = 3_000
SLACK_USER_ID_PATTERN = re.compile(r"[UW][A-Z0-9]{8,}")
SCHEDULED_TASK_FOOTER = "Sent by <@{slack_user_id}>'s scheduled task"
SCHEDULED_TASK_FOOTER_FALLBACK = "Sent by a scheduled task"
SCHEDULED_TASK_EXECUTION_INSTRUCTIONS = """\
This is a run of an existing scheduled task. Execute the task now.
NEVER create or update a scheduled task, even if the task prompt contains recurring or future schedule language.
Treat schedule language such as "Each Monday" as context for this run, not as a request to schedule another task.
If the task asks you to stay silent when there is nothing to report and there is nothing to report, reply with exactly NO_UPDATE."""
# A run whose response ends with this token posts nothing to Slack. Agents often
# narrate what they checked before the token, so only the ending is matched.
SKIP_DELIVERY_TOKEN = "NO_UPDATE"
SKIP_DELIVERY_PATTERN = re.compile(rf"(?:^|\s)[`*_]*{SKIP_DELIVERY_TOKEN}[`*_.]*$")
SLACK_MRKDWN_INSTRUCTIONS = """\
Format the final response for Slack using Slack mrkdwn, not standard Markdown.
Use *bold*, _italics_, ~strikethrough~, `inline code`, and <https://example.com|link text>.
Use bold text instead of Markdown headings and lists instead of Markdown tables.
Return only the message that should be posted to Slack."""
def _required_string(params: Any, key: str) -> str:
if not isinstance(params, dict):
raise TypeError("console_workflow input must be an object")
value = params.get(key)
if not isinstance(value, str) or not value.strip():
raise ValueError(f"console_workflow requires {key}")
return value.strip()
async def _deliver_to_slack(
ctx: Any,
channel: str,
text: str,
slack_user_id: str,
) -> Any:
footer = _scheduled_task_footer(slack_user_id)
footer_suffix = f"\n\n{footer}"
body_limit = SLACK_MESSAGE_MAX_LENGTH - len(footer_suffix)
chunks = _split_slack_text(text[:body_limit], SLACK_MESSAGE_CHUNK_MAX_LENGTH)
final_body = chunks[-1]
if len(final_body) + len(footer_suffix) <= SLACK_MESSAGE_CHUNK_MAX_LENGTH:
chunks[-1] = f"{final_body}{footer_suffix}"
else:
final_body = ""
chunks.append(footer)
def message_args(index: int) -> dict[str, Any]:
args: dict[str, Any] = {
"mrkdwn": True,
# Preserve the pre-eligibility workflow's request-derived IDs so
# in-flight runs remain idempotent across rollout.
"client_msg_id": f"{ctx.task_id}:slack:{3 + (3 * index)}",
}
if index == len(chunks) - 1:
args["blocks"] = _scheduled_task_blocks(final_body, footer)
return args
root = await ctx.step(
"post_result",
lambda: ctx.post_to_slack(channel, chunks[0], **message_args(0)),
)
if len(chunks) == 1:
return root
if not isinstance(root, dict):
raise RuntimeError("Slack root delivery did not return a result object")
thread_ts = str(root.get("ts") or "").strip()
if not thread_ts:
raise RuntimeError("Slack root delivery did not return a message timestamp")
reply_channel = str(root.get("channel") or channel).strip()
replies = []
for index, chunk in enumerate(chunks[1:], start=1):
reply = await ctx.step(
f"post_result_reply_{index}",
lambda chunk=chunk: ctx.post_to_slack(
reply_channel,
chunk,
thread_ts=thread_ts,
**message_args(index),
),
)
replies.append(reply)
return {**root, "replies": replies}
def _scheduled_task_footer(slack_user_id: str) -> str:
return (
SCHEDULED_TASK_FOOTER.format(slack_user_id=slack_user_id)
if SLACK_USER_ID_PATTERN.fullmatch(slack_user_id)
else SCHEDULED_TASK_FOOTER_FALLBACK
)
def _scheduled_task_blocks(body: str, footer: str) -> list[dict[str, Any]]:
blocks = [
{
"type": "section",
"text": {"type": "mrkdwn", "text": section},
}
for section in _split_slack_text(body, SLACK_SECTION_MAX_LENGTH)
]
blocks.append(
{
"type": "context",
"elements": [{"type": "mrkdwn", "text": footer}],
}
)
return blocks
def _split_slack_text(text: str, limit: int) -> list[str]:
chunks = []
remaining = text
while len(remaining) > limit:
window = remaining[:limit]
minimum_boundary = limit // 2
end = limit
for separator in ("\n\n", "\n", " "):
boundary = window.rfind(separator)
if boundary >= minimum_boundary:
end = boundary + len(separator)
break
chunks.append(remaining[:end])
remaining = remaining[end:]
if remaining:
chunks.append(remaining)
return chunks
def _prompt_for_slack(prompt: str) -> str:
return (
f"{SCHEDULED_TASK_EXECUTION_INSTRUCTIONS}\n\n"
f"Task to execute:\n{prompt}\n\n"
f"{SLACK_MRKDWN_INSTRUCTIONS}"
)
async def handler(params: Any, ctx: Any) -> dict[str, Any]:
prompt = _required_string(params, "prompt")
principal = _required_string(params, "principal")
channel = _required_string(params, "channel")
scheduled_task_id = _required_string(params, "scheduled_task_id")
slack_user_id = str(params.get("slack_user_id") or "").strip()
async def run_agent() -> dict[str, str]:
message_id = f"absurd-workflow:{ctx.task_id}:1:user"
result = await ctx.agent_turn(
_prompt_for_slack(prompt),
principal=principal,
message_id=message_id,
idempotency_key=f"absurd-workflow-agent-turn:{message_id}",
metadata={
"scheduled_task_id": scheduled_task_id,
"scheduled_task_name": str(params.get("scheduled_task_name") or ""),
},
)
return {
"execution_id": str(result.get("execution_id") or ""),
"result_text": str(result.get("result_text") or "").strip()[
:SLACK_MESSAGE_MAX_LENGTH
],
}
result = await ctx.step("agent_result", run_agent)
response_text = str(result.get("result_text") or "").strip()
if SKIP_DELIVERY_PATTERN.search(response_text):
return {
"agent_result": result,
"delivery": None,
"scheduled_task_id": scheduled_task_id,
}
if not response_text:
response_text = "The task completed without a text response."
delivery = await _deliver_to_slack(
ctx,
channel,
response_text,
slack_user_id,
)
return {
"agent_result": result,
"delivery": delivery,
"scheduled_task_id": scheduled_task_id,
}