-
Notifications
You must be signed in to change notification settings - Fork 394
Expand file tree
/
Copy pathhosted_agents.go
More file actions
1780 lines (1625 loc) · 77.3 KB
/
Copy pathhosted_agents.go
File metadata and controls
1780 lines (1625 loc) · 77.3 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
package godo
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
const (
hostedAgentManifestMediaType = "application/x-yaml"
hostedAgentWorkspaceMediaType = "application/octet-stream"
hostedAgentsSessionsBasePath = "/v2/agents/sessions"
hostedAgentPolicyValidatePath = hostedAgentsSessionsBasePath + "/policy/validate"
hostedAgentSessionByIDPath = hostedAgentsSessionsBasePath + "/%s"
hostedAgentSessionEventsPath = hostedAgentSessionByIDPath + "/events"
hostedAgentSessionInputPath = hostedAgentSessionByIDPath + "/input"
hostedAgentSessionRequestPath = hostedAgentSessionByIDPath + "/request"
hostedAgentSessionHITLPath = hostedAgentSessionByIDPath + "/hitl/%s"
hostedAgentSessionSandboxExecPath = hostedAgentSessionByIDPath + "/sandbox/exec"
hostedAgentSandboxSizesPath = hostedAgentsSessionsBasePath + "/sandbox/sizes"
hostedAgentSessionPausePath = hostedAgentSessionByIDPath + "/pause"
hostedAgentSessionResumePath = hostedAgentSessionByIDPath + "/resume"
hostedAgentSessionWorkspaceUploadPath = hostedAgentSessionByIDPath + "/workspace/upload"
hostedAgentSessionWorkspaceDownloadPath = hostedAgentSessionByIDPath + "/workspace/download"
hostedAgentSessionWorkspaceTransfersPath = hostedAgentSessionByIDPath + "/workspace/transfers"
hostedAgentSessionWorkspaceTransferByIDPath = hostedAgentSessionWorkspaceTransfersPath + "/%s"
hostedAgentSessionWorkspaceTransferPartURLsPath = hostedAgentSessionWorkspaceTransferByIDPath + "/part-upload-urls"
hostedAgentSessionWorkspaceTransferCommitPath = hostedAgentSessionWorkspaceTransferByIDPath + "/commit"
hostedAgentSessionWorkspaceTransferCancelPath = hostedAgentSessionWorkspaceTransferByIDPath + "/cancel"
// Team-scoped external-provider (e.g. GitHub) OAuth connect flow.
hostedAgentProviderAuthPath = "/v2/agents/auth/%s"
hostedAgentProviderAuthPollPath = hostedAgentProviderAuthPath + "/poll"
hostedAgentSessionCheckpointsPath = hostedAgentSessionByIDPath + "/checkpoints"
hostedAgentSessionCheckpointByIDPath = hostedAgentSessionCheckpointsPath + "/%s"
hostedAgentSessionCheckpointRollbackPath = hostedAgentSessionCheckpointByIDPath + "/rollback"
hostedAgentSessionForkPath = hostedAgentSessionByIDPath + "/fork"
// HostedAgentForkMaxCount is the v1 cap on children created by one fork call.
HostedAgentForkMaxCount = 4
workspaceContentSHA256Header = "X-Content-Sha256"
workspaceIsArchiveHeader = "X-Workspace-Is-Archive"
workspaceSizeBytesHeader = "X-Workspace-Size-Bytes"
// sseLastEventIDHeader is the standard SSE resume cursor. The data-plane
// events endpoint takes the cursor here rather than as a query parameter.
sseLastEventIDHeader = "Last-Event-ID"
// workspaceDownloadFooter is appended by OHS after a successful download
// payload so integrity survives intermediaries that strip HTTP trailers
// (e.g. Cloudflare). Format: DOWSSHA1 + 64 lowercase hex + '\n' = 73 bytes.
workspaceDownloadFooterPrefix = "DOWSSHA1"
workspaceDownloadFooterLen = len(workspaceDownloadFooterPrefix) + 64 + 1
)
// HostedAgentsService exposes the DigitalOcean Hosted Agents session API
// (HarnessAPI from harness.proto). Routes live under /v2/agents/sessions.
type HostedAgentsService interface {
// CreateSession provisions a session using the legacy JSON body (agent_kind,
// repo_hint, idle_timeout_seconds). Prefer CreateSessionFromManifest for
// Environment Spec YAML (or CreateSessionFromEnvironment for a saved
// Environment).
CreateSession(context.Context, *HostedAgentSessionCreateRequest) (*HostedAgentSession, *Response, error)
// CreateSessionFromManifest uploads an environment spec YAML document
// (Content-Type: application/x-yaml). Legacy agents.digitalocean.com/v1alpha1
// Agent manifests are also accepted where the API still supports them.
// For OpenAI sandbox-provider sessions (adapter codex-agentapi), pass
// OpenAISessionID in opt so harness-api can persist openai_session_id for
// attach correlation (?openai_session_id=). doctl resolves ${...}
// placeholders client-side before calling this API; there is no
// server-side variables map.
CreateSessionFromManifest(context.Context, []byte, *HostedAgentManifestCreateOptions) (*HostedAgentSession, *Response, error)
// CreateSessionFromEnvironment provisions a session from an existing
// immutable Environment, referenced by config_id. The request uses
// Content-Type: application/json with a {name, config_id} body (optional
// resume_on_topoff); the environment's stored manifest and declared
// credentials seed the session at create time.
CreateSessionFromEnvironment(context.Context, *HostedAgentSessionFromEnvironmentRequest) (*HostedAgentSession, *Response, error)
// CreateSessionFromConfig is an alias for CreateSessionFromEnvironment.
// Prefer CreateSessionFromEnvironment; this name remains for compatibility.
CreateSessionFromConfig(context.Context, *HostedAgentSessionFromConfigRequest) (*HostedAgentSession, *Response, error)
// ValidatePolicy checks a manifest's tool-permission policy against the
// agent's capabilities without creating a session. Manifest is the same YAML
// document accepted by CreateSessionFromManifest (Content-Type:
// application/x-yaml). Returns per-rule verdicts; OK is false when any strict
// rule is unsupported or unverified (i.e. CreateSession would reject it).
ValidatePolicy(context.Context, []byte) (*HostedAgentPolicyValidationResult, *Response, error)
ListSessions(context.Context, *HostedAgentSessionListOptions) (*HostedAgentSessionsListResponse, *Response, error)
GetSession(context.Context, string) (*HostedAgentSession, *Response, error)
// UpdateSession patches session-scoped settings on an existing session and
// returns the updated snapshot. Never touches the agent manifest or config.
UpdateSession(context.Context, string, *HostedAgentSessionUpdateRequest) (*HostedAgentSession, *Response, error)
DestroySession(context.Context, string) (*Response, error)
PauseSession(context.Context, string) (*Response, error)
ResumeSession(context.Context, string) (*Response, error)
StreamSession(context.Context, string, *HostedAgentSessionStreamOptions) (*HostedAgentSessionStream, *Response, error)
SendInput(context.Context, string, *HostedAgentSendInputRequest) (*HostedAgentSendInputResponse, *Response, error)
RelayRequest(context.Context, string, *HostedAgentRelayRequest) (*HostedAgentRelayResponse, *Response, error)
ResolveHITL(context.Context, string, string, *HostedAgentResolveHITLRequest) (*Response, error)
// StartProviderAuth begins (or resumes) the team-scoped connect flow for an
// external provider (e.g. "github"). The team is derived from the
// authenticated principal; there is no request body.
StartProviderAuth(context.Context, string) (*HostedAgentProviderAuthStart, *Response, error)
// PollProviderAuth reports whether a pending connect link has been
// authorized. pollURL is the PollURL returned by StartProviderAuth.
PollProviderAuth(context.Context, string, string) (*HostedAgentProviderAuthPoll, *Response, error)
ExecInSandbox(context.Context, string, *HostedAgentSandboxExecRequest) (*HostedAgentSandboxExecResponse, *Response, error)
// ListSandboxSizes returns the customer-selectable sandbox (microVM) size
// catalog (GET /v2/agents/sessions/sandbox/sizes). Every slug is accepted by
// CreateSession as spec.sandbox.sizeSlug. Ordered smallest-to-largest; no
// pagination.
ListSandboxSizes(context.Context) (*HostedAgentSandboxSizesResponse, *Response, error)
UploadWorkspace(context.Context, string, *HostedAgentWorkspaceUploadRequest) (*HostedAgentWorkspaceUploadResponse, *Response, error)
DownloadWorkspace(context.Context, string, *HostedAgentWorkspaceDownloadRequest) (*HostedAgentWorkspaceDownload, *Response, error)
// Large-file (>~50 MiB) staged workspace transfer APIs. Streaming
// UploadWorkspace / DownloadWorkspace remain for smaller payloads.
CreateWorkspaceTransfer(context.Context, string, *HostedAgentWorkspaceTransferCreateRequest) (*HostedAgentWorkspaceTransfer, *Response, error)
CreateWorkspaceTransferPartUploadURLs(context.Context, string, string, *HostedAgentWorkspaceTransferPartUploadURLsRequest) (*HostedAgentWorkspaceTransferPartUploadURLs, *Response, error)
CommitWorkspaceTransfer(context.Context, string, string, *HostedAgentWorkspaceTransferCommitRequest) (*HostedAgentWorkspaceTransfer, *Response, error)
GetWorkspaceTransfer(context.Context, string, string) (*HostedAgentWorkspaceTransfer, *Response, error)
CancelWorkspaceTransfer(context.Context, string, string, *HostedAgentWorkspaceTransferCancelRequest) (*HostedAgentWorkspaceTransferCancelResponse, *Response, error)
// Checkpoint / fork / rollback (session save points).
CreateCheckpoint(context.Context, string, *HostedAgentCheckpointCreateRequest) (*HostedAgentCheckpoint, *Response, error)
ListCheckpoints(context.Context, string, *HostedAgentCheckpointListOptions) (*HostedAgentCheckpointsListResponse, *Response, error)
GetCheckpoint(context.Context, string, string) (*HostedAgentCheckpoint, *Response, error)
DeleteCheckpoint(context.Context, string, string) (*HostedAgentCheckpointDeleteResponse, *Response, error)
ForkSession(context.Context, string, *HostedAgentForkSessionRequest) (*HostedAgentForkSessionResponse, *Response, error)
RollbackToCheckpoint(context.Context, string, string) (*HostedAgentSession, *Response, error)
// Environments (immutable team-scoped environment definitions). Routes
// live under /v2/agents/configs. Prefer the Environment* methods; the
// AgentConfig* names remain as compatible aliases.
ListEnvironments(context.Context, *HostedEnvironmentListOptions) (*HostedEnvironmentsListResponse, *Response, error)
GetEnvironment(context.Context, string) (*HostedEnvironment, *Response, error)
CreateEnvironment(context.Context, *HostedEnvironmentCreateRequest) (*HostedEnvironment, *Response, error)
DeleteEnvironment(context.Context, string) (*Response, error)
ListEnvironmentSessions(context.Context, string, *HostedAgentSessionListOptions) (*HostedAgentSessionsListResponse, *Response, error)
// Prefer ListEnvironments / GetEnvironment / CreateEnvironment /
// DeleteEnvironment / ListEnvironmentSessions.
ListAgentConfigs(context.Context, *HostedAgentConfigListOptions) (*HostedAgentConfigsListResponse, *Response, error)
GetAgentConfig(context.Context, string) (*HostedAgentConfig, *Response, error)
CreateAgentConfig(context.Context, *HostedAgentConfigCreateRequest) (*HostedAgentConfig, *Response, error)
DeleteAgentConfig(context.Context, string) (*Response, error)
ListAgentConfigSessions(context.Context, string, *HostedAgentSessionListOptions) (*HostedAgentSessionsListResponse, *Response, error)
// Team custom templates (BYOA). Routes live under /v2/agents/templates.
ListTemplates(context.Context, *HostedAgentTemplateListOptions) (*HostedAgentTemplatesListResponse, *Response, error)
CreateTemplate(context.Context, *HostedAgentTemplateCreateRequest) (*HostedAgentTemplate, *Response, error)
GetTemplate(context.Context, string) (*HostedAgentTemplate, *Response, error)
UpdateTemplate(context.Context, string, *HostedAgentTemplateUpdateRequest) (*HostedAgentTemplate, *Response, error)
DeleteTemplate(context.Context, string) (*HostedAgentTemplateDeleteResponse, *Response, error)
ListTemplateBuilds(context.Context, string, *HostedAgentTemplateBuildListOptions) (*HostedAgentTemplateBuildsListResponse, *Response, error)
GetTemplateBuild(context.Context, string, string) (*HostedAgentTemplateBuild, *Response, error)
GetTemplateBuildLogs(context.Context, string, string) (*HostedAgentTemplateBuildLogs, *Response, error)
}
// HostedAgentsServiceOp handles communication with Hosted Agents session methods.
type HostedAgentsServiceOp struct {
client *Client
}
var _ HostedAgentsService = &HostedAgentsServiceOp{}
// HostedAgentKind identifies the agent runtime provisioned for a session.
type HostedAgentKind string
const (
HostedAgentKindUnspecified HostedAgentKind = "AGENT_KIND_UNSPECIFIED"
HostedAgentKindClaudeCode HostedAgentKind = "AGENT_KIND_CLAUDE_CODE"
HostedAgentKindOpenCode HostedAgentKind = "AGENT_KIND_OPENCODE"
HostedAgentKindCodexCLI HostedAgentKind = "AGENT_KIND_CODEX_CLI"
HostedAgentKindCursorCLI HostedAgentKind = "AGENT_KIND_CURSOR_CLI"
// HostedAgentKindOpenAICodex is the OpenAI Agents API sandbox-provider kind
// (adapter codex-agentapi). Attach bridges to OpenAI, not DO's SSE stream.
HostedAgentKindOpenAICodex HostedAgentKind = "AGENT_KIND_OPENAI_CODEX"
HostedAgentKindNone HostedAgentKind = "AGENT_KIND_NONE"
HostedAgentKindCustom HostedAgentKind = "AGENT_KIND_CUSTOM"
)
// HostedAgentSessionStatus is the lifecycle status of a hosted agent session.
type HostedAgentSessionStatus string
const (
HostedAgentSessionStatusUnspecified HostedAgentSessionStatus = "SESSION_STATUS_UNSPECIFIED"
HostedAgentSessionStatusProvisioning HostedAgentSessionStatus = "SESSION_STATUS_PROVISIONING"
HostedAgentSessionStatusReady HostedAgentSessionStatus = "SESSION_STATUS_READY"
HostedAgentSessionStatusDetached HostedAgentSessionStatus = "SESSION_STATUS_DETACHED"
HostedAgentSessionStatusDestroying HostedAgentSessionStatus = "SESSION_STATUS_DESTROYING"
HostedAgentSessionStatusDestroyed HostedAgentSessionStatus = "SESSION_STATUS_DESTROYED"
HostedAgentSessionStatusFailed HostedAgentSessionStatus = "SESSION_STATUS_FAILED"
HostedAgentSessionStatusPaused HostedAgentSessionStatus = "SESSION_STATUS_PAUSED"
)
// HostedAgentSessionPauseReason is why a paused session was paused. The API
// reserves the right to add reasons, so an unrecognized value is an opaque
// reason string rather than an error: compare against the constants below to
// recognize a reason, but pass anything else through as-is.
type HostedAgentSessionPauseReason string
const (
// HostedAgentSessionPauseReasonManual is a pause requested through PauseSession.
HostedAgentSessionPauseReasonManual HostedAgentSessionPauseReason = "manual"
// HostedAgentSessionPauseReasonIdle is an automatic pause after inactivity.
HostedAgentSessionPauseReasonIdle HostedAgentSessionPauseReason = "idle"
// HostedAgentSessionPauseReasonZeroBalance is a pause by the prepayment gate.
// It is the only reason the server auto-resumes from, and only for sessions
// with ResumeOnTopoff set.
HostedAgentSessionPauseReasonZeroBalance HostedAgentSessionPauseReason = "zero_balance"
// Deprecated: Use HostedAgentSessionPauseReasonZeroBalance. Servers now return
// "zero_balance"; this constant is kept for backward compatibility with older API responses.
HostedAgentSessionPauseReasonLowBalance HostedAgentSessionPauseReason = "low_balance"
)
// HostedAgentProviderAuthState tracks OAuth authorization for an external provider.
type HostedAgentProviderAuthState string
const (
HostedAgentProviderAuthStateUnspecified HostedAgentProviderAuthState = "PROVIDER_AUTH_STATE_UNSPECIFIED"
HostedAgentProviderAuthStateNone HostedAgentProviderAuthState = "PROVIDER_AUTH_STATE_NONE"
HostedAgentProviderAuthStatePending HostedAgentProviderAuthState = "PROVIDER_AUTH_STATE_PENDING"
HostedAgentProviderAuthStateAuthorized HostedAgentProviderAuthState = "PROVIDER_AUTH_STATE_AUTHORIZED"
HostedAgentProviderAuthStateExpired HostedAgentProviderAuthState = "PROVIDER_AUTH_STATE_EXPIRED"
)
// HostedAgentRunState is the lifecycle state of a single agent run.
type HostedAgentRunState string
const (
HostedAgentRunStateUnspecified HostedAgentRunState = "RUN_STATE_UNSPECIFIED"
HostedAgentRunStateQueued HostedAgentRunState = "RUN_STATE_QUEUED"
HostedAgentRunStateRunning HostedAgentRunState = "RUN_STATE_RUNNING"
HostedAgentRunStateAwaitingHITL HostedAgentRunState = "RUN_STATE_AWAITING_HITL"
HostedAgentRunStatePaused HostedAgentRunState = "RUN_STATE_PAUSED"
HostedAgentRunStateCompleted HostedAgentRunState = "RUN_STATE_COMPLETED"
HostedAgentRunStateFailed HostedAgentRunState = "RUN_STATE_FAILED"
)
// HostedAgentHITLActionKind classifies a human-in-the-loop approval request.
type HostedAgentHITLActionKind string
const (
HostedAgentHITLActionUnspecified HostedAgentHITLActionKind = "HITL_ACTION_KIND_UNSPECIFIED"
HostedAgentHITLActionBash HostedAgentHITLActionKind = "HITL_ACTION_BASH"
HostedAgentHITLActionFileWriteOutsideWorkspace HostedAgentHITLActionKind = "HITL_ACTION_FILE_WRITE_OUTSIDE_WORKSPACE"
HostedAgentHITLActionGitHubCommitPush HostedAgentHITLActionKind = "HITL_ACTION_GITHUB_COMMIT_PUSH"
HostedAgentHITLActionGitHubCreatePR HostedAgentHITLActionKind = "HITL_ACTION_GITHUB_CREATE_PR"
HostedAgentHITLActionGitHubBranchDelete HostedAgentHITLActionKind = "HITL_ACTION_GITHUB_BRANCH_DELETE"
HostedAgentHITLActionGitHubForcePush HostedAgentHITLActionKind = "HITL_ACTION_GITHUB_FORCE_PUSH"
)
// HostedAgentHITLOutcome is the user's decision on a HITL request.
type HostedAgentHITLOutcome string
const (
HostedAgentHITLOutcomeUnspecified HostedAgentHITLOutcome = "HITL_OUTCOME_UNSPECIFIED"
HostedAgentHITLOutcomeApprove HostedAgentHITLOutcome = "HITL_OUTCOME_APPROVE"
HostedAgentHITLOutcomeReject HostedAgentHITLOutcome = "HITL_OUTCOME_REJECT"
HostedAgentHITLOutcomeDefer HostedAgentHITLOutcome = "HITL_OUTCOME_DEFER"
)
// HostedAgentResolutionSource records where a HITL decision originated.
type HostedAgentResolutionSource string
const (
HostedAgentResolutionSourceUnspecified HostedAgentResolutionSource = "RESOLUTION_SOURCE_UNSPECIFIED"
HostedAgentResolutionSourceInlineKeystroke HostedAgentResolutionSource = "RESOLUTION_SOURCE_INLINE_KEYSTROKE"
HostedAgentResolutionSourceOutOfBand HostedAgentResolutionSource = "RESOLUTION_SOURCE_OUT_OF_BAND"
)
// HostedAgentRunFailureCode classifies a failed run.
type HostedAgentRunFailureCode string
const (
HostedAgentRunFailureCodeUnspecified HostedAgentRunFailureCode = "RUN_FAILURE_CODE_UNSPECIFIED"
HostedAgentRunFailureCodeModelError HostedAgentRunFailureCode = "RUN_FAILURE_CODE_MODEL_ERROR"
HostedAgentRunFailureCodeModelTimeout HostedAgentRunFailureCode = "RUN_FAILURE_CODE_MODEL_TIMEOUT"
HostedAgentRunFailureCodeToolError HostedAgentRunFailureCode = "RUN_FAILURE_CODE_TOOL_ERROR"
HostedAgentRunFailureCodeSandboxLost HostedAgentRunFailureCode = "RUN_FAILURE_CODE_SANDBOX_LOST"
HostedAgentRunFailureCodeHITLRejected HostedAgentRunFailureCode = "RUN_FAILURE_CODE_HITL_REJECTED"
HostedAgentRunFailureCodeBudgetExceeded HostedAgentRunFailureCode = "RUN_FAILURE_CODE_BUDGET_EXCEEDED"
HostedAgentRunFailureCodeInternal HostedAgentRunFailureCode = "RUN_FAILURE_CODE_INTERNAL"
)
// HostedAgentEventKind is the SSE event discriminator for session stream
// payloads. The values are the canonical SPI event type names (dot-separated)
// emitted on the wire's `type` field — NOT proto enum names. They mirror the
// spi.EventType constants owned by the hosted-agents stack.
type HostedAgentEventKind string
const (
HostedAgentEventKindUnspecified HostedAgentEventKind = ""
HostedAgentEventKindRunStarted HostedAgentEventKind = "run.started"
HostedAgentEventKindTokenChunk HostedAgentEventKind = "run.token_delta"
HostedAgentEventKindToolCallStarted HostedAgentEventKind = "run.tool_call_started"
HostedAgentEventKindToolCallCompleted HostedAgentEventKind = "run.tool_call_completed"
HostedAgentEventKindHITLRequested HostedAgentEventKind = "run.human_input_requested"
HostedAgentEventKindHITLResolved HostedAgentEventKind = "run.human_input_received"
HostedAgentEventKindRunCompleted HostedAgentEventKind = "run.completed"
HostedAgentEventKindRunFailed HostedAgentEventKind = "run.failed"
HostedAgentEventKindRunPaused HostedAgentEventKind = "run.paused"
HostedAgentEventKindRunResumed HostedAgentEventKind = "run.resumed"
HostedAgentEventKindSessionUpdated HostedAgentEventKind = "session.updated"
HostedAgentEventKindRunStateCheckpointed HostedAgentEventKind = "run.state_checkpointed"
HostedAgentEventKindRunHandoff HostedAgentEventKind = "run.handoff"
HostedAgentEventKindRunUsageRecorded HostedAgentEventKind = "run.usage_recorded"
HostedAgentEventKindRunSandboxAllocated HostedAgentEventKind = "run.sandbox_allocated"
HostedAgentEventKindRunSandboxReleased HostedAgentEventKind = "run.sandbox_released"
HostedAgentEventKindRunCostAccrued HostedAgentEventKind = "run.cost_accrued"
HostedAgentEventKindRunLog HostedAgentEventKind = "run.log"
// HostedAgentEventKindStreamState is a transport control frame, not an agent
// event: it reports the health of the SSE connection itself. Only the
// data-plane events endpoint emits it. It arrives in the same envelope as an
// event, but only SessionID, At and Payload are meaningful — decode Payload
// with HostedAgentStreamState. Renderers should skip it rather than display
// it as session activity.
HostedAgentEventKindStreamState HostedAgentEventKind = "stream.state"
)
// HostedAgentStreamState is the payload of a HostedAgentEventKindStreamState
// frame: the current health of the SSE connection.
type HostedAgentStreamState struct {
State HostedAgentStreamStateValue `json:"state"`
Cursor string `json:"cursor,omitempty"`
}
// HostedAgentStreamStateValue enumerates the stream health states.
type HostedAgentStreamStateValue string
const (
// HostedAgentStreamStateLive means events are being delivered contiguously.
HostedAgentStreamStateLive HostedAgentStreamStateValue = "live"
// HostedAgentStreamStateCatchingUp means the connection is replaying recent
// history before it joins the live tail.
HostedAgentStreamStateCatchingUp HostedAgentStreamStateValue = "catching_up"
// HostedAgentStreamStateDegraded means delivery continues with reduced
// guarantees (the server fell back to polling).
HostedAgentStreamStateDegraded HostedAgentStreamStateValue = "degraded"
// HostedAgentStreamStateSuperseded means a newer connection from the same
// device took over. The server closes this stream; the client should stop
// rather than reconnect, or the two connections will evict each other.
HostedAgentStreamStateSuperseded HostedAgentStreamStateValue = "superseded"
)
// HostedAgentSessionOriginProduct identifies the product workflow that created
// a session. Wire values match harness SessionOrigin.product.
type HostedAgentSessionOriginProduct string
const (
HostedAgentSessionOriginProductDirect HostedAgentSessionOriginProduct = "direct"
HostedAgentSessionOriginProductSimulation HostedAgentSessionOriginProduct = "simulation"
HostedAgentSessionOriginProductEvaluation HostedAgentSessionOriginProduct = "evaluation"
)
// HostedAgentSessionOriginRequest is the product-provenance claim on create.
// Omission creates a verified direct session. Simulation and evaluation require
// resource_id; direct forbids it. verified is server-assigned and must not be
// sent on create (see HostedAgentSessionOrigin).
type HostedAgentSessionOriginRequest struct {
Product HostedAgentSessionOriginProduct `json:"product"`
ResourceID string `json:"resource_id,omitempty"`
}
// HostedAgentSessionOrigin is server-returned product-workflow provenance.
// Verified is true for direct sessions and for product claims established
// through a trusted adapter.
type HostedAgentSessionOrigin struct {
Product HostedAgentSessionOriginProduct `json:"product"`
ResourceID string `json:"resource_id,omitempty"`
Verified bool `json:"verified"`
}
// HostedAgentSession is a provisioned hosted-agent sandbox session.
type HostedAgentSession struct {
SessionID string `json:"session_id"`
Name string `json:"name,omitempty"`
AgentKind HostedAgentKind `json:"agent_kind"`
Status HostedAgentSessionStatus `json:"status"`
CreatedAt Timestamp `json:"created_at"`
LastEventAt Timestamp `json:"last_event_at"`
RepoHint string `json:"repo_hint,omitempty"`
ProviderAuth map[string]HostedAgentProviderAuthState `json:"provider_auth,omitempty"`
// Origin is present for newly created sessions (including direct). Older
// sessions may omit it.
Origin *HostedAgentSessionOrigin `json:"origin,omitempty"`
// PauseReason qualifies Status when it is SESSION_STATUS_PAUSED, and is
// omitted otherwise. Unrecognized values are opaque, not errors — see
// HostedAgentSessionPauseReason.
PauseReason HostedAgentSessionPauseReason `json:"pause_reason,omitempty"`
// SandboxID is the sandbox identity for support / debugging. Informational;
// omitted until a sandbox is allocated.
SandboxID string `json:"sandbox_id,omitempty"`
// ResumeOnTopoff is the consent to auto-resume this session when a
// prepayment balance is restored. Set at create (manifest query param or
// config JSON body), toggled afterwards with UpdateSession, and returned on
// get/list so clients can confirm enrollment. Never inherited by forks.
// Omitted when false.
ResumeOnTopoff bool `json:"resume_on_topoff,omitempty"`
// OpenAISessionID is the OpenAI Agents session id (sess_…) linked to this DO
// sandbox for AGENT_KIND_OPENAI_CODEX. Used by attach to bridge to OpenAI;
// omitempty for other agent kinds.
OpenAISessionID string `json:"openai_session_id,omitempty"`
// OpenAIEnvironmentID is captured from the resolved CODEX_ENVIRONMENT_ID
// guest env value at create. Non-secret correlation metadata.
OpenAIEnvironmentID string `json:"openai_environment_id,omitempty"`
// ParentSessionID is set on forked child sessions; empty/omitted for roots.
ParentSessionID string `json:"parent_session_id,omitempty"`
// ForkID is a branch label on forked sessions; empty/omitted for roots.
ForkID string `json:"fork_id,omitempty"`
// ConfigID is the durable Environment UUID the session was created from
// (inline manifests persist an environment too, named after the session).
// Returned on create/get/list; omitted for sessions created before
// environment references were stored. Historically called Agent Config.
ConfigID string `json:"config_id,omitempty"`
// Warnings carries non-fatal create-time advisories from the server
// (manifest parse + policy fidelity). Populated on the create response
// only; omitted on get/list.
Warnings []string `json:"warnings,omitempty"`
}
// HostedAgentRun represents a single execution within a session.
type HostedAgentRun struct {
RunID string `json:"run_id"`
SessionID string `json:"session_id"`
State HostedAgentRunState `json:"state"`
StartedAt Timestamp `json:"started_at"`
EndedAt *Timestamp `json:"ended_at,omitempty"`
CumulativeCostMicros int64 `json:"cumulative_cost_micros"`
}
// HostedAgentHITLRequest is a pending human-in-the-loop approval.
type HostedAgentHITLRequest struct {
RequestID string `json:"request_id"`
SessionID string `json:"session_id"`
RunID string `json:"run_id"`
Action HostedAgentHITLActionKind `json:"action"`
Details map[string]interface{} `json:"details,omitempty"`
Workdir string `json:"workdir,omitempty"`
Deadline *Timestamp `json:"deadline,omitempty"`
}
// HostedAgentHITLDecision records a resolved HITL request.
type HostedAgentHITLDecision struct {
RequestID string `json:"request_id"`
Outcome HostedAgentHITLOutcome `json:"outcome"`
Actor string `json:"actor,omitempty"`
At Timestamp `json:"at"`
Reason string `json:"reason,omitempty"`
}
// HostedAgentEvent is one SSE payload from a session stream (see StreamSession).
//
// The server serializes the SPI canonical event envelope, whose JSON shape
// differs from this struct's field names: the discriminator is `type` (not
// `kind`), the per-kind body is `data` (not `payload`), and the timestamp is
// `timestamp` (not `at`). UnmarshalJSON maps that wire shape onto these fields,
// so callers read Kind/Payload/At directly.
type HostedAgentEvent struct {
EventID string
SessionID string
RunID string
Seq uint64
At Timestamp
Kind HostedAgentEventKind
Payload json.RawMessage
// SourceEventID is the native event id from the agent runtime before
// canonical mapping (Event.source_event_id). Empty when the runtime does
// not supply stable ids or the server does not forward it.
SourceEventID string
// SourceEventType is the native event type label from the agent runtime
// (e.g. codex's "item/agentMessage/delta"). Empty when not forwarded.
SourceEventType string
// SourceRaw is the exact native event bytes the in-sandbox adapter
// captured before canonical mapping (Event.source_raw) — for codex, one
// JSON-RPC frame as read off the app-server transport. Only present when
// the stream was opened with HostedAgentSessionStreamOptions.IncludeRaw
// and the server retained the bytes; base64 on the wire (JSON []byte).
SourceRaw []byte
}
// hostedAgentEventWire is the on-the-wire SPI canonical event envelope.
type hostedAgentEventWire struct {
EventID string `json:"event_id"`
RunID string `json:"run_id"`
SessionID string `json:"session_id"`
Timestamp Timestamp `json:"timestamp"`
Seq uint64 `json:"seq"`
SourceEventID string `json:"source_event_id,omitempty"`
SourceEventType string `json:"source_event_type,omitempty"`
SourceRaw []byte `json:"source_raw,omitempty"`
Type HostedAgentEventKind `json:"type"`
Data json.RawMessage `json:"data"`
}
// UnmarshalJSON decodes the SPI canonical event wire shape.
func (e *HostedAgentEvent) UnmarshalJSON(b []byte) error {
var w hostedAgentEventWire
if err := json.Unmarshal(b, &w); err != nil {
return err
}
e.EventID = w.EventID
e.RunID = w.RunID
e.SessionID = w.SessionID
e.Seq = w.Seq
e.At = w.Timestamp
e.Kind = w.Type
e.Payload = w.Data
e.SourceEventID = w.SourceEventID
e.SourceEventType = w.SourceEventType
e.SourceRaw = w.SourceRaw
return nil
}
// HostedAgentSessionCreateRequest is the body for POST /v2/agents/sessions.
type HostedAgentSessionCreateRequest struct {
AgentKind HostedAgentKind `json:"agent_kind"`
RepoHint string `json:"repo_hint,omitempty"`
IdleTimeoutSeconds int64 `json:"idle_timeout_seconds,omitempty"`
// Origin claims product-workflow provenance. Omit for a verified direct
// session. Simulation/evaluation require resource_id.
Origin *HostedAgentSessionOriginRequest `json:"origin,omitempty"`
}
// HostedAgentSessionFromConfigRequest creates a session from an existing
// immutable Environment (POST /v2/agents/sessions with a JSON body). Name is
// required and becomes the new session name; ConfigID must be the UUID of an
// Environment owned by the caller's team.
// Prefer HostedAgentSessionFromEnvironmentRequest; this name remains for
// compatibility. The JSON field remains "config_id" on the wire.
type HostedAgentSessionFromConfigRequest struct {
Name string `json:"name"`
ConfigID string `json:"config_id"`
// ResumeOnTopoff opts the new session in to automatic resumption when the
// team's prepayment balance is restored. Session-scoped, not
// environment-scoped: the referenced Environment never confers it, so one
// shared Environment cannot enrol every session created from it. Omitted
// when false, which leaves the server default (also false).
ResumeOnTopoff bool `json:"resume_on_topoff,omitempty"`
}
// HostedAgentSessionFromEnvironmentRequest is the advertised alias for
// HostedAgentSessionFromConfigRequest.
type HostedAgentSessionFromEnvironmentRequest = HostedAgentSessionFromConfigRequest
// HostedAgentSessionUpdateRequest is the body for PATCH
// /v2/agents/sessions/{session_id}: an allowlisted subset of session-scoped
// settings, never an agents.yaml or Agent Config mutation. The server rejects
// unknown top-level keys, and rejects an empty object, so every field is a
// pointer: nil omits it and leaves the server-side value untouched.
type HostedAgentSessionUpdateRequest struct {
// ResumeOnTopoff sets whether the session opts in to automatic resumption
// once the team's prepayment balance is restored after a low-balance pause.
// Nil leaves the current consent unchanged. Revoking takes effect
// immediately for later sweeps; granting it does not by itself resume a
// session that is already paused.
ResumeOnTopoff *bool `json:"resume_on_topoff,omitempty"`
}
// empty reports whether the request would serialize to {}, which the server
// rejects with a 400. Checked client-side so a no-op call fails locally with a
// useful message instead of spending a round-trip to earn a certain error.
func (r *HostedAgentSessionUpdateRequest) empty() bool {
return r == nil || r.ResumeOnTopoff == nil
}
// HostedAgentManifestCreateOptions configures CreateSessionFromManifest.
// OpenAISessionID is sent as the openai_session_id query parameter (not in the
// YAML body). harness-api persists it for AGENT_KIND_OPENAI_CODEX attach
// correlation. See docs/design/openai-sandbox-provider.md.
type HostedAgentManifestCreateOptions struct {
OpenAISessionID string `url:"openai_session_id,omitempty"`
// ResumeOnTopoff opts the new session in to automatic resumption when the
// team's prepayment balance is restored after a low-balance pause. It is a
// query parameter rather than an agents.yaml field because that document is
// immutable and shared through Agent Configs, while spending consent has to
// stay per-session. Omitted when false (the server default).
ResumeOnTopoff bool `url:"resume_on_topoff,omitempty"`
}
// HostedAgentSessionListOptions specifies optional list filters.
type HostedAgentSessionListOptions struct {
PageToken string `url:"page_token,omitempty"`
PageSize int `url:"page_size,omitempty"`
Status HostedAgentSessionStatus `url:"status,omitempty"`
Name string `url:"name,omitempty"`
// ParentSessionID lists child (forked) sessions of the given parent.
ParentSessionID string `url:"parent_session_id,omitempty"`
}
// HostedAgentSessionsListResponse is returned by GET /v2/agents/sessions.
type HostedAgentSessionsListResponse struct {
Sessions []HostedAgentSession `json:"sessions"`
NextPageToken string `json:"next_page_token"`
}
// HostedAgentSessionStreamOptions configures the session SSE stream.
//
// ReplayOnly selects between the two modes StreamSession can open on the events
// endpoint (see StreamSession); Before and Limit page backwards through history
// within the replay-only mode.
type HostedAgentSessionStreamOptions struct {
// ReplayFrom is the resume cursor: the id of the last event the caller
// already rendered. On the live stream it is sent as Last-Event-ID; on a
// ReplayOnly read it is sent as the replay_from query parameter.
ReplayFrom string
// ReplayOnly reads the stored event history and ends the stream at the last
// stored event instead of holding the connection open for live events.
ReplayOnly bool
// Before turns the request into a single backward page of durable
// history: the events strictly older than this event id, oldest-first,
// after which the stream closes without live events. Set it to the
// oldest event id already held. Requires ReplayOnly, since a live
// attach cannot start in the past.
//
// A cursorless replay only covers the newest window of a session's
// history (the server's replay budget), so walking backwards from its
// oldest event is how older history is read. HasMore reports whether
// the walk can continue.
Before string
// Limit caps the events in one history page. Only meaningful with
// Before. Zero leaves the server's default (200); the server also caps
// any request at its replay budget.
Limit int
// IncludeRaw asks the server to include each event's native source bytes
// (HostedAgentEvent.SourceRaw) alongside the canonical payload. Raw
// payloads meaningfully fatten every event, so this is opt-in; consumers
// that don't translate native protocols should leave it off.
IncludeRaw bool
}
// HostedAgentSendInputRequest is the body for POST .../input.
type HostedAgentSendInputRequest struct {
Text string `json:"text"`
// SourceRaw optionally carries the client's exact native protocol frame
// this input was extracted from — for codex, the TUI's turn/start
// JSON-RPC message with its full params. The in-sandbox adapter uses it
// as the template for the turn it drives, so client intent beyond plain
// text (input items, model, effort, approval policy, ...) survives the
// text reduction. Only meaningful when the caller speaks the session's
// own agent protocol; Text stays required either way. Inbound
// counterpart of HostedAgentEvent.SourceRaw. Base64 on the wire per the
// proto bytes JSON mapping — encoding/json does that for []byte.
SourceRaw []byte `json:"source_raw,omitempty"`
}
// HostedAgentSendInputResponse is returned by POST .../input.
type HostedAgentSendInputResponse struct {
RunID string `json:"run_id"`
}
// HostedAgentRelayRequest is the body for POST .../request: one native
// agent-protocol request frame, forwarded to the session's agent verbatim.
//
// Where SendInput carries the one message with a canonical meaning ("the user
// said something"), this carries everything else a client that speaks the
// session's own protocol needs to ask — for codex, the requests behind
// interrupts, slash commands, and model pickers. The control plane never
// parses the frame; only the in-sandbox adapter decides what is safe to
// forward.
type HostedAgentRelayRequest struct {
// SourceRaw is the caller's native protocol request frame — for codex, a
// single JSON-RPC request object carrying the caller's own id. Named to
// match SendInput's field: both mean "my own frame, verbatim". Base64 on
// the wire per the proto bytes JSON mapping.
SourceRaw []byte `json:"source_raw"`
}
// HostedAgentRelayResponse is the reply to POST .../request.
type HostedAgentRelayResponse struct {
// SourceRaw is the agent's reply frame, addressed to the caller's own
// request id but otherwise verbatim. A protocol-level failure (a JSON-RPC
// error object) is a normal reply and arrives here rather than as an HTTP
// error.
//
// Empty means the in-sandbox adapter declined to forward the method.
// Callers must answer their own caller on that case rather than waiting
// for something that will not come.
SourceRaw []byte `json:"source_raw,omitempty"`
}
// HostedAgentResolveHITLRequest is the body for POST .../hitl/{requestID}.
type HostedAgentResolveHITLRequest struct {
Outcome HostedAgentHITLOutcome `json:"outcome"`
Reason string `json:"reason,omitempty"`
Source HostedAgentResolutionSource `json:"source,omitempty"`
// SourceRaw is the client's reply in the agent's own protocol, forwarded
// to the in-sandbox agent untouched. It carries what Outcome cannot: an
// elicitation's content, a tool's requested input, a scope beyond this one
// call. Outcome stays required alongside it — it is what the audit trail
// records, and what the agent falls back to when this is absent.
SourceRaw []byte `json:"source_raw,omitempty"`
// Content is a structured answer for a gated request that asks for DATA
// rather than just a verdict — an MCP *form* elicitation sends a
// requestedSchema and expects an object matching it back (e.g.
// {"site_url": "https://acme.atlassian.net"} for a Jira connection). Its
// keys are the requesting server's, never fixed here. Omitted for plain
// approvals, where Outcome alone is the whole answer. Mirrors
// harness-api's resolveHITLBody.Content; forwarded to the run and never
// persisted (form content can carry user-entered secrets).
Content map[string]any `json:"content,omitempty"`
}
// HostedAgentProviderAuthStart is returned by POST /v2/agents/auth/{provider}.
// Status is "pending" when the user must still authorize in a browser
// (ConnectURL/PollURL/VerificationCode are set), or "success" when the team is
// already connected (those fields are empty). It is a free-form connect-flow
// status, distinct from the HostedAgentProviderAuthState session field. The
// authorization handle is never exposed: tokens are exchanged server-side at
// session time.
type HostedAgentProviderAuthStart struct {
Provider string `json:"provider"`
Status string `json:"status"`
ConnectURL string `json:"connect_url,omitempty"`
PollURL string `json:"poll_url,omitempty"`
VerificationCode string `json:"verification_code,omitempty"`
ExpiresAt *Timestamp `json:"expires_at,omitempty"`
}
// HostedAgentProviderAuthPoll is returned by GET
// /v2/agents/auth/{provider}/poll. It reports only whether authorization has
// completed ("pending" or "success"); no secret is returned.
type HostedAgentProviderAuthPoll struct {
Provider string `json:"provider"`
Status string `json:"status"`
ExpiresAt *Timestamp `json:"expires_at,omitempty"`
}
// HostedAgentSandboxExecRequest is the body for POST .../sandbox/exec.
type HostedAgentSandboxExecRequest struct {
Argv []string `json:"argv"`
Workdir string `json:"workdir,omitempty"`
TimeoutSeconds int64 `json:"timeout_seconds,omitempty"`
}
// HostedAgentSandboxExecResponse is returned by POST .../sandbox/exec.
type HostedAgentSandboxExecResponse struct {
ExitCode int `json:"exit_code"`
Stdout string `json:"stdout,omitempty"`
Stderr string `json:"stderr,omitempty"`
}
// HostedAgentSandboxSize is a customer-selectable sandbox (microVM) size from
// GET /v2/agents/sessions/sandbox/sizes. Submit Slug as spec.sandbox.sizeSlug
// on CreateSession; VCPUs, MemoryMB, and the price fields are for display.
type HostedAgentSandboxSize struct {
Slug string `json:"slug,omitempty"`
VCPUs int `json:"vcpus,omitempty"`
MemoryMB int `json:"memory_mb,omitempty"`
PricePerHourUSD float64 `json:"price_per_hour_usd,omitempty"`
PricePerMonthUSD float64 `json:"price_per_month_usd,omitempty"`
}
// HostedAgentSandboxSizesResponse is returned by ListSandboxSizes.
type HostedAgentSandboxSizesResponse struct {
// Sizes is ordered smallest-to-largest.
Sizes []HostedAgentSandboxSize `json:"sizes"`
}
// HostedAgentWorkspaceUploadRequest is the input for UploadWorkspace.
type HostedAgentWorkspaceUploadRequest struct {
// Path is the destination resolved inside the workspace root (/workspace). Required.
Path string
// IsArchive indicates Body is a tar archive to extract at Path.
IsArchive bool
// ContentSHA256 is an optional hex SHA-256 digest of the payload, forwarded to the guest for verification.
ContentSHA256 string
// Body is the raw file or tar bytes to upload. Required.
Body io.Reader
}
// HostedAgentWorkspaceUploadResponse is returned by UploadWorkspace.
type HostedAgentWorkspaceUploadResponse struct {
Path string `json:"path"`
BytesWritten int64 `json:"bytes_written"`
}
// HostedAgentWorkspaceDownloadRequest is the input for DownloadWorkspace.
type HostedAgentWorkspaceDownloadRequest struct {
// Path is the source resolved inside the workspace root (/workspace). Required.
Path string
// AsArchive tar-streams the directory at Path when true.
AsArchive bool
}
// HostedAgentWorkspaceDownload is the streaming result of DownloadWorkspace.
// Body strips the trailing integrity footer and verifies SHA-256 of the
// payload: read it to EOF and then Close it. A missing, invalid, or mismatched
// footer is an error. An HTTP X-Content-Sha256 trailer may still be present
// but is best-effort only; the body footer is the source of truth.
type HostedAgentWorkspaceDownload struct {
Body io.ReadCloser
// IsArchive is true when the payload is a tar stream.
IsArchive bool
// SizeBytes is the X-Workspace-Size-Bytes hint (0 when unknown); payload
// size only (excludes the integrity footer). Not a Content-Length.
SizeBytes int64
}
// HostedAgentWorkspaceTransferDirection is the direction of a staged transfer.
type HostedAgentWorkspaceTransferDirection string
const (
HostedAgentWorkspaceTransferDirectionUpload HostedAgentWorkspaceTransferDirection = "upload"
HostedAgentWorkspaceTransferDirectionDownload HostedAgentWorkspaceTransferDirection = "download"
)
// HostedAgentWorkspaceTransferStatus is the status of a staged transfer.
type HostedAgentWorkspaceTransferStatus string
const (
HostedAgentWorkspaceTransferStatusPending HostedAgentWorkspaceTransferStatus = "pending"
HostedAgentWorkspaceTransferStatusInProgress HostedAgentWorkspaceTransferStatus = "in_progress"
HostedAgentWorkspaceTransferStatusCompleted HostedAgentWorkspaceTransferStatus = "completed"
HostedAgentWorkspaceTransferStatusFailed HostedAgentWorkspaceTransferStatus = "failed"
)
// HostedAgentWorkspaceTransferCreateRequest starts a large upload or download.
// Upload uses IsArchive; download uses AsArchive (per OHS HTTP contract).
type HostedAgentWorkspaceTransferCreateRequest struct {
Direction HostedAgentWorkspaceTransferDirection `json:"direction"`
Path string `json:"path"`
IsArchive bool `json:"is_archive,omitempty"`
AsArchive bool `json:"as_archive,omitempty"`
SizeBytes int64 `json:"size_bytes,omitempty"`
SHA256 string `json:"sha256,omitempty"`
}
// HostedAgentWorkspaceTransfer is returned by create/commit/get transfer calls.
type HostedAgentWorkspaceTransfer struct {
TransferID string `json:"transfer_id"`
Direction HostedAgentWorkspaceTransferDirection `json:"direction,omitempty"`
Status HostedAgentWorkspaceTransferStatus `json:"status"`
UploadID string `json:"upload_id,omitempty"`
PartSize int64 `json:"part_size,omitempty"`
ExpiresAt *Timestamp `json:"expires_at,omitempty"`
SizeBytes int64 `json:"size_bytes,omitempty"`
BytesWritten int64 `json:"bytes_written,omitempty"`
SHA256 string `json:"sha256,omitempty"`
DownloadURL string `json:"download_url,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
}
// HostedAgentWorkspaceTransferPartUploadURLsRequest requests presigned URLs for
// one or more upload parts. PartNumbers are 1-based.
type HostedAgentWorkspaceTransferPartUploadURLsRequest struct {
PartNumbers []int `json:"part_numbers"`
}
// HostedAgentWorkspaceTransferPartUploadURL is one entry in a part-upload-urls response.
// PUT the part bytes directly to UploadURL (not through OHS).
type HostedAgentWorkspaceTransferPartUploadURL struct {
PartNumber int `json:"part_number"`
UploadURL string `json:"upload_url"`
}
// HostedAgentWorkspaceTransferPartUploadURLs is returned by CreateWorkspaceTransferPartUploadURLs.
type HostedAgentWorkspaceTransferPartUploadURLs struct {
PartURLs []HostedAgentWorkspaceTransferPartUploadURL `json:"part_urls"`
}
// HostedAgentWorkspaceTransferCommitRequest finalizes an upload after all parts are PUT.
type HostedAgentWorkspaceTransferCommitRequest struct {
SHA256 string `json:"sha256,omitempty"`
}
// HostedAgentWorkspaceTransferCancelRequest aborts an in-flight transfer.
type HostedAgentWorkspaceTransferCancelRequest struct {
Reason string `json:"reason,omitempty"`
}
// HostedAgentWorkspaceTransferCancelResponse is returned by CancelWorkspaceTransfer.
type HostedAgentWorkspaceTransferCancelResponse struct {
TransferID string `json:"transfer_id"`
Aborted bool `json:"aborted"`
Status HostedAgentWorkspaceTransferStatus `json:"status"`
}
type hostedAgentSessionRoot struct {
Session *HostedAgentSession `json:"session"`
}
// CreateSession provisions a new hosted agent session.
func (s *HostedAgentsServiceOp) CreateSession(ctx context.Context, create *HostedAgentSessionCreateRequest) (*HostedAgentSession, *Response, error) {
if create == nil {
return nil, nil, errors.New("hosted agents: create request is required")
}
if create.AgentKind == "" || create.AgentKind == HostedAgentKindUnspecified {
return nil, nil, errors.New("hosted agents: agent_kind is required")
}
req, err := s.client.NewRequest(ctx, http.MethodPost, hostedAgentsSessionsBasePath, create)
if err != nil {
return nil, nil, err
}
root := new(hostedAgentSessionRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
if root.Session == nil {
return nil, resp, errors.New("hosted agents: create session returned no session")
}
return root.Session, resp, nil
}
func (s *HostedAgentsServiceOp) CreateSessionFromManifest(ctx context.Context, manifest []byte, opt *HostedAgentManifestCreateOptions) (*HostedAgentSession, *Response, error) {
if len(bytes.TrimSpace(manifest)) == 0 {
return nil, nil, errors.New("hosted agents: manifest is required")
}
path, err := addOptions(hostedAgentsSessionsBasePath, opt)
if err != nil {
return nil, nil, err
}
req, err := s.newCreateSessionPostRequest(ctx, path, bytes.NewReader(manifest), hostedAgentManifestMediaType)
if err != nil {
return nil, nil, err
}
return s.doCreateSession(ctx, req)
}
// CreateSessionFromEnvironment provisions a session from a durable Environment.
// The JSON {name, config_id} body selects the environment-backed create path on
// the server, which reloads the Environment's stored manifest and resolves its
// declared credentials into the new session.
func (s *HostedAgentsServiceOp) CreateSessionFromEnvironment(ctx context.Context, create *HostedAgentSessionFromEnvironmentRequest) (*HostedAgentSession, *Response, error) {
return s.CreateSessionFromConfig(ctx, create)
}
// CreateSessionFromConfig provisions a session from a durable Environment.
// Prefer CreateSessionFromEnvironment; this name remains for compatibility.
// The JSON {name, config_id} body selects the environment-backed create path on
// the server, which reloads the Environment's stored manifest and resolves its
// declared credentials into the new session.
func (s *HostedAgentsServiceOp) CreateSessionFromConfig(ctx context.Context, create *HostedAgentSessionFromConfigRequest) (*HostedAgentSession, *Response, error) {
if create == nil {
return nil, nil, errors.New("hosted agents: create request is required")
}
if create.Name == "" {
return nil, nil, errors.New("hosted agents: name is required")
}
if create.ConfigID == "" {
return nil, nil, errors.New("hosted agents: config_id is required")
}
req, err := s.client.NewRequest(ctx, http.MethodPost, hostedAgentsSessionsBasePath, create)
if err != nil {
return nil, nil, err
}
return s.doCreateSession(ctx, req)
}
func (s *HostedAgentsServiceOp) doCreateSession(ctx context.Context, req *http.Request) (*HostedAgentSession, *Response, error) {
root := new(hostedAgentSessionRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
if root.Session == nil {
return nil, resp, errors.New("hosted agents: create session returned no session")
}
return root.Session, resp, nil
}
func (s *HostedAgentsServiceOp) newCreateSessionPostRequest(ctx context.Context, path string, body io.Reader, contentType string) (*http.Request, error) {
u, err := s.client.BaseURL.Parse(path)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentType)
req.Header.Set("Accept", mediaType)
req.Header.Set("User-Agent", s.client.UserAgent)
return req, nil
}
// ListSessions returns sessions visible to the caller's team.