agentkit-sdk-python 0.8.9__py3-none-any.whl → 0.9.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. agentkit/apps/agent_server_app/agent_server_app.py +38 -4
  2. agentkit/frameworks/_agentsentry.py +192 -0
  3. agentkit/frameworks/langchain.py +17 -4
  4. agentkit/frameworks/langgraph.py +11 -1
  5. agentkit/plugins/agentsentry_v3.py +178 -0
  6. agentkit/plugins/llm_shield.py +161 -8
  7. agentkit/sdk/gateway/__init__.py +29 -0
  8. agentkit/sdk/gateway/client.py +70 -0
  9. agentkit/sdk/gateway/types.py +45 -0
  10. agentkit/sdk/runtime/gateway.py +1 -5
  11. agentkit/toolkit/cli/cli_deploy.py +24 -1
  12. agentkit/toolkit/cli/cli_launch.py +18 -0
  13. agentkit/toolkit/executors/deploy_executor.py +10 -0
  14. agentkit/toolkit/executors/lifecycle_executor.py +10 -0
  15. agentkit/toolkit/harness/deploy.py +4 -0
  16. agentkit/toolkit/runners/ve_agentkit.py +68 -3
  17. agentkit/toolkit/runtime_recreate_policy.py +125 -0
  18. agentkit/toolkit/sdk/client.py +16 -0
  19. agentkit/toolkit/sdk/deployer.py +10 -0
  20. agentkit/toolkit/sdk/lifecycle.py +10 -0
  21. agentkit/toolkit/strategies/base_strategy.py +2 -0
  22. agentkit/toolkit/strategies/cloud_strategy.py +1 -0
  23. agentkit/toolkit/strategies/hybrid_strategy.py +1 -0
  24. agentkit/version.py +1 -1
  25. {agentkit_sdk_python-0.8.9.dist-info → agentkit_sdk_python-0.9.2.dist-info}/METADATA +1 -1
  26. {agentkit_sdk_python-0.8.9.dist-info → agentkit_sdk_python-0.9.2.dist-info}/RECORD +30 -24
  27. {agentkit_sdk_python-0.8.9.dist-info → agentkit_sdk_python-0.9.2.dist-info}/WHEEL +1 -1
  28. {agentkit_sdk_python-0.8.9.dist-info → agentkit_sdk_python-0.9.2.dist-info}/entry_points.txt +0 -0
  29. {agentkit_sdk_python-0.8.9.dist-info → agentkit_sdk_python-0.9.2.dist-info}/licenses/LICENSE +0 -0
  30. {agentkit_sdk_python-0.8.9.dist-info → agentkit_sdk_python-0.9.2.dist-info}/top_level.txt +0 -0
@@ -9,14 +9,15 @@ import os
9
9
  from dataclasses import dataclass
10
10
  from enum import Enum
11
11
  from typing import Any, Literal
12
+ from urllib.parse import urlsplit
12
13
 
13
14
  import requests
14
15
  from google.adk.events import Event
15
16
  from google.adk.plugins import BasePlugin
16
17
  from google.genai import types
17
- from volcengine.Credentials import Credentials as SigningCredentials
18
18
  from volcengine.auth.SignerV4 import SignerV4
19
19
  from volcengine.base.Request import Request as SigningRequest
20
+ from volcengine.Credentials import Credentials as SigningCredentials
20
21
 
21
22
  from agentkit.platform.configuration import VolcConfiguration
22
23
  from agentkit.utils.http_defaults import http_timeout
@@ -36,6 +37,7 @@ _API_VERSION = "2025-08-31"
36
37
  _DEFAULT_REGION = "cn-beijing"
37
38
  _SERVICE = "llmshield"
38
39
  _PATH = "/v2/moderate"
40
+ SENTRY_V3_PATH = "/OpenTOP/V3/Lumen/Moderate"
39
41
  _INVOCATION_STATE_KEY = "__agentkit_llm_shield__"
40
42
  _TRUE_VALUES = frozenset({"1", "true", "yes", "on"})
41
43
  _FALSE_VALUES = frozenset({"", "0", "false", "no", "off"})
