agent-infra-sdk 0.1.1

Gateway-backed Rust SDK for Agent Infra APIs
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
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
use crate::operation::{OperationHandle, OperationObservation, OperationPoller, OperationProgress};
use crate::transport::{CallOptions, HttpTransport, InfraClientError, ServiceEndpoint};
use agent_workspace_contract::{
    AckResponse, BytesResponse, CloneWorkspaceRequest, CmdOutput, CommandResource, ContentResponse,
    CreateCommandRequest, CreatePreviewRequest, CreateSnapshotRequest, CreateUploadRequest,
    CreateWorkspaceRequest, DirEntry, EntriesResponse, ExecRequest, ExistsResponse,
    KeepAliveRequest, ListDirRequest, MigrateWorkspaceRequest, OperationState, OutputPage,
    PathRequest, PutWorkspaceFileRequest, StoredPreview, UploadChunkRequest, UploadSession,
    WORKSPACE_CAPABILITIES_PATH, WORKSPACE_COMMAND_CANCEL_PATH, WORKSPACE_COMMAND_OUTPUT_PATH,
    WORKSPACE_COMMAND_PATH, WORKSPACE_COMMANDS_PATH, WORKSPACE_CREATE_DIR_ALL_PATH,
    WORKSPACE_EXEC_PATH, WORKSPACE_EXISTS_PATH, WORKSPACE_LEASE_PATH, WORKSPACE_LIST_DIR_PATH,
    WORKSPACE_MIGRATE_PATH, WORKSPACE_OPERATION_CANCEL_PATH, WORKSPACE_OPERATIONS_PATH,
    WORKSPACE_PATH, WORKSPACE_READ_FILE_PATH, WORKSPACE_RECONCILE_PATH, WORKSPACE_REMOVE_FILE_PATH,
    WORKSPACE_RESOURCE_FILE_PATH, WORKSPACE_RESOURCE_SEARCH_PATH, WORKSPACE_RESUME_PATH,
    WORKSPACE_SERVICE_NAME, WORKSPACE_SNAPSHOT_RESTORE_PATH, WORKSPACE_SNAPSHOTS_PATH,
    WORKSPACE_SUSPEND_PATH, WORKSPACE_UPLOAD_PATH, WORKSPACE_UPLOADS_PATH, WORKSPACE_USAGE_PATH,
    WORKSPACE_WRITE_FILE_PATH, WORKSPACES_PATH, WorkspaceActionRequest, WorkspaceCapabilities,
    WorkspaceLease, WorkspaceOperation, WorkspacePage, WorkspaceRecord, WorkspaceResourceUsage,
    WorkspaceSearchRequest, WorkspaceSearchResponse, WriteFileRequest,
};
use async_trait::async_trait;
use reqwest::Client;
use std::sync::Arc;
use std::time::Duration;

/// Client for the Workspace service (`agent-workspace-server`). It owns no
/// workspace state; every wire type comes from `agent-workspace-contract`.
#[derive(Clone, Debug)]
pub struct WorkspaceClient {
    transport: HttpTransport,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionedContent {
    pub content: String,
    pub revision: Option<String>,
}

impl WorkspaceClient {
    pub(crate) fn new_with_endpoint(
        http: Client,
        endpoint: ServiceEndpoint,
        options: crate::ClientOptions,
    ) -> Self {
        let endpoint = endpoint.with_default_credential_audience("workspace");
        Self {
            transport: HttpTransport::new_with_options(
                http,
                WORKSPACE_SERVICE_NAME,
                endpoint,
                options,
            ),
        }
    }

    pub async fn capabilities(&self) -> Result<WorkspaceCapabilities, InfraClientError> {
        self.transport.get_json(WORKSPACE_CAPABILITIES_PATH).await
    }

    pub async fn create_workspace(
        &self,
        request: &CreateWorkspaceRequest,
        idempotency_key: &str,
    ) -> Result<OperationHandle<WorkspaceOperation>, InfraClientError> {
        let operation = self
            .transport
            .post_json_with_options(
                WORKSPACES_PATH,
                request,
                CallOptions::default().idempotency_key(idempotency_key),
            )
            .await?;
        Ok(self.operation_handle(operation))
    }

