theway-daemon 0.1.11

theway daemon — the single agent-runtime kernel (bin `thewayd`): harness assembly, local/sandbox tool policy, triggers/cron/session/DAG runtime, skills, MCP/LSP wiring, serving the gRPC/HTTP/MCP transports from theway-transport. Terminal UI lives in the theway-tui crate.
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
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
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};

use serde::Deserialize;
use serde_json::{Value, json};
use theway_contract::extension::{
    ExtensionAuditOperation, ExtensionAuditOutcome, ExtensionDiagnostic, ExtensionDiagnosticCode,
    ExtensionDiagnosticSeverity, ExtensionLifecycleEvent, ExtensionPermission,
};

use super::broker_paths::{audit_path, resolve_existing_path, resolve_write_path};
use super::broker_services::ExtensionBrokerServices;
use super::catalog::ExtensionPackage;
use super::engine::EngineInstanceKey;

const MAX_FILE_BYTES: usize = 1024 * 1024;
const MAX_NETWORK_BYTES: usize = 1024 * 1024;
const MAX_PROCESS_OUTPUT_BYTES: usize = 1024 * 1024;

#[derive(Clone)]
struct ActiveBrokerInvocation {
    cancellation: Arc<AtomicBool>,
    deadline: Instant,
    event: ExtensionLifecycleEvent,
    raw_payload: Value,
}

pub(super) struct BrokerRuntime {
    key: EngineInstanceKey,
    extension_id: String,
    session_id: String,
    workspace_root: PathBuf,
    permissions: BTreeSet<ExtensionPermission>,
    services: ExtensionBrokerServices,
    quota: BrokerOperationQuota,
    active: parking_lot::Mutex<Option<ActiveBrokerInvocation>>,
}

impl BrokerRuntime {
    pub(super) fn new(
        key: &EngineInstanceKey,
        package: &ExtensionPackage,
        services: ExtensionBrokerServices,
    ) -> Self {
        Self {
            key: key.clone(),
            extension_id: key.extension_id.clone(),
            session_id: key.session_id.clone(),
            workspace_root: package.workspace_root().to_path_buf(),
            permissions: package.granted_permissions().clone(),
            services,
            quota: BrokerOperationQuota::new(),
            active: parking_lot::Mutex::new(None),
        }
    }

    pub(super) fn begin(
        &self,
        limit: usize,
        cancellation: Arc<AtomicBool>,
        deadline: Instant,
        event: ExtensionLifecycleEvent,
        raw_payload: Value,
    ) {
        self.quota.begin(limit);
        *self.active.lock() = Some(ActiveBrokerInvocation {
            cancellation,
            deadline,
            event,
            raw_payload,
        });
    }

    pub(super) fn finish(&self) {
        self.active.lock().take();
    }

    pub(super) fn call(&self, operation: &str, serialized_arguments: &str) -> String {
        let result = self.call_inner(operation, serialized_arguments);
        match result {
            Ok(value) => json!({"ok": true, "value": value}).to_string(),
            Err(error) => {
                json!({"ok": false, "error": {"code": error.code, "message": error.message}})
                    .to_string()
            }
        }
    }

    fn call_inner(
        &self,
        operation: &str,
        serialized_arguments: &str,
    ) -> Result<Value, BrokerError> {
        if operation == "capabilities.has" {
            let arguments: CapabilityArguments = parse_arguments(serialized_arguments)?;
            let permission = arguments.permission.parse().map_err(|_| {
                BrokerError::contract("capability name is not a valid extension permission")
            })?;
            return Ok(Value::Bool(self.permissions.contains(&permission)));
        }
        self.quota.consume().map_err(|message| {
            self.diagnose(ExtensionDiagnosticCode::ResourceLimit, message);
            BrokerError::new("resource_limit", message)
        })?;
        let active = self.active.lock().clone().ok_or_else(|| {
            BrokerError::new("broker_unavailable", "capability broker is not active")
        })?;
        self.ensure_active(&active)?;
        match operation {
            "workspace.readText" => {
                self.workspace_read(parse_arguments(serialized_arguments)?, active)
            }
            "workspace.writeText" => {
                self.workspace_write(parse_arguments(serialized_arguments)?, active)
            }
            "process.run" => self.process_run(parse_arguments(serialized_arguments)?, active),
            "network.fetch" => self.network_fetch(parse_arguments(serialized_arguments)?, active),
            "secrets.read" => self.secret_read(parse_arguments(serialized_arguments)?),
            "providerRaw.read" => self.provider_raw(active),
            "state.schema" | "state.get" | "events.replay" | "memory.get" | "memory.set"
            | "memory.delete" | "memory.clear" => {
                self.services
                    .state
                    .call(&self.key, operation, serialized_arguments)
            }
            _ => Err(BrokerError::contract("unknown capability broker operation")),
        }
    }

