@taskforcehq/taskforce 0.3.329 → 0.3.330

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 (321) hide show
  1. package/dist/Taskforce.module.css +290 -45
  2. package/dist/components/features/AiProfilesModule.js +3 -5
  3. package/dist/components/features/TaskSettings.js +70 -14
  4. package/dist/components/features/TaskforceAgentsModule.d.ts +1 -2
  5. package/dist/components/features/TaskforceAgentsModule.js +586 -116
  6. package/dist/components/features/agentConnections/AgentConnectionControl.d.ts +15 -0
  7. package/dist/components/features/agentConnections/AgentConnectionControl.js +125 -0
  8. package/dist/components/features/agentConnections/ModelConnectionsPanel.d.ts +18 -0
  9. package/dist/components/features/agentConnections/ModelConnectionsPanel.js +393 -0
  10. package/dist/components/features/agentConnections/modelConnectionsApi.d.ts +65 -0
  11. package/dist/components/features/agentConnections/modelConnectionsApi.js +129 -0
  12. package/dist/components/features/taskforceAgentAssignments/AgentBehaviorAssignments.js +15 -24
  13. package/dist/components/features/taskforceAgentEditorModel.d.ts +2 -1
  14. package/dist/components/features/taskforceAgentEditorModel.js +3 -1
  15. package/dist/components/features/workflowManager/workflowManagerApi.d.ts +1 -1
  16. package/dist/components/features/workflowManager/workflowManagerApi.js +3 -0
  17. package/dist/components/task/TaskWorkflowAssignmentField.js +68 -10
  18. package/dist/components/views/StandaloneLayout.js +27 -26
  19. package/dist/components/views/standalone/modals/SyncStatusModal.d.ts +4 -3
  20. package/dist/components/views/standalone/modals/SyncStatusModal.js +33 -38
  21. package/dist/config/envSchema.js +48 -1
  22. package/dist/core/McpTokenService.d.ts +23 -1
  23. package/dist/core/McpTokenService.js +93 -10
  24. package/dist/core/TaskChecklistCommandService.d.ts +27 -0
  25. package/dist/core/TaskChecklistCommandService.js +83 -5
  26. package/dist/core/TaskLifecycleCommandService.d.ts +3 -1
  27. package/dist/core/TaskLifecycleCommandService.js +6 -2
  28. package/dist/core/Taskforce.d.ts +32 -0
  29. package/dist/core/Taskforce.js +125 -4
  30. package/dist/core/types.d.ts +8 -0
  31. package/dist/documentReviews/commandService.d.ts +2 -1
  32. package/dist/documentReviews/commandService.js +6 -3
  33. package/dist/hooks/sync/orchestratorShared.d.ts +1 -0
  34. package/dist/hooks/sync/orchestratorShared.js +2 -0
  35. package/dist/hooks/sync/useLocalSyncCoordinatorSnapshot.d.ts +3 -0
  36. package/dist/hooks/sync/useLocalSyncCoordinatorSnapshot.js +85 -9
  37. package/dist/hooks/sync/useSyncStatusControls.d.ts +4 -1
  38. package/dist/hooks/sync/useSyncStatusControls.js +47 -11
  39. package/dist/hooks/useSyncOrchestrator.d.ts +3 -0
  40. package/dist/hooks/useSyncOrchestrator.js +111 -2
  41. package/dist/hooks/useTaskData.d.ts +31 -1
  42. package/dist/hooks/useTaskData.js +29 -7
  43. package/dist/hooks/useTaskMutations.d.ts +3 -1
  44. package/dist/hooks/useTaskMutations.js +46 -12
  45. package/dist/hooks/useTaskforce.d.ts +2 -0
  46. package/dist/hooks/useTaskforce.js +11 -2
  47. package/dist/mcp/clientRegistry.d.ts +2 -2
  48. package/dist/mcp/clientRegistry.js +1 -1
  49. package/dist/mcp/documentAssetRegistrar.js +9 -6
  50. package/dist/mcp/durableTaskMutationRouter.d.ts +4 -1
  51. package/dist/mcp/durableTaskMutationRouter.js +10 -0
  52. package/dist/mcp/durableTaskRelationshipMutationRouter.js +4 -0
  53. package/dist/mcp/httpProtocolRouting.d.ts +10 -0
  54. package/dist/mcp/httpProtocolRouting.js +19 -0
  55. package/dist/mcp/localCliHealth.d.ts +2 -2
  56. package/dist/mcp/localCliHealth.js +2 -2
  57. package/dist/mcp/localServiceProxy.d.ts +1 -0
  58. package/dist/mcp/localServiceProxy.js +530 -68
  59. package/dist/mcp/planningAttachmentCommandAdapter.d.ts +3 -1
  60. package/dist/mcp/planningAttachmentCommandAdapter.js +20 -2
  61. package/dist/mcp/runtime.d.ts +54 -79
  62. package/dist/mcp/runtime.js +384 -97
  63. package/dist/mcp/taskPlanningRegistrar.js +23 -4
  64. package/dist/mcp/toolProfiles.d.ts +2 -0
  65. package/dist/mcp/toolProfiles.js +10 -0
  66. package/dist/mcp/toolRegistry.d.ts +1 -0
  67. package/dist/mcp/toolRegistry.js +1 -0
  68. package/dist/mcp/workflowExecutionRegistrar.js +4 -4
  69. package/dist/migrations/taskSchemaMigrations.d.ts +5 -0
  70. package/dist/migrations/taskSchemaMigrations.js +415 -0
  71. package/dist/runtime/appGates.d.ts +2 -1
  72. package/dist/runtime/appGates.js +7 -0
  73. package/dist/server/index.d.ts +3 -0
  74. package/dist/server/index.js +108 -11
  75. package/dist/server/localDatabaseIdentity.js +4 -1
  76. package/dist/server/localServiceLease.js +2 -1
  77. package/dist/server/localServiceSessions.d.ts +14 -17
  78. package/dist/server/localServiceSessions.js +308 -94
  79. package/dist/server/localWorkspaceSyncServerRuntime.js +12 -14
  80. package/dist/server/routes/admin.d.ts +4 -0
  81. package/dist/server/routes/admin.js +112 -3
  82. package/dist/server/routes/agents.d.ts +7 -0
  83. package/dist/server/routes/agents.js +277 -24
  84. package/dist/server/routes/billing.js +5 -1
  85. package/dist/server/routes/durableTaskHttpRouters.d.ts +2 -0
  86. package/dist/server/routes/executorPhaseAApprovals.d.ts +19 -0
  87. package/dist/server/routes/executorPhaseAApprovals.js +140 -0
  88. package/dist/server/routes/executorPhaseAIssuerRedemptions.d.ts +11 -0
  89. package/dist/server/routes/executorPhaseAIssuerRedemptions.js +24 -0
  90. package/dist/server/routes/githubReviewEvidence.d.ts +19 -0
  91. package/dist/server/routes/githubReviewEvidence.js +116 -0
  92. package/dist/server/routes/localService.d.ts +15 -4
  93. package/dist/server/routes/localService.js +136 -40
  94. package/dist/server/routes/modelConnections.d.ts +24 -0
  95. package/dist/server/routes/modelConnections.js +205 -0
  96. package/dist/server/routes/shared.d.ts +19 -0
  97. package/dist/server/routes/shared.js +95 -19
  98. package/dist/server/routes/sync.js +1 -0
  99. package/dist/server/routes/syncAuxRoutes.js +5 -1
  100. package/dist/server/routes/syncPushRoutes.d.ts +1 -0
  101. package/dist/server/routes/syncPushRoutes.js +1 -0
  102. package/dist/server/routes/syncV3FeedRoutes.js +10 -1
  103. package/dist/server/routes/syncV3OperationRoutes.js +35 -9
  104. package/dist/server/routes/tasks.js +21 -2
  105. package/dist/server/routes/workflows.js +9 -1
  106. package/dist/server/routes.js +59 -0
  107. package/dist/services/codexAppServerModelGateway.d.ts +54 -5
  108. package/dist/services/codexAppServerModelGateway.js +246 -21
  109. package/dist/services/codexDeviceCodeLoginManager.d.ts +39 -0
  110. package/dist/services/codexDeviceCodeLoginManager.js +265 -0
  111. package/dist/services/codexModelProviderConnectionLifecycle.d.ts +8 -0
  112. package/dist/services/codexModelProviderConnectionLifecycle.js +73 -0
  113. package/dist/services/executorPhaseAApprovalRuntime.d.ts +14 -0
  114. package/dist/services/executorPhaseAApprovalRuntime.js +24 -0
  115. package/dist/services/executorPhaseAApprovalService.d.ts +40 -0
  116. package/dist/services/executorPhaseAApprovalService.js +609 -0
  117. package/dist/services/executorPhaseADriftEvaluator.d.ts +78 -0
  118. package/dist/services/executorPhaseADriftEvaluator.js +93 -0
  119. package/dist/services/executorPhaseAIssuerCore.d.ts +126 -0
  120. package/dist/services/executorPhaseAIssuerCore.js +295 -0
  121. package/dist/services/executorPhaseAIssuerRedemptionService.d.ts +34 -0
  122. package/dist/services/executorPhaseAIssuerRedemptionService.js +158 -0
  123. package/dist/services/githubReviewEvidenceRuntime.d.ts +14 -0
  124. package/dist/services/githubReviewEvidenceRuntime.js +30 -0
  125. package/dist/services/githubReviewEvidenceService.d.ts +93 -0
  126. package/dist/services/githubReviewEvidenceService.js +336 -0
  127. package/dist/services/modelGateway.d.ts +7 -0
  128. package/dist/services/modelProviderConnectionService.d.ts +71 -0
  129. package/dist/services/modelProviderConnectionService.js +279 -0
  130. package/dist/services/modelProviderCredentialHome.d.ts +32 -0
  131. package/dist/services/modelProviderCredentialHome.js +271 -0
  132. package/dist/services/ownerScopedModelConnectionGateway.d.ts +12 -0
  133. package/dist/services/ownerScopedModelConnectionGateway.js +30 -0
  134. package/dist/services/taskforceAgentConnectionBindingService.d.ts +66 -0
  135. package/dist/services/taskforceAgentConnectionBindingService.js +185 -0
  136. package/dist/services/taskforceAgentMcpBridge.d.ts +1 -1
  137. package/dist/services/taskforceAgentMcpBridge.js +7 -24
  138. package/dist/shared/adminEdgeProxy.d.ts +5 -0
  139. package/dist/shared/adminEdgeProxy.js +94 -0
  140. package/dist/shared/adminProxySessionCookies.d.ts +16 -0
  141. package/dist/shared/adminProxySessionCookies.js +86 -0
  142. package/dist/shared/aiProfileColors.d.ts +31 -1
  143. package/dist/shared/aiProfileColors.js +14 -6
  144. package/dist/shared/executorPhaseAApprovalGoldenVector.json +269 -0
  145. package/dist/shared/executorPhaseAApprovalReceipt.d.ts +112 -0
  146. package/dist/shared/executorPhaseAApprovalReceipt.js +58 -0
  147. package/dist/shared/executorPhaseAApprovalTrustPolicy.json +10 -0
  148. package/dist/shared/executorPhaseADriftContracts.d.ts +37 -0
  149. package/dist/shared/executorPhaseADriftContracts.js +63 -0
  150. package/dist/shared/executorPhaseAIssuerContracts.d.ts +75 -0
  151. package/dist/shared/executorPhaseAIssuerContracts.js +90 -0
  152. package/dist/shared/executorPhaseARunAuthorization.d.ts +120 -0
  153. package/dist/shared/executorPhaseARunAuthorization.js +232 -0
  154. package/dist/shared/executorPhaseASchemaValidation.d.ts +7 -0
  155. package/dist/shared/executorPhaseASchemaValidation.js +53 -0
  156. package/dist/shared/executorPhaseASchemas/approval-receipt.schema.json +106 -0
  157. package/dist/shared/executorPhaseASchemas/drift-attestation.schema.json +54 -0
  158. package/dist/shared/executorPhaseASchemas/drift-request.schema.json +47 -0
  159. package/dist/shared/executorPhaseASchemas/foundation-manifest.schema.json +29 -0
  160. package/dist/shared/executorPhaseASchemas/issuer-audit-record.schema.json +24 -0
  161. package/dist/shared/executorPhaseASchemas/issuer-proof.schema.json +43 -0
  162. package/dist/shared/executorPhaseASchemas/issuer-redemption-request.schema.json +18 -0
  163. package/dist/shared/executorPhaseASchemas/issuer-redemption-response.schema.json +39 -0
  164. package/dist/shared/executorPhaseASchemas/logical-envelope.schema.json +149 -0
  165. package/dist/shared/executorPhaseASchemas/preflight-report.schema.json +216 -0
  166. package/dist/shared/executorPhaseASchemas/run-capability.schema.json +111 -0
  167. package/dist/shared/executorPhaseASchemas/sender-proof.schema.json +37 -0
  168. package/dist/shared/executorPhaseASchemas/workload-grant.schema.json +68 -0
  169. package/dist/shared/executorPhaseASchemas/workload-jwt-claims.schema.json +67 -0
  170. package/dist/shared/executorPhaseATiming.d.ts +1 -0
  171. package/dist/shared/executorPhaseATiming.js +1 -0
  172. package/dist/shared/planningIdentity.js +1 -1
  173. package/dist/shared/productLogoKeys.d.ts +2 -0
  174. package/dist/shared/productLogoKeys.js +18 -0
  175. package/dist/shared/taskforceAgentDefinition.d.ts +0 -1
  176. package/dist/shared/taskforceAgentDefinition.js +6 -9
  177. package/dist/shared/taskforceAgentModels.js +7 -3
  178. package/dist/shared/userFeatureGrants.d.ts +4 -0
  179. package/dist/shared/userFeatureGrants.js +7 -0
  180. package/dist/storage/executorPhaseAApprovalReceiptStore.d.ts +37 -0
  181. package/dist/storage/executorPhaseAApprovalReceiptStore.js +81 -0
  182. package/dist/storage/executorPhaseARunAuthorizationStore.d.ts +103 -0
  183. package/dist/storage/executorPhaseARunAuthorizationStore.js +492 -0
  184. package/dist/storage/githubReviewEvidenceInstallationStore.d.ts +26 -0
  185. package/dist/storage/githubReviewEvidenceInstallationStore.js +89 -0
  186. package/dist/storage/modelProviderConnectionStore.d.ts +99 -0
  187. package/dist/storage/modelProviderConnectionStore.js +446 -0
  188. package/dist/storage/postgresAdapter.d.ts +4 -0
  189. package/dist/storage/postgresAdapter.js +11 -0
  190. package/dist/storage/postgresWorker.js +9 -1
  191. package/dist/storage/postgresWorkerProtocol.d.ts +1 -0
  192. package/dist/storage/taskforceAgentConnectionBindingStore.d.ts +31 -0
  193. package/dist/storage/taskforceAgentConnectionBindingStore.js +84 -0
  194. package/dist/sync/coordinator/localSyncExecutionPermitStore.js +60 -29
  195. package/dist/sync/coordinator/localWorkspaceSyncPendingV2PushProgress.d.ts +10 -0
  196. package/dist/sync/coordinator/localWorkspaceSyncPendingV2PushProgress.js +29 -0
  197. package/dist/sync/coordinator/localWorkspaceSyncRunnerState.d.ts +15 -1
  198. package/dist/sync/coordinator/localWorkspaceSyncRunnerState.js +99 -2
  199. package/dist/sync/coordinator/workspaceSyncCredentialBroker.d.ts +1 -0
  200. package/dist/sync/coordinator/workspaceSyncCredentialBroker.js +33 -4
  201. package/dist/sync/engine/workspaceSyncContentLifecycleAdapter.d.ts +2 -1
  202. package/dist/sync/engine/workspaceSyncContentVersionStore.d.ts +38 -0
  203. package/dist/sync/engine/workspaceSyncContentVersionStore.js +50 -1
  204. package/dist/sync/engine/workspaceSyncEngineLifecyclePolicy.js +6 -6
  205. package/dist/sync/engine/workspaceSyncEnginePushCompletion.d.ts +14 -0
  206. package/dist/sync/engine/workspaceSyncEnginePushCompletion.js +84 -0
  207. package/dist/sync/engine/workspaceSyncEngineRecovery.js +1 -0
  208. package/dist/sync/engine/workspaceSyncEngineRuntime.d.ts +1 -0
  209. package/dist/sync/engine/workspaceSyncEngineRuntime.js +1 -0
  210. package/dist/sync/engine/workspaceSyncEngineServerRunnerOperations.js +112 -38
  211. package/dist/sync/engine/workspaceSyncEngineServerSnapshotReader.js +6 -0
  212. package/dist/sync/engine/workspaceSyncEngineTransfers.js +3 -1
  213. package/dist/sync/engine/workspaceSyncV2ChangeDispatcher.d.ts +1 -0
  214. package/dist/sync/engine/workspaceSyncV2ChangeDispatcher.js +29 -0
  215. package/dist/sync/syncApplyHandlers.d.ts +2 -0
  216. package/dist/sync/syncApplyHandlers.js +10 -1
  217. package/dist/sync/syncService.d.ts +15 -0
  218. package/dist/sync/syncService.js +83 -18
  219. package/dist/sync/taskforceAgentSyncAuthorization.d.ts +16 -0
  220. package/dist/sync/taskforceAgentSyncAuthorization.js +20 -0
  221. package/dist/sync/v3/combinedFeedCapability.js +4 -0
  222. package/dist/sync/v3/durableInitiativeMutationRouter.js +18 -10
  223. package/dist/sync/v3/durableOperationReplay.d.ts +14 -0
  224. package/dist/sync/v3/durableOperationReplay.js +18 -0
  225. package/dist/sync/v3/durableTaskAttachmentLinksMutationRouter.js +3 -0
  226. package/dist/sync/v3/durableTaskChecklistMutationRouter.d.ts +2 -1
  227. package/dist/sync/v3/durableTaskChecklistMutationRouter.js +58 -15
  228. package/dist/sync/v3/durableTaskCommentMutationRouter.js +3 -0
  229. package/dist/sync/v3/durableTaskHttpRootMutationRouter.d.ts +1 -1
  230. package/dist/sync/v3/durableTaskHttpRootMutationRouter.js +10 -0
  231. package/dist/sync/v3/durableTaxonomyMutationRouter.js +5 -0
  232. package/dist/sync/v3/durableWorkflowRuntimeMutationRouter.d.ts +11 -0
  233. package/dist/sync/v3/durableWorkflowRuntimeMutationRouter.js +39 -10
  234. package/dist/sync/v3/durableWorkstreamMutationRouter.js +18 -10
  235. package/dist/sync/v3/durableWorkstreamTaskOrderMutationRouter.js +16 -5
  236. package/dist/sync/v3/localOutboxDispatchRuntime.js +2 -2
  237. package/dist/sync/v3/localTaskChecklistOutboxHandler.js +16 -2
  238. package/dist/sync/v3/localTaskChecklistOutboxService.d.ts +4 -0
  239. package/dist/sync/v3/localTaskChecklistOutboxService.js +14 -1
  240. package/dist/sync/v3/localTaskStatusOutboxService.d.ts +8 -0
  241. package/dist/sync/v3/localTaskStatusOutboxService.js +219 -12
  242. package/dist/sync/v3/syncDurabilityStore.d.ts +34 -0
  243. package/dist/sync/v3/syncDurabilityStore.js +168 -2
  244. package/dist/sync/v3/taskChecklistMutationService.d.ts +11 -0
  245. package/dist/sync/v3/taskChecklistMutationService.js +44 -1
  246. package/dist/sync/v3/taskStatusMutationService.d.ts +29 -1
  247. package/dist/sync/v3/taskStatusMutationService.js +119 -3
  248. package/dist/sync/v3/workflowAssignmentSync.d.ts +5 -0
  249. package/dist/sync/v3/workflowAssignmentSync.js +27 -0
  250. package/dist/sync/v3/workspaceSyncJournalReader.js +1 -1
  251. package/dist/sync/v3/workspaceSyncOperationRetentionService.d.ts +16 -0
  252. package/dist/sync/v3/workspaceSyncOperationRetentionService.js +83 -0
  253. package/dist/sync/v3/workspaceSyncV3CloudOperationHandler.d.ts +1 -0
  254. package/dist/sync/v3/workspaceSyncV3CloudOperationHandler.js +9 -2
  255. package/dist/sync/v3/workspaceSyncV3CombinedRepairBaseline.d.ts +7 -0
  256. package/dist/sync/v3/workspaceSyncV3CombinedRepairBaseline.js +44 -32
  257. package/dist/sync/v3/workspaceSyncV3CombinedRepairMaterialization.d.ts +9 -5
  258. package/dist/sync/v3/workspaceSyncV3CombinedRepairMaterialization.js +54 -38
  259. package/dist/sync/v3/workspaceSyncV3CombinedRepairSnapshot.d.ts +10 -0
  260. package/dist/sync/v3/workspaceSyncV3CombinedRepairSnapshot.js +70 -31
  261. package/dist/sync/v3/workspaceSyncV3CombinedWireContract.d.ts +2 -1
  262. package/dist/sync/v3/workspaceSyncV3CombinedWireContract.js +16 -0
  263. package/dist/sync/v3/workspaceSyncV3CoverageRegistry.js +6 -0
  264. package/dist/sync/v3/workspaceSyncV3OperationProtocol.d.ts +3 -0
  265. package/dist/sync/v3/workspaceSyncV3OperatorDiagnostics.d.ts +5 -0
  266. package/dist/sync/v3/workspaceSyncV3OperatorDiagnostics.js +36 -2
  267. package/dist/sync/v3/workspaceSyncV3RepairSnapshotRetentionService.d.ts +17 -0
  268. package/dist/sync/v3/workspaceSyncV3RepairSnapshotRetentionService.js +64 -0
  269. package/dist/sync/v3/workspaceSyncV3WorkflowTaskCoverCoverage.d.ts +7 -0
  270. package/dist/sync/v3/workspaceSyncV3WorkflowTaskCoverCoverage.js +33 -0
  271. package/dist/sync/v3/workspaceSyncV3WorkflowTaskCoverWireContract.d.ts +7 -0
  272. package/dist/sync/v3/workspaceSyncV3WorkflowTaskCoverWireContract.js +8 -0
  273. package/dist/sync/workspaceRepair.d.ts +5 -2
  274. package/dist/sync/workspaceRepair.js +161 -6
  275. package/dist/sync/workspaceSyncModel.d.ts +21 -0
  276. package/dist/sync/workspaceSyncModel.js +35 -7
  277. package/dist/sync/workspaceSyncState.d.ts +1 -0
  278. package/dist/sync/workspaceSyncV2SnapshotBuilder.d.ts +6 -0
  279. package/dist/sync/workspaceSyncV2SnapshotBuilder.js +5 -0
  280. package/dist/ui/assets/AiIdentityRosterCard-OcSz1PkK.js +1 -0
  281. package/dist/ui/assets/AiProfilesModule-ByhYW5Xi.js +1 -0
  282. package/dist/ui/assets/{AnnotatedAttachmentWorkspace-B68Wg-RV.js → AnnotatedAttachmentWorkspace-BTM6nIg_.js} +1 -1
  283. package/dist/ui/assets/{AssetTraySortControl-C8Rztyal.js → AssetTraySortControl-DabEG8L4.js} +1 -1
  284. package/dist/ui/assets/{ContextAttachmentManager-Cj3c7X9y.js → ContextAttachmentManager-Coa8yVGM.js} +1 -1
  285. package/dist/ui/assets/{DocumentWorkspace-B5uvzems.js → DocumentWorkspace-BB0qhdix.js} +1 -1
  286. package/dist/ui/assets/{EntityActivityTimeline-BVFvCB5R.js → EntityActivityTimeline-CZ8x4UJE.js} +1 -1
  287. package/dist/ui/assets/{PlanningModule-B5DWQOGz.js → PlanningModule-pRPjR7v5.js} +1 -1
  288. package/dist/ui/assets/{PlansPage-AY4cGWco.js → PlansPage-D86pZSSl.js} +1 -1
  289. package/dist/ui/assets/{TaskContextUpload-DZxTVesW.js → TaskContextUpload-BVIkU9yT.js} +1 -1
  290. package/dist/ui/assets/TaskSettings-Cv1mNhv_.js +12 -0
  291. package/dist/ui/assets/TaskforceAgentsModule-b-8R25cJ.css +1 -0
  292. package/dist/ui/assets/TaskforceAgentsModule-gmH-PD2q.js +24 -0
  293. package/dist/ui/assets/{WorkflowManagerModule-DEr5di_r.js → WorkflowManagerModule-DbfnHJ-f.js} +1 -1
  294. package/dist/ui/assets/index-BZ-hdZSk.css +1 -0
  295. package/dist/ui/assets/index-CTsDBaef.js +7 -0
  296. package/dist/ui/assets/{vendor-icons-D9Lpw-j4.js → vendor-icons-Bsq-mcEn.js} +1 -1
  297. package/dist/ui/branding/logos/letterhead_dark.png +0 -0
  298. package/dist/ui/branding/logos/letterhead_light.png +0 -0
  299. package/dist/ui/branding/logos/signature_dark.png +0 -0
  300. package/dist/ui/branding/logos/signature_light.png +0 -0
  301. package/dist/ui/index.html +3 -3
  302. package/dist/utils/aiProfileDefaultLogo.js +16 -48
  303. package/dist/utils/httpSetCookie.d.ts +1 -0
  304. package/dist/utils/httpSetCookie.js +4 -1
  305. package/dist/utils/localRuntimeUrl.d.ts +1 -0
  306. package/dist/utils/localRuntimeUrl.js +14 -0
  307. package/dist/utils/productLogoRegistry.d.ts +2 -0
  308. package/dist/utils/productLogoRegistry.js +36 -0
  309. package/dist/utils/syncStatusPresentation.d.ts +4 -0
  310. package/dist/utils/syncStatusPresentation.js +17 -0
  311. package/dist/utils/taskEvents.d.ts +2 -0
  312. package/dist/utils/workspaceSyncPresentation.d.ts +1 -1
  313. package/dist/utils/workspaceSyncPresentation.js +23 -17
  314. package/package.json +22 -4
  315. package/dist/ui/assets/AiIdentityRosterCard-BZM4aQnM.js +0 -1
  316. package/dist/ui/assets/AiProfilesModule-BbAEWtHH.js +0 -1
  317. package/dist/ui/assets/TaskSettings-BeWAuyZj.js +0 -12
  318. package/dist/ui/assets/TaskforceAgentsModule-BifCYtjR.js +0 -21
  319. package/dist/ui/assets/TaskforceAgentsModule-D6IC0S7Q.css +0 -1
  320. package/dist/ui/assets/index-I5zhdtgt.js +0 -7
  321. package/dist/ui/assets/index-VRFsx3wz.css +0 -1