@@ -56,7 +58,9 @@ class LLMShieldPlugin(BasePlugin):
56
58
  """Moderate AgentKit text boundaries with Volcengine LLM Shield.
57
59
 
58
60
  Applications opt in by attaching the plugin to the ADK ``App.plugins``
59
- boundary; :meth:`from_env` reads the migration runtime environment, where a
61
+ boundary. Private AgentSentry uses AGENTSENTRY_URL and endpoint credentials;
62
+ AGENTSENTRY_ENABLED=false disables it independently of public LLM Shield.
63
+ :meth:`from_env` reads the migration runtime environment, where a
60
64
  configured ``TOOL_LLM_SHIELD_APP_ID`` enables moderation and
61
65
  ``ENABLE_LLM_SHIELD`` only overrides that default. Existing AgentKit
62
66
  applications are unchanged until they construct this plugin.
@@ -67,13 +71,26 @@ class LLMShieldPlugin(BasePlugin):
67
71
  def __init__(
68
72
  self,
69
73
  *,
70
- app_id: str,
74
+ app_id: str = "",
71
75
  region: str = _DEFAULT_REGION,
72
76
  timeout: float | None = None,
73
77
  base_url: str | None = None,
74
78
  max_output_bytes: int = 256 * 1024,
79
+ agentsentry_url: str | None = None,
75
80
  ) -> None:
76
81
  super().__init__(name="LLMShieldPlugin")
82
+ if agentsentry_url is not None:
83
+ from agentkit.plugins.agentsentry_v3 import AgentSentryV3
84
+
85
+ self.timeout = timeout if timeout is not None else http_timeout()
86
+ self._sentry_v3 = AgentSentryV3.from_env(agentsentry_url, self.timeout)
87
+ self.base_url = self._sentry_v3.url
88
+ self.region = self._sentry_v3.region
89
+ self.app_id = ""
90
+ self.account_id = self._sentry_v3.account_id
91
+ self.max_output_bytes = max_output_bytes
92
+ self._configuration = None
93
+ return
77
94
  if not app_id.strip():
78
95
  raise ValueError("LLM Shield app_id must not be empty")
79
96
  if not region.strip():
@@ -87,6 +104,9 @@ class LLMShieldPlugin(BasePlugin):
87
104
  self.base_url = (
88
105
  base_url or f"https://{self.region}.sdk.access.llm-shield.omini-shield.com"
89
106
  ).rstrip("/")
107
+ self._sentry_v3 = None
108
+ if urlsplit(self.base_url).path.rstrip("/") == SENTRY_V3_PATH:
109
+ raise ValueError("Configure V3 with agentsentry_url or AGENTSENTRY_URL")
90
110
  self.max_output_bytes = max_output_bytes
91
111
  self._configuration = VolcConfiguration(region=self.region)
92
112
 
@@ -94,6 +114,12 @@ class LLMShieldPlugin(BasePlugin):
94
114
  def from_env(cls) -> LLMShieldPlugin | None:
95
115
  """Build the plugin from the migration runtime environment.
96
116
 
117
+ AGENTSENTRY_URL selects private V3 with AGENTSENTRY_ACCOUNT_ID,
118
+ AGENTSENTRY_INSTANCE_ID and endpoint AGENTSENTRY_AK/SK credentials.
119
+ AGENTSENTRY_REGION defaults to cn-private. AGENTSENTRY_ENABLED=false
120
+ disables private moderation independently of ENABLE_LLM_SHIELD.
121
+ V3 reviews current user text and visible tool plans.
122
+
97
123
  A configured ``TOOL_LLM_SHIELD_APP_ID`` is the enablement signal, so
98
124
  migrations do not need a separate switch. ``ENABLE_LLM_SHIELD`` is an
99
125
  optional override: ``0/false/no/off`` forces the plugin off even when an
@@ -103,6 +129,19 @@ class LLMShieldPlugin(BasePlugin):
103
129
  credential chain.