    fn workspace_read(
        &self,
        arguments: ReadArguments,
        active: ActiveBrokerInvocation,
    ) -> Result<Value, BrokerError> {
        self.require(ExtensionPermission::WorkspaceRead)?;
        let path =
            resolve_existing_path(&self.workspace_root, &arguments.path).inspect_err(|_| {
                self.audit(
                    ExtensionAuditOperation::WorkspaceRead,
                    ExtensionAuditOutcome::Denied,
                    Some(ExtensionPermission::WorkspaceRead),
                    None,
                    std::iter::empty(),
                );
            })?;
        let relative = audit_path(&self.workspace_root, &path);
        let executor = Arc::clone(&self.services.executor);
        let cancellation = Arc::clone(&active.cancellation);
        let deadline = active.deadline;
        let result = self.services.block_on(async move {
            tokio::select! {
                result = executor.read_file(&path) => result.map_err(|error| error.to_string()),
                () = cancelled(cancellation, deadline) => Err("cancelled".into()),
            }
        });
        match result {
            Ok(content) if content.len() <= MAX_FILE_BYTES => {
                self.audit(
                    ExtensionAuditOperation::WorkspaceRead,
                    ExtensionAuditOutcome::Succeeded,
                    Some(ExtensionPermission::WorkspaceRead),
                    Some(&relative),
                    std::iter::empty(),
                );
                Ok(Value::String(content))
            }
            Ok(_) => self.fail_audited(
                ExtensionAuditOperation::WorkspaceRead,
                ExtensionPermission::WorkspaceRead,
                &relative,
                "resource_limit",
                "workspace read result exceeds the configured limit",
            ),
            Err(error) => self.async_failure(
                ExtensionAuditOperation::WorkspaceRead,
                ExtensionPermission::WorkspaceRead,
                &relative,
                error,
            ),
        }
    }

    fn workspace_write(
        &self,
        arguments: WriteArguments,
        active: ActiveBrokerInvocation,
    ) -> Result<Value, BrokerError> {
        self.require(ExtensionPermission::WorkspaceWrite)?;
        if arguments.content.len() > MAX_FILE_BYTES {
            return Err(BrokerError::new(
                "resource_limit",
                "workspace write content exceeds the configured limit",
            ));
        }
        let path = resolve_write_path(&self.workspace_root, &arguments.path).inspect_err(|_| {
            self.audit(
                ExtensionAuditOperation::WorkspaceWrite,
                ExtensionAuditOutcome::Denied,
                Some(ExtensionPermission::WorkspaceWrite),
                None,
                ["content".into()],
            );
        })?;
        let relative = audit_path(&self.workspace_root, &path);
        let executor = Arc::clone(&self.services.executor);
        let cancellation = Arc::clone(&active.cancellation);
        let deadline = active.deadline;
        let content = arguments.content;
        let result = self.services.block_on(async move {
            tokio::select! {
                result = executor.write_file(&path, &content) => result.map_err(|error| error.to_string()),
                () = cancelled(cancellation, deadline) => Err("cancelled".into()),
            }
        });
        match result {
            Ok(()) => {
                self.audit(
                    ExtensionAuditOperation::WorkspaceWrite,
                    ExtensionAuditOutcome::Succeeded,
                    Some(ExtensionPermission::WorkspaceWrite),
                    Some(&relative),
                    ["content".into()],
                );
                Ok(Value::Null)
            }
            Err(error) => self.async_failure(
                ExtensionAuditOperation::WorkspaceWrite,
                ExtensionPermission::WorkspaceWrite,
                &relative,
                error,
            ),
        }
    }