    pub async fn workspace(&self, workspace_id: &str) -> Result<WorkspaceRecord, InfraClientError> {
        self.workspace_with_options(workspace_id, CallOptions::default())
            .await
    }

    pub async fn workspace_with_options(
        &self,
        workspace_id: &str,
        options: CallOptions,
    ) -> Result<WorkspaceRecord, InfraClientError> {
        self.transport
            .get_json_with_options(&expand(WORKSPACE_PATH, &[workspace_id]), options)
            .await
    }

    pub async fn list_workspaces(
        &self,
        after: Option<&str>,
        limit: Option<usize>,
    ) -> Result<WorkspacePage, InfraClientError> {
        let mut path = format!("{WORKSPACES_PATH}?limit={}", limit.unwrap_or(50).min(200));
        if let Some(after) = after {
            path.push_str("&after=");
            path.push_str(&encode_query_component(after));
        }
        self.transport.get_json(&path).await
    }

    pub async fn suspend_workspace(
        &self,
        workspace_id: &str,
        request: &WorkspaceActionRequest,
        key: &str,
    ) -> Result<OperationHandle<WorkspaceOperation>, InfraClientError> {
        self.workspace_action(WORKSPACE_SUSPEND_PATH, workspace_id, request, key)
            .await
    }

    pub async fn resume_workspace(
        &self,
        workspace_id: &str,
        request: &WorkspaceActionRequest,
        key: &str,
    ) -> Result<OperationHandle<WorkspaceOperation>, InfraClientError> {
        self.workspace_action(WORKSPACE_RESUME_PATH, workspace_id, request, key)
            .await
    }

    pub async fn reconcile_workspace(
        &self,
        workspace_id: &str,
        request: &WorkspaceActionRequest,
        key: &str,
    ) -> Result<OperationHandle<WorkspaceOperation>, InfraClientError> {
        self.workspace_action(WORKSPACE_RECONCILE_PATH, workspace_id, request, key)
            .await
    }

    pub async fn delete_workspace(
        &self,
        workspace_id: &str,
        request: &WorkspaceActionRequest,
        key: &str,
    ) -> Result<OperationHandle<WorkspaceOperation>, InfraClientError> {
        let operation = self
            .transport
            .delete_json_with_options(
                &expand(WORKSPACE_PATH, &[workspace_id]),
                request,
                CallOptions::default().idempotency_key(key),
            )
            .await?;
        Ok(self.operation_handle(operation))
    }

    pub async fn workspace_usage(
        &self,
        workspace_id: &str,
    ) -> Result<WorkspaceResourceUsage, InfraClientError> {
        self.transport
            .get_json(&expand(WORKSPACE_USAGE_PATH, &[workspace_id]))
            .await
    }

    async fn workspace_action(
        &self,
        path: &str,
        workspace_id: &str,
        request: &WorkspaceActionRequest,
        key: &str,
    ) -> Result<OperationHandle<WorkspaceOperation>, InfraClientError> {
        let operation = self
            .transport
            .post_json_with_options(
                &expand(path, &[workspace_id]),
                request,
                CallOptions::default().idempotency_key(key),
            )
            .await?;
        Ok(self.operation_handle(operation))
    }

    pub async fn read_file(&self, path: &str) -> Result<String, InfraClientError> {
        Ok(self.read_file_versioned(path).await?.content)
    }

    /// Read a file from an explicit managed workspace. New consumers should
    /// prefer this over the implicit single-root compatibility API.
    pub async fn read_workspace_file(
        &self,
        workspace_id: &str,
        path: &str,
    ) -> Result<BytesResponse, InfraClientError> {
        self.read_workspace_file_with_options(workspace_id, path, CallOptions::default())
            .await
    }

    pub async fn read_workspace_file_with_options(
        &self,
        workspace_id: &str,
        path: &str,
        options: CallOptions,
    ) -> Result<BytesResponse, InfraClientError> {
        self.transport
            .get_json_with_options(&resource_file_path(workspace_id, path), options)
            .await
    }

