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
//! `tower::Service` spine for entelix model + tool calls.
//!
//! Two invocation types — [`ModelInvocation`] (request + ctx for a
//! `Codec`/`Transport` model call) and [`ToolInvocation`] (name +
//! input + ctx for a `Tool` execution) — flow through a layered
//! `tower::Service<Request, Response = ...>` stack. Cross-cutting
//! concerns (PII redaction, rate limiting, cost metering, OTel
//! observability) are `tower::Layer<S>` middleware. The composition
//! primitive is `tower::ServiceBuilder`; the dyn-erased handle is
//! [`BoxedModelService`] / [`BoxedToolService`].
//!
//! ## Why `tower::Service` rather than a bespoke `Hook` trait
//!
//! `tower` is the de-facto Rust async-middleware ecosystem
//! (`axum`, `tonic`, `reqwest-middleware`, `tower-http`). Adopting
//! it means:
//!
//! - `ServiceBuilder::new().layer(PolicyLayer).layer(OtelLayer)
//! .service(model)` is the composition contract — `model` is a
//! [`ChatModel`](crate::ChatModel)-produced leaf service.
//! - `Service::poll_ready` gives backpressure for free; layers like
//! `tower::limit::ConcurrencyLimitLayer`,
//! `tower::retry::RetryLayer`, and `tower::timeout::TimeoutLayer`
//! plug in unchanged.
//! - The same layer (e.g. `PolicyLayer`) wraps both model calls and
//! tool calls because it has separate `Service<ModelInvocation>`
//! and `Service<ToolInvocation>` impls behind the same struct.
use Arc;
use ;
use BoxFuture;
use Value;
use Service;
use BoxCloneService;
use crateBoxDeltaStream;
use crateExecutionContext;
use crateError;
use crate;
use crateToolMetadata;
/// One model call's full request + request-scope context. Layers
/// read both fields; the leaf service consumes them.
/// Streaming-side counterpart to [`ModelInvocation`] — the same
/// `request + ctx` payload but a distinct request type so the
/// `tower::Service` trait's associated `Response` can resolve to
/// [`ModelStream`] for the streaming spine while [`ModelInvocation`]
/// keeps resolving to [`ModelResponse`] for the one-shot spine.
///
/// Rust's `Service<Request>` carries `Response` as an associated
/// type — one trait impl per `(Self, Request)` pair. The wrapper
/// here is the cleanest way to expose two response types from one
/// leaf service: the same `InnerChatModel<C, T>` implements
/// `Service<ModelInvocation, Response = ModelResponse>` and
/// `Service<StreamingModelInvocation, Response = ModelStream>`,
/// and layers stack onto each independently.
///
/// `#[non_exhaustive]` to keep room for streaming-only knobs
/// (chunk size hints, partial-output buffers) post-1.0 without
/// breaking callers.
/// One tool call's identifier + descriptor + input + request-scope
/// context.
///
/// `tool_use_id` carries the IR's stable id so observability layers
/// can correlate `ToolStart` / `ToolComplete` / `ToolError` events
/// for the *same* dispatch even when several parallel calls share
/// the same tool name. `metadata` is the dispatched tool's full
/// declarative descriptor — name / version / effect / idempotent /
/// retry hint flow through the layer stack from a single source so
/// `OtelLayer`, `PolicyLayer`, and retry middleware see one
/// authoritative struct. Layers may mutate `input` (e.g. PII
/// redaction).
/// Type-erased, cloneable `Service<ModelInvocation>` handle. The
/// canonical pre-composed shape `ChatModel` exposes via its
/// `service()` accessor and that user code stores on agents.
pub type BoxedModelService = ;
/// Type-erased, cloneable `Service<ToolInvocation>` handle. Tool
/// dispatch funnels through this; `ToolRegistry` builds it on
/// demand from a registered `Tool` + the registry's layer stack.
pub type BoxedToolService = ;
/// Streaming dispatch result returned by
/// `Service<ModelInvocation, Response = ModelStream>` — the
/// caller-visible delta stream paired with a future that resolves
/// to the aggregated terminal response.
///
/// The [`Self::stream`] field carries the raw `StreamDelta` flow
/// (text chunks, tool-use boundaries, usage, rate-limit, warnings,
/// terminal `Stop`). The [`Self::completion`] future resolves to
/// `Ok(ModelResponse)` after the stream has been fully consumed
/// AND a `StreamAggregator` has reconstructed the final response;
/// it resolves to `Err(...)` if the stream errored mid-flight, was
/// dropped before terminal `Stop`, or violated the aggregator's
/// protocol invariants.
///
/// Layers (`OtelLayer`, `PolicyLayer`) wrap `completion` to emit
/// observability / cost events on the **`Ok` branch only** —
/// invariant 12. A stream that errors mid-flight surfaces the
/// error through the consumer's stream-side `Err` *and* through
/// `completion` resolving to `Err`; either way, no cost charge
/// fires.
///
/// `completion` is internally driven by the same stream
/// `stream` carries — consumers do not need to poll it
/// separately. The aggregator runs as the consumer drains the
/// stream; `completion` resolves naturally when the consumer
/// reads the terminal `Stop` (or drops the stream early, in which
/// case `completion` resolves `Err`).
/// Type-erased, cloneable `Service<StreamingModelInvocation,
/// Response = ModelStream>` handle. Parallel to
/// [`BoxedModelService`] for the streaming dispatch path.
/// `ChatModel::streaming_service()` produces this; `OtelLayer` /
/// `PolicyLayer` wrap it the same way they wrap
/// [`BoxedModelService`] for the one-shot path.
pub type BoxedStreamingService = ;
/// Convenience: an always-ready `Service` whose `poll_ready` returns
/// `Poll::Ready(Ok(()))` unconditionally. Most leaf services have
/// no internal queue and use this shape; layers inherit
/// `poll_ready` from their inner service.
/// Static identity for a [`tower::Layer`] participant in
/// [`crate::ChatModel::layer`] / `ToolRegistry::layer` composition.
///
/// [`crate::ChatModel::layer_names`] walks the composed stack and
/// surfaces the names through the typed introspection channel —
/// diagnostic dashboards read `entelix.chat_model.layers` without
/// parsing prose `Debug` output, conditional-wiring code asserts the
/// expected stack at boot ("did my staging `OtelLayer` actually
/// compose in?"), and audit trails distinguish runs whose policy
/// wiring drifted at deploy time.
///
/// **Conventions** (patch-version-stable — renaming is a breaking
/// change for dashboards keyed off the value):
///
/// - `snake_case` ASCII bucketing the layer's primary role
/// (`"policy"`, `"otel"`, `"retry"`, `"approval"`).
/// - One canonical name per concrete layer struct, surfaced as
/// `pub const NAME: &'static str` on the struct so renaming
/// happens in one place.
/// - The trait method returns `&'static str` because layer
/// composition is a startup-time event and the name is part of
/// the binary's identity — runtime-built names would defeat the
/// stable-key promise.
///
/// External `tower::Layer` middleware (e.g. `tower::limit`'s
/// `ConcurrencyLimitLayer`) wraps through [`WithName`] to
/// participate in the same channel.
/// Wraps any [`tower::Layer<S>`] with a static name so external
/// middleware participates in the [`crate::ChatModel::layer_names`]
/// introspection channel. The wrapper is transparent at the
/// `tower::Layer` boundary — `WithName::new("concurrency",
/// ConcurrencyLimitLayer::new(10)).layer(inner)` produces the same
/// service the underlying layer would.
///
/// First-party entelix layers (`PolicyLayer`, `OtelLayer`)
/// implement [`NamedLayer`] directly and do **not** need this
/// wrapper; it exists exclusively for external `tower` middleware.