104
130
  """
105
131
 
132
+ sentry_url = os.getenv("AGENTSENTRY_URL", "").strip()
133
+ if sentry_url:
134
+ from agentkit.plugins.agentsentry_v3 import enabled_from_env
135
+
136
+ return cls(agentsentry_url=sentry_url) if enabled_from_env() else None
137
+ if (
138
+ urlsplit(os.getenv("TOOL_LLM_SHIELD_URL", "")).path.rstrip("/")
139
+ == SENTRY_V3_PATH
140
+ ):
141
+ raise ValueError(
142
+ "Configure V3 with AGENTSENTRY_URL, not TOOL_LLM_SHIELD_URL"
143
+ )
144
+
106
145
  raw_override = os.getenv("ENABLE_LLM_SHIELD", "").strip().lower()
107
146
  app_id = os.getenv("TOOL_LLM_SHIELD_APP_ID", "").strip()
108
147
  if os.getenv("TOOL_LLM_SHIELD_API_KEY", "").strip():
@@ -135,10 +174,28 @@ class LLMShieldPlugin(BasePlugin):
135
174
  )
136
175
 
137
176
  async def moderate_text(
138
- self, text: str, *, role: Literal["user", "assistant"]
177
+ self,
178
+ text: str,
179
+ *,
180
+ role: Literal["user", "assistant"],
181
+ hook_name: str | None = None,
182
+ session_info: dict[str, str] | None = None,
139
183
  ) -> str | None:
140
184
  """Return replacement text when content must not pass unchanged."""
141
185
 
186
+ if self._sentry_v3:
187
+ if hook_name is None:
188
+ if role == "assistant":
189
+ return None
190
+ if role == "user":
191
+ hook_name = "before_dispatch"
192
+ return await asyncio.to_thread(
193
+ self._sentry_v3.moderate,
194
+ text,
195
+ role=role,
196
+ hook_name=hook_name,
197
+ session_info=session_info,
198
+ )
142
199
  if not text:
143
200
  return None
144
201
  if role not in {"user", "assistant"}:
@@ -240,14 +297,63 @@ class LLMShieldPlugin(BasePlugin):
240
297
  request.headers.update({"X-Top-Service": _SERVICE, "X-Top-Region": self.region})
241
298
  return dict(request.headers)
242
299
 
300
+ async def _moderate_boundary(self, text, *, role, hook_name, context):
301
+ if not self._sentry_v3:
302
+ return await self.moderate_text(text, role=role)
303
+ session = getattr(context, "session", None)
304
+ return await self.moderate_text(
305
+ text,
306
+ role=role,
307
+ hook_name=hook_name,
308
+ session_info={
309
+ "SessionID": getattr(session, "id", "") or "",
310
+ "RunID": getattr(context, "invocation_id", "") or "",
311
+ },
312
+ )
313
+
243
314
  async def before_run_callback(self, *, invocation_context) -> types.Content | None:
244
- text = _content_text(getattr(invocation_context, "user_content", None))
245
- replacement = await self.moderate_text(text, role="user")
315
+ text = _content_text(
316
+ getattr(invocation_context, "user_content", None),
317
+ visible_only=bool(self._sentry_v3),
318
+ )
319
+ replacement = await self._moderate_boundary(
320
+ text, role="user", hook_name="before_dispatch", context=invocation_context
321
+ )
246
322
  if replacement is None:
247
323
  return None
248
324
  _invocation_state(invocation_context)["terminal"] = True
249
325
  return _model_content(replacement)
250
326
 
327
+ async def before_model_callback(self, *, callback_context, llm_request):
328
+ if self._sentry_v3:
329
+ invocation = getattr(
330
+ callback_context, "_invocation_context", callback_context
331
+ )
332
+ state = _invocation_state(invocation)
333
+ state.pop("plans", None)
334
+ state.pop("partial_plan", None)
335
+ return None
336
+
337
+ async def after_model_callback(self, *, callback_context, llm_response):
338
+ """Retain visible native ADK tool plans without inspecting final replies."""
339
+ if not self._sentry_v3:
340
+ return None
341
+ invocation = getattr(callback_context, "_invocation_context", callback_context)
342
+ state = _invocation_state(invocation)
343
+ content = getattr(llm_response, "content", None)
344
+ text = _content_text(content, visible_only=True)
345
+ if getattr(llm_response, "partial", False):
346
+ state["partial_plan"] = state.get("partial_plan", "") + text
347
+ else:
348
+ text = text or state.pop("partial_plan", "")
349
+ for part in getattr(content, "parts", None) or []:
350
+ call = getattr(part, "function_call", None)
351
+ if call:
352
+ state.setdefault("plans", {})[
353
+ _native_call_key(call.name, call.args or {})
354
+ ] = text or state.get("partial_plan", "")
355
+ return None
356
+
251
357
  async def before_tool_callback(
252
358
  self,
253
359
  *,
@@ -255,6 +361,40 @@ class LLMShieldPlugin(BasePlugin):
255
361
  tool_args: dict[str, Any],
256
362
  tool_context: Any,
257
363
  ) -> dict[str, Any] | None:
364
+ if self._sentry_v3:
365
+ from agentkit.plugins.agentsentry_v3 import MISSING_PLAN
366
+
367
+ invocation = getattr(tool_context, "_invocation_context", tool_context)
368
+ key = _native_call_key(tool.name, tool_args)
369
+ plan = _invocation_state(invocation).get("plans", {}).pop(key, "")
370
+ if not plan:
371
+ return {
372
+ "result": MISSING_PLAN,
373
+ "reason": "missing_visible_execution_plan",
374
+ }
375
+ block = await asyncio.to_thread(
376
+ self._sentry_v3.moderate,
377
+ plan,
378
+ role="assistant",
379
+ hook_name="before_tool_call",
380
+ session_info={
381
+ "SessionID": getattr(
382
+ getattr(invocation, "session", None), "id", ""
383
+ ),
384
+ "RunID": getattr(invocation, "invocation_id", ""),
385
+ },
386
+ tool_calls=[
387
+ {
388
+ "ID": getattr(tool_context, "function_call_id", "") or "",
389
+ "Type": "function",
390
+ "Function": {
391
+ "Name": tool.name,
392
+ "Arguments": json.dumps(tool_args, ensure_ascii=False),
393
+ },
394
+ }
395
+ ],
396
+ )
397
+ return {"result": block} if block else None
258
398
  del tool, tool_context
259
399
  text = _tool_payload_text(tool_args)
260
400
  if text is None:
@@ -270,6 +410,8 @@ class LLMShieldPlugin(BasePlugin):
270
410
  tool_context: Any,
271
411
  result: dict[str, Any],
272
412
  ) -> dict[str, Any] | None:
413
+ if self._sentry_v3:
414
+ return None
273
415
  del tool, tool_args, tool_context
274
416
  text = _tool_payload_text(result)
275
417
  if text is None:
@@ -280,6 +422,8 @@ class LLMShieldPlugin(BasePlugin):
280
422
  async def on_event_callback(
281
423
  self, *, invocation_context, event: Event
282
424
  ) -> Event | None:
425
+ if self._sentry_v3:
426
+ return event
283
427
  state = _invocation_state(invocation_context)
284
428
  if state.get("terminal"):
285
429
  return event
@@ -328,11 +472,16 @@ def _invocation_state(invocation_context: Any) -> dict[str, Any]:
328
472
  return state
329
473
 
330
474
 
331
- def _content_text(content: Any) -> str:
475
+ def _content_text(content: Any, *, visible_only: bool = False) -> str:
332
476
  if content is None:
333
477
  return ""
334
478
  parts = getattr(content, "parts", None) or []
335
- texts = [str(part.text) for part in parts if getattr(part, "text", None)]
479
+ texts = [
480
+ str(part.text)
481
+ for part in parts
482
+ if getattr(part, "text", None)
483
+ and (not visible_only or not getattr(part, "thought", False))
484
+ ]
336
485
  return "\n".join(texts)
337
486
 
338
487
 
@@ -390,3 +539,7 @@ def _replace_event_text(event: Event, text: str) -> Event:
390
539
  parts.insert(0, types.Part(text=text))
391
540
  updated.content = content.model_copy(update={"parts": parts})
392
541
  return updated
542
+
543
+
544
+ def _native_call_key(name, args):
545
+ return name, json.dumps(args, sort_keys=True, ensure_ascii=False)
@@ -0,0 +1,29 @@
1
+ # Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .client import AgentkitGatewayClient
16
+ from .types import (
17
+ CreateGatewayPluginBindingRequest,
18
+ CreateGatewayPluginBindingResponse,
19
+ CreateGatewayPluginRequest,
20
+ CreateGatewayPluginResponse,
21
+ )
22
+
23
+ __all__ = [
24
+ "AgentkitGatewayClient",
25
+ "CreateGatewayPluginBindingRequest",
26
+ "CreateGatewayPluginBindingResponse",
27
+ "CreateGatewayPluginRequest",
28
+ "CreateGatewayPluginResponse",
29
+ ]
@@ -0,0 +1,70 @@
1
+ # Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import ClassVar
18
+
19
+ from agentkit.client import BaseAgentkitClient
20
+
21
+ from .types import (
22
+ CreateGatewayPluginBindingRequest,
23
+ CreateGatewayPluginBindingResponse,
24
+ CreateGatewayPluginRequest,
25
+ CreateGatewayPluginResponse,
26
+ )
27
+
28
+
29
+ class AgentkitGatewayClient(BaseAgentkitClient):
30
+ """Manage plugins on dedicated AgentKit gateways and bind them to MCP services."""
31
+
32
+ API_ACTIONS: ClassVar[dict[str, str]] = {
33
+ "CreateGatewayPlugin": "CreateGatewayPlugin",
34
+ "CreateGatewayPluginBinding": "CreateGatewayPluginBinding",
35
+ }
36
+
37
+ def __init__(
38
+ self,
39
+ access_key: str = "",
40
+ secret_key: str = "",
41
+ region: str = "",
42
+ session_token: str = "",
43
+ ) -> None:
44
+ super().__init__(
45
+ access_key=access_key,
46
+ secret_key=secret_key,
47
+ region=region,
48
+ session_token=session_token,
49
+ service_name="gateway",
50
+ )
51
+
52
+ def create_gateway_plugin(
53
+ self, request: CreateGatewayPluginRequest
54
+ ) -> CreateGatewayPluginResponse:
55
+ """Install a plugin; create a binding separately to apply it to requests."""
56
+ return self._invoke_api(
57
+ api_action="CreateGatewayPlugin",
58
+ request=request,
59
+ response_type=CreateGatewayPluginResponse,
60
+ )
61
+
62
+ def create_gateway_plugin_binding(
63
+ self, request: CreateGatewayPluginBindingRequest
64
+ ) -> CreateGatewayPluginBindingResponse:
65
+ """Bind an installed gateway plugin to a target MCP service."""
66
+ return self._invoke_api(
67
+ api_action="CreateGatewayPluginBinding",
68
+ request=request,
69
+ response_type=CreateGatewayPluginBindingResponse,
70
+ )
@@ -0,0 +1,45 @@
1
+ # Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ from pydantic import BaseModel, Field
18
+
19
+
20
+ class GatewayBaseModel(BaseModel):
21
+ model_config = {"populate_by_name": True}
22
+
23
+
24
+ class CreateGatewayPluginRequest(GatewayBaseModel):
25
+ gateway_instance_id: str = Field(..., alias="GatewayInstanceId")
26
+ gateway_plugin_name: str = Field(..., alias="GatewayPluginName")
27
+ gateway_plugin_config: str = Field(..., alias="GatewayPluginConfig")
28
+
29
+
30
+ class CreateGatewayPluginResponse(GatewayBaseModel):
31
+ gateway_plugin_id: str | None = Field(default=None, alias="GatewayPluginId")
32
+
33
+
34
+ class CreateGatewayPluginBindingRequest(GatewayBaseModel):
35
+ gateway_plugin_id: str = Field(..., alias="GatewayPluginId")
36
+ target_id: str = Field(..., alias="TargetId")
37
+ gateway_plugin_binding_config: str = Field(..., alias="GatewayPluginBindingConfig")
38
+ enable: bool | None = Field(default=None, alias="Enable")
39
+ comments: str | None = Field(default=None, alias="Comments")
40
+
41
+
42
+ class CreateGatewayPluginBindingResponse(GatewayBaseModel):
43
+ gateway_plugin_binding_id: str | None = Field(
44
+ default=None, alias="GatewayPluginBindingId"
45
+ )
@@ -47,6 +47,7 @@ def validate_runtime_gateway_create_config(
47
47
  has_network_configuration: bool = False,
48
48
  label: str = "runtime",
49
49
  ) -> None:
50
+ del has_network_configuration
50
51
  mode = (
51
52
  normalize_runtime_gateway_mode(gateway_mode, f"{label}.gateway_mode")
52
53
  or "Shared"
@@ -58,11 +59,6 @@ def validate_runtime_gateway_create_config(
58
59
  raise ValueError(
59
60
  f"{label}.gateway_instance_id is required when gateway_mode is Exclusive."
60
61
  )
61
- if has_network_configuration:
62
- raise ValueError(
63
- f"{label}.network cannot be used when gateway_mode is Exclusive; "
64
- "the Runtime follows the selected gateway instance network."
65
- )
66
62
  return
67
63
 
68
64
  if gateway_instance_id:
@@ -69,11 +69,28 @@ def deploy_command(
69
69
  "-y",
70
70
  help="Harness deploy: update an existing same-name harness without prompting.",
71
71
  ),
72
+ recreate_runtime: str = typer.Option(
73
+ "",
74
+ "--recreate-runtime",
75
+ help=(
76
+ "Whether to delete and recreate the Runtime when recovery needs "
77
+ "replacement (default: ask, No). Allowed: yes|no."
78
+ ),
79
+ ),
72
80
  ):
73
81
  """Deploy the Agent to target environment."""
74
82
  from agentkit.toolkit.executors import DeployExecutor
75
83
  from agentkit.toolkit.cli.console_reporter import ConsoleReporter
76
84
  from agentkit.toolkit.context import ExecutionContext
85
+ from agentkit.toolkit.runtime_recreate_policy import (
86
+ parse_runtime_recreate_policy,
87
+ )
88
+
89
+ try:
90
+ runtime_recreate_policy = parse_runtime_recreate_policy(recreate_runtime)
91
+ except ValueError as exc:
92
+ console.print(f"[red]{exc}[/red]")
93
+ raise typer.Exit(2)
77
94
 
78
95
  if harness is not None:
79
96
  _deploy_harness(
@@ -84,6 +101,7 @@ def deploy_command(
84
101
  discovery_url=discovery_url,
85
102
  allowed_id=allowed_id,
86
103
  assume_yes=yes,
104
+ runtime_recreate_policy=runtime_recreate_policy,
87
105
  )
88
106
  return
89
107
 
@@ -94,7 +112,10 @@ def deploy_command(
94
112
  ExecutionContext.set_reporter(reporter)
95
113
 
96
114
  executor = DeployExecutor(reporter=reporter)
97
- result = executor.execute(config_file=str(config_file))
115
+ result = executor.execute(
116
+ config_file=str(config_file),
117
+ runtime_recreate_policy=runtime_recreate_policy,
118
+ )
98
119
 
99
120
  # Format output
100
121
  if result.success:
@@ -126,6 +147,7 @@ def _deploy_harness(
126
147
  discovery_url,
127
148
  allowed_id,
128
149
  assume_yes: bool = False,
150
+ runtime_recreate_policy="prompt",
129
151
  ):
130
152
  """Deploy a harness spec <name>.harness.json from the current directory."""
131
153
  import sys
@@ -161,6 +183,7 @@ def _deploy_harness(
161
183
  allowed_id=allowed_id,
162
184
  reporter=reporter,
163
185
  on_conflict=on_conflict,
186
+ runtime_recreate_policy=runtime_recreate_policy,
164
187
  )
165
188
  except HarnessDeployAborted:
166
189
  console.print("[yellow]Harness deploy cancelled.[/yellow]")
@@ -31,6 +31,14 @@ def launch_command(
31
31
  "--preflight-mode",
32
32
  help="Preflight behavior: prompt|fail|warn|skip",
33
33
  ),
34
+ recreate_runtime: str = typer.Option(
35
+ "",
36
+ "--recreate-runtime",
37
+ help=(
38
+ "Whether to delete and recreate the Runtime when recovery needs "
39
+ "replacement (default: ask, No). Allowed: yes|no."
40
+ ),
41
+ ),
34
42
  ):
35
43
  """Build and deploy in one command."""
36
44
  from agentkit.toolkit.executors import LifecycleExecutor
@@ -38,6 +46,9 @@ def launch_command(
38
46
  from agentkit.toolkit.context import ExecutionContext
39
47
  from agentkit.toolkit.models import PreflightMode
40
48
  from agentkit.toolkit.config.global_config import get_global_config
49
+ from agentkit.toolkit.runtime_recreate_policy import (
50
+ parse_runtime_recreate_policy,
51
+ )
41
52
 
42
53
  console.print("[green]Launching agent...[/green]")
43
54
 
@@ -80,11 +91,18 @@ def launch_command(
80
91
  except Exception:
81
92
  pass
82
93
 
94
+ try:
95
+ runtime_recreate_policy = parse_runtime_recreate_policy(recreate_runtime)
96
+ except ValueError as exc:
97
+ console.print(f"[red]{exc}[/red]")
98
+ raise typer.Exit(2)
99
+
83
100
  executor = LifecycleExecutor(reporter=reporter)
84
101
  result = executor.launch(
85
102
  config_file=str(config_file),
86
103
  platform=platform,
87
104
  preflight_mode=resolved_mode,
105
+ runtime_recreate_policy=runtime_recreate_policy,
88
106
  )
89
107
 
90
108
  # Format output
@@ -30,6 +30,10 @@ Does NOT:
30
30
  from typing import Optional, Dict, Any
31
31
  from agentkit.toolkit.models import DeployResult, PreflightMode
32
32
  from agentkit.toolkit.reporter import Reporter
33
+ from agentkit.toolkit.runtime_recreate_policy import (
34
+ RuntimeRecreatePolicy,
35
+ normalize_runtime_recreate_policy,
36
+ )
33
37
  from .base_executor import BaseExecutor
34
38
 
35
39
 
@@ -62,6 +66,7 @@ class DeployExecutor(BaseExecutor):
62
66
  config_dict: Optional[Dict[str, Any]] = None,
63
67
  config_file: Optional[str] = None,
64
68
  preflight_mode: PreflightMode = PreflightMode.PROMPT,
69
+ runtime_recreate_policy: RuntimeRecreatePolicy = "prompt",
65
70
  ) -> DeployResult:
66
71
  """