    pub async fn put_workspace_file(
        &self,
        workspace_id: &str,
        path: &str,
        request: &PutWorkspaceFileRequest,
        options: CallOptions,
    ) -> Result<Option<String>, InfraClientError> {
        let response: AckResponse = self
            .transport
            .put_json_with_options(&resource_file_path(workspace_id, path), request, options)
            .await?;
        ensure_ack(response)
    }

    pub async fn search_workspace_files(
        &self,
        workspace_id: &str,
        request: &WorkspaceSearchRequest,
    ) -> Result<WorkspaceSearchResponse, InfraClientError> {
        self.search_workspace_files_with_options(workspace_id, request, CallOptions::default())
            .await
    }

    pub async fn search_workspace_files_with_options(
        &self,
        workspace_id: &str,
        request: &WorkspaceSearchRequest,
        options: CallOptions,
    ) -> Result<WorkspaceSearchResponse, InfraClientError> {
        self.transport
            .post_json_with_options(
                &expand(WORKSPACE_RESOURCE_SEARCH_PATH, &[workspace_id]),
                request,
                options.idempotent(true),
            )
            .await
    }

    pub async fn next_workspace_search(
        &self,
        workspace_id: &str,
        request: &WorkspaceSearchRequest,
        current: &WorkspaceSearchResponse,
    ) -> Result<Option<WorkspaceSearchResponse>, InfraClientError> {
        let Some(cursor) = current.next_cursor.as_deref() else {
            return Ok(None);
        };
        let mut next = request.clone();
        next.cursor = Some(cursor.to_string());
        self.search_workspace_files(workspace_id, &next)
            .await
            .map(Some)
    }

    pub async fn read_file_versioned(
        &self,
        path: &str,
    ) -> Result<VersionedContent, InfraClientError> {
        let response: ContentResponse = self
            .transport
            .post_json_idempotent(WORKSPACE_READ_FILE_PATH, &PathRequest { path: path.into() })
            .await?;
        Ok(VersionedContent {
            content: response.content,
            revision: response.revision,
        })
    }

    pub async fn write_file(&self, path: &str, content: &str) -> Result<(), InfraClientError> {
        self.write_file_with_options(path, content, None, CallOptions::default())
            .await
            .map(|_| ())
    }

    pub async fn write_file_if_match(
        &self,
        path: &str,
        content: &str,
        revision: &str,
    ) -> Result<String, InfraClientError> {
        self.write_file_with_options(
            path,
            content,
            Some(revision),
            // A lost successful CAS response cannot be replayed safely without
            // server-side idempotency-key storage: the original revision has
            // already changed. Keep automatic retry disabled by default.
            CallOptions::default(),
        )
        .await?
        .ok_or_else(|| InfraClientError::Protocol {
            service: WORKSPACE_SERVICE_NAME,
            message: "workspace omitted the revision after a conditional write".into(),
        })
    }

    pub async fn write_file_with_options(
        &self,
        path: &str,
        content: &str,
        if_match: Option<&str>,
        options: CallOptions,
    ) -> Result<Option<String>, InfraClientError> {
        let response: AckResponse = self
            .transport
            .post_json_with_options(
                WORKSPACE_WRITE_FILE_PATH,
                &WriteFileRequest {
                    path: path.into(),
                    content: content.into(),
                    if_match: if_match.map(Into::into),
                },
                options,
            )
            .await?;
        ensure_ack(response)
    }

    pub async fn exists(&self, path: &str) -> Result<bool, InfraClientError> {
        let response: ExistsResponse = self
            .transport
            .post_json_idempotent(WORKSPACE_EXISTS_PATH, &PathRequest { path: path.into() })
            .await?;
        Ok(response.exists)
    }

    pub async fn create_dir_all(&self, path: &str) -> Result<(), InfraClientError> {
        let response: AckResponse = self
            .transport
            .post_json(
                WORKSPACE_CREATE_DIR_ALL_PATH,
                &PathRequest { path: path.into() },
            )
            .await?;
        ensure_ack(response).map(|_| ())
    }

