Repository navigation
Expand file tree
/
Copy pathoperations.rs
More file actions
2089 lines (2032 loc) · 84.1 KB
/
Copy pathoperations.rs
File metadata and controls
2089 lines (2032 loc) · 84.1 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
impl Database {
pub(crate) fn ensure_agent_task_schema(conn: &mut Connection) -> anyhow::Result<()> {
conn.execute_batch(
"
CREATE TABLE IF NOT EXISTS wc_agent_tasks (
task_id TEXT PRIMARY KEY,
owner_principal_kind TEXT NOT NULL,
owner_principal_digest TEXT NOT NULL,
assignee_agent_id TEXT,
title TEXT NOT NULL,
instruction TEXT NOT NULL,
source_conversation_id TEXT,
source_message_id TEXT,
referenced_project_id TEXT,
state TEXT NOT NULL CHECK(state IN ('ready', 'active', 'succeeded', 'failed')),
latest_attempt_id TEXT,
terminal_attempt_id TEXT,
created_at_unix_ms INTEGER NOT NULL,
updated_at_unix_ms INTEGER NOT NULL,
terminal_at_unix_ms INTEGER,
CHECK(
(state IN ('ready', 'active') AND terminal_attempt_id IS NULL AND terminal_at_unix_ms IS NULL)
OR (state IN ('succeeded', 'failed') AND terminal_attempt_id IS NOT NULL AND terminal_at_unix_ms IS NOT NULL)
),
FOREIGN KEY(assignee_agent_id) REFERENCES wc_agent_identities(agent_id),
FOREIGN KEY(source_conversation_id) REFERENCES wc_conversations(conversation_id),
FOREIGN KEY(source_message_id) REFERENCES wc_conversation_messages(message_id)
);
CREATE INDEX IF NOT EXISTS idx_wc_agent_tasks_owner_updated
ON wc_agent_tasks(owner_principal_digest, updated_at_unix_ms DESC, task_id);
CREATE INDEX IF NOT EXISTS idx_wc_agent_tasks_assignee
ON wc_agent_tasks(owner_principal_digest, assignee_agent_id, updated_at_unix_ms DESC);
CREATE TABLE IF NOT EXISTS wc_agent_task_attempts (
attempt_id TEXT PRIMARY KEY,
task_id TEXT NOT NULL,
attempt_number INTEGER NOT NULL CHECK(attempt_number >= 1),
assignee_agent_id TEXT NOT NULL,
state TEXT NOT NULL CHECK(state IN ('active', 'expired', 'succeeded', 'failed')),
lease_expires_at_unix_ms INTEGER NOT NULL,
attempt_fence TEXT NOT NULL UNIQUE,
attempt_controller_generation INTEGER NOT NULL CHECK(attempt_controller_generation >= 1),
created_at_unix_ms INTEGER NOT NULL,
started_at_unix_ms INTEGER NOT NULL,
terminal_at_unix_ms INTEGER,
terminal_result TEXT,
terminal_reason TEXT,
CHECK(
(state = 'active' AND terminal_at_unix_ms IS NULL)
OR (state != 'active' AND terminal_at_unix_ms IS NOT NULL)
),
UNIQUE(task_id, attempt_number),
FOREIGN KEY(task_id) REFERENCES wc_agent_tasks(task_id),
FOREIGN KEY(assignee_agent_id) REFERENCES wc_agent_identities(agent_id)
);
CREATE TABLE IF NOT EXISTS wc_agent_task_coding_runs (
task_id TEXT NOT NULL,
attempt_id TEXT NOT NULL UNIQUE,
run_id TEXT NOT NULL UNIQUE,
runtime_project_id TEXT NOT NULL,
provider_id TEXT NOT NULL,
provider_instance_id TEXT NOT NULL,
authority_fingerprint TEXT NOT NULL,
coding_agent_intent_fingerprint TEXT NOT NULL,
binding_intent_fingerprint TEXT NOT NULL,
dispatch_state TEXT NOT NULL CHECK(dispatch_state IN ('prepared', 'not_started', 'outcome_unknown', 'bound', 'terminal')),
last_observed_run_state TEXT,
last_observed_execution_state TEXT,
last_observation_revision INTEGER,
terminal_stop_reason TEXT,
terminal_error_code TEXT,
terminal_message TEXT,
completed_at_unix INTEGER,
created_at_unix_ms INTEGER NOT NULL,
updated_at_unix_ms INTEGER NOT NULL,
terminal_at_unix_ms INTEGER,
FOREIGN KEY(task_id) REFERENCES wc_agent_tasks(task_id),
FOREIGN KEY(attempt_id) REFERENCES wc_agent_task_attempts(attempt_id)
);
CREATE INDEX IF NOT EXISTS idx_wc_agent_task_coding_runs_task
ON wc_agent_task_coding_runs(task_id, updated_at_unix_ms DESC);
CREATE TABLE IF NOT EXISTS wc_agent_task_endpoint_executions (
task_id TEXT NOT NULL,
attempt_id TEXT NOT NULL UNIQUE,
wake_id TEXT NOT NULL UNIQUE,
start_identity_fingerprint TEXT NOT NULL CHECK(length(start_identity_fingerprint) = 64),
endpoint_id TEXT,
endpoint_controller_generation INTEGER,
created_at_unix_ms INTEGER NOT NULL,
updated_at_unix_ms INTEGER NOT NULL,
PRIMARY KEY(task_id, attempt_id),
CHECK(
(endpoint_id IS NULL AND endpoint_controller_generation IS NULL)
OR (endpoint_id IS NOT NULL AND endpoint_controller_generation >= 1)
),
FOREIGN KEY(task_id) REFERENCES wc_agent_tasks(task_id),
FOREIGN KEY(attempt_id) REFERENCES wc_agent_task_attempts(attempt_id),
FOREIGN KEY(wake_id) REFERENCES wc_agent_wakes(wake_id),
FOREIGN KEY(endpoint_id) REFERENCES wc_agent_endpoints(endpoint_id)
);
CREATE INDEX IF NOT EXISTS idx_wc_agent_task_endpoint_executions_task
ON wc_agent_task_endpoint_executions(task_id, updated_at_unix_ms DESC);
CREATE UNIQUE INDEX IF NOT EXISTS idx_wc_agent_task_attempts_one_active
ON wc_agent_task_attempts(task_id) WHERE state = 'active';
CREATE INDEX IF NOT EXISTS idx_wc_agent_task_attempts_task_number
ON wc_agent_task_attempts(task_id, attempt_number DESC);
CREATE INDEX IF NOT EXISTS idx_wc_agent_task_attempts_assignee
ON wc_agent_task_attempts(assignee_agent_id, state, lease_expires_at_unix_ms);
-- Model-facing selector only. Rows are immutable: a newer Attempt,
-- assignee, fence, or controller generation inserts a new index and
-- never rewrites an older one. The stored fence is the same proof
-- start already issued; this row is not authority.
CREATE TABLE IF NOT EXISTS wc_agent_task_attempt_references (
principal_kind TEXT NOT NULL,
principal_digest TEXT NOT NULL,
ref_index INTEGER NOT NULL CHECK(ref_index >= 1),
task_id TEXT NOT NULL,
attempt_id TEXT NOT NULL,
assignee_agent_id TEXT NOT NULL,
attempt_fence TEXT NOT NULL,
attempt_controller_generation INTEGER NOT NULL CHECK(attempt_controller_generation >= 1),
created_at_unix_ms INTEGER NOT NULL,
PRIMARY KEY(principal_kind, principal_digest, ref_index),
UNIQUE(
principal_kind, principal_digest, task_id, attempt_id, assignee_agent_id,
attempt_fence, attempt_controller_generation
)
);
",
)?;
Ok(())
}
pub(crate) fn ensure_agent_task_endpoint_pin_schema(
conn: &mut Connection,
) -> anyhow::Result<()> {
let has_pin: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM pragma_table_info('wc_agent_task_endpoint_executions') WHERE name = 'pinned_endpoint_id')",
[],
|row| row.get(0),
)?;
if !has_pin {
conn.execute_batch(
"BEGIN IMMEDIATE;
ALTER TABLE wc_agent_task_endpoint_executions
ADD COLUMN pinned_endpoint_id TEXT REFERENCES wc_agent_endpoints(endpoint_id);
ALTER TABLE wc_agent_task_endpoint_executions
ADD COLUMN pinned_endpoint_controller_generation INTEGER CHECK(
(pinned_endpoint_id IS NULL AND pinned_endpoint_controller_generation IS NULL)
OR (pinned_endpoint_id IS NOT NULL AND pinned_endpoint_controller_generation IS NOT NULL
AND pinned_endpoint_controller_generation >= 1));
COMMIT;",
)?;
}
Ok(())
}
pub fn create_agent_task(
&self,
principal: &CommunicationPrincipal,
input: NewAgentTask,
) -> Result<AgentTaskMutation, CommunicationStoreError> {
self.create_agent_task_at(principal, input, now_unix_ms())
}
pub(crate) fn create_agent_task_at(
&self,
principal: &CommunicationPrincipal,
input: NewAgentTask,
now: i64,
) -> Result<AgentTaskMutation, CommunicationStoreError> {
validate_communication_principal(principal)?;
let title = validate_title(&input.title)?;
let instruction = validate_instruction(&input.instruction)?;
let assignee_agent_id = validate_optional_id(
input.assignee_agent_id.as_deref(),
DURABLE_AGENT_ID_PREFIX,
"invalid_agent_id",
)?;
let source_conversation_id = validate_optional_id(
input.source_conversation_id.as_deref(),
CONVERSATION_ID_PREFIX,
"invalid_conversation_id",
)?;
let source_message_id = validate_optional_id(
input.source_message_id.as_deref(),
CONVERSATION_MESSAGE_ID_PREFIX,
"invalid_message_id",
)?;
if source_message_id.is_some() && source_conversation_id.is_none() {
return Err(CommunicationStoreError::new(
"agent_task_source_invalid",
"source_message_id requires source_conversation_id",
));
}
let referenced_project_id =
validate_project_reference(input.referenced_project_id.as_deref())?;
let idempotency_key = validate_idempotency_key(&input.idempotency_key)?;
let request_hash = task_request_hash(&json!({
"title": title,
"instruction": instruction,
"assignee_agent_id": assignee_agent_id,
"source_conversation_id": source_conversation_id,
"source_message_id": source_message_id,
"referenced_project_id": referenced_project_id,
}));
let mut conn = self.lock_connection(crate::StoreDomain::AgentTask);
let transaction = conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(store_error)?;
if let Some(task_id) = lookup_idempotent_resource(
&transaction,
principal,
OP_CREATE_AGENT_TASK,
&idempotency_key,
&request_hash,
)? {
let task = load_owned_task(&transaction, principal, &task_id, now)?;
transaction.commit().map_err(store_error)?;
return Ok(AgentTaskMutation {
task: task.detail(now),
created: false,
replayed: true,
state_changed: false,
});
}
if let Some(agent_id) = assignee_agent_id.as_deref() {
require_owned_agent(&transaction, principal, agent_id)?;
}
validate_source_references(
&transaction,
principal,
source_conversation_id.as_deref(),
source_message_id.as_deref(),
)?;
let task_id = allocate_identity(
&transaction,
AGENT_TASK_ID_PREFIX,
"SELECT EXISTS(SELECT 1 FROM wc_agent_tasks WHERE task_id = ?1)",
)?;
transaction
.execute(
"INSERT INTO wc_agent_tasks (
task_id, owner_principal_kind, owner_principal_digest,
assignee_agent_id, title, instruction, source_conversation_id,
source_message_id, referenced_project_id, state, latest_attempt_id,
terminal_attempt_id, created_at_unix_ms, updated_at_unix_ms,
terminal_at_unix_ms
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 'ready', NULL, NULL, ?10, ?10, NULL)",
params![
task_id,
principal.kind,
principal.digest,
assignee_agent_id,
title,
instruction,
source_conversation_id,
source_message_id,
referenced_project_id,
now,
],
)
.map_err(store_error)?;
record_idempotent_resource(
&transaction,
principal,
OP_CREATE_AGENT_TASK,
&idempotency_key,
&request_hash,
&task_id,
now,
)?;
let task = load_owned_task(&transaction, principal, &task_id, now)?;
transaction.commit().map_err(store_error)?;
Ok(AgentTaskMutation {
task: task.detail(now),
created: true,
replayed: false,
state_changed: true,
})
}
pub fn list_agent_tasks(
&self,
principal: &CommunicationPrincipal,
assignee_agent_id: Option<&str>,
offset: usize,
limit: usize,
) -> Result<AgentTaskPage, CommunicationStoreError> {
validate_communication_principal(principal)?;
let assignee_agent_id = validate_optional_id(
assignee_agent_id,
DURABLE_AGENT_ID_PREFIX,
"invalid_agent_id",
)?;
if limit == 0 || limit > MAX_AGENT_TASK_LIST_LIMIT {
return Err(CommunicationStoreError::new(
"invalid_agent_task_list_limit",
format!("limit must be 1..={MAX_AGENT_TASK_LIST_LIMIT}"),
));
}
let now = now_unix_ms();
let conn = self.lock_connection(crate::StoreDomain::AgentTask);
let (total_count, task_ids) = if let Some(agent_id) = assignee_agent_id.as_deref() {
let total_count = conn
.query_row(
"SELECT COUNT(*) FROM wc_agent_tasks
WHERE owner_principal_kind = ?1 AND owner_principal_digest = ?2
AND assignee_agent_id = ?3",
params![principal.kind, principal.digest, agent_id],
|row| row.get::<_, i64>(0),
)
.map_err(store_error)?;
let mut statement = conn
.prepare(
"SELECT task_id FROM wc_agent_tasks
WHERE owner_principal_kind = ?1 AND owner_principal_digest = ?2
AND assignee_agent_id = ?3
ORDER BY updated_at_unix_ms DESC, task_id
LIMIT ?4 OFFSET ?5",
)
.map_err(store_error)?;
let ids = statement
.query_map(
params![
principal.kind,
principal.digest,
agent_id,
limit as i64,
offset as i64
],
|row| row.get::<_, String>(0),
)
.map_err(store_error)?
.collect::<Result<Vec<_>, _>>()
.map_err(store_error)?;
(total_count, ids)
} else {
let total_count = conn
.query_row(
"SELECT COUNT(*) FROM wc_agent_tasks
WHERE owner_principal_kind = ?1 AND owner_principal_digest = ?2",
params![principal.kind, principal.digest],
|row| row.get::<_, i64>(0),
)
.map_err(store_error)?;
let mut statement = conn
.prepare(
"SELECT task_id FROM wc_agent_tasks
WHERE owner_principal_kind = ?1 AND owner_principal_digest = ?2
ORDER BY updated_at_unix_ms DESC, task_id
LIMIT ?3 OFFSET ?4",
)
.map_err(store_error)?;
let ids = statement
.query_map(
params![
principal.kind,
principal.digest,
limit as i64,
offset as i64
],
|row| row.get::<_, String>(0),
)
.map_err(store_error)?
.collect::<Result<Vec<_>, _>>()
.map_err(store_error)?;
(total_count, ids)
};
let tasks = task_ids
.iter()
.map(|task_id| {
load_owned_task(&conn, principal, task_id, now).map(|task| task.summary(now))
})
.collect::<Result<Vec<_>, _>>()?;
let next_offset = if offset.saturating_add(tasks.len()) < total_count as usize {
Some(offset.saturating_add(tasks.len()))
} else {
None
};
Ok(AgentTaskPage {
total_count,
offset,
next_offset,
truncated: next_offset.is_some(),
tasks,
})
}
pub fn read_agent_task(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
) -> Result<AgentTaskDetail, CommunicationStoreError> {
self.read_agent_task_at(principal, task_id, now_unix_ms())
}
/// The current Attempt pin when that Attempt is the task assignee's live lease.
/// Expired, terminal, or assignee-mismatched Attempts return `None` and never
/// publish the fence on a Task summary.
pub fn live_agent_task_attempt_pin(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
) -> Result<Option<LiveAgentTaskAttemptPin>, CommunicationStoreError> {
self.live_agent_task_attempt_pin_at(principal, task_id, now_unix_ms())
}
pub(crate) fn live_agent_task_attempt_pin_at(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
now: i64,
) -> Result<Option<LiveAgentTaskAttemptPin>, CommunicationStoreError> {
validate_communication_principal(principal)?;
validate_id(task_id, AGENT_TASK_ID_PREFIX, "invalid_agent_task_id")?;
let conn = self.lock_connection(crate::StoreDomain::AgentTask);
let task = load_owned_task(&conn, principal, task_id, now)?;
let Some(attempt) = task.latest_attempt.as_ref() else {
return Ok(None);
};
if attempt.effective_state(now) != AgentTaskAttemptState::Active
|| task.assignee_agent_id.as_deref() != Some(attempt.assignee_agent_id.as_str())
{
return Ok(None);
}
Ok(Some(LiveAgentTaskAttemptPin {
attempt_id: attempt.attempt_id.clone(),
assignee_agent_id: attempt.assignee_agent_id.clone(),
attempt_fence: attempt.attempt_fence.clone(),
attempt_controller_generation: attempt.attempt_controller_generation,
}))
}
pub(crate) fn read_agent_task_at(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
now: i64,
) -> Result<AgentTaskDetail, CommunicationStoreError> {
validate_communication_principal(principal)?;
validate_id(task_id, AGENT_TASK_ID_PREFIX, "invalid_agent_task_id")?;
let conn = self.lock_connection(crate::StoreDomain::AgentTask);
Ok(load_owned_task(&conn, principal, task_id, now)?.detail(now))
}
pub fn assign_agent_task(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
assignee_agent_id: &str,
) -> Result<AgentTaskMutation, CommunicationStoreError> {
self.assign_agent_task_with_now(principal, task_id, assignee_agent_id, None)
}
#[cfg(test)]
pub(crate) fn assign_agent_task_at(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
assignee_agent_id: &str,
now: i64,
) -> Result<AgentTaskMutation, CommunicationStoreError> {
self.assign_agent_task_with_now(principal, task_id, assignee_agent_id, Some(now))
}
fn assign_agent_task_with_now(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
assignee_agent_id: &str,
now: Option<i64>,
) -> Result<AgentTaskMutation, CommunicationStoreError> {
validate_communication_principal(principal)?;
validate_id(task_id, AGENT_TASK_ID_PREFIX, "invalid_agent_task_id")?;
validate_id(
assignee_agent_id,
DURABLE_AGENT_ID_PREFIX,
"invalid_agent_id",
)?;
let mut conn = self.lock_connection(crate::StoreDomain::AgentTask);
let transaction = conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(store_error)?;
let now = now.unwrap_or_else(now_unix_ms);
let mut task = load_owned_task(&transaction, principal, task_id, now)?;
if task.stored_state.terminal() {
return Err(task_terminal_error());
}
require_owned_agent(&transaction, principal, assignee_agent_id)?;
materialize_expired_latest_attempt(&transaction, &mut task, now)?;
if task.assignee_agent_id.as_deref() != Some(assignee_agent_id) {
if let Some(error) = blocking_execution_error(task.latest_coding_run.as_ref()) {
return Err(error);
}
}
if task
.latest_attempt
.as_ref()
.is_some_and(|attempt| attempt.stored_state == AgentTaskAttemptState::Active)
{
if task.assignee_agent_id.as_deref() == Some(assignee_agent_id) {
transaction.commit().map_err(store_error)?;
return Ok(AgentTaskMutation {
task: task.detail(now),
created: false,
replayed: false,
state_changed: false,
});
}
return Err(CommunicationStoreError::new(
"agent_task_attempt_active",
"AgentTask has an unexpired active Attempt; reassignment is fenced",
));
}
if task.assignee_agent_id.as_deref() == Some(assignee_agent_id) {
transaction.commit().map_err(store_error)?;
return Ok(AgentTaskMutation {
task: task.detail(now),
created: false,
replayed: false,
state_changed: false,
});
}
transaction
.execute(
"UPDATE wc_agent_tasks
SET assignee_agent_id = ?2, state = 'ready', updated_at_unix_ms = ?3
WHERE task_id = ?1",
params![task_id, assignee_agent_id, now.max(task.updated_at_unix_ms)],
)
.map_err(store_error)?;
task = load_owned_task(&transaction, principal, task_id, now)?;
transaction.commit().map_err(store_error)?;
Ok(AgentTaskMutation {
task: task.detail(now),
created: false,
replayed: false,
state_changed: true,
})
}
pub fn start_agent_task_attempt(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
assignee_agent_id: &str,
idempotency_key: &str,
) -> Result<AgentTaskAttemptStartMutation, CommunicationStoreError> {
self.start_agent_task_attempt_with_now(
principal,
task_id,
assignee_agent_id,
idempotency_key,
None,
)
}
#[cfg(test)]
pub(crate) fn start_agent_task_attempt_at(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
assignee_agent_id: &str,
idempotency_key: &str,
now: i64,
) -> Result<AgentTaskAttemptStartMutation, CommunicationStoreError> {
self.start_agent_task_attempt_with_now(
principal,
task_id,
assignee_agent_id,
idempotency_key,
Some(now),
)
}
fn start_agent_task_attempt_with_now(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
assignee_agent_id: &str,
idempotency_key: &str,
now: Option<i64>,
) -> Result<AgentTaskAttemptStartMutation, CommunicationStoreError> {
validate_communication_principal(principal)?;
validate_id(task_id, AGENT_TASK_ID_PREFIX, "invalid_agent_task_id")?;
validate_id(
assignee_agent_id,
DURABLE_AGENT_ID_PREFIX,
"invalid_agent_id",
)?;
let idempotency_key = validate_idempotency_key(idempotency_key)?;
let request_hash = task_request_hash(&json!({
"task_id": task_id,
"assignee_agent_id": assignee_agent_id,
}));
let mut conn = self.lock_connection(crate::StoreDomain::AgentTask);
let transaction = conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(store_error)?;
let now = now.unwrap_or_else(now_unix_ms);
let mut task = load_owned_task(&transaction, principal, task_id, now)?;
if let Some(attempt_id) = lookup_idempotent_resource(
&transaction,
principal,
OP_START_AGENT_TASK_ATTEMPT,
&idempotency_key,
&request_hash,
)? {
let attempt = load_attempt_for_task(&transaction, task_id, &attempt_id, now)?
.ok_or_else(|| {
CommunicationStoreError::new(
"agent_task_attempt_not_found",
"AgentTaskAttempt does not exist",
)
})?;
let record = attempt.record(now);
let fence = attempt.attempt_fence.clone();
transaction.commit().map_err(store_error)?;
return Ok(AgentTaskAttemptStartMutation {
task: task.summary(now),
attempt: record,
attempt_fence: fence,
replayed: true,
state_changed: false,
});
}
if task.stored_state.terminal() {
return Err(task_terminal_error());
}
let current_assignee = task.assignee_agent_id.as_deref().ok_or_else(|| {
CommunicationStoreError::new(
"agent_task_unassigned",
"AgentTask must have an explicit assignee before an Attempt can start",
)
})?;
if current_assignee != assignee_agent_id {
return Err(CommunicationStoreError::new(
"agent_task_assignee_mismatch",
"Requested Agent does not match the AgentTask current assignee",
));
}
require_owned_agent(&transaction, principal, assignee_agent_id)?;
materialize_expired_latest_attempt(&transaction, &mut task, now)?;
if let Some(error) = blocking_execution_error(task.latest_coding_run.as_ref()) {
return Err(error);
}
if task
.latest_attempt
.as_ref()
.is_some_and(|attempt| attempt.stored_state == AgentTaskAttemptState::Active)
{
return Err(CommunicationStoreError::new(
"agent_task_attempt_active",
"AgentTask already has an unexpired authoritative Attempt",
));
}
let attempt_number = task
.latest_attempt
.as_ref()
.map(|attempt| attempt.attempt_number.saturating_add(1))
.unwrap_or(1);
let attempt_id = allocate_identity(
&transaction,
AGENT_TASK_ATTEMPT_ID_PREFIX,
"SELECT EXISTS(SELECT 1 FROM wc_agent_task_attempts WHERE attempt_id = ?1)",
)?;
let attempt_fence = new_proof(AGENT_TASK_ATTEMPT_FENCE_PREFIX);
let lease_expires_at = now.saturating_add(DEFAULT_AGENT_TASK_ATTEMPT_LEASE_MS);
transaction
.execute(
"INSERT INTO wc_agent_task_attempts (
attempt_id, task_id, attempt_number, assignee_agent_id, state,
lease_expires_at_unix_ms, attempt_fence, attempt_controller_generation,
created_at_unix_ms, started_at_unix_ms, terminal_at_unix_ms,
terminal_result, terminal_reason
) VALUES (?1, ?2, ?3, ?4, 'active', ?5, ?6, 1, ?7, ?7, NULL, NULL, NULL)",
params![
attempt_id,
task_id,
attempt_number,
assignee_agent_id,
lease_expires_at,
attempt_fence,
now,
],
)
.map_err(store_error)?;
transaction
.execute(
"UPDATE wc_agent_tasks
SET state = 'active', latest_attempt_id = ?2, updated_at_unix_ms = ?3
WHERE task_id = ?1",
params![task_id, attempt_id, now.max(task.updated_at_unix_ms)],
)
.map_err(store_error)?;
record_idempotent_resource(
&transaction,
principal,
OP_START_AGENT_TASK_ATTEMPT,
&idempotency_key,
&request_hash,
&attempt_id,
now,
)?;
task = load_owned_task(&transaction, principal, task_id, now)?;
let attempt =
load_attempt_for_task(&transaction, task_id, &attempt_id, now)?.ok_or_else(|| {
CommunicationStoreError::new(
"agent_task_attempt_not_found",
"AgentTaskAttempt disappeared after creation",
)
})?;
let record = attempt.record(now);
let fence = attempt.attempt_fence.clone();
transaction.commit().map_err(store_error)?;
Ok(AgentTaskAttemptStartMutation {
task: task.summary(now),
attempt: record,
attempt_fence: fence,
replayed: false,
state_changed: true,
})
}
#[allow(clippy::too_many_arguments)]
pub fn start_agent_task_endpoint_continuation(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
attempt_id: &str,
assignee_agent_id: &str,
attempt_fence: &str,
attempt_controller_generation: i64,
) -> Result<AgentTaskEndpointExecutionMutation, CommunicationStoreError> {
let authority = AttemptAuthority::validated(
principal,
task_id,
attempt_id,
assignee_agent_id,
attempt_fence,
attempt_controller_generation,
)?;
self.start_agent_task_endpoint_continuation_with_now(
principal,
authority,
None,
now_unix_ms(),
)
}
/// Start a continuation whose immutable execution target is this exact live
/// Endpoint generation. Replacement carriers cannot claim this Task Wake.
#[allow(clippy::too_many_arguments)]
pub fn start_agent_task_endpoint_continuation_pinned(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
attempt_id: &str,
assignee_agent_id: &str,
attempt_fence: &str,
attempt_controller_generation: i64,
endpoint_id: &str,
endpoint_controller_generation: i64,
) -> Result<AgentTaskEndpointExecutionMutation, CommunicationStoreError> {
let authority = AttemptAuthority::validated(
principal,
task_id,
attempt_id,
assignee_agent_id,
attempt_fence,
attempt_controller_generation,
)?;
validate_id(endpoint_id, AGENT_ENDPOINT_ID_PREFIX, "invalid_endpoint_id")?;
if endpoint_controller_generation < 1 {
return Err(CommunicationStoreError::new(
"invalid_controller_generation",
"Pinned Endpoint generation must be at least 1",
));
}
self.start_agent_task_endpoint_continuation_with_now(
principal,
authority,
Some((endpoint_id, endpoint_controller_generation)),
now_unix_ms(),
)
}
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn start_agent_task_endpoint_continuation_at(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
attempt_id: &str,
assignee_agent_id: &str,
attempt_fence: &str,
attempt_controller_generation: i64,
now: i64,
) -> Result<AgentTaskEndpointExecutionMutation, CommunicationStoreError> {
let authority = AttemptAuthority::validated(
principal,
task_id,
attempt_id,
assignee_agent_id,
attempt_fence,
attempt_controller_generation,
)?;
self.start_agent_task_endpoint_continuation_with_now(principal, authority, None, now)
}
fn start_agent_task_endpoint_continuation_with_now(
&self,
principal: &CommunicationPrincipal,
authority: AttemptAuthority<'_>,
pinned_endpoint: Option<(&str, i64)>,
now: i64,
) -> Result<AgentTaskEndpointExecutionMutation, CommunicationStoreError> {
let task_id = authority.task_id;
let attempt_id = authority.attempt_id;
let assignee_agent_id = authority.assignee_agent_id;
let mut start_identity = authority.identity_json();
if let Some((endpoint_id, generation)) = pinned_endpoint {
start_identity["pinned_endpoint_id"] = json!(endpoint_id);
start_identity["pinned_endpoint_controller_generation"] = json!(generation);
}
let start_identity_fingerprint = digest_json(
"webcodex.agent-task.endpoint-continuation.start.v1",
&start_identity,
)
.expect("AgentTask endpoint continuation identity serializes");
let mut conn = self.lock_connection(crate::StoreDomain::AgentTask);
let transaction = conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(store_error)?;
let task = load_owned_task(&transaction, principal, task_id, now)?;
if let Some(existing_fingerprint) = transaction
.query_row(
"SELECT start_identity_fingerprint
FROM wc_agent_task_endpoint_executions
WHERE task_id = ?1 AND attempt_id = ?2",
params![task_id, attempt_id],
|row| row.get::<_, String>(0),
)
.optional()
.map_err(store_error)?
{
if existing_fingerprint != start_identity_fingerprint {
return Err(CommunicationStoreError::new(
"agent_task_endpoint_execution_binding_conflict",
"AgentTaskAttempt Endpoint execution already exists for a different exact start identity",
));
}
let execution = load_endpoint_execution_for_attempt(&transaction, task_id, attempt_id)?
.ok_or_else(|| {
CommunicationStoreError::new(
"agent_task_storage_invariant",
"AgentTask Endpoint execution disappeared during exact replay",
)
})?;
transaction.commit().map_err(store_error)?;
return Ok(AgentTaskEndpointExecutionMutation {
execution,
replayed: true,
state_changed: false,
});
}
let _attempt = require_current_attempt(&transaction, &task, authority, now)?;
if let Some((endpoint_id, generation)) = pinned_endpoint {
let endpoint = require_current_endpoint(
&transaction,
principal,
assignee_agent_id,
endpoint_id,
Some(generation),
)?;
if !endpoint.wake_capable {
return Err(CommunicationStoreError::new(
"endpoint_not_wake_capable",
"Pinned Agent Endpoint is not wake-capable",
));
}
}
if load_coding_run_binding_for_attempt(&transaction, task_id, attempt_id)?.is_some() {
return Err(CommunicationStoreError::new(
"agent_task_execution_backend_conflict",
"AgentTaskAttempt is already bound to the CodingAgentRun execution backend",
));
}
let wake_id = allocate_identity(
&transaction,
AGENT_WAKE_ID_PREFIX,
"SELECT EXISTS(SELECT 1 FROM wc_agent_wakes WHERE wake_id = ?1)",
)?;
transaction
.execute(
"INSERT INTO wc_agent_wakes (
wake_id, target_agent_id, trigger_kind,
first_triggering_delivery_id, latest_triggering_delivery_id,
latest_conversation_id, latest_message_id,
inbox_high_watermark, queued_delivery_count_snapshot,
source_task_id, source_task_attempt_id, source_event_id,
state, revision, created_at_unix_ms, updated_at_unix_ms,
claimed_attempt_id, claimed_endpoint_id,
claimed_controller_generation, claim_lease_expires_at_unix_ms,
consumed_at_unix_ms, consumed_by_endpoint_id,
consumed_controller_generation
) VALUES (?1, ?2, ?3, NULL, NULL, NULL, NULL, NULL, NULL, ?4, ?5, NULL,
'pending', 1, ?6, ?6, NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
params![
wake_id,
assignee_agent_id,
WAKE_TRIGGER_AGENT_TASK_ATTEMPT,
task_id,
attempt_id,
now,
],
)
.map_err(store_error)?;
transaction
.execute(
"INSERT INTO wc_agent_task_endpoint_executions (
task_id, attempt_id, wake_id, start_identity_fingerprint,
endpoint_id, endpoint_controller_generation,
created_at_unix_ms, updated_at_unix_ms,
pinned_endpoint_id, pinned_endpoint_controller_generation
) VALUES (?1, ?2, ?3, ?4, NULL, NULL, ?5, ?5, ?6, ?7)",
params![
task_id,
attempt_id,
wake_id,
start_identity_fingerprint,
now,
pinned_endpoint.map(|(endpoint_id, _)| endpoint_id),
pinned_endpoint.map(|(_, generation)| generation),
],
)
.map_err(store_error)?;
let execution = load_endpoint_execution_for_attempt(&transaction, task_id, attempt_id)?
.ok_or_else(|| {
CommunicationStoreError::new(
"agent_task_storage_invariant",
"AgentTask Endpoint execution disappeared after creation",
)
})?;
transaction.commit().map_err(store_error)?;
Ok(AgentTaskEndpointExecutionMutation {
execution,
replayed: false,
state_changed: true,
})
}
#[allow(clippy::too_many_arguments)]
pub fn heartbeat_agent_task_attempt(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
attempt_id: &str,
assignee_agent_id: &str,
attempt_fence: &str,
attempt_controller_generation: i64,
) -> Result<AgentTaskAttemptHeartbeatMutation, CommunicationStoreError> {
let authority = AttemptAuthority::validated(
principal,
task_id,
attempt_id,
assignee_agent_id,
attempt_fence,
attempt_controller_generation,
)?;
self.heartbeat_agent_task_attempt_with_now(principal, authority, None, None, None)
}
#[allow(clippy::too_many_arguments)]
pub fn heartbeat_agent_task_attempt_with_active_turn_proof(
&self,
principal: &CommunicationPrincipal,
task_id: &str,
attempt_id: &str,
assignee_agent_id: &str,
attempt_fence: &str,
attempt_controller_generation: i64,
active_turn_wake_id: Option<&str>,
active_turn_consume_token: Option<&str>,
) -> Result<AgentTaskAttemptHeartbeatMutation, CommunicationStoreError> {
let authority = AttemptAuthority::validated(