    fn process_run(
        &self,
        arguments: ProcessArguments,
        active: ActiveBrokerInvocation,
    ) -> Result<Value, BrokerError> {
        self.require(ExtensionPermission::ProcessSpawn)?;
        if arguments.argv.is_empty() || arguments.argv.len() > 128 {
            return Err(BrokerError::contract(
                "process argv must contain 1-128 items",
            ));
        }
        let target = arguments.argv[0].chars().take(80).collect::<String>();
        self.audit(
            ExtensionAuditOperation::ProcessSpawn,
            ExtensionAuditOutcome::Allowed,
            Some(ExtensionPermission::ProcessSpawn),
            Some(&target),
            ["arguments".into()],
        );
        let timeout = arguments
            .timeout_ms
            .map(Duration::from_millis)
            .unwrap_or(Duration::from_secs(30))
            .min(active.deadline.saturating_duration_since(Instant::now()));
        let executor = Arc::clone(&self.services.executor);
        let workspace = self.workspace_root.clone();
        let argv = arguments.argv;
        let cancellation = Arc::clone(&active.cancellation);
        let deadline = active.deadline;
        let result = self.services.block_on(async move {
            tokio::select! {
                result = executor.run_command(&workspace, &argv, timeout) => {
                    result.map_err(|error| error.to_string())
                }
                () = cancelled(cancellation, deadline) => Err("cancelled".into()),
            }
        });
        match result {
            Ok(output) => {
                let stdout = truncate_bytes(output.stdout, MAX_PROCESS_OUTPUT_BYTES);
                let stderr = truncate_bytes(output.stderr, MAX_PROCESS_OUTPUT_BYTES);
                self.audit(
                    ExtensionAuditOperation::ProcessSpawn,
                    ExtensionAuditOutcome::Succeeded,
                    Some(ExtensionPermission::ProcessSpawn),
                    Some(&target),
                    ["arguments".into(), "stdout".into(), "stderr".into()],
                );
                Ok(json!({
                    "stdout": stdout,
                    "stderr": stderr,
                    "exitCode": output.exit_code,
                }))
            }
            Err(error) => self.async_failure(
                ExtensionAuditOperation::ProcessSpawn,
                ExtensionPermission::ProcessSpawn,
                &target,
                error,
            ),
        }
    }

