3030 DiscoverFn ,
3131 EventSink ,
3232 RpcPostFn ,
33- _as_int ,
34- _cascade_summary_entry ,
3533 _is_dict ,
3634 _is_strict_int ,
3735 _opt_dict ,
3836 _rpc_post ,
37+ _start_cascade as _start_cascade ,
3938 _subdict ,
4039 discover_antigravity_language_server ,
41- post_idempotent_with_refresh ,
42- refresh_endpoint_binding ,
40+ resolve_initial_cascade as resolve_initial_cascade ,
4341)
4442from .manager_input import manager_input_matches
4543
7977 "CORTEX_STEP_TYPE_CHECKPOINT" ,
8078 "CORTEX_STEP_TYPE_SYSTEM_MESSAGE" ,
8179})
80+ _CONTINUATION_BOUNDARY_SYSTEM_STEPS = frozenset ({
81+ "CORTEX_STEP_TYPE_SYSTEM_MESSAGE" ,
82+ "CORTEX_STEP_TYPE_CHECKPOINT" ,
83+ })
8284
8385
8486class CascadeReader (Protocol ):
@@ -100,52 +102,44 @@ def _max_cascade_steps(env: Mapping[str, str] | None = None) -> int:
100102 return parsed if parsed >= 0 else ANTIGRAVITY_MAX_CASCADE_STEPS
101103
102104
103- def _start_cascade (
104- ls_url : str ,
105- csrf_token : str ,
106- work_dir : Path ,
107- * ,
108- rpc_post_fn : RpcPostFn = _rpc_post ,
109- ) -> str :
110- started = rpc_post_fn (
111- ls_url ,
112- csrf_token ,
113- "StartCascade" ,
114- {
115- "source" : "CORTEX_TRAJECTORY_SOURCE_CASCADE_CLIENT" ,
116- "workspaceUris" : [work_dir .resolve ().as_uri ()],
117- },
118- timeout = 10.0 ,
119- )
120- cascade_id = str (started .get ("cascadeId" ) or "" ).strip ()
121- if not cascade_id :
122- raise CodexChatAgentError (
123- f"StartCascade did not return a cascadeId: { started } " ,
124- gate = None ,
125- error_code = "antigravity_start_failed" ,
126- )
127- return cascade_id
128-
129-
130105def _is_transient_continue_input (step : JsonMap ) -> bool :
131106 return (
132107 step .get ("type" ) == "CORTEX_STEP_TYPE_USER_INPUT"
133108 and _native_user_input_text (step ) == ANTIGRAVITY_TRANSIENT_CONTINUE_PROMPT
134109 )
135110
136111
112+ def _is_continuation_boundary_system_step (step : JsonMap ) -> bool :
113+ """Return True for a settled host-injected system/checkpoint step at retry boundaries."""
114+ source = _subdict (step , "metadata" ).get ("source" )
115+ return (
116+ step .get ("type" ) in _CONTINUATION_BOUNDARY_SYSTEM_STEPS
117+ and step .get ("status" ) in _SETTLED_STEP_STATUSES
118+ and source in (None , "CORTEX_STEP_SOURCE_SYSTEM" )
119+ )
120+
121+
122+ def _trailing_effective_step (steps : Sequence [IndexedStep ]) -> IndexedStep | None :
123+ """Return the last step ignoring settled host-injected boundary system steps."""
124+ for idx , step in reversed (steps ):
125+ if not _is_continuation_boundary_system_step (step ):
126+ return idx , step
127+ return None
128+
129+
137130def _split_turn_segments (current_steps : Sequence [IndexedStep ]) -> list [list [IndexedStep ]] | None :
138131 """Split a turn across bounded transient-continuation USER_INPUT boundaries."""
139132 if not current_steps :
140133 return []
141134 segments : list [list [IndexedStep ]] = [[]]
142135 for pos , (idx , step ) in enumerate (current_steps ):
143136 if pos > 0 and step .get ("type" ) == "CORTEX_STEP_TYPE_USER_INPUT" :
137+ effective = _trailing_effective_step (segments [- 1 ])
144138 if (
145139 not _is_transient_continue_input (step )
146140 or len (segments ) > ANTIGRAVITY_MAX_TRANSIENT_STEP_RETRIES
147- or not segments [ - 1 ]
148- or segments [ - 1 ][ - 1 ] [1 ].get ("type" ) != "CORTEX_STEP_TYPE_ERROR_MESSAGE"
141+ or effective is None
142+ or effective [1 ].get ("type" ) != "CORTEX_STEP_TYPE_ERROR_MESSAGE"
149143 ):
150144 return None
151145 segments .append ([(idx , step )])
@@ -197,6 +191,11 @@ def _turn_steps_allow_completion(
197191 (idx for idx , step in seg if step .get ("type" ) == "CORTEX_STEP_TYPE_ERROR_MESSAGE" ),
198192 default = None ,
199193 )
194+ next_seg_exec : str | None = None
195+ if not is_final_seg :
196+ raw_next = _subdict (segments [seg_idx + 1 ][0 ][1 ], "metadata" ).get ("executionId" )
197+ if isinstance (raw_next , str ) and raw_next :
198+ next_seg_exec = raw_next
200199 for idx , step in seg :
201200 if (
202201 step is not final
@@ -206,6 +205,13 @@ def _turn_steps_allow_completion(
206205 and step .get ("type" ) != "CORTEX_STEP_TYPE_USER_INPUT"
207206 ):
208207 continue
208+ if (
209+ not is_final_seg
210+ and last_error_idx is not None
211+ and idx > last_error_idx
212+ and not _is_continuation_boundary_system_step (step )
213+ ):
214+ return False
209215 if is_final_seg :
210216 if not _step_allows_completed_turn (step , final = final ):
211217 return False
@@ -220,7 +226,19 @@ def _turn_steps_allow_completion(
220226 "CORTEX_STEP_TYPE_SYSTEM_MESSAGE" ,
221227 "CORTEX_STEP_TYPE_CHECKPOINT" ,
222228 }
223- if step_exec != seg_exec and not (allow_none and step_exec is None ):
229+ allow_next_exec = (
230+ not is_final_seg
231+ and last_error_idx is not None
232+ and idx > last_error_idx
233+ and _is_continuation_boundary_system_step (step )
234+ and next_seg_exec is not None
235+ and step_exec == next_seg_exec
236+ )
237+ if (
238+ step_exec != seg_exec
239+ and not (allow_none and step_exec is None )
240+ and not allow_next_exec
241+ ):
224242 return False
225243 return True
226244
@@ -790,11 +808,17 @@ def _verify_idle_terminal(
790808) -> bool :
791809 """Evaluate terminal idle status, tolerating cleared retries until answer settles."""
792810 final = current_steps [- 1 ][1 ] if current_steps else {}
793- final_is_error = final .get ("type" ) == "CORTEX_STEP_TYPE_ERROR_MESSAGE"
794- error_message = _subdict (final , "errorMessage" ) if final_is_error else {}
811+ effective = _trailing_effective_step (current_steps )
812+ error_step = (
813+ effective [1 ]
814+ if effective is not None and effective [1 ].get ("type" ) == "CORTEX_STEP_TYPE_ERROR_MESSAGE"
815+ else {}
816+ )
817+ final_is_error = bool (error_step )
818+ error_message = _subdict (error_step , "errorMessage" ) if final_is_error else {}
795819 cleared_retry = (
796820 final_is_error
797- and final .get ("status" ) == "CORTEX_STEP_STATUS_CLEARED"
821+ and error_step .get ("status" ) == "CORTEX_STEP_STATUS_CLEARED"
798822 and error_message .get ("shouldShowUser" ) is not True
799823 )
800824 if final_is_error and not cleared_retry :
@@ -811,7 +835,7 @@ def _verify_idle_terminal(
811835 )
812836 error .native_error_info = detail if _is_dict (detail ) else str (detail )
813837 if (
814- final .get ("status" ) == "CORTEX_STEP_STATUS_DONE"
838+ error_step .get ("status" ) == "CORTEX_STEP_STATUS_DONE"
815839 and all (step .get ("status" ) in _SETTLED_STEP_STATUSES for _ , step in current_steps )
816840 ):
817841 on_retire_active_turn ()
@@ -906,88 +930,3 @@ def build_cascade_config(model_placeholder: str, *, restricted: bool) -> JsonDic
906930 ),
907931 }
908932 }
909-
910-
911- def resolve_initial_cascade (
912- * ,
913- ls_url : str ,
914- csrf_token : str ,
915- work_dir : Path ,
916- resume_thread_id : str | None ,
917- history : list [dict [str , str ]] | None ,
918- max_steps : int ,
919- rpc_post_fn : RpcPostFn ,
920- rollover_fn : Callable [[Sequence [Mapping [str , object ]]], list [dict [str , str ]]],
921- env : Mapping [str , str ] | None = None ,
922- discover_fn : DiscoverFn | None = None ,
923- ) -> tuple [str , bool , list [dict [str , str ]] | None , str , str ]:
924- """Resolve or rotate a resumed cascade, or start a new one."""
925- endpoint = [ls_url , csrf_token ]
926- rediscovered = False
927-
928- def _apply (new_url : str , new_token : str ) -> bool :
929- endpoint [0 ], endpoint [1 ] = new_url , new_token
930- return True
931-
932- def _refresh_once (failed_url : str , failed_token : str , timeout : float ) -> bool :
933- nonlocal rediscovered
934- if rediscovered or discover_fn is None :
935- return False
936- rediscovered = True
937- return refresh_endpoint_binding (
938- current_fn = lambda : (endpoint [0 ], endpoint [1 ]),
939- apply_fn = _apply , failed_url = failed_url , failed_token = failed_token ,
940- env = env , timeout = timeout , discover_fn = discover_fn ,
941- )
942-
943- cascade_id = str (resume_thread_id or "" ).strip ()
944- resumed = False
945- rotated = False
946- if cascade_id :
947- rotate_now = False
948- try :
949- traj = post_idempotent_with_refresh (
950- current_fn = lambda : (endpoint [0 ], endpoint [1 ]),
951- refresh_fn = _refresh_once ,
952- method = "GetCascadeTrajectory" ,
953- payload = {"cascadeId" : cascade_id },
954- timeout = 10.0 ,
955- rpc_post_fn = rpc_post_fn ,
956- )
957- if _is_dict (traj ) and traj .get ("trajectory" ):
958- resumed = True
959- raw_steps = _subdict (traj , "trajectory" ).get ("steps" )
960- fallback_len = len (raw_steps ) if isinstance (raw_steps , list ) else 0
961- total_steps = _as_int (traj .get ("numTotalSteps" )) or fallback_len
962- rotate_now = (
963- max_steps > 0 and total_steps >= max_steps
964- and traj .get ("status" ) != "CASCADE_RUN_STATUS_RUNNING"
965- and history is not None
966- )
967- except CodexChatAgentError as exc :
968- resumed = False
969- if exc .error_code == "antigravity_transport_error" and max_steps > 0 and history is not None :
970- try :
971- entry = _cascade_summary_entry (
972- rpc_post_fn (endpoint [0 ], endpoint [1 ], "GetAllCascadeTrajectories" , {}, timeout = 5.0 ),
973- cascade_id ,
974- )
975- except CodexChatAgentError :
976- entry = None
977- if (
978- entry is not None
979- and _as_int (entry .get ("stepCount" )) >= max_steps
980- and entry .get ("status" ) != "CASCADE_RUN_STATUS_RUNNING"
981- ):
982- rotate_now = True
983- if rotate_now and history is not None :
984- cascade_id = _start_cascade (endpoint [0 ], endpoint [1 ], work_dir , rpc_post_fn = rpc_post_fn )
985- resumed , rotated , history = False , True , rollover_fn (history )
986- if cascade_id and not resumed and not rotated :
987- raise CodexChatAgentError (
988- "The original Antigravity conversation is unavailable. Restore it in Antigravity or start a new Chat explicitly." ,
989- gate = None , error_code = "resume_failed" ,
990- )
991- if not resumed and not rotated :
992- cascade_id = _start_cascade (endpoint [0 ], endpoint [1 ], work_dir , rpc_post_fn = rpc_post_fn )
993- return cascade_id , resumed , history , endpoint [0 ], endpoint [1 ]
0 commit comments