pi-workflows 0.16.3

Terminal client and live relay for hosted pi-workflows state
Documentation
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! Serde types for the workflow documents carried in server-owned run views.
//! Unknown document fields are tolerated, but the client envelope is strict.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;

pub const RUN_BUNDLE_SCHEMA: &str = "pi-workflows.run-run.v1";
pub const RUN_STATE_SCHEMA: &str = "pi-workflows.run-state.v1";
pub const DEFINITION_SNAPSHOT_SCHEMA: &str = "pi-workflows.definition-snapshot.v1";
pub const SESSION_BINDING_SCHEMA: &str = "pi-workflows.session-binding.v1";
pub const SESSION_EVENT_SCHEMA: &str = "pi-workflows.session-event.v1";
pub const SESSION_CAPTURE_SCHEMA: &str = "pi-workflows.session-capture.v1";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunStatus {
    Queued,
    Running,
    Waiting,
    Paused,
    Completed,
    Failed,
    TimedOut,
    Cancelled,
    Ambiguous,
}

impl RunStatus {
    pub fn is_terminal(self) -> bool {
        matches!(
            self,
            RunStatus::Completed | RunStatus::Failed | RunStatus::TimedOut | RunStatus::Cancelled
        )
    }

    pub fn label(self) -> &'static str {
        match self {
            RunStatus::Queued => "queued",
            RunStatus::Running => "running",
            RunStatus::Waiting => "waiting",
            RunStatus::Paused => "paused",
            RunStatus::Completed => "completed",
            RunStatus::Failed => "failed",
            RunStatus::TimedOut => "timed_out",
            RunStatus::Cancelled => "cancelled",
            RunStatus::Ambiguous => "ambiguous",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkflowActivity {
    SupervisedRunner,
    OriginTurn,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkflowControl {
    Pause,
    Resume,
    Cancel,
    Answer,
    Review,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WorkflowDisplay {
    pub status: RunStatus,
    pub activity: Option<WorkflowActivity>,
    pub controls: Vec<WorkflowControl>,
    pub reason: Option<String>,
    #[serde(rename = "reasonContent", skip_serializing_if = "Option::is_none")]
    pub reason_content: Option<Value>,
}

impl WorkflowDisplay {
    pub fn active_node<'a>(&self, state: &'a RunState) -> Option<&'a str> {
        if self.status != RunStatus::Running {
            return None;
        }
        state.current_node.as_deref().or_else(|| {
            (self.activity == Some(WorkflowActivity::OriginTurn))
                .then_some(state.waiting_on.as_deref())
                .flatten()
        })
    }
}

#[cfg(test)]
mod workflow_display_tests {
    use super::{RunState, RunStatus, WorkflowActivity, WorkflowControl, WorkflowDisplay};
    use serde_json::json;

    #[test]
    fn preserves_the_server_display_and_uses_only_a_running_origin_turn_as_the_active_wait() {
        let state: RunState = serde_json::from_value(json!({
            "schema":"pi-workflows.run-state.v1",
            "traceSeq":1,
            "runId":"run-1",
            "workflowName":"smoke",
            "startedAt":"2026-01-01T00:00:00.000Z",
            "updatedAt":"2026-01-01T00:00:01.000Z",
            "status":"waiting",
            "input":{},
            "outputs":{},
            "results":{},
            "steps":[],
            "waitingOn":"work"
        }))
        .unwrap();
        let running: WorkflowDisplay = serde_json::from_value(json!({
            "status":"running",
            "activity":"origin_turn",
            "controls":["pause","cancel"],
            "reason":null,
            "reasonContent":{"turn":"active"}
        }))
        .unwrap();

        assert_eq!(running.status, RunStatus::Running);
        assert_eq!(running.activity, Some(WorkflowActivity::OriginTurn));
        assert_eq!(
            running.controls,
            vec![WorkflowControl::Pause, WorkflowControl::Cancel]
        );
        assert_eq!(running.active_node(&state), Some("work"));

        let waiting = WorkflowDisplay {
            status: RunStatus::Waiting,
            activity: None,
            controls: vec![WorkflowControl::Pause, WorkflowControl::Cancel],
            reason: Some("waiting".into()),
            reason_content: None,
        };
        assert_eq!(waiting.active_node(&state), None);
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NodeOutcome {
    Ok,
    TimedOut,
    Failed,
    Cancelled,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum WorkflowSource {
    Builtin { id: String, revision: String },
    File { path: String, hash: String },
}

impl WorkflowSource {
    pub fn display(&self) -> String {
        match self {
            WorkflowSource::Builtin { id, revision } => format!("builtin:{id}@{revision}"),
            WorkflowSource::File { path, .. } => path.clone(),
        }
    }
}

#[cfg(test)]
mod workflow_source_tests {
    use super::WorkflowSource;

    #[test]
    fn parses_and_displays_each_source_kind() {
        let builtin: WorkflowSource =
            serde_json::from_str(r#"{"kind":"builtin","id":"monitor","revision":"1"}"#)
                .expect("built-in source should parse");
        let file: WorkflowSource =
            serde_json::from_str(r#"{"kind":"file","path":"/tmp/demo.workflow.ts","hash":"abc"}"#)
                .expect("file source should parse");

        assert_eq!(builtin.display(), "builtin:monitor@1");
        assert_eq!(file.display(), "/tmp/demo.workflow.ts");
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Manifest {
    pub schema: String,
    #[serde(rename = "runId")]
    pub run_id: String,
    #[serde(rename = "workflowName")]
    pub workflow_name: String,
    #[serde(rename = "runTitle", skip_serializing_if = "Option::is_none")]
    pub run_title: Option<String>,
    #[serde(rename = "workflowSource", skip_serializing_if = "Option::is_none")]
    pub workflow_source: Option<WorkflowSource>,
    #[serde(rename = "startedAt")]
    pub started_at: String,
    #[serde(rename = "finishedAt", skip_serializing_if = "Option::is_none")]
    pub finished_at: Option<String>,
    pub status: RunStatus,
    #[serde(rename = "traceSchema")]
    pub trace_schema: String,
    pub paths: ManifestPaths,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ManifestPaths {
    pub workflow: String,
    pub state: String,
    pub trace: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub artifacts: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RunState {
    pub schema: String,
    #[serde(rename = "traceSeq")]
    pub trace_seq: u64,
    #[serde(rename = "runId")]
    pub run_id: String,
    #[serde(rename = "workflowName")]
    pub workflow_name: String,
    #[serde(rename = "runTitle", skip_serializing_if = "Option::is_none")]
    pub run_title: Option<String>,
    #[serde(rename = "workflowSource", skip_serializing_if = "Option::is_none")]
    pub workflow_source: Option<WorkflowSource>,
    #[serde(rename = "parentRunId", skip_serializing_if = "Option::is_none")]
    pub parent_run_id: Option<String>,
    #[serde(rename = "carriedStepCount", skip_serializing_if = "Option::is_none")]
    pub carried_step_count: Option<u64>,
    #[serde(rename = "workflowSources", skip_serializing_if = "Option::is_none")]
    pub workflow_sources: Option<Vec<Value>>,
    #[serde(rename = "definitionDigest", skip_serializing_if = "Option::is_none")]
    pub definition_digest: Option<String>,
    #[serde(rename = "startedAt")]
    pub started_at: String,
    #[serde(rename = "finishedAt", skip_serializing_if = "Option::is_none")]
    pub finished_at: Option<String>,
    #[serde(rename = "updatedAt")]
    pub updated_at: String,
    pub status: RunStatus,
    pub input: Value,
    pub outputs: BTreeMap<String, Value>,
    pub results: BTreeMap<String, Value>,
    pub steps: Vec<StepRecord>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updates: Option<Vec<Value>>,
    #[serde(rename = "currentNode", skip_serializing_if = "Option::is_none")]
    pub current_node: Option<String>,
    #[serde(rename = "currentAttemptId", skip_serializing_if = "Option::is_none")]
    pub current_attempt_id: Option<String>,
    #[serde(
        rename = "currentNodeStartedAt",
        skip_serializing_if = "Option::is_none"
    )]
    pub current_node_started_at: Option<String>,
    #[serde(
        rename = "currentSettingsScopeId",
        skip_serializing_if = "Option::is_none"
    )]
    pub current_settings_scope_id: Option<String>,
    #[serde(
        rename = "currentSettingsChangeNumber",
        skip_serializing_if = "Option::is_none"
    )]
    pub current_settings_change_number: Option<u64>,
    #[serde(
        rename = "currentSettingsHash",
        skip_serializing_if = "Option::is_none"
    )]
    pub current_settings_hash: Option<String>,
    #[serde(rename = "statusDetail", skip_serializing_if = "Option::is_none")]
    pub status_detail: Option<String>,
    #[serde(rename = "humanDecision", skip_serializing_if = "Option::is_none")]
    pub human_decision: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub paused: Option<bool>,
    #[serde(rename = "waitingOn", skip_serializing_if = "Option::is_none")]
    pub waiting_on: Option<String>,
    #[serde(rename = "finalOutput", skip_serializing_if = "Option::is_none")]
    pub final_output: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NodeResult {
    #[serde(rename = "attemptId")]
    pub attempt_id: String,
    #[serde(rename = "nodeId")]
    pub node_id: String,
    #[serde(rename = "nodeType")]
    pub node_type: String,
    pub outcome: NodeOutcome,
    #[serde(rename = "startedAt")]
    pub started_at: String,
    #[serde(rename = "finishedAt")]
    pub finished_at: String,
    #[serde(rename = "durationMs")]
    pub duration_ms: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StepRecord {
    #[serde(rename = "attemptId")]
    pub attempt_id: String,
    #[serde(rename = "nodeId")]
    pub node_id: String,
    #[serde(rename = "nodeType")]
    pub node_type: String,
    pub outcome: NodeOutcome,
    #[serde(rename = "startedAt")]
    pub started_at: String,
    #[serde(rename = "finishedAt")]
    pub finished_at: String,
    /// Full prompt for agent steps (`null` otherwise); may be an
    /// externalized `$artifact` object in persisted form.
    pub prompt: Value,
    pub output: Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<ActionReceipt>,
    #[serde(rename = "assistantMessage", skip_serializing_if = "Option::is_none")]
    pub assistant_message: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conversation: Option<ConversationRange>,
    #[serde(rename = "settingsScopeId", skip_serializing_if = "Option::is_none")]
    pub settings_scope_id: Option<String>,
    #[serde(
        rename = "settingsChangeNumber",
        skip_serializing_if = "Option::is_none"
    )]
    pub settings_change_number: Option<u64>,
    #[serde(rename = "settingsHash", skip_serializing_if = "Option::is_none")]
    pub settings_hash: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionReceipt {
    #[serde(rename = "actionType")]
    pub action_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    #[serde(rename = "exitCode", skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signal: Option<Value>,
    #[serde(rename = "durationMs", skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<f64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConversationRange {
    #[serde(rename = "firstEntryId")]
    pub first_entry_id: String,
    #[serde(rename = "lastEntryId")]
    pub last_entry_id: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TraceEvent {
    pub seq: u64,
    pub at: String,
    pub scope: String,
    #[serde(rename = "type")]
    pub event_type: String,
    #[serde(rename = "runId")]
    pub run_id: String,
    #[serde(rename = "nodeId", skip_serializing_if = "Option::is_none")]
    pub node_id: Option<String>,
    #[serde(rename = "attemptId", skip_serializing_if = "Option::is_none")]
    pub attempt_id: Option<String>,
    pub payload: Value,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SessionBinding {
    pub schema: String,
    #[serde(rename = "runId")]
    pub run_id: String,
    #[serde(rename = "piSessionId")]
    pub pi_session_id: String,
    #[serde(rename = "piSessionFile", skip_serializing_if = "Option::is_none")]
    pub pi_session_file: Option<String>,
    pub cwd: String,
    #[serde(rename = "boundAt")]
    pub bound_at: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SessionEntryRecord {
    pub seq: u64,
    pub at: String,
    pub entry: Value,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SessionEventRecord {
    pub seq: u64,
    pub at: String,
    #[serde(rename = "nodeId")]
    pub node_id: String,
    #[serde(rename = "attemptId")]
    pub attempt_id: String,
    #[serde(rename = "turnId", skip_serializing_if = "Option::is_none")]
    pub turn_id: Option<String>,
    #[serde(rename = "messageId", skip_serializing_if = "Option::is_none")]
    pub message_id: Option<String>,
    #[serde(rename = "toolCallId", skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
    #[serde(rename = "type")]
    pub event_type: String,
    pub payload: Value,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionCaptureStatus {
    Recording,
    Complete,
    Failed,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionCaptureFailure {
    #[serde(rename = "failedAt")]
    pub failed_at: String,
    pub code: String,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SessionCapture {
    pub schema: String,
    #[serde(rename = "eventSchema")]
    pub event_schema: String,
    pub status: SessionCaptureStatus,
    #[serde(rename = "eventCount")]
    pub event_count: u64,
    #[serde(rename = "entryCount")]
    pub entry_count: u64,
    #[serde(rename = "lastEventSeq")]
    pub last_event_seq: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failure: Option<SessionCaptureFailure>,
}

// --- Definition snapshot ---

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DefinitionSnapshot {
    pub schema: String,
    pub name: String,
    #[serde(rename = "startAt")]
    pub start_at: String,
    /// Insertion order matters (BFS fallback order, display order), so the
    /// map preserves the document order of the JSON object.
    pub nodes: serde_json::Map<String, Value>,
    pub edges: Vec<EdgeDef>,
}

impl DefinitionSnapshot {
    pub fn node_type(&self, node_id: &str) -> Option<&str> {
        self.nodes
            .get(node_id)?
            .get("nodeType")
            .and_then(Value::as_str)
    }

    pub fn node_action_execution(&self, node_id: &str) -> Option<&str> {
        self.nodes
            .get(node_id)?
            .get("actionExecution")
            .and_then(Value::as_str)
    }

    pub fn node_ids(&self) -> impl Iterator<Item = &str> {
        self.nodes.keys().map(String::as_str)
    }
}

/// A workflow edge: either a simple `from -> to` or a labelled switch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum EdgeDef {
    Simple { from: String, to: String },
    Switch { from: String, switch: SwitchDef },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SwitchDef {
    pub on: String,
    /// Case order matters for edge expansion; preserve document order.
    pub cases: serde_json::Map<String, Value>,
}

/// An artifact reference extracted from a `{"$artifact": …}` sentinel.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ArtifactRef {
    pub path: String,
    #[serde(rename = "mediaType")]
    pub media_type: String,
    pub bytes: u64,
    pub sha256: String,
}

/// Detect the `$artifact` sentinel: an object whose only key is `$artifact`.
pub fn as_artifact_ref(value: &Value) -> Option<ArtifactRef> {
    let object = value.as_object()?;
    if object.len() != 1 {
        return None;
    }
    serde_json::from_value(object.get("$artifact")?.clone()).ok()
}

/// Unwrap one level of `{"$escaped": …}` if present.
pub fn as_escaped(value: &Value) -> Option<&Value> {
    let object = value.as_object()?;
    if object.len() != 1 {
        return None;
    }
    object.get("$escaped")
}