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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
//! Pipeline domain model — the complete type system for graph execution, node contracts, and
//! runtime context.
//!
//! # Overview
//!
//! A **pipeline** is a directed graph of **nodes** connected by **edges**.
//! Each edge links one node's output pin to another node's input pin. The engine performs a
//! BFS queue traversal, executing nodes in arrival order and forwarding the output
//! **payload** (a `serde_json::Value`) downstream through the edges.
//! Cycles are permitted — a node can be revisited when an edge points back to an earlier node
//! (e.g. a conditional loop via `n.logic.if`'s `false` pin).
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ PipelineGraph │
//! │ │
//! │ ┌───────────────────┐ edge: n0/out → n1/in │
//! │ │ PipelineNode (n0) │ ──────────────────────────────────────► │
//! │ │ kind: n.trigger │ │
//! │ │ config: { path } │ ┌─────────────────────┐ │
//! │ └───────────────────┘ │ PipelineNode (n1) │ │
//! │ │ kind: n.pg.query │ │
//! │ │ config: { query } │ │
//! │ └──────────┬──────────┘ │
//! │ │ edge: n1/out → n2/in │
//! │ ▼ │
//! │ ┌─────────────────────┐ │
//! │ │ PipelineNode (n2) │ │
//! │ │ kind: n.web.response│ │
//! │ │ config: { tmpl } │ │
//! │ └─────────────────────┘ │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! # Three Separate Concerns
//!
//! This module contains three groups of types that must not be confused:
//!
//! | Group | Types | Purpose |
//! |-------|-------|---------|
//! | **Graph** | [`PipelineGraph`], [`PipelineNode`], [`PipelineEdge`] | Persisted pipeline definition — what gets saved to `*.zf.json` and loaded at runtime |
//! | **Definition** | [`NodeDefinition`], [`NodeScriptBridge`], [`NodeAiToolDefinition`] | Static contract describing what a node kind *is* — its schemas, pins, and capabilities |
//! | **Runtime** | [`PipelineContext`], [`PipelineOutput`], [`PipelineError`], [`ExecuteOptions`] | Values produced and consumed during a single pipeline execution run |
//!
//! # Node Definition vs Node Instance
//!
//! **[`NodeDefinition`]** is the *kind-level* contract — it is the same for every instance of
//! `n.pg.query` across all pipelines. It is declared once per node kind via a `definition()`
//! function in each node module (e.g. `pg_query::definition()`), registered into a catalog,
//! and served at `/docs/node` via [`NodeContractDocument`].
//!
//! **[`PipelineNode`]** is a *graph-level instance* — a specific occurrence of a node kind
//! inside one pipeline, identified by a unique `id`, carrying its own `config` blob. Many
//! `PipelineNode` instances can share the same `kind` string but have different configs.
//!
//! ```text
//! NodeDefinition (kind = "n.pg.query")
//! ├── config_schema: { credential_id: required, query: required, ... }
//! ├── input_schema: { type: object }
//! ├── output_schema: { rows: array } | { affected_rows: integer }
//! ├── input_pins: ["in"]
//! └── output_pins: ["out"]
//!
//! ↑ validates config against config_schema at register time
//!
//! PipelineNode { id: "n1", kind: "n.pg.query", config: { credential_id: "pg-main", query: "SELECT ..." } }
//! PipelineNode { id: "n4", kind: "n.pg.query", config: { credential_id: "pg-replica", query: "SELECT ..." } }
//! ```
//!
//! # Config Schema
//!
//! [`NodeDefinition::config_schema`] is the single source of truth for what static
//! configuration a node kind accepts. It is a JSON Schema object derived from each node's
//! typed `Config` struct via `schemars::schema_for!` (available through the `rmcp::schemars`
//! re-export).
//!
//! Adding `#[derive(JsonSchema)]` to a node's `Config` struct and calling
//! `serde_json::to_value(schemars::schema_for!(Config))` in its `definition()` function
//! provides:
//!
//! 1. **Validation at register time** — `config` blobs on incoming [`PipelineNode`]s can be
//! checked against the schema before a pipeline is saved to disk. Bad config fails fast
//! rather than at execution time.
//! 2. **UI dialog auto-generation** — the pipeline editor reads `config_schema.properties`
//! to render the correct field types, labels, and required markers without hardcoding them
//! in TypeScript.
//! 3. **DSL flag derivation** — the DSL parser can map `--flag` names to `config` JSON keys
//! by reading schema property names, eliminating hardcoded mapping tables.
//! 4. **API docs** — `config_schema` is included in [`NodeContractItem`] and surfaced at
//! `/docs/node` so external tooling can discover node capabilities programmatically.
//!
//! # Pin System
//!
//! Nodes communicate through named **pins**. An output pin on one node connects to an input
//! pin on another via a [`PipelineEdge`]. The flowing value between pins is a
//! `serde_json::Value` (the **payload**).
//!
//! ```text
//! NodeA { output_pins: ["out", "error"] }
//! │
//! │ PipelineEdge { from_node: "A", from_pin: "out", to_node: "B", to_pin: "in" }
//! ▼
//! NodeB { input_pins: ["in"] }
//! ```
//!
//! Pin names are declared in [`NodeDefinition`] (the kind-level contract) and instantiated in
//! [`PipelineNode`] (the graph instance). Trigger nodes have no input pins. Terminal nodes
//! need not have output pins — their payload becomes the HTTP response.
//!
//! # Authoring a New Node
//!
//! Every node module must expose:
//!
//! 1. A `pub fn definition() -> NodeDefinition` that populates all contract fields.
//! 2. A `pub struct Config` with `#[derive(Serialize, Deserialize, JsonSchema)]` documenting
//! accepted config fields via doc comments.
//! 3. A `pub struct Node` that implements [`crate::pipeline::nodes::NodeHandler`].
//! 4. Register the `definition()` call in `pipeline/nodes/basic/mod.rs →
//! builtin_node_definitions()`.
//!
//! ```rust,ignore
//! // my_node.rs
//! use schemars::JsonSchema;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
//! pub struct Config {
//! /// Required: the thing the node needs.
//! pub my_field: String,
//! /// Optional override.
//! #[serde(default)]
//! pub optional_field: Option<String>,
//! }
//!
//! pub fn definition() -> NodeDefinition {
//! NodeDefinition {
//! kind: "n.my.node".to_string(),
//! title: "My Node".to_string(),
//! description: "Does the thing.".to_string(),
//! config_schema: serde_json::to_value(schemars::schema_for!(Config)).unwrap_or_default(),
//! input_schema: serde_json::json!({ "type": "object" }),
//! output_schema: serde_json::json!({ "type": "object", "properties": { "result": { "type": "string" } } }),
//! input_pins: vec!["in".to_string()],
//! output_pins: vec!["out".to_string()],
//! ..Default::default()
//! }
//! }
//! ```
//!
//! # Contract Document
//!
//! At startup, [`crate::pipeline::nodes::basic::builtin_node_definitions()`] returns all
//! [`NodeDefinition`]s. The platform converts them to [`NodeContractItem`]s via
//! `From<NodeDefinition>` and assembles a [`NodeContractDocument`] served at `/docs/node`.
//! This endpoint is the programmatic API for everything that needs to know about node
//! capabilities: UI, DSL tooling, LLM assistant, external integrations.
//!
//! # Payload Flow
//!
//! During execution, the engine feeds an initial payload (from the HTTP request) into the
//! trigger node. Each node receives an **input payload** (the output of the upstream node
//! that fired its input pin) and produces an **output payload** forwarded downstream.
//! [`NodeDefinition::input_schema`] and [`NodeDefinition::output_schema`] document these
//! payload shapes — they describe the *flowing data*, not the static config.
//!
//! The trigger node is special: it receives the raw request payload and passes it through
//! unchanged (or enriched). Downstream nodes transform the payload until a terminal node
//! (e.g. `n.web.response`) produces the final HTTP response.
use ;
use ;
use Value;
/// How a DSL flag value is interpreted by the parser.
///
/// The universal transformation rule `--flag-name` → `flag_name` (replace `-` with `_`)
/// applies to ALL flags automatically. `DslFlagKind` controls only how the *value* is parsed.
/// One DSL flag declaration owned by a [`NodeDefinition`].
///
/// Each node declares the DSL flags it accepts. The parser uses these as the
/// **single source of truth** for flag→config mapping:
///
/// - **Parsing**: `config_key` is the authoritative destination key. Undeclared flags are a parse error.
/// - **Value coercion**: `kind` controls how the value is interpreted (scalar, list, bool).
/// - **Help text**: `pipeline --help n.web.response` lists all flags with descriptions.
/// - **Required validation**: flags with `required: true` must be present when registering.
/// - **LLM context**: surfaced in `/docs/node` so agents know exactly what flags to emit.
///
/// Every flag used in DSL MUST be declared here. No fallback, no auto-rule.
// ── Node field definitions ────────────────────────────────────────────────────
//
// These types describe the **UI form fields** for each node kind. Every node
// declares its own `fields: Vec<NodeFieldDef>` inside `definition()`. The
// pipeline editor reads these from the `/docs/node` API response and renders a
// generic config form — no TypeScript changes needed when a new node is added.
/// What kind of UI widget a node field uses.
/// Where a select/datalist field's options come from at runtime.
/// One option in a `select`, `datalist`, or `method_buttons` field.
/// One item in a code-editor sidebar section.
/// A collapsible group of items shown in the code-editor sidebar.
/// Describes one form field in a node's config dialog.
///
/// Nodes declare `fields: Vec<NodeFieldDef>` in their `definition()`.
/// The pipeline editor reads this from `/docs/node` and renders the form
/// generically — no frontend changes are needed when a new node is added.
/// One item in a node's dialog layout tree.
///
/// `Field(name)` references a `NodeFieldDef` by its `name` key.
/// `Row` renders children horizontally (equal-width flex columns).
/// `Col` renders children vertically (nested stack inside a row cell).
///
/// Top-level `NodeDefinition::layout` is an implicit vertical stack.
/// Serializes as untagged: `"field_name"`, `{"row":[...]}`, `{"col":[...]}`.
// ── Pipeline graph ─────────────────────────────────────────────────────────────
/// A complete pipeline graph ready for execution.
///
/// Persisted as `repo/pipelines/<name>.zf.json`. Loaded by
/// [`crate::platform::services::PipelineRuntimeService`] at server startup and on demand.
///
/// # Execution entry point
///
/// The engine starts traversal from [`entry_nodes`](PipelineGraph::entry_nodes). If the
/// list is empty, the engine falls back to nodes that have no incoming edges (i.e. nodes
/// with no input pins — trigger nodes).
///
/// # JSON shape
///
/// ```json
/// {
/// "kind": "zebflow.pipeline",
/// "version": "0.1",
/// "id": "blog-home",
/// "nodes": [ ... ],
/// "edges": [ ... ]
/// }
/// ```
/// One node instance inside a [`PipelineGraph`].
///
/// This is the *instance* — not the kind-level contract. Many nodes with the same `kind`
/// can exist in the same graph or across different graphs, each with different `config`.
///
/// # Config vs Definition
///
/// `config` is a raw `serde_json::Value` blob. The engine deserializes it into the node
/// kind's typed `Config` struct at build/compile time. The shape is defined by
/// [`NodeDefinition::config_schema`].
///
/// # Pins
///
/// `input_pins` and `output_pins` are stored per instance to allow the graph serialization
/// format to be self-describing. They must be consistent with what
/// [`NodeDefinition::input_pins`] and [`NodeDefinition::output_pins`] declare for the kind.
/// A directed connection from one node's output pin to another node's input pin.
///
/// Together, all edges in a [`PipelineGraph`] form the DAG. The engine follows edges
/// to determine which node fires next and what payload it receives.
///
/// # Example
///
/// ```json
/// { "from_node": "trigger", "from_pin": "out", "to_node": "query", "to_pin": "in" }
/// ```
///
/// The `from`/`to` aliases allow a shorter JSON representation in `.zf.json` files.
/// Declares that this node kind can be invoked from inside an `n.script` node.
///
/// When `enabled = true` the language engine exposes the node's capability as a global
/// function under `bridge_name` inside the Deno sandbox. Pipeline authors can call it
/// directly from JavaScript without adding a separate graph node.
///
/// # Example
///
/// ```js
/// // inside n.script source
/// const rows = await n.pg.query({ credential_id: "main-db", query: "SELECT * FROM posts" });
/// ```
/// Registers this node kind as a callable AI tool for LLM-based agents.
///
/// When `registered = true`, the assistant can invoke this node's capability by name
/// during an agentic pipeline run (e.g. Zebtune calling `n.pg.query` to answer a question).
/// `tool_input_schema` is a JSON Schema object the LLM uses to form valid tool arguments.
/// The canonical contract for one node kind.
///
/// **One `NodeDefinition` per node kind** — not per instance. Every node module exposes a
/// `pub fn definition() -> NodeDefinition` and registers it via
/// `builtin_node_definitions()`.
///
/// # Three Schemas
///
/// A `NodeDefinition` carries three independent JSON Schema objects. Understanding the
/// difference is critical:
///
/// | Field | Describes | Populated by |
/// |-------|-----------|--------------|
/// | `config_schema` | Static fields in the node's `Config` struct | `schemars::schema_for!(Config)` |
/// | `input_schema` | Payload shape this node *consumes* from upstream | Hand-written in `definition()` |
/// | `output_schema` | Payload shape this node *produces* downstream | Hand-written in `definition()` |
///
/// `config_schema` is the authoritative source for what can be put in
/// [`PipelineNode::config`]. Downstream consumers (UI dialog renderer, DSL parser, register
/// validator) all read this schema rather than hardcoding field knowledge.
///
/// `input_schema` and `output_schema` document the *flowing payload* — the `serde_json::Value`
/// passed between nodes at runtime. They are informational for now (not enforced at runtime)
/// but drive UI tooltips and LLM context.
///
/// # Pin Declarations
///
/// `input_pins` and `output_pins` list the pin names this kind exposes. Trigger nodes have
/// empty `input_pins`. Logic nodes like `n.logic.match` have dynamic `output_pins` (empty
/// here, populated per instance in the graph).
///
/// # Usage Dimensions
///
/// A node kind can be usable in three ways simultaneously:
/// 1. As a **graph node** — always true for any registered kind.
/// 2. As a **script bridge** — callable from `n.script` Deno sandbox (see [`NodeScriptBridge`]).
/// 3. As an **AI tool** — invokable by LLM agents (see [`NodeAiToolDefinition`]).
///
/// The [`NodeUsageMatrix`] in [`NodeContractItem`] captures all three dimensions.
/// Script bridge capability as exposed in a [`NodeUsageMatrix`].
/// AI tool capability as exposed in a [`NodeUsageMatrix`].
/// Summary of where and how a node kind can be used.
///
/// A node is always usable as a pipeline graph node. The matrix additionally records
/// whether it is callable from script and/or invokable by AI agents.
/// One entry in the node contract document, ready for API serialization.
///
/// Produced from a [`NodeDefinition`] via `From<NodeDefinition> for NodeContractItem`.
/// Carries all three schemas plus the [`NodeUsageMatrix`].
///
/// Served inside [`NodeContractDocument`] at `GET /docs/node`. External consumers
/// (pipeline editor UI, DSL tooling, LLM assistant, external integrations) use this
/// document to discover node capabilities without reading Rust source.
/// Root response envelope for `GET /docs/node`.
///
/// Contains all registered node contracts in a single document. Clients should check
/// `ok = true` before processing `items`. `schema_version` can be used to detect
/// breaking changes to the contract format.
///
/// # Assembling the document
///
/// ```rust,ignore
/// let items: Vec<NodeContractItem> = builtin_node_definitions()
/// .into_iter()
/// .map(NodeContractItem::from)
/// .collect();
/// let doc = NodeContractDocument {
/// ok: true,
/// schema_version: "1",
/// source: "builtin",
/// items,
/// };
/// ```
/// Converts a kind-level [`NodeDefinition`] into an API-facing [`NodeContractItem`].
///
/// This is the main path for building the `/docs/node` response. It flattens the
/// `script_bridge` and `ai_tool` metadata into the flat [`NodeUsageMatrix`] structure.
/// A streaming step event emitted by long-running nodes (e.g. `n.ai.zebtune`).
///
/// Sent through [`ExecuteOptions::step_tx`] so the platform can forward individual
/// reasoning steps to the client via SSE before the final output is ready.
///
/// `step` is a short machine-readable tag (e.g. `"thinking"`, `"tool_call"`,
/// `"tool_result"`, `"final"`). `at` is a wall-clock timestamp or elapsed time string.
/// Per-execution options passed to the pipeline engine.
///
/// Currently only carries an optional SSE step channel. Pass `Default::default()` for
/// standard non-streaming execution.
/// Immutable execution context passed to every node during a pipeline run.
///
/// Contains the tenant/project scope and a unique request id for tracing. The `input`
/// field carries the original trigger payload — nodes should read their flowing payload
/// from `NodeExecutionInput::payload`, not from here.
///
/// `route` carries the inbound HTTP request path for webhook-triggered pipelines.
/// It is injected into every node's `metadata` under the key `"route"` so that
/// downstream nodes can access the real request path without reading it from a
/// potentially-transformed payload.
/// Per-node execution record captured by the pipeline engine during a run.
/// Final output of a completed pipeline execution.
///
/// `value` is the payload produced by the last (terminal) node. For `n.web.response` with
/// `--template` this contains `{ html, compiled_scripts, hydration_payload }`. For all other terminal nodes
/// it is whatever the node returned.
///
/// `trace` is a flat ordered list of trace strings emitted by each node in execution order,
/// useful for debugging slow or failed runs.
/// A typed error produced at any point during pipeline execution.
///
/// `code` is a stable SCREAMING_SNAKE_CASE string prefixed by the node kind
/// (e.g. `"FW_NODE_PG_CONFIG"`, `"FW_NODE_WEB_RENDER_COMPILE"`). It is safe to
/// match on in tests and error handlers. `message` is the human-readable detail.
///
/// `node_id` and `node_kind` are optionally populated by the engine at the BFS execution
/// boundary so error messages include the failing node identity.
///
/// # Stable error code conventions
///
/// | Prefix | Meaning |
/// |--------|---------|
/// | `FW_NODE_<KIND>_CONFIG` | Node config validation failed at build time |
/// | `FW_NODE_<KIND>_COMPILE` | Node compile/build phase failed |
/// | `FW_NODE_<KIND>_RUN` | Node execution failed at runtime |
/// | `FW_NODE_<KIND>_CREDENTIAL*` | Credential lookup or kind mismatch |
/// | `FW_NODE_<KIND>_INPUT_PIN` | Unexpected input pin name |