@qingflow-tech/qingflow-cli 1.1.1 → 1.1.33

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 (120) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/pyproject.toml +1 -1
  4. package/skills/qingflow-cli/SKILL.md +59 -45
  5. package/skills/qingflow-cli/manifest.yaml +1 -1
  6. package/skills/qingflow-cli/reference/00-INDEX.md +35 -0
  7. package/skills/qingflow-cli/reference/QINGFLOW_CLI_BUILDER_APP_DELIVERY_WORKFLOW.md +21 -477
  8. package/skills/qingflow-cli/reference/QINGFLOW_CLI_BUILDER_VIEWS_WORKFLOW.md +44 -290
  9. package/skills/qingflow-cli/reference/QINGFLOW_CLI_SCHEMA_APPLY_FIELD_TYPES_AND_SCENARIOS.md +11 -102
  10. package/skills/qingflow-cli/reference/builder/10-build-single-app.md +57 -0
  11. package/skills/qingflow-cli/reference/builder/20-build-complete-system.md +84 -0
  12. package/skills/qingflow-cli/reference/builder/30-schema-fields.md +317 -0
  13. package/skills/qingflow-cli/reference/builder/40-layout.md +70 -0
  14. package/skills/qingflow-cli/reference/builder/50-views.md +540 -0
  15. package/skills/qingflow-cli/reference/builder/60-charts.md +328 -0
  16. package/skills/qingflow-cli/reference/builder/70-portal.md +372 -0
  17. package/skills/qingflow-cli/reference/builder/80-buttons-associated-resources.md +148 -0
  18. package/skills/qingflow-cli/reference/builder/90-workflow.md +41 -0
  19. package/skills/qingflow-cli/reference/builder/99-publish-verify.md +64 -0
  20. package/skills/qingflow-cli/reference/builder/README.md +62 -0
  21. package/skills/qingflow-cli/reference/builder/code-integrations/README.md +130 -0
  22. package/skills/qingflow-cli/reference/builder/code-integrations/code-block.md +66 -0
  23. package/skills/qingflow-cli/reference/builder/code-integrations/q-linker.md +77 -0
  24. package/skills/qingflow-cli/reference/builder/reference/app-delivery-sop.md +511 -0
  25. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/README.md +308 -0
  26. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/build-complete-system.md +819 -0
  27. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/build-single-app.md +836 -0
  28. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/complete-system-development-guide.md +137 -0
  29. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/create-app.md +203 -0
  30. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/environments.md +63 -0
  31. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/flow-actors-and-permissions.md +142 -0
  32. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/gotchas.md +116 -0
  33. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/match-rules.md +114 -0
  34. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/public-surface-sync.md +75 -0
  35. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/single-app-development-guide.md +69 -0
  36. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/solution-playbooks.md +52 -0
  37. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/tool-selection.md +113 -0
  38. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/update-flow.md +7 -0
  39. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/update-layout.md +7 -0
  40. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/update-schema.md +7 -0
  41. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/update-views.md +7 -0
  42. package/skills/qingflow-cli/reference/builder/reference/match-rules.md +229 -0
  43. package/skills/qingflow-cli/reference/builder/reference/workspace-icons.md +89 -0
  44. package/skills/qingflow-cli/reference/builder/workflow/01-overview.md +47 -0
  45. package/skills/qingflow-cli/reference/builder/workflow/02-update-mode.md +63 -0
  46. package/skills/qingflow-cli/reference/builder/workflow/03-flow-patterns.md +59 -0
  47. package/skills/qingflow-cli/reference/builder/workflow/04-stage1-business-modeling.md +131 -0
  48. package/skills/qingflow-cli/reference/builder/workflow/05-stage2-members-roles.md +29 -0
  49. package/skills/qingflow-cli/reference/builder/workflow/06-stage3-build-spec.md +217 -0
  50. package/skills/qingflow-cli/reference/builder/workflow/07-stage4-validate-spec.md +42 -0
  51. package/skills/qingflow-cli/reference/builder/workflow/08-stage5-apply-verify.md +67 -0
  52. package/skills/qingflow-cli/reference/builder/workflow/09-stage6-summary.md +88 -0
  53. package/skills/qingflow-cli/reference/builder/workflow/10-node-config-reference.md +93 -0
  54. package/skills/qingflow-cli/reference/builder/workflow/11-troubleshooting.md +17 -0
  55. package/skills/qingflow-cli/reference/builder/workflow/README.md +88 -0
  56. package/skills/qingflow-cli/reference/builder/workflow/workflow-schema.json +1754 -0
  57. package/skills/qingflow-cli/reference/charts_upsert_dashboard_starter.example.json +81 -0
  58. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_ADMIN_CHEATSHEET.md +94 -0
  59. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_DATA_RETRIEVAL_WORKFLOW.md +139 -0
  60. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_EXPLORATION_REPORT.md +84 -0
  61. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_FIELD_DATA_TYPES.md +129 -0
  62. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_MEMBER_CHEATSHEET.md +195 -0
  63. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_ONE_SHOT_CHEATSHEET.md +159 -0
  64. package/skills/qingflow-cli/reference/examples/README.md +17 -0
  65. package/skills/qingflow-cli/reference/examples/associated/associated_resources_semantic_full.example.json +50 -0
  66. package/skills/qingflow-cli/reference/examples/buttons/custom_buttons_advanced.example.json +56 -0
  67. package/skills/qingflow-cli/reference/examples/charts/charts_remove.example.json +1 -0
  68. package/skills/qingflow-cli/reference/examples/charts/charts_reorder.example.json +1 -0
  69. package/skills/qingflow-cli/reference/examples/charts/charts_upsert_bar.example.json +8 -0
  70. package/skills/qingflow-cli/reference/examples/charts/charts_upsert_dashboard_starter.example.json +118 -0
  71. package/skills/qingflow-cli/reference/examples/charts/charts_upsert_minimal.example.json +13 -0
  72. package/skills/qingflow-cli/reference/examples/layout/layout_sections_full.example.json +22 -0
  73. package/skills/qingflow-cli/reference/examples/portal/portal_sections_all_types.example.json +145 -0
  74. package/skills/qingflow-cli/reference/examples/portal/portal_sections_five_types.example.json +126 -0
  75. package/skills/qingflow-cli/reference/examples/portal/portal_sections_standard_workbench.example.json +178 -0
  76. package/skills/qingflow-cli/reference/examples/record/record_insert_all_field_types.example.json +35 -0
  77. package/skills/qingflow-cli/reference/examples/schema/_batch_schema_complex.json +18 -0
  78. package/skills/qingflow-cli/reference/examples/schema/_batch_schema_scalar.json +17 -0
  79. package/skills/qingflow-cli/reference/examples/schema/schema_add_fields_minimal.example.json +7 -0
  80. package/skills/qingflow-cli/reference/examples/schema/schema_apply_add_fields_all_types.json +78 -0
  81. package/skills/qingflow-cli/reference/examples/schema/schema_multi_app_form_relation_layout.example.json +166 -0
  82. package/skills/qingflow-cli/reference/examples/schema/schema_single_app_form_standard.example.json +95 -0
  83. package/skills/qingflow-cli/reference/examples/views/views_batch_full.example.json +159 -0
  84. package/skills/qingflow-cli/reference/examples/views/views_upsert_table_minimal.example.json +42 -0
  85. package/skills/qingflow-cli/reference/portal_sections_all_types.example.json +18 -4
  86. package/skills/qingflow-cli/reference/portal_sections_five_types.example.json +3 -3
  87. package/skills/qingflow-cli/reference/portal_sections_standard_workbench.example.json +57 -7
  88. package/skills/qingflow-cli/reference/record/QINGFLOW_CLI_RECORD_CREATE_WORKFLOW.md +22 -0
  89. package/skills/qingflow-cli/reference/record/QINGFLOW_CLI_RECORD_DELETE_WORKFLOW.md +31 -0
  90. package/skills/qingflow-cli/reference/record/QINGFLOW_CLI_RECORD_IMPORT_WORKFLOW.md +176 -0
  91. package/skills/qingflow-cli/reference/record/QINGFLOW_CLI_RECORD_UPDATE_WORKFLOW.md +167 -0
  92. package/skills/qingflow-cli/reference/record/analysis/README.md +130 -0
  93. package/skills/qingflow-cli/reference/record/analysis/analysis-gotchas.md +91 -0
  94. package/skills/qingflow-cli/reference/record/analysis/analysis-patterns.md +112 -0
  95. package/skills/qingflow-cli/reference/record/analysis/business-context.md +74 -0
  96. package/skills/qingflow-cli/reference/record/analysis/confidence-reporting.md +69 -0
  97. package/skills/qingflow-cli/reference/record/analysis/data-access-playbook.md +106 -0
  98. package/skills/qingflow-cli/reference/record/analysis/pandas-recipes.md +172 -0
  99. package/skills/qingflow-cli/reference/record/analysis/report-format.md +76 -0
  100. package/skills/qingflow-cli/reference/record/insert/README.md +125 -0
  101. package/skills/qingflow-cli/reference/schema_apply_add_fields_all_types.json +1 -1
  102. package/skills/qingflow-cli/reference/task/QINGFLOW_CLI_TASK_CONTEXT_WORKFLOW.md +153 -0
  103. package/skills/qingflow-cli/reference/task/ops/README.md +134 -0
  104. package/skills/qingflow-cli/reference/task/ops/environments.md +43 -0
  105. package/skills/qingflow-cli/reference/task/ops/workflow-usage.md +29 -0
  106. package/skills/qingflow-cli/reference/views_upsert_table_minimal.example.json +42 -7
  107. package/skills/qingflow-cli/scripts/validate_system_build_summary.py +124 -0
  108. package/skills/qingflow-cli/scripts/workflow/diff_flow_spec.py +275 -0
  109. package/skills/qingflow-cli/scripts/workflow/validate_flow_spec.py +605 -0
  110. package/src/qingflow_mcp/builder_facade/models.py +413 -119
  111. package/src/qingflow_mcp/builder_facade/service.py +4211 -676
  112. package/src/qingflow_mcp/cli/commands/builder.py +233 -74
  113. package/src/qingflow_mcp/cli/main.py +34 -0
  114. package/src/qingflow_mcp/public_surface.py +10 -0
  115. package/src/qingflow_mcp/server_app_builder.py +68 -34
  116. package/src/qingflow_mcp/solution/compiler/workflow_compiler.py +173 -0
  117. package/src/qingflow_mcp/solution/executor.py +2 -0
  118. package/src/qingflow_mcp/tools/ai_builder_tools.py +2662 -451
  119. package/src/qingflow_mcp/tools/record_tools.py +23 -11
  120. package/src/qingflow_mcp/tools/task_context_tools.py +35 -11
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from concurrent.futures import ThreadPoolExecutor, as_completed
3
4
  from copy import deepcopy
4
5
  import json
5
6
  import time
@@ -15,7 +16,7 @@ from ..builder_facade.button_style_catalog import (
15
16
  )
16
17
  from ..public_surface import public_builder_contract_tool_names
17
18
  from ..config import DEFAULT_PROFILE
18
- from ..errors import QingflowApiError, backend_code_int
19
+ from ..errors import QingflowApiError, backend_code_int, backend_code_value_int
19
20
  from ..json_types import JSONObject
20
21
  from ..builder_facade.models import (
21
22
  AssociatedResourcesApplyRequest,
@@ -27,6 +28,10 @@ from ..builder_facade.models import (
27
28
  FieldPatch,
28
29
  FieldRemovePatch,
29
30
  FieldUpdatePatch,
31
+ FlowPreset,
32
+ FlowNodePatch,
33
+ FlowPlanRequest,
34
+ FlowTransitionPatch,
30
35
  LayoutApplyMode,
31
36
  LayoutPlanRequest,
32
37
  LayoutPreset,
@@ -45,6 +50,8 @@ from ..builder_facade.models import (
45
50
  ViewUpsertPatch,
46
51
  ViewsPreset,
47
52
  ViewsPlanRequest,
53
+ public_view_partial_payload,
54
+ public_view_upsert_payload,
48
55
  )
49
56
  from ..builder_facade.service import AiBuilderFacade, INTEGRATION_OUTPUT_TARGET_FIELD_TYPES
50
57
  from ..solution.compiler.icon_utils import (
@@ -66,6 +73,7 @@ from .qingbi_report_tools import QingbiReportTools
66
73
  from .role_tools import RoleTools
67
74
  from .solution_tools import SolutionTools
68
75
  from .view_tools import ViewTools
76
+ from .workflow_tools import WorkflowTools
69
77
 
70
78
 
71
79
  def _normalize_builder_view_key(value: str) -> str:
@@ -75,6 +83,52 @@ def _normalize_builder_view_key(value: str) -> str:
75
83
  return raw
76
84
 
77
85
 
86
+ def _payload_get(payload: JSONObject, *keys: str, default: Any = None) -> Any:
87
+ for key in keys:
88
+ if key in payload:
89
+ return payload.get(key)
90
+ return default
91
+
92
+
93
+ def _payload_list(payload: JSONObject, *keys: str, default: list | None = None) -> list:
94
+ value = _payload_get(payload, *keys, default=default if default is not None else [])
95
+ return value if isinstance(value, list) else []
96
+
97
+
98
+ def _payload_bool(payload: JSONObject, *keys: str, default: bool = True) -> bool:
99
+ value = _payload_get(payload, *keys, default=default)
100
+ if isinstance(value, bool):
101
+ return value
102
+ if isinstance(value, str):
103
+ normalized = value.strip().lower()
104
+ if normalized in {"1", "true", "yes", "y", "on"}:
105
+ return True
106
+ if normalized in {"0", "false", "no", "n", "off"}:
107
+ return False
108
+ return bool(value)
109
+
110
+
111
+ def _elapsed_ms(started_at: float) -> int:
112
+ return max(0, int((time.perf_counter() - started_at) * 1000))
113
+
114
+
115
+ def _merge_duration_breakdown(payload: JSONObject, **items: int | None) -> None:
116
+ breakdown = payload.get("duration_breakdown_ms")
117
+ if not isinstance(breakdown, dict):
118
+ breakdown = {}
119
+ payload["duration_breakdown_ms"] = breakdown
120
+ for key, value in items.items():
121
+ if value is None:
122
+ continue
123
+ breakdown[key] = int(value)
124
+
125
+
126
+ def _inline_form_layout_was_handled(payload: JSONObject) -> bool:
127
+ inline_layout = payload.get("inline_form_layout")
128
+ return isinstance(inline_layout, dict) and bool(inline_layout.get("requested"))
129
+
130
+
131
+ PUBLIC_STABLE_FLOW_NODE_TYPES = ["start", "approve", "fill", "copy", "webhook", "end"]
78
132
  BUILDER_APPLY_SCHEMA_VERSION = "builder.apply.v1"
79
133
  BUILDER_APPLY_TOOL_NAMES = {
80
134
  "package_apply",
@@ -89,6 +143,9 @@ BUILDER_APPLY_TOOL_NAMES = {
89
143
  "portal_delete",
90
144
  "app_publish_verify",
91
145
  }
146
+ MULTI_APP_SCHEMA_APPLY_PARALLEL_LIMIT = 10
147
+ VIEW_APPLY_PARALLEL_LIMIT = 20
148
+ PORTAL_INLINE_CHART_MAX_WORKERS = 10
92
149
 
93
150
 
94
151
  class AiBuilderTools(ToolBase):
@@ -109,6 +166,7 @@ class AiBuilderTools(ToolBase):
109
166
  buttons=CustomButtonTools(sessions, backend),
110
167
  packages=PackageTools(sessions, backend),
111
168
  views=ViewTools(sessions, backend),
169
+ workflows=WorkflowTools(sessions, backend),
112
170
  portals=PortalTools(sessions, backend),
113
171
  charts=QingbiReportTools(sessions, backend),
114
172
  roles=RoleTools(sessions, backend),
@@ -116,6 +174,193 @@ class AiBuilderTools(ToolBase):
116
174
  solutions=SolutionTools(sessions, backend),
117
175
  )
118
176
 
177
+ def _apply_app_batch(self, *, tool_name: str, profile: str, apps: list[JSONObject], apply_one) -> JSONObject:
178
+ started_at = time.perf_counter()
179
+ batch_item_apply_ms = 0
180
+ child_total_ms = 0
181
+
182
+ def finish(payload: JSONObject) -> JSONObject:
183
+ _merge_duration_breakdown(
184
+ payload,
185
+ batch_item_apply_ms=batch_item_apply_ms,
186
+ child_total_ms=child_total_ms,
187
+ total_ms=_elapsed_ms(started_at),
188
+ )
189
+ return _attach_builder_apply_envelope(tool_name, payload)
190
+
191
+ if not isinstance(apps, list) or not apps:
192
+ return finish(
193
+ _config_failure(
194
+ tool_name=tool_name,
195
+ message=f"{tool_name} batch mode requires non-empty apps[].",
196
+ fix_hint="Pass apps as a JSON array; each item must include app_key plus that resource's normal payload.",
197
+ details={"expected_shape": {"apps": [{"app_key": "APP_KEY"}]}},
198
+ )
199
+ )
200
+
201
+ app_results: list[JSONObject] = []
202
+ errors: list[JSONObject] = []
203
+ for index, item in enumerate(apps):
204
+ if not isinstance(item, dict):
205
+ error = {
206
+ "index": index,
207
+ "status": "failed",
208
+ "error_code": "APPS_FILE_ITEM_INVALID",
209
+ "message": "apps[] item must be an object",
210
+ "reason_path": f"apps[{index}]",
211
+ }
212
+ errors.append(error)
213
+ app_results.append(error)
214
+ continue
215
+ app_key = str(item.get("app_key") or item.get("appKey") or "").strip()
216
+ if not app_key:
217
+ error = {
218
+ "index": index,
219
+ "status": "failed",
220
+ "error_code": "APPS_FILE_APP_KEY_REQUIRED",
221
+ "message": "apps[] item requires app_key",
222
+ "reason_path": f"apps[{index}].app_key",
223
+ }
224
+ errors.append(error)
225
+ app_results.append(error)
226
+ continue
227
+ try:
228
+ item_started_at = time.perf_counter()
229
+ result = apply_one(index, item, app_key)
230
+ except (QingflowApiError, RuntimeError) as error:
231
+ batch_item_apply_ms += _elapsed_ms(item_started_at)
232
+ api_error = _coerce_api_error(error)
233
+ result = {
234
+ "status": "failed",
235
+ "error_code": f"{tool_name.upper()}_BATCH_ITEM_FAILED",
236
+ "recoverable": True,
237
+ "message": _public_error_message(f"{tool_name.upper()}_BATCH_ITEM_FAILED", api_error),
238
+ "app_key": app_key,
239
+ "normalized_args": {"app_key": app_key},
240
+ "details": {"transport_error": _transport_error_payload(api_error)},
241
+ "request_id": api_error.request_id,
242
+ "backend_code": api_error.backend_code,
243
+ "http_status": None if api_error.http_status == 404 else api_error.http_status,
244
+ }
245
+ else:
246
+ batch_item_apply_ms += _elapsed_ms(item_started_at)
247
+ if isinstance(result, dict):
248
+ child_breakdown = result.get("duration_breakdown_ms")
249
+ child_total = child_breakdown.get("total_ms") if isinstance(child_breakdown, dict) else None
250
+ if isinstance(child_total, (int, float)) and child_total >= 0:
251
+ child_total_ms += int(child_total)
252
+ status = str(result.get("status") or "success") if isinstance(result, dict) else "failed"
253
+ wrapped: JSONObject = {
254
+ "index": index,
255
+ "app_key": app_key,
256
+ "status": status,
257
+ "result": result if isinstance(result, dict) else {"status": "failed", "message": str(result)},
258
+ }
259
+ if status == "failed":
260
+ error = {
261
+ "index": index,
262
+ "app_key": app_key,
263
+ "status": status,
264
+ "error_code": wrapped["result"].get("error_code"),
265
+ "message": wrapped["result"].get("message"),
266
+ }
267
+ errors.append(error)
268
+ wrapped["error"] = error
269
+ app_results.append(wrapped)
270
+
271
+ partial = sum(1 for item in app_results if str(item.get("status") or "") == "partial_success")
272
+ succeeded = sum(1 for item in app_results if str(item.get("status") or "") in {"success", "partial_success"})
273
+ failed = len(app_results) - succeeded
274
+ status = "failed" if succeeded == 0 else "partial_success" if failed > 0 or partial > 0 else "success"
275
+ write_executed = any(
276
+ isinstance(item.get("result"), dict) and bool(item["result"].get("write_executed"))
277
+ for item in app_results
278
+ )
279
+ payload: JSONObject = {
280
+ "status": status,
281
+ "error_code": None if status == "success" else f"{tool_name.upper()}_BATCH_PARTIAL" if succeeded else f"{tool_name.upper()}_BATCH_FAILED",
282
+ "recoverable": failed > 0 or partial > 0,
283
+ "message": (
284
+ f"applied {tool_name} to {succeeded}/{len(app_results)} apps"
285
+ if status != "success"
286
+ else f"applied {tool_name} to {succeeded} apps"
287
+ ),
288
+ "normalized_args": {"apps": apps},
289
+ "apps": app_results,
290
+ "errors": errors,
291
+ "verification": {
292
+ "batch_verified": failed == 0 and partial == 0,
293
+ "succeeded": succeeded,
294
+ "partial": partial,
295
+ "failed": failed,
296
+ },
297
+ "write_executed": write_executed,
298
+ "write_succeeded": write_executed and failed == 0 and partial == 0,
299
+ "safe_to_retry": not write_executed,
300
+ }
301
+ return finish(payload)
302
+
303
+ def _read_app_batch(self, *, tool_name: str, profile: str, app_keys: list[str], read_one) -> JSONObject:
304
+ normalized_keys = [str(item).strip() for item in app_keys if str(item).strip()]
305
+ if not normalized_keys:
306
+ return _config_failure(
307
+ tool_name=tool_name,
308
+ message=f"{tool_name} batch mode requires non-empty app_keys[].",
309
+ fix_hint="Pass app_keys as a non-empty list of app keys.",
310
+ details={"expected_shape": {"app_keys": ["APP_A", "APP_B"]}},
311
+ )
312
+ apps: list[JSONObject] = []
313
+ errors: list[JSONObject] = []
314
+ for index, app_key in enumerate(normalized_keys):
315
+ try:
316
+ result = read_one(app_key)
317
+ except (QingflowApiError, RuntimeError) as error:
318
+ api_error = _coerce_api_error(error)
319
+ result = {
320
+ "status": "failed",
321
+ "error_code": f"{tool_name.upper()}_BATCH_ITEM_FAILED",
322
+ "recoverable": True,
323
+ "message": _public_error_message(f"{tool_name.upper()}_BATCH_ITEM_FAILED", api_error),
324
+ "app_key": app_key,
325
+ "details": {"transport_error": _transport_error_payload(api_error)},
326
+ "request_id": api_error.request_id,
327
+ "backend_code": api_error.backend_code,
328
+ "http_status": None if api_error.http_status == 404 else api_error.http_status,
329
+ }
330
+ status = str(result.get("status") or "success") if isinstance(result, dict) else "failed"
331
+ app_item: JSONObject = {
332
+ "index": index,
333
+ "app_key": app_key,
334
+ "status": status,
335
+ "data": result,
336
+ }
337
+ if status == "failed":
338
+ error = {
339
+ "index": index,
340
+ "app_key": app_key,
341
+ "status": "failed",
342
+ "error_code": result.get("error_code") if isinstance(result, dict) else None,
343
+ "message": result.get("message") if isinstance(result, dict) else str(result),
344
+ }
345
+ app_item["error"] = error
346
+ errors.append(error)
347
+ apps.append(app_item)
348
+ partial = sum(1 for item in apps if str(item.get("status") or "") == "partial_success")
349
+ succeeded = sum(1 for item in apps if str(item.get("status") or "") in {"success", "partial_success"})
350
+ failed = len(apps) - succeeded
351
+ status = "failed" if succeeded == 0 else "partial_success" if failed > 0 or partial > 0 else "success"
352
+ return {
353
+ "status": status,
354
+ "error_code": None if status == "success" else f"{tool_name.upper()}_BATCH_PARTIAL" if succeeded else f"{tool_name.upper()}_BATCH_FAILED",
355
+ "recoverable": failed > 0 or partial > 0,
356
+ "message": f"read {tool_name} for {succeeded}/{len(apps)} apps" if status != "success" else f"read {tool_name} for {succeeded} apps",
357
+ "normalized_args": {"app_keys": normalized_keys},
358
+ "app_keys": normalized_keys,
359
+ "apps": apps,
360
+ "errors": errors,
361
+ "verification": {"batch_verified": failed == 0 and partial == 0, "succeeded": succeeded, "partial": partial, "failed": failed},
362
+ }
363
+
119
364
  def register(self, mcp) -> None:
120
365
  """注册当前工具到 MCP 服务。"""
121
366
  @mcp.tool()
@@ -139,7 +384,6 @@ class AiBuilderTools(ToolBase):
139
384
  profile: str = DEFAULT_PROFILE,
140
385
  package_id: int | None = None,
141
386
  package_name: str | None = None,
142
- create_if_missing: bool = False,
143
387
  icon: str | JSONObject | None = None,
144
388
  color: str | None = None,
145
389
  icon_name: str | None = None,
@@ -153,7 +397,6 @@ class AiBuilderTools(ToolBase):
153
397
  profile=profile,
154
398
  package_id=package_id,
155
399
  package_name=package_name,
156
- create_if_missing=create_if_missing,
157
400
  icon=icon,
158
401
  color=color,
159
402
  icon_name=icon_name,
@@ -271,6 +514,7 @@ class AiBuilderTools(ToolBase):
271
514
  patch_buttons: list[JSONObject] | None = None,
272
515
  remove_buttons: list[JSONObject] | None = None,
273
516
  view_configs: list[JSONObject] | None = None,
517
+ apps: list[JSONObject] | None = None,
274
518
  ) -> JSONObject:
275
519
  return self.app_custom_buttons_apply(
276
520
  profile=profile,
@@ -279,6 +523,7 @@ class AiBuilderTools(ToolBase):
279
523
  patch_buttons=patch_buttons or [],
280
524
  remove_buttons=remove_buttons or [],
281
525
  view_configs=view_configs or [],
526
+ apps=apps,
282
527
  )
283
528
 
284
529
  @mcp.tool()
@@ -290,6 +535,7 @@ class AiBuilderTools(ToolBase):
290
535
  remove_associated_item_ids: list[int] | None = None,
291
536
  reorder_associated_item_ids: list[int] | None = None,
292
537
  view_configs: list[JSONObject] | None = None,
538
+ apps: list[JSONObject] | None = None,
293
539
  ) -> JSONObject:
294
540
  return self.app_associated_resources_apply(
295
541
  profile=profile,
@@ -299,15 +545,16 @@ class AiBuilderTools(ToolBase):
299
545
  remove_associated_item_ids=remove_associated_item_ids or [],
300
546
  reorder_associated_item_ids=reorder_associated_item_ids or [],
301
547
  view_configs=view_configs or [],
548
+ apps=apps,
302
549
  )
303
550
 
304
551
  @mcp.tool()
305
- def app_get(profile: str = DEFAULT_PROFILE, app_key: str = "") -> JSONObject:
306
- return self.app_get(profile=profile, app_key=app_key)
552
+ def app_get(profile: str = DEFAULT_PROFILE, app_key: str = "", app_keys: list[str] | None = None) -> JSONObject:
553
+ return self.app_get(profile=profile, app_key=app_key, app_keys=app_keys)
307
554
 
308
555
  @mcp.tool()
309
- def app_get_fields(profile: str = DEFAULT_PROFILE, app_key: str = "") -> JSONObject:
310
- return self.app_get_fields(profile=profile, app_key=app_key)
556
+ def app_get_fields(profile: str = DEFAULT_PROFILE, app_key: str = "", app_keys: list[str] | None = None) -> JSONObject:
557
+ return self.app_get_fields(profile=profile, app_key=app_key, app_keys=app_keys)
311
558
 
312
559
  @mcp.tool()
313
560
  def app_repair_code_blocks(
@@ -319,20 +566,28 @@ class AiBuilderTools(ToolBase):
319
566
  return self.app_repair_code_blocks(profile=profile, app_key=app_key, field=field, apply=apply)
320
567
 
321
568
  @mcp.tool()
322
- def app_get_layout(profile: str = DEFAULT_PROFILE, app_key: str = "") -> JSONObject:
323
- return self.app_get_layout(profile=profile, app_key=app_key)
569
+ def app_get_layout(profile: str = DEFAULT_PROFILE, app_key: str = "", app_keys: list[str] | None = None) -> JSONObject:
570
+ return self.app_get_layout(profile=profile, app_key=app_key, app_keys=app_keys)
571
+
572
+ @mcp.tool()
573
+ def app_get_views(profile: str = DEFAULT_PROFILE, app_key: str = "", app_keys: list[str] | None = None) -> JSONObject:
574
+ return self.app_get_views(profile=profile, app_key=app_key, app_keys=app_keys)
324
575
 
325
576
  @mcp.tool()
326
- def app_get_views(profile: str = DEFAULT_PROFILE, app_key: str = "") -> JSONObject:
327
- return self.app_get_views(profile=profile, app_key=app_key)
577
+ def app_get_flow(profile: str = DEFAULT_PROFILE, app_key: str = "", app_keys: list[str] | None = None) -> JSONObject:
578
+ return self.app_get_flow(profile=profile, app_key=app_key, app_keys=app_keys)
328
579
 
329
580
  @mcp.tool()
330
- def app_get_flow(profile: str = DEFAULT_PROFILE, app_key: str = "") -> JSONObject:
331
- return self.app_get_flow(profile=profile, app_key=app_key)
581
+ def app_get_charts(profile: str = DEFAULT_PROFILE, app_key: str = "", app_keys: list[str] | None = None) -> JSONObject:
582
+ return self.app_get_charts(profile=profile, app_key=app_key, app_keys=app_keys)
332
583
 
333
584
  @mcp.tool()
334
- def app_get_charts(profile: str = DEFAULT_PROFILE, app_key: str = "") -> JSONObject:
335
- return self.app_get_charts(profile=profile, app_key=app_key)
585
+ def app_get_buttons(profile: str = DEFAULT_PROFILE, app_key: str = "", app_keys: list[str] | None = None) -> JSONObject:
586
+ return self.app_get_buttons(profile=profile, app_key=app_key, app_keys=app_keys)
587
+
588
+ @mcp.tool()
589
+ def app_get_associated_resources(profile: str = DEFAULT_PROFILE, app_key: str = "", app_keys: list[str] | None = None) -> JSONObject:
590
+ return self.app_get_associated_resources(profile=profile, app_key=app_key, app_keys=app_keys)
336
591
 
337
592
  @mcp.tool()
338
593
  def portal_list(profile: str = DEFAULT_PROFILE) -> JSONObject:
@@ -370,19 +625,19 @@ class AiBuilderTools(ToolBase):
370
625
  icon_color: str | None = None,
371
626
  icon_config: JSONObject | None = None,
372
627
  visibility: JSONObject | None = None,
373
- create_if_missing: bool = False,
374
628
  publish: bool = True,
629
+ form: list[JSONObject] | None = None,
375
630
  add_fields: list[JSONObject] | None = None,
376
631
  update_fields: list[JSONObject] | None = None,
377
632
  remove_fields: list[JSONObject] | None = None,
378
633
  apps: list[JSONObject] | None = None,
379
634
  ) -> JSONObject:
380
635
  if apps is not None:
381
- if app_key or app_name or app_title or add_fields or update_fields or remove_fields:
636
+ if app_key or app_name or app_title or form or add_fields or update_fields or remove_fields:
382
637
  return _config_failure(
383
638
  tool_name="app_schema_apply",
384
- message="app_schema_apply multi-app mode accepts package_id/create_if_missing plus apps only.",
385
- fix_hint="Use `apps` for batch mode, or use the single-app arguments without `apps`.",
639
+ message="app_schema_apply multi-app mode accepts package_id plus apps only.",
640
+ fix_hint="Put per-app form in apps[].form when using batch mode.",
386
641
  )
387
642
  if package_id is None:
388
643
  return _config_failure(
@@ -394,9 +649,9 @@ class AiBuilderTools(ToolBase):
394
649
  profile=profile,
395
650
  package_id=package_id,
396
651
  visibility=visibility,
397
- create_if_missing=create_if_missing,
398
652
  publish=publish,
399
653
  apps=apps,
654
+ form=None,
400
655
  add_fields=[],
401
656
  update_fields=[],
402
657
  remove_fields=[],
@@ -406,18 +661,18 @@ class AiBuilderTools(ToolBase):
406
661
  has_app_title = bool((app_title or "").strip())
407
662
  has_package_id = package_id is not None
408
663
  if has_app_key:
409
- if create_if_missing or has_package_id:
664
+ if has_package_id:
410
665
  return _config_failure(
411
666
  tool_name="app_schema_apply",
412
667
  message="app_schema_apply edit mode accepts app_key and optional app_name rename only.",
413
- fix_hint="For existing apps, use `app_key` and optionally `app_name`. For create mode, use `package_id + app_name + create_if_missing=true`.",
668
+ fix_hint="For existing apps, use `app_key` and optionally `app_name`. For create mode, use `package_id + app_name`.",
414
669
  )
415
- elif not (create_if_missing and has_package_id and (has_app_name or has_app_title)):
670
+ elif not (has_package_id and (has_app_name or has_app_title)):
416
671
  return _config_failure(
417
672
  tool_name="app_schema_apply",
418
- message="app_schema_apply create mode requires package_id, app_name, and create_if_missing=true.",
419
- fix_hint="Use `app_key` for existing apps, or pass `package_id + app_name + create_if_missing=true` to create a new app.",
420
- )
673
+ message="app_schema_apply create mode requires package_id and app_name.",
674
+ fix_hint="Use `app_key` for existing apps, or pass `package_id + app_name` to create a new app.",
675
+ )
421
676
  return self.app_schema_apply(
422
677
  profile=profile,
423
678
  app_key=app_key,
@@ -430,12 +685,12 @@ class AiBuilderTools(ToolBase):
430
685
  icon_color=icon_color,
431
686
  icon_config=icon_config,
432
687
  visibility=visibility,
433
- create_if_missing=create_if_missing,
434
688
  publish=publish,
689
+ form=form or [],
435
690
  add_fields=add_fields or [],
436
691
  update_fields=update_fields or [],
437
692
  remove_fields=remove_fields or [],
438
- apps=[],
693
+ apps=None,
439
694
  )
440
695
 
441
696
  @mcp.tool()
@@ -445,8 +700,9 @@ class AiBuilderTools(ToolBase):
445
700
  mode: str = "merge",
446
701
  publish: bool = True,
447
702
  sections: list[JSONObject] | None = None,
703
+ apps: list[JSONObject] | None = None,
448
704
  ) -> JSONObject:
449
- return self.app_layout_apply(profile=profile, app_key=app_key, mode=mode, publish=publish, sections=sections or [])
705
+ return self.app_layout_apply(profile=profile, app_key=app_key, mode=mode, publish=publish, sections=sections or [], apps=apps)
450
706
 
451
707
  @mcp.tool()
452
708
  def app_flow_get(
@@ -454,7 +710,7 @@ class AiBuilderTools(ToolBase):
454
710
  app_key: str = "",
455
711
  version_id: str = "",
456
712
  ) -> JSONObject:
457
- return self.app_get_flow(profile=profile, app_key=app_key, version_id=version_id or None)
713
+ return self.app_flow_get(profile=profile, app_key=app_key, version_id=version_id or None)
458
714
 
459
715
  @mcp.tool()
460
716
  def app_flow_get_schema(profile: str = DEFAULT_PROFILE, schema_version: str = "") -> JSONObject:
@@ -464,18 +720,26 @@ class AiBuilderTools(ToolBase):
464
720
  def app_flow_apply(
465
721
  profile: str = DEFAULT_PROFILE,
466
722
  app_key: str = "",
723
+ mode: str = "replace",
467
724
  publish: bool = True,
725
+ nodes: list[JSONObject] | None = None,
726
+ transitions: list[JSONObject] | None = None,
468
727
  spec: JSONObject | None = None,
469
728
  idempotency_key: str = "",
470
729
  schema_version: str = "",
730
+ patch_nodes: list[JSONObject] | None = None,
471
731
  ) -> JSONObject:
472
732
  return self.app_flow_apply(
473
733
  profile=profile,
474
734
  app_key=app_key,
735
+ mode=mode,
475
736
  publish=publish,
476
- spec=spec or {},
737
+ nodes=nodes or [],
738
+ transitions=transitions or [],
739
+ spec=spec,
477
740
  idempotency_key=idempotency_key or None,
478
741
  schema_version=schema_version or None,
742
+ patch_nodes=patch_nodes,
479
743
  )
480
744
 
481
745
  @mcp.tool()
@@ -486,6 +750,7 @@ class AiBuilderTools(ToolBase):
486
750
  upsert_views: list[JSONObject] | None = None,
487
751
  patch_views: list[JSONObject] | None = None,
488
752
  remove_views: list[str] | None = None,
753
+ apps: list[JSONObject] | None = None,
489
754
  ) -> JSONObject:
490
755
  return self.app_views_apply(
491
756
  profile=profile,
@@ -494,6 +759,7 @@ class AiBuilderTools(ToolBase):
494
759
  upsert_views=upsert_views or [],
495
760
  patch_views=patch_views or [],
496
761
  remove_views=remove_views or [],
762
+ apps=apps,
497
763
  )
498
764
 
499
765
  @mcp.tool()
@@ -504,6 +770,7 @@ class AiBuilderTools(ToolBase):
504
770
  patch_charts: list[JSONObject] | None = None,
505
771
  remove_chart_ids: list[str] | None = None,
506
772
  reorder_chart_ids: list[str] | None = None,
773
+ apps: list[JSONObject] | None = None,
507
774
  ) -> JSONObject:
508
775
  return self.app_charts_apply(
509
776
  profile=profile,
@@ -512,6 +779,7 @@ class AiBuilderTools(ToolBase):
512
779
  patch_charts=patch_charts or [],
513
780
  remove_chart_ids=remove_chart_ids or [],
514
781
  reorder_chart_ids=reorder_chart_ids or [],
782
+ apps=apps,
515
783
  )
516
784
 
517
785
  @mcp.tool()
@@ -533,6 +801,7 @@ class AiBuilderTools(ToolBase):
533
801
  dash_global_config: JSONObject | None = None,
534
802
  config: JSONObject | None = None,
535
803
  payload: JSONObject | None = None,
804
+ patch_sections: list[JSONObject] | None = None,
536
805
  ) -> JSONObject:
537
806
  payload = payload if isinstance(payload, dict) else {}
538
807
  has_dash_key = bool((dash_key or "").strip())
@@ -570,6 +839,7 @@ class AiBuilderTools(ToolBase):
570
839
  dash_global_config=dash_global_config,
571
840
  config=config or {},
572
841
  payload=payload,
842
+ patch_sections=patch_sections,
573
843
  )
574
844
 
575
845
  @mcp.tool(description=self._high_risk_tool_description(operation="delete", target="portal"))
@@ -583,11 +853,13 @@ class AiBuilderTools(ToolBase):
583
853
  def app_publish_verify(
584
854
  profile: str = DEFAULT_PROFILE,
585
855
  app_key: str = "",
856
+ app_keys: list[str] | None = None,
586
857
  expected_package_id: int | None = None,
587
858
  ) -> JSONObject:
588
859
  return self.app_publish_verify(
589
860
  profile=profile,
590
861
  app_key=app_key,
862
+ app_keys=app_keys,
591
863
  expected_package_id=expected_package_id,
592
864
  )
593
865
 
@@ -759,7 +1031,6 @@ class AiBuilderTools(ToolBase):
759
1031
  profile: str,
760
1032
  package_id: int | None = None,
761
1033
  package_name: str | None = None,
762
- create_if_missing: bool = False,
763
1034
  icon: str | JSONObject | None = None,
764
1035
  color: str | None = None,
765
1036
  icon_name: str | None = None,
@@ -790,14 +1061,13 @@ class AiBuilderTools(ToolBase):
790
1061
  tool_name="package_apply",
791
1062
  icon=icon,
792
1063
  color=color,
793
- creating=package_id is None and bool(create_if_missing),
1064
+ creating=package_id is None and bool(str(package_name or "").strip()),
794
1065
  )
795
1066
  if icon_failure is not None:
796
1067
  return _attach_builder_apply_envelope("package_apply", icon_failure)
797
1068
  normalized_args = {
798
1069
  "package_id": package_id,
799
1070
  **({"package_name": package_name} if str(package_name or "").strip() else {}),
800
- "create_if_missing": bool(create_if_missing),
801
1071
  **({"icon": icon} if icon else {}),
802
1072
  **({"color": color} if color else {}),
803
1073
  **({"visibility": visibility_patch.model_dump(mode="json")} if visibility_patch is not None else {}),
@@ -809,7 +1079,6 @@ class AiBuilderTools(ToolBase):
809
1079
  profile=profile,
810
1080
  package_id=package_id,
811
1081
  package_name=package_name,
812
- create_if_missing=create_if_missing,
813
1082
  icon=icon,
814
1083
  color=color,
815
1084
  visibility=visibility_patch,
@@ -1063,8 +1332,24 @@ class AiBuilderTools(ToolBase):
1063
1332
  patch_buttons: list[JSONObject] | None = None,
1064
1333
  remove_buttons: list[JSONObject],
1065
1334
  view_configs: list[JSONObject] | None = None,
1335
+ apps: list[JSONObject] | None = None,
1066
1336
  ) -> JSONObject:
1067
1337
  """执行应用按钮 apply 逻辑。"""
1338
+ if apps is not None:
1339
+ return self._apply_app_batch(
1340
+ tool_name="app_custom_buttons_apply",
1341
+ profile=profile,
1342
+ apps=apps,
1343
+ apply_one=lambda _index, item, item_app_key: self.app_custom_buttons_apply(
1344
+ profile=profile,
1345
+ app_key=item_app_key,
1346
+ upsert_buttons=_payload_list(item, "upsert_buttons", "upsertButtons", "buttons", default=upsert_buttons or []),
1347
+ patch_buttons=_payload_list(item, "patch_buttons", "patchButtons", default=patch_buttons or []),
1348
+ remove_buttons=_payload_list(item, "remove_buttons", "removeButtons", default=remove_buttons or []),
1349
+ view_configs=_payload_list(item, "view_configs", "viewConfigs", default=view_configs or []),
1350
+ apps=None,
1351
+ ),
1352
+ )
1068
1353
  raw_request = {
1069
1354
  "app_key": app_key,
1070
1355
  "upsert_buttons": upsert_buttons,
@@ -1117,8 +1402,35 @@ class AiBuilderTools(ToolBase):
1117
1402
  reorder_associated_item_ids: list[int],
1118
1403
  view_configs: list[JSONObject],
1119
1404
  patch_resources: list[JSONObject] | None = None,
1405
+ apps: list[JSONObject] | None = None,
1120
1406
  ) -> JSONObject:
1121
1407
  """执行应用关联资源 apply 逻辑。"""
1408
+ if apps is not None:
1409
+ return self._apply_app_batch(
1410
+ tool_name="app_associated_resources_apply",
1411
+ profile=profile,
1412
+ apps=apps,
1413
+ apply_one=lambda _index, item, item_app_key: self.app_associated_resources_apply(
1414
+ profile=profile,
1415
+ app_key=item_app_key,
1416
+ upsert_resources=_payload_list(item, "upsert_resources", "upsertResources", "resources", default=upsert_resources or []),
1417
+ patch_resources=_payload_list(item, "patch_resources", "patchResources", default=patch_resources or []),
1418
+ remove_associated_item_ids=_payload_list(
1419
+ item,
1420
+ "remove_associated_item_ids",
1421
+ "removeAssociatedItemIds",
1422
+ default=remove_associated_item_ids or [],
1423
+ ),
1424
+ reorder_associated_item_ids=_payload_list(
1425
+ item,
1426
+ "reorder_associated_item_ids",
1427
+ "reorderAssociatedItemIds",
1428
+ default=reorder_associated_item_ids or [],
1429
+ ),
1430
+ view_configs=_payload_list(item, "view_configs", "viewConfigs", default=view_configs or []),
1431
+ apps=None,
1432
+ ),
1433
+ )
1122
1434
  raw_request = {
1123
1435
  "app_key": app_key,
1124
1436
  "upsert_resources": upsert_resources,
@@ -1281,8 +1593,15 @@ class AiBuilderTools(ToolBase):
1281
1593
  ))
1282
1594
 
1283
1595
  @tool_cn_name("应用详情查询")
1284
- def app_get(self, *, profile: str, app_key: str) -> JSONObject:
1596
+ def app_get(self, *, profile: str, app_key: str, app_keys: list[str] | None = None) -> JSONObject:
1285
1597
  """执行应用相关逻辑。"""
1598
+ if app_keys is not None:
1599
+ return self._read_app_batch(
1600
+ tool_name="app_get",
1601
+ profile=profile,
1602
+ app_keys=app_keys,
1603
+ read_one=lambda item_app_key: self.app_get(profile=profile, app_key=item_app_key, app_keys=None),
1604
+ )
1286
1605
  normalized_args = {"app_key": app_key}
1287
1606
  return _publicize_package_fields(_safe_tool_call(
1288
1607
  lambda: self._facade.app_get(profile=profile, app_key=app_key),
@@ -1303,8 +1622,15 @@ class AiBuilderTools(ToolBase):
1303
1622
  )
1304
1623
 
1305
1624
  @tool_cn_name("应用字段详情查询")
1306
- def app_get_fields(self, *, profile: str, app_key: str) -> JSONObject:
1625
+ def app_get_fields(self, *, profile: str, app_key: str, app_keys: list[str] | None = None) -> JSONObject:
1307
1626
  """执行应用相关逻辑。"""
1627
+ if app_keys is not None:
1628
+ return self._read_app_batch(
1629
+ tool_name="app_get_fields",
1630
+ profile=profile,
1631
+ app_keys=app_keys,
1632
+ read_one=lambda item_app_key: self.app_get_fields(profile=profile, app_key=item_app_key, app_keys=None),
1633
+ )
1308
1634
  normalized_args = {"app_key": app_key}
1309
1635
  return _safe_tool_call(
1310
1636
  lambda: self._facade.app_get_fields(profile=profile, app_key=app_key),
@@ -1343,8 +1669,15 @@ class AiBuilderTools(ToolBase):
1343
1669
  )
1344
1670
 
1345
1671
  @tool_cn_name("应用布局详情查询")
1346
- def app_get_layout(self, *, profile: str, app_key: str) -> JSONObject:
1672
+ def app_get_layout(self, *, profile: str, app_key: str, app_keys: list[str] | None = None) -> JSONObject:
1347
1673
  """执行应用相关逻辑。"""
1674
+ if app_keys is not None:
1675
+ return self._read_app_batch(
1676
+ tool_name="app_get_layout",
1677
+ profile=profile,
1678
+ app_keys=app_keys,
1679
+ read_one=lambda item_app_key: self.app_get_layout(profile=profile, app_key=item_app_key, app_keys=None),
1680
+ )
1348
1681
  normalized_args = {"app_key": app_key}
1349
1682
  return _safe_tool_call(
1350
1683
  lambda: self._facade.app_get_layout(profile=profile, app_key=app_key),
@@ -1365,8 +1698,15 @@ class AiBuilderTools(ToolBase):
1365
1698
  )
1366
1699
 
1367
1700
  @tool_cn_name("应用视图详情查询")
1368
- def app_get_views(self, *, profile: str, app_key: str) -> JSONObject:
1701
+ def app_get_views(self, *, profile: str, app_key: str, app_keys: list[str] | None = None) -> JSONObject:
1369
1702
  """执行应用相关逻辑。"""
1703
+ if app_keys is not None:
1704
+ return self._read_app_batch(
1705
+ tool_name="app_get_views",
1706
+ profile=profile,
1707
+ app_keys=app_keys,
1708
+ read_one=lambda item_app_key: self.app_get_views(profile=profile, app_key=item_app_key, app_keys=None),
1709
+ )
1370
1710
  normalized_args = {"app_key": app_key}
1371
1711
  return _safe_tool_call(
1372
1712
  lambda: self._facade.app_get_views(profile=profile, app_key=app_key),
@@ -1375,25 +1715,53 @@ class AiBuilderTools(ToolBase):
1375
1715
  suggested_next_call={"tool_name": "app_get_views", "arguments": {"profile": profile, "app_key": app_key}},
1376
1716
  )
1377
1717
 
1378
- @tool_cn_name("Workflow Spec Schema")
1379
- def app_flow_get_schema(self, *, profile: str, schema_version: str | None = None) -> JSONObject:
1380
- normalized_args = {"schema_version": schema_version}
1718
+ @tool_cn_name("应用流程摘要读取")
1719
+ def app_read_flow_summary(self, *, profile: str, app_key: str) -> JSONObject:
1720
+ """执行应用相关逻辑。"""
1721
+ normalized_args = {"app_key": app_key}
1381
1722
  return _safe_tool_call(
1382
- lambda: self._facade.flow_get_schema(profile=profile, schema_version=schema_version),
1383
- error_code="FLOW_SPEC_SCHEMA_FAILED",
1723
+ lambda: self._facade.app_read_flow_summary(profile=profile, app_key=app_key),
1724
+ error_code="FLOW_READ_FAILED",
1384
1725
  normalized_args=normalized_args,
1385
- suggested_next_call={"tool_name": "app_flow_get_schema", "arguments": {"profile": profile, **normalized_args}},
1726
+ suggested_next_call={"tool_name": "app_get_flow", "arguments": {"profile": profile, "app_key": app_key}},
1386
1727
  )
1387
1728
 
1388
- @tool_cn_name("Workflow Spec 读取")
1389
- def app_get_flow(self, *, profile: str, app_key: str, version_id: str | None = None) -> JSONObject:
1729
+ @tool_cn_name("应用流程详情查询")
1730
+ def app_get_flow(self, *, profile: str, app_key: str, app_keys: list[str] | None = None) -> JSONObject:
1390
1731
  """执行应用相关逻辑。"""
1732
+ if app_keys is not None:
1733
+ return self._read_app_batch(
1734
+ tool_name="app_get_flow",
1735
+ profile=profile,
1736
+ app_keys=app_keys,
1737
+ read_one=lambda item_app_key: self.app_get_flow(profile=profile, app_key=item_app_key, app_keys=None),
1738
+ )
1739
+ normalized_args = {"app_key": app_key}
1740
+ return _safe_tool_call(
1741
+ lambda: self._facade.app_get_flow(profile=profile, app_key=app_key),
1742
+ error_code="APP_GET_FLOW_FAILED",
1743
+ normalized_args=normalized_args,
1744
+ suggested_next_call={"tool_name": "app_get_flow", "arguments": {"profile": profile, "app_key": app_key}},
1745
+ )
1746
+
1747
+ @tool_cn_name("应用流程规格查询")
1748
+ def app_flow_get(self, *, profile: str, app_key: str, version_id: str | None = None) -> JSONObject:
1391
1749
  normalized_args = {"app_key": app_key, "version_id": version_id}
1392
1750
  return _safe_tool_call(
1393
1751
  lambda: self._facade.flow_get(profile=profile, app_key=app_key, version_id=version_id),
1394
- error_code="APP_GET_FLOW_FAILED",
1752
+ error_code="APP_FLOW_GET_FAILED",
1753
+ normalized_args=normalized_args,
1754
+ suggested_next_call={"tool_name": "app_flow_get", "arguments": {"profile": profile, **normalized_args}},
1755
+ )
1756
+
1757
+ @tool_cn_name("应用流程规格 Schema 查询")
1758
+ def app_flow_get_schema(self, *, profile: str, schema_version: str | None = None) -> JSONObject:
1759
+ normalized_args = {"schema_version": schema_version}
1760
+ return _safe_tool_call(
1761
+ lambda: self._facade.flow_get_schema(profile=profile, schema_version=schema_version),
1762
+ error_code="APP_FLOW_SCHEMA_GET_FAILED",
1395
1763
  normalized_args=normalized_args,
1396
- suggested_next_call={"tool_name": "app_flow_get", "arguments": {"profile": profile, "app_key": app_key}},
1764
+ suggested_next_call={"tool_name": "app_flow_get_schema", "arguments": {"profile": profile, **normalized_args}},
1397
1765
  )
1398
1766
 
1399
1767
  @tool_cn_name("应用图表摘要读取")
@@ -1408,8 +1776,15 @@ class AiBuilderTools(ToolBase):
1408
1776
  )
1409
1777
 
1410
1778
  @tool_cn_name("应用图表详情查询")
1411
- def app_get_charts(self, *, profile: str, app_key: str) -> JSONObject:
1779
+ def app_get_charts(self, *, profile: str, app_key: str, app_keys: list[str] | None = None) -> JSONObject:
1412
1780
  """执行应用相关逻辑。"""
1781
+ if app_keys is not None:
1782
+ return self._read_app_batch(
1783
+ tool_name="app_get_charts",
1784
+ profile=profile,
1785
+ app_keys=app_keys,
1786
+ read_one=lambda item_app_key: self.app_get_charts(profile=profile, app_key=item_app_key, app_keys=None),
1787
+ )
1413
1788
  normalized_args = {"app_key": app_key}
1414
1789
  return _safe_tool_call(
1415
1790
  lambda: self._facade.app_get_charts(profile=profile, app_key=app_key),
@@ -1418,6 +1793,40 @@ class AiBuilderTools(ToolBase):
1418
1793
  suggested_next_call={"tool_name": "app_get_charts", "arguments": {"profile": profile, "app_key": app_key}},
1419
1794
  )
1420
1795
 
1796
+ @tool_cn_name("自定义按钮读取")
1797
+ def app_get_buttons(self, *, profile: str, app_key: str = "", app_keys: list[str] | None = None) -> JSONObject:
1798
+ if app_keys is not None:
1799
+ return self._read_app_batch(
1800
+ tool_name="app_get_buttons",
1801
+ profile=profile,
1802
+ app_keys=app_keys,
1803
+ read_one=lambda item_app_key: self.app_get_buttons(profile=profile, app_key=item_app_key, app_keys=None),
1804
+ )
1805
+ normalized_args = {"app_key": app_key}
1806
+ return _safe_tool_call(
1807
+ lambda: self._facade.app_get_buttons(profile=profile, app_key=app_key),
1808
+ error_code="APP_GET_BUTTONS_FAILED",
1809
+ normalized_args=normalized_args,
1810
+ suggested_next_call={"tool_name": "app_get_buttons", "arguments": {"profile": profile, "app_key": app_key}},
1811
+ )
1812
+
1813
+ @tool_cn_name("关联资源读取")
1814
+ def app_get_associated_resources(self, *, profile: str, app_key: str = "", app_keys: list[str] | None = None) -> JSONObject:
1815
+ if app_keys is not None:
1816
+ return self._read_app_batch(
1817
+ tool_name="app_get_associated_resources",
1818
+ profile=profile,
1819
+ app_keys=app_keys,
1820
+ read_one=lambda item_app_key: self.app_get_associated_resources(profile=profile, app_key=item_app_key, app_keys=None),
1821
+ )
1822
+ normalized_args = {"app_key": app_key}
1823
+ return _safe_tool_call(
1824
+ lambda: self._facade.app_get_associated_resources(profile=profile, app_key=app_key),
1825
+ error_code="APP_GET_ASSOCIATED_RESOURCES_FAILED",
1826
+ normalized_args=normalized_args,
1827
+ suggested_next_call={"tool_name": "app_get_associated_resources", "arguments": {"profile": profile, "app_key": app_key}},
1828
+ )
1829
+
1421
1830
  @tool_cn_name("门户列表查询")
1422
1831
  def portal_list(self, *, profile: str) -> JSONObject:
1423
1832
  """执行门户相关逻辑。"""
@@ -1489,7 +1898,6 @@ class AiBuilderTools(ToolBase):
1489
1898
  icon: str = "",
1490
1899
  color: str = "",
1491
1900
  visibility: JSONObject | None = None,
1492
- create_if_missing: bool = False,
1493
1901
  add_fields: list[JSONObject],
1494
1902
  update_fields: list[JSONObject],
1495
1903
  remove_fields: list[JSONObject],
@@ -1504,7 +1912,6 @@ class AiBuilderTools(ToolBase):
1504
1912
  icon=icon,
1505
1913
  color=color,
1506
1914
  visibility=visibility,
1507
- create_if_missing=create_if_missing,
1508
1915
  add_fields=add_fields,
1509
1916
  update_fields=update_fields,
1510
1917
  remove_fields=remove_fields,
@@ -1520,7 +1927,6 @@ class AiBuilderTools(ToolBase):
1520
1927
  "icon": icon,
1521
1928
  "color": color,
1522
1929
  "visibility": visibility,
1523
- "create_if_missing": create_if_missing,
1524
1930
  "add_fields": add_fields,
1525
1931
  "update_fields": update_fields,
1526
1932
  "remove_fields": remove_fields,
@@ -1541,7 +1947,6 @@ class AiBuilderTools(ToolBase):
1541
1947
  "icon": icon,
1542
1948
  "color": color,
1543
1949
  "visibility": visibility,
1544
- "create_if_missing": create_if_missing,
1545
1950
  "add_fields": [{"name": "字段名称", "type": "text"}],
1546
1951
  "update_fields": [],
1547
1952
  "remove_fields": [],
@@ -1604,6 +2009,52 @@ class AiBuilderTools(ToolBase):
1604
2009
  suggested_next_call={"tool_name": "app_layout_plan", "arguments": {"profile": profile, **normalized_request}},
1605
2010
  )
1606
2011
 
2012
+ @tool_cn_name("应用流程规划")
2013
+ def app_flow_plan(
2014
+ self,
2015
+ *,
2016
+ profile: str,
2017
+ app_key: str,
2018
+ mode: str = "replace",
2019
+ nodes: list[JSONObject] | None = None,
2020
+ transitions: list[JSONObject] | None = None,
2021
+ preset: str | None = None,
2022
+ ) -> JSONObject:
2023
+ """执行应用相关逻辑。"""
2024
+ try:
2025
+ request = FlowPlanRequest.model_validate(
2026
+ {
2027
+ "app_key": app_key,
2028
+ "mode": mode,
2029
+ "nodes": nodes or [],
2030
+ "transitions": transitions or [],
2031
+ "preset": preset,
2032
+ }
2033
+ )
2034
+ except ValidationError as exc:
2035
+ return _validation_failure(
2036
+ str(exc),
2037
+ tool_name="app_flow_plan",
2038
+ exc=exc,
2039
+ suggested_next_call={
2040
+ "tool_name": "app_flow_plan",
2041
+ "arguments": {
2042
+ "profile": profile,
2043
+ "app_key": app_key,
2044
+ "mode": "replace",
2045
+ "preset": "basic_approval",
2046
+ "nodes": [],
2047
+ "transitions": [],
2048
+ },
2049
+ },
2050
+ )
2051
+ return _safe_tool_call(
2052
+ lambda: self._facade.app_flow_plan(profile=profile, request=request),
2053
+ error_code="FLOW_PLAN_FAILED",
2054
+ normalized_args=request.model_dump(mode="json"),
2055
+ suggested_next_call={"tool_name": "app_flow_plan", "arguments": {"profile": profile, **request.model_dump(mode="json")}},
2056
+ )
2057
+
1607
2058
  @tool_cn_name("应用视图规划")
