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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
//! A2A worker-event conversion into task stream events.
use super::schema::*;
use super::*;
pub(super) struct A2aWorkerSink {
pub(super) task_id: String,
pub(super) tasks: TaskStore,
}
impl harn_vm::agent_events::AgentEventSink for A2aWorkerSink {
fn handle_event(&self, event: &harn_vm::agent_events::AgentEvent) {
let payload = match event {
harn_vm::agent_events::AgentEvent::Artifact {
artifact_id,
kind,
title,
mime_type,
spec,
fallback,
size_bytes,
provenance,
metadata,
..
} => {
self.emit_agent_artifact(AgentArtifactUpdate {
artifact_id,
kind,
title: title.as_deref(),
mime_type,
spec,
fallback,
size_bytes: *size_bytes,
provenance,
metadata,
});
return;
}
harn_vm::agent_events::AgentEvent::ToolCallUpdate {
tool_call_id,
tool_name,
status,
raw_output: Some(output),
..
} if *status == harn_vm::agent_events::ToolCallStatus::Completed => {
self.emit_tool_artifact(tool_call_id, tool_name, output);
return;
}
harn_vm::agent_events::AgentEvent::WorkerUpdate {
worker_id,
worker_name,
worker_task,
worker_mode,
event,
status,
metadata,
audit,
..
} => {
let mut payload = json!({
"type": "worker_update",
"taskId": self.task_id,
"workerId": worker_id,
"workerName": worker_name,
"workerTask": worker_task,
"workerMode": worker_mode,
"event": event.as_str(),
"status": status,
"terminal": event.is_terminal(),
"metadata": metadata,
});
if let Some(audit) = audit {
payload["audit"] = audit.clone();
}
payload
}
harn_vm::agent_events::AgentEvent::PlanDocumentUpdated { event, .. } => {
let document = event.document();
json!({
"type": "harn_plan_document",
"taskId": self.task_id,
"entries": harn_vm::llm::plan::plan_document_entries(document),
"planDocument": document,
})
}
harn_vm::agent_events::AgentEvent::ProgressReported {
message, entries, ..
} => {
self.emit_progress_status(message.as_deref(), entries);
return;
}
harn_vm::agent_events::AgentEvent::HitlRequested {
request_id,
kind,
payload,
..
} => {
self.transition_input_required(request_id, kind, payload);
return;
}
harn_vm::agent_events::AgentEvent::HitlResolved {
request_id,
kind,
outcome,
..
} => {
self.resolve_input_required(request_id, kind, outcome);
return;
}
_ => return,
};
{
let mut tasks = self.tasks.lock().expect("tasks poisoned");
let Some(task) = tasks.get_mut(&self.task_id) else {
return;
};
publish_locked(task, payload);
}
// No `deliver_push` here: worker_update events stream live to
// active subscribers but don't fire push-config webhooks. Push
// delivery is reserved for the canonical task lifecycle
// transitions so high-volume worker traffic doesn't flood
// outbound HTTP endpoints.
}
}
struct AgentArtifactUpdate<'a> {
artifact_id: &'a str,
kind: &'a str,
title: Option<&'a str>,
mime_type: &'a str,
spec: &'a JsonValue,
fallback: &'a str,
size_bytes: u64,
provenance: &'a JsonValue,
metadata: &'a JsonValue,
}
impl A2aWorkerSink {
/// Translate a validated Harn artifact event into an A2A
/// `TaskArtifactUpdateEvent`. The declarative spec is the primary data
/// part; `fallback` gives text-only clients a stable degraded view.
fn emit_agent_artifact(&self, update: AgentArtifactUpdate<'_>) {
let name = update.title.unwrap_or(update.kind);
let artifact = json!({
"artifactId": update.artifact_id,
"name": name,
"parts": [
{
"type": "data",
"data": {
"kind": update.kind,
"mimeType": update.mime_type,
"spec": update.spec,
},
},
{
"type": "text",
"text": update.fallback,
},
],
"metadata": {
"timestamp": current_timestamp_rfc3339(),
"artifact_kind": update.kind,
"mime_type": update.mime_type,
"size_bytes": update.size_bytes,
"provenance": update.provenance,
"harn_metadata": update.metadata,
}
});
self.publish_artifact_update(artifact);
}
/// Translate a completed tool call's output into an A2A
/// `TaskArtifactUpdateEvent` and append the resulting artifact to
/// the task's stored artifact list. Each tool call materialises as
/// a single artifact (`lastChunk: true`, `append: false`) keyed by
/// the model-issued `tool_call_id` so streaming subscribers and
/// `tasks/get` callers see the same canonical shape.
fn emit_tool_artifact(&self, tool_call_id: &str, tool_name: &str, output: &JsonValue) {
let artifact = tool_output_artifact(tool_call_id, tool_name, output);
self.publish_artifact_update(artifact);
}
fn publish_artifact_update(&self, artifact: JsonValue) {
let context_id = {
let tasks = self.tasks.lock().expect("tasks poisoned");
tasks
.get(&self.task_id)
.and_then(|task| task.context_id.clone())
};
let mut event = json!({
"kind": "artifact-update",
"taskId": self.task_id,
"artifact": artifact,
"append": false,
"lastChunk": true,
});
if let Some(context_id) = context_id {
event["contextId"] = JsonValue::String(context_id);
}
let mut tasks = self.tasks.lock().expect("tasks poisoned");
let Some(task) = tasks.get_mut(&self.task_id) else {
return;
};
if task.status.is_terminal() {
return;
}
task.artifacts.push(artifact);
publish_locked(task, event);
}
fn emit_progress_status(&self, message: Option<&str>, entries: &JsonValue) {
let Some(text) = render_progress_message(message, entries) else {
return;
};
let mut tasks = self.tasks.lock().expect("tasks poisoned");
let Some(task) = tasks.get_mut(&self.task_id) else {
return;
};
if task.status.is_terminal() {
return;
}
task.status = TaskStatus::Working;
let mut event = json!({
"kind": "status-update",
"type": "status",
"taskId": self.task_id,
"status": {
"state": TaskStatus::Working.as_str(),
"message": {
"id": Uuid::now_v7().to_string(),
"role": "agent",
"parts": [
{
"kind": "text",
"type": "text",
"text": text,
}
],
},
},
"final": false,
});
if let Some(context_id) = task.context_id.as_ref() {
event["contextId"] = JsonValue::String(context_id.clone());
}
publish_locked(task, event);
}
/// Flip the task into `input-required` while a HITL primitive is
/// blocked waiting for a response. The script remains suspended on
/// a waitpoint; subscribers see two events — a structured `hitl`
/// extension event carrying the request payload, then the canonical
/// `status` transition. Idempotent for repeat HITL requests inside
/// the same task: only the first transitions the status.
///
/// No push-config webhook delivery here, mirroring the
/// `worker_update` policy: HITL transitions stream live to active
/// SSE subscribers and surface on `tasks/get`, but high-frequency
/// status flips don't fan out to outbound webhook endpoints.
fn transition_input_required(&self, request_id: &str, kind: &str, payload: &JsonValue) {
let mut tasks = self.tasks.lock().expect("tasks poisoned");
let Some(task) = tasks.get_mut(&self.task_id) else {
return;
};
// Don't override a terminal/cancelled task: the waitpoint
// emit can race the cancel path. Once the task is dead it
// must stay dead.
if task.status.is_terminal() {
return;
}
let hitl_event = json!({
"type": "hitl",
"taskId": self.task_id,
"phase": "requested",
"requestId": request_id,
"kind": kind,
"payload": payload,
});
publish_locked(task, hitl_event);
if task.status != TaskStatus::InputRequired {
task.status = TaskStatus::InputRequired;
publish_locked(task, status_event(&self.task_id, TaskStatus::InputRequired));
}
}
/// Companion to `transition_input_required`. Flip back to `working`
/// once the waitpoint resolves so subscribers see the task resume
/// (or terminate naturally on the next tick if the script returned
/// from the HITL call). Only flips out of `input-required`; if a
/// later `auth-required` / cancellation snuck in, leave it.
fn resolve_input_required(&self, request_id: &str, kind: &str, outcome: &str) {
let mut tasks = self.tasks.lock().expect("tasks poisoned");
let Some(task) = tasks.get_mut(&self.task_id) else {
return;
};
let hitl_event = json!({
"type": "hitl",
"taskId": self.task_id,
"phase": "resolved",
"requestId": request_id,
"kind": kind,
"outcome": outcome,
});
publish_locked(task, hitl_event);
if task.status == TaskStatus::InputRequired {
task.status = TaskStatus::Working;
publish_locked(task, status_event(&self.task_id, TaskStatus::Working));
}
}
}
fn render_progress_message(message: Option<&str>, entries: &JsonValue) -> Option<String> {
let mut sections = Vec::new();
if let Some(message) = message.map(str::trim).filter(|message| !message.is_empty()) {
sections.push(message.to_string());
}
if let Some(entries) = entries.as_array().filter(|entries| !entries.is_empty()) {
let mut lines = vec!["Plan:".to_string()];
for entry in entries {
let Some(content) = entry
.get("content")
.and_then(JsonValue::as_str)
.map(str::trim)
.filter(|content| !content.is_empty())
else {
continue;
};
let status = entry
.get("status")
.and_then(JsonValue::as_str)
.unwrap_or("pending");
let marker = if status == "completed" { "[x]" } else { "[ ]" };
let mut line = format!("- {marker} {content}");
let mut qualifiers = Vec::new();
if !matches!(status, "pending" | "completed") {
qualifiers.push(status.replace('_', " "));
}
if let Some(priority) = entry
.get("priority")
.and_then(JsonValue::as_str)
.filter(|priority| !priority.is_empty())
{
qualifiers.push(format!("priority: {priority}"));
}
if !qualifiers.is_empty() {
line.push_str(" (");
line.push_str(&qualifiers.join(", "));
line.push(')');
}
lines.push(line);
}
if lines.len() > 1 {
sections.push(lines.join("\n"));
}
}
if sections.is_empty() {
None
} else {
Some(sections.join("\n\n"))
}
}