    pub async fn list_dir(&self, path: &str) -> Result<Vec<DirEntry>, InfraClientError> {
        let response: EntriesResponse = self
            .transport
            .post_json_idempotent(
                WORKSPACE_LIST_DIR_PATH,
                &ListDirRequest {
                    path: path.into(),
                    include_hidden: false,
                    include_ignored: false,
                },
            )
            .await?;
        Ok(response.entries)
    }

    pub async fn exec(
        &self,
        command: &str,
        cwd: Option<&str>,
    ) -> Result<CmdOutput, InfraClientError> {
        self.transport
            .post_json(
                WORKSPACE_EXEC_PATH,
                &ExecRequest {
                    command: command.into(),
                    cwd: cwd.map(Into::into),
                },
            )
            .await
    }

    pub async fn remove_file(&self, path: &str) -> Result<(), InfraClientError> {
        let response: AckResponse = self
            .transport
            .post_json(
                WORKSPACE_REMOVE_FILE_PATH,
                &PathRequest { path: path.into() },
            )
            .await?;
        ensure_ack(response).map(|_| ())
    }

    pub async fn create_upload(
        &self,
        workspace_id: &str,
        request: &CreateUploadRequest,
        idempotency_key: &str,
    ) -> Result<UploadSession, InfraClientError> {
        self.transport
            .post_json_with_options(
                &expand(WORKSPACE_UPLOADS_PATH, &[workspace_id]),
                request,
                CallOptions::default().idempotency_key(idempotency_key),
            )
            .await
    }

    pub async fn create_preview(
        &self,
        workspace_id: &str,
        request: &CreatePreviewRequest,
        idempotency_key: &str,
    ) -> Result<StoredPreview, InfraClientError> {
        self.transport
            .post_json_with_options(
                &format!(
                    "/internal/v1/workspaces/{}/previews",
                    encode_path_segment(workspace_id)
                ),
                request,
                CallOptions::default().idempotency_key(idempotency_key),
            )
            .await
    }

    pub async fn upload(
        &self,
        workspace_id: &str,
        upload_id: &str,
    ) -> Result<UploadSession, InfraClientError> {
        self.transport
            .get_json(&expand(WORKSPACE_UPLOAD_PATH, &[workspace_id, upload_id]))
            .await
    }

    pub async fn upload_chunk(
        &self,
        workspace_id: &str,
        upload_id: &str,
        request: &UploadChunkRequest,
    ) -> Result<UploadSession, InfraClientError> {
        self.transport
            .put_json_with_options(
                &expand(WORKSPACE_UPLOAD_PATH, &[workspace_id, upload_id]),
                request,
                CallOptions::default(),
            )
            .await
    }

    pub async fn create_command(
        &self,
        workspace_id: &str,
        request: &CreateCommandRequest,
        idempotency_key: &str,
    ) -> Result<CommandResource, InfraClientError> {
        self.create_command_with_options(
            workspace_id,
            request,
            CallOptions::default().idempotency_key(idempotency_key),
        )
        .await
    }

    pub async fn create_command_with_options(
        &self,
        workspace_id: &str,
        request: &CreateCommandRequest,
        options: CallOptions,
    ) -> Result<CommandResource, InfraClientError> {
        self.transport
            .post_json_with_options(
                &expand(WORKSPACE_COMMANDS_PATH, &[workspace_id]),
                request,
                options,
            )
            .await
    }

    pub async fn command(
        &self,
        workspace_id: &str,
        command_id: &str,
    ) -> Result<CommandResource, InfraClientError> {
        self.command_with_options(workspace_id, command_id, CallOptions::default())
            .await
    }

    pub async fn command_with_options(
        &self,
        workspace_id: &str,
        command_id: &str,
        options: CallOptions,
    ) -> Result<CommandResource, InfraClientError> {
        self.transport
            .get_json_with_options(
                &expand(WORKSPACE_COMMAND_PATH, &[workspace_id, command_id]),
                options,
            )
            .await
    }

    pub async fn command_output(
        &self,
        workspace_id: &str,
        command_id: &str,
        after: u64,
        limit: Option<usize>,
    ) -> Result<OutputPage, InfraClientError> {
        self.command_output_with_options(
            workspace_id,
            command_id,
            after,
            limit,
            CallOptions::default(),
        )
        .await
    }