1608
2059
  def app_views_plan(
1609
2060
  self,
@@ -1611,6 +2062,7 @@ class AiBuilderTools(ToolBase):
1611
2062
  profile: str,
1612
2063
  app_key: str,
1613
2064
  upsert_views: list[JSONObject] | None = None,
2065
+ patch_views: list[JSONObject] | None = None,
1614
2066
  remove_views: list[str] | None = None,
1615
2067
  preset: str | None = None,
1616
2068
  ) -> JSONObject:
@@ -1629,6 +2081,7 @@ class AiBuilderTools(ToolBase):
1629
2081
  {
1630
2082
  "app_key": app_key,
1631
2083
  "upsert_views": upsert_views or [],
2084
+ "patch_views": patch_views or [],
1632
2085
  "remove_views": remove_views or [],
1633
2086
  "preset": preset,
1634
2087
  }
@@ -1645,6 +2098,7 @@ class AiBuilderTools(ToolBase):
1645
2098
  "app_key": app_key,
1646
2099
  "preset": "default_table",
1647
2100
  "upsert_views": [],
2101
+ "patch_views": [],
1648
2102
  "remove_views": [],
1649
2103
  },
1650
2104
  },
@@ -1652,8 +2106,24 @@ class AiBuilderTools(ToolBase):
1652
2106
  return _safe_tool_call(
1653
2107
  lambda: self._facade.app_views_plan(profile=profile, request=request),
1654
2108
  error_code="VIEWS_PLAN_FAILED",
1655
- normalized_args=request.model_dump(mode="json"),
1656
- suggested_next_call={"tool_name": "app_views_plan", "arguments": {"profile": profile, **request.model_dump(mode="json")}},
2109
+ normalized_args={
2110
+ "app_key": request.app_key,
2111
+ "upsert_views": [public_view_upsert_payload(view) for view in request.upsert_views],
2112
+ "patch_views": [public_view_partial_payload(patch) for patch in request.patch_views],
2113
+ "remove_views": list(request.remove_views),
2114
+ "preset": request.preset.value if request.preset is not None else None,
2115
+ },
2116
+ suggested_next_call={
2117
+ "tool_name": "app_views_plan",
2118
+ "arguments": {
2119
+ "profile": profile,
2120
+ "app_key": request.app_key,
2121
+ "upsert_views": [public_view_upsert_payload(view) for view in request.upsert_views],
2122
+ "patch_views": [public_view_partial_payload(patch) for patch in request.patch_views],
2123
+ "remove_views": list(request.remove_views),
2124
+ "preset": request.preset.value if request.preset is not None else None,
2125
+ },
2126
+ },
1657
2127
  )
1658
2128
 
1659
2129
  @tool_cn_name("应用结构应用")
@@ -1671,8 +2141,8 @@ class AiBuilderTools(ToolBase):
1671
2141
  icon_color: str | None = None,
1672
2142
  icon_config: JSONObject | None = None,
1673
2143
  visibility: JSONObject | None = None,
1674
- create_if_missing: bool = False,
1675
2144
  publish: bool = True,
2145
+ form: list[JSONObject] | None = None,
1676
2146
  add_fields: list[JSONObject],
1677
2147
  update_fields: list[JSONObject],
1678
2148
  remove_fields: list[JSONObject],
@@ -1698,11 +2168,25 @@ class AiBuilderTools(ToolBase):
1698
2168
  package_id = normalized_apps_payload.get("package_id") # type: ignore[assignment]
1699
2169
  apps = normalized_apps_payload.get("apps") # type: ignore[assignment]
1700
2170
  input_warnings = list(normalized_apps_payload.get("warnings") or [])
2171
+ normalized_apps: list[JSONObject] = []
2172
+ for index, app_item in enumerate(apps or []):
2173
+ if not isinstance(app_item, dict):
2174
+ normalized_apps.append(app_item)
2175
+ continue
2176
+ form_result = _apply_schema_form_to_payload(
2177
+ tool_name="app_schema_apply",
2178
+ payload=app_item,
2179
+ path=f"apps[{index}]",
2180
+ )
2181
+ failure = form_result.get("failure")
2182
+ if isinstance(failure, dict):
2183
+ return _attach_builder_apply_envelope("app_schema_apply", failure)
2184
+ normalized_apps.append(form_result.get("payload") or app_item)
2185
+ apps = normalized_apps
1701
2186
  result = self._app_schema_apply_multi(
1702
2187
  profile=profile,
1703
2188
  package_id=package_id,
1704
2189
  visibility=visibility,
1705
- create_if_missing=create_if_missing,
1706
2190
  publish=publish,
1707
2191
  apps=apps,
1708
2192
  )
@@ -1711,6 +2195,22 @@ class AiBuilderTools(ToolBase):
1711
2195
  result_warnings.extend(deepcopy(input_warnings))
1712
2196
  result["warnings"] = result_warnings
1713
2197
  return _attach_builder_apply_envelope("app_schema_apply", result)
2198
+ inline_form_layout_sections: list[JSONObject] = []
2199
+ if form:
2200
+ form_payload: JSONObject = {"form": form}
2201
+ if add_fields:
2202
+ form_payload["add_fields"] = add_fields
2203
+ form_result = _apply_schema_form_to_payload(
2204
+ tool_name="app_schema_apply",
2205
+ payload=form_payload,
2206
+ path="schema",
2207
+ )
2208
+ failure = form_result.get("failure")
2209
+ if isinstance(failure, dict):
2210
+ return _attach_builder_apply_envelope("app_schema_apply", failure)
2211
+ normalized_payload = form_result.get("payload") if isinstance(form_result.get("payload"), dict) else {}
2212
+ add_fields = list(normalized_payload.get("add_fields") or [])
2213
+ inline_form_layout_sections = list(form_result.get("layout_sections") or [])
1714
2214
  result = self._app_schema_apply_once(
1715
2215
  profile=profile,
1716
2216
  app_key=app_key,
@@ -1720,11 +2220,11 @@ class AiBuilderTools(ToolBase):
1720
2220
  icon=icon,
1721
2221
  color=color,
1722
2222
  visibility=visibility,
1723
- create_if_missing=create_if_missing,
1724
2223
  publish=publish,
1725
2224
  add_fields=add_fields,
1726
2225
  update_fields=update_fields,
1727
2226
  remove_fields=remove_fields,
2227
+ inline_form_layout_sections=inline_form_layout_sections,
1728
2228
  )
1729
2229
  result = self._retry_after_self_lock_release(
1730
2230
  profile=profile,
@@ -1738,11 +2238,11 @@ class AiBuilderTools(ToolBase):
1738
2238
  icon=icon,
1739
2239
  color=color,
1740
2240
  visibility=visibility,
1741
- create_if_missing=create_if_missing,
1742
2241
  publish=publish,
1743
2242
  add_fields=add_fields,
1744
2243
  update_fields=update_fields,
1745
2244
  remove_fields=remove_fields,
2245
+ inline_form_layout_sections=inline_form_layout_sections,
1746
2246
  ),
1747
2247
  )
1748
2248
  return _attach_builder_apply_envelope("app_schema_apply", result)
@@ -1753,52 +2253,116 @@ class AiBuilderTools(ToolBase):
1753
2253
  profile: str,
1754
2254
  package_id: int | None,
1755
2255
  visibility: JSONObject | None,
1756
- create_if_missing: bool,
1757
2256
  publish: bool,
1758
2257
  apps: list[JSONObject],
1759
2258
  ) -> JSONObject:
2259
+ started_at = time.perf_counter()
2260
+ validation_ms = 0
2261
+ app_shell_apply_ms = 0
2262
+ relation_compile_ms = 0
2263
+ app_field_apply_ms = 0
2264
+ relation_repair_ms = 0
2265
+ inline_layout_fallback_ms = 0
2266
+ child_schema_write_ms = 0
2267
+ child_inline_layout_ms = 0
2268
+ child_publish_ms = 0
2269
+ child_readback_ms = 0
1760
2270
  normalized_args: JSONObject = {
1761
2271
  "package_id": package_id,
1762
- "create_if_missing": create_if_missing,
1763
2272
  "publish": publish,
1764
2273
  "apps": deepcopy(apps),
1765
2274
  }
1766
2275
  if visibility is not None:
1767
2276
  normalized_args["visibility"] = deepcopy(visibility)
2277
+ parallelism: JSONObject = {"shell_workers": 0, "schema_workers": 0}
2278
+
2279
+ def merge_child_duration(child: JSONObject) -> None:
2280
+ nonlocal child_schema_write_ms
2281
+ nonlocal child_inline_layout_ms
2282
+ nonlocal child_publish_ms
2283
+ nonlocal child_readback_ms
2284
+ breakdown = child.get("duration_breakdown_ms") if isinstance(child, dict) else None
2285
+ if not isinstance(breakdown, dict):
2286
+ return
2287
+ for key, target in (
2288
+ ("schema_write_ms", "child_schema_write_ms"),
2289
+ ("inline_layout_ms", "child_inline_layout_ms"),
2290
+ ("publish_ms", "child_publish_ms"),
2291
+ ("readback_ms", "child_readback_ms"),
2292
+ ):
2293
+ value = breakdown.get(key)
2294
+ if isinstance(value, (int, float)) and value >= 0:
2295
+ if target == "child_schema_write_ms":
2296
+ child_schema_write_ms += int(value)
2297
+ elif target == "child_inline_layout_ms":
2298
+ child_inline_layout_ms += int(value)
2299
+ elif target == "child_publish_ms":
2300
+ child_publish_ms += int(value)
2301
+ elif target == "child_readback_ms":
2302
+ child_readback_ms += int(value)
2303
+
2304
+ def finish(response: JSONObject) -> JSONObject:
2305
+ _merge_duration_breakdown(
2306
+ response,
2307
+ multi_app_validation_ms=validation_ms,
2308
+ app_shell_apply_ms=app_shell_apply_ms,
2309
+ app_shell_parallel_wall_ms=app_shell_apply_ms,
2310
+ relation_compile_ms=relation_compile_ms,
2311
+ app_field_apply_ms=app_field_apply_ms,
2312
+ app_schema_parallel_wall_ms=app_field_apply_ms,
2313
+ relation_repair_parallel_wall_ms=relation_repair_ms,
2314
+ native_inline_layout_ms=child_inline_layout_ms,
2315
+ inline_layout_fallback_ms=inline_layout_fallback_ms,
2316
+ child_schema_write_ms=child_schema_write_ms,
2317
+ child_inline_layout_ms=child_inline_layout_ms,
2318
+ child_publish_ms=child_publish_ms,
2319
+ child_readback_ms=child_readback_ms,
2320
+ total_ms=_elapsed_ms(started_at),
2321
+ )
2322
+ return response
2323
+
2324
+ validation_started_at = time.perf_counter()
1768
2325
  system_field_failure = _reserved_system_field_name_failure_for_apps(
1769
2326
  tool_name="app_schema_apply",
1770
2327
  profile=profile,
1771
2328
  package_id=package_id,
1772
2329
  visibility=visibility,
1773
- create_if_missing=create_if_missing,
1774
2330
  publish=publish,
1775
2331
  apps=apps,
1776
2332
  )
1777
2333
  if system_field_failure is not None:
1778
- return system_field_failure
2334
+ validation_ms += _elapsed_ms(validation_started_at)
2335
+ return finish(system_field_failure)
1779
2336
  if package_id is None:
1780
- return _config_failure(
1781
- tool_name="app_schema_apply",
1782
- message="app_schema_apply multi-app mode requires package_id.",
1783
- fix_hint="Pass package_id and apps[].app_name for new apps, or apps[].app_key for existing apps.",
2337
+ validation_ms += _elapsed_ms(validation_started_at)
2338
+ return finish(
2339
+ _config_failure(
2340
+ tool_name="app_schema_apply",
2341
+ message="app_schema_apply multi-app mode requires package_id.",
2342
+ fix_hint="Pass package_id and apps[].app_name for new apps, or apps[].app_key for existing apps.",
2343
+ )
1784
2344
  )
1785
2345
  if not apps:
1786
- return _config_failure(
1787
- tool_name="app_schema_apply",
1788
- error_code="APPS_FILE_EMPTY",
1789
- message="app_schema_apply multi-app mode requires non-empty apps.",
1790
- fix_hint="Pass apps as a non-empty list of app schema items.",
2346
+ validation_ms += _elapsed_ms(validation_started_at)
2347
+ return finish(
2348
+ _config_failure(
2349
+ tool_name="app_schema_apply",
2350
+ error_code="APPS_FILE_EMPTY",
2351
+ message="app_schema_apply multi-app mode requires non-empty apps.",
2352
+ fix_hint="Pass apps as a non-empty list of app schema items.",
2353
+ )
1791
2354
  )
1792
2355
  shape_failure = _schema_apps_shape_failure(tool_name="app_schema_apply", apps=apps)
1793
2356
  if shape_failure is not None:
1794
- return shape_failure
2357
+ validation_ms += _elapsed_ms(validation_started_at)
2358
+ return finish(shape_failure)
1795
2359
  static_validation_failure = _multi_app_static_validation_failure(
1796
2360
  tool_name="app_schema_apply",
1797
2361
  apps=apps,
1798
- create_if_missing=create_if_missing,
1799
2362
  )
1800
2363
  if static_validation_failure is not None:
1801
- return static_validation_failure
2364
+ validation_ms += _elapsed_ms(validation_started_at)
2365
+ return finish(static_validation_failure)
1802
2366
  icon_errors: list[JSONObject] = []
1803
2367
  seen_new_app_icons: dict[str, int] = {}
1804
2368
  for index, raw_item in enumerate(apps):
@@ -1849,32 +2413,111 @@ class AiBuilderTools(ToolBase):
1849
2413
  else:
1850
2414
  seen_new_app_icons[normalized_icon] = index
1851
2415
  if icon_errors:
1852
- return _config_failure(
1853
- tool_name="app_schema_apply",
1854
- error_code="WORKSPACE_ICON_BATCH_INVALID",
1855
- message="one or more apps have invalid workspace icon configuration",
1856
- fix_hint="Call `qingflow --json builder icon catalog`, choose a distinct non-template icon and color for each new app, then retry.",
1857
- details={"icon_errors": icon_errors},
1858
- allowed_values={
1859
- "workspace_icon.icon_names": list(WORKSPACE_ICON_NAMES),
1860
- "workspace_icon.icon_colors": list(WORKSPACE_ICON_COLORS),
1861
- "workspace_icon.generic_icon_names": list(GENERIC_WORKSPACE_ICON_NAMES),
1862
- },
2416
+ validation_ms += _elapsed_ms(validation_started_at)
2417
+ return finish(
2418
+ _config_failure(
2419
+ tool_name="app_schema_apply",
2420
+ error_code="WORKSPACE_ICON_BATCH_INVALID",
2421
+ message="one or more apps have invalid workspace icon configuration",
2422
+ fix_hint="Call `qingflow --json builder icon catalog`, choose a distinct non-template icon and color for each new app, then retry.",
2423
+ details={"icon_errors": icon_errors},
2424
+ allowed_values={
2425
+ "workspace_icon.icon_names": list(WORKSPACE_ICON_NAMES),
2426
+ "workspace_icon.icon_colors": list(WORKSPACE_ICON_COLORS),
2427
+ "workspace_icon.generic_icon_names": list(GENERIC_WORKSPACE_ICON_NAMES),
2428
+ },
2429
+ )
1863
2430
  )
2431
+ validation_ms += _elapsed_ms(validation_started_at)
1864
2432
 
1865
2433
  client_key_to_app_key: dict[str, str] = {}
1866
2434
  app_name_to_app_key: dict[str, str] = {}
1867
2435
  created_app_keys: list[str] = []
1868
- results: list[JSONObject] = []
2436
+ results_by_index: list[JSONObject | None] = [None] * len(apps)
2437
+ shell_jobs: list[JSONObject] = []
1869
2438
  any_write_executed = False
1870
2439
  any_write_may_have_succeeded = False
1871
2440
  pending_readback_app_keys: list[str] = []
1872
2441
  pending_readback_app_names: list[str] = []
1873
2442
  client_keys: set[str] = set()
2443
+ client_key_indexes: dict[str, int] = {}
2444
+ app_name_indexes: dict[str, int] = {}
2445
+
2446
+ def worker_count(count: int) -> int:
2447
+ return min(MULTI_APP_SCHEMA_APPLY_PARALLEL_LIMIT, count) if count > 0 else 0
2448
+
2449
+ def mark_inline_layout_not_applied_in_schema(
2450
+ result: JSONObject,
2451
+ *,
2452
+ app_key: str,
2453
+ sections: list[JSONObject],
2454
+ ) -> JSONObject:
2455
+ marked = deepcopy(result)
2456
+ inline_payload: JSONObject = {
2457
+ "requested": True,
2458
+ "section_count": len(sections),
2459
+ "app_key": app_key or None,
2460
+ "applied": False,
2461
+ "applied_in_schema": False,
2462
+ "error_code": "INLINE_FORM_LAYOUT_NOT_APPLIED_IN_SCHEMA",
2463
+ "message": "schema save did not apply inline form layout; multi-app mode does not run app_layout_apply fallback",
2464
+ }
2465
+ marked["inline_form_layout"] = inline_payload
2466
+ verification = marked.get("verification") if isinstance(marked.get("verification"), dict) else {}
2467
+ verification = deepcopy(verification)
2468
+ verification["inline_form_layout_verified"] = False
2469
+ marked["verification"] = verification
2470
+ if marked.get("status") in {"success", "partial_success"}:
2471
+ marked["status"] = "partial_success"
2472
+ marked["error_code"] = marked.get("error_code") or "INLINE_FORM_LAYOUT_NOT_APPLIED_IN_SCHEMA"
2473
+ marked["message"] = "schema applied but inline form layout was not applied in schema save"
2474
+ marked["safe_to_retry"] = False
2475
+ return marked
2476
+
2477
+ def dependency_failure_for_item(index: int, item: JSONObject) -> JSONObject | None:
2478
+ blocked: list[JSONObject] = []
2479
+ for ref in _collect_multi_app_target_refs(item, path=f"apps[{index}]"):
2480
+ ref_value = str(ref.get("value") or "").strip()
2481
+ if not ref_value:
2482
+ continue
2483
+ target_index: int | None = None
2484
+ resolved = False
2485
+ if ref.get("kind") == "target_app_ref":
2486
+ target_index = client_key_indexes.get(ref_value)
2487
+ resolved = ref_value in client_key_to_app_key
2488
+ elif ref.get("kind") == "target_app":
2489
+ target_index = app_name_indexes.get(ref_value)
2490
+ resolved = ref_value in app_name_to_app_key
2491
+ if target_index is None or resolved:
2492
+ continue
2493
+ target_result = results_by_index[target_index] if 0 <= target_index < len(results_by_index) else None
2494
+ blocked.append(
2495
+ {
2496
+ "kind": ref.get("kind"),
2497
+ "value": ref_value,
2498
+ "path": ref.get("path"),
2499
+ "target_index": target_index,
2500
+ "target_status": target_result.get("status") if isinstance(target_result, dict) else None,
2501
+ "target_error_code": target_result.get("error_code") if isinstance(target_result, dict) else None,
2502
+ }
2503
+ )
2504
+ if not blocked:
2505
+ return None
2506
+ raw_item = apps[index] if 0 <= index < len(apps) else item
2507
+ failure = _multi_app_item_failure(
2508
+ index,
2509
+ raw_item,
2510
+ "DEPENDENCY_APP_NOT_READY",
2511
+ "one or more target apps failed or require readback, so this app schema was not written",
2512
+ )
2513
+ failure["stage"] = "dependency_check"
2514
+ failure["safe_to_retry"] = False
2515
+ failure["details"] = {"blocked_dependencies": blocked}
2516
+ return failure
1874
2517
 
1875
2518
  for index, raw_item in enumerate(apps):
1876
2519
  if not isinstance(raw_item, dict):
1877
- results.append(_multi_app_item_failure(index, raw_item, "INVALID_APP_ITEM", "apps[] items must be objects"))
2520
+ results_by_index[index] = _multi_app_item_failure(index, raw_item, "INVALID_APP_ITEM", "apps[] items must be objects")
1878
2521
  continue
1879
2522
  item = deepcopy(raw_item)
1880
2523
  client_key = str(item.get("client_key") or item.get("clientKey") or "").strip()
@@ -1882,51 +2525,124 @@ class AiBuilderTools(ToolBase):
1882
2525
  app_key = str(item.get("app_key") or item.get("appKey") or "").strip()
1883
2526
  if client_key:
1884
2527
  if client_key in client_keys:
1885
- results.append(_multi_app_item_failure(index, item, "DUPLICATE_CLIENT_KEY", f"duplicate client_key '{client_key}'"))
2528
+ results_by_index[index] = _multi_app_item_failure(index, item, "DUPLICATE_CLIENT_KEY", f"duplicate client_key '{client_key}'")
1886
2529
  continue
1887
2530
  client_keys.add(client_key)
2531
+ client_key_indexes[client_key] = index
2532
+ if app_name:
2533
+ app_name_indexes[app_name] = index
1888
2534
  if not app_key and not app_name:
1889
- results.append(_multi_app_item_failure(index, item, "APP_SELECTOR_REQUIRED", "apps[] requires app_key or app_name"))
2535
+ results_by_index[index] = _multi_app_item_failure(index, item, "APP_SELECTOR_REQUIRED", "apps[] requires app_key or app_name")
1890
2536
  continue
1891
-
1892
- initial_add_fields, deferred_add_fields = _split_multi_app_initial_add_fields(item, is_new_app=not bool(app_key))
1893
- item["_deferred_add_fields"] = deferred_add_fields
1894
- shell = self._app_schema_apply_once(
1895
- profile=profile,
1896
- app_key=app_key,
1897
- package_id=package_id if not app_key else None,
1898
- app_name=app_name,
1899
- app_title="",
1900
- icon=str(item.get("icon") or ""),
1901
- color=str(item.get("color") or ""),
1902
- visibility=item.get("visibility", visibility),
1903
- create_if_missing=create_if_missing and not app_key,
1904
- publish=publish and not deferred_add_fields,
1905
- add_fields=initial_add_fields,
1906
- update_fields=[],
1907
- remove_fields=[],
2537
+ shell_jobs.append(
2538
+ {
2539
+ "index": index,
2540
+ "item": item,
2541
+ "client_key": client_key,
2542
+ "app_name": app_name,
2543
+ "app_key": app_key,
2544
+ }
1908
2545
  )
1909
- public_shell = _publicize_package_fields(shell)
1910
- resolved_key = str(public_shell.get("app_key") or "").strip()
1911
- shell_write_executed = _schema_apply_result_has_write(public_shell)
1912
- shell_write_may_have_succeeded = _schema_apply_result_may_have_write(public_shell)
1913
- if shell_write_executed:
1914
- any_write_executed = True
1915
- if shell_write_may_have_succeeded:
1916
- any_write_may_have_succeeded = True
1917
- if public_shell.get("status") not in {"success", "partial_success"} or not resolved_key:
1918
- pending_readback = bool(shell_write_may_have_succeeded or shell_write_executed) and (
1919
- str(public_shell.get("next_action") or "") == "readback_before_retry"
1920
- or bool((public_shell.get("verification") if isinstance(public_shell.get("verification"), dict) else {}).get("readback_before_retry"))
1921
- or not resolved_key
2546
+
2547
+ shell_workers = worker_count(len(shell_jobs))
2548
+ parallelism["shell_workers"] = shell_workers
2549
+
2550
+ def run_shell_job(job: JSONObject) -> JSONObject:
2551
+ index = int(job["index"])
2552
+ item = deepcopy(job["item"])
2553
+ app_key = str(job.get("app_key") or "")
2554
+ app_name = str(job.get("app_name") or "")
2555
+ shell_started_at = time.perf_counter()
2556
+ try:
2557
+ shell = self._app_schema_apply_once(
2558
+ profile=profile,
2559
+ app_key=app_key,
2560
+ package_id=package_id if not app_key else None,
2561
+ app_name=app_name,
2562
+ app_title="",
2563
+ icon=str(item.get("icon") or ""),
2564
+ color=str(item.get("color") or ""),
2565
+ visibility=item.get("visibility", visibility),
2566
+ publish=False,
2567
+ add_fields=[],
2568
+ update_fields=[],
2569
+ remove_fields=[],
2570
+ inline_form_layout_sections=None,
2571
+ allow_inline_layout_fallback=False,
1922
2572
  )
1923
- item_status = "pending_readback" if pending_readback else "failed"
2573
+ return {
2574
+ "index": index,
2575
+ "job": job,
2576
+ "elapsed_ms": _elapsed_ms(shell_started_at),
2577
+ "public_shell": _publicize_package_fields(shell),
2578
+ }
2579
+ except Exception as error: # pragma: no cover - defensive guard for unexpected worker failures
2580
+ return {
2581
+ "index": index,
2582
+ "job": job,
2583
+ "elapsed_ms": _elapsed_ms(shell_started_at),
2584
+ "exception": repr(error),
2585
+ }
2586
+
2587
+ shell_outputs: list[JSONObject] = []
2588
+ shell_phase_started_at = time.perf_counter()
2589
+ if shell_jobs:
2590
+ with ThreadPoolExecutor(max_workers=shell_workers) as executor:
2591
+ futures = [executor.submit(run_shell_job, job) for job in shell_jobs]
2592
+ for future in as_completed(futures):
2593
+ shell_outputs.append(future.result())
2594
+ app_shell_apply_ms += _elapsed_ms(shell_phase_started_at)
2595
+
2596
+ for output in sorted(shell_outputs, key=lambda item: int(item.get("index", 0))):
2597
+ index = int(output["index"])
2598
+ job = output.get("job") if isinstance(output.get("job"), dict) else {}
2599
+ client_key = str(job.get("client_key") or "").strip()
2600
+ app_name = str(job.get("app_name") or "").strip()
2601
+ app_key = str(job.get("app_key") or "").strip()
2602
+ item = deepcopy(job.get("item") if isinstance(job.get("item"), dict) else {})
2603
+ exception = output.get("exception")
2604
+ if exception:
2605
+ results_by_index[index] = {
2606
+ "index": index,
2607
+ "row_number": index + 1,
2608
+ "client_key": client_key or None,
2609
+ "app_name": app_name or None,
2610
+ "app_key": app_key or None,
2611
+ "status": "pending_readback",
2612
+ "stage": "resolve_or_create_shell",
2613
+ "error_code": "APP_SHELL_APPLY_EXCEPTION",
2614
+ "message": str(exception),
2615
+ "write_executed": False,
2616
+ "write_may_have_succeeded": True,
2617
+ "safe_to_retry": False,
2618
+ "next_action": "readback_before_retry",
2619
+ }
2620
+ if app_name:
2621
+ pending_readback_app_names.append(app_name)
2622
+ any_write_may_have_succeeded = True
2623
+ continue
2624
+ public_shell = output.get("public_shell") if isinstance(output.get("public_shell"), dict) else {}
2625
+ merge_child_duration(public_shell)
2626
+ resolved_key = str(public_shell.get("app_key") or "").strip()
2627
+ shell_write_executed = _schema_apply_result_has_write(public_shell)
2628
+ shell_write_may_have_succeeded = _schema_apply_result_may_have_write(public_shell)
2629
+ if shell_write_executed:
2630
+ any_write_executed = True
2631
+ if shell_write_may_have_succeeded:
2632
+ any_write_may_have_succeeded = True
2633
+ if public_shell.get("status") not in {"success", "partial_success"} or not resolved_key:
2634
+ pending_readback = bool(shell_write_may_have_succeeded or shell_write_executed) and (
2635
+ str(public_shell.get("next_action") or "") == "readback_before_retry"
2636
+ or bool((public_shell.get("verification") if isinstance(public_shell.get("verification"), dict) else {}).get("readback_before_retry"))
2637
+ or not resolved_key
2638
+ )
2639
+ item_status = "pending_readback" if pending_readback else "failed"
1924
2640
  if pending_readback:
1925
2641
  if resolved_key:
1926
2642
  pending_readback_app_keys.append(resolved_key)
1927
2643
  if app_name:
1928
2644
  pending_readback_app_names.append(app_name)
1929
- results.append({
2645
+ results_by_index[index] = {
1930
2646
  "index": index,
1931
2647
  "row_number": index + 1,
1932
2648
  "client_key": client_key or None,
@@ -1941,8 +2657,8 @@ class AiBuilderTools(ToolBase):
1941
2657
  "safe_to_retry": False if pending_readback else (not shell_write_executed and not any_write_executed),
1942
2658
  **({"next_action": "readback_before_retry"} if pending_readback else {}),
1943
2659
  **({"verification": public_shell.get("verification")} if isinstance(public_shell.get("verification"), dict) else {}),
1944
- **({"created": True} if pending_readback and create_if_missing and not app_key else {}),
1945
- })
2660
+ **({"created": True} if pending_readback and not app_key else {}),
2661
+ }
1946
2662
  continue
1947
2663
  if bool(public_shell.get("created")):
1948
2664
  created_app_keys.append(resolved_key)
@@ -1955,7 +2671,7 @@ class AiBuilderTools(ToolBase):
1955
2671
  resolved_name = str(public_shell.get("app_name_after") or public_shell.get("app_name") or app_name or "").strip()
1956
2672
  if resolved_name:
1957
2673
  app_name_to_app_key[resolved_name] = resolved_key
1958
- results.append({
2674
+ results_by_index[index] = {
1959
2675
  "index": index,
1960
2676
  "row_number": index + 1,
1961
2677
  "client_key": client_key or None,
@@ -1966,80 +2682,246 @@ class AiBuilderTools(ToolBase):
1966
2682
  "shell_result": public_shell,
1967
2683
  "shell_field_diff": public_shell.get("field_diff") or {},
1968
2684
  "shell_field_diff_details": public_shell.get("field_diff_details") or {},
1969
- "deferred_add_fields": deferred_add_fields,
1970
- })
2685
+ }
1971
2686
 
1972
- final_items: list[JSONObject] = []
2687
+ final_items_by_index: list[JSONObject | None] = [None] * len(apps)
2688
+ schema_jobs: list[JSONObject] = []
1973
2689
  for index, raw_item in enumerate(apps):
1974
- existing = next((item for item in results if item.get("index") == index), None)
2690
+ existing = results_by_index[index] if 0 <= index < len(results_by_index) else None
1975
2691
  if not existing or existing.get("status") != "shell_ready":
1976
2692
  if existing:
1977
- final_items.append(existing)
2693
+ final_items_by_index[index] = existing
1978
2694
  continue
1979
2695
  item = deepcopy(raw_item)
1980
2696
  app_key = str(existing.get("app_key") or "").strip()
2697
+ dependency_failure = dependency_failure_for_item(index, item)
2698
+ if dependency_failure is not None:
2699
+ final_items_by_index[index] = dependency_failure
2700
+ any_write_executed = True
2701
+ continue
2702
+ compile_started_at = time.perf_counter()
1981
2703
  try:
1982
2704
  compiled_item = _compile_multi_app_schema_item_refs(item, client_key_to_app_key, app_name_to_app_key)
1983
2705
  except ValueError as error:
1984
- final_items.append({
2706
+ relation_compile_ms += _elapsed_ms(compile_started_at)
2707
+ final_items_by_index[index] = {
1985
2708
  **{key: existing.get(key) for key in ("index", "row_number", "client_key", "app_name", "app_key", "created")},
1986
2709
  "status": "failed",
1987
2710
  "stage": "compile_relation_refs",
1988
2711
  "error_code": "TARGET_APP_REF_NOT_FOUND",
1989
2712
  "message": str(error),
1990
2713
  "safe_to_retry": False,
1991
- })
2714
+ }
1992
2715
  any_write_executed = True
1993
2716
  continue
1994
-
1995
- deferred_add_fields = (
1996
- _compiled_multi_app_deferred_add_fields(compiled_item, existing)
1997
- if bool(existing.get("created"))
1998
- else list(compiled_item.get("add_fields") or [])
1999
- )
2717
+ relation_compile_ms += _elapsed_ms(compile_started_at)
2718
+ schema_add_fields = list(compiled_item.get("add_fields") or [])
2000
2719
  update_fields = list(compiled_item.get("update_fields") or [])
2001
2720
  remove_fields = list(compiled_item.get("remove_fields") or [])
2002
- if bool(existing.get("created")) and not deferred_add_fields and not update_fields and not remove_fields:
2003
- shell_result = existing.get("shell_result") if isinstance(existing.get("shell_result"), dict) else {}
2004
- item_status = shell_result.get("status") if shell_result.get("status") in {"success", "partial_success"} else "failed"
2005
- shell_field_diff = existing.get("shell_field_diff") if isinstance(existing.get("shell_field_diff"), dict) else {}
2006
- shell_field_diff_details = existing.get("shell_field_diff_details") if isinstance(existing.get("shell_field_diff_details"), dict) else {}
2007
- final_items.append({
2721
+ layout_sections = list(compiled_item.get("_inline_form_layout_sections") or [])
2722
+ field_phase_app_name = ""
2723
+ field_phase_icon = ""
2724
+ field_phase_color = ""
2725
+ field_phase_visibility = None
2726
+ relation_fields_for_retry = [
2727
+ deepcopy(field)
2728
+ for field in schema_add_fields
2729
+ if isinstance(field, dict) and _multi_app_field_type(field) == PublicFieldType.relation.value
2730
+ ]
2731
+ schema_jobs.append(
2732
+ {
2733
+ "index": index,
2734
+ "existing": existing,
2735
+ "item": item,
2736
+ "app_key": app_key,
2737
+ "field_phase_app_name": field_phase_app_name,
2738
+ "field_phase_icon": field_phase_icon,
2739
+ "field_phase_color": field_phase_color,
2740
+ "field_phase_visibility": field_phase_visibility,
2741
+ "schema_add_fields": schema_add_fields,
2742
+ "update_fields": update_fields,
2743
+ "remove_fields": remove_fields,
2744
+ "layout_sections": layout_sections,
2745
+ "relation_fields_for_retry": relation_fields_for_retry,
2746
+ }
2747
+ )
2748
+
2749
+ schema_workers = worker_count(len(schema_jobs))
2750
+ parallelism["schema_workers"] = schema_workers
2751
+ parallelism["schema_wave_count"] = 0
2752
+ parallelism["schema_wave_sizes"] = []
2753
+
2754
+ def run_schema_job(job: JSONObject) -> JSONObject:
2755
+ index = int(job["index"])
2756
+ app_key = str(job.get("app_key") or "")
2757
+ field_phase_app_name = str(job.get("field_phase_app_name") or "")
2758
+ field_phase_icon = str(job.get("field_phase_icon") or "")
2759
+ field_phase_color = str(job.get("field_phase_color") or "")
2760
+ field_phase_visibility = job.get("field_phase_visibility")
2761
+ schema_add_fields = list(job.get("schema_add_fields") or [])
2762
+ update_fields = list(job.get("update_fields") or [])
2763
+ remove_fields = list(job.get("remove_fields") or [])
2764
+ layout_sections = list(job.get("layout_sections") or [])
2765
+ relation_fields_for_retry = list(job.get("relation_fields_for_retry") or [])
2766
+ field_started_at = time.perf_counter()
2767
+ try:
2768
+ field_result = self._app_schema_apply_once(
2769
+ profile=profile,
2770
+ app_key=app_key,
2771
+ package_id=None,
2772
+ app_name=field_phase_app_name,
2773
+ app_title="",
2774
+ icon=field_phase_icon,
2775
+ color=field_phase_color,
2776
+ visibility=field_phase_visibility,
2777
+ publish=publish,
2778
+ add_fields=schema_add_fields,
2779
+ update_fields=update_fields,
2780
+ remove_fields=remove_fields,
2781
+ inline_form_layout_sections=layout_sections,
2782
+ allow_inline_layout_fallback=False,
2783
+ )
2784
+ public_result = _publicize_package_fields(field_result)
2785
+ except Exception as error: # pragma: no cover - defensive guard for unexpected worker failures
2786
+ return {
2787
+ "index": index,
2788
+ "job": job,
2789
+ "elapsed_ms": _elapsed_ms(field_started_at),
2790
+ "exception": repr(error),
2791
+ }
2792
+ if _multi_app_deferred_relation_retryable(public_result, relation_fields_for_retry):
2793
+ first_error = {
2794
+ "error_code": public_result.get("error_code"),
2795
+ "message": public_result.get("message"),
2796
+ "backend_code": public_result.get("backend_code"),
2797
+ "http_status": public_result.get("http_status"),
2798
+ "details": deepcopy(public_result.get("details")) if isinstance(public_result.get("details"), dict) else None,
2799
+ }
2800
+ retry_attempts: list[JSONObject] = []
2801
+ for retry_index, delay_seconds in enumerate((1.0, 5.0), start=1):
2802
+ retry_readback = self._stabilize_deferred_relation_metadata(
2803
+ profile=profile,
2804
+ source_app_key=app_key,
2805
+ deferred_add_fields=relation_fields_for_retry,
2806
+ delay_seconds=delay_seconds,
2807
+ )
2808
+ retry_result = self._app_schema_apply_once(
2809
+ profile=profile,
2810
+ app_key=app_key,
2811
+ package_id=None,
2812
+ app_name=field_phase_app_name,
2813
+ app_title="",
2814
+ icon=field_phase_icon,
2815
+ color=field_phase_color,
2816
+ visibility=field_phase_visibility,
2817
+ publish=publish,
2818
+ add_fields=schema_add_fields,
2819
+ update_fields=update_fields,
2820
+ remove_fields=remove_fields,
2821
+ inline_form_layout_sections=layout_sections,
2822
+ allow_inline_layout_fallback=False,
2823
+ )
2824
+ public_retry_result = _publicize_package_fields(retry_result)
2825
+ retry_attempts.append(
2826
+ {
2827
+ "attempt": retry_index,
2828
+ "delay_seconds": delay_seconds,
2829
+ "status": public_retry_result.get("status"),
2830
+ "error_code": public_retry_result.get("error_code"),
2831
+ "backend_code": public_retry_result.get("backend_code"),
2832
+ "http_status": public_retry_result.get("http_status"),
2833
+ "readback": retry_readback,
2834
+ }
2835
+ )
2836
+ public_result = public_retry_result
2837
+ if not _multi_app_deferred_relation_retryable(public_result, relation_fields_for_retry):
2838
+ break
2839
+ retry_details = public_result.get("details")
2840
+ if not isinstance(retry_details, dict):
2841
+ retry_details = {}
2842
+ public_result["details"] = retry_details
2843
+ retry_summary: JSONObject = {
2844
+ "attempted": True,
2845
+ "reason": "same_batch_relation_metadata_may_lag",
2846
+ "first_error": first_error,
2847
+ "attempts": retry_attempts,
2848
+ }
2849
+ if retry_attempts:
2850
+ retry_summary["readback"] = retry_attempts[-1].get("readback")
2851
+ retry_details["deferred_relation_retry"] = retry_summary
2852
+ if layout_sections and not _inline_form_layout_was_handled(public_result):
2853
+ public_result = mark_inline_layout_not_applied_in_schema(
2854
+ public_result,
2855
+ app_key=app_key,
2856
+ sections=layout_sections,
2857
+ )
2858
+ return {
2859
+ "index": index,
2860
+ "job": job,
2861
+ "elapsed_ms": _elapsed_ms(field_started_at),
2862
+ "public_result": public_result,
2863
+ }
2864
+
2865
+ def schema_job_dependency_indexes(job: JSONObject) -> set[int]:
2866
+ index = int(job.get("index", -1))
2867
+ item = job.get("item") if isinstance(job.get("item"), dict) else {}
2868
+ dependencies: set[int] = set()
2869
+ for ref in _collect_multi_app_target_refs(item, path=f"apps[{index}]"):
2870
+ ref_value = str(ref.get("value") or "").strip()
2871
+ if not ref_value:
2872
+ continue
2873
+ target_index: int | None = None
2874
+ if ref.get("kind") == "target_app_ref":
2875
+ target_index = client_key_indexes.get(ref_value)
2876
+ elif ref.get("kind") == "target_app":
2877
+ target_index = app_name_indexes.get(ref_value)
2878
+ if target_index is None or target_index == index:
2879
+ continue
2880
+ dependencies.add(target_index)
2881
+ return dependencies
2882
+
2883
+ def schema_dependency_failure(index: int, job: JSONObject, blocked_dependencies: list[JSONObject]) -> JSONObject:
2884
+ existing = job.get("existing") if isinstance(job.get("existing"), dict) else {}
2885
+ return {
2886
+ **{key: existing.get(key) for key in ("index", "row_number", "client_key", "app_name", "app_key", "created")},
2887
+ "status": "failed",
2888
+ "stage": "schema_dependency_check",
2889
+ "error_code": "DEPENDENCY_SCHEMA_NOT_READY",
2890
+ "message": "one or more same-batch target app schemas failed or are not ready, so this app schema was not written",
2891
+ "write_executed": False,
2892
+ "write_may_have_succeeded": False,
2893
+ "safe_to_retry": False,
2894
+ "details": {"blocked_dependencies": blocked_dependencies},
2895
+ }
2896
+
2897
+ def process_schema_output(output: JSONObject) -> None:
2898
+ nonlocal any_write_executed
2899
+ nonlocal any_write_may_have_succeeded
2900
+ index = int(output["index"])
2901
+ job = output.get("job") if isinstance(output.get("job"), dict) else {}
2902
+ existing = job.get("existing") if isinstance(job.get("existing"), dict) else {}
2903
+ app_key = str(job.get("app_key") or "")
2904
+ exception = output.get("exception")
2905
+ if exception:
2906
+ final_items_by_index[index] = {
2008
2907
  **{key: existing.get(key) for key in ("index", "row_number", "client_key", "app_name", "app_key", "created")},
2009
- "status": item_status,
2908
+ "status": "pending_readback",
2010
2909
  "stage": "schema_apply",
2011
- "field_diff": shell_field_diff,
2012
- "field_diff_details": shell_field_diff_details,
2013
- "shell_field_diff": shell_field_diff,
2014
- "shell_field_diff_details": shell_field_diff_details,
2015
- "published": bool(shell_result.get("published")),
2016
- "verified": bool(shell_result.get("verified")),
2017
- "error_code": shell_result.get("error_code"),
2018
- "message": shell_result.get("message"),
2019
- "write_executed": _schema_apply_result_has_write(shell_result),
2020
- "write_may_have_succeeded": _schema_apply_result_may_have_write(shell_result),
2910
+ "error_code": "SCHEMA_APPLY_EXCEPTION",
2911
+ "message": str(exception),
2912
+ "write_executed": False,
2913
+ "write_may_have_succeeded": True,
2021
2914
  "safe_to_retry": False,
2022
- **({"next_action": shell_result.get("next_action")} if shell_result.get("next_action") else {}),
2023
- **({"verification": shell_result.get("verification")} if isinstance(shell_result.get("verification"), dict) else {}),
2024
- })
2025
- continue
2026
-
2027
- field_result = self._app_schema_apply_once(
2028
- profile=profile,
2029
- app_key=app_key,
2030
- package_id=None,
2031
- app_name=str(compiled_item.get("app_name") or compiled_item.get("appTitle") or compiled_item.get("app_title") or ""),
2032
- app_title="",
2033
- icon=str(compiled_item.get("icon") or ""),
2034
- color=str(compiled_item.get("color") or ""),
2035
- visibility=compiled_item.get("visibility"),
2036
- create_if_missing=False,
2037
- publish=publish,
2038
- add_fields=deferred_add_fields,
2039
- update_fields=update_fields,
2040
- remove_fields=remove_fields,
2041
- )
2042
- public_result = _publicize_package_fields(field_result)
2915
+ "next_action": "readback_before_retry",
2916
+ }
2917
+ if app_key:
2918
+ pending_readback_app_keys.append(app_key)
2919
+ if existing.get("app_name"):
2920
+ pending_readback_app_names.append(str(existing.get("app_name")))
2921
+ any_write_may_have_succeeded = True
2922
+ return
2923
+ public_result = output.get("public_result") if isinstance(output.get("public_result"), dict) else {}
2924
+ merge_child_duration(public_result)
2043
2925
  if _schema_apply_result_has_write(public_result):
2044
2926
  any_write_executed = True
2045
2927
  if _schema_apply_result_may_have_write(public_result):
@@ -2054,7 +2936,7 @@ class AiBuilderTools(ToolBase):
2054
2936
  pending_readback_app_keys.append(app_key)
2055
2937
  if existing.get("app_name"):
2056
2938
  pending_readback_app_names.append(str(existing.get("app_name")))
2057
- final_items.append({
2939
+ final_items_by_index[index] = {
2058
2940
  **{key: existing.get(key) for key in ("index", "row_number", "client_key", "app_name", "app_key", "created")},
2059
2941
  "status": item_status,
2060
2942
  "stage": "schema_apply",
@@ -2069,9 +2951,225 @@ class AiBuilderTools(ToolBase):
2069
2951
  "write_executed": _schema_apply_result_has_write(public_result),
2070
2952
  "write_may_have_succeeded": _schema_apply_result_may_have_write(public_result),
2071
2953
  "safe_to_retry": False,
2954
+ **_multi_app_child_diagnostics(public_result),
2072
2955
  **({"next_action": public_result.get("next_action")} if public_result.get("next_action") else {}),
2073
2956
  **({"verification": public_result.get("verification")} if isinstance(public_result.get("verification"), dict) else {}),
2074
- })
2957
+ **({"inline_form_layout": public_result.get("inline_form_layout")} if isinstance(public_result.get("inline_form_layout"), dict) else {}),
2958
+ **({"inline_form_layout_result": public_result.get("inline_form_layout_result")} if isinstance(public_result.get("inline_form_layout_result"), dict) else {}),
2959
+ }
2960
+
2961
+ schema_jobs_by_index = {int(job["index"]): job for job in schema_jobs}
2962
+ schema_dependencies_by_index = {
2963
+ index: schema_job_dependency_indexes(job)
2964
+ for index, job in schema_jobs_by_index.items()
2965
+ }
2966
+ pending_schema_indexes = set(schema_jobs_by_index)
2967
+ schema_phase_started_at = time.perf_counter()
2968
+ while pending_schema_indexes:
2969
+ blocked_this_round = False
2970
+ for index in sorted(list(pending_schema_indexes)):
2971
+ blocked_dependencies: list[JSONObject] = []
2972
+ for dependency_index in sorted(schema_dependencies_by_index.get(index, set())):
2973
+ if dependency_index not in schema_jobs_by_index:
2974
+ continue
2975
+ dependency_result = final_items_by_index[dependency_index]
2976
+ if dependency_result is None:
2977
+ continue
2978
+ dependency_status = dependency_result.get("status")
2979
+ if dependency_status not in {"success", "partial_success"}:
2980
+ blocked_dependencies.append(
2981
+ {
2982
+ "target_index": dependency_index,
2983
+ "target_status": dependency_status,
2984
+ "target_error_code": dependency_result.get("error_code"),
2985
+ "target_app_key": dependency_result.get("app_key"),
2986
+ "target_app_name": dependency_result.get("app_name"),
2987
+ }
2988
+ )
2989
+ if not blocked_dependencies:
2990
+ continue
2991
+ final_items_by_index[index] = schema_dependency_failure(
2992
+ index,
2993
+ schema_jobs_by_index[index],
2994
+ blocked_dependencies,
2995
+ )
2996
+ pending_schema_indexes.remove(index)
2997
+ blocked_this_round = True
2998
+ any_write_executed = True
2999
+ if blocked_this_round:
3000
+ continue
3001
+
3002
+ ready_indexes = [
3003
+ index
3004
+ for index in sorted(pending_schema_indexes)
3005
+ if all(
3006
+ dependency_index not in pending_schema_indexes
3007
+ for dependency_index in schema_dependencies_by_index.get(index, set())
3008
+ if dependency_index in schema_jobs_by_index
3009
+ )
3010
+ ]
3011
+ if not ready_indexes:
3012
+ for index in sorted(pending_schema_indexes):
3013
+ existing = schema_jobs_by_index[index].get("existing")
3014
+ existing = existing if isinstance(existing, dict) else {}
3015
+ final_items_by_index[index] = {
3016
+ **{key: existing.get(key) for key in ("index", "row_number", "client_key", "app_name", "app_key", "created")},
3017
+ "status": "failed",
3018
+ "stage": "schema_dependency_check",
3019
+ "error_code": "DEPENDENCY_SCHEMA_CYCLE",
3020
+ "message": "same-batch target_app_ref dependencies contain a cycle; schema was not written",
3021
+ "write_executed": False,
3022
+ "write_may_have_succeeded": False,
3023
+ "safe_to_retry": False,
3024
+ "details": {
3025
+ "dependency_indexes": sorted(schema_dependencies_by_index.get(index, set())),
3026
+ },
3027
+ }
3028
+ any_write_executed = True
3029
+ pending_schema_indexes.clear()
3030
+ break
3031
+
3032
+ parallelism["schema_wave_count"] = int(parallelism.get("schema_wave_count") or 0) + 1
3033
+ schema_wave_sizes = parallelism.get("schema_wave_sizes")
3034
+ if isinstance(schema_wave_sizes, list):
3035
+ schema_wave_sizes.append(len(ready_indexes))
3036
+ wave_outputs: list[JSONObject] = []
3037
+ wave_workers = worker_count(len(ready_indexes))
3038
+ with ThreadPoolExecutor(max_workers=wave_workers) as executor:
3039
+ futures = [executor.submit(run_schema_job, schema_jobs_by_index[index]) for index in ready_indexes]
3040
+ for future in as_completed(futures):
3041
+ wave_outputs.append(future.result())
3042
+ for output in sorted(wave_outputs, key=lambda item: int(item.get("index", 0))):
3043
+ process_schema_output(output)
3044
+ for index in ready_indexes:
3045
+ pending_schema_indexes.remove(index)
3046
+ app_field_apply_ms += _elapsed_ms(schema_phase_started_at)
3047
+
3048
+ final_items: list[JSONObject] = [
3049
+ item if isinstance(item, dict) else _multi_app_item_failure(index, apps[index], "APP_ITEM_NOT_PROCESSED", "app item was not processed")
3050
+ for index, item in enumerate(final_items_by_index)
3051
+ ]
3052
+
3053
+ def relation_repair_patches(item: JSONObject) -> list[JSONObject]:
3054
+ details = item.get("details") if isinstance(item.get("details"), dict) else {}
3055
+ repair_plan = details.get("relation_repair_plan") if isinstance(details.get("relation_repair_plan"), list) else []
3056
+ patches: list[JSONObject] = []
3057
+ for plan_item in repair_plan:
3058
+ if not isinstance(plan_item, dict):
3059
+ continue
3060
+ patch = plan_item.get("suggested_patch")
3061
+ if isinstance(patch, dict):
3062
+ patches.append(deepcopy(patch))
3063
+ return patches
3064
+
3065
+ relation_repair_jobs: list[JSONObject] = []
3066
+ for item in final_items:
3067
+ if item.get("status") != "partial_success":
3068
+ continue
3069
+ app_key = str(item.get("app_key") or "").strip()
3070
+ patches = relation_repair_patches(item)
3071
+ if app_key and patches:
3072
+ relation_repair_jobs.append({"item": item, "app_key": app_key, "patches": patches})
3073
+
3074
+ def run_relation_repair_job(job: JSONObject) -> JSONObject:
3075
+ app_key = str(job.get("app_key") or "")
3076
+ patches = list(job.get("patches") or [])
3077
+ repair_started_at = time.perf_counter()
3078
+ try:
3079
+ repair_result = self._app_schema_apply_once(
3080
+ profile=profile,
3081
+ app_key=app_key,
3082
+ package_id=None,
3083
+ app_name="",
3084
+ app_title="",
3085
+ icon="",
3086
+ color="",
3087
+ visibility=None,
3088
+ publish=publish,
3089
+ add_fields=[],
3090
+ update_fields=patches,
3091
+ remove_fields=[],
3092
+ inline_form_layout_sections=None,
3093
+ allow_inline_layout_fallback=False,
3094
+ )
3095
+ public_repair = _publicize_package_fields(repair_result)
3096
+ except Exception as error: # pragma: no cover - defensive guard for unexpected worker failures
3097
+ return {"job": job, "elapsed_ms": _elapsed_ms(repair_started_at), "exception": repr(error)}
3098
+ return {
3099
+ "job": job,
3100
+ "elapsed_ms": _elapsed_ms(repair_started_at),
3101
+ "public_repair": public_repair,
3102
+ }
3103
+
3104
+ if relation_repair_jobs:
3105
+ repair_phase_started_at = time.perf_counter()
3106
+ repair_workers = worker_count(len(relation_repair_jobs))
3107
+ repair_outputs: list[JSONObject] = []
3108
+ with ThreadPoolExecutor(max_workers=repair_workers) as executor:
3109
+ futures = [executor.submit(run_relation_repair_job, job) for job in relation_repair_jobs]
3110
+ for future in as_completed(futures):
3111
+ repair_outputs.append(future.result())
3112
+ relation_repair_ms += _elapsed_ms(repair_phase_started_at)
3113
+ for output in repair_outputs:
3114
+ job = output.get("job") if isinstance(output.get("job"), dict) else {}
3115
+ original = job.get("item") if isinstance(job.get("item"), dict) else {}
3116
+ if not original:
3117
+ continue
3118
+ try:
3119
+ index = int(original.get("index"))
3120
+ except (TypeError, ValueError):
3121
+ continue
3122
+ if index < 0 or index >= len(final_items):
3123
+ continue
3124
+ repaired_item = deepcopy(original)
3125
+ exception = output.get("exception")
3126
+ if exception:
3127
+ repaired_item["relation_repair"] = {
3128
+ "attempted": True,
3129
+ "status": "failed",
3130
+ "error_code": "RELATION_REPAIR_EXCEPTION",
3131
+ "message": str(exception),
3132
+ }
3133
+ final_items[index] = repaired_item
3134
+ continue
3135
+ public_repair = output.get("public_repair") if isinstance(output.get("public_repair"), dict) else {}
3136
+ merge_child_duration(public_repair)
3137
+ if _schema_apply_result_has_write(public_repair):
3138
+ any_write_executed = True
3139
+ if _schema_apply_result_may_have_write(public_repair):
3140
+ any_write_may_have_succeeded = True
3141
+ repair_payload: JSONObject = {
3142
+ "attempted": True,
3143
+ "status": public_repair.get("status"),
3144
+ "error_code": public_repair.get("error_code"),
3145
+ "message": public_repair.get("message"),
3146
+ "verified": bool(public_repair.get("verified")),
3147
+ "field_diff": public_repair.get("field_diff") or {},
3148
+ **({"verification": public_repair.get("verification")} if isinstance(public_repair.get("verification"), dict) else {}),
3149
+ **({"details": public_repair.get("details")} if isinstance(public_repair.get("details"), dict) else {}),
3150
+ **({"duration_breakdown_ms": public_repair.get("duration_breakdown_ms")} if isinstance(public_repair.get("duration_breakdown_ms"), dict) else {}),
3151
+ }
3152
+ repaired_item["relation_repair"] = repair_payload
3153
+ repaired_item["field_diff"] = _merge_schema_field_diffs(repaired_item.get("field_diff") or {}, public_repair.get("field_diff") or {})
3154
+ repaired_item["field_diff_details"] = _merge_schema_field_diffs(
3155
+ repaired_item.get("field_diff_details") or {},
3156
+ public_repair.get("field_diff_details") or {},
3157
+ )
3158
+ if public_repair.get("status") == "success" and bool(public_repair.get("verified")):
3159
+ repaired_item["status"] = "success"
3160
+ repaired_item["error_code"] = None
3161
+ repaired_item["message"] = "applied schema patch; relation readback repaired"
3162
+ repaired_item["published"] = bool(public_repair.get("published"))
3163
+ repaired_item["verified"] = True
3164
+ original_verification = repaired_item.get("verification") if isinstance(repaired_item.get("verification"), dict) else {}
3165
+ repair_verification = public_repair.get("verification") if isinstance(public_repair.get("verification"), dict) else {}
3166
+ merged_verification = {**deepcopy(original_verification), **deepcopy(repair_verification)}
3167
+ repaired_item["verification"] = merged_verification
3168
+ details = repaired_item.get("details") if isinstance(repaired_item.get("details"), dict) else {}
3169
+ details = deepcopy(details)
3170
+ details.pop("relation_repair_plan", None)
3171
+ repaired_item["details"] = details
3172
+ final_items[index] = repaired_item
2075
3173
 
2076
3174
  pending_readback = sum(1 for item in final_items if item.get("status") == "pending_readback")
2077
3175
  succeeded = sum(1 for item in final_items if item.get("status") in {"success", "partial_success"})
@@ -2096,6 +3194,7 @@ class AiBuilderTools(ToolBase):
2096
3194
  "package_id": package_id,
2097
3195
  "publish_requested": publish,
2098
3196
  "apps": final_items,
3197
+ "parallelism": parallelism,
2099
3198
  "normalized_args": normalized_args,
2100
3199
  "verification": {
2101
3200
  "all_apps_succeeded": failed == 0,
@@ -2116,7 +3215,69 @@ class AiBuilderTools(ToolBase):
2116
3215
  response["next_action"] = "readback_before_retry"
2117
3216
  response["pending_readback_app_keys"] = list(dict.fromkeys(pending_readback_app_keys))
2118
3217
  response["pending_readback_app_names"] = list(dict.fromkeys(pending_readback_app_names))
2119
- return response
3218
+ return finish(response)
3219
+
3220
+ def _stabilize_deferred_relation_metadata(
3221
+ self,
3222
+ *,
3223
+ profile: str,
3224
+ source_app_key: str,
3225
+ deferred_add_fields: list[JSONObject],
3226
+ delay_seconds: float,
3227
+ ) -> list[JSONObject]:
3228
+ edit_context_result = self._finish_deferred_relation_edit_context(profile=profile, app_key=source_app_key)
3229
+ time.sleep(delay_seconds)
3230
+ app_keys = [source_app_key]
3231
+ for key in _multi_app_relation_target_app_keys(deferred_add_fields):
3232
+ if key and key not in app_keys:
3233
+ app_keys.append(key)
3234
+ readback: list[JSONObject] = []
3235
+ for app_key in app_keys:
3236
+ try:
3237
+ result = self._facade.app_read_fields(profile=profile, app_key=app_key)
3238
+ readback.append(
3239
+ {
3240
+ "app_key": app_key,
3241
+ "status": result.get("status"),
3242
+ "field_count": len(result.get("fields") or []),
3243
+ **({"edit_context": edit_context_result} if app_key == source_app_key else {}),
3244
+ }
3245
+ )
3246
+ except (QingflowApiError, RuntimeError) as error:
3247
+ api_error = _coerce_api_error(error)
3248
+ readback.append(
3249
+ {
3250
+ "app_key": app_key,
3251
+ "status": "failed",
3252
+ "transport_error": {
3253
+ "http_status": api_error.http_status,
3254
+ "backend_code": api_error.backend_code,
3255
+ "category": api_error.category,
3256
+ "request_id": api_error.request_id,
3257
+ },
3258
+ }
3259
+ )
3260
+ return readback
3261
+
3262
+ def _finish_deferred_relation_edit_context(self, *, profile: str, app_key: str) -> JSONObject:
3263
+ try:
3264
+ version_result = self._facade.apps.app_get_edit_version_no(profile=profile, app_key=app_key).get("result") or {}
3265
+ raw_version = version_result.get("editVersionNo") or version_result.get("versionNo") or 1
3266
+ edit_version_no = int(raw_version)
3267
+ self._facade.apps.app_edit_finished(profile=profile, app_key=app_key, payload={"editVersionNo": edit_version_no})
3268
+ return {"status": "success", "edit_version_no": edit_version_no}
3269
+ except (QingflowApiError, RuntimeError, TypeError, ValueError) as error:
3270
+ api_error = _coerce_api_error(error if isinstance(error, (QingflowApiError, RuntimeError)) else RuntimeError(str(error)))
3271
+ return {
3272
+ "status": "failed",
3273
+ "message": api_error.message,
3274
+ "transport_error": {
3275
+ "http_status": api_error.http_status,
3276
+ "backend_code": api_error.backend_code,
3277
+ "category": api_error.category,
3278
+ "request_id": api_error.request_id,
3279
+ },
3280
+ }
2120
3281
 
2121
3282
  def _app_schema_apply_once(
2122
3283
  self,
@@ -2129,14 +3290,17 @@ class AiBuilderTools(ToolBase):
2129
3290
  icon: str = "",
2130
3291
  color: str = "",
2131
3292
  visibility: JSONObject | None = None,
2132
- create_if_missing: bool = False,
2133
3293
  publish: bool = True,
2134
3294
  add_fields: list[JSONObject],
2135
3295
  update_fields: list[JSONObject],
2136
3296
  remove_fields: list[JSONObject],
3297
+ inline_form_layout_sections: list[JSONObject] | None = None,
3298
+ allow_inline_layout_fallback: bool = True,
2137
3299
  ) -> JSONObject:
2138
3300
  """执行内部辅助逻辑。"""
3301
+ started_at = time.perf_counter()
2139
3302
  effective_app_name = app_name or app_title
3303
+ creating = not bool(str(app_key or "").strip()) and package_id is not None and bool(str(effective_app_name or "").strip())
2140
3304
  system_field_failure = _reserved_system_field_name_failure(
2141
3305
  tool_name="app_schema_apply",
2142
3306
  profile=profile,
@@ -2146,7 +3310,6 @@ class AiBuilderTools(ToolBase):
2146
3310
  icon=icon,
2147
3311
  color=color,
2148
3312
  visibility=visibility,
2149
- create_if_missing=create_if_missing,
2150
3313
  publish=publish,
2151
3314
  add_fields=add_fields,
2152
3315
  update_fields=update_fields,
@@ -2158,38 +3321,19 @@ class AiBuilderTools(ToolBase):
2158
3321
  tool_name="app_schema_apply",
2159
3322
  icon=icon,
2160
3323
  color=color,
2161
- creating=not bool(str(app_key or "").strip()) and bool(create_if_missing),
3324
+ creating=creating,
2162
3325
  )
2163
3326
  if icon_failure is not None:
2164
3327
  return icon_failure
2165
- plan_result = self._rewrite_plan_result_for_apply(
2166
- result=self.app_schema_plan(
2167
- profile=profile,
2168
- app_key=app_key,
2169
- package_id=package_id,
2170
- app_name=effective_app_name,
2171
- icon=icon,
2172
- color=color,
2173
- visibility=visibility,
2174
- create_if_missing=create_if_missing,
2175
- add_fields=add_fields,
2176
- update_fields=update_fields,
2177
- remove_fields=remove_fields,
2178
- ),
2179
- profile=profile,
2180
- publish=publish,
2181
- plan_tool_name="app_schema_plan",
2182
- apply_tool_name="app_schema_apply",
2183
- )
2184
- if not isinstance(plan_result, dict) or plan_result.get("status") != "success":
2185
- return plan_result
2186
- plan_args = plan_result.get("normalized_args")
2187
- if not isinstance(plan_args, dict):
2188
- plan_args = {}
2189
3328
  try:
2190
- parsed_add = [FieldPatch.model_validate(item) for item in plan_args.get("add_fields") or []]
2191
- parsed_update = [FieldUpdatePatch.model_validate(item) for item in plan_args.get("update_fields") or []]
2192
- parsed_remove = [FieldRemovePatch.model_validate(item) for item in plan_args.get("remove_fields") or []]
3329
+ parsed_add = [FieldPatch.model_validate(item) for item in add_fields or []]
3330
+ parsed_update = [FieldUpdatePatch.model_validate(item) for item in update_fields or []]
3331
+ parsed_remove = [FieldRemovePatch.model_validate(item) for item in remove_fields or []]
3332
+ parsed_inline_layout = [
3333
+ LayoutSectionPatch.model_validate(item)
3334
+ for item in (inline_form_layout_sections or [])
3335
+ ]
3336
+ parsed_visibility = VisibilityPatch.model_validate(visibility) if visibility is not None else None
2193
3337
  except ValidationError as exc:
2194
3338
  return _validation_failure(
2195
3339
  str(exc),
@@ -2199,57 +3343,170 @@ class AiBuilderTools(ToolBase):
2199
3343
  "tool_name": "app_schema_apply",
2200
3344
  "arguments": {
2201
3345
  "profile": profile,
2202
- "app_key": str(plan_args.get("app_key") or app_key),
2203
- "package_id": plan_args.get("package_id", package_id),
2204
- "app_name": str(plan_args.get("app_name") or effective_app_name),
2205
- "icon": str(plan_args.get("icon") or icon),
2206
- "color": str(plan_args.get("color") or color),
2207
- "visibility": plan_args.get("visibility") or visibility,
2208
- "create_if_missing": bool(plan_args.get("create_if_missing", create_if_missing)),
3346
+ "app_key": str(app_key or ""),
3347
+ "package_id": package_id,
3348
+ "app_name": effective_app_name,
3349
+ "icon": str(icon or ""),
3350
+ "color": str(color or ""),
3351
+ "visibility": visibility,
2209
3352
  "publish": publish,
2210
- "add_fields": plan_args.get("add_fields") or [{"name": "字段名称", "type": "text", "required": False}],
2211
- "update_fields": plan_args.get("update_fields") or [],
2212
- "remove_fields": plan_args.get("remove_fields") or [],
3353
+ "add_fields": add_fields or [{"name": "字段名称", "type": "text", "required": False}],
3354
+ "update_fields": update_fields or [],
3355
+ "remove_fields": remove_fields or [],
2213
3356
  },
2214
3357
  },
2215
3358
  )
2216
3359
  normalized_args = {
2217
- "app_key": str(plan_args.get("app_key") or app_key),
2218
- "package_id": plan_args.get("package_id", package_id),
2219
- "app_name": str(plan_args.get("app_name") or effective_app_name),
2220
- "icon": str(plan_args.get("icon") or icon or ""),
2221
- "color": str(plan_args.get("color") or color or ""),
2222
- "visibility": plan_args.get("visibility") or visibility,
2223
- "create_if_missing": bool(plan_args.get("create_if_missing", create_if_missing)),
3360
+ "app_key": str(app_key or ""),
3361
+ "package_id": package_id,
3362
+ "app_name": effective_app_name,
3363
+ "icon": str(icon or ""),
3364
+ "color": str(color or ""),
3365
+ "visibility": parsed_visibility.model_dump(mode="json") if parsed_visibility is not None else None,
2224
3366
  "publish": publish,
2225
3367
  "add_fields": [patch.model_dump(mode="json") for patch in parsed_add],
2226
3368
  "update_fields": [patch.model_dump(mode="json") for patch in parsed_update],
2227
3369
  "remove_fields": [patch.model_dump(mode="json") for patch in parsed_remove],
3370
+ **(
3371
+ {
3372
+ "inline_form_layout_sections": [
3373
+ section.model_dump(mode="json", exclude_none=True)
3374
+ for section in parsed_inline_layout
3375
+ ]
3376
+ }
3377
+ if parsed_inline_layout
3378
+ else {}
3379
+ ),
2228
3380
  }
2229
3381
  result = _safe_tool_call(
2230
3382
  lambda: self._facade.app_schema_apply(
2231
3383
  profile=profile,
2232
- app_key=str(plan_args.get("app_key") or app_key),
2233
- package_tag_id=plan_args.get("package_id", package_id),
2234
- app_name=str(plan_args.get("app_name") or effective_app_name),
2235
- icon=str(plan_args.get("icon") or icon or ""),
2236
- color=str(plan_args.get("color") or color or ""),
2237
- visibility=VisibilityPatch.model_validate(plan_args.get("visibility")) if plan_args.get("visibility") is not None else None,
2238
- create_if_missing=bool(plan_args.get("create_if_missing", create_if_missing)),
3384
+ app_key=str(app_key or ""),
3385
+ package_tag_id=package_id,
3386
+ app_name=effective_app_name,
3387
+ icon=str(icon or ""),
3388
+ color=str(color or ""),
3389
+ visibility=parsed_visibility,
2239
3390
  publish=publish,
2240
3391
  add_fields=parsed_add,
2241
3392
  update_fields=parsed_update,
2242
3393
  remove_fields=parsed_remove,
3394
+ inline_form_layout_sections=parsed_inline_layout,
2243
3395
  ),
2244
3396
  error_code="SCHEMA_APPLY_FAILED",
2245
3397
  normalized_args=normalized_args,
2246
3398
  suggested_next_call={"tool_name": "app_schema_apply", "arguments": {"profile": profile, **normalized_args}},
2247
3399
  )
2248
- return _publicize_package_fields(result)
3400
+ public_result = _publicize_package_fields(result)
3401
+ if inline_form_layout_sections and allow_inline_layout_fallback and not _inline_form_layout_was_handled(public_result):
3402
+ layout_started_at = time.perf_counter()
3403
+ public_result = self._apply_inline_form_layout_after_schema(
3404
+ profile=profile,
3405
+ schema_result=public_result,
3406
+ fallback_app_key=str(app_key or ""),
3407
+ publish=publish,
3408
+ sections=inline_form_layout_sections,
3409
+ )
3410
+ _merge_duration_breakdown(
3411
+ public_result,
3412
+ inline_layout_ms=_elapsed_ms(layout_started_at),
3413
+ )
3414
+ _merge_duration_breakdown(public_result, total_ms=_elapsed_ms(started_at))
3415
+ return public_result
3416
+
3417
+ def _apply_inline_form_layout_after_schema(
3418
+ self,
3419
+ *,
3420
+ profile: str,
3421
+ schema_result: JSONObject,
3422
+ fallback_app_key: str = "",
3423
+ publish: bool,
3424
+ sections: list[JSONObject],
3425
+ ) -> JSONObject:
3426
+ result = deepcopy(schema_result)
3427
+ if not sections:
3428
+ return result
3429
+ app_key = str(result.get("app_key") or result.get("appKey") or fallback_app_key or "").strip()
3430
+ result["inline_form_layout"] = {
3431
+ "requested": True,
3432
+ "section_count": len(sections),
3433
+ "applied": False,
3434
+ }
3435
+ if result.get("status") not in {"success", "partial_success"}:
3436
+ result["inline_form_layout"]["skipped_reason"] = "schema_apply_failed"
3437
+ verification = result.get("verification") if isinstance(result.get("verification"), dict) else {}
3438
+ verification = deepcopy(verification)
3439
+ verification["inline_form_layout_verified"] = False
3440
+ result["verification"] = verification
3441
+ return result
3442
+ if not app_key:
3443
+ result["status"] = "partial_success"
3444
+ result["error_code"] = result.get("error_code") or "INLINE_FORM_LAYOUT_APP_KEY_MISSING"
3445
+ result["message"] = "schema applied but inline form layout could not run because app_key was not resolved"
3446
+ result["inline_form_layout"]["error_code"] = "INLINE_FORM_LAYOUT_APP_KEY_MISSING"
3447
+ verification = result.get("verification") if isinstance(result.get("verification"), dict) else {}
3448
+ verification = deepcopy(verification)
3449
+ verification["inline_form_layout_verified"] = False
3450
+ result["verification"] = verification
3451
+ result["safe_to_retry"] = False
3452
+ return result
3453
+ layout_result = self._app_layout_apply_once(
3454
+ profile=profile,
3455
+ app_key=app_key,
3456
+ mode="merge",
3457
+ publish=publish,
3458
+ sections=sections,
3459
+ )
3460
+ layout_ok = isinstance(layout_result, dict) and layout_result.get("status") in {"success", "partial_success"}
3461
+ result["inline_form_layout"] = {
3462
+ "requested": True,
3463
+ "section_count": len(sections),
3464
+ "app_key": app_key,
3465
+ "applied": layout_ok,
3466
+ "layout_status": layout_result.get("status") if isinstance(layout_result, dict) else "failed",
3467
+ **({"error_code": layout_result.get("error_code")} if isinstance(layout_result, dict) and layout_result.get("error_code") else {}),
3468
+ **({"message": layout_result.get("message")} if isinstance(layout_result, dict) and layout_result.get("message") else {}),
3469
+ }
3470
+ result["inline_form_layout_result"] = layout_result
3471
+ verification = result.get("verification") if isinstance(result.get("verification"), dict) else {}
3472
+ verification = deepcopy(verification)
3473
+ verification["inline_form_layout_verified"] = layout_ok
3474
+ result["verification"] = verification
3475
+ if layout_ok:
3476
+ result["write_executed"] = True
3477
+ return result
3478
+ result["status"] = "partial_success" if result.get("status") == "success" else result.get("status", "partial_success")
3479
+ result["error_code"] = result.get("error_code") or "INLINE_FORM_LAYOUT_APPLY_FAILED"
3480
+ result["message"] = "schema applied but inline form layout failed"
3481
+ result["safe_to_retry"] = False
3482
+ return result
2249
3483
 
2250
3484
  @tool_cn_name("应用布局应用")
2251
- def app_layout_apply(self, *, profile: str, app_key: str, mode: str = "merge", publish: bool = True, sections: list[JSONObject]) -> JSONObject:
3485
+ def app_layout_apply(
3486
+ self,
3487
+ *,
3488
+ profile: str,
3489
+ app_key: str,
3490
+ mode: str = "merge",
3491
+ publish: bool = True,
3492
+ sections: list[JSONObject],
3493
+ apps: list[JSONObject] | None = None,
3494
+ ) -> JSONObject:
2252
3495
  """执行应用相关逻辑。"""
3496
+ if apps is not None:
3497
+ return self._apply_app_batch(
3498
+ tool_name="app_layout_apply",
3499
+ profile=profile,
3500
+ apps=apps,
3501
+ apply_one=lambda _index, item, item_app_key: self.app_layout_apply(
3502
+ profile=profile,
3503
+ app_key=item_app_key,
3504
+ mode=str(_payload_get(item, "mode", default=mode) or mode),
3505
+ publish=_payload_bool(item, "publish", default=publish),
3506
+ sections=_payload_list(item, "sections", default=sections or []),
3507
+ apps=None,
3508
+ ),
3509
+ )
2253
3510
  result = self._app_layout_apply_once(
2254
3511
  profile=profile,
2255
3512
  app_key=app_key,
@@ -2272,27 +3529,9 @@ class AiBuilderTools(ToolBase):
2272
3529
 
2273
3530
  def _app_layout_apply_once(self, *, profile: str, app_key: str, mode: str = "merge", publish: bool = True, sections: list[JSONObject]) -> JSONObject:
2274
3531
  """执行内部辅助逻辑。"""
2275
- plan_result = self._rewrite_plan_result_for_apply(
2276
- result=self.app_layout_plan(
2277
- profile=profile,
2278
- app_key=app_key,
2279
- mode=mode,
2280
- sections=sections,
2281
- preset=None,
2282
- ),
2283
- profile=profile,
2284
- publish=publish,
2285
- plan_tool_name="app_layout_plan",
2286
- apply_tool_name="app_layout_apply",
2287
- )
2288
- if not isinstance(plan_result, dict) or plan_result.get("status") != "success":
2289
- return plan_result
2290
- plan_args = plan_result.get("normalized_args")
2291
- if not isinstance(plan_args, dict):
2292
- plan_args = {}
2293
3532
  try:
2294
- parsed_mode = LayoutApplyMode(str(plan_args.get("mode") or mode))
2295
- parsed_sections = [LayoutSectionPatch.model_validate(item) for item in plan_args.get("sections") or []]
3533
+ parsed_mode = LayoutApplyMode(str(mode or "merge"))
3534
+ parsed_sections = [LayoutSectionPatch.model_validate(item) for item in sections or []]
2296
3535
  except (ValueError, ValidationError) as exc:
2297
3536
  return _validation_failure(
2298
3537
  str(exc),
@@ -2302,15 +3541,15 @@ class AiBuilderTools(ToolBase):
2302
3541
  "tool_name": "app_layout_apply",
2303
3542
  "arguments": {
2304
3543
  "profile": profile,
2305
- "app_key": str(plan_args.get("app_key") or app_key),
2306
- "mode": str(plan_args.get("mode") or "merge"),
3544
+ "app_key": app_key,
3545
+ "mode": str(mode or "merge"),
2307
3546
  "publish": publish,
2308
- "sections": plan_args.get("sections") or [{"title": "基础信息", "rows": [["字段A", "字段B"]]}],
3547
+ "sections": sections or [{"title": "基础信息", "rows": [["字段A", "字段B"]]}],
2309
3548
  },
2310
3549
  },
2311
3550
  )
2312
3551
  normalized_args = {
2313
- "app_key": str(plan_args.get("app_key") or app_key),
3552
+ "app_key": app_key,
2314
3553
  "mode": parsed_mode.value,
2315
3554
  "publish": publish,
2316
3555
  "sections": [section.model_dump(mode="json", exclude_none=True) for section in parsed_sections],
@@ -2318,7 +3557,7 @@ class AiBuilderTools(ToolBase):
2318
3557
  return _safe_tool_call(
2319
3558
  lambda: self._facade.app_layout_apply(
2320
3559
  profile=profile,
2321
- app_key=str(plan_args.get("app_key") or app_key),
3560
+ app_key=app_key,
2322
3561
  mode=parsed_mode,
2323
3562
  publish=publish,
2324
3563
  sections=parsed_sections,
@@ -2334,51 +3573,140 @@ class AiBuilderTools(ToolBase):
2334
3573
  *,
2335
3574
  profile: str,
2336
3575
  app_key: str,
2337
- spec: JSONObject,
3576
+ mode: str = "replace",
2338
3577
  publish: bool = True,
3578
+ nodes: list[JSONObject] | None = None,
3579
+ transitions: list[JSONObject] | None = None,
3580
+ spec: JSONObject | None = None,
2339
3581
  idempotency_key: str | None = None,
2340
3582
  schema_version: str | None = None,
3583
+ patch_nodes: list[JSONObject] | None = None,
2341
3584
  ) -> JSONObject:
2342
3585
  """执行应用相关逻辑。"""
2343
- if not isinstance(spec, dict) or not spec:
2344
- return _config_failure(
3586
+ if patch_nodes is not None:
3587
+ normalized_args = {
3588
+ "app_key": app_key,
3589
+ "publish": publish,
3590
+ "patch_nodes": patch_nodes,
3591
+ "idempotency_key": idempotency_key,
3592
+ "schema_version": schema_version,
3593
+ }
3594
+ return _attach_builder_apply_envelope("app_flow_apply", _safe_tool_call(
3595
+ lambda: self._facade.flow_patch_nodes(
3596
+ profile=profile,
3597
+ app_key=app_key,
3598
+ patch_nodes=patch_nodes,
3599
+ publish=publish,
3600
+ idempotency_key=idempotency_key,
3601
+ schema_version=schema_version,
3602
+ ),
3603
+ error_code="FLOW_PATCH_FAILED",
3604
+ normalized_args=normalized_args,
3605
+ suggested_next_call={"tool_name": "app_flow_get", "arguments": {"profile": profile, "app_key": app_key}},
3606
+ ))
3607
+ if spec is not None:
3608
+ normalized_args = {
3609
+ "app_key": app_key,
3610
+ "publish": publish,
3611
+ "spec": spec,
3612
+ "idempotency_key": idempotency_key,
3613
+ "schema_version": schema_version,
3614
+ }
3615
+ return _attach_builder_apply_envelope("app_flow_apply", _safe_tool_call(
3616
+ lambda: self._facade.flow_apply(
3617
+ profile=profile,
3618
+ app_key=app_key,
3619
+ spec=spec,
3620
+ publish=publish,
3621
+ idempotency_key=idempotency_key,
3622
+ schema_version=schema_version,
3623
+ ),
3624
+ error_code="FLOW_SPEC_APPLY_FAILED",
3625
+ normalized_args=normalized_args,
3626
+ suggested_next_call={"tool_name": "app_flow_get", "arguments": {"profile": profile, "app_key": app_key}},
3627
+ ))
3628
+ effective_nodes = nodes or []
3629
+ effective_transitions = transitions or []
3630
+ result = self._app_flow_apply_once(
3631
+ profile=profile,
3632
+ app_key=app_key,
3633
+ mode=mode,
3634
+ publish=publish,
3635
+ nodes=effective_nodes,
3636
+ transitions=effective_transitions,
3637
+ )
3638
+ result = self._retry_after_self_lock_release(
3639
+ profile=profile,
3640
+ result=result,
3641
+ retry_call=lambda: self._app_flow_apply_once(
3642
+ profile=profile,
3643
+ app_key=app_key,
3644
+ mode=mode,
3645
+ publish=publish,
3646
+ nodes=effective_nodes,
3647
+ transitions=effective_transitions,
3648
+ ),
3649
+ )
3650
+ return _attach_builder_apply_envelope("app_flow_apply", result)
3651
+
3652
+ def _app_flow_apply_once(
3653
+ self,
3654
+ *,
3655
+ profile: str,
3656
+ app_key: str,
3657
+ mode: str = "replace",
3658
+ publish: bool = True,
3659
+ nodes: list[JSONObject],
3660
+ transitions: list[JSONObject],
3661
+ ) -> JSONObject:
3662
+ """执行内部辅助逻辑。"""
3663
+ try:
3664
+ request = FlowPlanRequest.model_validate(
3665
+ {
3666
+ "app_key": app_key,
3667
+ "mode": mode,
3668
+ "nodes": nodes or [],
3669
+ "transitions": transitions or [],
3670
+ "preset": None,
3671
+ }
3672
+ )
3673
+ except ValidationError as exc:
3674
+ return _validation_failure(
3675
+ str(exc),
2345
3676
  tool_name="app_flow_apply",
2346
- message="app_flow_apply requires a non-empty WorkflowSpecDTO `spec` object.",
2347
- fix_hint="Call app_flow_get_schema, then app_flow_get for GET-first baseline, patch spec, and apply.",
3677
+ exc=exc,
3678
+ suggested_next_call={
3679
+ "tool_name": "app_flow_apply",
3680
+ "arguments": {
3681
+ "profile": profile,
3682
+ "app_key": app_key,
3683
+ "mode": str(mode or "replace"),
3684
+ "publish": publish,
3685
+ "nodes": nodes or [{"id": "start", "type": "start", "name": "发起"}],
3686
+ "transitions": transitions or [],
3687
+ },
3688
+ },
2348
3689
  )
2349
3690
  normalized_args = {
2350
- "app_key": app_key,
3691
+ "app_key": request.app_key,
3692
+ "mode": request.mode,
2351
3693
  "publish": publish,
2352
- "spec": spec,
2353
- "idempotency_key": idempotency_key,
2354
- "schema_version": schema_version,
3694
+ "nodes": [node.model_dump(mode="json") for node in request.nodes],
3695
+ "transitions": [transition.model_dump(mode="json", by_alias=True) for transition in request.transitions],
2355
3696
  }
2356
- result = _safe_tool_call(
2357
- lambda: self._facade.flow_apply(
3697
+ return _safe_tool_call(
3698
+ lambda: self._facade.app_flow_apply(
2358
3699
  profile=profile,
2359
- app_key=app_key,
2360
- spec=spec,
3700
+ app_key=request.app_key,
3701
+ mode=request.mode,
2361
3702
  publish=publish,
2362
- idempotency_key=idempotency_key,
2363
- schema_version=schema_version,
3703
+ nodes=[node.model_dump(mode="json") for node in request.nodes],
3704
+ transitions=[transition.model_dump(mode="json", by_alias=True) for transition in request.transitions],
2364
3705
  ),
2365
3706
  error_code="FLOW_APPLY_FAILED",
2366
3707
  normalized_args=normalized_args,
2367
3708
  suggested_next_call={"tool_name": "app_flow_apply", "arguments": {"profile": profile, **normalized_args}},
2368
3709
  )
2369
- result = self._retry_after_self_lock_release(
2370
- profile=profile,
2371
- result=result,
2372
- retry_call=lambda: self._facade.flow_apply(
2373
- profile=profile,
2374
- app_key=app_key,
2375
- spec=spec,
2376
- publish=publish,
2377
- idempotency_key=idempotency_key,
2378
- schema_version=schema_version,
2379
- ),
2380
- )
2381
- return _attach_builder_apply_envelope("app_flow_apply", result)
2382
3710
 
2383
3711
  @tool_cn_name("应用视图应用")
2384
3712
  def app_views_apply(
@@ -2390,8 +3718,31 @@ class AiBuilderTools(ToolBase):
2390
3718
  upsert_views: list[JSONObject],
2391
3719
  patch_views: list[JSONObject] | None = None,
2392
3720
  remove_views: list[str],
3721
+ apps: list[JSONObject] | None = None,
3722
+ views: list[JSONObject] | None = None,
2393
3723
  ) -> JSONObject:
2394
3724
  """执行应用相关逻辑。"""
3725
+ if views is not None:
3726
+ return self._app_views_apply_view_batch(
3727
+ profile=profile,
3728
+ publish=publish,
3729
+ views=views,
3730
+ )
3731
+ if apps is not None:
3732
+ return self._apply_app_batch(
3733
+ tool_name="app_views_apply",
3734
+ profile=profile,
3735
+ apps=apps,
3736
+ apply_one=lambda _index, item, item_app_key: self.app_views_apply(
3737
+ profile=profile,
3738
+ app_key=item_app_key,
3739
+ publish=_payload_bool(item, "publish", default=publish),
3740
+ upsert_views=_payload_list(item, "upsert_views", "upsertViews", "views", default=upsert_views or []),
3741
+ patch_views=_payload_list(item, "patch_views", "patchViews", default=patch_views or []),
3742
+ remove_views=_payload_list(item, "remove_views", "removeViews", default=remove_views or []),
3743
+ apps=None,
3744
+ ),
3745
+ )
2395
3746
  result = self._app_views_apply_once(
2396
3747
  profile=profile,
2397
3748
  app_key=app_key,
@@ -2414,6 +3765,248 @@ class AiBuilderTools(ToolBase):
2414
3765
  )
2415
3766
  return _attach_builder_apply_envelope("app_views_apply", result)
2416
3767
 
3768
+ def _app_views_apply_view_batch(
3769
+ self,
3770
+ *,
3771
+ profile: str,
3772
+ publish: bool,
3773
+ views: list[JSONObject],
3774
+ ) -> JSONObject:
3775
+ started_at = time.perf_counter()
3776
+ if not isinstance(views, list) or not views:
3777
+ return _attach_builder_apply_envelope(
3778
+ "app_views_apply",
3779
+ _config_failure(
3780
+ tool_name="app_views_apply",
3781
+ message="app_views_apply views[] batch mode requires a non-empty views array.",
3782
+ fix_hint="Pass views as a JSON array; each item must include app_key and operation.",
3783
+ details={"expected_shape": {"views": [{"operation": "upsert", "app_key": "APP_KEY", "name": "业务视图", "type": "table", "columns": ["字段A"]}]}},
3784
+ ),
3785
+ )
3786
+
3787
+ def _infer_operation(item: JSONObject) -> str:
3788
+ raw = str(item.get("operation") or item.get("op") or "").strip().lower()
3789
+ aliases = {
3790
+ "create": "upsert",
3791
+ "update": "upsert",
3792
+ "replace": "upsert",
3793
+ "delete": "remove",
3794
+ "remove": "remove",
3795
+ "patch": "patch",
3796
+ "upsert": "upsert",
3797
+ }
3798
+ if raw:
3799
+ return aliases.get(raw, raw)
3800
+ if "set" in item or "unset" in item or "update" in item or "values" in item:
3801
+ return "patch"
3802
+ if "view_key" in item or "viewKey" in item:
3803
+ return "patch" if ("name" in item or "type" in item or "columns" in item or "fields" in item) else "remove"
3804
+ return "upsert"
3805
+
3806
+ def _view_job_payload(item: JSONObject) -> JSONObject:
3807
+ return {
3808
+ key: deepcopy(value)
3809
+ for key, value in item.items()
3810
+ if key
3811
+ not in {
3812
+ "operation",
3813
+ "op",
3814
+ "app_key",
3815
+ "appKey",
3816
+ "publish",
3817
+ }
3818
+ }
3819
+
3820
+ def _view_selector(payload: JSONObject) -> str:
3821
+ return str(payload.get("view_key") or payload.get("viewKey") or payload.get("viewgraphKey") or payload.get("viewGraphKey") or payload.get("name") or "").strip()
3822
+
3823
+ normalized_jobs: list[JSONObject] = []
3824
+ job_results: list[JSONObject | None] = [None for _ in views]
3825
+ errors: list[JSONObject] = []
3826
+ seen_patch_remove: dict[tuple[str, str], int] = {}
3827
+ seen_upsert_names: dict[tuple[str, str], int] = {}
3828
+
3829
+ def _add_validation_error(index: int, error_code: str, message: str, *, app_key: str = "", operation: str = "", reason_path: str = "") -> None:
3830
+ error = {
3831
+ "index": index,
3832
+ "app_key": app_key,
3833
+ "operation": operation,
3834
+ "status": "failed",
3835
+ "error_code": error_code,
3836
+ "message": message,
3837
+ **({"reason_path": reason_path} if reason_path else {}),
3838
+ }
3839
+ errors.append(error)
3840
+ job_results[index] = error
3841
+
3842
+ for index, item in enumerate(views):
3843
+ if not isinstance(item, dict):
3844
+ _add_validation_error(index, "VIEWS_FILE_ITEM_INVALID", "views[] item must be an object", reason_path=f"views[{index}]")
3845
+ continue
3846
+ app_key = str(item.get("app_key") or item.get("appKey") or "").strip()
3847
+ operation = _infer_operation(item)
3848
+ payload = _view_job_payload(item)
3849
+ if not app_key:
3850
+ _add_validation_error(index, "VIEWS_FILE_APP_KEY_REQUIRED", "views[] item requires app_key", operation=operation, reason_path=f"views[{index}].app_key")
3851
+ continue
3852
+ if operation not in {"upsert", "patch", "remove"}:
3853
+ _add_validation_error(index, "VIEWS_FILE_OPERATION_INVALID", "views[].operation must be upsert, patch, or remove", app_key=app_key, operation=operation, reason_path=f"views[{index}].operation")
3854
+ continue
3855
+ selector = _view_selector(payload)
3856
+ if operation in {"patch", "remove"} and not selector:
3857
+ _add_validation_error(index, "VIEWS_FILE_VIEW_SELECTOR_REQUIRED", f"{operation} view job requires view_key or name", app_key=app_key, operation=operation, reason_path=f"views[{index}].view_key")
3858
+ continue
3859
+ if operation in {"patch", "remove"} and selector:
3860
+ conflict_key = (app_key, selector)
3861
+ first_index = seen_patch_remove.get(conflict_key)
3862
+ if first_index is not None:
3863
+ _add_validation_error(index, "DUPLICATE_VIEW_JOB_CONFLICT", f"views[{index}] conflicts with views[{first_index}] for the same app/view selector", app_key=app_key, operation=operation, reason_path=f"views[{index}]")
3864
+ continue
3865
+ seen_patch_remove[conflict_key] = index
3866
+ if operation == "upsert":
3867
+ name = str(payload.get("name") or "").strip()
3868
+ if name:
3869
+ conflict_key = (app_key, name)
3870
+ first_index = seen_upsert_names.get(conflict_key)
3871
+ if first_index is not None:
3872
+ _add_validation_error(index, "DUPLICATE_VIEW_NAME_IN_BATCH", f"views[{index}] duplicates upsert view name from views[{first_index}] in the same app", app_key=app_key, operation=operation, reason_path=f"views[{index}].name")
3873
+ continue
3874
+ seen_upsert_names[conflict_key] = index
3875
+ normalized_jobs.append(
3876
+ {
3877
+ "index": index,
3878
+ "app_key": app_key,
3879
+ "operation": operation,
3880
+ "publish": _payload_bool(item, "publish", default=publish),
3881
+ "payload": payload,
3882
+ }
3883
+ )
3884
+
3885
+ def _extract_view_identity(result: JSONObject, fallback_payload: JSONObject, fallback_operation: str) -> tuple[str | None, str | None, str]:
3886
+ diff = result.get("views_diff") if isinstance(result.get("views_diff"), dict) else {}
3887
+ for key, operation_name in (("created", "created"), ("updated", "updated"), ("removed", "removed"), ("failed", "failed")):
3888
+ entries = diff.get(key)
3889
+ if isinstance(entries, list) and entries:
3890
+ entry = entries[0]
3891
+ if isinstance(entry, dict):
3892
+ return (
3893
+ str(entry.get("name") or entry.get("view_name") or entry.get("viewName") or fallback_payload.get("name") or "").strip() or None,
3894
+ str(entry.get("view_key") or entry.get("viewKey") or fallback_payload.get("view_key") or fallback_payload.get("viewKey") or "").strip() or None,
3895
+ operation_name,
3896
+ )
3897
+ if entry not in (None, ""):
3898
+ return (str(entry), None, operation_name)
3899
+ fallback_name = str(fallback_payload.get("name") or "").strip() or None
3900
+ fallback_view_key = str(fallback_payload.get("view_key") or fallback_payload.get("viewKey") or "").strip() or None
3901
+ return fallback_name, fallback_view_key, "removed" if fallback_operation == "remove" else "updated"
3902
+
3903
+ def _run_view_job(job: JSONObject) -> JSONObject:
3904
+ payload = deepcopy(job["payload"])
3905
+ operation = str(job["operation"])
3906
+ app_key = str(job["app_key"])
3907
+ job_publish = bool(job.get("publish"))
3908
+ if operation == "upsert":
3909
+ call_kwargs = {"upsert_views": [payload], "patch_views": [], "remove_views": []}
3910
+ elif operation == "patch":
3911
+ call_kwargs = {"upsert_views": [], "patch_views": [payload], "remove_views": []}
3912
+ else:
3913
+ call_kwargs = {"upsert_views": [], "patch_views": [], "remove_views": [_view_selector(payload)]}
3914
+ result = self._app_views_apply_once(
3915
+ profile=profile,
3916
+ app_key=app_key,
3917
+ publish=job_publish,
3918
+ **call_kwargs,
3919
+ )
3920
+ result = self._retry_after_self_lock_release(
3921
+ profile=profile,
3922
+ result=result,
3923
+ retry_call=lambda: self._app_views_apply_once(
3924
+ profile=profile,
3925
+ app_key=app_key,
3926
+ publish=job_publish,
3927
+ **call_kwargs,
3928
+ ),
3929
+ )
3930
+ status = str(result.get("status") or "success") if isinstance(result, dict) else "failed"
3931
+ name, view_key, actual_operation = _extract_view_identity(result if isinstance(result, dict) else {}, payload, operation)
3932
+ item: JSONObject = {
3933
+ "index": job["index"],
3934
+ "app_key": app_key,
3935
+ "operation": actual_operation if status != "failed" else operation,
3936
+ "requested_operation": operation,
3937
+ "status": status,
3938
+ **({"name": name} if name else {}),
3939
+ **({"view_key": view_key} if view_key else {}),
3940
+ "result": result if isinstance(result, dict) else {"status": "failed", "message": str(result)},
3941
+ }
3942
+ if status == "failed":
3943
+ item["error_code"] = item["result"].get("error_code")
3944
+ item["message"] = item["result"].get("message")
3945
+ return item
3946
+
3947
+ view_write_started_at = time.perf_counter()
3948
+ view_workers = min(VIEW_APPLY_PARALLEL_LIMIT, len(normalized_jobs)) if normalized_jobs else 0
3949
+ if normalized_jobs:
3950
+ with ThreadPoolExecutor(max_workers=view_workers) as executor:
3951
+ future_map = {executor.submit(_run_view_job, job): job for job in normalized_jobs}
3952
+ for future in as_completed(future_map):
3953
+ job = future_map[future]
3954
+ try:
3955
+ item_result = future.result()
3956
+ except (QingflowApiError, RuntimeError) as error:
3957
+ api_error = _coerce_api_error(error)
3958
+ item_result = {
3959
+ "index": job["index"],
3960
+ "app_key": job["app_key"],
3961
+ "operation": job["operation"],
3962
+ "requested_operation": job["operation"],
3963
+ "status": "failed",
3964
+ "error_code": "VIEW_BATCH_JOB_FAILED",
3965
+ "message": _public_error_message("VIEW_BATCH_JOB_FAILED", api_error),
3966
+ "details": {"transport_error": _transport_error_payload(api_error)},
3967
+ "request_id": api_error.request_id,
3968
+ "backend_code": api_error.backend_code,
3969
+ "http_status": None if api_error.http_status == 404 else api_error.http_status,
3970
+ }
3971
+ job_results[int(job["index"])] = item_result
3972
+ view_write_parallel_wall_ms = _elapsed_ms(view_write_started_at)
3973
+
3974
+ final_views = [item if isinstance(item, dict) else {"index": index, "status": "failed", "error_code": "VIEW_BATCH_JOB_MISSING", "message": "view batch job did not produce a result"} for index, item in enumerate(job_results)]
3975
+ errors.extend(item for item in final_views if str(item.get("status") or "") == "failed" and item not in errors)
3976
+ partial = sum(1 for item in final_views if str(item.get("status") or "") == "partial_success")
3977
+ succeeded = sum(1 for item in final_views if str(item.get("status") or "") in {"success", "partial_success"})
3978
+ failed = len(final_views) - succeeded
3979
+ status = "failed" if succeeded == 0 else "partial_success" if failed > 0 or partial > 0 else "success"
3980
+ write_executed = any(
3981
+ isinstance(item.get("result"), dict) and bool(item["result"].get("write_executed"))
3982
+ for item in final_views
3983
+ )
3984
+ payload: JSONObject = {
3985
+ "status": status,
3986
+ "error_code": None if status == "success" else "APP_VIEWS_APPLY_BATCH_PARTIAL" if succeeded else "APP_VIEWS_APPLY_BATCH_FAILED",
3987
+ "recoverable": failed > 0 or partial > 0,
3988
+ "message": f"applied app_views_apply to {succeeded}/{len(final_views)} views" if status != "success" else f"applied app_views_apply to {succeeded} views",
3989
+ "normalized_args": {"views": views},
3990
+ "views": final_views,
3991
+ "errors": errors,
3992
+ "parallelism": {"view_workers": view_workers, "same_app_parallel": True},
3993
+ "verification": {
3994
+ "batch_verified": failed == 0 and partial == 0,
3995
+ "succeeded": succeeded,
3996
+ "partial": partial,
3997
+ "failed": failed,
3998
+ },
3999
+ "write_executed": write_executed,
4000
+ "write_succeeded": write_executed and failed == 0 and partial == 0,
4001
+ "safe_to_retry": not write_executed,
4002
+ }
4003
+ _merge_duration_breakdown(
4004
+ payload,
4005
+ view_write_parallel_wall_ms=view_write_parallel_wall_ms,
4006
+ total_ms=_elapsed_ms(started_at),
4007
+ )
4008
+ return _attach_builder_apply_envelope("app_views_apply", payload)
4009
+
2417
4010
  def _app_views_apply_once(
2418
4011
  self,
2419
4012
  *,
@@ -2436,69 +4029,9 @@ class AiBuilderTools(ToolBase):
2436
4029
  )
2437
4030
  if reserved_failure is not None:
2438
4031
  return reserved_failure
2439
- if patch_views:
2440
- try:
2441
- parsed_views = [ViewUpsertPatch.model_validate(item) for item in (upsert_views or [])]
2442
- parsed_patch_views = [ViewPartialPatch.model_validate(item) for item in patch_views]
2443
- except ValidationError as exc:
2444
- return _visibility_validation_failure(
2445
- str(exc),
2446
- tool_name="app_views_apply",
2447
- exc=exc,
2448
- suggested_next_call={
2449
- "tool_name": "app_views_apply",
2450
- "arguments": {
2451
- "profile": profile,
2452
- "app_key": app_key,
2453
- "publish": publish,
2454
- "upsert_views": upsert_views or [],
2455
- "patch_views": [
2456
- {"view_key": "VIEW_KEY", "set": {"query_conditions": {"enabled": True, "rows": [["字段A"]]}}},
2457
- ],
2458
- "remove_views": remove_views or [],
2459
- },
2460
- },
2461
- )
2462
- normalized_args = {
2463
- "app_key": app_key,
2464
- "publish": publish,
2465
- "upsert_views": [view.model_dump(mode="json") for view in parsed_views],
2466
- "patch_views": [patch.model_dump(mode="json") for patch in parsed_patch_views],
2467
- "remove_views": list(remove_views or []),
2468
- }
2469
- return _safe_tool_call(
2470
- lambda: self._facade.app_views_apply(
2471
- profile=profile,
2472
- app_key=app_key,
2473
- publish=publish,
2474
- upsert_views=parsed_views,
2475
- patch_views=parsed_patch_views,
2476
- remove_views=list(remove_views or []),
2477
- ),
2478
- error_code="VIEWS_APPLY_FAILED",
2479
- normalized_args=normalized_args,
2480
- suggested_next_call={"tool_name": "app_views_apply", "arguments": {"profile": profile, **normalized_args}},
2481
- )
2482
- plan_result = self._rewrite_plan_result_for_apply(
2483
- result=self.app_views_plan(
2484
- profile=profile,
2485
- app_key=app_key,
2486
- upsert_views=upsert_views,
2487
- remove_views=remove_views,
2488
- preset=None,
2489
- ),
2490
- profile=profile,
2491
- publish=publish,
2492
- plan_tool_name="app_views_plan",
2493
- apply_tool_name="app_views_apply",
2494
- )
2495
- if not isinstance(plan_result, dict) or plan_result.get("status") != "success":
2496
- return plan_result
2497
- plan_args = plan_result.get("normalized_args")
2498
- if not isinstance(plan_args, dict):
2499
- plan_args = {}
2500
4032
  try:
2501
- parsed_views = [ViewUpsertPatch.model_validate(item) for item in plan_args.get("upsert_views") or []]
4033
+ parsed_views = [ViewUpsertPatch.model_validate(item) for item in (upsert_views or [])]
4034
+ parsed_patch_views = [ViewPartialPatch.model_validate(item) for item in (patch_views or [])]
2502
4035
  except ValidationError as exc:
2503
4036
  return _visibility_validation_failure(
2504
4037
  str(exc),
@@ -2508,27 +4041,29 @@ class AiBuilderTools(ToolBase):
2508
4041
  "tool_name": "app_views_apply",
2509
4042
  "arguments": {
2510
4043
  "profile": profile,
2511
- "app_key": str(plan_args.get("app_key") or app_key),
4044
+ "app_key": app_key,
2512
4045
  "publish": publish,
2513
- "upsert_views": plan_args.get("upsert_views") or [{"name": "业务台账视图", "type": "table", "columns": ["字段A"]}],
2514
- "remove_views": plan_args.get("remove_views") or [],
4046
+ "upsert_views": upsert_views or [{"name": "业务台账视图", "type": "table", "columns": ["字段A"]}],
4047
+ "patch_views": patch_views or [],
4048
+ "remove_views": remove_views or [],
2515
4049
  },
2516
4050
  },
2517
4051
  )
2518
4052
  normalized_args = {
2519
- "app_key": str(plan_args.get("app_key") or app_key),
4053
+ "app_key": app_key,
2520
4054
  "publish": publish,
2521
- "upsert_views": [view.model_dump(mode="json") for view in parsed_views],
2522
- "remove_views": list(plan_args.get("remove_views") or remove_views),
4055
+ "upsert_views": [public_view_upsert_payload(view) for view in parsed_views],
4056
+ "patch_views": [public_view_partial_payload(patch) for patch in parsed_patch_views],
4057
+ "remove_views": list(remove_views or []),
2523
4058
  }
2524
4059
  return _safe_tool_call(
2525
4060
  lambda: self._facade.app_views_apply(
2526
4061
  profile=profile,
2527
- app_key=str(plan_args.get("app_key") or app_key),
4062
+ app_key=app_key,
2528
4063
  publish=publish,
2529
4064
  upsert_views=parsed_views,
2530
- patch_views=[],
2531
- remove_views=list(plan_args.get("remove_views") or remove_views),
4065
+ patch_views=parsed_patch_views,
4066
+ remove_views=list(remove_views or []),
2532
4067
  ),
2533
4068
  error_code="VIEWS_APPLY_FAILED",
2534
4069
  normalized_args=normalized_args,
@@ -2566,8 +4101,24 @@ class AiBuilderTools(ToolBase):
2566
4101
  remove_chart_ids: list[str],
2567
4102
  reorder_chart_ids: list[str],
2568
4103
  patch_charts: list[JSONObject] | None = None,
4104
+ apps: list[JSONObject] | None = None,
2569
4105
  ) -> JSONObject:
2570
4106
  """执行应用相关逻辑。"""
4107
+ if apps is not None:
4108
+ return self._apply_app_batch(
4109
+ tool_name="app_charts_apply",
4110
+ profile=profile,
4111
+ apps=apps,
4112
+ apply_one=lambda _index, item, item_app_key: self.app_charts_apply(
4113
+ profile=profile,
4114
+ app_key=item_app_key,
4115
+ upsert_charts=_payload_list(item, "upsert_charts", "upsertCharts", "charts", default=upsert_charts or []),
4116
+ patch_charts=_payload_list(item, "patch_charts", "patchCharts", default=patch_charts or []),
4117
+ remove_chart_ids=_payload_list(item, "remove_chart_ids", "removeChartIds", default=remove_chart_ids or []),
4118
+ reorder_chart_ids=_payload_list(item, "reorder_chart_ids", "reorderChartIds", default=reorder_chart_ids or []),
4119
+ apps=None,
4120
+ ),
4121
+ )
2571
4122
  try:
2572
4123
  request = ChartApplyRequest.model_validate(
2573
4124
  {
@@ -2623,8 +4174,26 @@ class AiBuilderTools(ToolBase):
2623
4174
  dash_global_config: JSONObject | None = None,
2624
4175
  config: JSONObject | None = None,
2625
4176
  payload: JSONObject | None = None,
4177
+ patch_sections: list[JSONObject] | None = None,
2626
4178
  ) -> JSONObject:
2627
4179
  """执行门户相关逻辑。"""
4180
+ if patch_sections is not None:
4181
+ normalized_args = {
4182
+ "dash_key": dash_key,
4183
+ "publish": publish,
4184
+ "patch_sections": patch_sections,
4185
+ }
4186
+ return _attach_builder_apply_envelope("portal_apply", _publicize_package_fields(_safe_tool_call(
4187
+ lambda: self._facade.portal_patch_sections(
4188
+ profile=profile,
4189
+ dash_key=dash_key,
4190
+ patch_sections=patch_sections,
4191
+ publish=publish,
4192
+ ),
4193
+ error_code="PORTAL_PATCH_FAILED",
4194
+ normalized_args=normalized_args,
4195
+ suggested_next_call={"tool_name": "portal_get", "arguments": {"profile": profile, "dash_key": dash_key}},
4196
+ )))
2628
4197
  request_payload: dict[str, Any] = dict(payload) if isinstance(payload, dict) else {}
2629
4198
  if dash_key:
2630
4199
  request_payload["dash_key"] = dash_key
@@ -2719,9 +4288,22 @@ class AiBuilderTools(ToolBase):
2719
4288
  *,
2720
4289
  profile: str,
2721
4290
  app_key: str,
4291
+ app_keys: list[str] | None = None,
2722
4292
  expected_package_id: int | None = None,
2723
4293
  ) -> JSONObject:
2724
4294
  """执行应用相关逻辑。"""
4295
+ if app_keys is not None:
4296
+ return self._apply_app_batch(
4297
+ tool_name="app_publish_verify",
4298
+ profile=profile,
4299
+ apps=[{"app_key": item, "expected_package_id": expected_package_id} for item in app_keys],
4300
+ apply_one=lambda _index, item, item_app_key: self.app_publish_verify(
4301
+ profile=profile,
4302
+ app_key=item_app_key,
4303
+ app_keys=None,
4304
+ expected_package_id=item.get("expected_package_id") or item.get("expectedPackageId") or expected_package_id,
4305
+ ),
4306
+ )
2725
4307
  normalized_args = {"app_key": app_key, "expected_package_id": expected_package_id}
2726
4308
  result = _publicize_package_fields(_safe_tool_call(
2727
4309
  lambda: self._facade.app_publish_verify(profile=profile, app_key=app_key, expected_package_tag_id=expected_package_id),
@@ -2933,7 +4515,12 @@ def _schema_apps_expected_shape() -> JSONObject:
2933
4515
  "app_name": "员工花名册",
2934
4516
  "icon": "business-personalcard",
2935
4517
  "color": "emerald",
2936
- "add_fields": [{"name": "员工名称", "type": "text", "as_data_title": True}],
4518
+ "form": [
4519
+ {
4520
+ "section": "基础信息",
4521
+ "rows": [[{"name": "员工名称", "type": "text", "data_title": True}]],
4522
+ }
4523
+ ],
2937
4524
  }
2938
4525
  ],
2939
4526
  }
@@ -2942,7 +4529,7 @@ def _schema_apps_expected_shape() -> JSONObject:
2942
4529
  def _schema_apps_expected_shape_json() -> str:
2943
4530
  return (
2944
4531
  '{"package_id":1001,"apps":[{"client_key":"employee","app_name":"员工花名册",'
2945
- '"icon":"business-personalcard","color":"emerald","add_fields":[{"name":"员工名称","type":"text","as_data_title":true}]}]}'
4532
+ '"icon":"business-personalcard","color":"emerald","form":[{"section":"基础信息","rows":[[{"name":"员工名称","type":"text","data_title":true}]]}]}]}'
2946
4533
  )
2947
4534
 
2948
4535
 
@@ -3027,6 +4614,163 @@ def _normalize_schema_apps_argument(*, tool_name: str, package_id: int | None, a
3027
4614
  return {"package_id": normalized_package_id, "apps": normalized_items, "warnings": warnings}
3028
4615
 
3029
4616
 
4617
+ def _normalize_schema_form_field(field: JSONObject) -> JSONObject:
4618
+ payload = deepcopy(field)
4619
+ if "data_title" in payload and "as_data_title" not in payload and "asDataTitle" not in payload:
4620
+ payload["as_data_title"] = payload.pop("data_title")
4621
+ if "dataTitle" in payload and "as_data_title" not in payload and "asDataTitle" not in payload:
4622
+ payload["as_data_title"] = payload.pop("dataTitle")
4623
+ if "data_cover" in payload and "as_data_cover" not in payload and "asDataCover" not in payload:
4624
+ payload["as_data_cover"] = payload.pop("data_cover")
4625
+ if "dataCover" in payload and "as_data_cover" not in payload and "asDataCover" not in payload:
4626
+ payload["as_data_cover"] = payload.pop("dataCover")
4627
+ return payload
4628
+
4629
+
4630
+ def _schema_form_entry_name(entry: object) -> str:
4631
+ if isinstance(entry, dict):
4632
+ for key in ("name", "title", "label", "field_name", "fieldName"):
4633
+ if entry.get(key) is not None:
4634
+ return str(entry.get(key) or "").strip()
4635
+ return ""
4636
+ if isinstance(entry, (str, int)):
4637
+ return str(entry).strip()
4638
+ return ""
4639
+
4640
+
4641
+ def _schema_form_failure(*, tool_name: str, path: str, message: str, fix_hint: str) -> JSONObject:
4642
+ return _config_failure(
4643
+ tool_name=tool_name,
4644
+ error_code="FORM_SHAPE_INVALID",
4645
+ message=message,
4646
+ fix_hint=fix_hint,
4647
+ details={
4648
+ "path": path,
4649
+ "expected_shape": {
4650
+ "form": [
4651
+ {
4652
+ "section": "基础信息",
4653
+ "rows": [
4654
+ [
4655
+ {"name": "标题", "type": "text", "data_title": True},
4656
+ {"name": "状态", "type": "single_select", "options": ["待处理", "处理中", "已完成"]},
4657
+ ]
4658
+ ],
4659
+ }
4660
+ ]
4661
+ },
4662
+ },
4663
+ )
4664
+
4665
+
4666
+ def _compile_schema_form_payload(*, tool_name: str, form: object, path: str = "form") -> JSONObject:
4667
+ if form is None:
4668
+ return {"add_fields": [], "layout_sections": []}
4669
+ if not isinstance(form, list) or not form:
4670
+ return {
4671
+ "failure": _schema_form_failure(
4672
+ tool_name=tool_name,
4673
+ path=path,
4674
+ message=f"{path} must be a non-empty list of form sections.",
4675
+ fix_hint='Use form=[{"section":"基础信息","rows":[[{"name":"标题","type":"text","data_title":true}]]}].',
4676
+ )
4677
+ }
4678
+
4679
+ add_fields: list[JSONObject] = []
4680
+ layout_sections: list[JSONObject] = []
4681
+ for section_index, section in enumerate(form):
4682
+ section_path = f"{path}[{section_index}]"
4683
+ if not isinstance(section, dict):
4684
+ return {
4685
+ "failure": _schema_form_failure(
4686
+ tool_name=tool_name,
4687
+ path=section_path,
4688
+ message=f"{section_path} must be an object.",
4689
+ fix_hint="Each form section must include section and rows.",
4690
+ )
4691
+ }
4692
+ section_title = str(section.get("section") or section.get("title") or section.get("name") or "").strip()
4693
+ rows = section.get("rows")
4694
+ if not section_title:
4695
+ return {
4696
+ "failure": _schema_form_failure(
4697
+ tool_name=tool_name,
4698
+ path=f"{section_path}.section",
4699
+ message=f"{section_path}.section is required.",
4700
+ fix_hint='Set a business section title such as "基础信息" or "生产信息".',
4701
+ )
4702
+ }
4703
+ if not isinstance(rows, list) or not rows:
4704
+ return {
4705
+ "failure": _schema_form_failure(
4706
+ tool_name=tool_name,
4707
+ path=f"{section_path}.rows",
4708
+ message=f"{section_path}.rows must be a non-empty list.",
4709
+ fix_hint="Use rows as a list of field rows; each row is a list of field objects.",
4710
+ )
4711
+ }
4712
+ layout_rows: list[list[str]] = []
4713
+ for row_index, row in enumerate(rows):
4714
+ row_path = f"{section_path}.rows[{row_index}]"
4715
+ if isinstance(row, dict):
4716
+ row_fields = row.get("fields")
4717
+ else:
4718
+ row_fields = row
4719
+ if not isinstance(row_fields, list) or not row_fields:
4720
+ return {
4721
+ "failure": _schema_form_failure(
4722
+ tool_name=tool_name,
4723
+ path=row_path,
4724
+ message=f"{row_path} must be a non-empty field list.",
4725
+ fix_hint='Use rows like [[{"name":"字段A","type":"text"},{"name":"字段B","type":"number"}]].',
4726
+ )
4727
+ }
4728
+ layout_row: list[str] = []
4729
+ for field_index, field in enumerate(row_fields):
4730
+ field_path = f"{row_path}[{field_index}]"
4731
+ field_name = _schema_form_entry_name(field)
4732
+ if not field_name:
4733
+ return {
4734
+ "failure": _schema_form_failure(
4735
+ tool_name=tool_name,
4736
+ path=field_path,
4737
+ message=f"{field_path} must include a field name.",
4738
+ fix_hint='Each new field object must include name, for example {"name":"工单编号","type":"text"}.',
4739
+ )
4740
+ }
4741
+ layout_row.append(field_name)
4742
+ if isinstance(field, dict):
4743
+ add_fields.append(_normalize_schema_form_field(field))
4744
+ layout_rows.append(layout_row)
4745
+ layout_sections.append({"title": section_title, "rows": layout_rows})
4746
+ return {"add_fields": add_fields, "layout_sections": layout_sections}
4747
+
4748
+
4749
+ def _apply_schema_form_to_payload(*, tool_name: str, payload: JSONObject, path: str) -> JSONObject:
4750
+ form = payload.get("form")
4751
+ if form is None:
4752
+ return {"payload": payload, "layout_sections": []}
4753
+ existing_add_fields = payload.get("add_fields") or payload.get("addFields")
4754
+ if isinstance(existing_add_fields, list) and existing_add_fields:
4755
+ return {
4756
+ "failure": _config_failure(
4757
+ tool_name=tool_name,
4758
+ error_code="FORM_WITH_ADD_FIELDS_CONFLICT",
4759
+ message=f"{path} cannot use form and add_fields together.",
4760
+ fix_hint="Use form as the single schema creation shape: put fields under form[].rows[][].",
4761
+ details={"path": path, "conflicting_keys": ["form", "add_fields"]},
4762
+ )
4763
+ }
4764
+ compiled = _compile_schema_form_payload(tool_name=tool_name, form=form, path=f"{path}.form")
4765
+ if isinstance(compiled.get("failure"), dict):
4766
+ return {"failure": compiled["failure"]}
4767
+ normalized = deepcopy(payload)
4768
+ normalized.pop("form", None)
4769
+ normalized["add_fields"] = compiled.get("add_fields") or []
4770
+ normalized["_inline_form_layout_sections"] = compiled.get("layout_sections") or []
4771
+ return {"payload": normalized, "layout_sections": compiled.get("layout_sections") or []}
4772
+
4773
+
3030
4774
  def _multi_app_item_app_name(item: JSONObject) -> str:
3031
4775
  return str(item.get("app_name") or item.get("appName") or item.get("appTitle") or item.get("app_title") or item.get("title") or "").strip()
3032
4776
 
@@ -3048,7 +4792,7 @@ def _field_type_for_static_validation(field: JSONObject) -> str:
3048
4792
 
3049
4793
 
3050
4794
  def _is_data_title_field(field: JSONObject) -> bool:
3051
- return bool(field.get("as_data_title") or field.get("asDataTitle"))
4795
+ return bool(field.get("as_data_title") or field.get("asDataTitle") or field.get("data_title") or field.get("dataTitle"))
3052
4796
 
3053
4797
 
3054
4798
  def _collect_multi_app_target_refs(value: object, *, path: str) -> list[JSONObject]:
@@ -3075,7 +4819,6 @@ def _multi_app_static_validation_failure(
3075
4819
  *,
3076
4820
  tool_name: str,
3077
4821
  apps: list[JSONObject],
3078
- create_if_missing: bool,
3079
4822
  ) -> JSONObject | None:
3080
4823
  issues: list[JSONObject] = []
3081
4824
  client_key_indexes: dict[str, int] = {}
@@ -3138,17 +4881,6 @@ def _multi_app_static_validation_failure(
3138
4881
  }
3139
4882
  )
3140
4883
  continue
3141
- if new_app_item and not create_if_missing:
3142
- issues.append(
3143
- {
3144
- "index": index,
3145
- "row_number": index + 1,
3146
- "path": f"apps[{index}]",
3147
- "error_code": "CREATE_IF_MISSING_REQUIRED",
3148
- "message": "new multi-app items require create_if_missing=true",
3149
- "fix_hint": "Set create_if_missing=true, or pass app_key for an existing app.",
3150
- }
3151
- )
3152
4884
 
3153
4885
  add_fields = _multi_app_list_value(item, "add_fields", "addFields")
3154
4886
  if new_app_item:
@@ -3350,6 +5082,86 @@ def _compiled_multi_app_deferred_add_fields(compiled_item: JSONObject, existing_
3350
5082
  ]
3351
5083
 
3352
5084
 
5085
+ def _multi_app_child_diagnostics(result: JSONObject) -> JSONObject:
5086
+ diagnostics: JSONObject = {}
5087
+ for key in (
5088
+ "backend_code",
5089
+ "http_status",
5090
+ "request_id",
5091
+ "details",
5092
+ "suggested_next_call",
5093
+ "warnings",
5094
+ "publish_result",
5095
+ "duration_breakdown_ms",
5096
+ ):
5097
+ value = result.get(key)
5098
+ if value is None:
5099
+ continue
5100
+ if isinstance(value, (dict, list)) and not value:
5101
+ continue
5102
+ diagnostics[key] = deepcopy(value)
5103
+ return diagnostics
5104
+
5105
+
5106
+ def _multi_app_field_type(field: JSONObject) -> str:
5107
+ raw_type = str(field.get("type") or field.get("field_type") or field.get("fieldType") or "").strip()
5108
+ if raw_type:
5109
+ normalized = FIELD_TYPE_ALIASES.get(raw_type.lower())
5110
+ return normalized.value if normalized is not None else raw_type
5111
+ raw_type_id = field.get("type_id") or field.get("typeId") or field.get("field_type_id") or field.get("fieldTypeId")
5112
+ try:
5113
+ normalized_by_id = FIELD_TYPE_ID_ALIASES.get(int(raw_type_id))
5114
+ except (TypeError, ValueError):
5115
+ normalized_by_id = None
5116
+ return normalized_by_id.value if normalized_by_id is not None else ""
5117
+
5118
+
5119
+ def _multi_app_deferred_relation_retryable(result: JSONObject, deferred_add_fields: list[JSONObject]) -> bool:
5120
+ if not deferred_add_fields:
5121
+ return False
5122
+ if not any(_multi_app_field_type(field) == PublicFieldType.relation.value for field in deferred_add_fields if isinstance(field, dict)):
5123
+ return False
5124
+ if result.get("status") in {"success", "partial_success"}:
5125
+ return False
5126
+ if result.get("error_code") != "SCHEMA_APPLY_FAILED":
5127
+ return False
5128
+ if _schema_apply_result_has_write(result):
5129
+ return False
5130
+ return backend_code_value_int(_result_backend_code(result)) == 400
5131
+
5132
+
5133
+ def _result_backend_code(result: JSONObject) -> Any:
5134
+ if result.get("backend_code") is not None:
5135
+ return result.get("backend_code")
5136
+ details = result.get("details")
5137
+ if isinstance(details, dict):
5138
+ transport = details.get("transport_error")
5139
+ if isinstance(transport, dict):
5140
+ return transport.get("backend_code")
5141
+ return None
5142
+
5143
+
5144
+ def _multi_app_relation_target_app_keys(fields: list[JSONObject]) -> list[str]:
5145
+ app_keys: list[str] = []
5146
+
5147
+ def visit(value: Any) -> None:
5148
+ if isinstance(value, list):
5149
+ for item in value:
5150
+ visit(item)
5151
+ return
5152
+ if not isinstance(value, dict):
5153
+ return
5154
+ target_app_key = str(value.get("target_app_key") or value.get("targetAppKey") or "").strip()
5155
+ if target_app_key and target_app_key not in app_keys:
5156
+ app_keys.append(target_app_key)
5157
+ for child in value.values():
5158
+ if isinstance(child, (dict, list)):
5159
+ visit(child)
5160
+
5161
+ visit(fields)
5162
+ return app_keys
5163
+
5164
+
3353
5165
  def _multi_app_list_value(item: JSONObject, *keys: str) -> list[JSONObject]:
3354
5166
  for key in keys:
3355
5167
  value = item.get(key)
@@ -3527,7 +5339,6 @@ def _reserved_system_field_name_failure(
3527
5339
  icon: str | None = None,
3528
5340
  color: str | None = None,
3529
5341
  visibility: JSONObject | None = None,
3530
- create_if_missing: bool = False,
3531
5342
  publish: bool | None = None,
3532
5343
  add_fields: list[JSONObject] | None = None,
3533
5344
  update_fields: list[JSONObject] | None = None,
@@ -3547,7 +5358,6 @@ def _reserved_system_field_name_failure(
3547
5358
  "icon": icon or "",
3548
5359
  "color": color or "",
3549
5360
  "visibility": visibility,
3550
- "create_if_missing": create_if_missing,
3551
5361
  "add_fields": suggested_add_fields,
3552
5362
  "update_fields": update_fields or [],
3553
5363
  "remove_fields": remove_fields or [],
@@ -3576,7 +5386,6 @@ def _reserved_system_field_name_failure_for_apps(
3576
5386
  profile: str,
3577
5387
  package_id: int | None,
3578
5388
  visibility: JSONObject | None,
3579
- create_if_missing: bool,
3580
5389
  publish: bool,
3581
5390
  apps: list[JSONObject],
3582
5391
  ) -> JSONObject | None:
@@ -3592,7 +5401,6 @@ def _reserved_system_field_name_failure_for_apps(
3592
5401
  icon=str(item.get("icon") or ""),
3593
5402
  color=str(item.get("color") or ""),
3594
5403
  visibility=item.get("visibility") if isinstance(item.get("visibility"), dict) else visibility,
3595
- create_if_missing=create_if_missing,
3596
5404
  publish=publish,
3597
5405
  add_fields=list(item.get("add_fields") or item.get("addFields") or []),
3598
5406
  update_fields=list(item.get("update_fields") or item.get("updateFields") or []),
@@ -3610,7 +5418,6 @@ def _reserved_system_field_name_failure_for_apps(
3610
5418
  "profile": profile,
3611
5419
  "package_id": package_id,
3612
5420
  "visibility": visibility,
3613
- "create_if_missing": create_if_missing,
3614
5421
  "publish": publish,
3615
5422
  "apps": fixed_apps,
3616
5423
  }
@@ -3677,6 +5484,23 @@ def _reserved_system_view_name_failure(
3677
5484
  return None
3678
5485
 
3679
5486
 
5487
+ def _view_payload_has_action_buttons(
5488
+ *,
5489
+ upsert_views: list[JSONObject] | None = None,
5490
+ patch_views: list[JSONObject] | None = None,
5491
+ ) -> bool:
5492
+ for item in upsert_views or []:
5493
+ if isinstance(item, dict) and any(key in item for key in ("action_buttons", "actionButtons")):
5494
+ return True
5495
+ for item in patch_views or []:
5496
+ if not isinstance(item, dict):
5497
+ continue
5498
+ raw_set = item.get("set")
5499
+ if isinstance(raw_set, dict) and any(key in raw_set for key in ("action_buttons", "actionButtons")):
5500
+ return True
5501
+ return False
5502
+
5503
+
3680
5504
  def _config_failure(
3681
5505
  *,
3682
5506
  tool_name: str,
@@ -3768,12 +5592,13 @@ def _safe_tool_call(
3768
5592
  normalized_args: JSONObject,
3769
5593
  suggested_next_call: JSONObject | None,
3770
5594
  ) -> JSONObject:
5595
+ started_at = time.perf_counter()
3771
5596
  try:
3772
- return call()
5597
+ result = call()
3773
5598
  except (QingflowApiError, RuntimeError) as error:
3774
5599
  api_error = _coerce_api_error(error)
3775
5600
  public_http_status = None if api_error.http_status == 404 else api_error.http_status
3776
- return {
5601
+ result = {
3777
5602
  "status": "failed",
3778
5603
  "error_code": error_code,
3779
5604
  "recoverable": True,
@@ -3795,6 +5620,46 @@ def _safe_tool_call(
3795
5620
  "noop": False,
3796
5621
  "verification": {},
3797
5622
  }
5623
+ except ValueError as error:
5624
+ public_error_code, public_message = _public_value_error(error, fallback_error_code=error_code)
5625
+ result = {
5626
+ "status": "failed",
5627
+ "error_code": public_error_code,
5628
+ "recoverable": True,
5629
+ "message": public_message,
5630
+ "normalized_args": normalized_args,
5631
+ "missing_fields": [],
5632
+ "allowed_values": {},
5633
+ "details": {
5634
+ "validation_error": {
5635
+ "message": str(error),
5636
+ "fallback_error_code": error_code,
5637
+ }
5638
+ },
5639
+ "suggested_next_call": suggested_next_call,
5640
+ "write_executed": False,
5641
+ "safe_to_retry": True,
5642
+ "noop": False,
5643
+ "verification": {},
5644
+ }
5645
+ if isinstance(result, dict):
5646
+ _merge_duration_breakdown(result, tool_call_ms=_elapsed_ms(started_at))
5647
+ return result
5648
+
5649
+
5650
+ def _public_value_error(error: ValueError, *, fallback_error_code: str) -> tuple[str, str]:
5651
+ message = str(error).strip() or fallback_error_code
5652
+ prefix, separator, rest = message.partition(":")
5653
+ candidate = prefix.strip()
5654
+ if separator and _looks_like_public_error_code(candidate):
5655
+ return candidate, rest.strip() or message
5656
+ return fallback_error_code, message
5657
+
5658
+
5659
+ def _looks_like_public_error_code(value: str) -> bool:
5660
+ if not value or len(value) > 80 or not any(ch.isalpha() for ch in value):
5661
+ return False
5662
+ return all(ch.isupper() or ch.isdigit() or ch == "_" for ch in value)
3798
5663
 
3799
5664
 
3800
5665
  def _publicize_package_fields(value):
@@ -3874,6 +5739,8 @@ def _builder_apply_json_paths() -> JSONObject:
3874
5739
  "warnings": "$.warnings",
3875
5740
  "verification": "$.verification",
3876
5741
  "details": "$.details",
5742
+ "duration_breakdown_ms": "$.duration_breakdown_ms",
5743
+ "total_ms": "$.duration_breakdown_ms.total_ms",
3877
5744
  "write_executed": "$.write_executed",
3878
5745
  "write_may_have_succeeded": "$.write_may_have_succeeded",
3879
5746
  "safe_to_retry": "$.safe_to_retry",
@@ -3910,6 +5777,8 @@ def _builder_apply_summary(payload: JSONObject, resources: list[JSONObject]) ->
3910
5777
  and str(item.get("operation") or "") in {"updated", "layout_updated", "workflow_updated", "verified", "published"}
3911
5778
  )
3912
5779
  published_value = payload.get("published")
5780
+ if published_value is None:
5781
+ published_value = _builder_batch_published_value(payload)
3913
5782
  if published_value is None:
3914
5783
  publish_requested = payload.get("publish_requested")
3915
5784
  published_value = bool(publish_requested) and status in {"success", "partial_success"}
@@ -3939,6 +5808,24 @@ def _builder_apply_summary(payload: JSONObject, resources: list[JSONObject]) ->
3939
5808
  return summary
3940
5809
 
3941
5810
 
5811
+ def _builder_batch_published_value(payload: JSONObject) -> bool | None:
5812
+ apps = payload.get("apps")
5813
+ if not isinstance(apps, list) or not apps:
5814
+ return None
5815
+ values: list[bool] = []
5816
+ for item in apps:
5817
+ if not isinstance(item, dict):
5818
+ continue
5819
+ result = item.get("result") if isinstance(item.get("result"), dict) else {}
5820
+ if "published" in result:
5821
+ values.append(bool(result.get("published")))
5822
+ elif "published" in item:
5823
+ values.append(bool(item.get("published")))
5824
+ if not values:
5825
+ return None
5826
+ return all(values)
5827
+
5828
+
3942
5829
  def _builder_verification_truthy(value: object) -> bool:
3943
5830
  if value is None:
3944
5831
  return True
@@ -3956,6 +5843,8 @@ def _builder_apply_resources(tool_name: str, payload: JSONObject) -> list[JSONOb
3956
5843
  resources = _builder_package_resources(payload)
3957
5844
  elif tool_name == "app_schema_apply":
3958
5845
  resources = _builder_schema_resources(payload)
5846
+ elif isinstance(payload.get("apps"), list) and _builder_apply_tool_is_app_scoped(tool_name):
5847
+ resources = _builder_batch_app_resources(tool_name, payload)
3959
5848
  elif tool_name == "app_layout_apply":
3960
5849
  resources = [_builder_app_resource(payload, operation="layout_updated")]
3961
5850
  elif tool_name == "app_flow_apply":
@@ -3983,6 +5872,38 @@ def _builder_apply_resources(tool_name: str, payload: JSONObject) -> list[JSONOb
3983
5872
  return resources
3984
5873
 
3985
5874
 
5875
+ def _builder_batch_app_resources(tool_name: str, payload: JSONObject) -> list[JSONObject]:
5876
+ resources: list[JSONObject] = []
5877
+ operation_by_tool = {
5878
+ "app_schema_apply": "updated",
5879
+ "app_layout_apply": "layout_updated",
5880
+ "app_flow_apply": "workflow_updated",
5881
+ "app_views_apply": "updated",
5882
+ "app_custom_buttons_apply": "updated",
5883
+ "app_associated_resources_apply": "updated",
5884
+ "app_charts_apply": "updated",
5885
+ "app_publish_verify": "verified",
5886
+ }
5887
+ operation = operation_by_tool.get(tool_name, "updated")
5888
+ for item in payload.get("apps") or []:
5889
+ if not isinstance(item, dict):
5890
+ continue
5891
+ result = item.get("result") if isinstance(item.get("result"), dict) else {}
5892
+ nested_resources = result.get("resources") if isinstance(result, dict) else None
5893
+ if isinstance(nested_resources, list) and nested_resources:
5894
+ resources.extend(resource for resource in nested_resources if isinstance(resource, dict))
5895
+ continue
5896
+ app_payload: JSONObject = {
5897
+ **(result if isinstance(result, dict) else {}),
5898
+ "app_key": item.get("app_key") or (result.get("app_key") if isinstance(result, dict) else None),
5899
+ "status": item.get("status") or (result.get("status") if isinstance(result, dict) else None),
5900
+ "error_code": item.get("error_code") or (result.get("error_code") if isinstance(result, dict) else None),
5901
+ "message": item.get("message") or (result.get("message") if isinstance(result, dict) else None),
5902
+ }
5903
+ resources.append(_builder_app_resource(app_payload, operation=operation))
5904
+ return resources
5905
+
5906
+
3986
5907
  def _builder_apply_tool_is_app_scoped(tool_name: str) -> bool:
3987
5908
  return tool_name in {
3988
5909
  "app_schema_apply",
@@ -4290,6 +6211,33 @@ def _builder_field_resources(field_diff: object, *, parent: JSONObject | None) -
4290
6211
 
4291
6212
 
4292
6213
  def _builder_view_resources(payload: JSONObject) -> list[JSONObject]:
6214
+ if isinstance(payload.get("views"), list):
6215
+ resources: list[JSONObject] = []
6216
+ for item in payload.get("views") or []:
6217
+ if not isinstance(item, dict):
6218
+ continue
6219
+ result = item.get("result") if isinstance(item.get("result"), dict) else {}
6220
+ parent = _builder_app_parent({"app_key": item.get("app_key") or result.get("app_key")})
6221
+ operation = str(item.get("operation") or item.get("requested_operation") or "updated")
6222
+ if operation == "upsert":
6223
+ operation = "updated"
6224
+ resources.append(
6225
+ _builder_resource(
6226
+ resource_type="view",
6227
+ operation=operation,
6228
+ status=str(item.get("status") or result.get("status") or "success"),
6229
+ key=item.get("view_key") or item.get("viewKey"),
6230
+ name=item.get("name") or item.get("view_name") or item.get("viewName"),
6231
+ ids={
6232
+ **({"view_key": item.get("view_key") or item.get("viewKey")} if item.get("view_key") or item.get("viewKey") else {}),
6233
+ **({"app_key": item.get("app_key")} if item.get("app_key") else {}),
6234
+ },
6235
+ parent=parent,
6236
+ error_code=item.get("error_code") or result.get("error_code"),
6237
+ message=item.get("message") or result.get("message"),
6238
+ )
6239
+ )
6240
+ return resources
4293
6241
  diff = payload.get("views_diff") if isinstance(payload.get("views_diff"), dict) else {}
4294
6242
  verification_by_name = _builder_view_verification_by_name(payload)
4295
6243
  parent = _builder_app_parent(payload)
@@ -4331,6 +6279,15 @@ def _builder_view_resources(payload: JSONObject) -> list[JSONObject]:
4331
6279
  message=message,
4332
6280
  )
4333
6281
  )
6282
+ details = payload.get("details") if isinstance(payload.get("details"), dict) else {}
6283
+ action_buttons_result = details.get("action_buttons_result") if isinstance(details, dict) else None
6284
+ if isinstance(action_buttons_result, dict):
6285
+ nested_payload = {
6286
+ **action_buttons_result,
6287
+ "app_key": payload.get("app_key"),
6288
+ "app_name": payload.get("app_name"),
6289
+ }
6290
+ resources.extend(_builder_button_resources(nested_payload))
4334
6291
  return resources
4335
6292
 
4336
6293
 
@@ -4821,7 +6778,6 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
4821
6778
  "allowed_keys": [
4822
6779
  "package_id",
4823
6780
  "package_name",
4824
- "create_if_missing",
4825
6781
  "icon",
4826
6782
  "color",
4827
6783
  "icon_name",
@@ -4834,7 +6790,6 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
4834
6790
  "aliases": {
4835
6791
  "packageId": "package_id",
4836
6792
  "packageName": "package_name",
4837
- "createIfMissing": "create_if_missing",
4838
6793
  "iconName": "icon",
4839
6794
  "iconColor": "color",
4840
6795
  "icon_config.name": "icon",
@@ -4851,6 +6806,7 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
4851
6806
  },
4852
6807
  "execution_notes": [
4853
6808
  "create or update package metadata, visibility, grouping, and ordering in one call",
6809
+ "create mode: package_name without package_id creates a package",
4854
6810
  "creating a package requires explicit icon + color; icon=template is blocked because it is too generic",
4855
6811
  "agent-facing primary icon shape is icon + color; icon_name/icon_color, icon_config, and icon={name,color} are compatibility aliases that normalize to icon/color",
4856
6812
  "updating a package preserves existing icon/color when omitted; explicit icon/color values are still validated",
@@ -4859,6 +6815,7 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
4859
6815
  "package_id maps internally to backend tagId; do not use tag_id in public calls",
4860
6816
  "items is a full package layout tree; omitting existing app/portal items is blocked unless allow_detach=true",
4861
6817
  "item shapes: {type:'app', app_key}, {type:'portal', dash_key}, or {type:'group', group_id?, name, items:[...]}",
6818
+ "allow_detach=true with flat app/portal items and no groups is treated as an explicit full replacement and skips current layout read plus final package readback",
4862
6819
  "layout apply calls backend package ordering (MoveGroupAuth), so it requires package edit_app permission even when items=[] only clears/deletes existing groups",
4863
6820
  *_VISIBILITY_EXECUTION_NOTES,
4864
6821
  ],
@@ -4878,7 +6835,6 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
4878
6835
  "create_example": {
4879
6836
  "profile": "default",
4880
6837
  "package_name": "项目管理",
4881
- "create_if_missing": True,
4882
6838
  "icon": "briefcase",
4883
6839
  "color": "azure",
4884
6840
  "visibility": deepcopy(_VISIBILITY_WORKSPACE_EXAMPLE),
@@ -5097,6 +7053,7 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5097
7053
  "remove_buttons supports button_id or exact unique button_text",
5098
7054
  "after a remove_buttons DELETE is sent, the tool verifies deletion by single button_id readback; removed[] returns delete_executed, readback_status, and safe_to_retry_delete=false",
5099
7055
  "if a removed button returns readback_status=unavailable or still_exists, treat the result as readback pending and do not blindly repeat the delete",
7056
+ "pure create/update with returned button ids and no view_configs/remove skips the final custom-button inventory read; response details.final_readback_skipped=true",
5100
7057
  "all operations share one edit context and publish after at least one write succeeds; there is no draft-only mode for this tool",
5101
7058
  "background_color and text_color cannot both be white",
5102
7059
  ],
@@ -5190,6 +7147,7 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5190
7147
  "upsert_resources[].match_mappings[].target_field",
5191
7148
  "upsert_resources[].match_mappings[].source_field",
5192
7149
  "upsert_resources[].match_mappings[].value",
7150
+ "upsert_resources[].match_mappings[].values",
5193
7151
  "upsert_resources[].match_mappings[].operator",
5194
7152
  "upsert_resources[].match_rules",
5195
7153
  "patch_resources[].associated_item_id",
@@ -5224,6 +7182,16 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5224
7182
  "allowed_values": {
5225
7183
  "upsert_resources[].graph_type": ["chart", "view"],
5226
7184
  "upsert_resources[].report_source": ["app", "dataset"],
7185
+ "upsert_resources[].match_mappings[].operator": [
7186
+ "eq",
7187
+ "neq",
7188
+ "in",
7189
+ "contains",
7190
+ "gte",
7191
+ "lte",
7192
+ "is_empty",
7193
+ "not_empty",
7194
+ ],
5227
7195
  "view_configs[].limit_type": ["all", "select"],
5228
7196
  },
5229
7197
  "execution_notes": [
@@ -5236,12 +7204,15 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5236
7204
  "before creating an associated resource, read app_get.associated_resources and reuse an existing item with patch_resources when target_app_key + view_key/chart_key already matches; repeated upsert_resources without associated_item_id can create duplicate associated items",
5237
7205
  "graph_type=view uses view_key and internally compiles to the Qingflow view source; graph_type=chart uses chart_key and defaults to report_source=app",
5238
7206
  "report_source=app maps to BI_QINGFLOW; report_source=dataset maps to BI_DATASET for associating an existing dataset report; do not pass raw backend sourceType",
5239
- "use match_mappings for associated view/report filtering; dynamic conditions use source_field and static conditions use value",
7207
+ "use match_mappings for associated view/report filtering; dynamic conditions use source_field and static conditions use value/values",
5240
7208
  "match_mappings.source_field accepts source schema fields plus system fields 数据ID(-17) and 编号(0); match_mappings compiles to backend matchRules",
7209
+ "match_mappings uses the same public operator semantics as view/chart filters: eq, neq, in, contains, gte, lte, is_empty, not_empty; field_name/field are aliases of target_field",
7210
+ "static multi-value conditions use values; is_empty/not_empty conditions do not need source_field/value/values",
5241
7211
  "do not write raw match_rules unless preserving a legacy backend config; match_mappings and match_rules are mutually exclusive",
5242
7212
  "client_key only lets a view_config reference a resource created earlier in the same apply call through associated_item_refs; it is not persisted and cannot deduplicate later apply calls",
5243
7213
  "remove_associated_item_ids sends DELETE and verifies deletion with one associated-resource pool readback because the backend has no confirmed single-item GET; removed[] returns delete_executed, readback_status, and safe_to_retry_delete=false",
5244
7214
  "if an associated resource delete returns readback_status=unavailable or still_exists, treat the result as readback pending and do not blindly repeat the delete",
7215
+ "pure create/update with returned associated_item_id values and no view_configs/remove/reorder skips the final associated-resource pool read; response details.final_readback_skipped=true",
5245
7216
  "this tool publishes after at least one write succeeds; there is no draft-only mode",
5246
7217
  "visible=false hides the associated-resource area without clearing previous selected ids; visible=true with limit_type=all shows the whole app-level pool",
5247
7218
  ],
@@ -5276,7 +7247,7 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5276
7247
  },
5277
7248
  },
5278
7249
  "app_schema_plan": {
5279
- "allowed_keys": ["app_key", "package_id", "app_name", "icon", "color", "visibility", "create_if_missing", "add_fields", "update_fields", "remove_fields"],
7250
+ "allowed_keys": ["app_key", "package_id", "app_name", "icon", "color", "visibility", "add_fields", "update_fields", "remove_fields"],
5280
7251
  "aliases": {
5281
7252
  "app_title": "app_name",
5282
7253
  "title": "app_name",
@@ -5301,6 +7272,10 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5301
7272
  "field.customBtnTextStatus": "field.custom_button_text_enabled",
5302
7273
  "field.customBtnText": "field.custom_button_text",
5303
7274
  "field.subfieldUpdates": "field.subfield_updates",
7275
+ "field.data_title": "field.as_data_title",
7276
+ "field.dataTitle": "field.as_data_title",
7277
+ "field.data_cover": "field.as_data_cover",
7278
+ "field.dataCover": "field.as_data_cover",
5304
7279
  "field.asDataTitle": "field.as_data_title",
5305
7280
  "field.asDataCover": "field.as_data_cover",
5306
7281
  },
@@ -5327,8 +7302,7 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5327
7302
  "icon": "briefcase",
5328
7303
  "color": "emerald",
5329
7304
  "visibility": deepcopy(_VISIBILITY_WORKSPACE_EXAMPLE),
5330
- "create_if_missing": True,
5331
- "add_fields": [{"name": "项目名称", "type": "text", "as_data_title": True}],
7305
+ "add_fields": [{"name": "项目名称", "type": "text", "data_title": True}],
5332
7306
  "update_fields": [],
5333
7307
  "remove_fields": [],
5334
7308
  },
@@ -5361,8 +7335,8 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5361
7335
  "icon_color",
5362
7336
  "icon_config",
5363
7337
  "visibility",
5364
- "create_if_missing",
5365
7338
  "publish",
7339
+ "form",
5366
7340
  "add_fields",
5367
7341
  "update_fields",
5368
7342
  "remove_fields",
@@ -5376,6 +7350,9 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5376
7350
  "apps[].icon_color",
5377
7351
  "apps[].icon_config",
5378
7352
  "apps[].visibility",
7353
+ "apps[].form",
7354
+ "apps[].form[].section",
7355
+ "apps[].form[].rows",
5379
7356
  "apps[].add_fields",
5380
7357
  "apps[].update_fields",
5381
7358
  "apps[].remove_fields",
@@ -5420,6 +7397,10 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5420
7397
  "field.customBtnTextStatus": "field.custom_button_text_enabled",
5421
7398
  "field.customBtnText": "field.custom_button_text",
5422
7399
  "field.subfieldUpdates": "field.subfield_updates",
7400
+ "field.data_title": "field.as_data_title",
7401
+ "field.dataTitle": "field.as_data_title",
7402
+ "field.data_cover": "field.as_data_cover",
7403
+ "field.dataCover": "field.as_data_cover",
5423
7404
  "field.asDataTitle": "field.as_data_title",
5424
7405
  "field.asDataCover": "field.as_data_cover",
5425
7406
  },
@@ -5436,13 +7417,17 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5436
7417
  "execution_notes": [
5437
7418
  "use exactly one resource mode",
5438
7419
  "edit mode: app_key, optional app_name to rename the existing app",
5439
- "create mode: package_id + app_name + create_if_missing=true",
7420
+ "create mode: package_id + app_name",
7421
+ "create mode submits a create request directly after basic package add_app permission check; it does not scan app_name duplicates or reuse an existing app by name",
5440
7422
  "create mode follows backend CreateAppBean: package add_app permission is checked on the target package; package edit_app is not required for the create precheck",
5441
- "multi-app mode: pass package_id + create_if_missing + apps[]; do not mix apps with top-level app_key/app_name/add_fields/update_fields/remove_fields",
7423
+ "multi-app mode: pass package_id + apps[]; items with app_name and no app_key are created, items with app_key update existing apps",
5442
7424
  "CLI --apps-file primary shape is {package_id, apps:[...]}; raw app arrays and singleton wrapper arrays are compatibility paths, not recommended examples",
5443
- "multi-app mode preflights static errors before writing: duplicate client_key/app_name, missing data title on new apps, create_if_missing omissions, and unresolved target_app_ref/target_app",
7425
+ "create app schemas with form: form[].section names form sections; form[].rows[][] contains field objects; builder splits form into field creation plus form layout apply",
7426
+ "single-app CLI primary shape is --form-file; multi-app primary shape is apps[].form inside --apps-file",
7427
+ "multi-app mode validates static payload errors before writing: duplicate client_key/app_name, missing data title on new apps, and unresolved target_app_ref/target_app",
5444
7428
  "multi-app relation fields may use target_app_ref to point at another apps[].client_key; the tool creates/resolves app shells first and compiles it to target_app_key",
5445
7429
  "multi-app relation fields may also use target_app with another apps[].app_name; prefer target_app_ref/client_key when names may collide",
7430
+ "multi-app schema writes run in dependency waves: apps without same-batch relation dependencies write first, then dependent apps write in parallel by layer; response.parallelism includes schema_wave_count/schema_wave_sizes",
5446
7431
  "multi-app mode is not transactional; read created_app_keys and apps[].status before retrying, and retry only failed app items",
5447
7432
  "create mode defaults new app visibility to workspace/not when visibility is omitted; edit mode preserves current visibility when omitted",
5448
7433
  "create mode requires explicit icon + color; icon=template is blocked because it is too generic",
@@ -5455,8 +7440,8 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5455
7440
  "do not add form fields named 数据ID, 编号, 申请人, 申请时间, 创建人, 创建时间, 提交人, 提交时间, 更新时间, 更新人, 当前流程状态, 当前处理人, 当前处理节点, or 流程标题; these are Qingflow built-in system fields, not fields to create",
5456
7441
  *_VISIBILITY_EXECUTION_NOTES,
5457
7442
  "update_fields is the field-level partial update path; it reads current form schema and preserves untouched field config",
5458
- "multiple relation fields are backend-risky; read verification.relation_field_limit_verified and warnings before declaring the schema stable",
5459
- "backend 49614 is normalized to MULTIPLE_RELATION_FIELDS_UNSUPPORTED with a workaround message",
7443
+ "an app may contain multiple relation fields; do not downgrade secondary relations to text just because more than one relation exists",
7444
+ "backend relation errors are returned as normal schema apply failures with backend_code/details; they are not normalized into a one-relation modeling fallback",
5460
7445
  "relation_mode=multiple maps to referenceConfig.optionalDataNum=0",
5461
7446
  "relation fields now require both display_field and visible_fields in MCP/CLI payloads",
5462
7447
  "if relation target metadata lookup is blocked by 40161/40002/40027, explicit display_field.name and visible_fields[].name let builder degrade verification and still continue schema write",
@@ -5481,11 +7466,17 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5481
7466
  "icon": "briefcase",
5482
7467
  "color": "emerald",
5483
7468
  "visibility": deepcopy(_VISIBILITY_WORKSPACE_EXAMPLE),
5484
- "create_if_missing": True,
5485
7469
  "publish": True,
5486
- "add_fields": [
5487
- {"name": "项目名称", "type": "text", "as_data_title": True},
5488
- {"name": "项目封面", "type": "attachment", "as_data_cover": True},
7470
+ "form": [
7471
+ {
7472
+ "section": "基础信息",
7473
+ "rows": [
7474
+ [
7475
+ {"name": "项目名称", "type": "text", "data_title": True},
7476
+ {"name": "项目封面", "type": "attachment", "data_cover": True},
7477
+ ]
7478
+ ],
7479
+ }
5489
7480
  ],
5490
7481
  "update_fields": [],
5491
7482
  "remove_fields": [],
@@ -5493,7 +7484,6 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5493
7484
  "multi_app_example": {
5494
7485
  "profile": "default",
5495
7486
  "package_id": 1001,
5496
- "create_if_missing": True,
5497
7487
  "publish": True,
5498
7488
  "apps": [
5499
7489
  {
@@ -5501,9 +7491,16 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5501
7491
  "app_name": "员工花名册",
5502
7492
  "icon": "business-personalcard",
5503
7493
  "color": "emerald",
5504
- "add_fields": [
5505
- {"name": "员工名称", "type": "text", "as_data_title": True},
5506
- {"name": "员工照片", "type": "attachment", "as_data_cover": True},
7494
+ "form": [
7495
+ {
7496
+ "section": "基础信息",
7497
+ "rows": [
7498
+ [
7499
+ {"name": "员工名称", "type": "text", "data_title": True},
7500
+ {"name": "员工照片", "type": "attachment", "data_cover": True},
7501
+ ]
7502
+ ],
7503
+ }
5507
7504
  ],
5508
7505
  },
5509
7506
  {
@@ -5511,15 +7508,22 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5511
7508
  "app_name": "工时表",
5512
7509
  "icon": "clock",
5513
7510
  "color": "blue",
5514
- "add_fields": [
5515
- {"name": "工时标题", "type": "text", "as_data_title": True},
7511
+ "form": [
5516
7512
  {
5517
- "name": "关联员工",
5518
- "type": "relation",
5519
- "target_app_ref": "employee",
5520
- "display_field": {"name": "员工名称"},
5521
- "visible_fields": [{"name": "员工名称"}],
5522
- },
7513
+ "section": "基础信息",
7514
+ "rows": [
7515
+ [{"name": "工时标题", "type": "text", "data_title": True}],
7516
+ [
7517
+ {
7518
+ "name": "关联员工",
7519
+ "type": "relation",
7520
+ "target_app_ref": "employee",
7521
+ "display_field": {"name": "员工名称"},
7522
+ "visible_fields": [{"name": "员工名称"}],
7523
+ }
7524
+ ],
7525
+ ],
7526
+ }
5523
7527
  ],
5524
7528
  },
5525
7529
  ],
@@ -5703,56 +7707,109 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5703
7707
  "sections": [{"type": "paragraph", "paragraph_id": "basic", "title": "基础信息", "rows": [["项目名称", "项目负责人", "项目阶段", "优先级"]]}],
5704
7708
  },
5705
7709
  },
5706
- "app_flow_get_schema": {
5707
- "allowed_keys": ["schema_version"],
5708
- "aliases": {"schemaVersion": "schema_version"},
5709
- "allowed_values": {},
5710
- "execution_notes": [
5711
- "returns WorkflowSpec JSON Schema from /workflow/spec/schema",
5712
- "call this before authoring a new spec or validating spec shape",
5713
- "worksheet-level approval deduplication toggles (legacy global settings) are not yet part of WorkflowSpec",
5714
- ],
5715
- "minimal_example": {
5716
- "profile": "default",
5717
- "schema_version": "vnext-2026-06",
7710
+ "app_flow_plan": {
7711
+ "allowed_keys": ["app_key", "mode", "nodes", "transitions", "preset"],
7712
+ "aliases": {
7713
+ "overwrite": "replace",
7714
+ "base_preset": "preset",
7715
+ "default_approval": "basic_approval",
7716
+ "node.role_names": "node.assignees.role_names",
7717
+ "node.role_ids": "node.assignees.role_ids",
7718
+ "node.member_names": "node.assignees.member_names",
7719
+ "node.member_emails": "node.assignees.member_emails",
7720
+ "node.member_uids": "node.assignees.member_uids",
7721
+ "node.editable_fields": "node.permissions.editable_fields",
7722
+ "default_approval": "basic_approval",
5718
7723
  },
5719
- },
5720
- "app_flow_get": {
5721
- "allowed_keys": ["app_key", "version_id"],
5722
- "aliases": {"versionId": "version_id"},
5723
- "allowed_values": {},
7724
+ "allowed_values": {
7725
+ "mode": ["replace"],
7726
+ "preset": [member.value for member in FlowPreset],
7727
+ "node.type": PUBLIC_STABLE_FLOW_NODE_TYPES,
7728
+ },
7729
+ "dependency_hints": [
7730
+ "approval-style workflows require an explicit business status select field before app_flow_apply, such as 状态 / 处理状态 / 审批状态 / 工单状态",
7731
+ "approve/fill/copy nodes require at least one assignee",
7732
+ ],
5724
7733
  "execution_notes": [
5725
- "returns current WorkflowSpecDTO for one app via GET /workflow/spec",
5726
- "use GET-first before patching and app_flow_apply",
7734
+ "app_flow_plan is a legacy helper for linear public node aliases; use app_flow_get/app_flow_get_schema plus app_flow_apply spec or patch_nodes for the full WorkflowSpec path",
7735
+ "do not create platform system workflow fields such as 当前流程状态 / 当前处理人 / 当前处理节点 / 流程标题; use an explicit business status field instead",
5727
7736
  ],
5728
7737
  "minimal_example": {
5729
7738
  "profile": "default",
5730
7739
  "app_key": "APP_KEY",
7740
+ "mode": "replace",
7741
+ "preset": "basic_approval",
7742
+ "nodes": [
7743
+ {
7744
+ "id": "approve_1",
7745
+ "type": "approve",
7746
+ "name": "部门审批",
7747
+ "assignees": {"role_names": ["项目经理"]},
7748
+ "permissions": {"editable_fields": ["状态", "审批意见"]},
7749
+ }
7750
+ ],
7751
+ "transitions": [],
5731
7752
  },
5732
7753
  },
5733
7754
  "app_flow_apply": {
5734
- "allowed_keys": ["app_key", "publish", "spec", "idempotency_key", "schema_version"],
7755
+ "allowed_keys": [
7756
+ "app_key",
7757
+ "publish",
7758
+ "spec",
7759
+ "patch_nodes",
7760
+ "idempotency_key",
7761
+ "schema_version",
7762
+ "mode",
7763
+ "nodes",
7764
+ "transitions",
7765
+ ],
5735
7766
  "aliases": {
5736
- "schemaVersion": "schema_version",
7767
+ "overwrite": "replace",
7768
+ "patchNodes": "patch_nodes",
5737
7769
  "idempotencyKey": "idempotency_key",
7770
+ "schemaVersion": "schema_version",
7771
+ "node.role_names": "node.assignees.role_names",
7772
+ "node.role_ids": "node.assignees.role_ids",
7773
+ "node.member_names": "node.assignees.member_names",
7774
+ "node.member_emails": "node.assignees.member_emails",
7775
+ "node.member_uids": "node.assignees.member_uids",
7776
+ "node.editable_fields": "node.permissions.editable_fields",
7777
+ },
7778
+ "allowed_values": {
7779
+ "mode": ["replace"],
7780
+ "node.type": PUBLIC_STABLE_FLOW_NODE_TYPES,
5738
7781
  },
5739
- "allowed_values": {},
5740
7782
  "dependency_hints": [
5741
- "spec must be a complete WorkflowSpecDTO object (replace-only apply)",
7783
+ "approval-style workflows require an explicit business status select field before app_flow_apply, such as 状态 / 处理状态 / 审批状态 / 工单状态",
7784
+ "approve/fill/copy nodes require at least one assignee",
5742
7785
  ],
5743
7786
  "execution_notes": [
5744
- "posts to /workflow/spec:apply with appKey, idempotencyKey, schemaVersion, and spec",
5745
- "verification uses appliedSpec, diffSummary, and semanticLint from the apply response",
5746
- "publish=false keeps changes in draft when supported by the backend",
7787
+ "preferred full workflow path is app_flow_get_schema/app_flow_get -> app_flow_apply with spec",
7788
+ "use patch_nodes for targeted existing-node edits; each item uses id plus set/unset",
7789
+ "legacy nodes/transitions remains available for simple linear start/approve/fill/copy/webhook/end flows only",
7790
+ "do not mix spec, patch_nodes, and legacy nodes/transitions in one call",
7791
+ "do not create platform system workflow fields such as 当前流程状态 / 当前处理人 / 当前处理节点 / 流程标题; use an explicit business status field instead",
7792
+ "workflow readback is app_flow_get; use app_flow_get_schema when raw spec shape is unclear",
5747
7793
  ],
5748
7794
  "minimal_example": {
5749
7795
  "profile": "default",
5750
7796
  "app_key": "APP_KEY",
5751
7797
  "publish": True,
5752
- "spec": {
5753
- "nodes": [{"id": "n1", "type": "APPLICANT", "name": "发起"}],
5754
- "transitions": [],
5755
- },
7798
+ "spec": {"schemaVersion": "1", "nodes": [], "edges": []},
7799
+ },
7800
+ "patch_nodes_example": {
7801
+ "profile": "default",
7802
+ "app_key": "APP_KEY",
7803
+ "publish": True,
7804
+ "patch_nodes": [{"id": "approve_1", "set": {"name": "主管审批"}}],
7805
+ },
7806
+ "legacy_linear_example": {
7807
+ "profile": "default",
7808
+ "app_key": "APP_KEY",
7809
+ "mode": "replace",
7810
+ "publish": True,
7811
+ "nodes": [{"id": "start", "type": "start", "name": "发起"}, {"id": "end", "type": "end", "name": "结束"}],
7812
+ "transitions": [{"from": "start", "to": "end"}],
5756
7813
  },
5757
7814
  },
5758
7815
  "app_views_plan": {
@@ -5768,11 +7825,15 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5768
7825
  "upsert_views[].columns",
5769
7826
  "upsert_views[].filters",
5770
7827
  "upsert_views[].buttons",
7828
+ "upsert_views[].action_buttons",
7829
+ "upsert_views[].action_buttons_mode",
5771
7830
  "upsert_views[].visibility",
5772
7831
  "upsert_views[].query_conditions",
5773
7832
  "patch_views[].view_key",
5774
7833
  "patch_views[].name",
5775
7834
  "patch_views[].set",
7835
+ "patch_views[].set.action_buttons",
7836
+ "patch_views[].set.action_buttons_mode",
5776
7837
  "patch_views[].unset",
5777
7838
  ],
5778
7839
  "aliases": {
@@ -5800,6 +7861,14 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5800
7861
  "buttons[].buttonFormula": "buttons[].button_formula",
5801
7862
  "buttons[].buttonFormulaType": "buttons[].button_formula_type",
5802
7863
  "buttons[].printTpls": "buttons[].print_tpls",
7864
+ "actionButtons": "action_buttons",
7865
+ "actionButtonsMode": "action_buttons_mode",
7866
+ "action_buttons[].button_text": "action_buttons[].text",
7867
+ "action_buttons[].trigger_action": "action_buttons[].action",
7868
+ "action_buttons[].trigger_link_url": "action_buttons[].url",
7869
+ "action_buttons[].visibleWhen": "action_buttons[].visible_when",
7870
+ "action_buttons[].fieldMappings": "action_buttons[].field_mappings",
7871
+ "action_buttons[].defaultValues": "action_buttons[].default_values",
5803
7872
  },
5804
7873
  "allowed_values": {
5805
7874
  "preset": [member.value for member in ViewsPreset],
@@ -5807,6 +7876,9 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5807
7876
  "view.filter.operator": [member.value for member in ViewFilterOperator],
5808
7877
  "view.buttons.button_type": ["SYSTEM", "CUSTOM"],
5809
7878
  "view.buttons.config_type": ["TOP", "DETAIL", "INSIDE"],
7879
+ "view.action_buttons.action": ["add_data", "link", "qRobot", "wings"],
7880
+ "view.action_buttons.placement": [member.value for member in PublicButtonPlacement],
7881
+ "view.action_buttons_mode": ["merge", "replace"],
5810
7882
  **deepcopy(_VISIBILITY_ALLOWED_VALUES),
5811
7883
  },
5812
7884
  "execution_notes": [
@@ -5816,6 +7888,9 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5816
7888
  "upsert_views[].query_conditions.rows is a layout matrix of query-panel supported field names; it is compiled to backend queryCondition queIds",
5817
7889
  "do not put relation/attachment/subtable/code_block/q_linker/address fields in query_conditions; use filters for fixed filters or app_associated_resources_apply.match_mappings for current-record relation/report matching",
5818
7890
  "use patch_views for partial parameter replacement on existing views; the tool reads current config, merges patch_views[].set/unset, then submits the backend full-save payload internally",
7891
+ "business buttons should be declared with action_buttons on the target view; app_views_apply writes the view first, then compiles action_buttons through the custom button writer and binds them to the resulting view_key",
7892
+ "action_buttons_mode defaults to merge; replace rewrites this view's custom button bindings, and replace plus action_buttons=[] clears this view's custom button bindings without deleting button bodies",
7893
+ "legacy upsert_views[].buttons is a compatibility path for raw full replacement of existing view button config; do not use it as the normal agent path",
5819
7894
  "remove_views accepts a raw view_key or an exact unique view name; after DELETE the tool verifies deletion by single view_key readback, not by a full app view list",
5820
7895
  "deleted views return verification.by_view[].delete_executed, readback_status, and safe_to_retry_delete=false; if readback is pending, do not blindly repeat the delete",
5821
7896
  "do not create business views named 全部数据, 我的数据, 我发起的, 待办, 已办, or 抄送; these are built-in system/default views. Use business-specific names for new views, and pass the existing raw view_key or patch_views when changing a built-in view",
@@ -5846,6 +7921,27 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5846
7921
  ],
5847
7922
  "remove_views": [],
5848
7923
  },
7924
+ "action_buttons_example": {
7925
+ "profile": "default",
7926
+ "app_key": "APP_KEY",
7927
+ "upsert_views": [
7928
+ {
7929
+ "name": "生产工单执行视图",
7930
+ "type": "table",
7931
+ "columns": ["工单编号", "产品", "状态", "负责人"],
7932
+ "action_buttons": [
7933
+ {
7934
+ "text": "开始生产",
7935
+ "action": "link",
7936
+ "url": "https://example.com/start",
7937
+ "placement": "list",
7938
+ "visible_when": [{"field_name": "状态", "operator": "eq", "value": "待排产"}],
7939
+ }
7940
+ ],
7941
+ }
7942
+ ],
7943
+ "remove_views": [],
7944
+ },
5849
7945
  "full_upsert_query_conditions_example": {
5850
7946
  "profile": "default",
5851
7947
  "app_key": "APP_KEY",
@@ -5892,6 +7988,17 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5892
7988
  },
5893
7989
  "app_views_apply": {
5894
7990
  "allowed_keys": [
7991
+ "views",
7992
+ "views[].operation",
7993
+ "views[].app_key",
7994
+ "views[].view_key",
7995
+ "views[].name",
7996
+ "views[].type",
7997
+ "views[].columns",
7998
+ "views[].filters",
7999
+ "views[].action_buttons",
8000
+ "views[].set",
8001
+ "views[].unset",
5895
8002
  "app_key",
5896
8003
  "publish",
5897
8004
  "upsert_views",
@@ -5903,11 +8010,15 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5903
8010
  "upsert_views[].columns",
5904
8011
  "upsert_views[].filters",
5905
8012
  "upsert_views[].buttons",
8013
+ "upsert_views[].action_buttons",
8014
+ "upsert_views[].action_buttons_mode",
5906
8015
  "upsert_views[].visibility",
5907
8016
  "upsert_views[].query_conditions",
5908
8017
  "patch_views[].view_key",
5909
8018
  "patch_views[].name",
5910
8019
  "patch_views[].set",
8020
+ "patch_views[].set.action_buttons",
8021
+ "patch_views[].set.action_buttons_mode",
5911
8022
  "patch_views[].unset",
5912
8023
  ],
5913
8024
  "aliases": {
@@ -5923,6 +8034,10 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5923
8034
  "queryConditions": "query_conditions",
5924
8035
  "query_condition": "query_conditions",
5925
8036
  "queryCondition": "query_conditions",
8037
+ "views[].op": "views[].operation",
8038
+ "views[].fields": "views[].columns",
8039
+ "views[].viewKey": "views[].view_key",
8040
+ "views[].actionButtons": "views[].action_buttons",
5926
8041
  "patchViews": "patch_views",
5927
8042
  "startField": "start_field",
5928
8043
  "endField": "end_field",
@@ -5935,21 +8050,39 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5935
8050
  "buttons[].buttonFormula": "buttons[].button_formula",
5936
8051
  "buttons[].buttonFormulaType": "buttons[].button_formula_type",
5937
8052
  "buttons[].printTpls": "buttons[].print_tpls",
8053
+ "actionButtons": "action_buttons",
8054
+ "actionButtonsMode": "action_buttons_mode",
8055
+ "action_buttons[].button_text": "action_buttons[].text",
8056
+ "action_buttons[].trigger_action": "action_buttons[].action",
8057
+ "action_buttons[].trigger_link_url": "action_buttons[].url",
8058
+ "action_buttons[].visibleWhen": "action_buttons[].visible_when",
8059
+ "action_buttons[].fieldMappings": "action_buttons[].field_mappings",
8060
+ "action_buttons[].defaultValues": "action_buttons[].default_values",
5938
8061
  },
5939
8062
  "allowed_values": {
8063
+ "views[].operation": ["upsert", "patch", "remove"],
5940
8064
  "view.type": [member.value for member in PublicViewType],
5941
8065
  "view.filter.operator": [member.value for member in ViewFilterOperator],
5942
8066
  "view.buttons.button_type": ["SYSTEM", "CUSTOM"],
5943
8067
  "view.buttons.config_type": ["TOP", "DETAIL", "INSIDE"],
8068
+ "view.action_buttons.action": ["add_data", "link", "qRobot", "wings"],
8069
+ "view.action_buttons.placement": [member.value for member in PublicButtonPlacement],
8070
+ "view.action_buttons_mode": ["merge", "replace"],
5944
8071
  **deepcopy(_VISIBILITY_ALLOWED_VALUES),
5945
8072
  },
5946
8073
  "execution_notes": [
8074
+ "preferred batch input is views[]; each item has app_key and operation=upsert/patch/remove, and the same batch may mix same-app and cross-app views",
8075
+ f"views[] jobs run concurrently with an internal limit of {VIEW_APPLY_PARALLEL_LIMIT}; results are returned in input order",
5947
8076
  "apply may return partial_success when some views land and others fail",
5948
8077
  "creating a new view follows backend createViewgraphConfig and requires both ViewManagementAuth and DataManageAuth; updating/deleting existing views only requires ViewManagementAuth",
5949
8078
  "when duplicate view names exist, supply view_key to target the exact view",
5950
8079
  "read back app_get after any failed or partial view apply",
5951
8080
  "view existence verification and saved-filter verification are separate; treat filters as unverified until verification.view_filters_verified is true",
5952
8081
  "buttons omitted preserves existing button config; buttons=[] clears all buttons; buttons=[...] replaces the full button config",
8082
+ "business buttons should be declared with action_buttons on the target view; app_views_apply writes the view first, then compiles action_buttons through the custom button writer and binds them to the resulting view_key",
8083
+ "patch_views[].set.action_buttons can add buttons to an existing view without rewriting columns/filters; action_buttons_mode defaults to merge, replace rewrites this view's custom button bindings, and replace plus action_buttons=[] clears bindings without deleting button bodies",
8084
+ "publish=false with action_buttons is blocked as VIEW_ACTION_BUTTONS_REQUIRE_PUBLISH because the underlying custom button writer may publish after successful button writes",
8085
+ "legacy upsert_views[].buttons is a compatibility path for raw full replacement of existing view button config; do not use it as the normal agent path",
5953
8086
  "upsert_views[].visibility may set per-view visibility; omit it to preserve an existing view's auth or default a new view to workspace/not",
5954
8087
  "filters are saved fixed filters that apply when the view opens; query_conditions configure the frontend query panel and only apply after a user enters query values",
5955
8088
  "upsert_views[].query_conditions.rows is a layout matrix of query-panel supported field names; it is compiled to backend queryCondition queIds",
@@ -5965,10 +8098,8 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5965
8098
  ],
5966
8099
  "minimal_example": {
5967
8100
  "profile": "default",
5968
- "app_key": "APP_KEY",
5969
8101
  "publish": True,
5970
- "upsert_views": [{"name": "项目台账视图", "type": "table", "columns": ["项目名称"], "visibility": deepcopy(_VISIBILITY_WORKSPACE_EXAMPLE)}],
5971
- "remove_views": [],
8102
+ "views": [{"operation": "upsert", "app_key": "APP_KEY", "name": "项目台账视图", "type": "table", "columns": ["项目名称"], "visibility": deepcopy(_VISIBILITY_WORKSPACE_EXAMPLE)}],
5972
8103
  },
5973
8104
  "query_conditions_example": {
5974
8105
  "profile": "default",
@@ -5987,6 +8118,51 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
5987
8118
  ],
5988
8119
  "remove_views": [],
5989
8120
  },
8121
+ "action_buttons_example": {
8122
+ "profile": "default",
8123
+ "app_key": "APP_KEY",
8124
+ "publish": True,
8125
+ "upsert_views": [
8126
+ {
8127
+ "name": "生产工单执行视图",
8128
+ "type": "table",
8129
+ "columns": ["工单编号", "产品", "状态", "负责人"],
8130
+ "action_buttons": [
8131
+ {
8132
+ "text": "开始生产",
8133
+ "action": "link",
8134
+ "url": "https://example.com/start",
8135
+ "placement": "list",
8136
+ "visible_when": [{"field_name": "状态", "operator": "eq", "value": "待排产"}],
8137
+ }
8138
+ ],
8139
+ }
8140
+ ],
8141
+ "remove_views": [],
8142
+ },
8143
+ "action_buttons_patch_example": {
8144
+ "profile": "default",
8145
+ "app_key": "APP_KEY",
8146
+ "publish": True,
8147
+ "patch_views": [
8148
+ {
8149
+ "view_key": "RAW_VIEW_KEY",
8150
+ "set": {
8151
+ "action_buttons": [
8152
+ {
8153
+ "text": "创建验收单",
8154
+ "action": "add_data",
8155
+ "target_app_key": "ARRIVAL_APP",
8156
+ "field_mappings": [{"source_field": "数据ID", "target_field": "关联工单"}],
8157
+ "default_values": {"状态": "待验收"},
8158
+ "placement": "detail",
8159
+ }
8160
+ ]
8161
+ },
8162
+ }
8163
+ ],
8164
+ "remove_views": [],
8165
+ },
5990
8166
  "full_upsert_query_conditions_example": {
5991
8167
  "profile": "default",
5992
8168
  "app_key": "APP_KEY",
@@ -6102,8 +8278,8 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
6102
8278
  "aliases": {},
6103
8279
  "allowed_values": {},
6104
8280
  "execution_notes": [
6105
- "returns WorkflowSpecDTO for one app (alias of app_flow_get)",
6106
- "use app_flow_get_schema then app_flow_get before app_flow_apply",
8281
+ "returns workflow configuration summary for one app",
8282
+ "use this before app_flow_apply when you need the current node structure",
6107
8283
  ],
6108
8284
  "minimal_example": {
6109
8285
  "profile": "default",
@@ -6256,21 +8432,48 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
6256
8432
  },
6257
8433
  },
6258
8434
  "portal_apply": {
6259
- "allowed_keys": ["dash_key", "dash_name", "name", "package_id", "publish", "sections", "pages", "payload", "layout_preset", "visibility", "auth", "icon", "color", "hide_copyright", "dash_global_config", "config"],
8435
+ "allowed_keys": ["dash_key", "dash_name", "name", "package_id", "publish", "sections", "patch_sections", "pages", "payload", "layout_preset", "visibility", "auth", "icon", "color", "hide_copyright", "dash_global_config", "config"],
6260
8436
  "aliases": {
6261
8437
  "packageId": "package_id",
6262
8438
  "name": "dash_name",
6263
8439
  "sourceType": "source_type",
6264
8440
  "chartRef": "chart_ref",
8441
+ "inlineChart": "chart",
8442
+ "createChart": "chart",
6265
8443
  "viewRef": "view_ref",
6266
8444
  "dashStyleConfigBO": "dash_style_config",
6267
8445
  },
6268
- "section_allowed_keys": ["title", "source_type", "role", "position", "dash_style_config", "config", "chart_ref", "view_ref", "text", "url"],
8446
+ "section_allowed_keys": [
8447
+ "title",
8448
+ "source_type",
8449
+ "role",
8450
+ "position",
8451
+ "dash_style_config",
8452
+ "config",
8453
+ "chart",
8454
+ "chart.app_key",
8455
+ "chart.name",
8456
+ "chart.chart_name",
8457
+ "chart.chart_type",
8458
+ "chart.metric",
8459
+ "chart.metrics",
8460
+ "chart.group_by",
8461
+ "chart.where",
8462
+ "chart.filters",
8463
+ "chart.chart_id",
8464
+ "chart.chart_key",
8465
+ "chart_ref",
8466
+ "view_ref",
8467
+ "text",
8468
+ "url",
8469
+ ],
6269
8470
  "section_aliases": {
6270
8471
  "sourceType": "source_type",
6271
8472
  "zone": "role",
6272
8473
  "sectionRole": "role",
6273
8474
  "chartRef": "chart_ref",
8475
+ "inlineChart": "chart",
8476
+ "createChart": "chart",
6274
8477
  "viewRef": "view_ref",
6275
8478
  "dashStyleConfigBO": "dash_style_config",
6276
8479
  },
@@ -6295,7 +8498,9 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
6295
8498
  "remove a section by omitting it from the new sections list",
6296
8499
  "package_id is required when creating a new portal",
6297
8500
  "publish=false only guarantees draft and base-info updates; it does not claim live has changed",
6298
- "chart_ref resolves by chart_id first, then exact unique chart_name",
8501
+ "sections[].chart is the canonical QingBI chart field: chart_id/chart_key/chart_name references existing charts, while app_key+name/chart_type creates or updates app-source charts inline",
8502
+ f"portal inline chart creation runs as chart jobs with an internal parallel limit of {PORTAL_INLINE_CHART_MAX_WORKERS}; identical same-app chart definitions are reused, conflicting duplicates are rejected",
8503
+ "chart_ref and inline_chart remain compatibility aliases; do not use them as the normal agent path",
6299
8504
  "view_ref resolves by view_key first, then exact unique view_name",
6300
8505
  "pc layout uses a 24-column grid; mobile layout uses a 6-column grid",
6301
8506
  "if unsure about layout, omit position or use layout_preset=auto/dashboard_2col/dashboard_3col",
@@ -6323,7 +8528,12 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
6323
8528
  {
6324
8529
  "title": "经营概览",
6325
8530
  "source_type": "chart",
6326
- "chart_ref": {"app_key": "APP_KEY", "chart_name": "数据总量"},
8531
+ "chart": {
8532
+ "app_key": "APP_KEY",
8533
+ "name": "数据总量",
8534
+ "chart_type": "summary",
8535
+ "metric": {"field": "数据ID", "agg": "count"},
8536
+ },
6327
8537
  "position": {
6328
8538
  "pc": {"x": 0, "y": 0, "cols": 12, "rows": 6},
6329
8539
  "mobile": {"x": 0, "y": 0, "cols": 6, "rows": 6},
@@ -6342,7 +8552,7 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
6342
8552
  {
6343
8553
  "title": "销售趋势",
6344
8554
  "source_type": "chart",
6345
- "chart_ref": {"app_key": "APP_KEY", "chart_id": "CHART_ID"},
8555
+ "chart": {"chart_id": "CHART_ID"},
6346
8556
  }
6347
8557
  ],
6348
8558
  }
@@ -6409,6 +8619,7 @@ _BUILDER_TOOL_CONTRACTS: dict[str, JSONObject] = {
6409
8619
  _PRIVATE_BUILDER_TOOL_CONTRACTS = {
6410
8620
  "app_schema_plan",
6411
8621
  "app_layout_plan",
8622
+ "app_flow_plan",
6412
8623
  "app_views_plan",
6413
8624
  }
6414
8625