@@ -0,0 +1,24 @@
1
+ import{j as e,r as a,a as qa}from"./vendor-react-CKJs5o3c.js";import{f as gt,B as ss,C as ns,E as lt,t as r,F as si,w as Mn,G as ya,H as ni,J as ba,K as xa,L as ja,N as ka,O as Wt,Q as ai,S as qs,U as Sa,V as hs,W as ri,M as ii,X as oi,Y as Va,Z as li,_ as ci,$ as di,a0 as Vs,a1 as Ca}from"./index-CTsDBaef.js";import{a as Jt,A as ui,b as fi,w as Na,r as Aa}from"./AiIdentityRosterCard-OcSz1PkK.js";import{ay as vt,ba as tn,y as Cs,ao as mi,a0 as Wa,$ as pi,aJ as hi,aa as Dn,bb as gi,bc as ts,d as Lt,W as vi,bd as yi,q as bi,g as xi,be as ji,S as Bn,bf as ki,t as Pt,w as je,R as nn,a6 as On,u as Zt,X as yt,Z as st,bg as Si,Y as Ci,v as Ja,A as Ya,bh as Ws,ad as wa,ah as Qa,a2 as Xa,a7 as Za,ap as Ni,r as Ai,J as Xt,ak as wi,O as _a,bi as _i}from"./vendor-icons-Bsq-mcEn.js";import"./vendor-markdown-_lhNCyq-.js";import"./vendor-dnd-CJ-AjP-Y.js";import"./vendor-router-AqJMU8Lz.js";const An=1,Pe={name:80,shortDescription:240,purpose:2e3,listItem:1e3,listItems:24,workingGuidance:6e3,reference:200,promptContent:12e3};function Ta(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Ie(t,n,i,o){t.push({code:n,path:i,message:o})}function Ra(t,n,i,o){const f=new Set(n);Object.keys(t).forEach(w=>{f.has(w)||Ie(o,"unknown_field",i?`${i}.${w}`:w,"This field is not part of Agent Role v1.")})}function wn(t,n,i,o){if(typeof t!="string")return Ie(o,"required_string",n,"A string value is required."),"";const f=t.trim();return f?f.length>i&&Ie(o,"string_too_long",n,`Must be ${i} characters or less.`):Ie(o,"required_string",n,"A non-empty value is required."),f}function Ti(t,n,i,o){if(t==null||t==="")return;if(typeof t!="string"){Ie(o,"invalid_string",n,"Must be a string when provided.");return}const f=t.trim();if(f)return f.length>i&&Ie(o,"string_too_long",n,`Must be ${i} characters or less.`),f}function Js(t,n,i,o){if(!Array.isArray(t))return Ie(o,"invalid_list",n,"Must be an array of strings."),[];i.required&&t.length===0&&Ie(o,"required_list",n,"Provide at least one item."),i.maxItems&&t.length>i.maxItems&&Ie(o,"too_many_items",n,`Provide no more than ${i.maxItems} items.`);const f=new Set,w=[];return t.forEach((N,x)=>{if(typeof N!="string"){Ie(o,"invalid_string",`${n}[${x}]`,"Must be a string.");return}const k=N.trim();if(!k){Ie(o,"empty_list_item",`${n}[${x}]`,"List items cannot be blank.");return}k.length>i.maxItemLength&&Ie(o,"string_too_long",`${n}[${x}]`,`Must be ${i.maxItemLength} characters or less.`),!f.has(k)&&(f.add(k),w.push(k))}),w}function er(t){const n=[];if(!Ta(t))return{definition:null,issues:[{code:"invalid_definition",path:"",message:"Agent Role definition must be an object."}]};Ra(t,["schemaVersion","name","shortDescription","purpose","responsibilities","expectedOutputs","workingGuidance","recommendations"],"",n),t.schemaVersion!==An&&Ie(n,"unsupported_schema_version","schemaVersion",`Agent Role schemaVersion must be ${An}.`);const i=wn(t.name,"name",Pe.name,n),o=wn(t.shortDescription,"shortDescription",Pe.shortDescription,n),f=wn(t.purpose,"purpose",Pe.purpose,n),w=Js(t.responsibilities,"responsibilities",{required:!0,maxItems:Pe.listItems,maxItemLength:Pe.listItem},n),N=Js(t.expectedOutputs,"expectedOutputs",{required:!0,maxItems:Pe.listItems,maxItemLength:Pe.listItem},n),x=Ti(t.workingGuidance,"workingGuidance",Pe.workingGuidance,n),k=Ta(t.recommendations)?t.recommendations:null;k?Ra(k,["skillRefs","capabilityGroups"],"recommendations",n):Ie(n,"invalid_recommendations","recommendations","Recommendations must be an object.");const $=Js(k?.skillRefs??[],"recommendations.skillRefs",{maxItems:Pe.listItems,maxItemLength:Pe.reference},n),L=Js(k?.capabilityGroups??[],"recommendations.capabilityGroups",{maxItems:Pe.listItems,maxItemLength:Pe.reference},n),K={schemaVersion:An,name:i,shortDescription:o,purpose:f,responsibilities:w,expectedOutputs:N,...x?{workingGuidance:x}:{},recommendations:{skillRefs:$,capabilityGroups:L}};return n.length===0&&tr(K).length>Pe.promptContent&&Ie(n,"compiled_prompt_too_long","",`Compiled Role prompt content must be ${Pe.promptContent} characters or less.`),{definition:n.length===0?K:null,issues:n}}class Ri extends Error{constructor(n){super(n[0]?.message||"Agent Role definition is invalid."),this.issues=n,this.name="AgentRoleDefinitionValidationError"}code="AGENT_ROLE_DEFINITION_INVALID";statusCode=400}function Ei(t){const n=er(t);if(!n.definition)throw new Ri(n.issues);return n.definition}function Ea(t){return t.map(n=>`- ${n}`).join(`
2
+ `)}function tr(t){return[`Role: ${t.name}`,`Purpose and scope:
3
+ ${t.purpose}`,`Responsibilities:
4
+ ${Ea(t.responsibilities)}`,`Expected outputs:
5
+ ${Ea(t.expectedOutputs)}`,t.workingGuidance?`Role-specific working guidance:
6
+ ${t.workingGuidance}`:""].filter(Boolean).join(`
7
+
8
+ `)}function Ii(t){return tr(Ei(t))}const $i="_toolAccess_2stgb_1",Li="_skillSelector_2stgb_2",Pi="_effectiveSummary_2stgb_3",Mi="_sectionHeader_2stgb_13",Di="_workspaceHeader_2stgb_14",Oi="_titleLine_2stgb_32",zi="_moduleGrid_2stgb_36",Ui="_moduleOption_2stgb_42",Gi="_unavailableCapability_2stgb_43",Bi="_moduleOptionSelected_2stgb_66",Hi="_moduleIcon_2stgb_76",Fi="_selectedSkillIcon_2stgb_77",Ki="_provenanceIcon_2stgb_78",qi="_moduleCopy_2stgb_91",Vi="_futureGroups_2stgb_110",Wi="_unknownNotice_2stgb_122",Ji="_disabledExplanation_2stgb_123",Yi="_catalogError_2stgb_147",Qi="_selectedSkills_2stgb_160",Xi="_skillSearch_2stgb_168",Zi="_skillResults_2stgb_188",eo="_emptySelection_2stgb_266",to="_provenanceGrid_2stgb_275",so="_unavailableProvenance_2stgb_312",no="_previewCaveat_2stgb_316",ao="_librarySummary_2stgb_323",ro="_workspacePanel_2stgb_346",io="_futureAction_2stgb_356",oo="_workspaceTitleIcon_2stgb_370",lo="_previewCardIcon_2stgb_371",co="_relationshipFlow_2stgb_389",uo="_previewCards_2stgb_420",fo="_previewCard_2stgb_371",mo="_previewCardAvailable_2stgb_438",W={toolAccess:$i,skillSelector:Li,effectiveSummary:Pi,sectionHeader:Mi,workspaceHeader:Di,titleLine:Oi,moduleGrid:zi,moduleOption:Ui,unavailableCapability:Gi,moduleOptionSelected:Bi,moduleIcon:Hi,selectedSkillIcon:Fi,provenanceIcon:Ki,moduleCopy:qi,futureGroups:Vi,unknownNotice:Wi,disabledExplanation:Ji,catalogError:Yi,selectedSkills:Qi,skillSearch:Xi,skillResults:Zi,emptySelection:eo,provenanceGrid:to,unavailableProvenance:so,previewCaveat:no,librarySummary:ao,workspacePanel:ro,futureAction:io,workspaceTitleIcon:oo,previewCardIcon:lo,relationshipFlow:co,previewCards:uo,previewCard:fo,previewCardAvailable:mo},Hn=[{key:"tasks",label:"Tasks and schedule",description:"Read and update tasks, checklists, task workflows, and schedule context.",icon:Cs},{key:"planning",label:"Initiatives and workstreams",description:"Read planning structure and add planning comments.",icon:mi},{key:"documents",label:"Documents",description:"Find and read Taskforce documents and their review context.",icon:Wa},{key:"images",label:"Image Notes",description:"Find images and inspect annotation sessions.",icon:pi},{key:"workspace",label:"Workspace information",description:"Read workspace configuration, people, and managed Agent identity.",icon:hi}],po=Hn.map(t=>t.key);function Fn({selectedKeys:t,onChange:n,disabled:i=!1,mode:o="active",title:f="Tool Access",description:w,showFutureTools:N=!0,requireOne:x=!1,hasCustomOverrides:k=!1}){const $=new Set(t),L=new Set(po),K=t.filter(_=>!L.has(_)),I=o==="active"?"Available now":o==="requirement"?"Requirement preview":"Inheritance preview",R=o==="active"?"tf-chip-success":"tf-chip-warning",S=(_,H)=>{if(!n||i)return;const Y=H?[...t.filter(ie=>ie!==_),_]:t.filter(ie=>ie!==_),z=Y.filter(ie=>L.has(ie)).length;x&&z===0||n(Y)};return e.jsxs("section",{className:W.toolAccess,"aria-label":f,children:[e.jsxs("div",{className:W.sectionHeader,children:[e.jsxs("div",{children:[e.jsx("h3",{className:"tf-heading-section",children:f}),e.jsx("p",{className:"tf-text-helper",children:w||"Choose which Taskforce modules this Agent can use. Fewer enabled tools reduce runtime tool context."})]}),e.jsx("span",{className:R,children:I})]}),e.jsx("div",{className:W.moduleGrid,children:Hn.map(_=>{const H=_.icon,Y=$.has(_.key);return e.jsxs("label",{className:`${W.moduleOption} ${Y?W.moduleOptionSelected:""}`.trim(),children:[e.jsx("input",{type:"checkbox",checked:Y,disabled:i||!n,onChange:z=>S(_.key,z.target.checked)}),e.jsx("span",{className:W.moduleIcon,"aria-hidden":"true",children:e.jsx(H,{size:16})}),e.jsxs("span",{className:W.moduleCopy,children:[e.jsx("strong",{children:_.label}),e.jsx("small",{children:_.description})]})]},_.key)})}),k?e.jsxs("div",{className:W.unknownNotice,role:"status",children:[e.jsx(Dn,{size:14}),e.jsx("span",{children:"Custom per-tool overrides are active. Change any module selection to replace them with the module policy shown here."})]}):null,K.length>0?e.jsxs("div",{className:W.unknownNotice,role:"status",children:[e.jsx(Dn,{size:14}),e.jsxs("span",{children:["Preserved legacy keys: ",K.join(", "),". They are not available in the current managed Tool Access catalog."]}),n&&!i?e.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>n(t.filter(_=>L.has(_))),children:"Remove unsupported keys"}):null]}):null,N?e.jsxs("div",{className:W.futureGroups,children:[e.jsx(Ia,{icon:e.jsx(vt,{size:16}),title:"Connected tools",description:"Workspace-approved APIs and external MCP tools will appear here.",status:"Connections not available yet"}),e.jsx(Ia,{icon:e.jsx(gi,{size:16}),title:"Code Workspace",description:"Repository read, edit, Git, and publication access will be configured separately.",status:"Code Workspace not configured"})]}):null]})}function ho({skills:t,selectedIds:n,onChange:i,disabled:o=!1,loading:f=!1,error:w="",onRetry:N}){const[x,k]=a.useState(""),$=a.useRef(null),L=new Set(n),K=x.trim().toLowerCase(),I=t.filter(S=>S.lifecycleStatus==="active"&&!L.has(S.id)).filter(S=>!K||S.name.toLowerCase().includes(K)||S.description.toLowerCase().includes(K)).slice(0,8),R=new Map(t.map(S=>[S.id,S]));return e.jsxs("section",{className:W.skillSelector,"aria-label":"Included Skills",children:[e.jsxs("div",{className:W.sectionHeader,children:[e.jsxs("div",{children:[e.jsx("h3",{className:"tf-heading-section",children:"Included Skills"}),e.jsx("p",{className:"tf-text-helper",children:"Select Skills by name. They are saved with this Role now; automatic Agent inheritance is preview-only."})]}),e.jsx("span",{className:"tf-chip-warning",children:"Inheritance preview"})]}),e.jsxs("label",{className:"tf-field-stack",children:[e.jsx("span",{className:"tf-field-label",children:"Find a Skill"}),e.jsxs("span",{className:W.skillSearch,children:[e.jsx(Bn,{size:15,"aria-hidden":"true"}),e.jsx("input",{ref:$,type:"search",className:"tf-field-shell","aria-label":"Find a Skill to include",placeholder:f?"Loading Skills…":"Search by name or description",value:x,disabled:o||f,onChange:S=>k(S.target.value)})]})]}),w?e.jsxs("div",{className:W.catalogError,role:"alert",children:[e.jsx("span",{children:w}),N?e.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:N,children:"Retry"}):null]}):!f&&I.length>0?e.jsx("div",{className:W.skillResults,"aria-label":"Available Skills",children:I.map(S=>e.jsxs("button",{type:"button",disabled:o,onClick:()=>{i([...n,S.id]),k(""),$.current?.focus()},children:[e.jsxs("span",{children:[e.jsx("strong",{children:S.name}),e.jsx("small",{children:S.description||"No description"})]}),e.jsx("span",{className:"tf-chip-neutral",children:"Add"})]},S.id))}):f?null:e.jsx("p",{className:W.emptySelection,children:t.some(S=>S.lifecycleStatus==="active"&&!L.has(S.id))?"No Skills match this search.":"No additional Skills available."}),n.length>0?e.jsx("ul",{className:W.selectedSkills,children:n.map(S=>{const _=R.get(S);return e.jsxs("li",{children:[e.jsx("span",{className:W.selectedSkillIcon,"aria-hidden":"true",children:e.jsx(Lt,{size:15})}),e.jsxs("span",{children:[e.jsx("strong",{children:_?.name||"Missing Skill"}),e.jsx("small",{children:_?.description||S})]}),e.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",disabled:o,onClick:()=>{i(n.filter(H=>H!==S)),$.current?.focus()},children:"Remove"})]},S)})}):e.jsx("p",{className:W.emptySelection,children:"No Skills included in this Role."})]})}function go({hasRole:t,directSkillCount:n,toolKeys:i}){const o=Hn.filter(f=>i.includes(f.key)).map(f=>f.label);return e.jsxs("section",{className:W.effectiveSummary,"aria-label":"Effective configuration preview",children:[e.jsxs("div",{className:W.sectionHeader,children:[e.jsxs("div",{children:[e.jsx("h3",{className:"tf-heading-section",children:"Effective configuration"}),e.jsx("p",{className:"tf-text-helper",children:"A preview of where this Agent’s behavior and access come from."})]}),e.jsx("span",{className:"tf-chip-warning",children:"Partial preview"})]}),e.jsxs("div",{className:W.provenanceGrid,children:[e.jsxs("div",{children:[e.jsx("span",{className:W.provenanceIcon,children:e.jsx(ts,{size:15})}),e.jsxs("span",{children:[e.jsx("small",{children:"From Role"}),e.jsx("strong",{children:t?"Role guidance selected":"No Role selected"})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:W.provenanceIcon,children:e.jsx(Lt,{size:15})}),e.jsxs("span",{children:[e.jsx("small",{children:"Added to Agent"}),e.jsxs("strong",{children:[n," direct ",n===1?"Skill":"Skills"]})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:W.provenanceIcon,children:e.jsx(vi,{size:15})}),e.jsxs("span",{children:[e.jsx("small",{children:"Runtime Tool Access"}),e.jsx("strong",{children:o.length>0?o.join(", "):"No modules selected"})]})]}),e.jsxs("div",{className:W.unavailableProvenance,children:[e.jsx("span",{className:W.provenanceIcon,children:e.jsx(yi,{size:15})}),e.jsxs("span",{children:[e.jsx("small",{children:"Resources"}),e.jsx("strong",{children:"Not available yet"})]})]})]}),e.jsx("p",{className:W.previewCaveat,children:"Role guidance resolves today. Role-included Skills, Role Tool Access, Connections, and Resources are shown for experience review but are not yet inherited at runtime."})]})}function vo({kind:t}){return e.jsxs("div",{className:W.librarySummary,children:[t==="connections"?e.jsx(vt,{size:20}):e.jsx(tn,{size:20}),e.jsx("strong",{children:t==="connections"?"No Connections configured":"No Resource Collections yet"}),e.jsx("span",{children:t==="connections"?"Connections will make approved external tools and data providers available to Roles and Agents.":"Collections will tell Roles and Agents where to look for trusted information."}),e.jsx("span",{className:"tf-chip-neutral",children:"Preview only"})]})}function yo({kind:t}){const n=t==="connections";return e.jsxs("section",{className:W.workspacePanel,"aria-labelledby":`${t}-preview-title`,children:[e.jsxs("header",{className:W.workspaceHeader,children:[e.jsx("div",{className:W.workspaceTitleIcon,"aria-hidden":"true",children:n?e.jsx(vt,{size:20}):e.jsx(tn,{size:20})}),e.jsxs("div",{children:[e.jsxs("div",{className:W.titleLine,children:[e.jsx("h2",{id:`${t}-preview-title`,className:"tf-heading-page",children:n?"Connections":"Resources"}),e.jsx("span",{className:"tf-chip-warning",children:"Not available yet"})]}),e.jsx("p",{className:"tf-text-secondary",children:n?"Secure workspace integrations make external tools and provider data available for explicit Role and Agent access.":"Resource Collections define trusted places Agents can search without loading full source content into every prompt."})]}),e.jsxs("button",{type:"button",className:`tf-button-primary ${W.futureAction}`,disabled:!0,children:[n?e.jsx(bi,{size:15}):e.jsx(xi,{size:15}),n?"Add Connection":"New Collection"]})]}),e.jsxs("div",{className:W.relationshipFlow,"aria-label":"Configuration relationship",children:[e.jsx("span",{children:"Workspace"}),e.jsx("strong",{children:n?"Connection":"Resource Collection"}),e.jsx("span",{children:"Role"}),e.jsx("span",{children:"Agent"}),e.jsx("span",{children:"Runtime"})]}),e.jsx("div",{className:W.previewCards,children:n?e.jsxs(e.Fragment,{children:[e.jsx(Yt,{icon:e.jsx(Dn,{size:18}),title:"Taskforce managed tools",description:"Built-in modules use Taskforce-managed credentials and the current allowlisted runtime.",status:"Available now",available:!0}),e.jsx(Yt,{icon:e.jsx(tn,{size:18}),title:"Real estate data provider",description:"Example: search listings, retrieve property details, and read market statistics.",status:"Connection required"}),e.jsx(Yt,{icon:e.jsx(vt,{size:18}),title:"External MCP server",description:"Approved server tools will be imported individually with scopes and audit controls.",status:"Not available yet"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Yt,{icon:e.jsx(Wa,{size:18}),title:"Taskforce documents",description:"Curate existing workspace documents into a reusable source collection.",status:"Collection manager required"}),e.jsx(Yt,{icon:e.jsx(ji,{size:18}),title:"News sources",description:"Example: trusted publications, feeds, topics, regions, and recency rules.",status:"Provider required"}),e.jsx(Yt,{icon:e.jsx(Bn,{size:18}),title:"Web and data sources",description:"Allowed domains and connected datasets will be searched on demand.",status:"Not available yet"})]})}),e.jsxs("div",{className:W.disabledExplanation,children:[e.jsx(ki,{size:16}),e.jsxs("div",{children:[e.jsx("strong",{children:"Why this is disabled"}),e.jsx("span",{children:n?"Credential storage, scopes, connection health, and external tool allowlisting are not implemented.":"Collection persistence, authorization, retrieval, and marketplace portability are not implemented."})]})]})]})}function Ia({icon:t,title:n,description:i,status:o}){return e.jsxs("div",{className:W.unavailableCapability,"aria-disabled":"true",children:[e.jsx("span",{className:W.moduleIcon,"aria-hidden":"true",children:t}),e.jsxs("span",{className:W.moduleCopy,children:[e.jsx("strong",{children:n}),e.jsx("small",{children:i})]}),e.jsx("span",{className:"tf-chip-neutral",children:o})]})}function Yt({icon:t,title:n,description:i,status:o,available:f=!1}){return e.jsxs("article",{className:`${W.previewCard} ${f?W.previewCardAvailable:""}`.trim(),children:[e.jsx("div",{className:W.previewCardIcon,children:t}),e.jsxs("div",{children:[e.jsx("h3",{className:"tf-heading-card",children:n}),e.jsx("p",{className:"tf-text-secondary",children:i})]}),e.jsx("span",{className:f?"tf-chip-success":"tf-chip-neutral",children:o})]})}const bo="_root_3ejva_1",xo="_rootExternalLibrary_3ejva_11",jo="_library_3ejva_15",ko="_libraryExternal_3ejva_26",So="_libraryHeader_3ejva_39",Co="_search_3ejva_50",No="_retiredToggle_3ejva_78",Ao="_libraryList_3ejva_86",wo="_libraryState_3ejva_95",_o="_libraryError_3ejva_107",To="_libraryStateIcon_3ejva_112",Ro="_libraryCard_3ejva_117",Eo="_libraryCardSelected_3ejva_139",Io="_libraryCardIcon_3ejva_145",$o="_libraryCardLogo_3ejva_156",Lo="_libraryCardBody_3ejva_168",Po="_editor_3ejva_192",Mo="_editorHeader_3ejva_199",Do="_editorTitle_3ejva_213",Oo="_editorTitleLine_3ejva_225",zo="_headerActions_3ejva_240",Uo="_feedbackError_3ejva_247",Go="_feedbackSuccess_3ejva_248",Bo="_confirmation_3ejva_249",Ho="_fieldError_3ejva_275",Fo="_empty_3ejva_300",Ko="_emptyIcon_3ejva_310",qo="_editorGrid_3ejva_321",Vo="_formColumn_3ejva_331",Wo="_previewColumn_3ejva_337",Jo="_previewHeader_3ejva_348",Yo="_previewNote_3ejva_359",Qo="_preview_3ejva_337",Xo="_previewEmpty_3ejva_380",Zo="_metrics_3ejva_394",el="_lifecycleAction_3ejva_412",tl="_history_3ejva_422",sl="_spinner_3ejva_477",nl="_visuallyHidden_3ejva_481",T={root:bo,rootExternalLibrary:xo,library:jo,libraryExternal:ko,libraryHeader:So,search:Co,retiredToggle:No,libraryList:Ao,libraryState:wo,libraryError:_o,libraryStateIcon:To,libraryCard:Ro,libraryCardSelected:Eo,libraryCardIcon:Io,libraryCardLogo:$o,libraryCardBody:Lo,editor:Po,editorHeader:Mo,editorTitle:Do,editorTitleLine:Oo,headerActions:zo,feedbackError:Uo,feedbackSuccess:Go,confirmation:Bo,fieldError:Ho,empty:Fo,emptyIcon:Ko,editorGrid:qo,formColumn:Vo,previewColumn:Wo,previewHeader:Jo,previewNote:Yo,preview:Qo,previewEmpty:Xo,metrics:Zo,lifecycleAction:el,history:tl,spinner:sl,visuallyHidden:nl};function sr({singularLabel:t,pluralLabel:n,description:i,icon:o,items:f,selectedId:w,searchValue:N,onSearchChange:x,showRetired:k,onShowRetiredChange:$,loading:L,error:K,emptyMessage:I,onRetry:R,onCreate:S,onSelect:_,libraryPortalTarget:H}){const Y=e.jsxs(e.Fragment,{children:[H?e.jsxs("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:S,children:[e.jsx(Pt,{size:14})," New ",t]}):e.jsxs("div",{className:T.libraryHeader,children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"tf-heading-card",children:["Available ",n]}),e.jsx("p",{className:"tf-text-helper",children:i})]}),e.jsxs("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:S,children:[e.jsx(Pt,{size:14})," New"]})]}),e.jsxs("label",{className:T.search,children:[e.jsx(Bn,{size:14,"aria-hidden":"true"}),e.jsxs("span",{className:T.visuallyHidden,children:["Search ",n]}),e.jsx("input",{"aria-label":`Search ${n}`,value:N,onChange:z=>x(z.target.value),placeholder:`Search ${n.toLowerCase()}`})]}),e.jsxs("label",{className:T.retiredToggle,children:[e.jsx("input",{type:"checkbox",checked:k,onChange:z=>$(z.target.checked)}),"Show retired"]}),e.jsx("div",{className:T.libraryList,"aria-busy":L,children:L?e.jsxs("div",{className:T.libraryState,children:[e.jsx(je,{size:16,className:T.spinner,"aria-hidden":"true"}),"Loading ",n,"…"]}):K?e.jsxs("div",{className:`${T.libraryState} ${T.libraryError}`,role:"alert",children:[e.jsx("span",{children:K}),R?e.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:R,children:"Retry"}):null]}):f.length===0?e.jsxs("div",{className:T.libraryState,children:[e.jsx("span",{className:T.libraryStateIcon,"aria-hidden":"true",children:o}),I]}):f.map(z=>{const ie=z.id===w;return e.jsxs("button",{type:"button",className:`${T.libraryCard} ${ie?T.libraryCardSelected:""}`.trim(),onClick:()=>_(z.id),"aria-pressed":ie,children:[e.jsx("span",{className:T.libraryCardIcon,"aria-hidden":"true",children:o}),e.jsxs("span",{className:T.libraryCardBody,children:[e.jsx("strong",{children:z.name}),e.jsx("span",{children:z.description})]}),z.lifecycleStatus==="retired"?e.jsx("span",{className:"tf-chip-warning",children:"Retired"}):null]},z.id)})})]});return H?qa.createPortal(e.jsx("div",{className:`${T.library} ${T.libraryExternal}`,"aria-label":`${t} list`,children:Y}),H):e.jsx("aside",{className:T.library,"aria-label":`${t} Library`,children:Y})}function nr({icon:t,title:n,description:i,revision:o,retired:f=!1,showActions:w,dirty:N,saving:x,onReset:k,onSave:$}){return e.jsxs("header",{className:T.editorHeader,children:[e.jsxs("div",{className:T.editorTitle,children:[e.jsx("span",{"aria-hidden":"true",children:t}),e.jsxs("div",{children:[e.jsxs("div",{className:T.editorTitleLine,children:[e.jsx("h2",{className:"tf-heading-page",children:n}),f?e.jsx("span",{className:"tf-chip-warning",children:"Retired"}):null,!f&&o?e.jsxs("span",{className:"tf-chip-accent",children:["Revision ",o]}):null]}),e.jsx("p",{className:"tf-text-secondary",children:i})]})]}),w?e.jsxs("div",{className:T.headerActions,children:[e.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",disabled:!N||x,onClick:k,children:[e.jsx(nn,{size:14})," Reset"]}),e.jsxs("button",{type:"button",className:"tf-button-primary tf-button-compact",disabled:!N||x||f,onClick:$,children:[x?e.jsx(je,{size:14,className:T.spinner}):e.jsx(On,{size:14}),"Save"]})]}):null]})}function zn({type:t,message:n}){return e.jsxs("div",{className:t==="error"?T.feedbackError:T.feedbackSuccess,role:t==="error"?"alert":"status",children:[t==="error"?e.jsx(st,{size:15}):e.jsx(Cs,{size:15}),e.jsx("span",{children:n})]})}function ar(t,n){return new Map(n?t.map(i=>[i.path,i.message]):[])}function rr(t,n){const i=t.find(o=>n[o.path])?.path;i&&window.requestAnimationFrame(()=>n[i]?.focus())}function nt({id:t,message:n}){return n?e.jsx("small",{id:t,className:T.fieldError,children:n}):null}function ir({icon:t,title:n,description:i,actionLabel:o,onCreate:f}){return e.jsxs("div",{className:T.empty,children:[e.jsx("span",{className:T.emptyIcon,"aria-hidden":"true",children:t}),e.jsx("h3",{className:"tf-empty-title",children:n}),e.jsx("p",{className:"tf-empty-copy",children:i}),e.jsxs("button",{type:"button",className:"tf-button-primary",onClick:f,children:[e.jsx(Pt,{size:15})," ",o]})]})}function or({title:t,message:n,entityLabel:i,saving:o,onConfirm:f,onCancel:w}){const N=a.useId(),x=a.useId(),k=a.useRef(null);return a.useEffect(()=>{const $=document.activeElement instanceof HTMLElement?document.activeElement:null;return k.current?.focus(),()=>{$?.isConnected&&$.focus()}},[]),e.jsxs("div",{className:T.confirmation,role:"alertdialog","aria-modal":"false","aria-labelledby":N,"aria-describedby":x,onKeyDown:$=>{$.key!=="Escape"||o||($.preventDefault(),w())},children:[e.jsxs("div",{children:[e.jsx("strong",{id:N,children:t}),e.jsx("span",{id:x,children:n})]}),e.jsxs("button",{type:"button",className:"tf-button-destructive tf-button-compact",disabled:o,onClick:f,"aria-label":`Confirm ${i} retirement`,children:[e.jsx(Zt,{size:14})," Retire ",i]}),e.jsxs("button",{ref:k,type:"button",className:"tf-button-ghost tf-button-compact",disabled:o,onClick:w,"aria-label":`Cancel ${i} retirement`,children:[e.jsx(yt,{size:14})," Cancel"]})]})}function lr({entityLabel:t,note:n,meta:i,children:o,metrics:f=[],revisions:w=[],lifecycleStatus:N,saving:x=!1,retireDescription:k,restoreDescription:$,onRetire:L,onRestore:K}){const I=!!(N&&k&&$&&L&&K);return e.jsxs("aside",{className:T.previewColumn,"aria-label":`Compiled ${t} preview`,children:[e.jsxs("div",{className:T.previewHeader,children:[e.jsxs("div",{children:[e.jsx("span",{className:"tf-label-micro",children:"Runtime preview"}),e.jsx("h3",{className:"tf-heading-section",children:"Compiled runtime preview"})]}),i]}),e.jsx("p",{className:T.previewNote,children:n}),o,f.length>0?e.jsx("div",{className:T.metrics,children:f.map(R=>e.jsxs("div",{children:[e.jsx("span",{children:R.label}),e.jsx("strong",{children:R.value})]},R.label))}):null,w.length>0?e.jsxs("details",{className:T.history,children:[e.jsxs("summary",{children:[e.jsx(Si,{size:12})," Revision history"]}),e.jsx("ol",{children:w.map(R=>e.jsxs("li",{children:[e.jsxs("strong",{children:["Revision ",R.revision]}),e.jsx("span",{children:new Date(R.createdAt).toLocaleString()}),e.jsx("code",{children:R.contentHash.slice(0,12)})]},R.revision))})]}):null,I?e.jsxs("div",{className:T.lifecycleAction,children:[e.jsxs("div",{children:[e.jsx("strong",{children:N==="retired"?`Restore ${t}`:`Retire ${t}`}),e.jsx("span",{children:N==="retired"?$:k})]}),N==="retired"?e.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",disabled:x,onClick:K,children:[e.jsx(nn,{size:14})," Restore"]}):e.jsxs("button",{type:"button",className:"tf-button-destructive tf-button-compact",disabled:x,onClick:L,children:[e.jsx(Ci,{size:14})," Retire"]})]}):null]})}const al="_formSection_dyv9a_1",rl="_sectionHeader_dyv9a_9",il="_fieldGrid_dyv9a_13",ol="_configurationPreview_dyv9a_27",ll="_resourcesPreview_dyv9a_33",cl="_previewCode_dyv9a_49",ot={formSection:al,sectionHeader:rl,fieldGrid:il,configurationPreview:ol,resourcesPreview:ll,previewCode:cl},gs={name:"",shortDescription:"",purpose:"",responsibilities:"",expectedOutputs:"",workingGuidance:"",skillRefs:"",capabilityGroups:""};function es(t){return t.split(`
9
+ `).map(n=>n.trim()).filter(Boolean)}function dl(t){return{schemaVersion:1,name:t.name,shortDescription:t.shortDescription,purpose:t.purpose,responsibilities:es(t.responsibilities),expectedOutputs:es(t.expectedOutputs),...t.workingGuidance.trim()?{workingGuidance:t.workingGuidance}:{},recommendations:{skillRefs:es(t.skillRefs),capabilityGroups:es(t.capabilityGroups)}}}function vs(t){return{name:t.definition.name,shortDescription:t.definition.shortDescription,purpose:t.definition.purpose,responsibilities:t.definition.responsibilities.join(`
10
+ `),expectedOutputs:t.definition.expectedOutputs.join(`
11
+ `),workingGuidance:t.definition.workingGuidance||"",skillRefs:t.definition.recommendations.skillRefs.join(`
12
+ `),capabilityGroups:t.definition.recommendations.capabilityGroups.join(`
13
+ `)}}async function Ys(t){return t.json().catch(()=>({}))}function ul({workspaceId:t,libraryPortalTarget:n}){const[i,o]=a.useState([]),[f,w]=a.useState([]),[N,x]=a.useState(!0),[k,$]=a.useState(""),[L,K]=a.useState(null),[I,R]=a.useState(!1),[S,_]=a.useState(null),[H,Y]=a.useState(gs),[z,ie]=a.useState(""),[ve,Se]=a.useState(!1),[Ce,U]=a.useState(!0),[te,p]=a.useState(!1),[M,E]=a.useState(null),[ae,G]=a.useState(null),[Ne,oe]=a.useState(!1),[O,he]=a.useState(!1),ee=a.useRef({}),ge=a.useRef(0),A=i.find(v=>v.id===L)||null,ye=A?vs(A):gs,_e=JSON.stringify(H)!==JSON.stringify(ye),Ae=a.useCallback(v=>{K(v.id),R(!1),_(v.currentContentHash),Y(vs(v)),G(null),oe(!1),he(!1)},[]),le=a.useCallback(v=>{_e&&!window.confirm("Discard unsaved Role changes?")||Ae(v)},[Ae,_e]),Te=a.useCallback(async(v={})=>{U(!0),E(null);try{const F=await gt(`/api/taskforce/agent-roles?workspaceId=${encodeURIComponent(t)}&includeRetired=true`,{credentials:"include"}),Q=await Ys(F);if(!F.ok||Q.success===!1||!Array.isArray(Q.roles))throw new Error(String(Q.error||"Unable to load Agent Roles."));const Z=Q.roles,ke=i.find(me=>me.id===L)||null,fe=v.preserveDraft===!0&&(ke?JSON.stringify(H)!==JSON.stringify(vs(ke)):Object.values(H).some(me=>me.trim().length>0));o(Z);const $e=Z.find(me=>me.id===L)||Z.find(me=>me.lifecycleStatus==="active")||Z[0]||null;$e?(K($e.id),fe?G({type:"error",message:"This Role changed during synchronization. Your unsaved edits were preserved; saving will require resolving the version conflict."}):(R(!1),_($e.currentContentHash),Y(vs($e)))):fe?K(null):(K(null),R(!1),_(null),Y(gs))}catch(F){E(String(F?.message||F||"Unable to load Agent Roles."))}finally{U(!1)}},[H,i,L,t]);a.useEffect(()=>{Te()},[t]);const He=a.useCallback(async()=>{const v=ge.current+1;ge.current=v,w([]),$(""),x(!0);try{const F=await gt(`/api/taskforce/agent-skills?workspaceId=${encodeURIComponent(t)}&includeRetired=true`,{credentials:"include"}),Q=await Ys(F);if(v!==ge.current)return;if(!F.ok||Q.success===!1||!Array.isArray(Q.skills))throw new Error(String(Q.error||"Unable to load the Skill catalog."));w(Q.skills.map(Z=>({id:String(Z.id),name:String(Z.definition?.name||"Unnamed Skill"),description:String(Z.definition?.shortDescription||""),lifecycleStatus:Z.lifecycleStatus==="retired"?"retired":"active"})))}catch(F){if(v!==ge.current)return;$(String(F?.message||"Unable to load the Skill catalog."))}finally{v===ge.current&&x(!1)}},[t]);a.useEffect(()=>(He(),()=>{ge.current+=1}),[He]),a.useEffect(()=>{const v=Q=>{const Z=Q.detail;(String(Z?.workspaceId||"").trim()||"default")!==t||Z?.reason!=="sync-apply"||Te({preserveDraft:!0})};window.addEventListener(ss,v);const F=Q=>{const Z=Q.detail;(String(Z?.workspaceId||"").trim()||"default")===t&&He()};return window.addEventListener(ns,F),()=>{window.removeEventListener(ss,v),window.removeEventListener(ns,F)}},[Te,He,t]);const bt=a.useMemo(()=>{const v=z.trim().toLowerCase();return i.filter(F=>!ve&&F.lifecycleStatus==="retired"?!1:v?[F.definition.name,F.definition.shortDescription,F.definition.purpose].some(Q=>Q.toLowerCase().includes(v)):!0)},[z,i,ve]),we=a.useMemo(()=>er(dl(H)),[H]),Oe=a.useMemo(()=>{if(!we.definition)return"";try{return Ii(we.definition)}catch{return""}},[we]),We=()=>{_e&&!window.confirm("Discard unsaved Role changes?")||(K(null),R(!0),_(null),Y(gs),G(null),oe(!1),he(!1))},ce=()=>{const v=A?vs(A):gs;Y(v),_(A?.currentContentHash||null),G(null),oe(!1),he(!1)},y=(v,F)=>{Y(Q=>({...Q,[v]:F})),G(null)},d=async()=>{if(!we.definition||te){he(!0),G({type:"error",message:we.issues[0]?.message||"Complete the required Role fields."}),rr(we.issues,ee.current);return}p(!0),G(null);try{const v=await gt(A?`/api/taskforce/agent-roles/${encodeURIComponent(A.id)}`:"/api/taskforce/agent-roles",{method:A?"PATCH":"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:t,definition:we.definition,...A?{expectedContentHash:S}:{}})}),F=await Ys(v);if(!v.ok||F.success===!1||!F.role)throw new Error(String(F.error||"Unable to save Agent Role."));const Q=F.role;o(Z=>Z.some(fe=>fe.id===Q.id)?Z.map(fe=>fe.id===Q.id?Q:fe):[...Z,Q]),Ae(Q),G({type:"success",message:`Saved ${Q.definition.name}.`}),lt({workspaceId:t,reason:"role-save"})}catch(v){G({type:"error",message:String(v?.message||v||"Unable to save Agent Role.")})}finally{p(!1)}},h=async v=>{if(!(!A||te)){p(!0),G(null);try{const F=await gt(`/api/taskforce/agent-roles/${encodeURIComponent(A.id)}/${v}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:t,...v==="retire"?{confirm:!0}:{}})}),Q=await Ys(F);if(!F.ok||Q.success===!1||!Q.role)throw new Error(String(Q.error||`Unable to ${v} Agent Role.`));const Z=Q.role;o(ke=>ke.map(fe=>fe.id===Z.id?Z:fe)),Ae(Z),v==="retire"&&Se(!0),G({type:"success",message:v==="retire"?`Retired ${Z.definition.name}.`:`Restored ${Z.definition.name}.`}),lt({workspaceId:t,reason:v==="retire"?"role-retire":"role-restore"})}catch(F){G({type:"error",message:String(F?.message||F||`Unable to ${v} Agent Role.`)})}finally{p(!1)}}},u=a.useMemo(()=>ar(we.issues,O),[we.issues,O]),D=(v,F,Q,Z,ke=v)=>{const fe=`role-field-${ke.replaceAll(".","-")}`,$e=u.get(ke);return e.jsxs("label",{className:"tf-field-stack",children:[e.jsx("span",{className:"tf-field-label",children:F}),e.jsx("small",{id:`${fe}-hint`,className:"tf-field-hint",children:Q}),e.jsx("textarea",{ref:me=>{ee.current[ke]=me||void 0},id:fe,className:"tf-field-shell","aria-label":F,"aria-describedby":`${fe}-hint${$e?` ${fe}-error`:""}`,"aria-errormessage":$e?`${fe}-error`:void 0,value:H[v],onChange:me=>y(v,me.target.value),rows:Z,disabled:A?.lifecycleStatus==="retired","aria-invalid":!!$e}),e.jsx(nt,{id:`${fe}-error`,message:$e})]})},q=A?.usage.agentCount===0?"No active Agents currently reference this Role.":`${A?.usage.agentCount} active ${A?.usage.agentCount===1?"Agent references":"Agents reference"} this Role and will require repair before running.`;return e.jsxs("div",{className:`${T.root} ${n?T.rootExternalLibrary:""}`.trim(),children:[e.jsx(sr,{singularLabel:"Role",pluralLabel:"Roles",description:"Reusable professional profiles that define what an Agent does.",icon:e.jsx(ts,{size:15}),items:bt.map(v=>({id:v.id,name:v.definition.name,description:v.definition.shortDescription,lifecycleStatus:v.lifecycleStatus})),selectedId:L,searchValue:z,onSearchChange:ie,showRetired:ve,onShowRetiredChange:Se,loading:Ce,error:M,emptyMessage:i.length===0?"No Roles configured yet.":"No Roles match this view.",onRetry:()=>{Te()},onCreate:We,onSelect:v=>{const F=i.find(Q=>Q.id===v);F&&le(F)},libraryPortalTarget:n}),e.jsxs("section",{className:T.editor,"aria-label":A?`Edit ${A.definition.name}`:"Create Role",children:[e.jsx(nr,{icon:e.jsx(ts,{size:18}),title:I?"New Role":A?.definition.name||"Role Manager",description:"Define reusable professional guidance for what an Agent does and produces.",revision:A?.currentRevision,retired:A?.lifecycleStatus==="retired",showActions:I||!!A,dirty:_e,saving:te,onReset:ce,onSave:()=>{d()}}),Ne&&A?e.jsx(or,{title:`Retire ${A.definition.name}?`,message:q,entityLabel:"Role",saving:te,onConfirm:()=>{h("retire")},onCancel:()=>oe(!1)}):null,ae?e.jsx(zn,{type:ae.type,message:ae.message}):null,!I&&!A?e.jsx(ir,{icon:e.jsx(ts,{size:24}),title:"Create your first Role",description:"Roles define reusable professional responsibilities, outputs, and working guidance for Taskforce Agents.",actionLabel:"New Role",onCreate:We}):e.jsxs("div",{className:T.editorGrid,children:[e.jsxs("div",{className:T.formColumn,children:[e.jsxs("section",{className:ot.formSection,children:[e.jsxs("div",{className:ot.sectionHeader,children:[e.jsx("h3",{className:"tf-heading-section",children:"Identity and discovery"}),e.jsx("p",{className:"tf-text-helper",children:"Help people understand when this Role should be assigned."})]}),e.jsxs("div",{className:ot.fieldGrid,children:[e.jsxs("label",{className:"tf-field-stack",children:[e.jsx("span",{className:"tf-field-label",children:"Role name"}),e.jsx("input",{ref:v=>{ee.current.name=v||void 0},id:"role-field-name",className:"tf-field-shell",value:H.name,onChange:v=>y("name",v.target.value),disabled:A?.lifecycleStatus==="retired","aria-invalid":u.has("name"),"aria-errormessage":u.has("name")?"role-field-name-error":void 0}),e.jsx(nt,{id:"role-field-name-error",message:u.get("name")})]}),e.jsxs("label",{className:"tf-field-stack",children:[e.jsx("span",{className:"tf-field-label",children:"Short description"}),e.jsx("input",{ref:v=>{ee.current.shortDescription=v||void 0},id:"role-field-short-description",className:"tf-field-shell",value:H.shortDescription,onChange:v=>y("shortDescription",v.target.value),disabled:A?.lifecycleStatus==="retired","aria-invalid":u.has("shortDescription"),"aria-errormessage":u.has("shortDescription")?"role-field-short-description-error":void 0}),e.jsx(nt,{id:"role-field-short-description-error",message:u.get("shortDescription")})]})]}),e.jsxs("label",{className:"tf-field-stack",children:[e.jsx("span",{className:"tf-field-label",children:"Purpose and scope"}),e.jsx("textarea",{ref:v=>{ee.current.purpose=v||void 0},id:"role-field-purpose",className:"tf-field-shell",value:H.purpose,onChange:v=>y("purpose",v.target.value),rows:4,disabled:A?.lifecycleStatus==="retired","aria-invalid":u.has("purpose"),"aria-errormessage":u.has("purpose")?"role-field-purpose-error":void 0}),e.jsx(nt,{id:"role-field-purpose-error",message:u.get("purpose")})]})]}),e.jsxs("section",{className:ot.formSection,children:[e.jsxs("div",{className:ot.sectionHeader,children:[e.jsx("h3",{className:"tf-heading-section",children:"Runtime behavior"}),e.jsx("p",{className:"tf-text-helper",children:"This bounded guidance is compiled into the Agent runtime prompt."})]}),e.jsxs("div",{className:ot.fieldGrid,children:[D("responsibilities","Responsibilities","One responsibility per line.",6),D("expectedOutputs","Expected outputs","One output or artifact per line.",6)]}),D("workingGuidance","Role-specific working guidance","Optional operating guidance for agents using this Role.",5)]}),e.jsxs("div",{className:ot.configurationPreview,children:[e.jsx(ho,{skills:f,selectedIds:es(H.skillRefs),loading:N,error:k,onRetry:()=>{He()},disabled:A?.lifecycleStatus==="retired",onChange:v=>y("skillRefs",v.join(`
14
+ `))}),e.jsx(Fn,{selectedKeys:es(H.capabilityGroups),mode:"preview",title:"Tool Access",description:"Choose the Taskforce modules this Role is intended to provide. The selection is saved now; automatic Agent inheritance is not active yet.",disabled:A?.lifecycleStatus==="retired",onChange:v=>y("capabilityGroups",v.join(`
15
+ `))}),e.jsxs("section",{className:ot.resourcesPreview,"aria-label":"Role Resources",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"tf-heading-section",children:"Resources"}),e.jsx("p",{className:"tf-text-helper",children:"Trusted collections this Role should consult will appear here."})]}),e.jsx("span",{className:"tf-chip-neutral",children:"Not available yet"}),e.jsx("button",{type:"button",className:"tf-button-secondary",disabled:!0,children:"Add Resource Collection"})]})]})]}),e.jsx(lr,{entityLabel:"Role",note:"This is the exact bounded Role content supplied to the Agent runtime. Included Skills, Tool Access, Resources, and discovery text are excluded until their inheritance is implemented.",meta:e.jsxs("span",{className:"tf-chip-count",children:[Oe.length.toLocaleString()," chars"]}),metrics:A?[{label:"Revision",value:A.currentRevision},{label:"Agent references",value:A.usage.agentCount},{label:"Status",value:A.lifecycleStatus==="retired"?"Retired":"Active"},{label:"Saved revisions",value:A.revisions.length}]:[],revisions:A?.revisions||[],lifecycleStatus:A?.lifecycleStatus,saving:te,retireDescription:"Remove it from new selection while preserving its revision history.",restoreDescription:"Allow this Role to resolve for new Agent runs again.",onRetire:()=>oe(!0),onRestore:()=>{h("restore")},children:Oe?e.jsx("pre",{className:`${T.preview} ${ot.previewCode}`,children:Oe}):e.jsx("div",{className:T.previewEmpty,children:"Complete the required runtime fields to preview this Role."})})]})]})]})}async function fl(t){const[n,i]=await Promise.all([fetch(`/api/taskforce/agent-roles?workspaceId=${encodeURIComponent(t)}&includeRetired=true`,{credentials:"include"}),fetch(`/api/taskforce/agent-skills?workspaceId=${encodeURIComponent(t)}&includeRetired=true`,{credentials:"include"})]),[o,f]=await Promise.all([n.json().catch(()=>({})),i.json().catch(()=>({}))]);if(!n.ok||o?.success===!1)throw new Error(String(o?.error||"Unable to load Roles."));if(!i.ok||f?.success===!1)throw new Error(String(f?.error||"Unable to load Skills."));return{roles:Array.isArray(o?.roles)?o.roles:[],skills:Array.isArray(f?.skills)?f.skills:[]}}const ml="_assignments_oijvg_1",pl="_section_oijvg_8",hl="_sectionHeader_oijvg_16",gl="_sectionHeading_oijvg_24",vl="_referenceCopy_oijvg_48",yl="_empty_oijvg_49",bl="_roleControls_oijvg_61",xl="_skillAdd_oijvg_62",jl="_referenceList_oijvg_83",kl="_referenceRow_oijvg_91",Sl="_rowActions_oijvg_114",Cl="_issue_oijvg_119",Nl="_loadError_oijvg_133",xe={assignments:ml,section:pl,sectionHeader:hl,sectionHeading:gl,referenceCopy:vl,empty:yl,roleControls:bl,skillAdd:xl,referenceList:jl,referenceRow:kl,rowActions:Sl,issue:Cl,loadError:Nl};function $a(t){return t.resolution==="pinned"?`revision:${String(t.revision??"")}`:"current"}function Al(t,n){return{id:t.id,resolution:"pinned",revision:n}}function wl(t){return{id:t.id,resolution:"current"}}function La(t,n){const i=(t?.revisions||[]).map(f=>f.revision).filter(f=>String(f).trim().length>0),o=n.resolution==="pinned"?n.revision:void 0;return o!==void 0&&!i.some(f=>String(f)===String(o))&&i.push(o),i.filter((f,w)=>i.findIndex(N=>String(N)===String(f))===w).sort((f,w)=>{const N=Number(f),x=Number(w);return Number.isFinite(N)&&Number.isFinite(x)?x-N:String(w).localeCompare(String(f))})}function _l(t){const n=Number(t);return Number.isInteger(n)&&String(n)===t?n:t}function Pa(t,n){return n==="current"?wl(t):Al(t,_l(n.slice(9)))}function Tl({workspaceId:t,roleRef:n,skillRefs:i,onRoleRefChange:o,onSkillRefsChange:f,onManageRoles:w,onManageSkills:N}){const[x,k]=a.useState([]),[$,L]=a.useState([]),[K,I]=a.useState(!0),[R,S]=a.useState(""),[_,H]=a.useState(""),Y=a.useRef(0),z=a.useCallback(async()=>{const p=++Y.current;I(!0),S("");try{const M=await fl(t);if(p!==Y.current)return;k(M.roles),L(M.skills)}catch(M){if(p!==Y.current)return;S(String(M?.message||M||"Unable to load Role and Skill options."))}finally{p===Y.current&&I(!1)}},[t]);a.useEffect(()=>(z(),()=>{Y.current+=1}),[z]),a.useEffect(()=>{const p=E=>{const ae=E.detail;(String(ae?.workspaceId||"").trim()||"default")===t&&(ae?.reason!=="role-save"&&ae?.reason!=="role-retire"&&ae?.reason!=="role-restore"||z())},M=E=>{const ae=E.detail;(String(ae?.workspaceId||"").trim()||"default")===t&&z()};return window.addEventListener(ss,p),window.addEventListener(ns,M),()=>{window.removeEventListener(ss,p),window.removeEventListener(ns,M)}},[z,t]);const ie=a.useMemo(()=>new Map(x.map(p=>[p.id,p])),[x]),ve=a.useMemo(()=>new Map($.map(p=>[p.id,p])),[$]),Se=a.useMemo(()=>new Set(i.map(p=>p.id)),[i]),Ce=$.filter(p=>p.lifecycleStatus==="active"&&!Se.has(p.id)),U=n&&ie.get(n.id)||null,te=n?[...U?[]:[`Role ${n.id} is missing or unavailable.`],...U?.lifecycleStatus==="retired"?[`${U.definition.name} is retired.`]:[],...n.resolution==="pinned"&&U&&!U.revisions.some(p=>String(p.revision)===String(n.revision))?[`Role version ${String(n.revision)} is unavailable.`]:[]]:[];return e.jsxs("div",{className:xe.assignments,children:[e.jsxs("section",{className:xe.section,"aria-labelledby":"agent-role-heading",children:[e.jsxs("div",{className:xe.sectionHeader,children:[e.jsxs("div",{className:xe.sectionHeading,children:[e.jsx(ts,{size:17}),e.jsxs("div",{children:[e.jsx("strong",{id:"agent-role-heading",children:"Role"}),e.jsx("small",{children:"Optional reusable professional profile. An Agent can have one Role."})]})]}),e.jsx("button",{type:"button",className:r.secondaryHeaderBtn,onClick:w,children:"Manage Roles"})]}),e.jsxs("div",{className:xe.roleControls,children:[e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Role"}),e.jsxs("select",{className:r.select,"aria-label":"Role",value:n?.id||"",disabled:K,onChange:p=>{const M=p.target.value;o(M?{id:M,resolution:"current"}:null)},children:[e.jsx("option",{value:"",children:"No Role"}),n&&!U?e.jsxs("option",{value:n.id,children:["Missing Role · ",n.id]}):null,x.map(p=>e.jsxs("option",{value:p.id,disabled:p.lifecycleStatus==="retired",children:[p.definition.name,p.lifecycleStatus==="retired"?" · Retired":""]},p.id))]})]}),e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Version"}),e.jsxs("select",{className:r.select,"aria-label":"Role version",value:n?$a(n):"current",disabled:!n||!U,onChange:p=>{n&&o(Pa(n,p.target.value))},children:[e.jsx("option",{value:"current",children:U?`Use latest (Version ${U.currentRevision})`:"Use latest"}),n?La(U,n).map(p=>e.jsxs("option",{value:`revision:${String(p)}`,children:["Version ",p]},p)):null]})]})]}),U?.definition.shortDescription?e.jsx("small",{className:xe.empty,children:U.definition.shortDescription}):null,te.map(p=>e.jsxs("div",{className:xe.issue,role:"alert",children:[e.jsx(st,{size:13}),e.jsxs("span",{children:[p," Agent execution is blocked until this reference is repaired."]})]},p))]}),e.jsxs("section",{className:xe.section,"aria-labelledby":"agent-skills-heading",children:[e.jsxs("div",{className:xe.sectionHeader,children:[e.jsxs("div",{className:xe.sectionHeading,children:[e.jsx(Lt,{size:17}),e.jsxs("div",{children:[e.jsx("strong",{id:"agent-skills-heading",children:"Skills"}),e.jsx("small",{children:"Composable behavior applied in this exact order. Later Skills take precedence when guidance conflicts."})]})]}),e.jsx("button",{type:"button",className:r.secondaryHeaderBtn,onClick:N,children:"Manage Skills"})]}),e.jsxs("div",{className:xe.skillAdd,children:[e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Add Skill"}),e.jsxs("select",{className:r.select,"aria-label":"Skill to add",value:_,disabled:K||Ce.length===0,onChange:p=>H(p.target.value),children:[e.jsx("option",{value:"",children:"Select a Skill"}),Ce.map(p=>e.jsx("option",{value:p.id,children:p.definition.name},p.id))]})]}),e.jsx("button",{type:"button",className:"tf-control-icon",disabled:!_,"aria-label":"Add selected Skill",title:"Add selected Skill",onClick:()=>{!_||Se.has(_)||(f([...i,{id:_,resolution:"current"}]),H(""))},children:e.jsx(Pt,{size:14})})]}),i.length>0?e.jsx("ol",{className:xe.referenceList,children:i.map((p,M)=>{const E=ve.get(p.id)||null,ae=[...E?[]:[`Skill ${p.id} is missing or unavailable.`],...E?.lifecycleStatus==="retired"?[`${E.definition.name} is retired.`]:[],...p.resolution==="pinned"&&E&&!E.revisions.some(G=>String(G.revision)===String(p.revision))?[`Skill version ${String(p.revision)} is unavailable.`]:[]];return e.jsxs("li",{children:[e.jsxs("div",{className:xe.referenceRow,children:[e.jsxs("div",{className:xe.referenceCopy,children:[e.jsxs("strong",{children:[M+1,". ",E?.definition.name||`Missing Skill · ${p.id}`]}),e.jsx("small",{children:E?.definition.shortDescription||p.id})]}),e.jsxs("select",{className:r.select,"aria-label":`${E?.definition.name||p.id} version`,value:$a(p),disabled:!E,onChange:G=>{const Ne=[...i];Ne[M]=Pa(p,G.target.value),f(Ne)},children:[e.jsx("option",{value:"current",children:E?`Use latest (Version ${E.revision})`:"Use latest"}),La(E,p).map(G=>e.jsxs("option",{value:`revision:${String(G)}`,children:["Version ",G]},G))]}),e.jsxs("div",{className:xe.rowActions,children:[e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact","aria-label":`Move ${E?.definition.name||p.id} up`,disabled:M===0,onClick:()=>{if(M===0)return;const G=[...i];[G[M-1],G[M]]=[G[M],G[M-1]],f(G)},children:e.jsx(Ja,{size:14})}),e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact","aria-label":`Move ${E?.definition.name||p.id} down`,disabled:M===i.length-1,onClick:()=>{if(M===i.length-1)return;const G=[...i];[G[M],G[M+1]]=[G[M+1],G[M]],f(G)},children:e.jsx(Ya,{size:14})}),e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact","aria-label":`Remove ${E?.definition.name||p.id}`,onClick:()=>f(i.filter((G,Ne)=>Ne!==M)),children:e.jsx(yt,{size:14})})]})]}),ae.map(G=>e.jsxs("div",{className:xe.issue,role:"alert",children:[e.jsx(st,{size:13}),e.jsxs("span",{children:[G," Agent execution is blocked until this reference is repaired."]})]},G))]},`${p.id}-${M}`)})}):e.jsx("p",{className:xe.empty,children:"No Skills selected."}),R?e.jsx("p",{className:xe.loadError,role:"alert",children:R}):null]})]})}const Rl=1,El=[{key:"practical",label:"Practical"},{key:"encouraging",label:"Encouraging"},{key:"analytical",label:"Analytical"},{key:"direct",label:"Direct"},{key:"friendly-coach",label:"Friendly Coach"},{key:"creative-partner",label:"Creative Partner"}],Il=[{key:"concise",label:"Concise"},{key:"balanced",label:"Balanced"},{key:"detailed",label:"Detailed"},{key:"executive-summary",label:"Executive Summary"},{key:"critical-review",label:"Critical Review"},{key:"technical",label:"Technical"},{key:"creative",label:"Creative"}],$l=[{key:"taskforce-default",label:"Taskforce Agent"},{key:"photographic",label:"Photographic"},{key:"cinematic",label:"Cinematic"},{key:"painterly",label:"Painterly"},{key:"watercolor",label:"Watercolor"},{key:"graphic-novel",label:"Graphic Novel"},{key:"anime-inspired",label:"Anime-inspired"},{key:"stylized-3d",label:"Stylized 3D"},{key:"pixel-art",label:"Pixel Art"},{key:"ink-sketch",label:"Ink Sketch"}],Me="__custom__",Ll="Default",Pl="Help users complete work in Taskforce.",Ml="Be concise and actionable.",Kn=["tasks","planning","documents","images","workspace"],Dl=new Set(Kn);function Ss(t,n={}){const i=t?.behavior.personality,o=t?.behavior.responseStyle,f=t?.presentation.avatar.artStyle,w=new Set(t?.toolPolicy.disabledCapabilities||[]),N=t?.toolPolicy.requestedCapabilities?.length?t.toolPolicy.requestedCapabilities:Kn;return{purpose:t?.purpose||Pl,personalitySelection:i?.presetKey||(i?.customDescription?Me:""),personalityCustom:i?.customDescription||"",responseStyleSelection:o?.presetKey||(o?.customDescription?Me:""),responseStyleCustom:o?.customDescription||"",workingGuidelines:t?.behavior.workingGuidelines||n.systemPrompt||Ml,avatarVisualDescription:t?.presentation.avatar.visualDescription||"",avatarArtStyleSelection:f?.mode==="preset"?f.presetKey:f?.mode==="custom"?Me:"",avatarArtStyleCustom:f?.mode==="custom"?f.customDescription:"",roleRef:t?.roleRef?{...t.roleRef}:null,skillRefs:(t?.skillRefs||[]).map(x=>({...x})),requestedCapabilities:N.filter(x=>!w.has(x)),toolAccessChanged:!1}}function Ma(t,n){const i=n.trim();return t===Me?i?{customDescription:i}:void 0:t?{presetKey:t}:void 0}function Ol(t,n){const i=n.trim();return t===Me?i?{mode:"custom",customDescription:i}:void 0:t?{mode:"preset",presetKey:t}:void 0}function zl(t){const{baseDefinition:n,draft:i}=t,o=Ma(i.personalitySelection,i.personalityCustom),f=Ma(i.responseStyleSelection,i.responseStyleCustom),w=i.workingGuidelines.trim(),N=i.avatarVisualDescription.trim(),x=Ol(i.avatarArtStyleSelection,i.avatarArtStyleCustom),k=i.requestedCapabilities.filter(L=>Dl.has(L)),$=si(t.modelKey);return{...n||{},schemaVersion:Rl,name:t.name.trim(),purpose:i.purpose.trim(),model:{providerKey:t.providerKey,modelKey:t.modelKey,modelSource:$?.source||"bedrock",tier:t.tier,...$?.source==="subscription_dev"?{connectionScope:t.connectionScope||"local_dev"}:{}},behavior:{...o?{personality:o}:{},...f?{responseStyle:f}:{},...w?{workingGuidelines:w}:{}},presentation:{avatar:{...N?{visualDescription:N}:{},...x?{artStyle:x}:{}}},...i.roleRef?{roleRef:{...i.roleRef}}:{roleRef:void 0},skillRefs:i.skillRefs.map(L=>({...L})),toolPolicy:n?.toolPolicy&&!i.toolAccessChanged?n.toolPolicy:{basePolicyRef:n?.toolPolicy.basePolicyRef||{id:"managed-agent-default",resolution:"current"},requestedCapabilities:k.length>0?k:void 0,disabledCapabilities:k.length===0?[...Kn]:void 0,toolOverrides:void 0}}}function Ul(t,n){const i=Ss(t);return i.avatarVisualDescription!==n.avatarVisualDescription||i.avatarArtStyleSelection!==n.avatarArtStyleSelection||i.avatarArtStyleCustom!==n.avatarArtStyleCustom}const _n=1,Da=2e4,Ke={name:80,shortDescription:280,purpose:1e3,instructions:12e3,listItems:20,listItem:1e3,capabilityGroup:160};function Gl(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function qe(t,n,i,o){t.push({code:n,path:i,message:o})}function Qs(t,n,i,o){if(typeof t!="string")return qe(o,"required_string",n,"A string value is required."),"";const f=t.trim();return f?f.length>i&&qe(o,"string_too_long",n,`Must be ${i} characters or less.`):qe(o,"required_string",n,"A non-empty value is required."),f}function ys(t,n,i,o){if(!Array.isArray(t))return qe(o,"required_array",n,"An array of strings is required."),[];t.length>Ke.listItems&&qe(o,"too_many_items",n,`Must contain ${Ke.listItems} items or fewer.`);const f=new Set,w=[];return t.slice(0,Ke.listItems).forEach((N,x)=>{if(typeof N!="string"){qe(o,"invalid_list_item",`${n}.${x}`,"Must be a string.");return}const k=N.trim();if(!k){qe(o,"empty_list_item",`${n}.${x}`,"Must not be empty.");return}k.length>i&&qe(o,"string_too_long",`${n}.${x}`,`Must be ${i} characters or less.`);const $=k.toLocaleLowerCase();if(f.has($)){qe(o,"duplicate_list_item",`${n}.${x}`,"Duplicate items are not allowed.");return}f.add($),w.push(k)}),w}function cr(t){return[["Instructions",t.instructions],["Expected inputs",t.expectedInputs.map((i,o)=>`${o+1}. ${i}`).join(`
16
+ `)],["Expected outputs",t.expectedOutputs.map((i,o)=>`${o+1}. ${i}`).join(`
17
+ `)],["Quality checks",t.qualityChecks.map((i,o)=>`${o+1}. ${i}`).join(`
18
+ `)]].filter(([,i])=>!!i).map(([i,o])=>`${i}:
19
+ ${o}`).join(`
20
+
21
+ `)}function Bl(t){const n=[];if(!Gl(t))return{definition:null,issues:[{code:"invalid_definition",path:"definition",message:"Skill definition must be an object."}]};const i=new Set(["schemaVersion","name","shortDescription","purpose","instructions","expectedInputs","expectedOutputs","qualityChecks","exampleUseCases","recommendedCapabilityGroups"]);Object.keys(t).forEach(f=>{i.has(f)||qe(n,"unknown_field",f,"This field is not part of Agent Skill v1.")}),t.schemaVersion!==_n&&qe(n,"unsupported_schema_version","schemaVersion",`schemaVersion must be ${_n}.`);const o={schemaVersion:_n,name:Qs(t.name,"name",Ke.name,n),shortDescription:Qs(t.shortDescription,"shortDescription",Ke.shortDescription,n),purpose:Qs(t.purpose,"purpose",Ke.purpose,n),instructions:Qs(t.instructions,"instructions",Ke.instructions,n),expectedInputs:ys(t.expectedInputs,"expectedInputs",Ke.listItem,n),expectedOutputs:ys(t.expectedOutputs,"expectedOutputs",Ke.listItem,n),qualityChecks:ys(t.qualityChecks,"qualityChecks",Ke.listItem,n),exampleUseCases:ys(t.exampleUseCases,"exampleUseCases",Ke.listItem,n),recommendedCapabilityGroups:ys(t.recommendedCapabilityGroups,"recommendedCapabilityGroups",Ke.capabilityGroup,n)};return cr(o).length>Da&&qe(n,"compiled_prompt_too_long","instructions",`Compiled runtime content must be ${Da} characters or less.`),{definition:n.length===0?o:null,issues:n}}const Hl="_section_1e1mf_1",Fl="_sectionHeading_1e1mf_9",Kl="_twoColumn_1e1mf_20",ql="_instructions_1e1mf_26",Vl="_orderedList_1e1mf_36",Wl="_orderedRow_1e1mf_42",Jl="_orderedInput_1e1mf_49",Yl="_orderNumber_1e1mf_56",Ql="_orderActions_1e1mf_63",Xl="_listEmpty_1e1mf_69",De={section:Hl,sectionHeading:Fl,twoColumn:Kl,instructions:ql,orderedList:Vl,orderedRow:Wl,orderedInput:Jl,orderNumber:Yl,orderActions:Ql,listEmpty:Xl},bs={name:"",shortDescription:"",purpose:"",instructions:"",expectedInputs:[],expectedOutputs:[],qualityChecks:[],exampleUseCases:[],recommendedCapabilityGroups:[]};function Xs(t){const{schemaVersion:n,...i}=t.definition;return{...i,expectedInputs:[...i.expectedInputs],expectedOutputs:[...i.expectedOutputs],qualityChecks:[...i.qualityChecks],exampleUseCases:[...i.exampleUseCases],recommendedCapabilityGroups:[...i.recommendedCapabilityGroups]}}function It(t){return JSON.stringify(t)}function Tn(t,n){const o=(Array.isArray(t.issues)?t.issues:[])[0];return o?.message?`${o.path?`${o.path}: `:""}${o.message}`:String(t.error||n)}function Zs({fieldPath:t,label:n,helper:i,values:o,onChange:f,placeholder:w,disabled:N=!1,issues:x,fieldRefs:k}){const $=()=>f([...o,""]),L=(R,S)=>{const _=[...o];_[R]=S,f(_)},K=(R,S)=>{const _=R+S;if(_<0||_>=o.length)return;const H=[...o];[H[R],H[_]]=[H[_],H[R]],f(H)},I=x.get(t);return e.jsxs("div",{className:"tf-field-stack",children:[e.jsxs("div",{className:"tf-field-label-row",children:[e.jsx("span",{className:"tf-field-label",children:n}),e.jsxs("button",{type:"button",className:"tf-button-ghost tf-button-compact",disabled:N,onClick:$,children:[e.jsx(Pt,{size:13})," Add"]})]}),e.jsx("span",{className:"tf-field-hint",children:i}),e.jsx(nt,{id:`skill-field-${t}-error`,message:I}),o.length===0?e.jsx("div",{className:De.listEmpty,children:"No items added."}):e.jsx("div",{className:De.orderedList,children:o.map((R,S)=>{const _=x.get(`${t}.${S}`),H=_||(S===0?I:void 0),Y=_?`skill-field-${t}-${S}-error`:`skill-field-${t}-error`;return e.jsxs("div",{className:De.orderedRow,children:[e.jsx("span",{className:De.orderNumber,children:S+1}),e.jsxs("div",{className:De.orderedInput,children:[e.jsx("input",{ref:z=>{k.current[`${t}.${S}`]=z||void 0,S===0&&(k.current[t]=z||void 0)},id:`skill-field-${t}-${S}`,className:"tf-field-shell","aria-label":`${n} item ${S+1}`,"aria-invalid":!!H,"aria-errormessage":H?Y:void 0,value:R,placeholder:w,disabled:N,onChange:z=>L(S,z.target.value)}),e.jsx(nt,{id:`skill-field-${t}-${S}-error`,message:_})]}),e.jsxs("div",{className:De.orderActions,children:[e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact tf-control-icon-quiet","aria-label":`Move ${n.toLowerCase()} item up`,disabled:N||S===0,onClick:()=>{N||K(S,-1)},children:e.jsx(Ja,{size:13})}),e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact tf-control-icon-quiet","aria-label":`Move ${n.toLowerCase()} item down`,disabled:N||S===o.length-1,onClick:()=>{N||K(S,1)},children:e.jsx(Ya,{size:13})}),e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact tf-control-icon-quiet","aria-label":`Remove ${n.toLowerCase()} item`,disabled:N,onClick:()=>f(o.filter((z,ie)=>ie!==S)),children:e.jsx(yt,{size:13})})]})]},`${t}-${S}`)})})]})}function Zl({workspaceId:t,active:n=!0,libraryPortalTarget:i}){const[o,f]=a.useState([]),[w,N]=a.useState(null),[x,k]=a.useState(bs),[$,L]=a.useState(It(bs)),[K,I]=a.useState(!1),[R,S]=a.useState(!0),[_,H]=a.useState(!1),[Y,z]=a.useState(null),[ie,ve]=a.useState(null),[Se,Ce]=a.useState(""),[U,te]=a.useState(!1),[p,M]=a.useState(!1),[E,ae]=a.useState(!1),[G,Ne]=a.useState(!1),oe=a.useRef({}),O=o.find(y=>y.id===w)||null,he=It(x)!==$,ee=a.useCallback(y=>{if(he&&!window.confirm("Discard unsaved Skill changes?"))return;const d=Xs(y);N(y.id),k(d),L(It(d)),I(!1),M(!1),ae(!1),z(null),ve(null)},[he]),ge=a.useCallback(async y=>{y?.quiet||S(!0);try{const d=await gt(`/api/taskforce/agent-skills?workspaceId=${encodeURIComponent(t)}&includeRetired=true`,{credentials:"include"}),h=await d.json().catch(()=>({}));if(!d.ok||h?.success===!1||!Array.isArray(h?.skills))throw new Error(Tn(h,"Unable to load Skills."));const u=h.skills;f(u),N(D=>{if(K)return D;const q=u.find(v=>v.id===D)||u.find(v=>v.lifecycleStatus==="active")||u[0]||null;if(q&&(!he||q.id===D)){const v=Xs(q);k(v),L(It(v))}return q?.id||null}),z(null)}catch(d){z(String(d?.message||d||"Unable to load Skills."))}finally{S(!1)}},[K,he,t]);a.useEffect(()=>{!n||G||(Ne(!0),ge())},[n,ge,G]),a.useEffect(()=>{const y=d=>{const h=d.detail;String(h?.workspaceId||"").trim()===t&&ge({quiet:!0})};return window.addEventListener(ns,y),()=>window.removeEventListener(ns,y)},[ge,t]),a.useEffect(()=>{if(!he)return;const y=d=>{d.preventDefault(),d.returnValue=""};return window.addEventListener("beforeunload",y),()=>window.removeEventListener("beforeunload",y)},[he]);const A=a.useMemo(()=>{const y=Se.trim().toLocaleLowerCase();return o.filter(d=>!U&&d.lifecycleStatus==="retired"?!1:y?[d.definition.name,d.definition.shortDescription,d.definition.purpose].some(h=>h.toLocaleLowerCase().includes(y)):!0)},[Se,U,o]),ye=a.useMemo(()=>({schemaVersion:1,...x}),[x]),_e=a.useMemo(()=>Bl(ye),[ye]),Ae=a.useMemo(()=>cr(ye),[ye]),le=a.useMemo(()=>ar(_e.issues,E),[_e.issues,E]),Te=()=>{he&&!window.confirm("Discard unsaved Skill changes?")||(N(null),k(bs),L(It(bs)),I(!0),M(!1),ae(!1),z(null),ve(null))},He=()=>{const y=O?Xs(O):bs;k(y),L(It(y)),M(!1),ae(!1),z(null),ve(null)},bt=async()=>{if(!_){if(!_e.definition){ae(!0),z(_e.issues[0]?.message||"Complete the required Skill fields."),rr(_e.issues,oe.current);return}H(!0),z(null),ve(null);try{const y=O?`/api/taskforce/agent-skills/${encodeURIComponent(O.id)}`:"/api/taskforce/agent-skills",d=await gt(y,{method:O?"PATCH":"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t,definition:_e.definition,...O?{expectedContentHash:O.contentHash}:{}})}),h=await d.json().catch(()=>({}));if(!d.ok||h?.success===!1||!h?.skill)throw new Error(Tn(h,"Unable to save Skill."));const u=h.skill,D=Xs(u);f(q=>q.some(F=>F.id===u.id)?q.map(F=>F.id===u.id?u:F):[...q,u].sort((F,Q)=>F.definition.name.localeCompare(Q.definition.name))),N(u.id),k(D),L(It(D)),I(!1),ae(!1),ve(`Saved ${u.definition.name}.`),ya({workspaceId:t,skillId:u.id,reason:O?"update":"create"})}catch(y){z(String(y?.message||y||"Unable to save Skill."))}finally{H(!1)}}},we=async y=>{if(!(!O||_)){H(!0),z(null),ve(null);try{const d=await gt(`/api/taskforce/agent-skills/${encodeURIComponent(O.id)}/${y}`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t})}),h=await d.json().catch(()=>({}));if(!d.ok||h?.success===!1||!h?.skill)throw new Error(Tn(h,`Unable to ${y} Skill.`));const u=h.skill;f(D=>D.map(q=>q.id===u.id?u:q)),y==="retire"&&te(!0),M(!1),ve(`${y==="retire"?"Retired":"Restored"} ${u.definition.name}.`),ya({workspaceId:t,skillId:u.id,reason:y})}catch(d){z(String(d?.message||d||`Unable to ${y} Skill.`))}finally{H(!1)}}},Oe=O?.usage.workflowCount,We=O?O.usage.agentCount+(Oe||0):0,ce=[We>0?`${We} known Agent or Workflow configuration${We===1?" references":"s reference"} this Skill and will require repair before running.`:"No known Agent or Workflow configurations currently reference this Skill.",Oe===null?"Workflow reference counts are unavailable in this version, so review attached Workflows before retiring it.":""].filter(Boolean).join(" ");return e.jsxs("div",{className:`${T.root} ${i?T.rootExternalLibrary:""}`.trim(),children:[e.jsx(sr,{singularLabel:"Skill",pluralLabel:"Skills",description:"Reusable capabilities that define how an Agent performs a class of work.",icon:e.jsx(Lt,{size:15}),items:A.map(y=>({id:y.id,name:y.definition.name,description:y.definition.shortDescription,lifecycleStatus:y.lifecycleStatus})),selectedId:w,searchValue:Se,onSearchChange:Ce,showRetired:U,onShowRetiredChange:te,loading:R,error:null,emptyMessage:o.length===0?"No Skills configured yet.":"No Skills match this view.",onCreate:Te,onSelect:y=>{const d=o.find(h=>h.id===y);d&&ee(d)},libraryPortalTarget:i}),e.jsxs("main",{className:T.editor,children:[e.jsx(nr,{icon:e.jsx(Lt,{size:18}),title:K?"New Skill":O?.definition.name||"Skill Manager",description:"Define bounded, reusable guidance for how an Agent performs a class of work.",revision:O?.revision,retired:O?.lifecycleStatus==="retired",showActions:K||!!O,dirty:he,saving:_,onReset:He,onSave:()=>{bt()}}),p&&O?e.jsx(or,{title:`Retire ${O.definition.name}?`,message:ce,entityLabel:"Skill",saving:_,onConfirm:()=>{we("retire")},onCancel:()=>M(!1)}):null,Y?e.jsx(zn,{type:"error",message:Y}):null,ie?e.jsx(zn,{type:"success",message:ie}):null,!K&&!O?e.jsx(ir,{icon:e.jsx(Lt,{size:24}),title:"Create your first Skill",description:"Skills package reusable instructions, inputs, outputs, and quality checks without granting tools or permissions.",actionLabel:"New Skill",onCreate:Te}):e.jsxs("div",{className:T.editorGrid,children:[e.jsxs("div",{className:T.formColumn,children:[e.jsxs("section",{className:De.section,children:[e.jsx("div",{className:De.sectionHeading,children:e.jsxs("div",{children:[e.jsx("h3",{className:"tf-heading-section",children:"Identity and discovery"}),e.jsx("p",{className:"tf-text-helper",children:"These fields help people find and understand the Skill. They are not added to normal prompts."})]})}),e.jsxs("div",{className:De.twoColumn,children:[e.jsxs("label",{className:"tf-field-stack",children:[e.jsx("span",{className:"tf-field-label",children:"Name"}),e.jsx("input",{ref:y=>{oe.current.name=y||void 0},id:"skill-field-name",className:"tf-field-shell","aria-label":"Name","aria-invalid":!!le.get("name"),"aria-errormessage":le.get("name")?"skill-field-name-error":void 0,value:x.name,maxLength:80,disabled:O?.lifecycleStatus==="retired",onChange:y=>k(d=>({...d,name:y.target.value}))}),e.jsx(nt,{id:"skill-field-name-error",message:le.get("name")})]}),e.jsxs("label",{className:"tf-field-stack",children:[e.jsx("span",{className:"tf-field-label",children:"Short description"}),e.jsx("input",{ref:y=>{oe.current.shortDescription=y||void 0},id:"skill-field-short-description",className:"tf-field-shell","aria-label":"Short description","aria-invalid":!!le.get("shortDescription"),"aria-errormessage":le.get("shortDescription")?"skill-field-short-description-error":void 0,value:x.shortDescription,maxLength:280,disabled:O?.lifecycleStatus==="retired",onChange:y=>k(d=>({...d,shortDescription:y.target.value}))}),e.jsx(nt,{id:"skill-field-short-description-error",message:le.get("shortDescription")})]})]}),e.jsxs("label",{className:"tf-field-stack",children:[e.jsx("span",{className:"tf-field-label",children:"Purpose"}),e.jsx("textarea",{ref:y=>{oe.current.purpose=y||void 0},id:"skill-field-purpose",className:"tf-field-shell","aria-label":"Purpose","aria-invalid":!!le.get("purpose"),"aria-errormessage":le.get("purpose")?"skill-field-purpose-error":void 0,rows:3,value:x.purpose,maxLength:1e3,disabled:O?.lifecycleStatus==="retired",onChange:y=>k(d=>({...d,purpose:y.target.value}))}),e.jsx(nt,{id:"skill-field-purpose-error",message:le.get("purpose")})]})]}),e.jsxs("section",{className:De.section,children:[e.jsx("div",{className:De.sectionHeading,children:e.jsxs("div",{children:[e.jsx("h3",{className:"tf-heading-section",children:"Runtime behavior"}),e.jsx("p",{className:"tf-text-helper",children:"Only this bounded content is compiled into the Agent prompt."})]})}),e.jsxs("label",{className:"tf-field-stack",children:[e.jsx("span",{className:"tf-field-label",children:"Instructions"}),e.jsx("textarea",{ref:y=>{oe.current.instructions=y||void 0},id:"skill-field-instructions",className:`tf-field-shell ${De.instructions}`,"aria-label":"Instructions","aria-describedby":`skill-field-instructions-hint${le.get("instructions")?" skill-field-instructions-error":""}`,"aria-invalid":!!le.get("instructions"),"aria-errormessage":le.get("instructions")?"skill-field-instructions-error":void 0,rows:9,value:x.instructions,maxLength:12e3,disabled:O?.lifecycleStatus==="retired",placeholder:"Describe how the Agent should perform this capability.",onChange:y=>k(d=>({...d,instructions:y.target.value}))}),e.jsx("span",{id:"skill-field-instructions-hint",className:"tf-field-hint",children:"Markdown is supported as text. Scripts and executable bundles are not supported."}),e.jsx(nt,{id:"skill-field-instructions-error",message:le.get("instructions")})]}),e.jsx(Zs,{fieldPath:"expectedInputs",label:"Expected inputs",helper:"What information or artifacts should be available?",values:x.expectedInputs,placeholder:"e.g. Complete diff",onChange:y=>k(d=>({...d,expectedInputs:y})),disabled:O?.lifecycleStatus==="retired",issues:le,fieldRefs:oe}),e.jsx(Zs,{fieldPath:"expectedOutputs",label:"Expected outputs",helper:"What should this Skill produce?",values:x.expectedOutputs,placeholder:"e.g. Prioritized findings",onChange:y=>k(d=>({...d,expectedOutputs:y})),disabled:O?.lifecycleStatus==="retired",issues:le,fieldRefs:oe}),e.jsx(Zs,{fieldPath:"qualityChecks",label:"Quality checks",helper:"What must be true before the work is considered ready?",values:x.qualityChecks,placeholder:"e.g. Every finding cites evidence",onChange:y=>k(d=>({...d,qualityChecks:y})),disabled:O?.lifecycleStatus==="retired",issues:le,fieldRefs:oe})]}),e.jsxs("section",{className:De.section,children:[e.jsx("div",{className:De.sectionHeading,children:e.jsxs("div",{children:[e.jsx("h3",{className:"tf-heading-section",children:"Authoring metadata"}),e.jsx("p",{className:"tf-text-helper",children:"Useful for discovery and recommendations; excluded from runtime prompts and permissions."})]})}),e.jsx(Zs,{fieldPath:"exampleUseCases",label:"Example use cases",helper:"Situations where this Skill is useful.",values:x.exampleUseCases,placeholder:"e.g. Review a pull request",onChange:y=>k(d=>({...d,exampleUseCases:y})),disabled:O?.lifecycleStatus==="retired",issues:le,fieldRefs:oe}),e.jsx(Fn,{selectedKeys:x.recommendedCapabilityGroups,title:"Required Tool Access",description:"Select the Taskforce modules this Skill expects. Requirements are saved for discovery but are not enforced or granted yet.",mode:"requirement",showFutureTools:!1,disabled:O?.lifecycleStatus==="retired",onChange:y=>k(d=>({...d,recommendedCapabilityGroups:y}))})]})]}),e.jsx(lr,{entityLabel:"Skill",note:"This is the exact bounded Skill content supplied to the Agent runtime. Discovery and recommendation metadata are excluded.",meta:e.jsxs("span",{className:"tf-chip-count",children:[Ae.length.toLocaleString()," chars"]}),metrics:O?[{label:"Revision",value:O.revision},{label:"Agent references",value:O.usage.agentCount},{label:"Workflow references",value:O.usage.workflowCount??"Unavailable"},{label:"Status",value:O.lifecycleStatus==="retired"?"Retired":"Active"}]:[],revisions:O?.revisions||[],lifecycleStatus:O?.lifecycleStatus,saving:_,retireDescription:"Remove it from new selection while preserving immutable history.",restoreDescription:"Allow this Skill to resolve for new Agent runs again.",onRetire:()=>M(!0),onRestore:()=>{we("restore")},children:Ae?e.jsx("div",{className:T.preview,children:e.jsx(Mn,{variant:"detail",children:Ae})}):e.jsx("div",{className:T.previewEmpty,children:"Add runtime instructions to preview this Skill."})})]})]})]})}class ct extends Error{constructor(n,i,o){super(n),this.code=i,this.status=o,this.name="ModelConnectionsApiError"}}async function Ve(t,n,i){const o=new Headers(n?.headers||void 0);n?.body&&o.set("Content-Type","application/json");const f=String(i.workspaceId||"").trim();f&&f!=="default"&&o.set("x-taskforce-workspace-id",f);const w=i.resolveApiUrl?.(t)||t,N=await gt(w,{credentials:"include",...n,headers:o},i.apiBaseUrl),x=await N.json().catch(()=>({}));if(!N.ok||x.success===!1)throw new ct(String(x.error||`Model connection request failed (${N.status}).`),x.code,N.status);return x}async function Un(t){const n=await Ve("/api/taskforce/model-connections",void 0,t);return Array.isArray(n.connections)?n.connections:[]}async function ec(t){const n=await Ve("/api/taskforce/model-connections",void 0,t);return{eligible:n.eligible===!0,connections:Array.isArray(n.connections)?n.connections:[]}}async function tc(t){const n=await Ve("/api/taskforce/model-connections",{method:"POST",body:JSON.stringify({providerKey:"openai",authenticationType:"chatgpt_device_code"})},t);if(!n.connection)throw new ct("Model connection response was incomplete.");return n.connection}async function sc(t,n){const i=await Ve(`/api/taskforce/model-connections/${encodeURIComponent(t)}/login`,{method:"POST"},n);if(!i.login)throw new ct("Device authorization response was incomplete.");return i.login}async function nc(t,n,i){const o=await Ve(`/api/taskforce/model-connections/${encodeURIComponent(t)}/login/${encodeURIComponent(n)}`,void 0,i);if(!o.login)throw new ct("Device authorization response was incomplete.");return o.login}async function ac(t,n,i){const o=await Ve(`/api/taskforce/model-connections/${encodeURIComponent(t)}/login/${encodeURIComponent(n)}/cancel`,{method:"POST"},i);if(!o.login)throw new ct("Device authorization response was incomplete.");return o.login}async function qn(t,n,i){const o=await Ve(`/api/taskforce/model-connections/${encodeURIComponent(t)}/${n}`,{method:"POST"},i);if(!o.connection)throw new ct("Model connection response was incomplete.");return o.connection}const rc=(t,n)=>qn(t,"verify",n),ic=(t,n)=>qn(t,"refresh",n),oc=(t,n)=>qn(t,"disconnect",n);async function lc(t,n,i){const o=await Ve(`/api/taskforce/model-connections/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({displayName:n})},i);if(!o.connection)throw new ct("Model connection response was incomplete.");return o.connection}async function cc(t,n){await Ve(`/api/taskforce/model-connections/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function dc(t,n){const i=encodeURIComponent(String(n.workspaceId||"").trim());return(await Ve(`/api/taskforce/agents/${encodeURIComponent(t)}/connection-binding?workspaceId=${i}`,void 0,n)).binding||{bound:!1,available:!1,reasonCode:"MODEL_CONNECTION_REQUIRED"}}async function uc(t,n,i){const o=await Ve(`/api/taskforce/agents/${encodeURIComponent(t)}/connection-binding`,{method:"PUT",body:JSON.stringify({workspaceId:i.workspaceId,connectionId:n})},i);if(!o.binding)throw new ct("Agent connection response was incomplete.");return o.binding}async function fc(t,n){await Ve(`/api/taskforce/agents/${encodeURIComponent(t)}/connection-binding`,{method:"DELETE",body:JSON.stringify({workspaceId:n.workspaceId})},n)}function xs(t,n="The connection needs to be authorized again."){switch(String(t||"").trim().toUpperCase()){case"MODEL_CONNECTION_DEVICE_CODE_UNAVAILABLE":return"ChatGPT device authorization is unavailable for this account. Retry later or use another connection.";case"MODEL_CONNECTION_RATE_LIMITED":return"ChatGPT temporarily rate limited this connection. Wait a moment, then retry.";case"MODEL_CONNECTION_LOGIN_LIMIT_REACHED":case"MODEL_CONNECTION_LOGIN_CAPACITY_REACHED":return"Device authorization capacity is temporarily full. Wait a moment, then retry.";case"MODEL_CONNECTION_LOGIN_CANCELLED":return"Device authorization was cancelled.";case"MODEL_CONNECTION_LEASE_LOST":return"The connection changed while authorization was running. Start again.";default:return n}}const mc=1500,Oa=ni("chatgpt");function za(t){switch(t){case"active":return"Connected";case"pending":return"Not authorized";case"reconnect_required":return"Reconnect required";case"revoked":return"Revoked";case"disconnected":return"Disconnected";default:return"Unavailable"}}function Ua(t){return t==="active"?"tf-chip-success":t==="pending"||t==="disconnected"?"tf-chip-neutral":t==="reconnect_required"?"tf-chip-warning":"tf-chip-danger"}function js(t){return String(t.displayMetadata.displayName||t.displayMetadata.accountLabel||t.displayMetadata.accountEmail||"ChatGPT subscription")}function pc(t){const i=[t.lastVerifiedAt,t.lastRefreshedAt].filter(o=>!!o).map(o=>new Date(o)).filter(o=>!Number.isNaN(o.getTime())).sort((o,f)=>f.getTime()-o.getTime())[0];return i?`Checked ${i.toLocaleString()}`:"Not verified yet"}function hc({workspaceId:t,active:n,runtimeMode:i,eligible:o,cloudAccessAvailable:f=i==="cloud",cloudAccessPending:w=!1,cloudAuthConfigured:N=i==="cloud",resolveCloudAuthUrl:x,onConnectionActivated:k,onConnectionUnavailable:$,onReturnToAgent:L,pollIntervalMs:K=mc,libraryPortalTarget:I}){const R=a.useMemo(()=>({workspaceId:t,resolveApiUrl:x}),[x,t]),[S,_]=a.useState([]),[H,Y]=a.useState(""),[z,ie]=a.useState(i==="local"?null:o),[ve,Se]=a.useState(!1),[Ce,U]=a.useState(null),[te,p]=a.useState(null),[M,E]=a.useState(null),[ae,G]=a.useState(!1),[Ne,oe]=a.useState(null),[O,he]=a.useState(""),ee=a.useRef(0),ge=a.useRef(0),A=a.useRef(null),ye=i==="local"?z:o,_e=S.find(d=>d.id===H)||null,Ae=a.useCallback(async(d=!1)=>{if(!f)return;const h=++ge.current;d||Se(!0);try{if(i==="local"){const u=await ec(R);if(h!==ge.current)return;ie(u.eligible),_(u.connections)}else{const u=await Un(R);if(h!==ge.current)return;_(u)}d||E(null)}catch(u){if(h!==ge.current)return;E({type:"error",message:u.message||"Unable to load model connections."})}finally{!d&&h===ge.current&&Se(!1)}},[f,R,i]);a.useEffect(()=>{ge.current+=1,ee.current+=1,_([]),Y(""),ie(i==="local"?null:o),Se(!1),U(null),p(null),E(null),G(!1),oe(null),he("")},[f,R,o,i]),a.useEffect(()=>{Y(d=>d&&S.some(h=>h.id===d)?d:S.length===1?S[0].id:"")},[S]),a.useEffect(()=>{!n||!f||i==="cloud"&&!o||Ae()},[n,f,o,Ae,i]),a.useEffect(()=>()=>{ee.current+=1},[]);const le=a.useCallback(async(d,h)=>{if(h!==ee.current)return;p(null);let u;try{u=await Un(R)}catch(q){if(h!==ee.current)return;E({type:"error",message:q.message||"ChatGPT was authorized, but the connection status could not be refreshed."});return}if(h!==ee.current)return;_(u);const D=u.find(q=>q.id===d.connectionId)||null;if(!D){E({type:"error",message:"ChatGPT was authorized, but the connection status could not be refreshed."});return}Y(D.id);try{await k?.(D)}catch(q){if(h!==ee.current)return;E({type:"error",message:`ChatGPT is connected, but this Agent could not refresh its account selection. ${q.message||"Return to the Agent and select the account again."}`,returnToAgent:!!L});return}h===ee.current&&E({type:"success",message:"ChatGPT connection authorized."})},[R,k,L]),Te=a.useCallback(async(d,h)=>{let u=d;for(;h===ee.current&&u.status==="pending";){if(await new Promise(D=>window.setTimeout(D,K)),h!==ee.current)return;try{if(u=await nc(u.connectionId,u.id,R),h!==ee.current)return;p(u)}catch(D){if(h!==ee.current)return;E({type:"error",message:D.message||"Unable to check device authorization."});return}}if(h===ee.current){if(u.status==="active"){await le(u,h);return}p(null),u.status!=="cancelled"&&E({type:"error",message:xs(u.failureCode)})}},[le,R,K]),He=a.useCallback(async d=>{const h=++ee.current;E(null),G(!1),U(d?.id||"new");try{const u=d||await tc(R);if(h!==ee.current)return;_(q=>q.some(v=>v.id===u.id)?q.map(v=>v.id===u.id?u:v):[u,...q]),Y(u.id);const D=await sc(u.id,R);if(h!==ee.current)return;p(D),window.open(D.verificationUrl,"_blank","noopener,noreferrer"),Te(D,h)}catch(u){if(h!==ee.current)return;const D=u;E({type:"error",message:D.code?xs(D.code,D.message):D.message}),await Ae(!0)}finally{h===ee.current&&U(null)}},[R,Ae,Te]),bt=a.useCallback(async()=>{if(!te)return;const d=++ee.current;U(te.connectionId);try{const h=await ac(te.connectionId,te.id,R);if(d!==ee.current)return;h.status==="active"?await le(h,d):h.status==="pending"?(p(h),U(null),Te(h,d)):(p(null),E(h.status==="cancelled"?null:{type:"error",message:xs(h.failureCode)}))}catch(h){if(d!==ee.current)return;E({type:"error",message:h.message||"Unable to cancel authorization."}),U(null),Te(te,d)}finally{d===ee.current&&U(null)}},[le,R,te,Te]),we=a.useCallback(async()=>{if(!(!te?.userCode||!navigator.clipboard?.writeText))try{await navigator.clipboard.writeText(te.userCode),G(!0)}catch{G(!1)}},[te?.userCode]),Oe=a.useCallback(async(d,h)=>{U(d.id),E(null);try{if(h==="disconnect"&&!window.confirm("Disconnect this ChatGPT connection? Agents bound to it will be unavailable until you reconnect.")||h==="remove"&&!window.confirm("Remove this ChatGPT connection and its stored credentials? This cannot be undone."))return;if(h==="remove"){await cc(d.id,R),$?.(d.id),_(D=>D.filter(q=>q.id!==d.id)),Y(D=>D===d.id?"":D),E({type:"success",message:"ChatGPT connection removed."}),window.setTimeout(()=>A.current?.focus(),0);return}const u=h==="verify"?await rc(d.id,R):h==="refresh"?await ic(d.id,R):await oc(d.id,R);u.lifecycleStatus!=="active"&&$?.(d.id),_(D=>D.map(q=>q.id===u.id?u:q)),E({type:"success",message:h==="disconnect"?"ChatGPT connection disconnected.":"ChatGPT connection verified."})}catch(u){const D=u;E({type:"error",message:D.code?xs(D.code,D.message):D.message})}finally{U(null)}},[R,$]),We=a.useCallback(async d=>{const h=O.trim();if(!(!h||Ce)){U(d.id),E(null);try{const u=await lc(d.id,h,R);_(D=>D.map(q=>q.id===u.id?u:q)),oe(null),he(""),E({type:"success",message:"Model account renamed."})}catch(u){E({type:"error",message:u.message||"Unable to rename this model account."})}finally{U(null)}}},[Ce,O,R]),ce=e.jsxs("div",{className:`${T.library} ${I?T.libraryExternal:""}`.trim(),"aria-label":"Connection list",children:[f&&ye===!0?e.jsxs("button",{ref:A,type:"button",className:"tf-button-primary tf-button-compact",onClick:()=>{He()},disabled:!!(Ce||te),children:[Ce==="new"?e.jsx(je,{size:14,className:r.spinner}):e.jsx(vt,{size:14}),"Connect ChatGPT"]}):null,e.jsx("div",{className:T.libraryList,"aria-busy":ve,children:f?ye===!1?e.jsxs("div",{className:T.libraryState,children:[e.jsx(Ws,{size:18}),e.jsx("span",{children:"Connected accounts are not enabled."})]}):ye===null||ve?e.jsxs("div",{className:T.libraryState,children:[e.jsx(je,{size:16,className:r.spinner}),e.jsx("span",{children:"Loading connections…"})]}):S.length===0?e.jsxs("div",{className:T.libraryState,children:[e.jsx(vt,{size:18}),e.jsx("span",{children:"No connections yet."})]}):S.map(d=>{const h=d.id===H;return e.jsxs("button",{type:"button",className:`${T.libraryCard} ${h?T.libraryCardSelected:""}`.trim(),"aria-pressed":h,"aria-label":`Open ${js(d)}`,onClick:()=>{Y(d.id),oe(null),he("")},children:[e.jsx("span",{className:`${T.libraryCardIcon} ${T.libraryCardLogo}`.trim(),"aria-hidden":"true",children:e.jsx("img",{src:Oa,alt:""})}),e.jsxs("span",{className:T.libraryCardBody,children:[e.jsx("strong",{children:js(d)}),e.jsxs("span",{children:["OpenAI · ",d.displayMetadata.planLabel||"ChatGPT"]})]}),e.jsx("span",{className:Ua(d.lifecycleStatus),children:za(d.lifecycleStatus)})]},d.id)}):e.jsxs("div",{className:T.libraryState,children:[e.jsx(Ws,{size:18}),e.jsx("span",{children:w?"Checking Taskforce Cloud sign-in…":"Taskforce Cloud sign-in required."})]})})]});let y;if(!f)y=e.jsxs("div",{className:r.taskforceModelConnectionsEmpty,children:[e.jsx(Ws,{size:28}),e.jsx("strong",{children:w?"Checking Taskforce Cloud sign-in":N?"Taskforce Cloud sign-in required":"Taskforce Cloud connection required"}),e.jsx("span",{children:w?"Connection management will be available after your sign-in status is resolved.":N?"Sign in to Taskforce Cloud to manage connected model accounts from this local runtime.":"Connect this local runtime to a Taskforce Cloud environment to manage connected model accounts."})]});else if(ye===!1)y=e.jsxs("div",{className:r.taskforceModelConnectionsEmpty,children:[e.jsx(Ws,{size:28}),e.jsx("strong",{children:"Connected accounts are not enabled"}),e.jsx("span",{children:"Contact a Taskforce administrator to enable subscription-backed models for this account."})]});else if(ye===null)y=M?.type==="error"?e.jsxs("div",{className:r.taskforceAgentTestError,role:"alert",children:[e.jsx(st,{size:14}),e.jsx("span",{children:M.message}),e.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>{Ae()},disabled:ve,children:[e.jsx(wa,{size:14})," Retry"]})]}):e.jsxs("div",{className:r.taskforceModelConnectionsLoading,children:[e.jsx(je,{size:18,className:r.spinner})," Checking connection access"]});else{const d=_e,h=d?Ce===d.id:!1,u=d?.lifecycleStatus==="pending"||d?.lifecycleStatus==="reconnect_required"||d?.lifecycleStatus==="disconnected";y=e.jsxs(e.Fragment,{children:[e.jsx("header",{className:r.taskforceModelConnectionsHeader,children:e.jsxs("div",{children:[e.jsx("span",{className:"tf-heading-section",children:te?"Add connection":d?"Connection details":"Connections"}),e.jsx("p",{className:"tf-text-secondary",children:"Authorize accounts used by your Taskforce Agents in this environment."})]})}),M?e.jsxs("div",{className:M.type==="error"?r.taskforceAgentTestError:r.taskforceAgentTestNotice,role:M.type==="error"?"alert":"status",children:[M.type==="error"?e.jsx(st,{size:14}):e.jsx(Zt,{size:14}),e.jsx("span",{children:M.message}),M.returnToAgent?e.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:L,children:"Return to Agent"}):null]}):null,te?e.jsxs("section",{className:`${r.taskforceModelConnectionCard} ${r.taskforceModelConnectionLogin}`,children:[e.jsxs("div",{className:r.taskforceModelConnectionCardHeader,children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Authorize ChatGPT"}),e.jsx("span",{children:"Enter this one-time code in the browser window."})]}),e.jsxs("span",{className:"tf-chip-warning",children:[e.jsx(je,{size:12,className:r.spinner})," Waiting"]})]}),e.jsxs("div",{className:r.taskforceModelConnectionCodeRow,children:[e.jsx("code",{children:te.userCode}),e.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>{we()},title:ae?"Authorization code copied":"Copy authorization code","aria-label":ae?"Authorization code copied":"Copy authorization code",children:ae?e.jsx(Zt,{size:15}):e.jsx(Qa,{size:15})}),e.jsx("span",{role:"status","aria-live":"polite",children:ae?"Code copied.":""}),e.jsxs("a",{className:"tf-button-secondary tf-button-compact",href:te.verificationUrl,target:"_blank",rel:"noreferrer",children:[e.jsx(Xa,{size:14})," Open ChatGPT"]}),e.jsxs("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:()=>{bt()},children:[e.jsx(yt,{size:14})," Cancel"]})]})]}):ve?e.jsxs("div",{className:r.taskforceModelConnectionsLoading,children:[e.jsx(je,{size:18,className:r.spinner})," Loading connections"]}):d?e.jsxs("section",{className:r.taskforceModelConnectionCard,children:[e.jsxs("div",{className:r.taskforceModelConnectionCardHeader,children:[e.jsxs("div",{className:r.taskforceModelConnectionIdentity,children:[e.jsx("span",{className:r.taskforceModelConnectionLogo,children:e.jsx("img",{src:Oa,alt:""})}),e.jsxs("div",{className:r.taskforceModelConnectionIdentityText,children:[Ne===d.id?e.jsxs("div",{className:r.taskforceModelConnectionNameEditor,children:[e.jsx("input",{className:r.input,value:O,onChange:D=>he(D.target.value),"aria-label":"Model account name",maxLength:80,autoFocus:!0}),e.jsx("button",{type:"button",className:"tf-control-icon","aria-label":"Save model account name",title:"Save name",onClick:()=>{We(d)},disabled:h||!O.trim(),children:h?e.jsx(je,{size:14,className:r.spinner}):e.jsx(Zt,{size:14})}),e.jsx("button",{type:"button",className:"tf-control-icon","aria-label":"Cancel model account rename",title:"Cancel",onClick:()=>{oe(null),he("")},disabled:h,children:e.jsx(yt,{size:14})})]}):e.jsxs("div",{className:r.taskforceModelConnectionNameRow,children:[e.jsx("strong",{children:js(d)}),e.jsx("button",{type:"button",className:"tf-control-icon","aria-label":`Rename ${js(d)}`,title:"Rename model account",onClick:()=>{oe(d.id),he(js(d))},children:e.jsx(Za,{size:13})})]}),e.jsx("span",{children:"OpenAI · ChatGPT/Codex subscription"})]})]}),e.jsx("span",{className:Ua(d.lifecycleStatus),children:za(d.lifecycleStatus)})]}),e.jsxs("div",{className:r.taskforceModelConnectionMeta,children:[e.jsx("span",{children:d.displayMetadata.planLabel||"Subscription plan"}),e.jsx("span",{children:pc(d)})]}),d.failureCode?e.jsx("span",{className:"tf-text-warning",children:xs(d.failureCode)}):null,e.jsxs("div",{className:r.taskforceModelConnectionActions,children:[u?e.jsxs("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:()=>{He(d)},disabled:!!(Ce||te),children:[h?e.jsx(je,{size:14,className:r.spinner}):e.jsx(nn,{size:14}),d.lifecycleStatus==="pending"?"Authorize":"Reconnect"]}):null,d.lifecycleStatus==="active"?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>{Oe(d,"verify")},disabled:h,children:[e.jsx(Zt,{size:14})," Verify"]}),e.jsxs("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:()=>{Oe(d,"refresh")},disabled:h,title:"Refresh ChatGPT account status",children:[e.jsx(wa,{size:14})," Refresh"]}),e.jsxs("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:()=>{Oe(d,"disconnect")},disabled:h,children:[e.jsx(Ni,{size:14})," Disconnect"]})]}):null,d.lifecycleStatus==="pending"||d.lifecycleStatus==="reconnect_required"||d.lifecycleStatus==="disconnected"||d.lifecycleStatus==="revoked"?e.jsxs("button",{type:"button",className:"tf-button-destructive tf-button-compact",onClick:()=>{Oe(d,"remove")},disabled:h,children:[e.jsx(Ai,{size:14})," Remove"]}):null]})]}):e.jsxs("div",{className:r.taskforceModelConnectionsEmpty,children:[e.jsx(vt,{size:28}),e.jsx("strong",{children:S.length===0?"No connected accounts":"Select a connection"}),e.jsx("span",{children:S.length===0?"Connect ChatGPT to run eligible Codex Agents with your subscription.":"Choose an account from the Connection Library to view and manage it."})]})]})}return e.jsxs("div",{className:`${r.taskforceModelConnectionsRoot} ${I?r.taskforceModelConnectionsRootExternalLibrary:""}`.trim(),children:[I?qa.createPortal(ce,I):ce,e.jsx("div",{className:r.taskforceModelConnectionsWorkspace,children:y})]})}const Ga="Be concise and actionable.",ht="New Taskforce Agent",gc="Message this agent...",vc=1e4,yc=[{key:"taskforce_managed",label:"Taskforce Managed"}],ks="connection:",dr=20,ur=250;async function bc(t,n,i,o){for(let f=0;;f+=1)try{return await uc(t,n,i)}catch(w){if(!(o&&w instanceof ct&&w.code==="TASKFORCE_AGENT_NOT_FOUND"&&f<dr))throw w;await new Promise(x=>window.setTimeout(x,ur))}}function Ba(t){return String(t.displayMetadata.displayName||t.displayMetadata.accountLabel||t.displayMetadata.accountEmail||"ChatGPT subscription")}function en(t){return t?.source==="personal_byom"||t?.source==="subscription_dev"?"personal_connection":"taskforce_managed"}function Rn(t,n){return en(t)===n}const Qt=[{id:"agents",label:"Agents"},{id:"roles",label:"Roles"},{id:"skills",label:"Skills"},{id:"connections",label:"Connections"},{id:"resources",label:"Resources"}];function Ha(t){const n=t?.usage?.totalTokens;return n==null?"Not reported":`${n} tokens`}function En(t){return t?.latencyMs===void 0||t?.latencyMs===null?"Not reported":`${t.latencyMs} ms`}function In(t){return t?.avatarUrl?Va(t.avatarUrl,t.avatarRevision,t.avatarUpdatedAt):""}function xc(t){return t?.avatarSourceUrl?Va(t.avatarSourceUrl,t.avatarRevision,t.avatarUpdatedAt):""}function $n({src:t,fallbackSize:n}){const{activeImageUrl:i,handleImageError:o}=li(t);return i?e.jsx("img",{src:i,alt:"",onError:o}):e.jsx(Xt,{size:n})}function Fa(t){return new Promise((n,i)=>{const o=new FileReader;o.onload=()=>n(String(o.result||"")),o.onerror=()=>i(new Error("Failed to read image file.")),o.readAsDataURL(t)})}function $t(t){if(t==null||t==="")return null;const n=Number(t);return Number.isFinite(n)?Math.max(0,Math.floor(n)):null}function jc(t){const n=String(t||"").replace(/\s+/g," ").trim();return n.length>260?`${n.slice(0,257).trim()}...`:n}function kc(t){return/^\s*(?:<!doctype\s+html|<html\b)/i.test(String(t||""))}function Ka(t){return"Taskforce HQ"}function Ln(t){return t==="fast"?"Fast":t==="advanced"?"Advanced":"Balanced"}function Sc(t){return t==="verified"?"Verified":t==="configured"?"Configured":"Unavailable"}const Cc=/(token|secret|password|credential|api[-_]?key|access[-_]?key)/i,Pn=2e4;function sn(t,n=!0){return Array.isArray(t)?t.map(i=>sn(i,n)):!t||typeof t!="object"?typeof t!="string"?t:n&&t.length>240?`${t.slice(0,237).trim()}...`:t:Object.fromEntries(Object.entries(t).map(([i,o])=>[i,Cc.test(i)?"[redacted]":sn(o,n)]))}function Nc(t){const n=sn(t||{}),i=JSON.stringify(n,null,2);return i.length>700?`${i.slice(0,697).trim()}...`:i}function Ac(t){const n=String(t||"").replace(/\s+/g," ").trim();return n?n.length>320?`${n.slice(0,317).trim()}...`:n:"No result text returned."}function wc(t){const n=String(t.resultText||"No result text returned."),i=n.length>Pn?`${n.slice(0,Pn)}
22
+ [Result truncated after ${Pn.toLocaleString()} characters]`:n;return[`Tool: ${t.name}`,`Status: ${t.ok?"ok":"failed"}`,"Arguments",JSON.stringify(sn(t.arguments||{},!1),null,2),"Result",i].join(`
23
+ `)}function _c(t){const n=t.length;if(n===0)return"No tools used";const i=t.filter(f=>!f.ok).length,o=n===1?"tool":"tools";return i>0?`${n} ${o} used, ${i} failed`:`${n} ${o} used`}function Tc(t){const n=t.length,i=t.filter(f=>!f.ok).length,o=n===1?"tool":"tools";return i>0?`Used ${n} Taskforce ${o}; ${i} failed.`:`Used ${n} Taskforce ${o}.`}function Rc(t){return typeof t=="number"&&Number.isFinite(t)?`${t.toLocaleString()} tokens`:"Not configured"}function Ec(t,n){return t.role==="user"?"You":t.agentName||n}function Ic(t){return{id:t.id,workspaceId:t.workspaceId,agentId:t.agentId,taskId:t.taskId,taskReference:t.taskReference,taskTitle:t.taskTitle,context:t.context,title:t.title||t.messages.find(n=>n.role==="user")?.content||"Agent chat",messageCount:t.messages.length,modelProvider:t.modelProvider,modelId:t.modelId,usage:t.usage,latencyMs:t.latencyMs,createdAt:t.createdAt,updatedAt:t.updatedAt}}function Gn(t){const n=t?.context?.type==="task"?t.context:null,i=String(n?.taskId||t?.taskId||"").trim();if(!i)return null;const o=String(n?.taskReference||t?.taskReference||"").trim(),f=String(n?.taskTitle||t?.taskTitle||"").trim();return{type:"task",taskId:i,taskReference:o,taskTitle:f}}function fr(t,n){return t?!n||n.taskId!==t.taskId?t:{type:"task",taskId:t.taskId,taskReference:t.taskReference||n.taskReference,taskTitle:t.taskTitle||n.taskTitle}:null}function mr(t){const n=String(t.taskReference||"").trim(),i=String(t.taskTitle||"").trim();return n?`${n}${i?` · ${i}`:""}`:i||"Linked task"}function $c(t,n=null){const i=String(t.title||"Agent chat").trim()||"Agent chat",o=Number(t.messageCount||0),f=Gn(t),w=f?fr(f,n):null,N=o>0?`${i} (${o})`:i;return w?`${mr(w)} · ${N}`:N}function Fc({workspaceId:t,agentRosterTrayOpen:n=!0,onCloseAgentRosterTray:i,launchContext:o=null,onClearLaunchContext:f,onOpenTaskContext:w,taskReferences:N,surface:x="module",runtimeMode:k="local",cloudAuthConfigured:$=!1,authSessionResolved:L=!0,isAuthenticated:K=!1,resolveCloudAuthUrl:I,theme:R="dark",rememberedAgentId:S,rememberedConversationId:_,rememberedConversationByAgentId:H,rememberedSelectionReady:Y=!0,onRememberSelection:z,onRenderDrawerHeader:ie}){const ve=a.useRef(1),Se=a.useRef(null),Ce=a.useRef(null),U=a.useRef(null),te=a.useRef(!1),p=a.useRef(!1),M=a.useRef(null),E=a.useRef(0),ae=a.useRef(0),G=a.useRef(0),Ne=a.useRef(0),oe=a.useRef(0),O=[t,String(o?.taskId||""),String(o?.taskReference||""),String(o?.taskTitle||"")].join(`
24
+ `),he=a.useRef(O);he.current=O;const ee=a.useRef(null),ge=a.useRef({agents:null,roles:null,skills:null,connections:null,resources:null}),[A,ye]=a.useState("agents"),_e=a.useCallback((s,l=!1)=>{ye(s),l&&window.setTimeout(()=>ge.current[s]?.focus(),0)},[]),[Ae,le]=a.useState(0),[Te,He]=a.useState(null),[bt,we]=a.useState(null),[Oe,We]=a.useState(null),[ce,y]=a.useState([]),[d,h]=a.useState(()=>k==="local"?ba.filter(xa):[]),[u,D]=a.useState(null),[q,v]=a.useState(""),[F,Q]=a.useState("taskforce_hq"),[Z,ke]=a.useState("taskforce_managed"),[fe,$e]=a.useState([]),[me,xt]=a.useState(""),[Fe,Mt]=a.useState(null),[be,jt]=a.useState(ja),[pe,kt]=a.useState(ka),[an,St]=a.useState("balanced"),[de,Re]=a.useState(()=>Ss(null,{systemPrompt:Ga})),Vn=de.workingGuidelines,pr=a.useCallback(s=>{p.current=!0,Re(l=>({...l,workingGuidelines:s}))},[]),[Ns,as]=a.useState(""),[hr,As]=a.useState(!1),[rn,ws]=a.useState(""),[ze,_s]=a.useState(null),[rs,Ts]=a.useState([]),[Rs,Dt]=a.useState([]),[gr,Ot]=a.useState(!1),[on,Ct]=a.useState(""),[ln,Je]=a.useState(""),[zt,is]=a.useState(!1),[Wn,Ut]=a.useState(null),[Lc,at]=a.useState([]),[Es,Is]=a.useState(null),[cn,Nt]=a.useState(""),[Pc,vr]=a.useState(()=>[{id:ve.current++,type:"info",message:"Ready to run this agent through the server-side model gateway.",timestamp:new Date().toLocaleTimeString()}]),[Le,Jn]=a.useState(!1),[dn,Yn]=a.useState(""),[Ye,un]=a.useState(null),[Gt,fn]=a.useState(null),[Qn,mn]=a.useState([]),[Xn,Bt]=a.useState(""),[os,pn]=a.useState(!1),[Zn,yr]=a.useState(!1),[Ht,ea]=a.useState(!1),[ta,hn]=a.useState(""),[br,xr]=a.useState(0),gn=a.useRef(!1),[jr,sa]=a.useState(!1),[rt,Ft]=a.useState(!1),[vn,na]=a.useState(!1),[ls,Qe]=a.useState(null),[$s,Ls]=a.useState(null),[Ps,aa]=a.useState(()=>new Set),[kr,dt]=a.useState({}),[Sr,ra]=a.useState(!1),[ia,Ms]=a.useState(!1),[Cr,Xe]=a.useState(null),[Nr,At]=a.useState(null),[yn,oa]=a.useState(!1),[cs,bn]=a.useState(()=>new Set),wt=a.useRef(new Map),it=a.useRef(null),ut=a.useRef(0),Ar=a.useMemo(()=>{const s=yc.filter(c=>d.some(m=>Rn(m,c.key))).map(c=>({key:c.key,label:c.label})),l=fe.filter(c=>c.lifecycleStatus==="active"&&d.some(m=>m.source==="subscription_dev"&&m.providerKey===c.providerKey));for(const c of l)s.push({key:`${ks}${c.id}`,label:`${Ba(c)} · ${Wt(c.providerKey)}`});if(Z==="personal_connection"&&me&&!l.some(c=>c.id===me)){const c=fe.find(m=>m.id===me);s.push({key:`${ks}${me}`,label:`${c?Ba(c):"Connected account"} (unavailable)`,disabled:!0})}else Z==="personal_connection"&&!me&&s.push({key:Fe?.bound&&Fe.ownerIsCaller===!1?"connected-account-private":"connected-account-unavailable",label:Fe?.bound&&Fe.ownerIsCaller===!1?"Connected account managed by another user":"Connected account unavailable",disabled:!0});return s},[Fe?.bound,Fe?.ownerIsCaller,d,fe,Z,me]),wr=Z==="taskforce_managed"?"taskforce_managed":me?`${ks}${me}`:Fe?.bound&&Fe.ownerIsCaller===!1?"connected-account-private":"connected-account-unavailable",ds=a.useMemo(()=>fe.find(s=>s.id===me)||null,[fe,me]),ft=a.useMemo(()=>d.filter(s=>Rn(s,Z)&&(Z==="taskforce_managed"||!ds||s.providerKey===ds.providerKey)),[d,Z,ds]),_r=a.useMemo(()=>ai.filter(s=>ft.some(l=>l.providerKey===s.key)||s.key===be),[be,ft]),Kt=a.useMemo(()=>ft.filter(s=>s.providerKey===be),[be,ft]),Ds=a.useCallback((s,l)=>{const c=qs(l),m=d.filter(j=>j.providerKey===c);return String(s||"").trim()||m[0]?.key||""},[d]),Ue=a.useMemo(()=>Kt.find(s=>s.key===pe)||null,[pe,Kt]),xn=a.useMemo(()=>d.some(s=>s.source==="subscription_dev"),[d]),P=a.useMemo(()=>ce.find(s=>s.id===u)||null,[ce,u]),Os=a.useMemo(()=>String(S||"").trim(),[S]),la=a.useMemo(()=>String(_||"").trim(),[_]),zs=a.useMemo(()=>{const s={};return Object.entries(H||{}).forEach(([l,c])=>{const m=String(l||"").trim(),b=String(c||"").trim();!m||!b||(s[m]=b)}),s},[H]),Ze=k==="local"&&$,Tr=!Ze||L&&K&&!!I,jn=!(k==="local"&&$)||L&&K,_t=k==="cloud"||$&&L&&K&&!!I,Rr=k==="local"&&$&&!L,Tt=a.useMemo(()=>In(P),[P]),Er=a.useMemo(()=>xc(P),[P]),Rt=!!(u&&cs.has(u)),Us=u&&kr[u]||null,mt=a.useMemo(()=>rs.find(s=>s.id===ze)||null,[ze,rs]),Ee=a.useMemo(()=>{const s=String(o?.taskId||"").trim();if(!s)return null;const l=String(o?.taskReference||"").trim(),c=String(o?.taskTitle||"").trim();return{type:"task",taskId:s,taskReference:l,taskTitle:c}},[o?.taskId,o?.taskReference,o?.taskTitle]),ca=a.useMemo(()=>Gn(mt),[mt]),et=ze?ca?fr(ca,Ee):null:Ee,Ir=et?mr(et):"",$r=!!(et&&Ee&&!ze),Gs=a.useMemo(()=>{const s=String(mt?.agentId||u||"").trim();return ce.find(l=>l.id===s)||null},[ce,u,mt?.agentId]),Lr=Gs?.name||P?.name||q.trim()||ht,Bs=Gs?.color||P?.color||(Gs?.id?Jt(Gs.id):P?.id?Jt(P.id):void 0),da=a.useRef(""),Ge=a.useCallback((s,l)=>{if(!z)return;const c=String(s||"").trim(),m=String(l||"").trim(),b=`${c}:${m}`;da.current!==b&&(da.current=b,z({agentId:c||null,conversationId:m||null}))},[z]),ue=a.useCallback((s,l,c)=>{vr(m=>[...m,{id:ve.current++,type:s,message:l,timestamp:new Date().toLocaleTimeString(),...c&&c.length>0?{toolActivity:c}:{}}])},[]),qt=a.useCallback(()=>{ae.current+=1,Yn(""),un(null),fn(null),mn([]),Bt(""),pn(!1)},[]),Hs=a.useCallback(s=>{const l=U.current!==s.id;E.current+=1,oe.current+=1,l&&(ut.current+=1),p.current=!1,U.current=s.id,D(s.id),v(s.name),Q("taskforce_hq");const c=d.find(m=>m.key===s.modelKey);ke(en(c||{source:s.definition?.model.modelSource})),l&&(xt(""),Mt(null)),jt(qs(s.providerKey)),kt(Ds(s.modelKey,s.providerKey)),St(s.modelTier),Re(Ss(s.definition,{systemPrompt:s.systemPrompt})),as(s.color||Jt(s.id)),As(!1),te.current=!1,_s(null),Ts([]),Dt([]),Ot(!1),Ct(""),Je(""),is(!1),Ut(null),at([]),Qe(null),qt()},[d,Ds,qt]),kn=a.useCallback(s=>{Hs(s),Ge(s.id,zs[s.id]||null)},[Hs,zs,Ge]),Et=a.useCallback(s=>{E.current+=1;const l=Array.isArray(s?.messages)?s.messages:[],c=[...l].reverse().find(m=>m.role==="assistant");_s(s?.id||null),Dt(l),Ot(!1),Ct(""),Je(""),is(!1),Ut(c?{text:c.content,provider:s?.modelProvider||"taskforce_hq",modelId:s?.modelId||"Not reported",latencyMs:s?.latencyMs??null,usage:s?.usage||null}:null)},[]),us=a.useCallback(s=>{const l=Ic(s);Ts(c=>{const m=c.filter(b=>b.id!==l.id);return[l,...m]})},[]),ua=a.useCallback(()=>{E.current+=1,oe.current+=1,p.current=!1,U.current=null,D(null),v(""),Q("taskforce_hq"),ke("taskforce_managed"),jt(ja),kt(ka),St("balanced"),Re(Ss(null,{systemPrompt:Ga})),as(""),As(!1),te.current=!1,_s(null),Ts([]),Dt([]),Ot(!1),Ct(""),Je(""),is(!1),Ut(null),at([]),Qe(null),qt(),Ge(null,null)},[Ge,qt]),Fs=a.useCallback(s=>{if(s.type==="new"){ua(),ue("info","Started a new Taskforce agent draft.");return}kn(s.agent)},[ue,ua,kn]),fs=a.useCallback(s=>{if(!(s.type==="agent"&&s.agent.id===U.current)){if(!p.current){Fs(s);return}Ls(s)}},[Fs]),Pr=a.useCallback(()=>{if(!$s)return;const s=$s;Ls(null),p.current=!1,Fs(s)},[$s,Fs]);a.useEffect(()=>{const s=l=>{p.current&&(l.preventDefault(),l.returnValue="")};return window.addEventListener("beforeunload",s),()=>window.removeEventListener("beforeunload",s)},[]);const Sn=a.useCallback(async(s,l,c=()=>U.current===s)=>{Ft(!0);try{const m=await fetch(`/api/taskforce/agents/${encodeURIComponent(s)}/conversation?workspaceId=${encodeURIComponent(t)}&conversationId=${encodeURIComponent(l)}`,{credentials:"include"}),b=typeof m.clone=="function"?await m.clone().text().catch(()=>""):"",j=await m.json().catch(()=>({}));if(!c())return;if(!m.ok||j?.success===!1){const V=m.status===404?"Taskforce agent conversation API route is not available. Restart the app server so the latest routes are active.":`Unable to load saved agent conversation. HTTP ${m.status||"unknown"}.`;ue("error",String(j?.error||b||V));return}const g=j?.conversation||null;Et(g),g&&us(g),Ge(s,g?.id||null),at([])}catch(m){c()&&ue("error",String(m?.message||m||"Unable to load saved agent conversation."))}finally{c()&&Ft(!1)}},[ue,Et,Ge,us,t]),ms=a.useCallback(async(s,l)=>{sa(!0),Ft(!0);try{const c=await fetch(`/api/taskforce/agents/${encodeURIComponent(s)}/conversations?workspaceId=${encodeURIComponent(t)}`,{credentials:"include"}),m=typeof c.clone=="function"?await c.clone().text().catch(()=>""):"",b=await c.json().catch(()=>({}));if(!l())return;if(!c.ok||b?.success===!1){const g=c.status===404?"Taskforce agent conversation API route is not available. Restart the app server so the latest routes are active.":`Unable to load saved agent conversations. HTTP ${c.status||"unknown"}.`;ue("error",String(b?.error||m||g));return}const j=Array.isArray(b?.conversations)?b.conversations:[];if(Ts(j),j.length>0){const g=zs[s]||(s===Os?la:""),V=g?j.find(C=>C.id===g):null,se=Ee?j.find(C=>Gn(C)?.taskId===Ee.taskId):null,re=V?.id||se?.id||(Ee?null:j[0].id);re?await Sn(s,re,l):(Et(null),Ge(s,null),at([]))}else Et(null),Ge(s,null),at([])}catch(c){l()&&ue("error",String(c?.message||c||"Unable to load saved agent conversations."))}finally{l()&&(sa(!1),Ft(!1))}},[ue,Et,Sn,Os,zs,la,Ge,Ee,t]),ps=a.useCallback((s,l=!1)=>{const c=ee.current;if(c?.agentId===s&&c.loader===ms&&!l)return c.promise||Promise.resolve();const m=++G.current,b=Ne.current,g=ms(s,()=>U.current===s&&G.current===m&&Ne.current===b).finally(()=>{ee.current?.promise===g&&(ee.current={agentId:s,loader:ms,promise:null})});return ee.current={agentId:s,loader:ms,promise:g},g},[ms]),tt=a.useCallback(async s=>{const l=s?.quiet===!0;l||(ea(!0),Qe(null));try{const c=await fetch(`/api/taskforce/agents?workspaceId=${encodeURIComponent(t)}`,{credentials:"include"}),m=typeof c.clone=="function"?await c.clone().text().catch(()=>""):"",b=await c.json().catch(()=>({}));if(!c.ok||b?.success===!1){const re=c.status===404?"Taskforce agent API route is not available. Restart the app server so the latest routes are active.":`Unable to load saved agents. HTTP ${c.status||"unknown"}.`,C=String(b?.error||m||re);ue("error",C),l||Qe({type:"error",message:C});return}const j=Array.isArray(b?.agents)?b.agents:[],g=k==="local"&&$&&L&&K&&!!I;Array.isArray(b?.modelCatalog)&&!g?h(b.modelCatalog):k==="cloud"&&h([]),Ce.current=t,y(re=>{const C=new Map(re.map(J=>[J.id,J]));return j.map(J=>{const ne=wt.current.get(J.id),B=$t(J.avatarRevision);if(ne===void 0||B!==null&&B>=ne)return J;const X=C.get(J.id);return X?{...J,profileId:X.profileId||J.profileId||null,avatarUrl:X.avatarUrl,avatarSourceUrl:X.avatarSourceUrl,avatarRevision:X.avatarRevision,avatarUpdatedAt:X.avatarUpdatedAt}:J})}),bn(re=>{let C=null;for(const J of re){const ne=wt.current.get(J),B=j.find(Be=>Be.id===J),X=$t(B?.avatarRevision);ne===void 0||X===null||X<ne||(C??=new Set(re),C.delete(J),wt.current.delete(J))}return C||re});const V=U.current,se=V?j.find(re=>re.id===V):null;se&&!te.current&&as(se.color||Jt(se.id))}catch(c){const m=String(c?.message||c||"Unable to load saved agents.");ue("error",m),l||Qe({type:"error",message:m})}finally{l||ea(!1)}},[ue,L,$,K,I,k,t]);a.useEffect(()=>{qt()},[qt,t]),a.useEffect(()=>{tt()},[tt]),a.useEffect(()=>{if(k!=="local")return;const s=ba.filter(xa);if(!$||!L||!K||!I){gn.current&&h(s),gn.current=!1,hn("");return}gn.current=!0,h([]),hn("");let l=!1;return(async()=>{try{const c=await fetch(I("/api/taskforce/agents/model-catalog"),{credentials:"include"}),m=await c.json().catch(()=>({}));if(!c.ok||m?.success===!1||!Array.isArray(m?.modelCatalog))throw new Error("Cloud model catalog unavailable.");l||h(m.modelCatalog)}catch{l||hn("Unable to load models from Taskforce Cloud. Check your connection and try again.")}})(),()=>{l=!0}},[L,$,K,br,I,k,t]),a.useEffect(()=>{if(!xn||!_t){$e([]);return}let s=!1;return Un({workspaceId:t,resolveApiUrl:I}).then(l=>{s||$e(l)}).catch(()=>{s||$e([])}),()=>{s=!0}},[A,Ae,_t,I,xn,t]),a.useEffect(()=>{const s=P?.definition?.model.modelSource==="subscription_dev";if(!u||!s||!_t){Mt(null),s||xt("");return}if(it.current===u)return;const l=++ut.current;let c=!1;return dc(u,{workspaceId:t,resolveApiUrl:I}).then(m=>{c||l!==ut.current||it.current===u||p.current||(Mt(m),xt(m.ownerIsCaller?String(m.connectionId||""):""))}).catch(()=>{c||l!==ut.current||it.current===u||p.current||(Mt(null),xt(""))}),()=>{c=!0}},[_t,I,P?.definition?.model.modelSource,u,t]),a.useEffect(()=>{if(d.length===0)return;const s=d.find(c=>c.key===pe);if(s){const c=en(s);c!==Z&&ke(c),s.providerKey!==be&&jt(s.providerKey);return}if(u&&pe)return;const l=ft.find(c=>c.providerKey===be)||ft[0]||d[0];ke(en(l)),jt(l.providerKey),kt(l.key),St(l.defaultTier)},[d,pe,Z,be,u,ft]),a.useEffect(()=>{if(!Y||Ce.current!==t||Se.current===t)return;if(ce.length===0){if(Ht)return;Ge(null,null);return}Se.current=t;const s=ce.find(l=>l.id===Os);p.current||Hs(s||ce[0])},[ce,Hs,Ht,Os,Y,Ge,t]),a.useEffect(()=>{const s=l=>{const c=l.detail;if((String(c?.workspaceId||"").trim()||"default")!==t)return;const b=c?.reason;if(!(b==="sync-apply"||b==="agent-avatar-upload"||b==="agent-avatar-remove"||b==="agent-avatar-generate"&&!Ze)||(tt({quiet:!0}),b!=="sync-apply"))return;const g=String(c?.agentId||"").trim(),V=U.current;V&&(!g||g===V)&&ps(V,!0)};return window.addEventListener(ss,s),()=>window.removeEventListener(ss,s)},[tt,Ze,ps,t]),a.useEffect(()=>{const s=l=>{const c=l.detail;if((String(c?.workspaceId||"").trim()||"default")!==t||c?.origin==="taskforce-agents-module")return;const b=c?.taskforceAgentAvatar,j=String(b?.agentId||"").trim();if(b&&j){const g=$t(b.avatarRevision)??0;Ze&&(wt.current.set(j,g),bn(V=>new Set(V).add(j))),y(V=>V.map(se=>se.id===j?{...se,profileId:c.profileId||se.profileId||null,avatarUrl:b.avatarUrl,avatarSourceUrl:b.avatarSourceUrl,avatarRevision:g,avatarUpdatedAt:b.avatarUpdatedAt}:se))}tt({quiet:!0})};return window.addEventListener(Sa,s),()=>window.removeEventListener(Sa,s)},[tt,Ze,t]),a.useEffect(()=>{const s=window.setInterval(()=>{tt({quiet:!0})},vc);return()=>window.clearInterval(s)},[tt]),a.useEffect(()=>{U.current=u},[u]),a.useEffect(()=>{u&&ps(u)},[u,ps]),a.useEffect(()=>{if(cs.size===0)return;const s=window.setInterval(()=>{tt()},4e3);return()=>window.clearInterval(s)},[cs.size,tt]),a.useEffect(()=>{if(!(x!=="taskDrawer"||!ie))return ie(e.jsxs("div",{className:r.taskforceAgentDrawerAgentHeader,children:[e.jsxs("button",{type:"button",className:`${r.taskforceAgentDrawerAgentAvatar} ${r.taskforceAgentDrawerAgentAvatarButton} ${Rt?r.taskforceAgentAvatarSyncing:""}`.trim(),onClick:()=>oa(s=>!s),disabled:!u,title:P?`View ${P.name} profile`:"Select an agent to view profile","aria-label":P?`View ${P.name} profile`:"View agent profile","aria-expanded":yn,children:[Tt?e.jsx($n,{src:Tt,fallbackSize:16}):e.jsx(Xt,{size:16}),Rt?e.jsx(je,{size:12,className:`${r.spinner} ${r.taskforceAgentAvatarSyncIcon}`}):null]}),e.jsx("label",{className:r.taskforceAgentDrawerAgentPicker,children:e.jsx("select",{className:r.select,value:u||"",onChange:s=>{const l=ce.find(c=>c.id===s.target.value);l&&fs({type:"agent",agent:l})},disabled:!Y||Ht||ce.length===0||Le,"aria-label":"Agent",children:ce.length>0?ce.map(s=>e.jsx("option",{value:s.id,children:s.name},s.id)):e.jsx("option",{value:"",children:"No agents configured"})})})]})),()=>ie(null)},[ce,yn,Rt,Ht,ie,fs,P,Tt,u,x,Le]),a.useEffect(()=>{Ee&&ue("info",`Task context attached: ${Ee.taskReference}.`)},[ue,Ee]),a.useEffect(()=>{M.current?.scrollIntoView?.({block:"end"})},[Rs.length,rt,Le]);const fa=a.useCallback(()=>zl({baseDefinition:P?.definition,draft:de,name:q.trim()||ht,providerKey:be,modelKey:pe,tier:Ue?.defaultTier||an,connectionScope:Ue?.source==="subscription_dev"?_t?"personal":"local_dev":void 0}),[q,de,pe,an,_t,be,P?.definition,Ue?.defaultTier,Ue?.source]),Mr=a.useCallback(async s=>{le(l=>l+1)},[]),Dr=a.useCallback(s=>{$e(l=>l.filter(c=>c.id!==s))},[]),Or=async()=>{const s=q.trim(),l=de.purpose.trim();if(!s||!l||!pe||vn)return;const c=!u,m=fa(),b=m.model.modelSource==="subscription_dev",j=!!(u&&Fe?.bound&&Fe.ownerIsCaller===!1&&P?.definition?.model.modelSource==="subscription_dev"&&P.providerKey===m.model.providerKey),g=me;if(b&&!g&&!j){Qe({type:"error",message:"Select a connected model account before saving this Agent."});return}na(!0),Qe(null);try{const V=u?`/api/taskforce/agents/${encodeURIComponent(u)}`:"/api/taskforce/agents",se=await fetch(V,{method:u?"PATCH":"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t,definition:m,lifecycleStatus:P?.lifecycleStatus||(P?.enabled===!1?"disabled":"active"),...u?{expectedDefinitionHash:P?.definitionHash}:{},...hr&&Ns?{signatureColor:Ns}:{}})}),re=await se.json().catch(()=>({}));if(!se.ok||re?.success===!1||!re?.agent){const B=re?.code==="TASKFORCE_AGENT_DEFINITION_CONFLICT"?"This Agent changed after you opened it. Your draft is preserved; reload the Agent before saving again.":String(re?.error||"Unable to save agent.");ue("error",B),Qe({type:"error",message:B});return}const C=re.agent;p.current=!1,y(B=>B.some(Be=>Be.id===C.id)?B.map(Be=>Be.id===C.id?C:Be):[C,...B]),c?kn(C):(v(C.name),Q("taskforce_hq"),jt(qs(C.providerKey)),kt(Ds(C.modelKey,C.providerKey)),St(C.modelTier),Re(Ss(C.definition,{systemPrompt:C.systemPrompt})),as(C.color||Jt(C.id)),As(!1),te.current=!1);let J="";if(b&&g){const B=++ut.current;it.current=C.id;try{const X=await bc(C.id,g,{workspaceId:t,resolveApiUrl:I},k==="local");U.current===C.id&&ut.current===B&&(Mt(X),xt(g))}catch(X){J=X.message||"The selected model account could not be assigned."}finally{it.current===C.id&&(it.current=null)}}else if(!b&&Fe?.bound&&Fe.ownerIsCaller){const B=++ut.current;it.current=C.id;try{await fc(C.id,{workspaceId:t,resolveApiUrl:I}),U.current===C.id&&ut.current===B&&(Mt(null),xt(""))}catch{}finally{it.current===C.id&&(it.current=null)}}const ne=J?`Saved ${C.name}, but the model account could not be assigned. ${J}`:`Saved ${C.name}.`;ue(J?"error":"success",ne),U.current===C.id&&Qe({type:J?"error":"success",message:ne}),lt({workspaceId:t,agentId:C.id,reason:"agent-save"}),C.profileId&&Vs({workspaceId:t,profileId:C.profileId,reason:"update",origin:"taskforce-agents-module"}),c&&!In(C)&&ma(C)}catch(V){const se=String(V?.message||V||"Unable to save agent.");ue("error",se),Qe({type:"error",message:se})}finally{na(!1)}};async function ma(s){const l=s.id;if(!l||Ps.has(l))return!1;if(!Tr){const c=L?"Sign in to Taskforce Cloud to generate agent avatars.":"Cloud sign-in is still loading. Try again in a moment.";return dt(m=>({...m,[l]:{error:c,notice:null}})),!1}aa(c=>new Set(c).add(l)),Xe(null),At(null),dt(c=>({...c,[l]:{error:null,notice:null}}));try{const c=`/api/taskforce/agents/${encodeURIComponent(l)}/avatar/generate`,m=Ze&&I?I(c):c,b=await fetch(m,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t})}),j=typeof b.clone=="function"?await b.clone().text().catch(()=>""):"",g=await b.json().catch(()=>({}));if(!b.ok||g?.success===!1||!g?.agent){const J=b.status?`Unable to generate agent avatar. HTTP ${b.status}.`:"Unable to generate agent avatar.",ne=g?.details&&typeof g.details=="object"?g.details:null,B=[typeof ne?.modelId=="string"&&ne.modelId?`model ${ne.modelId}`:"",typeof ne?.region=="string"&&ne.region?`region ${ne.region}`:""].filter(Boolean),X=B.length?` Tried ${B.join(" in ")}.`:"",Be=kc(j)?`${J} Please try again.`:jc(j),pt=`${String(g?.error||Be||J)}${X}`;return dt(Ks=>({...Ks,[l]:{error:pt,notice:null}})),!1}const V=g.agent,se=typeof g?.avatar?.profileId=="string"?g.avatar.profileId.trim():"",re=Ze&&I?{...V,avatarUrl:V.avatarUrl?Aa(V.avatarUrl):V.avatarUrl,avatarSourceUrl:V.avatarSourceUrl?Aa(V.avatarSourceUrl):V.avatarSourceUrl}:V,C={...re,profileId:re.profileId||se||s.profileId||null};if(y(J=>J.map(ne=>ne.id===C.id?{...ne,...C,profileId:C.profileId||ne.profileId||null}:ne)),Ze){const J=$t(C.avatarRevision)??$t(g?.avatar?.avatarRevision)??0;wt.current.set(C.id,J),bn(ne=>new Set(ne).add(C.id)),dt(ne=>({...ne,[l]:{error:null,notice:`Generated photo for ${C.name} was saved in Taskforce Cloud. The local copy will be retained when sync runs.`}}))}else dt(J=>({...J,[l]:{error:null,notice:`Generated photo for ${C.name} was saved.`}}));return lt({workspaceId:t,agentId:C.id,reason:"agent-avatar-generate"}),Vs({workspaceId:t,profileId:typeof g?.avatar?.profileId=="string"?g.avatar.profileId:null,reason:"avatar",origin:"taskforce-agents-module"}),!0}catch(c){const m=String(c?.message||c||"Unable to generate agent avatar.");return dt(b=>({...b,[l]:{error:m,notice:null}})),!1}finally{aa(c=>{const m=new Set(c);return m.delete(l),m})}}const zr=async()=>!u||!P?!1:Ul(P.definition,de)?(Xe("Save the avatar description and art style before generating."),At(null),!1):ma(P),pa=s=>{const l=String(s?.id||"").trim();l&&y(c=>c.map(m=>m.profileId===l?{...m,avatarUrl:typeof s.avatarUrl=="string"?s.avatarUrl:null,avatarSourceUrl:typeof s.avatarSourceUrl=="string"?s.avatarSourceUrl:null,avatarRevision:Number.isFinite(Number(s.avatarRevision))?Math.max(0,Math.floor(Number(s.avatarRevision))):m.avatarRevision,avatarUpdatedAt:typeof s.avatarUpdatedAt=="string"?s.avatarUpdatedAt:m.avatarUpdatedAt}:m))},Ur=async(s,l,c)=>{const m=String(P?.profileId||"").trim();if(!u||!m)return Xe("Save the agent before editing its profile photo."),!1;if(!s.type.startsWith("image/"))return Xe("Agent profile photo must be an image file."),!1;Ms(!0),Xe(null),At(null),dt(j=>{const g={...j};return delete g[u],g});const b=Ze&&cs.has(u)&&!!I;try{const j=await Ca(s,{maxBytes:5242880});if(j.exceededLimit)throw new Error(s.type==="image/gif"?"Animated GIF agent photos must be 5 MB or smaller.":"Agent profile photo must be 5 MB or smaller.");let g=null;if(l){const Ks=await Ca(l,{maxBytes:5242880});if(Ks.exceededLimit)throw new Error(l.type==="image/gif"?"Animated GIF agent source photos must be 5 MB or smaller.":"Agent profile source photo must be 5 MB or smaller.");g=Ks.file}const V=j.file,se=await Fa(V),re=g?await Fa(g):null,C={profileId:m,preserveExistingSource:c?.preserveExistingSource===!0,displayImage:{dataUrl:se,mimeType:V.type||"application/octet-stream",originalName:V.name||"display-avatar"}};g&&re&&(C.sourceImage={dataUrl:re,mimeType:g.type||"application/octet-stream",originalName:g.name||"source-avatar"});const J="/api/taskforce/workspace/ai-profiles/avatar/upload",ne=b&&I?Na(I(J)):J,B=await fetch(ne,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)}),X=await B.json().catch(()=>({}));if(!B.ok||!X?.profile)throw new Error(String(X?.error||"Failed to update agent profile photo."));const Be=b&&I?{...X.profile,avatarUrl:X.profile.avatarUrl?I(X.profile.avatarUrl):X.profile.avatarUrl,avatarSourceUrl:X.profile.avatarSourceUrl?I(X.profile.avatarSourceUrl):X.profile.avatarSourceUrl}:X.profile;pa(Be);const pt=$t(Be.avatarRevision);return b&&pt!==null&&wt.current.set(u,pt),b||(lt({workspaceId:t,agentId:u,reason:"agent-avatar-upload"}),Vs({workspaceId:t,profileId:m,reason:"avatar",origin:"taskforce-agents-module"})),!0}catch(j){return Xe(String(j?.message||"Failed to update agent profile photo.")),!1}finally{Ms(!1)}},Gr=async()=>{const s=String(P?.profileId||"").trim();if(!u||!s)return;Ms(!0),Xe(null),At(null),dt(c=>{const m={...c};return delete m[u],m});const l=Ze&&cs.has(u)&&!!I;try{const c="/api/taskforce/workspace/ai-profiles/avatar",m=l&&I?Na(I(c)):c,b=await fetch(m,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:s,avatarUrl:null,avatarSourceUrl:null})}),j=await b.json().catch(()=>({}));if(!b.ok||!j?.profile)throw new Error(String(j?.error||"Failed to remove agent profile photo."));pa(j.profile);const g=$t(j.profile.avatarRevision);l&&g!==null&&wt.current.set(u,g),At(l?"Agent profile photo removed in Taskforce Cloud. The local copy will be retained when sync runs.":"Agent profile photo removed."),l||(lt({workspaceId:t,agentId:u,reason:"agent-avatar-remove"}),Vs({workspaceId:t,profileId:s,reason:"avatar",origin:"taskforce-agents-module"}))}catch(c){Xe(String(c?.message||"Failed to remove agent profile photo."))}finally{Ms(!1)}},Br=()=>fs({type:"new"}),Hr=s=>{p.current=!0;const l=s.startsWith(ks)?s.slice(ks.length):"",c=l?"personal_connection":"taskforce_managed",m=l&&fe.find(g=>g.id===l)||null,j=d.filter(g=>Rn(g,c)).find(g=>!m||g.providerKey===m.providerKey)||null;ke(c),xt(l),j&&(jt(j.providerKey),kt(j.key),St(j.defaultTier))},Fr=s=>{p.current=!0;const l=qs(s),c=ft.filter(m=>m.providerKey===l);jt(l),kt(c[0]?.key||""),St(c[0]?.defaultTier||"balanced")},Kr=s=>{p.current=!0;const l=Ds(s,be),c=Kt.find(m=>m.key===l);kt(l),c&&St(c.defaultTier)},Cn=()=>{zt||(E.current+=1,Ot(!1),Ct(""),Je(""))},qr=()=>{!u||!ze||!mt||(E.current+=1,Ct(mt.title||"Agent chat"),Je(""),Ot(!0))},Vr=async s=>{s.preventDefault();const l=on.trim();if(!u||!ze||zt)return;if(!l){Je("Chat name is required.");return}if(l===mt?.title){Cn();return}const c=u,m=ze,b=++E.current;is(!0),Je("");try{const j=await fetch(`/api/taskforce/agents/${encodeURIComponent(c)}/conversations/${encodeURIComponent(m)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t,title:l})}),g=await j.json().catch(()=>({}));if(E.current!==b||U.current!==c)return;if(!j.ok||g?.success===!1||!g?.conversation){Je(String(g?.error||"Unable to rename chat."));return}us(g.conversation),Ot(!1),Ct(""),lt({workspaceId:t,agentId:c,conversationId:m,reason:"conversation-update"})}catch(j){if(E.current!==b||U.current!==c)return;Je(String(j?.message||j||"Unable to rename chat."))}finally{E.current===b&&is(!1)}},Wr=async()=>{if(!u){ws(""),Dt([]),Ut(null),at([]),_s(null),ue("info","Started a new unsaved chat.");return}const s=u,l=O,c=++oe.current,m=()=>U.current===s&&oe.current===c&&he.current===l;if(await ps(s),!m())return;const b=++Ne.current;Ft(!0),at([]);try{const j=await fetch(`/api/taskforce/agents/${encodeURIComponent(s)}/conversation/new`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t,...Ee?{taskId:Ee.taskId,taskReference:Ee.taskReference,taskTitle:Ee.taskTitle}:{}})}),g=await j.json().catch(()=>({}));if(!m()||Ne.current!==b)return;if(!j.ok||g?.success===!1){ue("error",String(g?.error||"Unable to start a new chat."));return}ws("");const V=g?.conversation||null;Ne.current+=1,Et(V),Ge(s,V?.id||null),V&&us(V),lt({workspaceId:t,agentId:s,conversationId:g?.conversation?.id||null,reason:"conversation-create"}),ue("info","Started a new saved chat.")}catch(j){m()&&ue("error",String(j?.message||j||"Unable to start a new chat."))}finally{m()&&Ft(!1)}},ha=async()=>{const s=dn.trim(),l=q.trim()||ht;if(!s||!de.purpose.trim()||!pe||os)return;const c=fa();if(!jn){Bt(L?"Sign in to Taskforce Cloud to test this agent.":"Cloud sign-in is still loading. Try again in a moment.");return}if(c.model.modelSource==="subscription_dev"&&(!ds||ds.lifecycleStatus!=="active")){Bt("Select an active connected model account before testing this Agent.");return}pn(!0);const m=++ae.current;un(null),fn(null),mn([]),Bt("");try{const b=await fetch("/api/taskforce/agents/model-gateway/test",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t,agentName:l,providerKey:be,modelKey:pe,prompt:s,messages:[{role:"user",content:s}],draftDefinition:c,...c.model.modelSource==="subscription_dev"?{connectionId:me}:{}})}),j=await b.json().catch(()=>({}));if(ae.current!==m)return;if(!b.ok||j?.success===!1){Bt(String(j?.error||"Agent test failed."));return}un(j?.result||null),fn({agentName:l,providerKey:be,modelKey:pe,prompt:s,definition:c});const g=Array.isArray(j?.mcpToolCalls)?j.mcpToolCalls:[];mn(g.reduce((V,se,re)=>{const C=String(se?.name||"").trim();return C&&V.push({id:`draft-${re}-${C}`,name:C,arguments:se.arguments,resultText:se.text,ok:se.ok!==!1}),V},[]))}catch(b){if(ae.current!==m)return;Bt(String(b?.message||b||"Agent test failed."))}finally{ae.current===m&&pn(!1)}},Jr=s=>{s.key!=="Enter"||s.shiftKey||s.nativeEvent.isComposing||(s.preventDefault(),ha())},ga=async()=>{const s=rn.trim(),l=Vn.trim(),c=q.trim()||ht;if(!s||!pe||Le||rt)return;if(!jn){const j=L?"Sign in to Taskforce Cloud to chat with Taskforce agents.":"Cloud sign-in is still loading. Try again in a moment.";Nt(j),ue("error",j);return}Jn(!0),Ut(null),Nt("");const m=Date.now(),b=[...Rs,{role:"user",content:s}];Dt(b),ws(""),at([]),ue("info",`Started test prompt for ${c}.`);try{let j,g,V=0;for(;j=await fetch("/api/taskforce/agents/model-gateway/test",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t,agentId:u,conversationId:ze,agentName:c,providerKey:be,modelKey:pe,prompt:s,messages:b,system:l,tier:Ue?.defaultTier||an,...et?{taskId:et.taskId,taskReference:et.taskReference,taskTitle:et.taskTitle}:{}})}),g=await j.json().catch(()=>({})),k==="local"&&g?.code==="AGENT_NOT_AVAILABLE_IN_CLOUD"&&V<dr;)V+=1,Nt("Waiting for this Agent to synchronize with Taskforce Cloud..."),await new Promise(X=>window.setTimeout(X,ur));if(!j.ok||g?.success===!1){const B=String(g?.error||"Model gateway test failed.");Nt(B),ue("error",B);return}Nt("");const se=g?.result||null;Ut(se);const re=Array.isArray(g?.mcpToolCalls)?g.mcpToolCalls:[],C=re.reduce((B,X,Be)=>{const pt=String(X?.name||"").trim();return pt&&B.push({id:`${m}-${Be}-${pt}`,name:pt,arguments:X.arguments,resultText:X.text,ok:X.ok!==!1}),B},[]);if(at(C),C.length>0){const B=C.some(X=>!X.ok);ue(B?"error":"success",Tc(C),C)}const J=g?.workflowCompletion;let ne=J?.taskSnapshot||null;J?.executionId&&J.assignmentSnapshot&&(ne=await ci(J,{workspaceId:t,runtimeMode:k})),re.length>0&&C.forEach(B=>{(B.name==="add_comment"||B.name==="add_task_checklist_item"||B.name==="update_task_checklist_item"||B.name==="replace_task_checklist"||B.name==="complete_workflow_step")&&B.ok&&di({workspaceId:t,taskId:(B.name==="complete_workflow_step"?J?.taskId:null)||et?.taskId||String(B.arguments?.taskId||B.arguments?.id||"").trim()||null,reason:B.name==="add_comment"?"agent-comment":B.name==="complete_workflow_step"?"workflow-step":"agent-checklist",...B.name==="complete_workflow_step"&&ne?{authoritativeTask:ne}:{},...B.name==="complete_workflow_step"&&J?.assignmentSnapshot?{authoritativeWorkflowAssignment:J.assignmentSnapshot}:{}})}),g?.conversation?(Et(g.conversation),Ge(u,g.conversation.id||ze||null),us(g.conversation),lt({workspaceId:t,agentId:u,conversationId:g.conversation.id||ze,reason:"conversation-update"})):Dt(se?.text?[...b,{role:"assistant",content:String(se.text),agentId:u||void 0,agentName:c,providerKey:be,providerLabel:Wt(be),modelKey:pe,modelLabel:hs(pe),modelId:String(se.modelId||""),...C.length>0?{toolActivity:C.map(({id:B,...X})=>X)}:{}}]:b),ue("success",`Model gateway completed successfully in ${se?.latencyMs??Date.now()-m} ms.`)}catch(j){const g=String(j?.message||j||"Model gateway test failed.");Nt(g),ue("error",g)}finally{Jn(!1)}},Yr=s=>{s.key!=="Enter"||s.shiftKey||s.nativeEvent.isComposing||(s.preventDefault(),ga())},Qr=s=>{!u||!s||s===ze||Sn(u,s)},Xr=async s=>{if(!navigator.clipboard?.writeText){Is({id:s.id,status:"failed"});return}try{await navigator.clipboard.writeText(wc(s)),Is({id:s.id,status:"copied"}),window.setTimeout(()=>{Is(l=>l?.id===s.id?null:l)},1600)}catch{Is({id:s.id,status:"failed"})}},Zr=s=>e.jsx("div",{className:r.taskforceAgentToolActivityList,children:s.map(l=>e.jsxs("details",{className:`${r.taskforceAgentToolCall} ${l.ok?"":r.taskforceAgentToolCallFailed}`.trim(),children:[e.jsxs("summary",{children:[l.ok?e.jsx(Cs,{size:13}):e.jsx(st,{size:13}),e.jsx("span",{className:r.taskforceAgentToolCallName,children:l.name}),e.jsx("span",{className:r.taskforceAgentToolCallStatus,children:l.ok?"ok":"failed"})]}),e.jsxs("div",{className:r.taskforceAgentToolDetailsGrid,children:[e.jsxs("button",{type:"button",className:r.taskforceAgentToolCopyButton,onClick:()=>{Xr(l)},"aria-label":`Copy ${l.name} tool call details`,title:"Copy diagnostic details, including the full result up to 20,000 characters",children:[Es?.id===l.id&&Es.status==="copied"?e.jsx(Zt,{size:13}):e.jsx(Qa,{size:13}),e.jsx("span",{"aria-live":"polite",children:Es?.id===l.id?Es.status==="copied"?"Copied":"Copy failed":"Copy"})]}),e.jsx("span",{children:"Arguments"}),e.jsx("pre",{children:Nc(l.arguments)}),e.jsx("span",{children:"Result preview"}),e.jsx("pre",{children:Ac(l.resultText)})]})]},l.id))}),va=(s,l="Tool Activity")=>e.jsxs("details",{className:r.taskforceAgentToolActivity,children:[e.jsxs("summary",{children:[e.jsx("span",{children:l}),e.jsx("strong",{children:_c(s)})]}),Zr(s)]}),Vt=A==="agents"?{icon:e.jsx(Xt,{size:14}),title:"Agent Roster",empty:"No agents configured yet."}:A==="roles"?{icon:e.jsx(ts,{size:14}),title:"Role Library",empty:"No roles configured yet."}:A==="skills"?{icon:e.jsx(Lt,{size:14}),title:"Skill Library",empty:"Browse and manage Skills in the editor."}:A==="connections"?{icon:e.jsx(vt,{size:14}),title:"Connection Library",empty:"Connections are not available yet."}:{icon:e.jsx(tn,{size:14}),title:"Resource Library",empty:"Resource Collections are not available yet."},ei=e.jsxs("div",{className:r.taskforceAgentBuilderNavigation,children:[e.jsx("div",{className:r.taskforceAgentBuilderTabs,role:"tablist","aria-label":"Taskforce Agent builders",children:Qt.map((s,l)=>{const c=A===s.id;return e.jsx("button",{ref:m=>{ge.current[s.id]=m},type:"button",className:`${r.taskforceAgentBuilderTab} ${c?r.taskforceAgentBuilderTabActive:""}`.trim(),role:"tab","aria-selected":c,"aria-controls":`taskforce-agent-builder-${s.id}`,id:`taskforce-agent-builder-tab-${s.id}`,tabIndex:c?0:-1,onClick:()=>{ye(s.id)},onKeyDown:m=>{let b=l;if(m.key==="ArrowRight")b=(l+1)%Qt.length;else if(m.key==="ArrowLeft")b=(l-1+Qt.length)%Qt.length;else if(m.key==="Home")b=0;else if(m.key==="End")b=Qt.length-1;else return;m.preventDefault();const j=Qt[b];ye(j.id),ge.current[j.id]?.focus()},children:s.label},s.id)})}),A==="agents"?e.jsxs("button",{type:"button",className:`${r.secondaryHeaderBtn} ${r.taskforceAgentBuilderCreateBtn}`.trim(),onClick:Br,children:[e.jsx(Pt,{size:14}),"New Agent"]}):null]}),Nn=n,ti=e.jsxs("aside",{className:`${r.docTrayPanel} ${Nn?r.docTrayPanelOpen:""}`.trim(),"aria-hidden":!Nn,"aria-label":Vt.title,children:[e.jsxs("div",{className:r.taskforceAgentRosterHeader,children:[e.jsxs("span",{className:r.taskforceAgentRosterTitle,children:[Vt.icon,Vt.title]}),A==="agents"&&Ht&&e.jsx(je,{size:14,className:r.spinner}),i?e.jsx("button",{type:"button",className:"tf-control-icon",onClick:i,title:`Collapse ${Vt.title.toLowerCase()}`,"aria-label":`Collapse ${Vt.title.toLowerCase()}`,children:e.jsx(wi,{size:16})}):null]}),e.jsx("div",{className:`${r.taskforceAgentRosterContent} tf-scrollbar tf-tray-scroll-viewport`,children:A==="roles"?e.jsx("div",{ref:He,className:r.taskforceAgentLibraryPortal}):A==="skills"?e.jsx("div",{ref:we,className:r.taskforceAgentLibraryPortal}):A==="connections"?e.jsx("div",{ref:We,className:r.taskforceAgentLibraryPortal}):A==="resources"?e.jsx(vo,{kind:"resources"}):A==="agents"&&ce.length>0?e.jsx("div",{className:r.taskforceAgentList,children:ce.map(s=>{const l=In(s),c=s.color||Jt(s.id);return e.jsx(ui,{name:s.name,username:s.username,subtitle:"Taskforce Agent",avatar:l?e.jsx($n,{src:l,fallbackSize:22}):e.jsx(Xt,{size:22}),avatarStyle:{color:c},selected:s.id===u,disabled:!Y,onSelect:()=>fs({type:"agent",agent:s}),ariaLabel:`Edit ${s.name}`,bottomUtility:e.jsx("span",{className:r.aiProfileGroupSignatureSwatch,style:{backgroundColor:c},title:`Signature color ${c}`,"aria-hidden":"true"})},s.id)})}):e.jsx("p",{className:r.taskforceAgentListEmpty,children:Vt.empty})})]});return x==="taskDrawer"?e.jsxs("div",{className:r.taskforceAgentDrawerSurface,children:[et?e.jsxs("div",{className:r.taskforceAgentContextBanner,children:[e.jsxs("div",{children:[e.jsx("span",{children:"Context"}),e.jsx("strong",{children:Ir})]}),e.jsxs("div",{className:r.taskforceAgentContextActions,children:[w?e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:()=>w(et.taskId),title:"Open task","aria-label":"Open task",children:e.jsx(Xa,{size:13})}):null,f&&$r?e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:f,title:"Clear task context","aria-label":"Clear task context",children:e.jsx(yt,{size:13})}):null]})]}):null,yn&&P?e.jsxs("section",{className:r.taskforceAgentProfileTray,"aria-label":`${P.name} profile`,children:[e.jsxs("div",{className:r.taskforceAgentProfileTrayHeader,children:[e.jsxs("span",{className:`${r.taskforceAgentAvatarPreview} ${Rt?r.taskforceAgentAvatarSyncing:""}`.trim(),"aria-hidden":"true",children:[Tt?e.jsx($n,{src:Tt,fallbackSize:18}):e.jsx(Xt,{size:18}),Rt?e.jsx(je,{size:13,className:`${r.spinner} ${r.taskforceAgentAvatarSyncIcon}`}):null]}),e.jsxs("div",{className:r.taskforceAgentProfileTrayIdentity,children:[e.jsx("span",{children:"Agent profile"}),e.jsx("strong",{children:P.name}),e.jsxs("small",{children:[Wt(P.providerKey)," · ",Ln(P.modelTier)]})]}),e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:()=>oa(!1),title:"Close agent profile","aria-label":"Close agent profile",children:e.jsx(yt,{size:13})})]}),e.jsxs("dl",{className:r.taskforceAgentProfileTrayDetails,children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Platform"}),e.jsx("dd",{children:Ka(P.modelProvider)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:Wt(P.providerKey)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Model"}),e.jsx("dd",{children:hs(P.modelKey)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Default tier"}),e.jsx("dd",{children:Ln(P.modelTier)})]})]})]}):null,e.jsxs("div",{className:r.taskforceAgentDrawerControls,children:[ie?null:e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Agent"}),e.jsx("select",{className:r.select,value:u||"",onChange:s=>{const l=ce.find(c=>c.id===s.target.value);l&&fs({type:"agent",agent:l})},disabled:!Y||Ht||ce.length===0||Le,children:ce.length>0?ce.map(s=>e.jsxs("option",{value:s.id,children:[s.name," · ",hs(s.modelKey)]},s.id)):e.jsx("option",{value:"",children:"No agents configured"})})]}),gr?e.jsxs("form",{className:r.taskforceAgentConversationRename,onSubmit:Vr,children:[e.jsx("input",{className:r.input,"aria-label":"Chat name",value:on,onChange:s=>{Ct(s.target.value),ln&&Je("")},onKeyDown:s=>{s.key==="Escape"&&(s.preventDefault(),Cn())},maxLength:120,autoFocus:!0,disabled:zt}),e.jsx("button",{type:"submit",className:"tf-control-icon","aria-label":"Save chat name",title:"Save chat name",disabled:zt||!on.trim(),children:zt?e.jsx(je,{size:14,className:r.spinner}):e.jsx(On,{size:14})}),e.jsx("button",{type:"button",className:"tf-control-icon",onClick:Cn,"aria-label":"Cancel renaming",title:"Cancel",disabled:zt,children:e.jsx(yt,{size:14})}),ln?e.jsx("div",{className:r.taskforceAgentConversationRenameError,role:"alert",children:ln}):null]}):e.jsxs("div",{className:r.taskforceAgentDrawerChatControls,children:[u?e.jsx("select",{className:`${r.select} ${r.taskforceAgentConversationSelect}`.trim(),"aria-label":"Saved chats",value:ze||"",onChange:s=>Qr(s.target.value),disabled:Le||rt||jr||rs.length===0,children:rs.length>0?e.jsxs(e.Fragment,{children:[ze?null:e.jsx("option",{value:"",children:"Select chat"}),rs.map(s=>e.jsx("option",{value:s.id,children:$c(s,Ee)},s.id))]}):e.jsx("option",{value:"",children:"No chats"})}):null,e.jsx("button",{type:"button",className:"tf-control-icon",onClick:qr,disabled:Le||rt||!mt,"aria-label":"Rename chat",title:"Rename chat",children:e.jsx(Za,{size:14})}),e.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>{Wr()},disabled:Le||rt||!u,"aria-label":"New chat",title:"New chat",children:e.jsx(Pt,{size:14})})]})]}),e.jsxs("div",{className:`${r.taskforceAgentConversationList} ${r.taskforceAgentDrawerConversationList} tf-scrollbar`,children:[rt?e.jsx("div",{className:r.taskforceAgentConversationEmpty,children:"Loading saved conversation..."}):Rs.length>0?Rs.map((s,l)=>e.jsxs("div",{"data-conversation-role":s.role,style:s.role==="assistant"&&Bs?{"--conversation-accent":Bs}:void 0,className:`${r.taskforceAgentConversationMessage} ${s.role==="user"?r.taskforceAgentConversationMessageUser:r.taskforceAgentConversationMessageAssistant}`.trim(),children:[e.jsx("span",{children:Ec(s,Lr)}),e.jsx(Mn,{variant:"conversation",className:r.taskforceAgentConversationBody,taskReferences:N,children:s.content}),s.role==="assistant"&&s.toolActivity?.length?va(s.toolActivity.map((c,m)=>({...c,id:`${l}-${m}-${c.name}`})),"Taskforce actions"):null]},`${s.role}-${l}`)):Le?null:e.jsx("div",{className:r.taskforceAgentConversationEmpty,children:u?"No conversation yet.":"Select an agent to start chatting."}),Le&&!rt?e.jsxs("div",{"data-conversation-role":"assistant",style:Bs?{"--conversation-accent":Bs}:void 0,className:`${r.taskforceAgentConversationMessage} ${r.taskforceAgentConversationMessageAssistant}`.trim(),children:[e.jsx("span",{children:q.trim()||ht}),e.jsx("p",{children:"Waiting for model response..."})]}):null,e.jsx("div",{ref:M,"aria-hidden":"true"})]}),e.jsxs("div",{className:r.taskforceAgentDrawerPrompt,children:[e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Message"}),e.jsx("textarea",{className:r.input,value:rn,onChange:s=>{ws(s.target.value),cn&&Nt("")},onKeyDown:Yr,disabled:Le||rt||!u,placeholder:Le?"Waiting for response...":gc,maxLength:4e3})]}),e.jsxs("button",{type:"button",className:r.secondaryHeaderBtn,onClick:()=>{ga()},disabled:Le||rt||!rn.trim()||!pe||!u,children:[Le?e.jsx(je,{size:14,className:r.spinner}):e.jsx(_a,{size:14}),"Send"]}),cn?e.jsx("div",{className:r.taskforceAgentDrawerPromptStatus,role:"status",children:cn}):null]}),e.jsxs("div",{className:r.taskforceAgentDrawerMetrics,"aria-label":"Response metrics",children:[e.jsxs("span",{children:[e.jsx("strong",{children:"Usage"}),Ha(Wn)]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Latency"}),En(Wn)]})]})]}):e.jsxs("div",{className:`${r.standalonePage} ${r.standaloneContent} ${r.taskforceAgentsModuleRoot} ${Nn?r.taskforceAgentsModuleTrayOpen:""}`.trim(),children:[ti,e.jsxs("div",{className:`${r.taskforceAgentsModuleMain} tf-scrollbar`,children:[e.jsxs("div",{className:r.settingsContent,style:{maxWidth:1180,margin:"0 auto",width:"100%"},children:[ei,e.jsx("div",{className:`${r.settingGroup} ${r.taskforceAgentBuilderPanel}`,hidden:A!=="agents",children:e.jsxs("div",{className:r.taskforceAgentTestGrid,role:"tabpanel",id:"taskforce-agent-builder-agents","aria-labelledby":"taskforce-agent-builder-tab-agents",children:[e.jsxs("div",{className:r.settingGroup,children:[e.jsxs("div",{className:r.taskforceAgentAvatarPanel,children:[e.jsxs("div",{className:r.taskforceAgentAvatarEditControl,children:[e.jsx(ri,{label:P?`Edit ${P.name} photo`:"Photo editing is unavailable until agent creation",imageUrl:Tt,fallback:e.jsx(Xt,{size:28}),accentColor:Ns||P?.color,size:88,editBadgeSize:28,editIconSize:14,disabled:!u,loading:!!(u&&Ps.has(u)),loadingLabel:`Generating ${P?.name||"agent"} photo`,error:!!Us?.error,errorLabel:Us?.error||"Agent photo generation failed",onClick:()=>{Xe(null),At(null),ra(!0)}}),Rt?e.jsx(je,{size:16,className:`${r.spinner} ${r.taskforceAgentAvatarSyncIcon}`}):null]}),e.jsxs("div",{className:r.taskforceAgentAvatarCopy,children:[e.jsx("strong",{children:q.trim()||P?.name||ht}),e.jsx("span",{className:r.taskforceAgentAvatarRole,children:"Taskforce Agent"}),Rt?e.jsx("small",{children:"Syncing avatar..."}):null]}),e.jsxs("div",{className:r.taskforceAgentToolbar,children:[ls?e.jsxs("span",{className:ls.type==="error"?"tf-chip-danger":"tf-chip-success",role:ls.type==="error"?"alert":"status","aria-label":"Agent configuration status",children:[ls.type==="error"?e.jsx(st,{size:12}):e.jsx(Cs,{size:12}),ls.message]}):null,e.jsxs("button",{type:"button",className:r.secondaryHeaderBtn,"aria-expanded":Zn,"aria-controls":"taskforce-agent-test-panel",title:"Uses the current draft, including unsaved changes. Test messages are not saved and cannot modify tasks.",onClick:()=>yr(s=>!s),children:[e.jsx(_i,{size:14}),"Test Agent"]}),e.jsxs("button",{type:"button",className:r.secondaryHeaderBtn,onClick:()=>{Or()},disabled:vn||!q.trim()||!de.purpose.trim()||!pe||!Ue,children:[vn?e.jsx(je,{size:14,className:r.spinner}):e.jsx(On,{size:14}),"Save"]})]})]}),Zn?e.jsxs("section",{id:"taskforce-agent-test-panel",className:r.taskforceAgentHeaderTestPanel,"aria-label":"Isolated Agent test",children:[e.jsxs("div",{className:r.taskforceAgentTestComposer,children:[e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Test Prompt"}),e.jsx("textarea",{className:r.input,value:dn,onChange:s=>Yn(s.target.value),onKeyDown:Jr,placeholder:"Ask the draft agent a representative question...",rows:4,disabled:os})]}),e.jsx("button",{type:"button",className:`tf-control-icon ${r.taskforceAgentTestSendButton}`,"aria-label":"Send test prompt",title:"Send test prompt",onClick:()=>{ha()},disabled:os||!dn.trim()||!de.purpose.trim()||!pe,children:os?e.jsx(je,{size:15,className:r.spinner}):e.jsx(_a,{size:15})})]}),jn?null:e.jsx("p",{className:r.taskforceAgentTestRestriction,children:L?"Sign in to Taskforce Cloud to run agent tests.":"Checking Taskforce Cloud sign-in..."}),Xn?e.jsxs("div",{className:r.taskforceAgentTestError,role:"alert",children:[e.jsx(st,{size:14}),e.jsx("span",{children:Xn})]}):null,os?e.jsxs("div",{className:r.taskforceAgentTestPending,role:"status",children:[e.jsx(je,{size:15,className:r.spinner}),e.jsx("span",{children:"Testing agent..."})]}):null,Ye?e.jsxs("div",{className:r.taskforceAgentTestResult,role:"status","aria-live":"polite",children:[e.jsxs("div",{className:r.taskforceAgentTestResultHeader,children:[e.jsxs("span",{children:[e.jsx(Cs,{size:14})," Test completed"]}),e.jsxs("span",{children:[En(Ye)," · ",Ha(Ye)]})]}),e.jsx("div",{className:r.taskforceAgentTestResponse,children:e.jsx(Mn,{variant:"conversation",children:Ye.text})}),e.jsxs("details",{className:r.taskforceAgentToolActivity,children:[e.jsxs("summary",{children:[e.jsx("span",{children:"Response Details"}),e.jsx("strong",{children:hs(Gt?.modelKey||pe)})]}),e.jsxs("div",{className:r.taskforceAgentMetaGrid,children:[e.jsxs("div",{children:[e.jsx("span",{children:"Tested agent"}),e.jsx("strong",{children:Gt?.agentName||q.trim()||ht})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Provider"}),e.jsx("strong",{children:Wt(Gt?.providerKey||be)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Runtime model"}),e.jsx("code",{children:Ye.modelId||"Not reported"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Test prompt"}),e.jsx("strong",{children:Gt?.prompt||"Not reported"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Tested purpose"}),e.jsx("strong",{children:Gt?.definition.purpose||"Not reported"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Tested working guidelines"}),e.jsx("strong",{children:Gt?.definition.behavior.workingGuidelines||"None"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Stop reason"}),e.jsx("strong",{children:Ye.stopReason||"Not reported"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Input tokens"}),e.jsx("strong",{children:Ye.usage?.inputTokens??"Not reported"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Output tokens"}),e.jsx("strong",{children:Ye.usage?.outputTokens??"Not reported"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Total tokens"}),e.jsx("strong",{children:Ye.usage?.totalTokens??"Not reported"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Latency"}),e.jsx("strong",{children:En(Ye)})]})]}),Qn.length>0?va(Qn,"Managed Tool Activity"):null]})]}):null]}):null,P?.configurationState&&P.configurationState!=="valid"?e.jsxs("div",{className:r.taskforceAgentTestError,role:"alert",children:[e.jsx(st,{size:14}),e.jsxs("span",{children:["This Agent configuration is ",P.configurationState.replace(/-/g," "),".",P.configurationIssues?.[0]?.message?` ${P.configurationIssues[0].message}`:" Repair the highlighted configuration before testing it."]})]}):null,ta?e.jsxs("div",{className:r.taskforceAgentTestError,role:"alert",children:[e.jsx(st,{size:14}),e.jsx("span",{children:ta}),e.jsxs("button",{type:"button",className:`${r.secondaryHeaderBtn} ${r.taskforceAgentRetryButton}`,onClick:()=>xr(s=>s+1),children:[e.jsx(nn,{size:14}),"Retry"]})]}):null,e.jsxs("div",{className:r.topRow,children:[e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Agent Name"}),e.jsx("input",{className:r.input,value:q,onChange:s=>{p.current=!0,v(s.target.value)},placeholder:ht,required:!0,maxLength:80})]}),e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Platform"}),e.jsx("div",{className:r.taskforceAgentReadonlyField,"aria-label":"Platform",children:Ka()})]}),e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Model Source"}),e.jsx("select",{className:r.select,value:wr,onChange:s=>Hr(s.target.value),children:Ar.map(s=>e.jsx("option",{value:s.key,disabled:s.disabled,children:s.label},s.key))})]}),e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Provider"}),e.jsx("select",{className:r.select,value:be,onChange:s=>Fr(s.target.value),children:_r.map(s=>e.jsx("option",{value:s.key,children:s.label},s.key))})]}),e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Model"}),e.jsxs("select",{className:r.select,value:pe,onChange:s=>Kr(s.target.value),disabled:Kt.length===0,children:[!Ue&&pe?e.jsxs("option",{value:pe,disabled:!0,children:[hs(pe)," (unavailable)"]}):null,Kt.map(s=>e.jsx("option",{value:s.key,children:s.label},s.key)),Kt.length===0&&!pe?e.jsxs("option",{value:"",children:["No configured ",Wt(be)," models yet"]}):null]})]}),e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Default Tier"}),e.jsx("div",{className:r.taskforceAgentReadonlyField,children:Ue?Ln(Ue.defaultTier):"No configured tier"})]})]}),e.jsxs("div",{className:r.taskforceAgentSignatureColorField,children:[e.jsx("span",{className:r.label,title:"Identifies this agent across Taskforce.","aria-label":"Signature Color. Identifies this agent across Taskforce.",children:"Signature Color"}),e.jsx("div",{className:r.aiProfileColorPicker,"aria-label":"Signature color options",children:fi.map(({name:s,value:l})=>e.jsx("button",{type:"button",className:r.aiProfileColorOption,style:{backgroundColor:l},"aria-label":`Use ${s}`,"aria-pressed":Ns.toLowerCase()===l.toLowerCase(),onClick:()=>{p.current=!0,as(l),As(!0),te.current=!0}},l))})]}),e.jsxs("div",{className:r.taskforceAgentBehaviorGrid,children:[e.jsxs("label",{className:`${r.field} ${r.taskforceAgentBehaviorWide}`,children:[e.jsx("span",{className:r.label,children:"Purpose"}),e.jsx("small",{className:r.taskforceAgentFieldHelper,children:"What should this agent help with?"}),e.jsx("textarea",{className:r.input,"aria-label":"Purpose",value:de.purpose,onChange:s=>{p.current=!0,Re(l=>({...l,purpose:s.target.value}))},maxLength:1e3,rows:3,required:!0})]}),e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Personality and Voice"}),e.jsx("small",{className:r.taskforceAgentFieldHelper,children:"How should this agent behave or portray itself?"}),e.jsxs("select",{className:r.select,"aria-label":"Personality and Voice",value:de.personalitySelection,onChange:s=>{p.current=!0,Re(l=>({...l,personalitySelection:s.target.value,personalityCustom:s.target.value===Me?l.personalityCustom:""}))},children:[e.jsx("option",{value:"",children:"No preset"}),El.map(s=>e.jsx("option",{value:s.key,children:s.label},s.key)),e.jsx("option",{value:Me,children:"Custom"})]})]}),e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Response Style"}),e.jsx("small",{className:r.taskforceAgentFieldHelper,children:"How should answers be written and structured?"}),e.jsxs("select",{className:r.select,"aria-label":"Response Style",value:de.responseStyleSelection,onChange:s=>{p.current=!0,Re(l=>({...l,responseStyleSelection:s.target.value,responseStyleCustom:s.target.value===Me?l.responseStyleCustom:""}))},children:[e.jsx("option",{value:"",children:"No preset"}),Il.map(s=>e.jsx("option",{value:s.key,children:s.label},s.key)),e.jsx("option",{value:Me,children:"Custom"})]})]}),de.personalitySelection===Me?e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Custom Personality and Voice"}),e.jsx("textarea",{className:r.input,"aria-label":"Custom Personality and Voice",value:de.personalityCustom,onChange:s=>{p.current=!0,Re(l=>({...l,personalityCustom:s.target.value}))},maxLength:4e3,rows:3})]}):null,de.responseStyleSelection===Me?e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Custom Response Style"}),e.jsx("textarea",{className:r.input,"aria-label":"Custom Response Style",value:de.responseStyleCustom,onChange:s=>{p.current=!0,Re(l=>({...l,responseStyleCustom:s.target.value}))},maxLength:4e3,rows:3})]}):null,e.jsxs("label",{className:`${r.field} ${r.taskforceAgentBehaviorWide}`,children:[e.jsx("span",{className:r.label,children:"Working Guidelines"}),e.jsx("small",{className:r.taskforceAgentFieldHelper,children:"How should this agent approach tasks, decisions, and constraints?"}),e.jsx("textarea",{className:r.input,"aria-label":"Working Guidelines",style:{minHeight:108,resize:"vertical"},value:Vn,onChange:s=>pr(s.target.value),maxLength:8e3})]})]}),e.jsxs("div",{className:r.taskforceAgentPresentationGroup,children:[e.jsxs("div",{children:[e.jsx("span",{className:r.label,children:"Avatar Generation Direction"}),e.jsx("small",{className:r.taskforceAgentFieldHelper,children:"Saved for manual avatar generation only. These details are excluded from normal Agent context."})]}),e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Avatar Visual Description"}),e.jsx("textarea",{className:r.input,"aria-label":"Avatar Visual Description",value:de.avatarVisualDescription,onChange:s=>{p.current=!0,Re(l=>({...l,avatarVisualDescription:s.target.value}))},maxLength:4e3,rows:3,placeholder:"Describe what this agent or character looks like."})]}),e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Avatar Art Style"}),e.jsxs("select",{className:r.select,"aria-label":"Avatar Art Style",value:de.avatarArtStyleSelection,onChange:s=>{p.current=!0,Re(l=>({...l,avatarArtStyleSelection:s.target.value,avatarArtStyleCustom:s.target.value===Me?l.avatarArtStyleCustom:""}))},children:[e.jsx("option",{value:"",children:Ll}),$l.map(s=>e.jsx("option",{value:s.key,children:s.label},s.key)),e.jsx("option",{value:Me,children:"Custom"})]})]}),de.avatarArtStyleSelection===Me?e.jsxs("label",{className:r.field,children:[e.jsx("span",{className:r.label,children:"Custom Avatar Art Style"}),e.jsx("textarea",{className:r.input,"aria-label":"Custom Avatar Art Style",value:de.avatarArtStyleCustom,onChange:s=>{p.current=!0,Re(l=>({...l,avatarArtStyleCustom:s.target.value}))},maxLength:4e3,rows:3,placeholder:"Describe medium, palette, lighting, period, or atmosphere."})]}):null]}),e.jsxs("details",{className:r.taskforceAgentToolActivity,children:[e.jsxs("summary",{children:[e.jsx("span",{children:"Technical model details"}),e.jsx("strong",{children:Ue?Sc(Ue.availability):"Unavailable"})]}),e.jsxs("div",{className:r.taskforceAgentMetaGrid,children:[e.jsxs("div",{children:[e.jsx("span",{children:"Model ID"}),e.jsx("code",{children:Ue?.runtimeModelId||"No configured model"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Max Output"}),e.jsx("strong",{children:Rc(Ue?.defaultMaxTokens)})]})]})]})]}),e.jsxs("aside",{className:r.taskforceAgentOutputStack,"aria-label":"Agent Role and Capabilities",children:[e.jsx(Tl,{workspaceId:t,roleRef:de.roleRef,skillRefs:de.skillRefs,onRoleRefChange:s=>{p.current=!0,Re(l=>({...l,roleRef:s}))},onSkillRefsChange:s=>{p.current=!0,Re(l=>({...l,skillRefs:s}))},onManageRoles:()=>ye("roles"),onManageSkills:()=>ye("skills")}),e.jsx(Fn,{selectedKeys:de.requestedCapabilities,hasCustomOverrides:!!(P?.definition?.toolPolicy.toolOverrides?.length&&!de.toolAccessChanged),onChange:s=>{p.current=!0,Re(l=>({...l,requestedCapabilities:s,toolAccessChanged:!0}))}}),e.jsx(go,{hasRole:!!de.roleRef,directSkillCount:de.skillRefs.length,toolKeys:de.requestedCapabilities})]})]})}),e.jsx("section",{className:r.taskforceAgentBuilderPanel,role:"tabpanel",id:"taskforce-agent-builder-roles","aria-labelledby":"taskforce-agent-builder-tab-roles",hidden:A!=="roles",children:A==="roles"?e.jsx(ul,{workspaceId:t,libraryPortalTarget:Te}):null}),e.jsx("section",{className:r.taskforceAgentBuilderPanel,role:"tabpanel",id:"taskforce-agent-builder-skills","aria-labelledby":"taskforce-agent-builder-tab-skills",hidden:A!=="skills",children:e.jsx(Zl,{workspaceId:t,active:A==="skills",libraryPortalTarget:bt},t)}),e.jsx("section",{className:r.taskforceAgentBuilderPanel,role:"tabpanel",id:"taskforce-agent-builder-connections","aria-labelledby":"taskforce-agent-builder-tab-connections",hidden:A!=="connections",children:A==="connections"?e.jsx(hc,{workspaceId:t,active:!0,runtimeMode:k,eligible:xn,cloudAccessAvailable:_t,cloudAccessPending:Rr,cloudAuthConfigured:$,resolveCloudAuthUrl:I,onConnectionActivated:Mr,onConnectionUnavailable:Dr,onReturnToAgent:()=>_e("agents",!0),libraryPortalTarget:Oe}):null}),e.jsx("section",{className:r.taskforceAgentBuilderPanel,role:"tabpanel",id:"taskforce-agent-builder-resources","aria-labelledby":"taskforce-agent-builder-tab-resources",hidden:A!=="resources",children:A==="resources"?e.jsx(yo,{kind:"resources"}):null})]}),e.jsx(ii,{isOpen:!!$s,onClose:()=>Ls(null),title:"Discard unsaved changes?",size:"sm",theme:R,closeOnOverlayClick:!1,footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"tf-button-secondary",onClick:()=>Ls(null),"data-modal-initial-focus":!0,children:"Keep editing"}),e.jsx("button",{type:"button",className:"tf-button-destructive",onClick:Pr,children:"Discard changes"})]}),children:e.jsx("p",{children:"Your unsaved Agent changes will be lost."})}),e.jsx(oi,{isOpen:Sr,theme:R,title:"Edit Agent Profile Photo",currentImageUrl:Tt,editorImageUrl:Er,fallbackInitial:(P?.name||"Agent").charAt(0).toUpperCase(),accept:"image/png,image/jpeg,image/webp,image/gif",busy:ia,generating:!!(u&&Ps.has(u)),generateLabel:P?.avatarUrl?"Regenerate":"Generate",hasPendingImage:!1,canRemove:!!P?.avatarUrl,error:Cr||Us?.error||null,notice:Nr||Us?.notice||null,onClose:()=>{ia||(ra(!1),Xe(null),At(null))},onApplyImage:Ur,onGenerateImage:u&&!Ps.has(u)?zr:void 0,onRemoveImage:Gr},u||"agent-avatar-draft")]})]})}export{Fc as TaskforceAgentsModule};
@@ -1 +1 @@
1
- import{r as n,j as e}from"./vendor-react-CKJs5o3c.js";import{a2 as ze,a3 as Me,a4 as Oe,a5 as He,a6 as Le,a7 as Fe,M as Be,t as $,a8 as Ue,a9 as Ge,aa as Je,T as Ye,ab as _e,ac as Ze}from"./index-I5zhdtgt.js";import{w as J,az as le,ak as Qe,t as pe,Z as je,bj as Xe,bk as et,a6 as tt,bl as st,bm as nt,a7 as rt,a as at,x as lt,v as it,A as ot,r as ct}from"./vendor-icons-D9Lpw-j4.js";import"./vendor-markdown-_lhNCyq-.js";import"./vendor-dnd-CJ-AjP-Y.js";import"./vendor-router-AqJMU8Lz.js";const dt="_root_1bn9e_1",ut="_main_1bn9e_13",ft="_trayOpen_1bn9e_21",mt="_libraryHeader_1bn9e_25",pt="_libraryTitle_1bn9e_34",bt="_libraryContent_1bn9e_41",ht="_libraryList_1bn9e_48",wt="_libraryItem_1bn9e_54",xt="_libraryItemSelected_1bn9e_75",yt="_libraryItemCopy_1bn9e_80",gt="_libraryItemName_1bn9e_84",_t="_libraryItemMeta_1bn9e_94",jt="_libraryBadges_1bn9e_101",Nt="_statusRow_1bn9e_102",vt="_content_1bn9e_109",kt="_visuallyHidden_1bn9e_115",St="_pageHeader_1bn9e_127",Ct="_pageHeading_1bn9e_136",Dt="_detailHeader_1bn9e_144",Et="_metadataEditor_1bn9e_148",Wt="_titleRow_1bn9e_154",It="_editor_1bn9e_169",Tt="_stickyToolbar_1bn9e_173",Kt="_toolbarGroup_1bn9e_188",Rt="_versionSelect_1bn9e_194",$t="_description_1bn9e_211",qt="_metrics_1bn9e_217",Vt="_metric_1bn9e_217",At="_section_1bn9e_249",Pt="_sectionHeader_1bn9e_253",zt="_stepToolbar_1bn9e_254",Mt="_stepActions_1bn9e_255",Ot="_stepList_1bn9e_266",Ht="_stepEditor_1bn9e_273",Lt="_stepToolbarExpanded_1bn9e_285",Ft="_stepExpandButton_1bn9e_289",Bt="_stepSummary_1bn9e_311",Ut="_stepFields_1bn9e_328",Gt="_fullField_1bn9e_335",Jt="_stepToggles_1bn9e_337",Yt="_requiredToggle_1bn9e_345",Zt="_stepsEmpty_1bn9e_356",Qt="_stepNumber_1bn9e_376",Xt="_emptyState_1bn9e_382",es="_loadingState_1bn9e_383",ts="_emptyStateInner_1bn9e_391",ss="_errorBanner_1bn9e_399",ns="_errorMessage_1bn9e_407",s={root:dt,main:ut,trayOpen:ft,libraryHeader:mt,libraryTitle:pt,libraryContent:bt,libraryList:ht,libraryItem:wt,libraryItemSelected:xt,libraryItemCopy:yt,libraryItemName:gt,libraryItemMeta:_t,libraryBadges:jt,statusRow:Nt,content:vt,visuallyHidden:kt,pageHeader:St,pageHeading:Ct,detailHeader:Dt,metadataEditor:Et,titleRow:Wt,editor:It,stickyToolbar:Tt,toolbarGroup:Kt,versionSelect:Rt,description:$t,metrics:qt,metric:Vt,section:At,sectionHeader:Pt,stepToolbar:zt,stepActions:Mt,stepList:Ot,stepEditor:Ht,stepToolbarExpanded:Lt,stepExpandButton:Ft,stepSummary:Bt,stepFields:Ut,fullField:Gt,stepToggles:Jt,requiredToggle:Yt,stepsEmpty:Zt,stepNumber:Qt,emptyState:Xt,loadingState:es,emptyStateInner:ts,errorBanner:ss,errorMessage:ns};function rs(c){const[_,k]=n.useState([]),[u,w]=n.useState(""),[E,g]=n.useState(null),[q,i]=n.useState(!0),[O,H]=n.useState(!1),[Y,L]=n.useState(!1),[Z,F]=n.useState(!1),[B,Q]=n.useState(!1),[ie,X]=n.useState(!1),[oe,ce]=n.useState(0),[de,x]=n.useState(null),m=n.useRef(0),p=n.useRef(c);p.current=c;const y=n.useCallback(async()=>{const r=++m.current;i(!0),x(null);try{const o=await ze();if(r!==m.current)return;k(o),w(f=>f&&o.some(({template:C})=>C.id===f)?f:o[0]?.template.id||"")}catch(o){if(r!==m.current)return;x(String(o?.message||o||"Unable to load workflows."))}finally{r===m.current&&i(!1)}},[c]);n.useEffect(()=>{k([]),w(""),g(null),y()},[y,c]),n.useEffect(()=>{let r=!1;if(!u){g(null),H(!1);return}return H(!0),x(null),Me(u).then(o=>{r||g(o)}).catch(o=>{r||(g(null),x(String(o?.message||o||"Unable to load workflow.")))}).finally(()=>{r||H(!1)}),()=>{r=!0}},[oe,u]);const S=n.useCallback(()=>{if(u&&!E){ce(r=>r+1);return}y()},[y,E,u]),j=n.useCallback(async r=>{const o=c;L(!0),x(null);try{const f=await Oe(r);return p.current!==o||(g(f),w(f.template.id),await y(),p.current===o&&w(f.template.id)),!0}catch(f){return p.current!==o||x(String(f?.message||f||"Unable to create workflow.")),!1}finally{L(!1)}},[y,c]),V=n.useCallback(async r=>{if(!u)return!1;const o=c,f=u;F(!0),x(null);try{const C=await He(f,{name:r.name,description:r.description,steps:r.steps});return p.current!==o||(g(C),await y(),p.current===o&&w(f)),!0}catch(C){return p.current!==o||x(String(C?.message||C||"Unable to save workflow draft.")),!1}finally{F(!1)}},[y,u,c]),T=n.useCallback(async()=>{if(!u)return!1;const r=c,o=u;Q(!0),x(null);try{const f=await Le(o);return p.current!==r||(g(f),await y(),p.current===r&&w(o)),!0}catch(f){return p.current!==r||x(String(f?.message||f||"Unable to publish workflow.")),!1}finally{Q(!1)}},[y,u,c]),A=n.useCallback(async()=>{if(!u)return!1;const r=c,o=u;X(!0),x(null);try{const f=await Fe(o);return p.current!==r||(g(f),await y(),p.current===r&&w(o)),!0}catch(f){return p.current!==r||x(String(f?.message||f||"Unable to create workflow draft.")),!1}finally{X(!1)}},[y,u,c]);return{workflows:_,selectedWorkflowId:u,selectedWorkflow:E,loadingLibrary:q,loadingDetails:O,creatingWorkflow:Y,savingWorkflow:Z,publishingWorkflow:B,creatingDraft:ie,error:de,setSelectedWorkflowId:w,refreshLibrary:y,retry:S,createWorkflow:j,saveDraft:V,publishDraft:T,createNextDraft:A,clearError:()=>x(null)}}const as="_title_lvjgs_1",ls="_message_lvjgs_7",is="_actions_lvjgs_13",be={title:as,message:ls,actions:is};function os({isOpen:c,workflowName:_,versionNumber:k,busy:u,onCancel:w,onPublish:E,theme:g}){return e.jsx(Be,{isOpen:c,onClose:w,title:e.jsxs("span",{className:be.title,children:[e.jsx(le,{size:18})," Publish Workflow"]}),size:"sm",closeOnOverlayClick:!1,closeDisabled:u,theme:g,footer:e.jsxs("div",{className:be.actions,children:[e.jsx("button",{type:"button",className:"tf-button-secondary",onClick:w,disabled:u,"data-modal-initial-focus":!0,children:"Cancel"}),e.jsxs("button",{type:"button",className:"tf-button-primary",onClick:E,disabled:u,children:[u?e.jsx(J,{size:15,className:$.spinner}):e.jsx(le,{size:15}),"Publish Version ",k]})]}),children:e.jsxs("p",{className:be.message,children:["Publish ",e.jsx("strong",{children:_})," as Version ",k,"? Published versions are immutable. Future changes require a new draft."]})})}const re="draft";function cs(c){return c.draftVersionId&&c.latestPublishedVersion?.versionNumber?`Version ${c.latestPublishedVersion.versionNumber} published`:c.draftVersionId?"Unpublished":c.latestPublishedVersion?.versionNumber?`Version ${c.latestPublishedVersion.versionNumber}`:"No version"}function ds(c){if(!c)return"Not published";const _=new Date(c);return Number.isNaN(_.getTime())?"Not published":_.toLocaleDateString()}function ae(c,_,k){return JSON.stringify({name:c,description:_,steps:k.map(({clientKey:u,...w})=>w)})}function ws({workspaceId:c,libraryTrayOpen:_=!0,onCloseLibraryTray:k,assigneeOptions:u=[],theme:w,onUnsavedChangesChange:E}){const{workflows:g,selectedWorkflowId:q,selectedWorkflow:i,loadingLibrary:O,loadingDetails:H,creatingWorkflow:Y,savingWorkflow:L,publishingWorkflow:Z,creatingDraft:F,error:B,setSelectedWorkflowId:Q,retry:ie,createWorkflow:X,saveDraft:oe,publishDraft:ce,createNextDraft:de,clearError:x}=rs(c),[m,p]=n.useState(!1),[y,S]=n.useState(!1),[j,V]=n.useState(""),[T,A]=n.useState(""),[r,o]=n.useState([]),[f,C]=n.useState(""),[P,ee]=n.useState(!1),[te,U]=n.useState(""),[ue,W]=n.useState(new Set),[he,fe]=n.useState(null),[Ne,z]=n.useState(!1),me=n.useRef(null),se=n.useRef(new Map),K=n.useRef(null),D=n.useMemo(()=>i?te===re&&i.draft?i.draft:i.publishedVersions.find(({version:a})=>a.id===te)||i.draft||i.publishedVersions[0]||null:null,[te,i]),we=D?.version.status==="draft"?re:D?.version.id||"",ve=n.useMemo(()=>ae(j,T,r),[T,j,r]),N=m||D?.version.status==="draft",I=N&&ve!==f,b=Y||L||Z||F,ke=(i?.publishedVersions[0]?.version.versionNumber||0)+1,xe=n.useMemo(()=>u.filter(({kind:t,archivedAt:a})=>t!=="unassigned"&&!a),[u]),Se=n.useMemo(()=>Ue(xe),[xe]);n.useEffect(()=>{p(!1),S(!1),U(""),W(new Set),z(!1),K.current=null},[c]),n.useEffect(()=>{if(!i||m||!D)return;const t=D.version.name||i.template.name,a=D.version.description??i.template.description??"",d=D.steps.map(h=>({...h,clientKey:h.id}));V(t),A(a),o(d),C(ae(t,a,d));const l=K.current;S(!1),l?(W(new Set(d.filter((h,v)=>l.has(v)).map(({clientKey:h})=>h))),K.current=null):W(new Set),ee(!1)},[m,D,i]),n.useEffect(()=>{if(!I)return;const t=a=>{a.preventDefault(),a.returnValue=""};return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[I]),n.useEffect(()=>(E?.(I),()=>E?.(!1)),[I,E]);const ne=t=>{if(!I){t();return}fe(()=>t)},Ce=()=>{const t=he;fe(null),t?.()},ye=()=>{ne(()=>{x();const t=[];p(!0),S(!0),V(""),A(""),o(t),C(ae("","",t)),W(new Set),ee(!1),window.setTimeout(()=>me.current?.focus(),0)})},De=()=>{ne(()=>{if(x(),p(!1),S(!1),i){const t=i.draft?.version.name||i.template.name,a=i.draft?.version.description??i.publishedVersions[0]?.version.description??i.template.description??"",d=(i.draft?.steps||i.publishedVersions[0]?.steps||[]).map(l=>({...l,clientKey:l.id}));V(t),A(a),o(d),C(ae(t,a,d))}})},Ee=()=>{const t=`new-step-${Date.now()}-${r.length}`;o(a=>[...a,{id:t,clientKey:t,workflowVersionId:i?.draft?.version.id||"",position:a.length,name:"",instructions:"",ownerType:null,ownerId:null,expectedArtifact:null,requiresCommentEvidence:!1,isRequired:!0}]),W(a=>new Set(a).add(t)),window.setTimeout(()=>se.current.get(t)?.focus(),0)},M=(t,a)=>{o(d=>d.map(l=>l.clientKey===t?{...l,...a}:l))},ge=(t,a)=>{const d=t+a;d<0||d>=r.length||o(l=>{const h=[...l];return[h[t],h[d]]=[h[d],h[t]],h.map((v,R)=>({...v,position:R}))})},We=()=>r.map(t=>{const{clientKey:a,id:d,workflowVersionId:l,position:h,...v}=t;return{...v,name:t.name.trim(),instructions:t.instructions,ownerType:t.ownerType??null,ownerId:t.ownerId??null,expectedArtifact:t.expectedArtifact??null,requiresCommentEvidence:t.requiresCommentEvidence===!0,isRequired:t.isRequired}}),Ie=async()=>{if(ee(!0),!j.trim()){S(!0),window.setTimeout(()=>me.current?.focus(),0);return}const t=r.find(l=>!l.name.trim());if(t){W(l=>new Set(l).add(t.clientKey)),window.setTimeout(()=>se.current.get(t.clientKey)?.focus(),0);return}const a={name:j.trim(),description:T.trim(),steps:We()};K.current=new Set(r.map((l,h)=>ue.has(l.clientKey)?h:-1).filter(l=>l>=0)),(m?await X(a):await oe(a))?(p(!1),ee(!1)):K.current=null},Te=t=>{W(a=>{const d=new Set(a);return d.has(t)?d.delete(t):d.add(t),d})},Ke=t=>{t!==we&&ne(()=>{S(!1),U(t)})},Re=async()=>{K.current=new Set(r.map((a,d)=>ue.has(a.clientKey)?d:-1).filter(a=>a>=0)),await ce()||(K.current=null),z(!1)},$e=async()=>{const t=te;U(re),await de()||U(t)},qe=t=>{t===q&&!m||ne(()=>{p(!1),S(!1),U(""),z(!1),Q(t)})},Ve=e.jsxs("aside",{className:`${$.docTrayPanel} ${_?$.docTrayPanelOpen:""}`.trim(),"aria-hidden":!_,children:[e.jsxs("div",{className:s.libraryHeader,children:[e.jsxs("span",{className:`${s.libraryTitle} tf-label-micro`,children:[e.jsx(le,{size:14})," Workflow Library"]}),O?e.jsx(J,{size:14,className:$.spinner}):null,k?e.jsx("button",{type:"button",className:"tf-control-icon",onClick:k,title:"Collapse workflow library","aria-label":"Collapse workflow library",children:e.jsx(Qe,{size:16})}):null]}),e.jsx("div",{className:`${s.libraryContent} tf-scrollbar tf-tray-scroll-viewport`,children:g.length>0?e.jsx("div",{className:s.libraryList,children:g.map(t=>e.jsxs("button",{type:"button",className:`${s.libraryItem} ${t.template.id===q&&!m?s.libraryItemSelected:""}`.trim(),disabled:b,onClick:()=>qe(t.template.id),"aria-pressed":t.template.id===q&&!m,children:[e.jsxs("span",{className:s.libraryItemCopy,children:[e.jsx("span",{className:s.libraryItemName,children:t.template.name}),e.jsx("span",{className:s.libraryItemMeta,children:cs(t)})]}),e.jsxs("span",{className:s.libraryBadges,children:[t.draftVersionId?e.jsx("span",{className:"tf-chip-warning",children:"Draft"}):null,t.latestPublishedVersion?e.jsx("span",{className:"tf-chip-success",children:"Published"}):null]})]},t.template.id))}):O?null:e.jsx("p",{className:"tf-text-helper",children:"No workflows configured yet."})})]}),Ae=m||!!i;return e.jsxs("div",{className:`${s.root} ${_?s.trayOpen:""}`.trim(),children:[Ve,e.jsx("main",{className:`${s.main} tf-scrollbar`,children:e.jsxs("div",{className:s.content,children:[e.jsxs("header",{className:s.pageHeader,children:[e.jsxs("div",{className:s.pageHeading,children:[e.jsx("h2",{className:"tf-heading-section",children:"Workflow Manager"}),e.jsx("p",{className:"tf-text-helper",children:"Design reusable workflows for Taskforce agents."})]}),e.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:ye,disabled:b,children:[e.jsx(pe,{size:15})," New Workflow"]})]}),B?e.jsxs("div",{className:`${s.errorBanner} tf-surface-inset tf-text-error`,role:"alert",children:[e.jsxs("span",{className:s.errorMessage,children:[e.jsx(je,{size:14})," ",B]}),e.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:ie,children:"Retry"})]}):null,H||O&&!i&&!m?e.jsx("div",{className:s.loadingState,"aria-live":"polite",children:e.jsx(J,{size:20,className:$.spinner})}):B&&q&&!i&&!m?e.jsx("div",{className:s.emptyState,children:e.jsxs("div",{className:s.emptyStateInner,children:[e.jsx(je,{size:24}),e.jsx("h3",{className:"tf-heading-card",children:"Workflow details unavailable"}),e.jsx("p",{className:"tf-text-helper",children:"Retry the request to load this workflow."})]})}):Ae?e.jsxs("div",{className:s.editor,children:[e.jsxs("div",{className:s.stickyToolbar,role:"toolbar","aria-label":N?"Workflow draft actions":"Workflow version actions",children:[N?e.jsxs("div",{className:s.toolbarGroup,children:[e.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:Ee,disabled:b,children:[e.jsx(pe,{size:14})," Add Step"]}),e.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>W(new Set(r.map(({clientKey:t})=>t))),disabled:r.length===0,title:"Expand all steps","aria-label":"Expand all steps",children:e.jsx(Xe,{size:15})}),e.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>W(new Set),disabled:r.length===0,title:"Collapse all steps","aria-label":"Collapse all steps",children:e.jsx(et,{size:15})})]}):e.jsx("span",{}),e.jsxs("div",{className:s.toolbarGroup,children:[!m&&i?e.jsxs("select",{className:`${s.versionSelect} tf-field-shell`,"aria-label":"Workflow version",value:we,onChange:t=>Ke(t.target.value),disabled:b,children:[i.draft?e.jsx("option",{value:re,children:"Draft"}):null,i.publishedVersions.map(({version:t})=>e.jsxs("option",{value:t.id,children:["Version ",t.versionNumber]},t.id))]}):null,m?e.jsx("span",{className:"tf-chip-warning",children:"Draft"}):null,m?e.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:De,disabled:b,children:"Cancel"}):null,N?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:s.visuallyHidden,role:"status","aria-live":"polite",children:I?"Workflow has unsaved changes.":"Workflow draft is saved."}),e.jsxs("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:()=>{Ie()},disabled:!I||b,children:[Y||L?e.jsx(J,{size:15,className:$.spinner}):e.jsx(tt,{size:15})," Save Draft"]}),m?null:e.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>z(!0),disabled:I||r.length===0||b,title:I?"Save the draft before publishing.":r.length===0?"Add at least one step before publishing.":"Publish this workflow version",children:[e.jsx(st,{size:15})," Publish"]})]}):i?.draft?null:e.jsxs("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:()=>{$e()},disabled:b,children:[F?e.jsx(J,{size:15,className:$.spinner}):e.jsx(nt,{size:15})," Create New Draft"]})]})]}),e.jsx("div",{className:s.detailHeader,children:e.jsx("div",{className:s.metadataEditor,children:y?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"tf-field-stack",children:[e.jsx("label",{className:"tf-field-label",htmlFor:"workflow-draft-name",children:"Workflow name"}),e.jsx("input",{id:"workflow-draft-name",ref:me,className:"tf-field-shell",value:j,onChange:t=>V(t.target.value),"aria-invalid":P&&!j.trim(),"aria-describedby":P&&!j.trim()?"workflow-draft-name-error":void 0,readOnly:b}),P&&!j.trim()?e.jsx("span",{id:"workflow-draft-name-error",className:"tf-text-error",children:"Workflow name is required."}):null]}),e.jsxs("div",{className:"tf-field-stack",children:[e.jsx("label",{className:"tf-field-label",htmlFor:"workflow-draft-description",children:"Description"}),e.jsx("textarea",{id:"workflow-draft-description",className:"tf-field-shell",rows:3,value:T,onChange:t=>A(t.target.value),readOnly:b})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:s.titleRow,children:[e.jsx("h3",{className:"tf-heading-card",children:j||"Untitled workflow"}),e.jsx("div",{className:s.statusRow,children:N&&!m?e.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>S(!0),title:"Edit workflow details","aria-label":"Edit workflow details",children:e.jsx(rt,{size:14})}):null})]}),T?e.jsx("p",{className:`${s.description} tf-text-body`,children:T}):null]})})}),!m&&i?e.jsxs("div",{className:s.metrics,children:[e.jsxs("div",{className:s.metric,children:[e.jsx("span",{className:"tf-label-micro",children:"Current version"}),e.jsx("strong",{children:D?.version.status==="draft"?"Draft":`Version ${D?.version.versionNumber||1}`})]}),e.jsxs("div",{className:s.metric,children:[e.jsx("span",{className:"tf-label-micro",children:"Steps"}),e.jsx("strong",{children:r.length})]}),e.jsxs("div",{className:s.metric,children:[e.jsx("span",{className:"tf-label-micro",children:"Last published"}),e.jsx("strong",{children:ds(i.publishedVersions[0]?.version.publishedAt)})]})]}):null,e.jsxs("section",{className:s.section,children:[e.jsx("div",{className:s.sectionHeader,children:e.jsx("h4",{className:"tf-heading-card",children:"Workflow Steps"})}),r.length>0?e.jsx("div",{className:s.stepList,children:r.map((t,a)=>{const d=ue.has(t.clientKey);return e.jsxs("div",{className:s.stepEditor,children:[e.jsxs("div",{className:`${s.stepToolbar} ${d?s.stepToolbarExpanded:""}`.trim(),children:[e.jsxs("button",{type:"button",className:s.stepExpandButton,onClick:()=>Te(t.clientKey),"aria-expanded":d,"aria-controls":`workflow-step-fields-${t.clientKey}`,children:[d?e.jsx(at,{size:15}):e.jsx(lt,{size:15}),e.jsx("span",{className:s.stepNumber,children:a+1}),e.jsx("strong",{children:t.name.trim()||"Untitled step"})]}),e.jsxs("div",{className:s.stepSummary,children:[e.jsx("span",{children:Ge(t.ownerId,u)}),e.jsx("span",{className:t.isRequired?"tf-chip-neutral":"tf-chip-warning",children:t.isRequired?"Required":"Optional"})]}),N?e.jsxs("div",{className:s.stepActions,children:[e.jsx("button",{type:"button",className:"tf-control-icon",title:"Move step up","aria-label":`Move step ${a+1} up`,onClick:()=>ge(a,-1),disabled:b||a===0,children:e.jsx(it,{size:14})}),e.jsx("button",{type:"button",className:"tf-control-icon",title:"Move step down","aria-label":`Move step ${a+1} down`,onClick:()=>ge(a,1),disabled:b||a===r.length-1,children:e.jsx(ot,{size:14})}),e.jsx("button",{type:"button",className:"tf-control-icon",title:"Remove step","aria-label":`Remove step ${a+1}`,onClick:()=>o(l=>l.filter(({clientKey:h})=>h!==t.clientKey)),disabled:b,children:e.jsx(ct,{size:14})})]}):null]}),d?e.jsxs("div",{id:`workflow-step-fields-${t.clientKey}`,className:s.stepFields,children:[e.jsxs("div",{className:"tf-field-stack",children:[e.jsx("label",{className:"tf-field-label",htmlFor:`workflow-step-name-${t.clientKey}`,children:"Step name"}),e.jsx("input",{id:`workflow-step-name-${t.clientKey}`,ref:l=>{l?se.current.set(t.clientKey,l):se.current.delete(t.clientKey)},className:"tf-field-shell",value:t.name,onChange:l=>M(t.clientKey,{name:l.target.value}),"aria-invalid":P&&!t.name.trim(),"aria-describedby":P&&!t.name.trim()?`workflow-step-name-error-${t.clientKey}`:void 0,disabled:!N,readOnly:b}),P&&!t.name.trim()?e.jsx("span",{id:`workflow-step-name-error-${t.clientKey}`,className:"tf-text-error",children:"Step name is required."}):null]}),e.jsxs("div",{className:"tf-field-stack",children:[e.jsx("label",{className:"tf-field-label",id:`workflow-step-owner-label-${t.clientKey}`,children:"Owner"}),(()=>{const l=Je(Se,t.ownerId),h=l.find(({value:v})=>String(v)===String(t.ownerId||"unassigned"))||l[0];return e.jsx(Ye,{value:t.ownerId||"unassigned",options:l,disabled:!N||b,ariaLabelledBy:`workflow-step-owner-label-${t.clientKey}`,portalPanel:!0,panelMinWidth:280,panelAlign:"start",searchable:!0,searchPlaceholder:"Search owners...",noResultsText:"No owners found.",triggerContent:h?e.jsx(_e,{option:h}):void 0,renderOptionContent:v=>{const R=l.find(({value:G})=>String(G)===String(v.value));return R?e.jsx(_e,{option:R}):v.label},onChange:v=>{const R=String(v),G=l.find(({value:Pe})=>String(Pe)===R);M(t.clientKey,{ownerId:G?.kind==="unassigned"?null:R,ownerType:G?.kind==="agent"?"agent":G?.kind==="member"?"user":null})}})})()]}),e.jsxs("div",{className:`${s.fullField} tf-field-stack`,children:[e.jsx("label",{className:"tf-field-label",htmlFor:`workflow-step-instructions-${t.clientKey}`,children:"Instructions"}),e.jsx("textarea",{id:`workflow-step-instructions-${t.clientKey}`,className:"tf-field-shell",rows:4,value:t.instructions,onChange:l=>M(t.clientKey,{instructions:l.target.value}),placeholder:"Describe the work to complete in this step.",disabled:!N,readOnly:b})]}),e.jsxs("div",{className:"tf-field-stack",children:[e.jsx("label",{className:"tf-field-label",htmlFor:`workflow-step-artifact-${t.clientKey}`,children:"Output label"}),e.jsx("input",{id:`workflow-step-artifact-${t.clientKey}`,className:"tf-field-shell",value:t.expectedArtifact||"",onChange:l=>M(t.clientKey,{expectedArtifact:l.target.value||null}),placeholder:"Optional output description",disabled:!N,readOnly:b})]}),e.jsxs("div",{className:s.stepToggles,children:[e.jsxs("label",{className:s.requiredToggle,title:"Requires the step owner to add a task comment before completing this step.",children:[e.jsx("input",{type:"checkbox",checked:t.requiresCommentEvidence===!0,onChange:l=>M(t.clientKey,{requiresCommentEvidence:l.target.checked}),disabled:!N||b}),"Require task comment"]}),e.jsxs("label",{className:s.requiredToggle,title:"Marks this step as mandatory when execution policy is enforced.",children:[e.jsx("input",{type:"checkbox",checked:t.isRequired,onChange:l=>M(t.clientKey,{isRequired:l.target.checked}),disabled:!N||b}),"Required step"]})]})]}):null]},t.clientKey)})}):e.jsx("div",{className:s.stepsEmpty,children:e.jsx("p",{className:"tf-text-helper",children:"No steps have been added yet."})})]})]}):e.jsx("div",{className:s.emptyState,children:e.jsxs("div",{className:s.emptyStateInner,children:[e.jsx(le,{size:30}),e.jsx("h3",{className:"tf-heading-card",children:"No workflows yet"}),e.jsx("p",{className:"tf-text-helper",children:"Create a workflow to begin defining a reusable process."}),e.jsxs("button",{type:"button",className:"tf-button-primary",onClick:ye,children:[e.jsx(pe,{size:15})," New Workflow"]})]})})]})}),e.jsx(Ze,{isOpen:!!he,onKeepEditing:()=>fe(null),onDiscard:Ce,theme:w}),e.jsx(os,{isOpen:Ne,workflowName:j,versionNumber:ke,busy:Z,onCancel:()=>z(!1),onPublish:()=>{Re()},theme:w})]})}export{ws as WorkflowManagerModule};
1
+ import{r as n,j as e}from"./vendor-react-CKJs5o3c.js";import{a2 as ze,a3 as Me,a4 as Oe,a5 as He,a6 as Le,a7 as Fe,M as Be,t as $,a8 as Ue,a9 as Ge,aa as Je,T as Ye,ab as _e,ac as Ze}from"./index-CTsDBaef.js";import{w as J,az as le,ak as Qe,t as pe,Z as je,bj as Xe,bk as et,a6 as tt,bl as st,bm as nt,a7 as rt,a as at,x as lt,v as it,A as ot,r as ct}from"./vendor-icons-Bsq-mcEn.js";import"./vendor-markdown-_lhNCyq-.js";import"./vendor-dnd-CJ-AjP-Y.js";import"./vendor-router-AqJMU8Lz.js";const dt="_root_1bn9e_1",ut="_main_1bn9e_13",ft="_trayOpen_1bn9e_21",mt="_libraryHeader_1bn9e_25",pt="_libraryTitle_1bn9e_34",bt="_libraryContent_1bn9e_41",ht="_libraryList_1bn9e_48",wt="_libraryItem_1bn9e_54",xt="_libraryItemSelected_1bn9e_75",yt="_libraryItemCopy_1bn9e_80",gt="_libraryItemName_1bn9e_84",_t="_libraryItemMeta_1bn9e_94",jt="_libraryBadges_1bn9e_101",Nt="_statusRow_1bn9e_102",vt="_content_1bn9e_109",kt="_visuallyHidden_1bn9e_115",St="_pageHeader_1bn9e_127",Ct="_pageHeading_1bn9e_136",Dt="_detailHeader_1bn9e_144",Et="_metadataEditor_1bn9e_148",Wt="_titleRow_1bn9e_154",It="_editor_1bn9e_169",Tt="_stickyToolbar_1bn9e_173",Kt="_toolbarGroup_1bn9e_188",Rt="_versionSelect_1bn9e_194",$t="_description_1bn9e_211",qt="_metrics_1bn9e_217",Vt="_metric_1bn9e_217",At="_section_1bn9e_249",Pt="_sectionHeader_1bn9e_253",zt="_stepToolbar_1bn9e_254",Mt="_stepActions_1bn9e_255",Ot="_stepList_1bn9e_266",Ht="_stepEditor_1bn9e_273",Lt="_stepToolbarExpanded_1bn9e_285",Ft="_stepExpandButton_1bn9e_289",Bt="_stepSummary_1bn9e_311",Ut="_stepFields_1bn9e_328",Gt="_fullField_1bn9e_335",Jt="_stepToggles_1bn9e_337",Yt="_requiredToggle_1bn9e_345",Zt="_stepsEmpty_1bn9e_356",Qt="_stepNumber_1bn9e_376",Xt="_emptyState_1bn9e_382",es="_loadingState_1bn9e_383",ts="_emptyStateInner_1bn9e_391",ss="_errorBanner_1bn9e_399",ns="_errorMessage_1bn9e_407",s={root:dt,main:ut,trayOpen:ft,libraryHeader:mt,libraryTitle:pt,libraryContent:bt,libraryList:ht,libraryItem:wt,libraryItemSelected:xt,libraryItemCopy:yt,libraryItemName:gt,libraryItemMeta:_t,libraryBadges:jt,statusRow:Nt,content:vt,visuallyHidden:kt,pageHeader:St,pageHeading:Ct,detailHeader:Dt,metadataEditor:Et,titleRow:Wt,editor:It,stickyToolbar:Tt,toolbarGroup:Kt,versionSelect:Rt,description:$t,metrics:qt,metric:Vt,section:At,sectionHeader:Pt,stepToolbar:zt,stepActions:Mt,stepList:Ot,stepEditor:Ht,stepToolbarExpanded:Lt,stepExpandButton:Ft,stepSummary:Bt,stepFields:Ut,fullField:Gt,stepToggles:Jt,requiredToggle:Yt,stepsEmpty:Zt,stepNumber:Qt,emptyState:Xt,loadingState:es,emptyStateInner:ts,errorBanner:ss,errorMessage:ns};function rs(c){const[_,k]=n.useState([]),[u,w]=n.useState(""),[E,g]=n.useState(null),[q,i]=n.useState(!0),[O,H]=n.useState(!1),[Y,L]=n.useState(!1),[Z,F]=n.useState(!1),[B,Q]=n.useState(!1),[ie,X]=n.useState(!1),[oe,ce]=n.useState(0),[de,x]=n.useState(null),m=n.useRef(0),p=n.useRef(c);p.current=c;const y=n.useCallback(async()=>{const r=++m.current;i(!0),x(null);try{const o=await ze();if(r!==m.current)return;k(o),w(f=>f&&o.some(({template:C})=>C.id===f)?f:o[0]?.template.id||"")}catch(o){if(r!==m.current)return;x(String(o?.message||o||"Unable to load workflows."))}finally{r===m.current&&i(!1)}},[c]);n.useEffect(()=>{k([]),w(""),g(null),y()},[y,c]),n.useEffect(()=>{let r=!1;if(!u){g(null),H(!1);return}return H(!0),x(null),Me(u).then(o=>{r||g(o)}).catch(o=>{r||(g(null),x(String(o?.message||o||"Unable to load workflow.")))}).finally(()=>{r||H(!1)}),()=>{r=!0}},[oe,u]);const S=n.useCallback(()=>{if(u&&!E){ce(r=>r+1);return}y()},[y,E,u]),j=n.useCallback(async r=>{const o=c;L(!0),x(null);try{const f=await Oe(r);return p.current!==o||(g(f),w(f.template.id),await y(),p.current===o&&w(f.template.id)),!0}catch(f){return p.current!==o||x(String(f?.message||f||"Unable to create workflow.")),!1}finally{L(!1)}},[y,c]),V=n.useCallback(async r=>{if(!u)return!1;const o=c,f=u;F(!0),x(null);try{const C=await He(f,{name:r.name,description:r.description,steps:r.steps});return p.current!==o||(g(C),await y(),p.current===o&&w(f)),!0}catch(C){return p.current!==o||x(String(C?.message||C||"Unable to save workflow draft.")),!1}finally{F(!1)}},[y,u,c]),T=n.useCallback(async()=>{if(!u)return!1;const r=c,o=u;Q(!0),x(null);try{const f=await Le(o);return p.current!==r||(g(f),await y(),p.current===r&&w(o)),!0}catch(f){return p.current!==r||x(String(f?.message||f||"Unable to publish workflow.")),!1}finally{Q(!1)}},[y,u,c]),A=n.useCallback(async()=>{if(!u)return!1;const r=c,o=u;X(!0),x(null);try{const f=await Fe(o);return p.current!==r||(g(f),await y(),p.current===r&&w(o)),!0}catch(f){return p.current!==r||x(String(f?.message||f||"Unable to create workflow draft.")),!1}finally{X(!1)}},[y,u,c]);return{workflows:_,selectedWorkflowId:u,selectedWorkflow:E,loadingLibrary:q,loadingDetails:O,creatingWorkflow:Y,savingWorkflow:Z,publishingWorkflow:B,creatingDraft:ie,error:de,setSelectedWorkflowId:w,refreshLibrary:y,retry:S,createWorkflow:j,saveDraft:V,publishDraft:T,createNextDraft:A,clearError:()=>x(null)}}const as="_title_lvjgs_1",ls="_message_lvjgs_7",is="_actions_lvjgs_13",be={title:as,message:ls,actions:is};function os({isOpen:c,workflowName:_,versionNumber:k,busy:u,onCancel:w,onPublish:E,theme:g}){return e.jsx(Be,{isOpen:c,onClose:w,title:e.jsxs("span",{className:be.title,children:[e.jsx(le,{size:18})," Publish Workflow"]}),size:"sm",closeOnOverlayClick:!1,closeDisabled:u,theme:g,footer:e.jsxs("div",{className:be.actions,children:[e.jsx("button",{type:"button",className:"tf-button-secondary",onClick:w,disabled:u,"data-modal-initial-focus":!0,children:"Cancel"}),e.jsxs("button",{type:"button",className:"tf-button-primary",onClick:E,disabled:u,children:[u?e.jsx(J,{size:15,className:$.spinner}):e.jsx(le,{size:15}),"Publish Version ",k]})]}),children:e.jsxs("p",{className:be.message,children:["Publish ",e.jsx("strong",{children:_})," as Version ",k,"? Published versions are immutable. Future changes require a new draft."]})})}const re="draft";function cs(c){return c.draftVersionId&&c.latestPublishedVersion?.versionNumber?`Version ${c.latestPublishedVersion.versionNumber} published`:c.draftVersionId?"Unpublished":c.latestPublishedVersion?.versionNumber?`Version ${c.latestPublishedVersion.versionNumber}`:"No version"}function ds(c){if(!c)return"Not published";const _=new Date(c);return Number.isNaN(_.getTime())?"Not published":_.toLocaleDateString()}function ae(c,_,k){return JSON.stringify({name:c,description:_,steps:k.map(({clientKey:u,...w})=>w)})}function ws({workspaceId:c,libraryTrayOpen:_=!0,onCloseLibraryTray:k,assigneeOptions:u=[],theme:w,onUnsavedChangesChange:E}){const{workflows:g,selectedWorkflowId:q,selectedWorkflow:i,loadingLibrary:O,loadingDetails:H,creatingWorkflow:Y,savingWorkflow:L,publishingWorkflow:Z,creatingDraft:F,error:B,setSelectedWorkflowId:Q,retry:ie,createWorkflow:X,saveDraft:oe,publishDraft:ce,createNextDraft:de,clearError:x}=rs(c),[m,p]=n.useState(!1),[y,S]=n.useState(!1),[j,V]=n.useState(""),[T,A]=n.useState(""),[r,o]=n.useState([]),[f,C]=n.useState(""),[P,ee]=n.useState(!1),[te,U]=n.useState(""),[ue,W]=n.useState(new Set),[he,fe]=n.useState(null),[Ne,z]=n.useState(!1),me=n.useRef(null),se=n.useRef(new Map),K=n.useRef(null),D=n.useMemo(()=>i?te===re&&i.draft?i.draft:i.publishedVersions.find(({version:a})=>a.id===te)||i.draft||i.publishedVersions[0]||null:null,[te,i]),we=D?.version.status==="draft"?re:D?.version.id||"",ve=n.useMemo(()=>ae(j,T,r),[T,j,r]),N=m||D?.version.status==="draft",I=N&&ve!==f,b=Y||L||Z||F,ke=(i?.publishedVersions[0]?.version.versionNumber||0)+1,xe=n.useMemo(()=>u.filter(({kind:t,archivedAt:a})=>t!=="unassigned"&&!a),[u]),Se=n.useMemo(()=>Ue(xe),[xe]);n.useEffect(()=>{p(!1),S(!1),U(""),W(new Set),z(!1),K.current=null},[c]),n.useEffect(()=>{if(!i||m||!D)return;const t=D.version.name||i.template.name,a=D.version.description??i.template.description??"",d=D.steps.map(h=>({...h,clientKey:h.id}));V(t),A(a),o(d),C(ae(t,a,d));const l=K.current;S(!1),l?(W(new Set(d.filter((h,v)=>l.has(v)).map(({clientKey:h})=>h))),K.current=null):W(new Set),ee(!1)},[m,D,i]),n.useEffect(()=>{if(!I)return;const t=a=>{a.preventDefault(),a.returnValue=""};return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[I]),n.useEffect(()=>(E?.(I),()=>E?.(!1)),[I,E]);const ne=t=>{if(!I){t();return}fe(()=>t)},Ce=()=>{const t=he;fe(null),t?.()},ye=()=>{ne(()=>{x();const t=[];p(!0),S(!0),V(""),A(""),o(t),C(ae("","",t)),W(new Set),ee(!1),window.setTimeout(()=>me.current?.focus(),0)})},De=()=>{ne(()=>{if(x(),p(!1),S(!1),i){const t=i.draft?.version.name||i.template.name,a=i.draft?.version.description??i.publishedVersions[0]?.version.description??i.template.description??"",d=(i.draft?.steps||i.publishedVersions[0]?.steps||[]).map(l=>({...l,clientKey:l.id}));V(t),A(a),o(d),C(ae(t,a,d))}})},Ee=()=>{const t=`new-step-${Date.now()}-${r.length}`;o(a=>[...a,{id:t,clientKey:t,workflowVersionId:i?.draft?.version.id||"",position:a.length,name:"",instructions:"",ownerType:null,ownerId:null,expectedArtifact:null,requiresCommentEvidence:!1,isRequired:!0}]),W(a=>new Set(a).add(t)),window.setTimeout(()=>se.current.get(t)?.focus(),0)},M=(t,a)=>{o(d=>d.map(l=>l.clientKey===t?{...l,...a}:l))},ge=(t,a)=>{const d=t+a;d<0||d>=r.length||o(l=>{const h=[...l];return[h[t],h[d]]=[h[d],h[t]],h.map((v,R)=>({...v,position:R}))})},We=()=>r.map(t=>{const{clientKey:a,id:d,workflowVersionId:l,position:h,...v}=t;return{...v,name:t.name.trim(),instructions:t.instructions,ownerType:t.ownerType??null,ownerId:t.ownerId??null,expectedArtifact:t.expectedArtifact??null,requiresCommentEvidence:t.requiresCommentEvidence===!0,isRequired:t.isRequired}}),Ie=async()=>{if(ee(!0),!j.trim()){S(!0),window.setTimeout(()=>me.current?.focus(),0);return}const t=r.find(l=>!l.name.trim());if(t){W(l=>new Set(l).add(t.clientKey)),window.setTimeout(()=>se.current.get(t.clientKey)?.focus(),0);return}const a={name:j.trim(),description:T.trim(),steps:We()};K.current=new Set(r.map((l,h)=>ue.has(l.clientKey)?h:-1).filter(l=>l>=0)),(m?await X(a):await oe(a))?(p(!1),ee(!1)):K.current=null},Te=t=>{W(a=>{const d=new Set(a);return d.has(t)?d.delete(t):d.add(t),d})},Ke=t=>{t!==we&&ne(()=>{S(!1),U(t)})},Re=async()=>{K.current=new Set(r.map((a,d)=>ue.has(a.clientKey)?d:-1).filter(a=>a>=0)),await ce()||(K.current=null),z(!1)},$e=async()=>{const t=te;U(re),await de()||U(t)},qe=t=>{t===q&&!m||ne(()=>{p(!1),S(!1),U(""),z(!1),Q(t)})},Ve=e.jsxs("aside",{className:`${$.docTrayPanel} ${_?$.docTrayPanelOpen:""}`.trim(),"aria-hidden":!_,children:[e.jsxs("div",{className:s.libraryHeader,children:[e.jsxs("span",{className:`${s.libraryTitle} tf-label-micro`,children:[e.jsx(le,{size:14})," Workflow Library"]}),O?e.jsx(J,{size:14,className:$.spinner}):null,k?e.jsx("button",{type:"button",className:"tf-control-icon",onClick:k,title:"Collapse workflow library","aria-label":"Collapse workflow library",children:e.jsx(Qe,{size:16})}):null]}),e.jsx("div",{className:`${s.libraryContent} tf-scrollbar tf-tray-scroll-viewport`,children:g.length>0?e.jsx("div",{className:s.libraryList,children:g.map(t=>e.jsxs("button",{type:"button",className:`${s.libraryItem} ${t.template.id===q&&!m?s.libraryItemSelected:""}`.trim(),disabled:b,onClick:()=>qe(t.template.id),"aria-pressed":t.template.id===q&&!m,children:[e.jsxs("span",{className:s.libraryItemCopy,children:[e.jsx("span",{className:s.libraryItemName,children:t.template.name}),e.jsx("span",{className:s.libraryItemMeta,children:cs(t)})]}),e.jsxs("span",{className:s.libraryBadges,children:[t.draftVersionId?e.jsx("span",{className:"tf-chip-warning",children:"Draft"}):null,t.latestPublishedVersion?e.jsx("span",{className:"tf-chip-success",children:"Published"}):null]})]},t.template.id))}):O?null:e.jsx("p",{className:"tf-text-helper",children:"No workflows configured yet."})})]}),Ae=m||!!i;return e.jsxs("div",{className:`${s.root} ${_?s.trayOpen:""}`.trim(),children:[Ve,e.jsx("main",{className:`${s.main} tf-scrollbar`,children:e.jsxs("div",{className:s.content,children:[e.jsxs("header",{className:s.pageHeader,children:[e.jsxs("div",{className:s.pageHeading,children:[e.jsx("h2",{className:"tf-heading-section",children:"Workflow Manager"}),e.jsx("p",{className:"tf-text-helper",children:"Design reusable workflows for Taskforce agents."})]}),e.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:ye,disabled:b,children:[e.jsx(pe,{size:15})," New Workflow"]})]}),B?e.jsxs("div",{className:`${s.errorBanner} tf-surface-inset tf-text-error`,role:"alert",children:[e.jsxs("span",{className:s.errorMessage,children:[e.jsx(je,{size:14})," ",B]}),e.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:ie,children:"Retry"})]}):null,H||O&&!i&&!m?e.jsx("div",{className:s.loadingState,"aria-live":"polite",children:e.jsx(J,{size:20,className:$.spinner})}):B&&q&&!i&&!m?e.jsx("div",{className:s.emptyState,children:e.jsxs("div",{className:s.emptyStateInner,children:[e.jsx(je,{size:24}),e.jsx("h3",{className:"tf-heading-card",children:"Workflow details unavailable"}),e.jsx("p",{className:"tf-text-helper",children:"Retry the request to load this workflow."})]})}):Ae?e.jsxs("div",{className:s.editor,children:[e.jsxs("div",{className:s.stickyToolbar,role:"toolbar","aria-label":N?"Workflow draft actions":"Workflow version actions",children:[N?e.jsxs("div",{className:s.toolbarGroup,children:[e.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:Ee,disabled:b,children:[e.jsx(pe,{size:14})," Add Step"]}),e.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>W(new Set(r.map(({clientKey:t})=>t))),disabled:r.length===0,title:"Expand all steps","aria-label":"Expand all steps",children:e.jsx(Xe,{size:15})}),e.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>W(new Set),disabled:r.length===0,title:"Collapse all steps","aria-label":"Collapse all steps",children:e.jsx(et,{size:15})})]}):e.jsx("span",{}),e.jsxs("div",{className:s.toolbarGroup,children:[!m&&i?e.jsxs("select",{className:`${s.versionSelect} tf-field-shell`,"aria-label":"Workflow version",value:we,onChange:t=>Ke(t.target.value),disabled:b,children:[i.draft?e.jsx("option",{value:re,children:"Draft"}):null,i.publishedVersions.map(({version:t})=>e.jsxs("option",{value:t.id,children:["Version ",t.versionNumber]},t.id))]}):null,m?e.jsx("span",{className:"tf-chip-warning",children:"Draft"}):null,m?e.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:De,disabled:b,children:"Cancel"}):null,N?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:s.visuallyHidden,role:"status","aria-live":"polite",children:I?"Workflow has unsaved changes.":"Workflow draft is saved."}),e.jsxs("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:()=>{Ie()},disabled:!I||b,children:[Y||L?e.jsx(J,{size:15,className:$.spinner}):e.jsx(tt,{size:15})," Save Draft"]}),m?null:e.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>z(!0),disabled:I||r.length===0||b,title:I?"Save the draft before publishing.":r.length===0?"Add at least one step before publishing.":"Publish this workflow version",children:[e.jsx(st,{size:15})," Publish"]})]}):i?.draft?null:e.jsxs("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:()=>{$e()},disabled:b,children:[F?e.jsx(J,{size:15,className:$.spinner}):e.jsx(nt,{size:15})," Create New Draft"]})]})]}),e.jsx("div",{className:s.detailHeader,children:e.jsx("div",{className:s.metadataEditor,children:y?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"tf-field-stack",children:[e.jsx("label",{className:"tf-field-label",htmlFor:"workflow-draft-name",children:"Workflow name"}),e.jsx("input",{id:"workflow-draft-name",ref:me,className:"tf-field-shell",value:j,onChange:t=>V(t.target.value),"aria-invalid":P&&!j.trim(),"aria-describedby":P&&!j.trim()?"workflow-draft-name-error":void 0,readOnly:b}),P&&!j.trim()?e.jsx("span",{id:"workflow-draft-name-error",className:"tf-text-error",children:"Workflow name is required."}):null]}),e.jsxs("div",{className:"tf-field-stack",children:[e.jsx("label",{className:"tf-field-label",htmlFor:"workflow-draft-description",children:"Description"}),e.jsx("textarea",{id:"workflow-draft-description",className:"tf-field-shell",rows:3,value:T,onChange:t=>A(t.target.value),readOnly:b})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:s.titleRow,children:[e.jsx("h3",{className:"tf-heading-card",children:j||"Untitled workflow"}),e.jsx("div",{className:s.statusRow,children:N&&!m?e.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>S(!0),title:"Edit workflow details","aria-label":"Edit workflow details",children:e.jsx(rt,{size:14})}):null})]}),T?e.jsx("p",{className:`${s.description} tf-text-body`,children:T}):null]})})}),!m&&i?e.jsxs("div",{className:s.metrics,children:[e.jsxs("div",{className:s.metric,children:[e.jsx("span",{className:"tf-label-micro",children:"Current version"}),e.jsx("strong",{children:D?.version.status==="draft"?"Draft":`Version ${D?.version.versionNumber||1}`})]}),e.jsxs("div",{className:s.metric,children:[e.jsx("span",{className:"tf-label-micro",children:"Steps"}),e.jsx("strong",{children:r.length})]}),e.jsxs("div",{className:s.metric,children:[e.jsx("span",{className:"tf-label-micro",children:"Last published"}),e.jsx("strong",{children:ds(i.publishedVersions[0]?.version.publishedAt)})]})]}):null,e.jsxs("section",{className:s.section,children:[e.jsx("div",{className:s.sectionHeader,children:e.jsx("h4",{className:"tf-heading-card",children:"Workflow Steps"})}),r.length>0?e.jsx("div",{className:s.stepList,children:r.map((t,a)=>{const d=ue.has(t.clientKey);return e.jsxs("div",{className:s.stepEditor,children:[e.jsxs("div",{className:`${s.stepToolbar} ${d?s.stepToolbarExpanded:""}`.trim(),children:[e.jsxs("button",{type:"button",className:s.stepExpandButton,onClick:()=>Te(t.clientKey),"aria-expanded":d,"aria-controls":`workflow-step-fields-${t.clientKey}`,children:[d?e.jsx(at,{size:15}):e.jsx(lt,{size:15}),e.jsx("span",{className:s.stepNumber,children:a+1}),e.jsx("strong",{children:t.name.trim()||"Untitled step"})]}),e.jsxs("div",{className:s.stepSummary,children:[e.jsx("span",{children:Ge(t.ownerId,u)}),e.jsx("span",{className:t.isRequired?"tf-chip-neutral":"tf-chip-warning",children:t.isRequired?"Required":"Optional"})]}),N?e.jsxs("div",{className:s.stepActions,children:[e.jsx("button",{type:"button",className:"tf-control-icon",title:"Move step up","aria-label":`Move step ${a+1} up`,onClick:()=>ge(a,-1),disabled:b||a===0,children:e.jsx(it,{size:14})}),e.jsx("button",{type:"button",className:"tf-control-icon",title:"Move step down","aria-label":`Move step ${a+1} down`,onClick:()=>ge(a,1),disabled:b||a===r.length-1,children:e.jsx(ot,{size:14})}),e.jsx("button",{type:"button",className:"tf-control-icon",title:"Remove step","aria-label":`Remove step ${a+1}`,onClick:()=>o(l=>l.filter(({clientKey:h})=>h!==t.clientKey)),disabled:b,children:e.jsx(ct,{size:14})})]}):null]}),d?e.jsxs("div",{id:`workflow-step-fields-${t.clientKey}`,className:s.stepFields,children:[e.jsxs("div",{className:"tf-field-stack",children:[e.jsx("label",{className:"tf-field-label",htmlFor:`workflow-step-name-${t.clientKey}`,children:"Step name"}),e.jsx("input",{id:`workflow-step-name-${t.clientKey}`,ref:l=>{l?se.current.set(t.clientKey,l):se.current.delete(t.clientKey)},className:"tf-field-shell",value:t.name,onChange:l=>M(t.clientKey,{name:l.target.value}),"aria-invalid":P&&!t.name.trim(),"aria-describedby":P&&!t.name.trim()?`workflow-step-name-error-${t.clientKey}`:void 0,disabled:!N,readOnly:b}),P&&!t.name.trim()?e.jsx("span",{id:`workflow-step-name-error-${t.clientKey}`,className:"tf-text-error",children:"Step name is required."}):null]}),e.jsxs("div",{className:"tf-field-stack",children:[e.jsx("label",{className:"tf-field-label",id:`workflow-step-owner-label-${t.clientKey}`,children:"Owner"}),(()=>{const l=Je(Se,t.ownerId),h=l.find(({value:v})=>String(v)===String(t.ownerId||"unassigned"))||l[0];return e.jsx(Ye,{value:t.ownerId||"unassigned",options:l,disabled:!N||b,ariaLabelledBy:`workflow-step-owner-label-${t.clientKey}`,portalPanel:!0,panelMinWidth:280,panelAlign:"start",searchable:!0,searchPlaceholder:"Search owners...",noResultsText:"No owners found.",triggerContent:h?e.jsx(_e,{option:h}):void 0,renderOptionContent:v=>{const R=l.find(({value:G})=>String(G)===String(v.value));return R?e.jsx(_e,{option:R}):v.label},onChange:v=>{const R=String(v),G=l.find(({value:Pe})=>String(Pe)===R);M(t.clientKey,{ownerId:G?.kind==="unassigned"?null:R,ownerType:G?.kind==="agent"?"agent":G?.kind==="member"?"user":null})}})})()]}),e.jsxs("div",{className:`${s.fullField} tf-field-stack`,children:[e.jsx("label",{className:"tf-field-label",htmlFor:`workflow-step-instructions-${t.clientKey}`,children:"Instructions"}),e.jsx("textarea",{id:`workflow-step-instructions-${t.clientKey}`,className:"tf-field-shell",rows:4,value:t.instructions,onChange:l=>M(t.clientKey,{instructions:l.target.value}),placeholder:"Describe the work to complete in this step.",disabled:!N,readOnly:b})]}),e.jsxs("div",{className:"tf-field-stack",children:[e.jsx("label",{className:"tf-field-label",htmlFor:`workflow-step-artifact-${t.clientKey}`,children:"Output label"}),e.jsx("input",{id:`workflow-step-artifact-${t.clientKey}`,className:"tf-field-shell",value:t.expectedArtifact||"",onChange:l=>M(t.clientKey,{expectedArtifact:l.target.value||null}),placeholder:"Optional output description",disabled:!N,readOnly:b})]}),e.jsxs("div",{className:s.stepToggles,children:[e.jsxs("label",{className:s.requiredToggle,title:"Requires the step owner to add a task comment before completing this step.",children:[e.jsx("input",{type:"checkbox",checked:t.requiresCommentEvidence===!0,onChange:l=>M(t.clientKey,{requiresCommentEvidence:l.target.checked}),disabled:!N||b}),"Require task comment"]}),e.jsxs("label",{className:s.requiredToggle,title:"Marks this step as mandatory when execution policy is enforced.",children:[e.jsx("input",{type:"checkbox",checked:t.isRequired,onChange:l=>M(t.clientKey,{isRequired:l.target.checked}),disabled:!N||b}),"Required step"]})]})]}):null]},t.clientKey)})}):e.jsx("div",{className:s.stepsEmpty,children:e.jsx("p",{className:"tf-text-helper",children:"No steps have been added yet."})})]})]}):e.jsx("div",{className:s.emptyState,children:e.jsxs("div",{className:s.emptyStateInner,children:[e.jsx(le,{size:30}),e.jsx("h3",{className:"tf-heading-card",children:"No workflows yet"}),e.jsx("p",{className:"tf-text-helper",children:"Create a workflow to begin defining a reusable process."}),e.jsxs("button",{type:"button",className:"tf-button-primary",onClick:ye,children:[e.jsx(pe,{size:15})," New Workflow"]})]})})]})}),e.jsx(Ze,{isOpen:!!he,onKeepEditing:()=>fe(null),onDiscard:Ce,theme:w}),e.jsx(os,{isOpen:Ne,workflowName:j,versionNumber:ke,busy:Z,onCancel:()=>z(!1),onPublish:()=>{Re()},theme:w})]})}export{ws as WorkflowManagerModule};