    pub async fn command_output_with_options(
        &self,
        workspace_id: &str,
        command_id: &str,
        after: u64,
        limit: Option<usize>,
        options: CallOptions,
    ) -> Result<OutputPage, InfraClientError> {
        let mut path = expand(WORKSPACE_COMMAND_OUTPUT_PATH, &[workspace_id, command_id]);
        path.push_str(&format!(
            "?after={after}&limit={}",
            limit.unwrap_or(64).min(64)
        ));
        self.transport.get_json_with_options(&path, options).await
    }

    pub async fn next_command_output(
        &self,
        workspace_id: &str,
        command_id: &str,
        current: &OutputPage,
        limit: Option<usize>,
    ) -> Result<Option<OutputPage>, InfraClientError> {
        let Some(cursor) = current.next_cursor else {
            return Ok(None);
        };
        self.command_output(workspace_id, command_id, cursor, limit)
            .await
            .map(Some)
    }

    pub async fn cancel_command(
        &self,
        workspace_id: &str,
        command_id: &str,
    ) -> Result<CommandResource, InfraClientError> {
        self.cancel_command_with_options(
            workspace_id,
            command_id,
            CallOptions::default()
                .idempotency_key(format!("cancel-command:{workspace_id}:{command_id}")),
        )
        .await
    }

    pub async fn cancel_command_with_options(
        &self,
        workspace_id: &str,
        command_id: &str,
        options: CallOptions,
    ) -> Result<CommandResource, InfraClientError> {
        self.transport
            .post_json_with_options(
                &expand(WORKSPACE_COMMAND_CANCEL_PATH, &[workspace_id, command_id]),
                &serde_json::json!({}),
                options,
            )
            .await
    }

    pub async fn create_snapshot(
        &self,
        workspace_id: &str,
        request: &CreateSnapshotRequest,
        idempotency_key: &str,
    ) -> Result<OperationHandle<WorkspaceOperation>, InfraClientError> {
        let operation: WorkspaceOperation = self
            .transport
            .post_json_with_options(
                &expand(WORKSPACE_SNAPSHOTS_PATH, &[workspace_id]),
                request,
                CallOptions::default().idempotency_key(idempotency_key),
            )
            .await?;
        Ok(self.operation_handle(operation))
    }

    pub async fn restore_snapshot(
        &self,
        workspace_id: &str,
        snapshot_id: &str,
        idempotency_key: &str,
    ) -> Result<OperationHandle<WorkspaceOperation>, InfraClientError> {
        let operation: WorkspaceOperation = self
            .transport
            .post_json_with_options(
                &expand(
                    WORKSPACE_SNAPSHOT_RESTORE_PATH,
                    &[workspace_id, snapshot_id],
                ),
                &serde_json::json!({}),
                CallOptions::default().idempotency_key(idempotency_key),
            )
            .await?;
        Ok(self.operation_handle(operation))
    }

    pub async fn clone_workspace(
        &self,
        workspace_id: &str,
        request: &CloneWorkspaceRequest,
        idempotency_key: &str,
    ) -> Result<OperationHandle<WorkspaceOperation>, InfraClientError> {
        let operation: WorkspaceOperation = self
            .transport
            .post_json_with_options(
                &expand(
                    agent_workspace_contract::WORKSPACE_CLONE_PATH,
                    &[workspace_id],
                ),
                request,
                CallOptions::default().idempotency_key(idempotency_key),
            )
            .await?;
        Ok(self.operation_handle(operation))
    }

    pub async fn migrate_workspace(
        &self,
        workspace_id: &str,
        request: &MigrateWorkspaceRequest,
        idempotency_key: &str,
    ) -> Result<OperationHandle<WorkspaceOperation>, InfraClientError> {
        let operation: WorkspaceOperation = self
            .transport
            .post_json_with_options(
                &expand(WORKSPACE_MIGRATE_PATH, &[workspace_id]),
                request,
                CallOptions::default().idempotency_key(idempotency_key),
            )
            .await?;
        Ok(self.operation_handle(operation))
    }

