-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathmod.rs
More file actions
1866 lines (1734 loc) · 76.8 KB
/
Copy pathmod.rs
File metadata and controls
1866 lines (1734 loc) · 76.8 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
//! Agent SDK entry points for invoking Agent-related functionality from the app.
//! For now this provides a simple runner that echoes the received command.
use std::fmt::Write;
use std::future::Future;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use ai::api_keys::{ApiKeyManager, AwsCredentialsRefreshStrategy};
use anyhow::Context;
pub(crate) use driver::harness::{task_env_vars, validate_cli_installed, ClaudeHarness};
pub use driver::AgentDriver;
use driver::AgentDriverError;
use telemetry::CliTelemetryEvent;
use tracing::Instrument as _;
use warp_cli::agent::{
AgentCommand, AgentProfileCommand, Harness, OutputFormat, Prompt, RunAgentArgs,
};
use warp_cli::api_key::ApiKeyCommand;
use warp_cli::artifact::ArtifactCommand;
use warp_cli::environment::{EnvironmentCommand, ImageCommand};
use warp_cli::federate::FederateCommand;
use warp_cli::harness_support::{HarnessSupportCommand, ReportArtifactCommand, TaskStatus};
use warp_cli::integration::IntegrationCommand;
use warp_cli::mcp::MCPCommand;
use warp_cli::memory_store::{MemoryCommand, MemoryStoreCommand};
use warp_cli::model::ModelCommand;
use warp_cli::provider::ProviderCommand;
use warp_cli::runner::RunnerCommand;
use warp_cli::schedule::ScheduleSubcommand;
use warp_cli::secret::SecretCommand;
use warp_cli::share::ShareRequest;
use warp_cli::task::{MessageCommand, TaskCommand};
use warp_cli::{CliCommand, GlobalOptions, OZ_HARNESS_ENV};
use warp_core::features::FeatureFlag;
use warp_errors::report_error;
use warp_graphql::object_permissions::OwnerType;
use warp_isolation_platform::IsolationPlatformError;
#[cfg(not(target_family = "wasm"))]
use warp_logging::log_file_path;
use warp_managed_secrets::ManagedSecretManager;
use warp_server_client::iap::{IapManager, IapManagerEvent};
use warpui::platform::TerminationMode;
use warpui::{AppContext, ModelSpawner, SingletonEntity};
use crate::ai::agent::api::convert_conversation::{
convert_conversation_data_to_ai_conversation, RestorationMode,
};
use crate::ai::agent::api::ServerConversationToken;
use crate::ai::agent::conversation::AIConversationId;
use crate::ai::agent_sdk::driver::harness::{harness_kind, HarnessKind};
use crate::ai::agent_sdk::driver::{AgentDriverOptions, AgentRunPrompt, Task};
use crate::ai::agent_sdk::mcp_config::build_mcp_servers_from_specs;
use crate::ai::agent_sdk::setup_observability::{
OzRunTimelineEvent, SetupClientEventReporter, SetupStep,
};
use crate::ai::ambient_agents::task::HarnessConfig;
use crate::ai::ambient_agents::AmbientAgentTaskId;
use crate::ai::attachment_utils::attachments_download_dir;
#[cfg(not(target_family = "wasm"))]
use crate::ai::aws_credentials::refresh_aws_credentials;
use crate::ai::cloud_environments::CloudAmbientAgentEnvironment;
use crate::ai::llms::LLMId;
use crate::ai::skills::{
clone_repo_for_skill, resolve_skill_spec, ResolveSkillError, ResolvedSkill,
};
use crate::auth::auth_manager::{AuthManager, AuthManagerEvent};
use crate::auth::AuthStateProvider;
use crate::cloud_object::model::persistence::CloudModel;
use crate::cloud_object::CloudObjectLookup as _;
use crate::send_telemetry_sync_from_app_ctx;
use crate::server::ids::{ServerId, SyncId};
use crate::server::server_api::ai::{AIClient, AgentConfigSnapshot, GitCredential};
use crate::server::server_api::ServerApiProvider;
use crate::terminal::view::ConversationRestorationInNewPaneType;
use crate::workflows::workflow::Workflow;
mod admin;
mod agent_config;
mod agent_management;
mod ambient;
mod api_key;
mod artifact;
pub(crate) mod artifact_upload;
mod common;
mod config_file;
pub(crate) mod driver;
mod environment;
mod federate;
mod harness_support;
#[cfg(not(target_family = "wasm"))]
mod integration;
#[cfg(not(target_family = "wasm"))]
mod integration_output;
mod mcp;
mod mcp_config;
mod memory_store;
mod model;
mod oauth_flow;
pub mod output;
mod profiles;
mod provider;
pub(crate) mod retry;
mod runner;
mod schedule;
mod secret;
pub(crate) mod setup_observability;
mod telemetry;
#[cfg(test)]
mod test_support;
mod text_layout;
/// Prints a non-blocking warning to stderr when the CLI is invoked with a team-scoped API key.
fn maybe_warn_team_api_key(ctx: &AppContext) {
let auth_state = AuthStateProvider::handle(ctx).as_ref(ctx).get();
let owner_type = auth_state.api_key_owner_type();
if !matches!(owner_type, Some(OwnerType::Team)) {
return;
}
eprintln!(
"\x1b[33mWarning: Free cloud credits apply to personal runs only but this run uses \
a team API key. If you want to use free cloud credits, consider using a personal API key instead.\x1b[0m"
);
}
/// Run a Warp CLI command.
#[tracing::instrument(name = "agent_sdk::run", skip_all, err, fields(tags.cloud_agent = true))]
pub fn run(
ctx: &mut AppContext,
command: CliCommand,
global_options: GlobalOptions,
) -> anyhow::Result<()> {
let event = command_to_telemetry_event(&command);
send_telemetry_sync_from_app_ctx!(event, ctx);
launch_command(ctx, command, global_options)
}
/// Dispatch a CLI command to its handler.
fn dispatch_command(
ctx: &mut AppContext,
command: CliCommand,
global_options: GlobalOptions,
) -> anyhow::Result<()> {
match command {
CliCommand::Agent(agent_cmd) => run_agent(ctx, global_options, agent_cmd),
CliCommand::Environment(environment_cmd) => {
if !FeatureFlag::CloudEnvironments.is_enabled() {
return Err(anyhow::anyhow!("invalid value 'environment'"));
}
environment::run(ctx, global_options, environment_cmd)
}
CliCommand::MCP(mcp_cmd) => mcp::run(ctx, global_options, mcp_cmd),
CliCommand::Run(task_cmd) => run_task(ctx, global_options, task_cmd),
CliCommand::Model(model_cmd) => model::run(ctx, global_options, model_cmd),
CliCommand::MemoryStore(memory_store_cmd) => {
memory_store::run(ctx, global_options, memory_store_cmd)
}
CliCommand::Memory(memory_cmd) => memory_store::run_memory(ctx, global_options, memory_cmd),
CliCommand::Login => admin::login(ctx),
CliCommand::Logout => admin::logout(ctx),
CliCommand::Whoami => admin::whoami(ctx, global_options.output_format),
CliCommand::Provider(provider_cmd) => {
if !FeatureFlag::ProviderCommand.is_enabled() {
return Err(anyhow::anyhow!("invalid value 'provider'"));
}
provider::run(ctx, global_options, provider_cmd)
}
#[cfg(not(target_family = "wasm"))]
CliCommand::Integration(integration_cmd) => {
if !FeatureFlag::IntegrationCommand.is_enabled() {
return Err(anyhow::anyhow!("invalid value 'integration'"));
}
integration::run(ctx, global_options, integration_cmd)
}
#[cfg(target_family = "wasm")]
CliCommand::Integration(_) => {
return Err(anyhow::anyhow!("invalid value 'integration'"));
}
CliCommand::Schedule(schedule_cmd) => {
if !FeatureFlag::ScheduledAmbientAgents.is_enabled() {
return Err(anyhow::anyhow!("invalid value 'schedule'"));
}
schedule::run(ctx, global_options, schedule_cmd)
}
CliCommand::Secret(secret_cmd) => {
if !FeatureFlag::WarpManagedSecrets.is_enabled() {
return Err(anyhow::anyhow!("invalid value 'secret'"));
}
secret::run(ctx, global_options, secret_cmd)
}
CliCommand::Federate(federate_cmd) => {
if !FeatureFlag::OzIdentityFederation.is_enabled() {
return Err(anyhow::anyhow!("invalid value 'federate'"));
}
federate::run(ctx, global_options, federate_cmd)
}
CliCommand::HarnessSupport(args) => {
if !FeatureFlag::AgentHarness.is_enabled() {
return Err(anyhow::anyhow!("invalid value 'harness-support'"));
}
harness_support::run(ctx, global_options, args)
}
CliCommand::Artifact(artifact_cmd) => {
if !FeatureFlag::ArtifactCommand.is_enabled() {
return Err(anyhow::anyhow!("invalid value 'artifact'"));
}
artifact::run(ctx, global_options, artifact_cmd)
}
CliCommand::ApiKey(api_key_cmd) => {
if !FeatureFlag::APIKeyManagement.is_enabled() {
return Err(anyhow::anyhow!("invalid value 'api-key'"));
}
api_key::run(ctx, global_options, api_key_cmd)
}
CliCommand::Runner(runner_cmd) => {
if !FeatureFlag::CloudAgentRunners.is_enabled() {
return Err(anyhow::anyhow!("invalid value 'runner'"));
}
runner::run(ctx, global_options, runner_cmd)
}
}
}
fn format_skill_resolution_error(err: ResolveSkillError) -> String {
match err {
ResolveSkillError::NotFound { skill } => {
format!("Skill '{skill}' not found")
}
ResolveSkillError::RepoNotFound { repo } => {
format!("Repository '{repo}' not found")
}
ResolveSkillError::Ambiguous { skill, candidates } => {
let mut msg = format!(
"Skill '{skill}' is ambiguous; specify as repo:skill_name\n\nCandidates:\n"
);
for path in candidates {
msg.push_str(&format!("- {}\n", path.display()));
}
msg
}
ResolveSkillError::OrgMismatch {
repo,
expected,
found,
} => {
format!("Repository '{repo}' found but belongs to org '{found}', expected '{expected}'")
}
ResolveSkillError::ParseFailed { path, message } => {
format!("Failed to parse skill file {}: {message}", path.display())
}
ResolveSkillError::CloneFailed { org, repo, message } => {
format!("Failed to clone repository '{org}/{repo}': {message}")
}
}
}
/// Run the agent with the provided command.
fn run_agent(
ctx: &mut AppContext,
global_options: GlobalOptions,
command: AgentCommand,
) -> anyhow::Result<()> {
match command {
AgentCommand::Run(args) => {
if args.environment.is_some() && !FeatureFlag::CloudEnvironments.is_enabled() {
return Err(anyhow::anyhow!("unexpected argument '--environment' found"));
}
if args.conversation.is_some() && !FeatureFlag::CloudConversations.is_enabled() {
return Err(anyhow::anyhow!(
"unexpected argument '--conversation' found"
));
}
if args.skill.is_some() && !FeatureFlag::OzPlatformSkills.is_enabled() {
return Err(anyhow::anyhow!("unexpected argument '--skill' found"));
}
if args.harness != Harness::Oz && !FeatureFlag::AgentHarness.is_enabled() {
return Err(anyhow::anyhow!("unexpected argument '--harness' found"));
}
if args.harness == Harness::OpenCode {
return Err(anyhow::anyhow!(
"The opencode harness is only supported for local child agent launches."
));
}
let server_api = ServerApiProvider::handle(ctx).as_ref(ctx).get_ai_client();
// Start the agent driver runner, which will handle the rest of the setup steps
// (managing both sync and async steps) as well as triggering the driver.
let runner = ctx.add_singleton_model(|_| AgentDriverRunner);
runner.update(ctx, move |_, ctx| {
let spawner = ctx.spawner();
ctx.spawn(
AgentDriverRunner::setup_and_run_driver(
spawner,
args,
server_api,
global_options.output_format,
),
|_, result, _ctx| {
if let Err(e) = result {
report_fatal_error(e.into(), _ctx);
}
},
);
});
Ok(())
}
AgentCommand::RunCloud(args) => {
if args.environment.environment.is_some()
&& !FeatureFlag::CloudEnvironments.is_enabled()
{
return Err(anyhow::anyhow!("unexpected argument '--environment' found"));
}
if args.conversation.is_some() && !FeatureFlag::CloudConversations.is_enabled() {
return Err(anyhow::anyhow!(
"unexpected argument '--conversation' found"
));
}
if args.harness != Harness::Oz && !FeatureFlag::AgentHarness.is_enabled() {
return Err(anyhow::anyhow!("unexpected argument '--harness' found"));
}
if let Err(msg) = args.validate_auth_secrets() {
return Err(anyhow::anyhow!(msg));
}
if args.runner.is_some() && !FeatureFlag::CloudRunners.is_enabled() {
return Err(anyhow::anyhow!("unexpected argument '--runner' found"));
}
ambient::run_ambient_agent(ctx, args)
}
AgentCommand::Profile(sub) => profiles::run(ctx, global_options, sub),
AgentCommand::List(args) => {
agent_management::list_agents(ctx, global_options.output_format, args)
}
AgentCommand::Get(args) => {
agent_management::get_agent(ctx, global_options.output_format, args)
}
AgentCommand::Create(args) => {
agent_management::create_agent(ctx, global_options.output_format, args)
}
AgentCommand::Update(args) => {
agent_management::update_agent(ctx, global_options.output_format, args)
}
AgentCommand::Delete(args) => {
agent_management::delete_agent(ctx, global_options.output_format, args)
}
AgentCommand::Skills(args) => agent_config::list_skills(ctx, args),
}
}
/// Build the merged agent configuration from all sources and the Task for the driver.
/// Merge precedence: file < CLI < skill
fn build_merged_config_and_task(
args: &RunAgentArgs,
resolved_skill: &Option<ResolvedSkill>,
prompt: &Option<Prompt>,
ctx: &mut AppContext,
) -> anyhow::Result<(AgentConfigSnapshot, Task)> {
// Server-side prompt resolution (task_id is set): the task config already lives on the
// server and individual CLI flags (--model, --mcp, etc.) are the only local overrides.
// No config file is involved — the worker never passes --file alongside --task-id.
if args.task_id.is_some() {
return build_server_side_task(args, resolved_skill, ctx);
}
let loaded_file = match args.config_file.file.as_deref() {
Some(path) => Some(config_file::load_config_file(path)?),
None => None,
};
let cli_mcp_servers = build_mcp_servers_from_specs(&args.all_mcp_specs())?;
// Merge precedence: file < CLI < skill
let file_merged = config_file::merge_with_precedence(loaded_file.as_ref(), Default::default());
// Runner support is gated. The `run` command has no `--runner` flag, but a
// config file can still set `runner_id`, so reject it when the flag is off.
if file_merged.runner_id.is_some() && !FeatureFlag::CloudRunners.is_enabled() {
return Err(anyhow::anyhow!(
"`runner_id` is set in the config file but runner support is not enabled"
));
}
// Skill provides base_prompt and optionally name
let (skill_name, runtime_base_prompt) = match resolved_skill {
Some(skill) => (Some(skill.name.clone()), Some(skill.instructions.clone())),
None => (None, None),
};
// When a non-Oz harness is active, --model targets the harness rather than the Oz model.
let harness_model_id = if args.harness != Harness::Oz {
args.model.model.clone()
} else {
None
};
let harness_override = (args.harness != Harness::Oz).then_some(HarnessConfig {
harness_type: args.harness,
model_id: harness_model_id,
reasoning_level: None,
});
let oz_model = if args.harness == Harness::Oz {
args.model.model.clone().or(file_merged.model_id)
} else {
None
};
let mut merged_config = AgentConfigSnapshot {
// CLI name > skill name > file name
name: args.name.clone().or(skill_name).or(file_merged.name),
environment_id: args.environment.clone().or(file_merged.environment_id),
runner_id: file_merged.runner_id,
model_id: oz_model,
// Skill base_prompt takes precedence over file base_prompt
base_prompt: runtime_base_prompt.clone().or(file_merged.base_prompt),
mcp_servers: config_file::merge_mcp_servers(file_merged.mcp_servers, cli_mcp_servers),
profile_id: args.profile.clone(),
worker_host: file_merged.worker_host,
skill_spec: file_merged.skill_spec,
computer_use_enabled: args
.computer_use
.computer_use_override()
.or(file_merged.computer_use_enabled),
harness: harness_override,
harness_auth_secrets: None,
};
let runtime_mcp_specs = match merged_config.mcp_servers.as_ref() {
Some(mcp_servers) => config_file::mcp_specs_from_mcp_servers(mcp_servers)?,
None => Vec::new(),
};
let model_override: Option<LLMId> = merged_config
.model_id
.as_deref()
.filter(|_| args.harness == Harness::Oz)
.map(|model_id| common::validate_agent_mode_base_model_id(model_id, ctx))
.transpose()?;
// Keep the task config snapshot aligned with the effective model selection.
merged_config.model_id = model_override.clone().map(|id| id.to_string());
// Combine base_prompt with user prompt locally.
let local_prompt = match (merged_config.base_prompt.as_deref(), prompt) {
(Some(base_prompt), Some(Prompt::PlainText(user_prompt))) => {
Prompt::PlainText(format!("{base_prompt}\n\n{user_prompt}"))
}
(Some(base_prompt), None) => {
// Skill-only invocation: use skill instructions as the prompt
Prompt::PlainText(base_prompt.to_string())
}
(_, Some(p)) => p.clone(),
(None, None) => {
return Err(anyhow::anyhow!(AgentDriverError::InvalidRuntimeState));
}
};
let task = Task {
prompt: AgentRunPrompt::Local(resolve_prompt(&local_prompt, ctx)?),
model: model_override,
profile: args.profile.clone(),
mcp_specs: runtime_mcp_specs,
harness: harness_kind(args.harness)?,
};
Ok((merged_config, task))
}
/// Build the task for server-side prompt resolution (task_id is set).
/// Only CLI args contribute — no config file merge needed.
fn build_server_side_task(
args: &RunAgentArgs,
resolved_skill: &Option<ResolvedSkill>,
ctx: &mut AppContext,
) -> anyhow::Result<(AgentConfigSnapshot, Task)> {
let cli_mcp_servers = build_mcp_servers_from_specs(&args.all_mcp_specs())?;
let runtime_mcp_specs = match cli_mcp_servers.as_ref() {
Some(mcp_servers) => config_file::mcp_specs_from_mcp_servers(mcp_servers)?,
None => Vec::new(),
};
let harness_model_id = if args.harness != Harness::Oz {
args.model.model.clone()
} else {
None
};
let model_override: Option<LLMId> = if args.harness == Harness::Oz {
args.model
.model
.as_deref()
.map(|model_id| common::validate_agent_mode_base_model_id(model_id, ctx))
.transpose()?
} else {
None
};
let harness_override = (args.harness != Harness::Oz).then_some(HarnessConfig {
harness_type: args.harness,
model_id: harness_model_id,
reasoning_level: None,
});
let skill_name = resolved_skill.as_ref().map(|s| s.name.clone());
let model_id_string = model_override.as_ref().map(|id| id.to_string());
let profile = args.profile.clone();
let environment = args.environment.clone();
let config = AgentConfigSnapshot {
name: args.name.clone().or(skill_name),
environment_id: environment.clone(),
runner_id: None,
model_id: model_id_string,
base_prompt: None,
mcp_servers: cli_mcp_servers,
profile_id: profile.clone(),
worker_host: None,
skill_spec: None,
computer_use_enabled: args.computer_use.computer_use_override(),
harness: harness_override,
harness_auth_secrets: None,
};
let skill = resolved_skill.as_ref().map(|s| s.parsed_skill.clone());
let task = Task {
prompt: AgentRunPrompt::ServerSide {
skill,
attachments_dir: None,
},
model: model_override,
profile,
mcp_specs: runtime_mcp_specs,
harness: harness_kind(args.harness)?,
};
Ok((config, task))
}
fn reconcile_task_harness(
task_id: &str,
selected_harness: &mut Harness,
task_harness: Harness,
) -> Result<HarnessKind, AgentDriverError> {
if *selected_harness == Harness::Oz {
*selected_harness = task_harness;
} else if task_harness != *selected_harness {
return Err(AgentDriverError::TaskHarnessMismatch {
task_id: task_id.to_string(),
expected: task_harness.to_string(),
got: selected_harness.to_string(),
});
}
harness_kind(*selected_harness)
}
/// Resolve a `Prompt` to a plain string.
fn resolve_prompt(prompt: &Prompt, ctx: &AppContext) -> Result<String, AgentDriverError> {
match prompt {
Prompt::PlainText(prompt_str) => Ok(prompt_str.to_string()),
Prompt::SavedPrompt(workflow_id) => {
let Some(workflow) = CloudModel::as_ref(ctx).get_workflow_by_uid(workflow_id) else {
return Err(AgentDriverError::AIWorkflowNotFound(workflow_id.to_owned()));
};
let Workflow::AgentMode { query, .. } = &workflow.model().data else {
return Err(AgentDriverError::AIWorkflowNotFound(workflow_id.to_owned()));
};
Ok(query.to_owned())
}
}
}
/// Run the task with the provided command.
fn run_task(
ctx: &mut AppContext,
global_options: GlobalOptions,
command: TaskCommand,
) -> anyhow::Result<()> {
match command {
TaskCommand::List(args) => ambient::list_ambient_agent_tasks(ctx, global_options, args),
TaskCommand::Get(args) => {
if args.conversation {
if !FeatureFlag::ConversationApi.is_enabled() {
return Err(anyhow::anyhow!(
"The --conversation flag is not available in this build"
));
}
ambient::get_run_conversation(ctx, args.task_id)
} else {
ambient::get_ambient_agent_task_status(ctx, global_options, args)
}
}
TaskCommand::Conversation(conv_cmd) => {
if !FeatureFlag::ConversationApi.is_enabled() {
return Err(anyhow::anyhow!(
"The 'conversation' subcommand is not available in this build"
));
}
match conv_cmd {
warp_cli::task::ConversationCommand::Get(args) => {
ambient::get_conversation(ctx, args.conversation_id)
}
}
}
TaskCommand::Message(message_cmd) => ambient::run_message(ctx, global_options, message_cmd),
}
}
/// Singleton model that provides a ModelContext for spawning async operations
/// when starting the agent driver. This is needed because conversation fetching
/// requires spawning an async task, which requires a ModelContext.
struct AgentDriverRunner;
impl warpui::Entity for AgentDriverRunner {
type Event = ();
}
impl warpui::SingletonEntity for AgentDriverRunner {}
impl AgentDriverRunner {
#[tracing::instrument(skip_all, err, fields(
tags.cloud_agent = true,
args.sandboxed = args.sandboxed,
args.computer_use = args.computer_use.computer_use,
args.no_computer_use = args.computer_use.no_computer_use
))]
async fn setup_and_run_driver(
foreground: ModelSpawner<Self>,
args: RunAgentArgs,
server_api: Arc<dyn AIClient>,
output_format: OutputFormat,
) -> Result<(), AgentDriverError> {
// Extract the task ID as early as possible for best-effort setup observability.
// Local CLI-created runs may not have a task yet, so those setup events explicitly no-op.
let mut task_id: Option<AmbientAgentTaskId> =
args.task_id.as_deref().and_then(|s| s.parse().ok());
Self::set_ambient_agent_task_id(&foreground, task_id).await?;
let background = foreground.spawn(|_, ctx| ctx.background_executor()).await?;
let setup_events = match task_id {
Some(task_id) => SetupClientEventReporter::new(task_id, server_api.clone(), background),
None => SetupClientEventReporter::noop(server_api.clone(), background),
};
setup_events
.post_timeline_event(OzRunTimelineEvent::WorkerContainerReady)
.await;
// Ensure we've synced team state before starting the driver.
setup_events
.record_result(
SetupStep::TeamMetadataRefresh,
Self::refresh_team_metadata(&foreground),
)
.await?;
// Wait for Warp Drive to sync before building the task config, since
// prompt resolution (SavedPrompt -> workflow lookup) and environment
// resolution (CloudAmbientAgentEnvironment lookup) depend on it.
setup_events
.record_result(SetupStep::WarpDriveSync, async {
if foreground
.spawn(|_, ctx| common::refresh_warp_drive(ctx))
.await?
.await
.is_err()
{
return Err(AgentDriverError::WarpDriveSyncFailed);
}
Ok(())
})
.await?;
// Set up and run the driver, reporting any errors back to the server.
let result: Result<(), AgentDriverError> = async {
// Pull relevant variables out of args before moving it into the closure.
let share_requests = args.share.share.clone();
let bedrock_inference_role = args.bedrock_inference_role.clone();
let bedrock_role_region = args.bedrock_role_region.clone();
let has_task_id = args.task_id.is_some();
let args_harness = args.harness;
// `--conversation` path (user-invoked local resume): validate before any task side
// effects so mismatches fail fast. The `--task-id` path derives its conversation id
// from the server-side task metadata inside `build_driver_options_and_task`. Both
// can currently be passed together (the worker server-side appends `--conversation`
// alongside `--task-id` for Slack/Linear followups); when both are set, the explicit
// `--conversation` value wins via the merge below.
if !has_task_id {
if let Some(conversation_id) = args.conversation.as_deref() {
common::fetch_and_validate_conversation_harness(
server_api.clone(),
conversation_id,
args_harness,
)
.await?;
}
}
let resume_conversation_id = args.conversation.clone();
// Build driver options and task, handling task creation or existing task setup.
// For the `--task-id` path, `task_conversation_id` is the `conversation_id` read off
// the fetched `AmbientAgentTask` (set by the server when linking the task to an
// existing conversation, e.g. via `run-cloud --conversation`).
let (mut driver_options, task, task_conversation_id) =
Self::build_driver_options_and_task(&foreground, args, &server_api, &setup_events)
.await?;
// Update the effective task ID so errors are reported correctly.
// This only matters if we created a task ID locally.
task_id = driver_options.task_id.or(task_id);
// The `--task-id` branch already validated `args_harness` against the task's harness
// setting inside `build_driver_options_and_task`; the conversation that the task spawned
// necessarily uses the same harness, so no extra conversation-metadata roundtrip is
// needed here. Just merge the task's linked conversation id into the resume target.
let resume_conversation_id = resume_conversation_id.or(task_conversation_id);
let bedrock_task_id = driver_options.task_id.map(|id| id.to_string());
#[cfg(not(target_family = "wasm"))]
if let Some(role_arn) = bedrock_inference_role {
// clap's `requires` constraint enforces this at parse time, so a missing
// region here means a caller is constructing `RunAgentArgs` directly
// without the flag. Fail loudly so callers don't silently fall back to a
// hard-coded STS region.
let role_region = bedrock_role_region.ok_or_else(|| {
AgentDriverError::AwsBedrockCredentialsFailed(
"--bedrock-role-region is required when --bedrock-inference-role is set"
.to_string(),
)
})?;
// Set the OIDC strategy on the UI thread and kick off the refresh; the
// returned future resolves when credentials are committed to the model.
let refresh_future = foreground
.spawn(move |_, ctx| {
ApiKeyManager::handle(ctx).update(ctx, |manager, ctx| {
// From here on, refresh credentials via OIDC federation only.
manager.set_aws_credentials_refresh_strategy(
AwsCredentialsRefreshStrategy::OidcManaged {
task_id: bedrock_task_id,
role_arn,
region: role_region,
},
);
refresh_aws_credentials(manager, ctx)
})
})
.await?;
refresh_future
.await
.map_err(AgentDriverError::AwsBedrockCredentialsFailed)?;
}
match &task.harness {
HarnessKind::Unsupported(harness) => {
return Err(AgentDriverError::HarnessSetupFailed {
harness: harness.to_string(),
reason: format!(
"The {harness} harness is only supported for local child agent launches."
),
});
}
HarnessKind::Oz | HarnessKind::ThirdParty(_) => {}
}
// Validate that the third-party harness is installed and authed.
if let HarnessKind::ThirdParty(harness) = &task.harness {
harness.validate()?;
}
if let Some(task_id) = driver_options.task_id {
driver::write_run_started(&task_id.to_string(), output_format);
}
// Pull conversation information, if we have it
if let Some(conversation_id) = resume_conversation_id {
driver_options.resume = setup_events
.record_result(
SetupStep::ConversationResumeLoading,
Self::load_conversation_information(
&foreground,
conversation_id,
&task.harness,
),
)
.await?;
}
// Run the driver
foreground
.spawn(move |_, ctx| {
Self::create_and_run_driver(
ctx,
driver_options,
output_format,
share_requests,
task,
);
})
.await?;
Ok(())
}
.await;
if let Err(ref err) = result {
if let Some(task_id) = task_id {
driver::report_driver_error(task_id, err, &server_api).await;
}
}
result
}
async fn refresh_team_metadata(
foreground: &ModelSpawner<Self>,
) -> Result<(), AgentDriverError> {
foreground
.spawn(
|_, ctx| -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> {
Box::pin(common::refresh_workspace_metadata(ctx))
},
)
.await?
.await
.map_err(|_| AgentDriverError::TeamMetadataRefreshTimeout)
}
async fn set_ambient_agent_task_id(
foreground: &ModelSpawner<Self>,
task_id: Option<AmbientAgentTaskId>,
) -> Result<(), AgentDriverError> {
foreground
.spawn(move |_, ctx| {
ServerApiProvider::handle(ctx)
.as_ref(ctx)
.get()
.set_ambient_agent_task_id(task_id);
})
.await?;
Ok(())
}
async fn fetch_task_git_credentials(
task_id_str: String,
ai_client: Arc<dyn AIClient>,
) -> anyhow::Result<Vec<GitCredential>> {
let workload_token = warp_isolation_platform::issue_workload_token(Some(
std::time::Duration::from_secs(5 * 60),
))
.await?
.token;
ai_client
.get_task_git_credentials(task_id_str, workload_token)
.await
}
async fn bootstrap_git_credentials_for_task(
foreground: &ModelSpawner<Self>,
task_id_str: &str,
args: &RunAgentArgs,
) -> Result<(), AgentDriverError> {
if warp_isolation_platform::detect().is_none() && args.configure_git_credentials_with_github
{
foreground
.spawn(|_, _| {
command::blocking::Command::new("gh")
.args(["auth", "setup-git"])
.spawn()
.map_err(|err| {
AgentDriverError::ConfigBuildFailed(anyhow::anyhow!(
"gh auth setup-git failed: {err:?}"
))
})
})
.await?
.map(|_| ())?;
return Ok(());
}
if !FeatureFlag::GitCredentialRefresh.is_enabled() {
return Ok(());
}
if task_id_str.parse::<AmbientAgentTaskId>().is_err() {
log::debug!(
"Skipping git credentials bootstrap: could not parse task ID '{task_id_str}'"
);
return Ok(());
}
let (ai_client, task_id_str) = foreground
.spawn({
let task_id_str = task_id_str.to_string();
move |_, ctx| {
let ai_client = ServerApiProvider::handle(ctx)
.as_ref(ctx)
.get_ai_client()
.clone();
(ai_client, task_id_str)
}
})
.await?;
let credentials = match Self::fetch_task_git_credentials(task_id_str, ai_client).await {
Ok(credentials) => credentials,
Err(err)
if err
.downcast_ref::<IsolationPlatformError>()
.is_some_and(|err| {
matches!(err, IsolationPlatformError::NoIsolationPlatformDetected)
}) =>
{
log::debug!("Skipping git credentials bootstrap: {err}");
return Ok(());
}
Err(err) => {
return Err(AgentDriverError::SkillResolutionFailed(format!(
"Failed to fetch git credentials before skill resolution: {err:#}"
)));
}
};
if credentials.is_empty() {
log::debug!("No git credentials returned before skill resolution");
return Ok(());
}
driver::git_credentials::configure_git_credentials(&credentials).map_err(|err| {
AgentDriverError::SkillResolutionFailed(format!(
"Failed to write git credentials before skill resolution: {err:#}"
))
})?;
log::info!("Git credentials configured before task setup");
Ok(())
}
/// Resolve the skill spec from args, if one was provided.
///
/// In sandboxed mode with a fully-qualified spec (org + repo), the repo is
/// cloned first since it may not exist locally. Otherwise we resolve directly
/// against the local filesystem.
async fn resolve_skill(
foreground: &ModelSpawner<Self>,
args: &RunAgentArgs,
working_dir: &Path,
setup_events: &SetupClientEventReporter,
) -> Result<Option<ResolvedSkill>, AgentDriverError> {
if !FeatureFlag::OzPlatformSkills.is_enabled() {
return Ok(None);
}
let Some(skill_spec) = args.skill.clone() else {
return Ok(None);
};
// In sandboxed mode with a fully-qualified spec, clone the repo first.
let needs_clone = args.sandboxed && skill_spec.org.is_some() && skill_spec.repo.is_some();
if needs_clone {
let org = skill_spec.org.as_ref().expect("org checked above");
let repo_name = skill_spec.repo.as_ref().expect("repo checked above");
log::info!("Cloning {org}/{repo_name} for skill resolution in sandboxed mode");
setup_events
.record_result(SetupStep::SkillRepoClone, async {
clone_repo_for_skill(org, repo_name, working_dir)
.await
.map_err(|err| {
AgentDriverError::SkillResolutionFailed(format_skill_resolution_error(
err,
))
})
})
.await?;
}
let working_dir_buf = working_dir.to_path_buf();
let skill = foreground
.spawn(move |_, ctx| resolve_skill_spec(&skill_spec, &working_dir_buf, ctx))
.await?
.map_err(|err| {
AgentDriverError::SkillResolutionFailed(format_skill_resolution_error(err))
})?;
log::debug!(
"Resolved skill '{}' from {}",
skill.name,
skill.skill_path.display()
);
Ok(Some(skill))
}
/// Build the AgentDriverOptions and Task, handling task creation or existing task setup.
///
/// The third tuple element is the conversation id read off the server-side task metadata
/// on the `--task-id` branch. It's `None` when no task id was passed or when the task is
/// not linked to a conversation; callers use it to drive `--task-id`-implied resume
/// without requiring the caller to also pass `--conversation`.
async fn build_driver_options_and_task(
foreground: &ModelSpawner<Self>,
args: RunAgentArgs,