-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathspec.rs
More file actions
1892 lines (1774 loc) · 69.6 KB
/
Copy pathspec.rs
File metadata and controls
1892 lines (1774 loc) · 69.6 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
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The agent job — st2's view of a rendered VRS `agent.kdl` (spec.md §2).
//!
//! A job reads like a Nomad job: the *agent* is the job, its **tasks** are `pty{}` (interactive —
//! allocates a terminal, an agent harness) and `exec{}` (a plain process — the ding, daemons, a
//! stage's script; must NOT allocate a terminal, R09). st2 reads only the runner-normative subset:
//! `identity`, presentation (`name`, `description`), `host`, `role` (metadata only), `type`,
//! `workspace`, whole-agent desired state (plus legacy `retired`), `keep`, `supervisor`,
//! `restart{}`, `deliver`, `session-driver`, typed harness drivers, task lifecycle, Resource
//! bindings (declaration metadata), and the tasks. Everything else that is render-only (`harness`,
//! `model`, `persona`, `permissions`, legacy `transport` metadata, `strategy`, `meta{}`) is baked
//! into the tasks/commands by the render layer and ignored here.
//!
//! Three on-disk formats lower to this model: KDL (canonical, parsed by hand in `kdl_format`), and
//! TOML/JSON (serde). Every spec is a `service` — `type = batch` is retired; evals run through the
//! native `st2 eval` path (`eval_spec`/`eval_run`), which has its own model.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::time::Duration;
use serde::de::{self, MapAccess, Visitor};
use serde::{Deserialize, Serialize};
/// Maximum Unicode scalar count for an agent's human-facing label.
pub const AGENT_NAME_MAX_CHARS: usize = 160;
/// Maximum Unicode scalar count for an agent's enduring responsibility description.
pub const AGENT_DESCRIPTION_MAX_CHARS: usize = 1_000;
/// Maximum UTF-8 byte length for a non-running desired-state rationale.
pub const AGENT_DESIRED_STATE_REASON_MAX_BYTES: usize = 160;
/// Maximum ASCII length of an explicit agent address (R24).
pub const AGENT_ADDRESS_MAX_BYTES: usize = 255;
/// Maximum length of one dotted agent-address segment (R24).
pub const AGENT_ADDRESS_SEGMENT_MAX_BYTES: usize = 63;
/// Maximum ASCII length of an explicit immutable agent ID.
///
/// The two admitted producers are UUIDv7 for a new subject and the frozen `<host>.<identity>`
/// bus identity of a migrated legacy subject, so the ID namespace shares the address budget.
pub const AGENT_ID_MAX_BYTES: usize = 255;
/// Declarative whole-agent lifecycle intent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentDesiredState {
Running,
Suspended {
reason: String,
},
/// `None` exists only for legacy `retired #true` declarations.
Retired {
reason: Option<String>,
},
}
/// One provider-native message delivery transport declared by an agent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeliveryTransport {
Mcp,
AppServer,
PiChannel,
}
impl DeliveryTransport {
pub fn as_str(self) -> &'static str {
match self {
Self::Mcp => "mcp",
Self::AppServer => "app-server",
Self::PiChannel => "pi-channel",
}
}
fn parse(value: &str) -> anyhow::Result<Self> {
match value {
"mcp" => Ok(Self::Mcp),
"app-server" => Ok(Self::AppServer),
"pi-channel" => Ok(Self::PiChannel),
_ => anyhow::bail!(
"unsupported `deliver` value '{value}' (expected `mcp`, `app-server`, or `pi-channel`)"
),
}
}
pub fn session_driver(self) -> SessionDriver {
match self {
Self::Mcp => SessionDriver::Claude,
Self::AppServer => SessionDriver::Codex,
Self::PiChannel => SessionDriver::Pi,
}
}
}
/// The native session driver entered by an otherwise opaque launch.
///
/// This is an ownership assertion only. It does not render a provider launch or select a message
/// delivery transport.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SessionDriver {
Claude,
Codex,
Pi,
OpenCode,
Omp,
}
impl SessionDriver {
pub fn as_str(self) -> &'static str {
match self {
Self::Claude => "claude",
Self::Codex => "codex",
Self::Pi => "pi",
Self::OpenCode => "opencode",
Self::Omp => "omp",
}
}
fn parse(value: &str) -> anyhow::Result<Self> {
match value {
"claude" => Ok(Self::Claude),
"codex" => Ok(Self::Codex),
"pi" => Ok(Self::Pi),
"opencode" => Ok(Self::OpenCode),
"omp" => Ok(Self::Omp),
_ => anyhow::bail!(
"unsupported `session-driver` value '{value}' (expected `claude`, `codex`, `pi`, `opencode`, or `omp`)"
),
}
}
/// Parse the canonical driver name carried by `session-driver`.
pub fn from_name(value: &str) -> anyhow::Result<Self> {
Self::parse(value)
}
}
/// Non-secret facts that prove how a managed session can be admitted for delivery.
///
/// This is deliberately separate from activity and runtime health. A credential-backed seat names
/// only its opaque account identifier; an anonymous seat names the exact harness and model allowlist
/// it can launch without credentials.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind", deny_unknown_fields)]
pub enum DeliveryReadiness {
Credential {
account_id: Option<String>,
},
Anonymous {
harness: SessionDriver,
models: Vec<String>,
},
}
impl DeliveryReadiness {
pub fn validate(&mut self) -> anyhow::Result<()> {
match self {
Self::Credential { account_id } => {
if let Some(account_id) = account_id {
validate_delivery_readiness_value("account-id", account_id)?;
}
}
Self::Anonymous { harness: _, models } => {
anyhow::ensure!(
!models.is_empty(),
"anonymous delivery-readiness requires at least one model"
);
anyhow::ensure!(
models.len() <= 32,
"anonymous delivery-readiness accepts at most 32 models"
);
for model in models.iter() {
validate_delivery_readiness_value("model", model)?;
}
models.sort();
models.dedup();
}
}
Ok(())
}
}
fn validate_delivery_readiness_value(field: &str, value: &str) -> anyhow::Result<()> {
anyhow::ensure!(
!value.is_empty() && value.len() <= 200,
"delivery-readiness {field} must be 1..=200 UTF-8 bytes"
);
anyhow::ensure!(
value.trim() == value
&& !value
.chars()
.any(|character| character.is_control() || matches!(character, '\u{2028}' | '\u{2029}')),
"delivery-readiness {field} must have no surrounding whitespace, controls, or line separators"
);
Ok(())
}
/// One typed harness driver declaration.
///
/// st2 expands this field into inspectable Agent Spec KDL before task and render compilation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Driver {
Claude(ClaudeDriver),
Codex(CodexDriver),
Pi(PiDriver),
OpenCode(OpenCodeDriver),
Omp(OmpDriver),
}
impl Driver {
pub fn name(&self) -> &'static str {
match self {
Self::Claude(_) => "claude",
Self::Codex(_) => "codex",
Self::Pi(_) => "pi",
Self::OpenCode(_) => "opencode",
Self::Omp(_) => "omp",
}
}
pub fn session_driver(&self) -> SessionDriver {
match self {
Self::Claude(_) => SessionDriver::Claude,
Self::Codex(_) => SessionDriver::Codex,
Self::Pi(_) => SessionDriver::Pi,
Self::OpenCode(_) => SessionDriver::OpenCode,
Self::Omp(_) => SessionDriver::Omp,
}
}
}
/// Typed fields accepted by a `claude {}` driver block.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ClaudeDriver {
pub model: Option<String>,
pub effort: Option<String>,
#[serde(default)]
pub dev_channels: bool,
pub prompt: String,
#[serde(default)]
pub args: Vec<String>,
}
/// Typed fields accepted by a `pi {}` driver block.
///
/// `effort` carries pi's thinking level verbatim; st2 does not translate the maintained harnesses'
/// effort vocabularies into one another.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct PiDriver {
pub model: Option<String>,
pub effort: Option<String>,
pub prompt: String,
#[serde(default)]
pub args: Vec<String>,
}
/// Typed fields accepted by a `codex {}` driver block.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct CodexDriver {
pub model: Option<String>,
pub effort: Option<String>,
pub prompt: String,
#[serde(default)]
pub args: Vec<String>,
}
/// Typed fields accepted by an `opencode {}` driver block.
///
/// OpenCode has no effort axis; its permission policy lives in its config file rather than a
/// launch flag, so neither appears here.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct OpenCodeDriver {
pub model: Option<String>,
pub prompt: String,
#[serde(default)]
pub args: Vec<String>,
}
/// Typed fields accepted by an `omp {}` driver block.
///
/// omp is pi-family and exposes the same two axes under the same flags: `effort` carries omp's
/// thinking level verbatim (`--thinking`), exactly as [`PiDriver`] does for pi.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct OmpDriver {
pub model: Option<String>,
pub effort: Option<String>,
pub prompt: String,
#[serde(default)]
pub args: Vec<String>,
}
impl AgentDesiredState {
pub fn as_str(&self) -> &'static str {
match self {
Self::Running => "running",
Self::Suspended { .. } => "suspended",
Self::Retired { .. } => "retired",
}
}
pub fn reason(&self) -> Option<&str> {
match self {
Self::Running => None,
Self::Suspended { reason } => Some(reason),
Self::Retired { reason } => reason.as_deref(),
}
}
pub fn is_running(&self) -> bool {
matches!(self, Self::Running)
}
pub fn is_suspended(&self) -> bool {
matches!(self, Self::Suspended { .. })
}
pub fn is_retired(&self) -> bool {
matches!(self, Self::Retired { .. })
}
}
/// A rendered agent job, lowered to the shared declaration fields st2 and other readers inspect.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentSpec {
/// Explicit immutable catalog-global agent ID (R24). `None` on a legacy declaration that
/// catalog ID migration has not reached yet; required in the target grammar.
pub id: Option<String>,
/// Explicit mutable agent address (R24). `None` means the positional `identity` below is the
/// effective legacy address.
pub address: Option<String>,
/// The positional declaration key and legacy address fallback. Not immutable subject identity.
pub identity: String,
/// Optional mutable human-facing label. Never used as an automation selector.
pub name: Option<String>,
/// Optional enduring responsibility boundary. Never used for lifecycle decisions.
pub description: Option<String>,
/// Which machine runs this agent. `None` → resolved to the path's host / this machine.
pub host: Option<String>,
/// Optional declared persona role. Preserved as metadata and ignored for execution.
pub role: Option<String>,
/// `service` (long-running, respawns) — the only job type. Defaults to service.
pub job_type: JobType,
/// The repo/worktree; **defaults each task's cwd** (spec.md §2).
pub workspace: Option<String>,
/// Bare identity or `<host>.<identity>` of this agent's supervisor — crash-dings route here.
pub supervisor: Option<String>,
/// Whole-agent lifecycle intent. Non-running states are reconciled absent.
pub desired_state: AgentDesiredState,
/// Agent-level GC pin: `true` exempts all of its tasks from garbage collection.
pub keep: bool,
/// Crash/restart policy (§4). `None` → the runner's default policy.
pub restart: Option<Restart>,
/// Provider-native delivery selected by `deliver`; `None` means legacy `ding` or no delivery.
pub delivery: Option<DeliveryTransport>,
/// Native session ownership asserted for an otherwise opaque launch.
pub session_driver: Option<SessionDriver>,
/// Typed harness declaration used by task and render compilation.
pub driver: Option<Driver>,
/// Non-secret admission facts for the managed delivery path.
pub delivery_readiness: Option<DeliveryReadiness>,
/// Named typed references used by the agent. st2 preserves these for readers but does not
/// resolve them or assign launch, readiness, access, or lifecycle semantics.
pub resources: Vec<Resource>,
/// Named event subscriptions. Command-less streams are external ingress endpoints; launched
/// streams additionally lower to one derived exec companion.
pub streams: Vec<Stream>,
/// The runnable tasks (`pty` + `exec`), sorted by name for determinism.
pub tasks: Vec<Task>,
/// Where this spec was loaded from — the anchor for its resources and for edits.
pub path: PathBuf,
}
impl AgentSpec {
/// The explicit native session owner after typed-driver normalization.
pub fn effective_session_driver(&self) -> Option<SessionDriver> {
self.session_driver
.or_else(|| self.driver.as_ref().map(Driver::session_driver))
}
}
fn deserialize_optional_selector<'de, D>(
deserializer: D,
) -> Result<Option<serde_json::Value>, D::Error>
where
D: serde::Deserializer<'de>,
{
serde_json::Value::deserialize(deserializer).map(Some)
}
/// One agent-local semantic binding to an externally identified resource.
///
/// `name` is an agent-local label and `uri` is the exact absolute identity. `reason` explains why
/// the reference belongs in this Agent Spec. `inactive_reason` preserves a reference that is no
/// longer active for this agent without asserting anything about the resource itself.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Resource {
name: String,
uri: String,
reason: String,
#[serde(skip_serializing_if = "Option::is_none")]
inactive_reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
selector: Option<serde_json::Value>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ResourceDescriptor {
name: String,
uri: String,
reason: String,
inactive_reason: Option<String>,
#[serde(default, deserialize_with = "deserialize_optional_selector")]
selector: Option<serde_json::Value>,
}
impl Resource {
/// Construct a descriptor after enforcing the same invariants as catalog parsing.
pub fn new(name: String, uri: String, reason: String) -> Result<Self, String> {
if name.is_empty()
|| name.len() > 200
|| name.trim() != name
|| name.chars().any(char::is_control)
{
return Err(
"resource binding name must be 1..=200 bytes without surrounding whitespace or controls"
.into(),
);
}
if name == "declaration" {
return Err("resource binding name 'declaration' is reserved by resync".into());
}
validate_resource_uri(&uri).map_err(|reason| {
format!("resource binding '{name}' `uri` must be an exact absolute URI or a catalog-relative path: {reason}")
})?;
validate_resource_explanation(&name, "reason", &reason)?;
Ok(Self {
name,
uri,
reason,
inactive_reason: None,
selector: None,
})
}
/// Construct a preserved reference that is inactive for this agent.
pub fn new_inactive(
name: String,
uri: String,
reason: String,
inactive_reason: String,
) -> Result<Self, String> {
let mut resource = Self::new(name, uri, reason)?;
validate_resource_explanation(&resource.name, "inactive-reason", &inactive_reason)?;
resource.inactive_reason = Some(inactive_reason);
Ok(resource)
}
pub fn name(&self) -> &str {
&self.name
}
pub fn uri(&self) -> &str {
&self.uri
}
pub fn reason(&self) -> &str {
&self.reason
}
pub fn inactive_reason(&self) -> Option<&str> {
self.inactive_reason.as_deref()
}
pub fn selector(&self) -> Option<&serde_json::Value> {
self.selector.as_ref()
}
pub fn with_selector(mut self, selector: serde_json::Value) -> Self {
self.selector = Some(selector);
self
}
}
impl<'de> Deserialize<'de> for Resource {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let descriptor = ResourceDescriptor::deserialize(deserializer)?;
let selector = descriptor.selector;
let resource = match descriptor.inactive_reason {
None => Self::new(descriptor.name, descriptor.uri, descriptor.reason),
Some(inactive_reason) => Self::new_inactive(
descriptor.name,
descriptor.uri,
descriptor.reason,
inactive_reason,
),
};
resource
.map(|resource| match selector {
Some(selector) => resource.with_selector(selector),
None => resource,
})
.map_err(de::Error::custom)
}
}
/// The kind of job. Only `service` (long-running) remains — `type = batch` is retired; the native
/// `st2 eval` path (eval_spec/eval_run) replaces the old staged batch executor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum JobType {
#[default]
Service,
}
/// A task: one process st2 keeps running (a `pty` task) or runs once (a terminal-free `exec` task).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Task {
/// `pty` (interactive, allocates a terminal) or `exec` (plain process, terminal-free).
pub kind: TaskKind,
/// `true` when st2 generated this task from shorthand rather than the author declaring runnable
/// work. Derived sidecars run alongside an authored task, but cannot make a job runnable alone.
pub derived: bool,
/// The task name (`agent`, `ding`, …).
pub name: String,
/// Explicit on-disk id. `None` → `<host>.<identity>.<name>` at spawn.
pub id: Option<String>,
/// A shell program, run verbatim under `sh -c`.
pub command: Option<String>,
/// A direct program invocation. Element 0 is the program and the rest are its arguments.
///
/// Mutually exclusive with [`Task::command`]. Neither field means this is not a launch target.
pub argv: Option<Vec<String>>,
/// Working dir; `None` → the agent's `workspace`, else the spec file's directory.
pub cwd: Option<String>,
/// Arbitrary metadata (values are `$`-expanded at spawn).
pub tags: BTreeMap<String, String>,
/// Environment (values are `$`-expanded at spawn).
pub env: BTreeMap<String, String>,
/// Per-task GC pin.
pub keep: bool,
/// Reconciliation policy. `adopt-only` is a migration fence: st2 may adopt a live generation,
/// but must not reap a dead generation or create a missing replacement.
pub lifecycle: TaskLifecycle,
}
/// Whether a task allocates a terminal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskKind {
/// Interactive — allocates a pseudo-terminal (an agent harness).
Pty,
/// Non-interactive — a plain process, no terminal (R09).
Exec,
}
/// How st2 reconciles a declared task.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TaskLifecycle {
/// Ordinary service lifecycle: launch when absent and replace when dead.
#[default]
Service,
/// Migration fence: adopt an already-live generation, otherwise hold without mutation.
AdoptOnly,
}
/// Restart policy (§4). Applies to long-running `service` tasks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Restart {
/// Max restarts within `interval`.
pub attempts: u32,
/// The window `attempts` is counted over.
pub interval: Duration,
/// Wait between restarts.
pub delay: Duration,
/// `fail` = stop after `attempts` (surface it) · `delay` = keep restarting, resetting per interval.
pub mode: RestartMode,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RestartMode {
/// Stop after `attempts` exhaust and surface it.
Fail,
/// Keep restarting, resetting the counter each interval.
Delay,
}
impl Default for Restart {
/// The runner default when a job omits `restart{}` — mirrors the pre-VRS flapping-cap (3 / 60s),
/// keep-restarting.
fn default() -> Self {
Self {
attempts: 3,
interval: Duration::from_secs(60),
delay: Duration::from_secs(0),
mode: RestartMode::Delay,
}
}
}
impl AgentSpec {
/// The bus id this spec compiles to — `<host>.<identity>` — using `this_host` when `host` is unset.
pub fn bus_id(&self, this_host: &str) -> String {
format!(
"{}.{}",
self.host.as_deref().unwrap_or(this_host),
self.identity
)
}
/// The effective immutable subject ID during the ID migration window (R24).
///
/// The explicit `id` when the declaration carries one, otherwise the legacy
/// `<host>.<identity>` bus identity — which is exactly the value catalog ID migration freezes
/// as this subject's explicit ID, so a mixed catalog stays coherent while it is migrated.
pub fn effective_id(&self, this_host: &str) -> String {
self.id
.clone()
.unwrap_or_else(|| self.bus_id(this_host))
}
/// The effective agent address (R24): the explicit `address` when present, otherwise the
/// positional `identity` legacy fallback.
pub fn effective_address(&self) -> &str {
self.address.as_deref().unwrap_or(&self.identity)
}
/// The human-routable bus address `<host>.<effective address>` (R24), using `this_host` when
/// `host` is unset. This is a mutable route, never the immutable subject ID.
pub fn bus_address(&self, this_host: &str) -> String {
format!(
"{}.{}",
self.host.as_deref().unwrap_or(this_host),
self.effective_address()
)
}
/// The host that should run this spec, defaulting to `this_host` when unset.
pub fn resolved_host<'a>(&'a self, this_host: &'a str) -> &'a str {
self.host.as_deref().unwrap_or(this_host)
}
/// True when a compiled or authored task contains a launch.
/// Callers that accept driver blocks must compile generated tasks before this check.
/// A generated sidecar cannot make an otherwise-empty job runnable.
pub fn is_runnable(&self) -> bool {
self.tasks
.iter()
.any(|task| !task.derived && (task.command.is_some() || task.argv.is_some()))
}
/// True when the declaration selected legacy screen delivery or one native transport.
pub fn has_delivery_transport(&self) -> bool {
self.driver.is_some()
|| self.delivery.is_some()
|| self
.tasks
.iter()
.any(|task| task.derived && task.kind == TaskKind::Exec && task.name == "ding")
}
/// The restart policy in effect (declared, else the runner default).
pub fn restart_policy(&self) -> Restart {
self.restart.clone().unwrap_or_default()
}
}
// ---- Duration parsing ("60s", "5s", "20m", "2h", "3d") ---------------------------------------
/// Parse a duration like `60s` / `5m` / `2h` / `3d` (also a bare integer = seconds).
pub fn parse_duration(s: &str) -> Result<Duration, String> {
let s = s.trim();
if s.is_empty() {
return Err("empty duration".into());
}
let (num, unit) = match s.find(|c: char| c.is_ascii_alphabetic()) {
Some(i) => (&s[..i], &s[i..]),
None => (s, "s"), // bare number → seconds
};
let n: u64 = num
.trim()
.parse()
.map_err(|_| format!("bad duration number in '{s}'"))?;
let secs = match unit.trim() {
"s" | "sec" | "secs" => n,
"m" | "min" | "mins" => n * 60,
"h" | "hr" | "hrs" => n * 3600,
"d" | "day" | "days" => n * 86400,
"ms" => return Ok(Duration::from_millis(n)),
other => return Err(format!("unknown duration unit '{other}' in '{s}'")),
};
Ok(Duration::from_secs(secs))
}
// ---- Raw deserialization target (shared by TOML + JSON) --------------------------------------
/// The permissive on-disk shape. Unknown keys (`harness`, `model`, `persona`, `permissions`,
/// `transport`, `strategy`, `meta`, …) are intentionally dropped — that is how st2 stays
/// render-agnostic.
#[derive(Debug, Default, Deserialize)]
pub(crate) struct RawSpec {
pub id: Option<String>,
pub address: Option<String>,
pub identity: Option<String>,
pub name: Option<String>,
pub description: Option<String>,
pub host: Option<String>,
pub role: Option<String>,
#[serde(rename = "type")]
pub job_type: Option<String>,
pub workspace: Option<String>,
pub supervisor: Option<String>,
#[serde(default, deserialize_with = "deserialize_explicit_optional")]
pub retired: Option<Option<bool>>,
#[serde(default, deserialize_with = "deserialize_explicit_optional")]
pub desired_state: Option<Option<String>>,
#[serde(default, deserialize_with = "deserialize_explicit_optional")]
pub desired_state_reason: Option<Option<String>>,
#[serde(default)]
pub keep: bool,
pub restart: Option<RawRestart>,
/// Named resource bindings. Singular `resource` matches canonical KDL and keeps TOML/JSON maps
/// aligned with `resource "<name>"`.
#[serde(default)]
pub resource: RawResources,
/// Compact catalog form: the agent itself is one pty carrying this command.
pub command: Option<String>,
/// Compact catalog form: the agent itself is one pty launched directly with this argv.
pub argv: Option<Vec<String>>,
/// Compact catalog form: environment inherited by the agent pty and every sidecar.
#[serde(default)]
pub env: BTreeMap<String, String>,
/// Compact catalog form: include the built-in `st2 ding` sidecar.
#[serde(default)]
pub ding: bool,
/// Compact catalog form: select one provider-native delivery transport.
#[serde(default, deserialize_with = "deserialize_explicit_optional")]
pub deliver: Option<Option<String>>,
/// Native session ownership asserted for an otherwise opaque launch.
#[serde(default, deserialize_with = "deserialize_explicit_optional")]
pub session_driver: Option<Option<String>>,
/// Non-secret facts used to admit the managed delivery path.
pub delivery_readiness: Option<DeliveryReadiness>,
/// Direct typed provider driver block.
#[serde(flatten)]
pub driver: RawDriver,
/// Compact catalog form: reconciliation policy for the generated agent PTY.
pub lifecycle: Option<String>,
/// `pty "<name>" {}` / `[pty.<name>]` — interactive tasks.
#[serde(default)]
pub pty: BTreeMap<String, RawTask>,
/// `exec "<name>" {}` / `[exec.<name>]` — terminal-free tasks.
#[serde(default)]
pub exec: BTreeMap<String, RawTask>,
/// `stream "<name>" {}` / `[stream.<name>]` — an external event source whose stdout lines st2
/// delivers into this agent's inbox. Lowers to one derived exec companion, exactly like `ding`.
#[serde(default)]
pub stream: BTreeMap<String, RawStream>,
}
/// A declared event source. Exactly one of `command` / `argv` launches the source process.
#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct RawStream {
pub command: Option<String>,
pub argv: Option<Vec<String>>,
}
/// One agent-owned event subscription.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Stream {
pub name: String,
pub launch: Option<StreamLaunch>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case", tag = "type", content = "value")]
pub enum StreamLaunch {
Command(String),
Argv(Vec<String>),
}
/// The longest stream name that still leaves a legible `<host>.<identity>.stream-<name>` runtime id.
const STREAM_NAME_MAX_CHARS: usize = 40;
/// Derived stream task names are exactly `stream-<declared name>`.
pub const STREAM_TASK_PREFIX: &str = "stream-";
/// The declared stream name behind a derived task name, if this is a stream companion.
pub fn stream_name_of_task(task_name: &str) -> Option<&str> {
task_name.strip_prefix(STREAM_TASK_PREFIX)
}
/// A stream name becomes part of a runner-owned task name and runtime id, so it is restricted to a
/// lowercase slug. This keeps `stream-<name>` unambiguous against the `<bus-id>.<task>` id grammar.
fn validate_stream_name(identity: &str, name: &str) -> anyhow::Result<()> {
anyhow::ensure!(
!name.is_empty() && name.chars().count() <= STREAM_NAME_MAX_CHARS,
"agent '{identity}' stream name '{name}' must be 1..={STREAM_NAME_MAX_CHARS} characters"
);
anyhow::ensure!(
name.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
&& !name.starts_with('-')
&& !name.ends_with('-'),
"agent '{identity}' stream name '{name}' must match [a-z0-9]([a-z0-9-]*[a-z0-9])?"
);
anyhow::ensure!(
name != "resync",
"agent '{identity}' stream name '{name}' is reserved for built-in resync events"
);
Ok(())
}
/// The permissive raw envelope keeps the provider name at the same level in KDL, TOML, and JSON.
#[derive(Debug, Default, Deserialize)]
pub(crate) struct RawDriver {
pub(crate) claude: Option<ClaudeDriver>,
pub(crate) codex: Option<CodexDriver>,
pub(crate) pi: Option<PiDriver>,
pub(crate) opencode: Option<OpenCodeDriver>,
pub(crate) omp: Option<OmpDriver>,
}
impl RawDriver {
fn lower(self, identity: &str) -> anyhow::Result<Option<Driver>> {
// Named rather than positional so a fourth provider cannot silently widen a tuple match.
let mut declared: Vec<(&str, Driver)> = Vec::new();
if let Some(driver) = self.claude {
declared.push(("claude", Driver::Claude(driver)));
}
if let Some(driver) = self.codex {
declared.push(("codex", Driver::Codex(driver)));
}
if let Some(driver) = self.pi {
declared.push(("pi", Driver::Pi(driver)));
}
if let Some(driver) = self.opencode {
declared.push(("opencode", Driver::OpenCode(driver)));
}
if let Some(driver) = self.omp {
declared.push(("omp", Driver::Omp(driver)));
}
match declared.len() {
0 => Ok(None),
1 => Ok(Some(declared.pop().expect("length was just checked").1)),
_ => {
let names = declared
.iter()
.map(|(name, _)| *name)
.collect::<Vec<_>>()
.join("` and `");
anyhow::bail!("agent '{identity}' declares both `{names}`; choose one driver")
}
}
}
}
#[derive(Debug, Default)]
pub(crate) struct RawResources(BTreeMap<String, RawResource>);
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct RawResource {
pub(crate) uri: String,
pub(crate) reason: String,
pub(crate) inactive_reason: Option<String>,
#[serde(default, deserialize_with = "deserialize_optional_selector")]
pub(crate) selector: Option<serde_json::Value>,
}
#[derive(Debug, Default, Deserialize)]
pub(crate) struct RawTask {
pub id: Option<String>,
pub command: Option<String>,
pub argv: Option<Vec<String>>,
pub cwd: Option<String>,
#[serde(default)]
pub tags: BTreeMap<String, String>,
#[serde(default)]
pub env: BTreeMap<String, String>,
#[serde(default)]
pub keep: bool,
pub lifecycle: Option<String>,
}
#[derive(Debug, Default, Deserialize)]
pub(crate) struct RawRestart {
pub attempts: Option<u32>,
pub interval: Option<String>,
pub delay: Option<String>,
pub mode: Option<String>,
}
impl RawRestart {
pub(crate) fn lower(self) -> Restart {
let d = Restart::default();
Restart {
attempts: self.attempts.unwrap_or(d.attempts),
interval: self
.interval
.and_then(|s| parse_duration(&s).ok())
.unwrap_or(d.interval),
delay: self
.delay
.and_then(|s| parse_duration(&s).ok())
.unwrap_or(d.delay),
mode: match self.mode.as_deref() {
Some("fail") => RestartMode::Fail,
Some("delay") => RestartMode::Delay,
_ => d.mode,
},
}
}
}
impl RawResources {
pub(crate) fn insert(&mut self, name: String, resource: RawResource) -> anyhow::Result<()> {
if self.0.insert(name.clone(), resource).is_some() {
anyhow::bail!("duplicate resource binding '{name}'");
}
Ok(())
}
fn lower(self) -> anyhow::Result<Vec<Resource>> {
self.0
.into_iter()
.map(|(name, resource)| {
let selector = resource.selector;
let resource = match resource.inactive_reason {
None => Resource::new(name, resource.uri, resource.reason),
Some(inactive_reason) => {
Resource::new_inactive(name, resource.uri, resource.reason, inactive_reason)
}
}
.map_err(anyhow::Error::msg)?;
Ok(match selector {
Some(selector) => resource.with_selector(selector),
None => resource,
})
})
.collect()
}
}
impl<'de> Deserialize<'de> for RawResources {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ResourceMapVisitor;
impl<'de> Visitor<'de> for ResourceMapVisitor {
type Value = RawResources;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a map of uniquely named resource bindings")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut resources = BTreeMap::new();
while let Some((name, resource)) = map.next_entry::<String, RawResource>()? {
if resources.insert(name.clone(), resource).is_some() {
return Err(de::Error::custom(format!(
"duplicate resource binding '{name}'"
)));
}
}
Ok(RawResources(resources))
}
}
deserializer.deserialize_map(ResourceMapVisitor)
}
}
fn validate_resource_explanation(name: &str, field: &str, value: &str) -> Result<(), String> {
if value.is_empty() || value.len() > 160 {
return Err(format!(
"resource binding '{name}' `{field}` must be 1..160 UTF-8 bytes"
));
}
if value.trim() != value
|| value
.chars()
.any(|character| character.is_control() || matches!(character, '\u{2028}' | '\u{2029}'))
{
return Err(format!(
"resource binding '{name}' `{field}` must have no surrounding Unicode whitespace, controls, or line separators"
));
}
Ok(())
}
/// A resource URI is either an exact absolute URI (any scheme) or a catalog-relative path with no
/// scheme at all, resolved by the consumer against the declaration directory. Relative carriers