    pub async fn keep_alive(
        &self,
        workspace_id: &str,
        request: &KeepAliveRequest,
    ) -> Result<WorkspaceLease, InfraClientError> {
        self.transport
            .put_json_with_options(
                &expand(WORKSPACE_LEASE_PATH, &[workspace_id]),
                request,
                CallOptions::default(),
            )
            .await
    }

    pub async fn operation(
        &self,
        operation_id: &str,
    ) -> Result<OperationHandle<WorkspaceOperation>, InfraClientError> {
        let operation = WorkspaceOperationPoller {
            transport: self.transport.clone(),
        }
        .poll(operation_id)
        .await?;
        Ok(self.operation_handle(operation))
    }

    fn operation_handle(
        &self,
        operation: WorkspaceOperation,
    ) -> OperationHandle<WorkspaceOperation> {
        OperationHandle::new(
            operation.id.clone(),
            Some(operation),
            Arc::new(WorkspaceOperationPoller {
                transport: self.transport.clone(),
            }),
        )
    }
}

#[derive(Clone, Debug)]
struct WorkspaceOperationPoller {
    transport: HttpTransport,
}

#[async_trait]
impl OperationPoller<WorkspaceOperation> for WorkspaceOperationPoller {
    async fn poll(&self, operation_id: &str) -> Result<WorkspaceOperation, InfraClientError> {
        self.transport
            .get_json(&expand(WORKSPACE_OPERATIONS_PATH, &[operation_id]))
            .await
    }

    async fn cancel(&self, operation_id: &str) -> Result<(), InfraClientError> {
        let operation: WorkspaceOperation = self.poll(operation_id).await?;
        let _: WorkspaceOperation = self
            .transport
            .post_json_with_options(
                &expand(WORKSPACE_OPERATION_CANCEL_PATH, &[operation_id]),
                &WorkspaceActionRequest {
                    expected_version: operation.version,
                    reason: None,
                },
                // Cancellation carries an optimistic version. Until the
                // service stores a cancellation idempotency key, replaying a
                // lost success can manufacture a false version conflict.
                CallOptions::default(),
            )
            .await?;
        Ok(())
    }

    fn observe(&self, operation: &WorkspaceOperation) -> OperationObservation {
        let progress = match operation.state {
            OperationState::Succeeded => OperationProgress::Succeeded,
            OperationState::Failed => OperationProgress::Failed,
            OperationState::Canceled => OperationProgress::Canceled,
            OperationState::Queued | OperationState::Running | OperationState::Canceling => {
                OperationProgress::Pending
            }
        };
        OperationObservation {
            progress,
            next_poll_after: operation.next_poll_after_ms.map(Duration::from_millis),
            error_code: operation.error_code.clone(),
        }
    }
}

fn ensure_ack(response: AckResponse) -> Result<Option<String>, InfraClientError> {
    if response.ok {
        Ok(response.revision)
    } else {
        Err(InfraClientError::Protocol {
            service: WORKSPACE_SERVICE_NAME,
            message: "operation returned ok=false".into(),
        })
    }
}

fn expand(template: &str, values: &[&str]) -> String {
    let mut result = template.to_string();
    for value in values {
        let Some(start) = result.find('{') else {
            break;
        };
        let Some(relative_end) = result[start..].find('}') else {
            break;
        };
        result.replace_range(start..=start + relative_end, &encode_path_segment(value));
    }
    result
}

fn resource_file_path(workspace_id: &str, path: &str) -> String {
    let encoded_path = path
        .trim_start_matches('/')
        .split('/')
        .map(encode_path_segment)
        .collect::<Vec<_>>()
        .join("/");
    expand(WORKSPACE_RESOURCE_FILE_PATH, &[workspace_id]).replace("{*filePath}", &encoded_path)
}

fn encode_path_segment(value: &str) -> String {
    let mut encoded = String::with_capacity(value.len());
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
            encoded.push(char::from(byte));
        } else {
            use std::fmt::Write as _;
            write!(&mut encoded, "%{byte:02X}").expect("writing to String cannot fail");
        }
    }
    encoded
}

fn encode_query_component(value: &str) -> String {
    encode_path_segment(value)
}