    fn network_fetch(
        &self,
        arguments: NetworkArguments,
        active: ActiveBrokerInvocation,
    ) -> Result<Value, BrokerError> {
        self.require(ExtensionPermission::NetworkConnect)?;
        let url = reqwest::Url::parse(&arguments.url)
            .map_err(|_| BrokerError::contract("network URL is invalid"))?;
        if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
            return Err(BrokerError::contract(
                "network URL must use HTTP or HTTPS with a host",
            ));
        }
        let target = format!(
            "{}://{}{}",
            url.scheme(),
            url.host_str().unwrap_or_default(),
            url.port()
                .map(|port| format!(":{port}"))
                .unwrap_or_default()
        );
        let cancellation = Arc::clone(&active.cancellation);
        let deadline = active.deadline;
        let result = self.services.block_on(async move {
            let client = reqwest::Client::builder()
                .redirect(reqwest::redirect::Policy::limited(5))
                .build()
                .map_err(|error| format!("HTTP client initialization failed: {error}"))?;
            let mut request = match arguments.method.as_deref().unwrap_or("GET") {
                "GET" => client.get(url),
                "POST" => client.post(url),
                _ => return Err("network method must be GET or POST".into()),
            };
            for (name, value) in arguments.headers {
                request = request.header(name, value);
            }
            if let Some(body) = arguments.body {
                request = request.body(body);
            }
            let mut response = tokio::select! {
                response = request.send() => response.map_err(|error| format!("network request failed: {error}"))?,
                () = cancelled(Arc::clone(&cancellation), deadline) => return Err("cancelled".into()),
            };
            let status = response.status().as_u16();
            let mut body = Vec::new();
            loop {
                let chunk = tokio::select! {
                    chunk = response.chunk() => chunk.map_err(|error| format!("network response failed: {error}"))?,
                    () = cancelled(Arc::clone(&cancellation), deadline) => return Err("cancelled".into()),
                };
                let Some(chunk) = chunk else { break };
                if body.len().saturating_add(chunk.len()) > MAX_NETWORK_BYTES {
                    return Err("network response exceeds the configured limit".into());
                }
                body.extend_from_slice(&chunk);
            }
            Ok((status, String::from_utf8_lossy(&body).into_owned()))
        });
        match result {
            Ok((status, body)) => {
                self.audit(
                    ExtensionAuditOperation::NetworkConnect,
                    ExtensionAuditOutcome::Succeeded,
                    Some(ExtensionPermission::NetworkConnect),
                    Some(&target),
                    ["headers".into(), "body".into(), "response".into()],
                );
                Ok(json!({"status": status, "body": body}))
            }
            Err(error) => self.async_failure(
                ExtensionAuditOperation::NetworkConnect,
                ExtensionPermission::NetworkConnect,
                &target,
                error,
            ),
        }
    }

    fn secret_read(&self, arguments: SecretArguments) -> Result<Value, BrokerError> {
        let permission = ExtensionPermission::SecretsRead(arguments.name.clone());
        self.require(permission.clone())?;
        let value = self
            .services
            .secrets
            .read()
            .get(&arguments.name)
            .cloned()
            .ok_or_else(|| BrokerError::new("not_found", "named secret is unavailable"))?;
        self.audit(
            ExtensionAuditOperation::SecretRead,
            ExtensionAuditOutcome::Succeeded,
            Some(permission),
            Some(&arguments.name),
            ["value".into()],
        );
        Ok(Value::String(value))
    }

    fn provider_raw(&self, active: ActiveBrokerInvocation) -> Result<Value, BrokerError> {
        self.require(ExtensionPermission::ProviderRaw)?;
        if !matches!(
            active.event,
            ExtensionLifecycleEvent::BeforeProviderRequestHeaders
                | ExtensionLifecycleEvent::BeforeProviderRequestRaw
        ) {
            return Err(BrokerError::new(
                "scope_mismatch",
                "provider raw data is unavailable for this lifecycle event",
            ));
        }
        self.audit(
            ExtensionAuditOperation::ProviderRawRead,
            ExtensionAuditOutcome::Succeeded,
            Some(ExtensionPermission::ProviderRaw),
            None,
            ["value".into()],
        );
        Ok(active.raw_payload)
    }

    fn require(&self, permission: ExtensionPermission) -> Result<(), BrokerError> {
        if self.permissions.contains(&permission) {
            return Ok(());
        }
        self.diagnose(
            ExtensionDiagnosticCode::PermissionDenied,
            "extension attempted an undeclared or ungranted capability operation",
        );
        self.audit(
            audit_operation(&permission),
            ExtensionAuditOutcome::Denied,
            Some(permission),
            None,
            std::iter::empty(),
        );
        Err(BrokerError::new(
            "permission_denied",
            "extension capability is not declared and granted",
        ))
    }

    fn ensure_active(&self, active: &ActiveBrokerInvocation) -> Result<(), BrokerError> {
        if active.cancellation.load(Ordering::Acquire) {
            return Err(BrokerError::new(
                "cancelled",
                "broker operation was cancelled",
            ));
        }
        if Instant::now() >= active.deadline {
            return Err(BrokerError::new(
                "timeout",
                "broker operation exceeded its deadline",
            ));
        }
        Ok(())
    }

    fn async_failure<T>(
        &self,
        operation: ExtensionAuditOperation,
        permission: ExtensionPermission,
        target: &str,
        error: String,
    ) -> Result<T, BrokerError> {
        let cancelled = error == "cancelled";
        self.audit(
            operation,
            if cancelled {
                ExtensionAuditOutcome::Cancelled
            } else {
                ExtensionAuditOutcome::Failed
            },
            Some(permission),
            Some(target),
            std::iter::empty(),
        );
        Err(BrokerError::new(
            if cancelled {
                "cancelled"
            } else {
                "broker_failed"
            },
            if cancelled {
                "broker operation was cancelled"
            } else {
                "broker operation failed"
            },
        ))
    }

    fn fail_audited<T>(
        &self,
        operation: ExtensionAuditOperation,
        permission: ExtensionPermission,
        target: &str,
        code: &'static str,
        message: &'static str,
    ) -> Result<T, BrokerError> {
        self.audit(
            operation,
            ExtensionAuditOutcome::Failed,
            Some(permission),
            Some(target),
            std::iter::empty(),
        );
        Err(BrokerError::new(code, message))
    }

    fn audit(
        &self,
        operation: ExtensionAuditOperation,
        outcome: ExtensionAuditOutcome,
        capability: Option<ExtensionPermission>,
        target: Option<&str>,
        redacted_fields: impl IntoIterator<Item = String>,
    ) {
        self.services.audit.record(
            self.extension_id.clone(),
            Some(self.session_id.clone()),
            operation,
            outcome,
            capability,
            target,
            redacted_fields,
        );
    }

    fn diagnose(&self, code: ExtensionDiagnosticCode, message: &str) {
        let mut diagnostic = ExtensionDiagnostic::new(
            self.extension_id.clone(),
            code,
            ExtensionDiagnosticSeverity::Error,
            message,
        );
        diagnostic.session_id = Some(self.session_id.clone());
        self.services.diagnostics.lock().push(diagnostic);
    }

    pub(super) fn clear_ephemeral_memory(&self) {
        self.services.clear_memory(&self.key);
    }
}

#[derive(Debug)]
pub(super) struct BrokerError {
    pub(super) code: &'static str,
    pub(super) message: &'static str,
}

