Repository navigation
Expand file tree
/
Copy pathpersonal_commands.rs
More file actions
1640 lines (1532 loc) · 55.7 KB
/
Copy pathpersonal_commands.rs
File metadata and controls
1640 lines (1532 loc) · 55.7 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
//! Custom transformations from the user's `hex.config.ts` (or `hex.config.js`),
//! run in-process by embedded QuickJS ([`script`]) on one worker thread. The
//! worker loads the config, reloads it when the config folder changes (keeping
//! the last good registration when a reload fails), and answers transformation
//! calls, each under its own timeout. A config that uses `fetch` or
//! `node:child_process` reaches them only once the person allows that exact
//! config ([`trust`]). The Output pane reads the status, including what to
//! ask, from `personal-commands.json`.
mod fetch;
mod io;
mod process;
mod script;
mod trust;
mod typescript;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant, SystemTime};
use color_eyre::eyre::{Result, WrapErr, eyre};
use serde::{Deserialize, Serialize};
use crate::dictation::context::ContextSnapshot;
use io::Capabilities;
use script::Script;
pub use trust::Permissions;
/// The config file names Hex looks for, in the config folder.
const CONFIG_FILES: [&str; 2] = ["hex.config.ts", "hex.config.js"];
/// Files Hex owns in the config folder and rewrites when they differ.
const MANAGED_FILES: [(&str, &str); 2] = [
("hex.d.ts", include_str!("personal_commands/hex.d.ts")),
("AGENTS.md", include_str!("personal_commands/AGENTS.md")),
];
/// Starting points written only where the user has none.
const TEMPLATE_FILES: [(&str, &str); 1] = [(
"tsconfig.json",
include_str!("personal_commands/tsconfig.json"),
)];
const TEMPLATE_CONFIG: &str = include_str!("personal_commands/hex.config.ts");
const POLL_INTERVAL: Duration = Duration::from_millis(250);
const RELOAD_DEBOUNCE: Duration = Duration::from_millis(350);
const MAX_REGISTRATION_BYTES: usize = 256 * 1024;
const MAX_TRANSFORMATIONS: usize = 128;
const MAX_TRANSFORMATIONS_PER_INVOCATION: usize = 32;
const MAX_WATCH_ENTRIES: usize = 4096;
const MAX_WATCH_DEPTH: usize = 32;
const MAX_STATUS_BYTES: usize = 256 * 1024;
const MAX_STATUS_ERROR_BYTES: usize = 4096;
const MAX_TRANSFORMATION_TEXT_BYTES: usize = 48 * 1024;
/// A transformation's limit unless it sets `timeout`: one second for plain
/// JavaScript, thirty when its config can fetch or run programs.
const PURE_TIMEOUT: Duration = Duration::from_secs(1);
const IO_TIMEOUT: Duration = Duration::from_secs(30);
/// The most `timeout` can ask for.
const MAX_TIMEOUT: Duration = Duration::from_secs(60);
/// How much longer than the chain's own limits a dictation waits for the
/// worker, which may be loading a config or finishing earlier work first.
const QUEUE_ALLOWANCE: Duration = Duration::from_secs(5);
const LOWERCASE_TRANSFORMATION_ID: &str = "lowercase";
const SPONGEBOB_TRANSFORMATION_ID: &str = "spongebob-case";
const NO_TRAILING_PUNCTUATION_TRANSFORMATION_ID: &str = "no-trailing-punctuation";
struct BuiltinTransformation {
id: &'static str,
name: &'static str,
description: &'static str,
apply: fn(&str) -> String,
}
const BUILTIN_TRANSFORMATIONS: &[BuiltinTransformation] = &[
BuiltinTransformation {
id: LOWERCASE_TRANSFORMATION_ID,
name: "Lowercase",
description: "Convert the final text to lowercase",
apply: str::to_lowercase,
},
BuiltinTransformation {
id: SPONGEBOB_TRANSFORMATION_ID,
name: "SpongeBob case",
description: "Alternate lowercase and uppercase letters",
apply: spongebob_case,
},
BuiltinTransformation {
id: NO_TRAILING_PUNCTUATION_TRANSFORMATION_ID,
name: "No trailing punctuation",
description: "Remove punctuation at the end of the text",
apply: remove_trailing_punctuation,
},
];
fn builtin_transformation(id: &str) -> Option<&'static BuiltinTransformation> {
BUILTIN_TRANSFORMATIONS
.iter()
.find(|transformation| transformation.id == id)
}
#[cfg(target_os = "macos")]
pub fn is_builtin_transformation(id: &str) -> bool {
builtin_transformation(id).is_some()
}
/// `text` after the built-in transformation `id`, or None when `id` is not
/// built in (a script runs in the transformation host instead).
pub fn apply_builtin_transformation(id: &str, text: &str) -> Option<String> {
builtin_transformation(id).map(|builtin| (builtin.apply)(text))
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StatusSnapshot {
pub active_generation: Option<u64>,
#[serde(default)]
pub transformations: Vec<StatusTransformation>,
pub host_state: HostState,
pub last_reload_error: Option<String>,
/// What the loaded config can reach, when it uses `fetch` or programs.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<Permissions>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct StatusTransformation {
pub id: String,
pub name: String,
pub description: Option<String>,
}
pub fn include_builtin_transformations(status: &mut StatusSnapshot) {
status
.transformations
.retain(|transformation| builtin_transformation(&transformation.id).is_none());
status.transformations.splice(
0..0,
BUILTIN_TRANSFORMATIONS
.iter()
.map(|transformation| StatusTransformation {
id: transformation.id.into(),
name: transformation.name.into(),
description: Some(transformation.description.into()),
}),
);
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum HostState {
NotConfigured,
Starting,
Active,
Unavailable,
Stopped,
}
impl Default for StatusSnapshot {
fn default() -> Self {
Self {
active_generation: None,
transformations: Vec::new(),
host_state: HostState::NotConfigured,
last_reload_error: None,
permissions: None,
}
}
}
/// The config hash the person allowed to use `fetch` and programs, if any.
pub fn approved_config() -> Option<String> {
trust::approved(&crate::app_paths::transform_trust_file().ok()?)
}
/// Allows the loaded config whose files hash to `hash`.
pub fn approve_config(hash: &str) -> Result<()> {
trust::approve(&crate::app_paths::transform_trust_file()?, hash)
}
pub fn load_status() -> Result<StatusSnapshot> {
let path = crate::app_paths::personal_commands_status_file()?;
load_status_at(&path)
}
fn load_status_at(path: &Path) -> Result<StatusSnapshot> {
let bytes = match fs::read(path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(StatusSnapshot::default());
}
Err(error) => return Err(error.into()),
};
if bytes.len() > MAX_STATUS_BYTES {
return Err(eyre!(
"personal command status exceeds {MAX_STATUS_BYTES} bytes"
));
}
let status: StatusSnapshot = serde_json::from_slice(&bytes)?;
validate_status(&status)?;
Ok(status)
}
fn persist_status_at(path: &Path, status: &StatusSnapshot) -> Result<()> {
validate_status(status)?;
let encoded = serde_json::to_vec(status)?;
if encoded.len() > MAX_STATUS_BYTES {
return Err(eyre!(
"personal command status exceeds {MAX_STATUS_BYTES} bytes"
));
}
let parent = path
.parent()
.ok_or_else(|| eyre!("personal command status path has no parent"))?;
fs::create_dir_all(parent)?;
crate::durable::write(path, &encoded)?;
Ok(())
}
fn validate_status(status: &StatusSnapshot) -> Result<()> {
if status
.last_reload_error
.as_ref()
.is_some_and(|error| error.len() > MAX_STATUS_ERROR_BYTES)
{
return Err(eyre!("personal command status error is too large"));
}
if status.transformations.len() > MAX_TRANSFORMATIONS {
return Err(eyre!("personal transformation catalog is too large"));
}
validate_transformations(&status.transformations, "status ")?;
Ok(())
}
fn validate_transformations(
transformations: &[StatusTransformation],
label_prefix: &str,
) -> Result<()> {
let mut ids = HashSet::new();
for transformation in transformations {
validate_text(
&transformation.id,
&format!("{label_prefix}transformation id"),
128,
)?;
validate_text(
&transformation.name,
&format!("{label_prefix}transformation name"),
1024,
)?;
if let Some(description) = &transformation.description {
validate_text(
description,
&format!("{label_prefix}transformation description"),
1024,
)?;
}
if !ids.insert(transformation.id.clone()) {
return Err(eyre!("{label_prefix}transformation IDs must be unique"));
}
}
Ok(())
}
/// The config file in `workspace`, if there is exactly one.
fn find_config(workspace: &Path) -> Result<Option<&'static str>> {
let found = CONFIG_FILES
.into_iter()
.filter(|name| workspace.join(name).is_file())
.collect::<Vec<_>>();
match found.as_slice() {
[] => Ok(None),
[config] => Ok(Some(config)),
[first, second, ..] => Err(eyre!(
"{first} and {second} both exist; keep only one config file"
)),
}
}
/// Whether the personal command folder has a config to load.
pub fn workspace_configured() -> bool {
crate::app_paths::personal_commands_workspace()
.is_ok_and(|workspace| matches!(find_config(&workspace), Ok(Some(_)) | Err(_)))
}
/// Creates the config folder with Hex's typings and agent notes, and a
/// starter `hex.config.ts` unless a config already exists.
pub fn initialize_workspace() -> Result<PathBuf> {
let workspace = crate::app_paths::personal_commands_workspace()?;
initialize_workspace_at(&workspace)?;
Ok(workspace)
}
/// Loads `~/.config/hex`'s config as Hex does and summarizes its transformations.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub fn check_workspace() -> Result<String> {
let workspace = crate::app_paths::personal_commands_workspace()?;
check_workspace_at(&workspace)
}
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn check_workspace_at(workspace: &Path) -> Result<String> {
let workspace = workspace.to_path_buf();
let handle = thread::Builder::new()
.name("personal-commands-check".into())
.stack_size(script::THREAD_STACK_SIZE)
.spawn(move || {
let Some(config) = find_config(&workspace)? else {
return Err(eyre!(
"no hex.config.ts or hex.config.js in {}",
workspace.display()
));
};
let (_, candidate) = load_config(&workspace, config)?;
Ok(format!(
"{}: {} transformation{}",
workspace.join(config).display(),
candidate.transformations.len(),
if candidate.transformations.len() == 1 {
""
} else {
"s"
}
))
})?;
handle
.join()
.map_err(|_| eyre!("personal transformation check panicked"))?
}
fn initialize_workspace_at(workspace: &Path) -> Result<()> {
fs::create_dir_all(workspace)?;
refresh_managed_files(workspace)?;
for (name, contents) in TEMPLATE_FILES {
let path = workspace.join(name);
if !path.exists() {
fs::write(path, contents)?;
}
}
if find_config(workspace)?.is_none() {
// The staged name ends in .tmp so the watcher never loads a partial file.
let staged = workspace.join(format!(".{}.{}.tmp", CONFIG_FILES[0], std::process::id()));
fs::write(&staged, TEMPLATE_CONFIG)?;
if let Err(error) = fs::rename(&staged, workspace.join(CONFIG_FILES[0])) {
let _ = fs::remove_file(&staged);
return Err(error.into());
}
}
Ok(())
}
/// Writes the typings and agent notes this build of Hex ships, where they
/// differ, so an existing folder follows app updates.
fn refresh_managed_files(workspace: &Path) -> Result<()> {
for (name, contents) in MANAGED_FILES {
let path = workspace.join(name);
if fs::read(&path).is_ok_and(|current| current == contents.as_bytes()) {
continue;
}
fs::write(&path, contents)
.wrap_err_with(|| format!("could not write {}", path.display()))?;
}
Ok(())
}
pub struct PersonalCommands {
requests: SyncSender<Request>,
stop: Arc<AtomicBool>,
worker: Option<thread::JoinHandle<()>>,
worker_done: Receiver<()>,
transformations: Arc<TransformationClient>,
}
impl PersonalCommands {
/// Starts the host, unless an organization turned transformations off
/// (`DisableTransforms`).
pub fn start(transformations: Arc<TransformationClient>) -> Option<Self> {
let lock = crate::policy::Lock::Transforms;
if crate::policy::Policy::current().locks(lock) {
tracing::info!("{}", lock.refusal());
return None;
}
let (request_sender, requests) = mpsc::sync_channel(32);
let stop = Arc::new(AtomicBool::new(false));
let (done_sender, worker_done) = mpsc::sync_channel(1);
let workspace = crate::app_paths::personal_commands_workspace().ok()?;
let status_file = crate::app_paths::personal_commands_status_file().ok();
let trust_file = crate::app_paths::transform_trust_file().ok();
let worker_transformations = transformations.clone();
let worker_requests = request_sender.clone();
let worker_stop = stop.clone();
let worker = thread::Builder::new()
.name("personal-commands".into())
.stack_size(script::THREAD_STACK_SIZE)
.spawn(move || {
// Scripts never leave this thread.
Worker {
transformations: worker_transformations,
requests: worker_requests,
workspace,
status_file,
trust_file,
generation: 0,
loaded: None,
status: StatusSnapshot {
host_state: HostState::Starting,
..StatusSnapshot::default()
},
}
.run(&requests, &worker_stop);
let _ = done_sender.send(());
})
.ok()?;
Some(Self {
requests: request_sender,
stop,
worker: Some(worker),
worker_done,
transformations,
})
}
}
impl Drop for PersonalCommands {
fn drop(&mut self) {
self.transformations.clear();
self.stop.store(true, Ordering::Release);
let _ = self.requests.try_send(Request::Reload);
if self
.worker_done
.recv_timeout(Duration::from_secs(2))
.is_ok()
&& let Some(worker) = self.worker.take()
&& worker.join().is_err()
{
tracing::warn!("personal command worker panicked during shutdown");
}
}
}
enum Request {
Transform(Box<TransformationRequest>),
/// Reload the config now; also wakes the worker to stop.
Reload,
}
/// The script worker's state: the loaded config and the status the Modes pane reads.
struct Worker {
transformations: Arc<TransformationClient>,
requests: SyncSender<Request>,
workspace: PathBuf,
status_file: Option<PathBuf>,
/// Where the person's approval of a config's `fetch` and programs lives.
trust_file: Option<PathBuf>,
/// Counts every load, so a stale transformation never reaches a newer config.
generation: u64,
loaded: Option<Loaded>,
status: StatusSnapshot,
}
/// The loaded config, the generation it registered as, and each
/// transformation's time limit.
struct Loaded {
generation: u64,
script: Script,
limits: HashMap<String, Duration>,
}
impl Worker {
fn run(mut self, requests: &Receiver<Request>, stop: &AtomicBool) {
self.persist();
if matches!(find_config(&self.workspace), Ok(Some(_)))
&& let Err(error) = refresh_managed_files(&self.workspace)
{
tracing::warn!(%error, "could not refresh the personal command typings");
}
let mut fingerprint = workspace_fingerprint(&self.workspace);
self.reload();
let mut changed_at = None;
let mut reload_now = false;
let mut next_poll = Instant::now() + POLL_INTERVAL;
while !stop.load(Ordering::Acquire) {
match requests.recv_timeout(next_poll.saturating_duration_since(Instant::now())) {
Ok(Request::Transform(request)) => self.transform(*request, stop),
Ok(Request::Reload) => reload_now = true,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
if stop.load(Ordering::Acquire) {
break;
}
let now = Instant::now();
if now >= next_poll {
next_poll = now + POLL_INTERVAL;
let next = workspace_fingerprint(&self.workspace);
if next != fingerprint {
fingerprint = next;
changed_at = Some(now);
}
}
if reload_now || changed_at.is_some_and(|changed| changed.elapsed() >= RELOAD_DEBOUNCE)
{
reload_now = false;
changed_at = None;
self.reload();
}
}
self.transformations.clear();
self.status.host_state = HostState::Stopped;
self.persist();
}
/// Loads the config as it is now. A config that fails to load leaves the
/// last good one active and reports the error; a removed config
/// unregisters everything.
fn reload(&mut self) {
let config = match find_config(&self.workspace) {
Ok(Some(config)) => config,
Ok(None) => {
if self.loaded.is_some() || self.status.host_state != HostState::NotConfigured {
self.deactivate();
self.persist();
}
return;
}
Err(error) => {
self.reject(&error.to_string());
return;
}
};
self.generation += 1;
let started = Instant::now();
match load_config(&self.workspace, config) {
Ok((script, candidate)) => {
self.transformations.activate(
self.generation,
candidate.limits.clone(),
self.requests.clone(),
);
let permissions = script.permissions().clone();
self.loaded = Some(Loaded {
generation: self.generation,
script,
limits: candidate.limits,
});
self.status = StatusSnapshot {
active_generation: Some(self.generation),
transformations: candidate.transformations,
host_state: HostState::Active,
last_reload_error: None,
permissions: permissions.capabilities().any().then_some(permissions),
};
self.persist();
tracing::info!(
generation = self.generation,
duration_us = started.elapsed().as_micros(),
"personal transformations loaded"
);
}
Err(error) => self.reject(&format!("{error:#}")),
}
}
fn reject(&mut self, error: &str) {
self.status.host_state = if self.loaded.is_some() {
HostState::Active
} else {
HostState::Unavailable
};
self.status.last_reload_error = Some(bounded_status_error(error));
self.persist();
tracing::error!(
error,
"personal command config rejected; keeping the previous one"
);
}
/// Forgets everything the last config registered.
fn deactivate(&mut self) {
self.loaded = None;
self.transformations.clear();
self.status = StatusSnapshot {
host_state: HostState::NotConfigured,
..StatusSnapshot::default()
};
}
fn persist(&self) {
let Some(path) = &self.status_file else {
return;
};
if let Err(error) = persist_status_at(path, &self.status) {
tracing::warn!(%error, "could not persist personal command status");
}
}
fn transform(&self, request: TransformationRequest, stop: &AtomicBool) {
let started = Instant::now();
let result = match self
.loaded
.as_ref()
.filter(|loaded| loaded.generation == request.generation)
{
None => Err("custom transformation generation is unavailable".into()),
Some(loaded) => self
.run_chain(loaded, &request, stop)
.map_err(|error| bounded_error(&error)),
};
tracing::info!(
generation = request.generation,
status = if result.is_ok() {
"completed"
} else {
"failed"
},
duration_us = started.elapsed().as_micros(),
"custom transformation"
);
let _ = request.response.send(result);
}
/// Runs `request`'s transformations in order, each under its own limit.
fn run_chain(
&self,
loaded: &Loaded,
request: &TransformationRequest,
stop: &AtomicBool,
) -> std::result::Result<String, String> {
let context = json(&invocation_context(&request.context));
let allowed = self.allowed(&loaded.script);
let mut text = request.text.clone();
for id in &request.ids {
let limit = loaded.limits.get(id).copied().unwrap_or(PURE_TIMEOUT);
let started = Instant::now();
let result = loaded
.script
.transform(id, &text, &context, limit, allowed, stop);
tracing::info!(
generation = loaded.generation,
id,
status = if result.is_ok() {
"completed"
} else {
"failed"
},
duration_ms = started.elapsed().as_millis() as u64,
"custom transformation step"
);
text = result?;
if text.len() > MAX_TRANSFORMATION_TEXT_BYTES {
return Err("custom transformation output is too large".into());
}
}
Ok(text)
}
/// The host APIs `script` may use: what it can reach, once the person
/// allowed this exact config.
fn allowed(&self, script: &Script) -> Capabilities {
let permissions = script.permissions();
let approved = permissions.capabilities().any()
&& self
.trust_file
.as_deref()
.and_then(trust::approved)
.is_some_and(|hash| hash == permissions.hash);
if approved {
permissions.capabilities()
} else {
Capabilities::NONE
}
}
}
/// Loads `config` from `workspace` and validates its transformations.
fn load_config(workspace: &Path, config: &str) -> Result<(Script, Candidate)> {
let script = Script::load(workspace, config).map_err(|error| eyre!(error))?;
if script.registration().len() > MAX_REGISTRATION_BYTES {
return Err(eyre!(
"the config registers more than {MAX_REGISTRATION_BYTES} bytes of transformations"
));
}
let registration: Registration = serde_json::from_str(script.registration())
.wrap_err("the config's transformations are invalid")?;
if registration.transformations.len() > MAX_TRANSFORMATIONS {
return Err(eyre!(
"personal registry exceeds {MAX_TRANSFORMATIONS} transformations"
));
}
let default_limit = if script.permissions().capabilities().any() {
IO_TIMEOUT
} else {
PURE_TIMEOUT
};
let limits = registration
.transformations
.iter()
.map(|transformation| {
let limit = transformation
.timeout
.map_or(default_limit, Duration::from_millis)
.min(MAX_TIMEOUT);
(transformation.id.clone(), limit)
})
.collect();
let transformations = registration
.transformations
.into_iter()
.map(|transformation| StatusTransformation {
id: transformation.id,
name: transformation.name,
description: transformation.description,
})
.collect::<Vec<_>>();
validate_transformations(&transformations, "")?;
Ok((
script,
Candidate {
limits,
transformations,
},
))
}
struct Candidate {
/// Each transformation's time limit, by id.
limits: HashMap<String, Duration>,
transformations: Vec<StatusTransformation>,
}
fn json(value: &impl Serialize) -> String {
serde_json::to_string(value).expect("plain data serializes")
}
/// The registration a config's `install` produces.
#[derive(Deserialize)]
struct Registration {
#[serde(default)]
transformations: Vec<RegisteredTransformation>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RegisteredTransformation {
id: String,
name: String,
description: Option<String>,
/// Milliseconds; the default depends on what the config can reach.
timeout: Option<u64>,
}
#[derive(Default)]
pub struct TransformationClient {
active: RwLock<Option<ActiveTransformations>>,
}
#[derive(Clone)]
struct ActiveTransformations {
generation: u64,
/// Each registered transformation's time limit, by id.
limits: HashMap<String, Duration>,
requests: SyncSender<Request>,
}
struct TransformationRequest {
generation: u64,
ids: Vec<String>,
text: String,
context: ContextSnapshot,
response: SyncSender<std::result::Result<String, String>>,
}
impl TransformationClient {
pub fn transform(
&self,
ids: &[String],
text: &str,
context: &ContextSnapshot,
cancelled: &AtomicBool,
) -> std::result::Result<String, String> {
if ids.is_empty() {
return Ok(text.into());
}
if text.len() > MAX_TRANSFORMATION_TEXT_BYTES {
return Err("custom transformation input is too large".into());
}
if ids.len() > MAX_TRANSFORMATIONS_PER_INVOCATION {
return Err("mode references too many transformations".into());
}
let mut output = text.to_string();
let mut custom = Vec::new();
for id in ids {
if let Some(builtin) = builtin_transformation(id) {
if !custom.is_empty() {
output = self.transform_custom(&custom, &output, context, cancelled)?;
custom.clear();
}
output = (builtin.apply)(&output);
} else {
custom.push(id.clone());
}
}
if !custom.is_empty() {
output = self.transform_custom(&custom, &output, context, cancelled)?;
}
Ok(output)
}
fn transform_custom(
&self,
ids: &[String],
text: &str,
context: &ContextSnapshot,
cancelled: &AtomicBool,
) -> std::result::Result<String, String> {
let active = self
.active
.read()
.unwrap_or_else(|error| error.into_inner())
.clone()
.ok_or_else(|| "custom transformations are unavailable".to_string())?;
let Some(budget) = ids
.iter()
.map(|id| active.limits.get(id).copied())
.sum::<Option<Duration>>()
else {
return Err("mode references an unavailable custom transformation".into());
};
let budget = budget + QUEUE_ALLOWANCE;
let (sender, receiver) = mpsc::sync_channel(1);
active
.requests
.try_send(Request::Transform(Box::new(TransformationRequest {
generation: active.generation,
ids: ids.to_vec(),
text: text.into(),
context: context.clone(),
response: sender,
})))
.map_err(|error| match error {
TrySendError::Full(_) => "custom transformation queue is full".to_string(),
TrySendError::Disconnected(_) => {
"custom transformations are unavailable".to_string()
}
})?;
let started = Instant::now();
loop {
if cancelled.load(Ordering::Acquire) {
return Err("dictation was cancelled".into());
}
let remaining = budget.saturating_sub(started.elapsed());
if remaining.is_zero() {
return Err("custom transformations timed out".into());
}
match receiver.recv_timeout(remaining.min(Duration::from_millis(50))) {
Ok(result) => return result,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err("custom transformations stopped".into());
}
}
}
}
fn activate(
&self,
generation: u64,
limits: HashMap<String, Duration>,
requests: SyncSender<Request>,
) {
*self
.active
.write()
.unwrap_or_else(|error| error.into_inner()) = Some(ActiveTransformations {
generation,
limits,
requests,
});
}
fn clear(&self) {
*self
.active
.write()
.unwrap_or_else(|error| error.into_inner()) = None;
}
}
fn spongebob_case(text: &str) -> String {
let mut uppercase = false;
let mut output = String::with_capacity(text.len());
for character in text.chars() {
if !character.is_alphabetic() {
output.push(character);
continue;
}
if uppercase {
output.extend(character.to_uppercase());
} else {
output.extend(character.to_lowercase());
}
uppercase = !uppercase;
}
output
}
// Sentence marks only. Closing quotes and brackets stay so a dictated
// quotation or parenthetical keeps its pairing intact.
const TRAILING_PUNCTUATION: &[char] = &[
'.', ',', '!', '?', ';', ':', '\u{2026}', '\u{3002}', '\u{ff01}', '\u{ff1f}', '\u{3001}',
'\u{ff0c}', '\u{ff1b}', '\u{ff1a}',
];
fn remove_trailing_punctuation(text: &str) -> String {
let body = text.trim_end();
let trailing_whitespace = &text[body.len()..];
let mut output = body.trim_end_matches(TRAILING_PUNCTUATION).to_string();
output.push_str(trailing_whitespace);
output
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct InvocationContext {
#[serde(skip_serializing_if = "Option::is_none")]
application: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
browser_host: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
browser_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
window_title: Option<String>,
}
fn invocation_context(context: &ContextSnapshot) -> InvocationContext {
InvocationContext {
application: context.application.clone(),
browser_host: context.browser_host().map(Into::into),
browser_url: context.browser_url.as_ref().map(ToString::to_string),
window_title: context.window_title.clone(),
}
}
fn workspace_fingerprint(root: &Path) -> u64 {
let mut hash = 1469598103934665603;
let mut queue = VecDeque::from([(root.to_path_buf(), 0_usize)]);
let mut visited = 0;
while let Some((path, depth)) = queue.pop_front() {
if depth > MAX_WATCH_DEPTH || visited >= MAX_WATCH_ENTRIES {
hash ^= u64::MAX;
break;
}
let Ok(entries) = fs::read_dir(path) else {
continue;
};
let mut entries = entries.flatten().collect::<Vec<_>>();
entries.sort_by_key(|entry| entry.file_name());
for entry in entries {
visited += 1;
if visited > MAX_WATCH_ENTRIES {
hash ^= u64::MAX;
break;
}
let path = entry.path();
let name = entry.file_name();
if name == "node_modules" || name == ".git" {
continue;
}
let Ok(metadata) = fs::symlink_metadata(&path) else {
continue;
};
if metadata.file_type().is_symlink() {
continue;
}
if metadata.is_dir() {
queue.push_back((path, depth + 1));
} else if metadata.is_file()
&& matches!(
path.extension().and_then(|value| value.to_str()),
Some("ts" | "json")
)
{
for byte in path.as_os_str().as_encoded_bytes() {
hash = hash
.wrapping_mul(1099511628211)
.wrapping_add(u64::from(*byte));
}
hash ^= metadata.len();
let modified = metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH);
if let Ok(duration) = modified.duration_since(SystemTime::UNIX_EPOCH) {
hash ^= duration.as_nanos() as u64;
}
}
}
}
hash