67
72
  Execute deployment operation.
@@ -79,6 +84,7 @@ class DeployExecutor(BaseExecutor):
79
84
  config_dict: Configuration dictionary (highest priority)
80
85
  config_file: Path to configuration file
81
86
  preflight_mode: How to handle missing cloud services (default: PROMPT)
87
+ runtime_recreate_policy: Whether delete/recreate recovery is allowed.
82
88
 
83
89
  Returns:
84
90
  DeployResult: Deployment result from Strategy (no transformation applied)
@@ -90,6 +96,9 @@ class DeployExecutor(BaseExecutor):
90
96
  """
91
97
  token = None
92
98
  try:
99
+ runtime_recreate_policy = normalize_runtime_recreate_policy(
100
+ runtime_recreate_policy
101
+ )
93
102
  # Override preflight_mode from global config defaults if configured
94
103
  try:
95
104
  from agentkit.toolkit.config.global_config import get_global_config
@@ -129,6 +138,7 @@ class DeployExecutor(BaseExecutor):
129
138
  )
130
139
 
131
140
  strategy = self._get_strategy(launch_type, config_manager=config)
141
+ strategy.runtime_recreate_policy = runtime_recreate_policy
132
142
  strategy_config = self._get_strategy_config_object(config, launch_type)
133
143
 
134
144
  self.logger.info(f"Starting deployment with {launch_type} strategy...")
@@ -28,6 +28,10 @@ from .deploy_executor import DeployExecutor
28
28
  from .status_executor import StatusExecutor
29
29
  from agentkit.toolkit.models import LifecycleResult, PreflightMode, PreflightResult
30
30
  from agentkit.toolkit.reporter import Reporter
31
+ from agentkit.toolkit.runtime_recreate_policy import (
32
+ RuntimeRecreatePolicy,
33
+ normalize_runtime_recreate_policy,
34
+ )
31
35
 
32
36
 
33
37
  class LifecycleExecutor(BaseExecutor):
@@ -124,6 +128,7 @@ class LifecycleExecutor(BaseExecutor):
124
128
  config_file: Optional[Union[str, Path]] = None,
125
129
  platform: str = "auto",
126
130
  preflight_mode: PreflightMode = PreflightMode.PROMPT,
131
+ runtime_recreate_policy: RuntimeRecreatePolicy = "prompt",
127
132
  ) -> LifecycleResult:
128
133
  """