impl BrokerError {
    pub(super) fn new(code: &'static str, message: &'static str) -> Self {
        Self { code, message }
    }

    pub(super) fn contract(message: &'static str) -> Self {
        Self::new("invalid_arguments", message)
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CapabilityArguments {
    permission: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ReadArguments {
    path: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct WriteArguments {
    path: String,
    content: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ProcessArguments {
    argv: Vec<String>,
    #[serde(default)]
    timeout_ms: Option<u64>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct NetworkArguments {
    url: String,
    #[serde(default)]
    method: Option<String>,
    #[serde(default)]
    headers: BTreeMap<String, String>,
    #[serde(default)]
    body: Option<String>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SecretArguments {
    name: String,
}

fn parse_arguments<T: for<'de> Deserialize<'de>>(source: &str) -> Result<T, BrokerError> {
    serde_json::from_str(source)
        .map_err(|_| BrokerError::contract("capability broker arguments are invalid"))
}

fn audit_operation(permission: &ExtensionPermission) -> ExtensionAuditOperation {
    match permission {
        ExtensionPermission::WorkspaceRead => ExtensionAuditOperation::WorkspaceRead,
        ExtensionPermission::WorkspaceWrite => ExtensionAuditOperation::WorkspaceWrite,
        ExtensionPermission::ProcessSpawn => ExtensionAuditOperation::ProcessSpawn,
        ExtensionPermission::NetworkConnect => ExtensionAuditOperation::NetworkConnect,
        ExtensionPermission::ProviderRaw => ExtensionAuditOperation::ProviderRawRead,
        ExtensionPermission::SecretsRead(_) => ExtensionAuditOperation::SecretRead,
        _ => ExtensionAuditOperation::TrustChanged,
    }
}

async fn cancelled(cancellation: Arc<AtomicBool>, deadline: Instant) {
    loop {
        if cancellation.load(Ordering::Acquire) || Instant::now() >= deadline {
            return;
        }
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
}

fn truncate_bytes(mut value: String, limit: usize) -> String {
    if value.len() <= limit {
        return value;
    }
    let mut boundary = limit;
    while !value.is_char_boundary(boundary) {
        boundary -= 1;
    }
    value.truncate(boundary);
    value
}

/// Invocation-local budget shared by all capability brokers installed in one
/// QuickJS context. Broker adapters consume one unit before touching a daemon
/// resource, so a failed broker operation still counts toward the limit.
pub(super) struct BrokerOperationQuota {
    remaining: AtomicUsize,
}

impl BrokerOperationQuota {
    pub(super) fn new() -> Self {
        Self {
            remaining: AtomicUsize::new(0),
        }
    }

    pub(super) fn begin(&self, limit: usize) {
        self.remaining.store(limit, Ordering::Release);
    }

    pub(super) fn consume(&self) -> Result<(), &'static str> {
        self.remaining
            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |remaining| {
                remaining.checked_sub(1)
            })
            .map(|_| ())
            .map_err(|_| "extension broker operation quota exceeded")
    }
}

/// Package name of the only host module available to extension imports.
pub(super) const PLUGIN_SDK_MODULE: &str = "@theway-ai/plugin-sdk";

/// Generate the plugin SDK host module. Capability brokers are added as
/// explicit API methods; no ambient daemon authority is copied into the
/// JavaScript global object.
pub(super) fn generated_theway_module() -> String {
    r#"
export function defineExtension(setup) {
  if (typeof setup !== "function") {
    throw new TypeError("defineExtension requires a setup function");
  }
  return Object.freeze({ setup });
}
"#
    .to_string()
}

/// Names intentionally absent from the direct package environment. Tests use
/// this list to keep future host additions capability-brokered.
pub(super) const FORBIDDEN_DIRECT_GLOBALS: &[&str] = &[
    "process",
    "Deno",
    "Bun",
    "require",
    "fetch",
    "XMLHttpRequest",
    "WebSocket",
    "thewayFilesystem",
    "thewayNetwork",
    "thewayEnvironment",
    "thewaySecrets",
    "thewayProvider",
    "thewayPersistence",
];

#[cfg(test)]
mod tests {
    use super::BrokerOperationQuota;

    #[test]
    fn broker_quota_rejects_operations_after_the_configured_limit() {
        let quota = BrokerOperationQuota::new();
        quota.begin(2);
        assert_eq!(quota.consume(), Ok(()));
        assert_eq!(quota.consume(), Ok(()));
        assert_eq!(
            quota.consume(),
            Err("extension broker operation quota exceeded")
        );
    }
}