129
134
  Launch an Agent service (build + deploy in one step).
@@ -141,6 +146,7 @@ class LifecycleExecutor(BaseExecutor):
141
146
  the Docker build target platform and is independent from the
142
147
  launch_type (local/cloud/hybrid) configured in agentkit.yaml.
143
148
  preflight_mode: How to handle missing cloud services (default: PROMPT)
149
+ runtime_recreate_policy: Whether delete/recreate recovery is allowed.
144
150
 
145
151
  Returns:
146
152
  LifecycleResult: Contains build_result and deploy_result with endpoint information
@@ -151,6 +157,9 @@ class LifecycleExecutor(BaseExecutor):
151
157
  """
152
158
  token = None
153
159
  try:
160
+ runtime_recreate_policy = normalize_runtime_recreate_policy(
161
+ runtime_recreate_policy
162
+ )
154
163
  self.reporter.info("🚀 Starting launch operation...")
155
164
 
156
165
  # Preflight check: verify required cloud services for both build and deploy
@@ -206,6 +215,7 @@ class LifecycleExecutor(BaseExecutor):
206
215
  config_dict=config_dict,
207
216
  config_file=config_file,
208
217
  preflight_mode=PreflightMode.SKIP,
218
+ runtime_recreate_policy=runtime_recreate_policy,
209
219
  )
210
220
 
211
221
  if not deploy_result.success:
@@ -28,6 +28,7 @@ from typing import Any, Callable, Dict, Optional, Union
28
28
 
29
29
  from ..models import LifecycleResult
30
30
  from ..reporter import Reporter
31
+ from ..runtime_recreate_policy import RuntimeRecreatePolicy
31
32
  from .config_builder import build_agentkit_config
32
33
  from .env_mapping import to_runtime_env
33
34
 
@@ -202,6 +203,7 @@ def deploy_harness(
202
203
  allowed_id: Optional[str] = None,
203
204
  reporter: Optional[Reporter] = None,
204
205
  on_conflict: Optional[Callable[[Dict[str, Any]], bool]] = None,
206
+ runtime_recreate_policy: RuntimeRecreatePolicy = "prompt",
205
207
  ) -> LifecycleResult:
206
208
  """Deploy a harness spec as an AgentKit runtime (cloud build, no local Docker).
207
209
 
@@ -234,6 +236,7 @@ def deploy_harness(
234
236
  reporter: Progress reporter forwarded to the launch (default: silent).
235
237
  on_conflict: Callback consulted when a single same-name harness exists;
236
238
  returns True to update it, False to abort.
239
+ runtime_recreate_policy: Whether delete/recreate recovery is allowed.
237
240
 
238
241
  Returns:
239
242
  LifecycleResult: the build+deploy result from ``sdk.launch``.
@@ -379,6 +382,7 @@ def deploy_harness(
379
382
  result = launch(
380
383
  config_dict=cfg,
381
384
  preflight_mode=PreflightMode.WARN,
385
+ runtime_recreate_policy=runtime_recreate_policy,
382
386
  reporter=reporter,
383
387
  )
384
388
  finally: